Kanishk Sachdev

Software Engineer and Student

Spinning ASCII Donut

A JavaScript implementation of the famous spinning donut algorithm. This renders a 3D torus using ASCII characters, demonstrating 3D projection, lighting calculations, and Z-buffering.

Technical Implementation:

3D Mathematics: Generates points on a torus surface using parametric equations with theta (tube angle) and phi (rotation around torus center).

3D Rotation: Applies rotation matrices around X and Z axes to create the spinning effect, with precomputed sine and cosine values for performance.

Perspective Projection: Projects 3D coordinates to 2D screen space using perspective division (x/z, y/z) with distance-based scaling.

Lighting & Z-Buffer: Calculates surface normals for lighting effects and uses Z-buffering to handle proper depth sorting of overlapping surfaces.

Attribution: Based on the optimization work by Andy Sloane. Original algorithm and detailed explanation available at a1k0n.net/2021/01/13/optimizing-donut.html

Animation is currently running. The donut rotates continuously using real-time 3D calculations and ASCII character mapping based on surface lighting.

Loading donut...

Torus Geometry

1.0
2.0
6.0

Animation Settings

0.6

Characters from darkest to brightest for shading

Algorithm Details:

Torus Generation: Uses parametric equations to generate points on the torus surface. R1 controls the tube thickness, R2 controls the overall size.

Rotation Matrix: Applies 3D rotation transformations around multiple axes to create the smooth spinning motion you see.

ASCII Mapping: Maps calculated lighting values to different ASCII characters, creating depth perception through character brightness.

Performance: Optimized with precomputed trigonometric values and efficient Z-buffer operations for smooth real-time rendering.

Feel free to contact me at kanishksachdev@gmail.com