Shaders From Zero · Episode 22

Materials

Materials is Episode 22 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 22 · Shaders From Zero · Season 3

Real scenes don't have one material. The floor is plaster, the ball is steel, the cup is glass. Each material reflects light differently — plaster scatters it back in every direction, steel mirrors what's around it tinted by its own color, glass lets most of it through and bends it. Up to this episode every surface in our raymarcher has shared a single shading function. That's the cardinal sin of computer graphics: making the lighting honest and the surfaces fake.

The fix is small. Every SDF needs to report not just how far am I from a surface, but also what kind of surface. We encode that with a per-SDF integer material ID, returned alongside the distance. The march loop carries the ID to the hit point, and the shading code branches on it. Diffuse for the floor, metallic for the gold sphere, dielectric for the glass. Three lighting models in one shader.

0 fps
Material IDs · branch on hit
All surfaces matte. The starting point — every shape gets the same shading.

The material ID trick

Until now sceneSDF returned a single float — the distance to the nearest surface. To carry a material ID we widen the return type to vec2: distance in .x, material ID in .y.

vec2 sceneSDF(vec3 p) {
  float floor = p.y;
  float gold  = length(p - vec3(-1.0, 1.0, 0.0)) - 0.7;
  float glass = length(p - vec3( 1.0, 0.8, 0.0)) - 0.6;

  vec2 res = vec2(floor, 0.0);                  // material 0 = floor
  if (gold  < res.x) res = vec2(gold,  1.0);    // material 1 = gold
  if (glass < res.x) res = vec2(glass, 2.0);    // material 2 = glass
  return res;
}

The key thing to notice: we don't use min(a, b) any more. That returns only the smaller distance and throws the ID away. Instead, an explicit if that updates BOTH components together. Every time a closer surface wins the comparison, we re-tag the result with its material.

The march loop stays almost identical — it just reads .x instead of the bare scalar, and remembers .y at the hit:

float t = 0.0;
bool hit = false;
float matID = 0.0;
vec3 hitP = vec3(0.0);
for (int i = 0; i < 100; i++) {
  vec3 p = ro + rd * t;
  vec2 res = sceneSDF(p);
  if (res.x < 0.001) { hit = true; matID = res.y; hitP = p; break; }
  if (t > 50.0) break;
  t += res.x;
}

After the loop, matID tells the shading code which surface we hit and therefore which lighting model to run. That's the whole trick. The rest of this episode is what to put inside each branch.

Material 0 — Diffuse (floor)

The simplest case, and the one we already know from Episode 19. Lambert diffuse plus a touch of ambient, plus a soft shadow from the key light. The floor reads as light blue plaster:

vec3 baseColor = vec3(0.55, 0.58, 0.6);
float diff = max(dot(N, L), 0.0);
float sh = softShadow(hitP + N * 0.01, L, 0.02, 20.0, 16.0);
vec3 col = baseColor * (0.15 + 0.85 * diff * sh);

Nothing new. Diffuse materials don't reflect their environment — they scatter incoming light back in every direction equally, which is why a chalk-white wall looks the same from every angle. The base color IS the color you see.

Material 1 — Metallic (gold)

Metals are the opposite of diffuse: they reflect almost everything they receive, and they do it in a single coherent direction (mirror reflection, not scatter). In real PBR, metals have no diffuse term at all — every photon either gets specularly reflected or absorbed. So the dominant ingredient isn't Lambert; it's the reflection of the environment.

vec3 R = reflect(rd, N);
vec3 reflColor = traceReflection(hitP + N * 0.01, R);
float fresnel = pow(1.0 - max(dot(-rd, N), 0.0), 5.0);
vec3 goldColor = vec3(1.0, 0.78, 0.36);
// Tint the reflection by the metal's color — that's how gold gets its yellow look
vec3 col = reflColor * mix(goldColor * 0.85, vec3(1.0), fresnel);

The mix(goldColor, white, fresnel) is the trick that separates gold from chrome. At face-on viewing angles (low fresnel), the reflection is tinted by the metal's intrinsic color — gold's yellow tint, copper's orange, brass's pale tan. At glancing angles (high fresnel), all metals reflect closer to white because fresnel reflection at grazing angles is achromatic. That's why a gold ring looks yellow in the middle but white at the rim. Eleven lines of GLSL, the entire metal/non-metal distinction.

The traceReflection helper is just a second small raymarch from the hit point along the reflection direction R. If it hits another surface, return that surface's diffuse shade; if it misses, return the procedural sky. One bounce only — fine for shiny convex objects, breaks down for concave/multi-bounce geometry, which we'll address later.

Material 2 — Dielectric (glass-like)

Glass is the hard case. Light entering a dielectric splits into a reflected component (bouncing off the surface like a mirror) and a refracted component (bending through the medium and exiting the other side). Both fractions exist simultaneously; their relative strength is governed by — surprise — fresnel.

