A simple real-time 2D raytracer prototype built in C with SDL2.
Rays are emitted from a light source and stopped when they hit objects (circles).
This creates a hard-shadow casting effect that can be moved interactively with the mouse.
- C + SDL2 hardware-accelerated rendering (
SDL_Renderer). - Light source follows your mouse.
- Rays emitted in all directions (150 configurable).
- Circle obstacle blocks rays → real-time shadow casting.
- Basic ray–circle intersection math.
A ray is defined by:
- ( O = (x_0, y_0) ) = ray origin (light source).
- ( d = (\cos\theta, \sin\theta) ) = direction vector (unit length).
- ( t ) = distance along the ray.
A circle with center ( C = (c_x, c_y) ) and radius ( r ):
Plugging the ray into the circle equation:
Expands to a quadratic in (t):
where:
Discriminant:
- If ( \Delta < 0 ): no intersection.
- If ( \Delta \ge 0 ):
Choose the smallest positive ( t ) to find the first hit.
The ray endpoint at intersection is:
- Emit evenly spaced rays in a circle:
- Each ray endpoint =
- Screen edge if no hit.
- Circle boundary if hit.
Thus obstacles block rays and create real-time shadows.
-
Generate rays around full (360^\circ).
angle = i * (2 * M_PI / RAYS_NUMBER); dx = cos(angle); dy = sin(angle);
-
Test each ray against all circles in the scene (blockers).
- Use quadratic intersection.
- If hit → shorten to (t_{\text{hit}}).
- Else → keep screen border endpoint.
-
Render:
- For each ray, draw a line from ((x_0,y_0)) → endpoint.
- Draw obstacles and light.
-
Done → interactive raytracing demo.
- Mouse drag → moves the light source around the window.
- Rays and shadows update in real time.
