Ray Tracing & Optics — SDF Marching, Fresnel & Rayleigh Scattering

From a single ray-sphere intersection to a full path tracer: how ray tracing simulates light physically. Snell's law refraction, Fresnel reflectance, total internal reflection, SDF sphere tracing, atmospheric Rayleigh scattering — every concept with interactive browser simulations.

How Ray Tracing Works

The core insight of ray tracing is deceptively simple: for each pixel, cast a ray from the camera into the scene, find the closest intersection, and shade that point by casting shadow rays toward light sources. Repeat with reflection and refraction rays, and physically accurate images emerge. The only physics inputs are the law of reflection (θ_r = θ_i) and Snell's law (n₁ sin θ₁ = n₂ sin θ₂).

Modern GPU ray tracers and path tracers (NVIDIA RTX, Apple Metal ray tracing) do exactly this at billions of rays per second. The simulations here run entirely in the browser — some in JavaScript, others in GLSL fragment shaders — so you can modify the scene and see physical light behaviour in real time.

Fresnel Equations & Snell's Law

Snell's law:  n₁ sin θ₁ = n₂ sin θ₂
Critical angle (TIR):  θ_c = arcsin(n₂/n₁)  (n₁ > n₂)

Fresnel reflectance (s-polarisation):
  r_s = (n₁ cos θ₁ − n₂ cos θ₂) / (n₁ cos θ₁ + n₂ cos θ₂)

Fresnel reflectance (p-polarisation):
  r_p = (n₂ cos θ₁ − n₁ cos θ₂) / (n₂ cos θ₁ + n₁ cos θ₂)

Reflectance R = |r|²,  Transmittance T = 1 − R
Schlick approximation: R(θ) ≈ R₀ + (1−R₀)(1−cos θ)⁵

Atmospheric Optics & Scattering

The sky is blue and sunsets are red because of Rayleigh scattering: the intensity scattered by gas molecules is proportional to λ⁻⁴, so short-wavelength blue photons scatter ~5.5× more strongly than red. At sunset, sunlight travels through ~38× more atmosphere, depleting blue and leaving red and orange. These are not special effects — they follow directly from the electromagnetic scattering cross-section of molecules much smaller than a wavelength.

SDF ray marching vs traditional ray tracing: In classic ray tracing you write analytical intersection functions for each primitive. SDF marching replaces all of this with a single distance function: the ray advances by the minimum distance to any surface, guaranteed never to overshoot. The payoff is free smooth blending (smooth-min), infinite detail levels, and trivial deformations — but the SDF must be Lipschitz continuous (gradient magnitude ≤ 1) for sphere tracing to converge.

Algorithms at a Glance

Sphere tracing SDF primitives Soft shadows AO Snell's law Fresnel equations Schlick approximation Total internal reflection Thin-lens equation Rayleigh λ⁻⁴ scattering Huygens-Fresnel diffraction CIE XYZ colour space Fraunhofer diffraction