006 — Sun, Moon, PBR and Toon

2026-11-06 → 2026-11-09

Until the previous post, ARAL had no light at all: the sky tinted the scene through its spherical harmonics, and that was it. This step adds the directional lights, a sun and a moon that follow the time of day, and replaces the unlit shader with a real PBR one. Toon shading comes for free on top of it, as a parameter.

The sun disk at the end of the afternoon, over the ruins

Directional lights: four fixed slots

No light ids, no allocation: ARAL has 4 slots, period.

struct SDirectionalLight
{
  Vec3 direction  = {0.0f, 0.0f, -1.0f};   // propagation, like Blender
  Vec3 color      = {1.0f, 1.0f, 1.0f};
  F32  intensity  = 0.0f;                  // 0 = off
  // + shadow settings, used in the next step
};

Inga::SDirectionalLight fill;
fill.direction = {-0.3f, 0.5f, -0.8f};
fill.color     = {0.6f, 0.7f, 1.0f};
fill.intensity = 0.3f;
renderer->setDirectionalLight(1, fill);    // invalid slot → error + refused

Two conventions, each in its place: the API takes the propagation direction (natural to describe a light, same as Blender), the UBO stores the direction towards the light, so every shader formula is written with L without a sign to remember. The CPU does the negation once.

Slot 0 is the sky's: sun by day, moon by night

With setAstroFollowTime(true), slot 0 is computed every frame from the time of day, and setDirectionalLight(0, …) is refused. Slots 1 to 3 stay manual.

The orbit

The sun runs on a circle set by two angles, setAstroOrbit(azimuthDeg, tiltFromVerticalDeg):

θ  = 2π (t − 0.25)              // t = 0.25 sunrise, 0.5 noon, 0.75 sunset
e  = ( cos φ,  sin φ, 0)        // where it rises, on the horizon
h  = (−sin φ,  cos φ, 0)        // horizontal, perpendicular to e
toSun(θ) = cos θ · e + sin θ · (cos i · up + sin i · h)

e and the tilted axis are unit and perpendicular, so toSun is a unit vector without normalizing. Max elevation is 90° − i (default: azimuth 45°, tilt 30° → 60°). Sunrise and sunset are fixed by θ, not by the sky keyframes: if the game moves dawn or dusk, only the colors follow.

The moon is the opposite of the sun on the same orbit: toBody = (toSun.z >= 0) ? toSun : -toSun. One orbit to compute, and it rises when the sun sets. A simplification — a real moon has its own orbit and phases — but it can come later without changing the UBO.

Color: keyframes for the artist, the atmosphere for the rest

Each sky keyframe got an astralColor and an astralIntensity: the color of the sun seen at the zenith. The orange at sunset is not in the keyframes, it's computed from the real elevation of the sun.

The first version had an orange dusk keyframe. It never showed: the blend is linear in time, so at t = 0.625 the sun was still at 34° but only half orange, and it reached full orange at t ≈ 0.74 — on the horizon, just as the fade turned it off.

Now the color comes from Rayleigh extinction: the air scatters blue far more than red (1/λ⁴), and the lower the sun, the longer the path through the air.

T(λ) = exp(−τ(λ) · m)                    // Beer-Lambert
τ    = (0.046, 0.108, 0.265)              // optical depth at zenith, R G B (Bruneton & Neyret 2008)
m    = 1 / (z + 0.025 · exp(−11 z))       // air mass: 1 at zenith, ~40 at the horizon
tint = exp(−(τ − τR) · turbidity · (m − 1))

Normalized on red (the brightness of the red channel is kept) and relative to the zenith (m − 1): a sun at the zenith keeps exactly its keyframe color. Golden under ~10°, orange under ~5°, red under ~2°. turbidity is the weather: 0 = no tint, 0.5 = very clear air, 1 = default, 2–3 = haze or smoke, where even a low moon turns orange.

