A ray tracer written in Forth that renders three spheres on a checkerboard ground plane. Outputs an 800x600 PPM image to stdout with no external dependencies.
- 3 spheres — large red (left), reflective chrome (center), small blue (right)
- Checkerboard ground plane — alternating white and green tiles
- Sky gradient — white at the horizon fading to blue at the zenith
- Diffuse shading — Lambertian lighting from a single point light
- Specular highlights — Blinn-Phong model with per-material shininess
- Hard shadows — shadow rays to the light source
- Mirror reflections — up to 2 bounces, visible in the chrome sphere
ccforth -o raytrace examples/raytrace/raytrace.fth
./raytrace > scene.ppm
View the output with any image viewer that supports PPM:
feh scene.ppm
display scene.ppm
eog scene.ppm
Or convert to PNG:
convert scene.ppm scene.png
The program is a single file (~300 lines) organised into sections:
- Utilities —
f>byte(clamp and convert float to 0–255),F,(compile a float literal into the dictionary) - Vector math —
vec+,vec-,vec-scale,vec-dot,vec-length,vec-normalizeoperating on 3 floats on the float stack - Scene data — sphere geometry and materials stored in a
CREATEblock (9 floats per sphere: position, radius, color, shininess, reflectivity), light position, ambient level - Camera — look-at camera with orthonormal basis vectors
(forward, right, up) stored in
FVARIABLEs;pixel-raygenerates a normalised ray direction for each pixel - Intersection —
ray-sphere(quadratic formula),ray-plane(ground plane at y=0),trace-scene(find closest hit, store result inFVARIABLEhit state) - Shading —
sky-color(horizon-to-zenith gradient),checkerboard(alternating tiles viaFLOOR),shade-lighting(diffuse + Blinn-Phong specular with shadow test),trace-ray(recursive, usesRECURSEfor reflection bounces) - Output — PPM P6 header, per-pixel rendering loop,
MAINentry point
- Typed float locals —
{: F: x F: y F: z :}keeps vectors in CPU registers in the compiled C output - Compile-time data —
CREATE+F,to store sphere data in the dictionary at compile time RECURSE— recursive ray tracing for mirror reflectionsFVARIABLEstate — hit state and shading accumulators avoid exceeding the locals limit while keeping the code readable