float ior = 1.5;
vec3 T = refract(rd, N, 1.0 / ior);
vec3 refrColor = proceduralSky(T);
vec3 R = reflect(rd, N);
vec3 reflColor = traceReflection(hitP + N * 0.01, R);
float fresnel = pow(1.0 - max(dot(-rd, N), 0.0), 5.0);
vec3 col = mix(refrColor, reflColor, fresnel);

Face-on, fresnel is near zero, so the result is mostly refraction — you see through the glass. Edge-on, fresnel approaches one, so the result is mostly reflection — the rim of the sphere mirrors the environment. That alternation between transparent middle and reflective rim is THE visual signature of glass.

Notice the shortcut: for the refracted ray we just sample the procedural sky in direction T. We're not raymarching through the medium and out the other side; we're assuming the world behind the glass is the sky. This is the same cheat we used in Episode 12 — full dielectric requires marching the refracted ray through the medium until it exits, then refracting again at the back surface, which is a whole second loop. For a single isolated glass sphere against the sky, you can't tell the difference.

The procedural sky

The procedural sky from Episode 12 returns to do double duty here: it's the "ray missed everything" background AND the source we sample for reflection and refraction lookups. Same function, no changes:

vec3 proceduralSky(vec3 dir) {
  float t = clamp(dir.y * 0.5 + 0.5, 0.0, 1.0);
  vec3 zenith  = vec3(0.15, 0.35, 0.7);
  vec3 horizon = vec3(0.9, 0.7, 0.45);
  vec3 nadir   = vec3(0.05, 0.04, 0.06);
  vec3 col = mix(nadir, horizon, smoothstep(0.0, 0.5, t));
  col = mix(col, zenith, smoothstep(0.5, 1.0, t));
  float sun = pow(max(dot(dir, normalize(vec3(0.5, 0.8, 0.3))), 0.0), 64.0);
  col += vec3(1.5, 1.2, 0.9) * sun;
  return col;
}

Any direction in, color out. No textures, no extra GPU memory. The sun direction matches the key light direction, which keeps reflections and direct lighting consistent — a metal sphere reflecting "the sun" actually reflects the same light that's casting the floor's shadows.

Common pitfalls

  • Forgot to RETURN the material ID from sceneSDF after a min. The most common bug. Every comparison must update both the distance and the ID together. Use explicit if (newD < res.x) res = vec2(newD, newID), never min on the vec2.
  • min(vec2, vec2) doesn't do what you want. GLSL's min on a vector returns componentwise minimums: smallest x paired with smallest y. If the smallest x came from surface A and surface B happens to have the smallest y, you'll shade surface A's geometry with surface B's material. Garbage.
  • Wrong IOR for glass. Common values: window glass 1.5, water 1.33, ice 1.31, diamond 2.4. Setting ior to 1.0 (no refraction) makes glass invisible; setting it to 3.0 makes everything look like a fisheye.
  • Metal with a Lambert term. Metals don't diffuse. If you add baseColor * diff to gold, it looks like painted plastic. Skip the diffuse contribution entirely for material 1.
  • refract returning vec3(0) (total internal reflection). When the angle is steep enough relative to the IOR ratio, refract gives up and returns zero, which then samples the sky at vec3(0) — a constant. Fall back to reflColor when length(T) < 0.01, or just accept the artifact for our cheap sky-lookup version.
  • Forgot to update calcNormal for the new SDF signature. calcNormal sums SDF samples, so each call now returns a vec2. Take .x at every sample site, otherwise you'll get a compile error and waste ten minutes squinting at it.

Exercises

  1. Add a fourth material — colored dielectric. Sample the sky as before, then multiply the refracted color by an absorption tint (vec3(0.7, 0.95, 0.85) for a faint emerald). Real glass absorbs wavelength-dependently as light passes through the volume; we fake it with a constant tint.
  2. Vary goldColor to copper (vec3(0.95, 0.64, 0.54)), silver (vec3(0.97, 0.96, 0.92)), or chrome (vec3(0.95, 0.93, 0.88)). Watch how face-on color shifts but grazing-angle reflections all wash out toward white.
  3. Drive the IOR with uTime: float ior = 1.0 + 0.5 + 0.5 * sin(uTime). The glass shifts from invisible (1.0) through water (1.33) to extreme (2.0). At 1.0 you should not see the sphere at all — exactly what an invisible cloak of equal index of refraction does in real life.

What's next

Episode 23 — Volumetrics & Fog. Until now every ray has marched through pure empty space until it hit a hard surface. Real-world space isn't empty — it's full of dust, mist, smoke, atmosphere. We extend the march to integrate a density field along the ray, then layer that on top of our solid scene. Same loop, different per-step contribution.