The moon does not blend keyframes: just after sunset, a blend between dusk and night would give a moon five times too bright, and orange, coming from the other side of the sky — the sun teleporting. The moon uses the night keyframe only (a cold blue: not physical, but that's how the eye sees at night) and its own Rayleigh tint.

Near the horizon the light fades out (saturate((z − 0.02) / 0.05)): a body just below the horizon would light ceilings from below, and at the sun → moon switch the direction flips. With the fade, the light is off during the flip, and the sky ambient carries the scene alone for that moment.

The disk, without geometry

The sun has no mesh, no sprite, no quad. The sky is one full-screen triangle; each pixel asks "am I looking at the sun?":

float c = dot(dir, toAstro);                       // cos of the angle pixel ↔ sun
col += disk * smoothstep(cos(r * 1.5), cos(r), c)  // r = angular radius
            * horizon * sink;

It started as a debugging tool: lightDir[0] is computed on the CPU, and a sign error is invisible until something draws it. With the disk, the lit side of every object must face it. Terrain hides it for free: the sky is drawn after the objects with LESS_OR_EQUAL, so the disk only appears where nothing was drawn.

PBR

The fragment shader is now a microfacet BRDF, taken from Filament:

  • D: GGX distribution
  • V: height-correlated Smith visibility
  • F: Schlick Fresnel
  • roughness clamped to 0.045: below that, a point highlight sparkles from one frame to the next
  • f0 = mix(0.04, albedo, metallic), and a metal has no diffuse
for (uint i = 0u; i < lightCount; ++i)
{
  vec3  L   = frame.lightDir[i].xyz;
  float NdL = max(dot(n, L), 0.0);
  vec3  H   = normalize(V + L);
  vec3  F   = F_Schlick(max(dot(V, H), 0.0), f0);
  vec3 spec = D_GGX(NdH, a) * V_SmithGGXCorrelated(NdV, NdL, a) * F;
  vec3 diff = (1.0 - F) * diffuseColor / PI;
  float k   = toonNdotL(NdL, bands, softness);     // = NdL when toon is off
  Lo += (diff + spec) * lightColor[i].rgb * lightColor[i].w * k;
}

The ambient keeps the sky SH from the previous post: (1 − F) · diffuse · SH(n). Material textures follow glTF: albedo, metallic / roughness, occlusion (with its strength), emissive, normal.

A placeholder for the IBL

Without image-based lighting, a metal in the shade has nothing to reflect: it turns black. Real IBL (pre-filtered cubemap + BRDF LUT) comes later. Meanwhile the specular ambient reads the sky SH in the reflection direction:

vec3 R               = reflect(-V, n);
vec3 ambientSpecular = F_SchlickRoughness(NdV, f0, rough) * max(evalSH(R), 0.0);

Right for a rough metal, too blurry for a polished one — but no more black metal, and the IBL plugs in at exactly this line.

Normal maps

The mannequin: normal map, mirrored UVs, no seam

  • Tangents read from the glTF, regenerated when missing with MikkTSpace — the same algorithm as Blender's baker, so a normal map baked in Blender matches exactly. Missing normals are regenerated too (flat, or smooth under an angle threshold); until now createMesh silently put (0, 0, 1).
  • After generation, vertices are welded again; the count can change, and a mesh can switch to 32-bit indices above 65535 vertices.
  • No UVs → no tangents: a warning, and the normal map is ignored.
  • In the shader: tangent transformed like the normal, sign w × det for mirrored objects, Gram-Schmidt, and a fallback orthogonal vector when the tangent degenerates.

Checked on the mannequin above (mirrored UVs, no seam), and by forcing MikkTSpace on a mesh that has tangents in the file: identical image, max difference 3/255 on 2 pixels.

Toon, as a parameter

The style of ProjectO isn't decided yet. Rather than a second shader, toon is a parameter of the PBR shader: NdotL quantized into bands, edges smoothed so they don't alias.

float toonNdotL(float NoL, float bands, float softness)
{
  if (bands < 2.0) return NoL;                    // 0 = off
  float x = NoL * (bands - 1.0);
  float w = max(fwidth(x), softness);
  float q = floor(x) + smoothstep(0.5 - w, 0.5 + w, fract(x));
  return q / (bands - 1.0);
}

fwidth keeps at least one pixel of transition whatever the distance; softness widens it for a softer look. A value uniform over the draw: no divergence, a few instructions per pixel. Switchable at runtime, to decide on the same scene:

inga:toon 0 3          // 3 bands
inga:toon 0 5 0.1      // 5 bands, softer edges
inga:toon 0 0          // off

An external tester: InGaTester and Sponza

Until now, the tests lived in ProjectO's main.cpp, next to the game. They moved to a dedicated project, InGaTester, written entirely by Claude Code. That's the point: someone other than me, using only the public API of the engine, the way an external developer would. If something is hard to use or breaks, it shows there.

  • a strict command line, one test per process: --test-node, --test-instance, --test-sort, --test-material, --test-texture, --test-viewport, --test-sky, --test-normal-map…
  • tools/run_tests.sh: assets → build → every test in its own process → summary; exit code = number of failures (12 / 12 PASS, Debug + ASan, ~2 min)
  • a world: Khronos Sponza, a ground, and N generated objects (2000 by default) — cubes and spheres of random size, height and rotation, some spinning, some moving, over 64 materials (32 generated textured ones with albedo, normal and ORM, 32 plain values)

Sponza in ARAL

InGaTester: generated cubes and spheres, textured and plain materials

The whole InGaTester world: 2000 objects around Sponza

On the side: SIMD math

The math library became header-only (like GLM) with an F32x4 type per target: SSE4.1, NEON, and an explicit scalar fallback — no _mm_* left in the math code itself. The frustum test from devlog 004 now runs in SIMD, checked against the scalar version on the same visible set. Also found: without -fno-semantic-interposition, math calls inside the shared library went through the PLT and were never inlined.

Little problems

  • The orange sunset that never showed — see above: the color moved from the keyframes to the atmosphere.
  • The moon teleporting the sun — the moon doesn't blend keyframes.
  • Sponza and the ground at the same height: z-fighting between Sponza's floor (−0.02) and the test ground, moved to −0.10.
  • Black metal in the shade — the SH placeholder until the real IBL.

Tested on

AMD RX 6800 (RADV), Linux / Wayland. The Steam Deck measurement is postponed to the next step, shadows included.

Next step

Step 14: shadow maps.