TExcelTAD

Field Notes

Shader code is short, so its bugs are concentrated. The lessons below are the ones graphics programmers usually learn from a broken build, a slow frame on one phone, or a screen that went black after an innocent change.

1. Know what is expensive: fetches, divergence, then math

On a GPU, arithmetic is cheap. A modern GPU does a fused multiply-add per lane per clock, and sin, exp or rsqrt cost a few of those. What costs more:

  • Texture fetches, especially dependent ones (where the UV comes from another fetch) and cache misses (random UVs, large textures without mipmaps). A fetch has hundreds of cycles of latency; the GPU hides it by switching to other work, but only if there is enough other work.
  • Divergent branches. GPUs run threads in groups (32 lanes in a warp on NVIDIA, 32 or 64 in a wavefront on AMD) that share one instruction stream. If lanes in a group disagree on an if, the group executes both sides with lanes masked off. A branch on a uniform value (the same for every pixel, like a material toggle) is nearly free; a branch on noise or on a texture value may cost the sum of both paths.
  • Register pressure. Big shaders with many live variables reduce how many groups fit on a core at once, which removes the latency hiding that makes fetches cheap.
  • Overdraw of expensive shaders: transparent particles running a 200-instruction shader ten layers deep.

So the practical rules are:

  • Replace small data-dependent ifs with math (mix, step, clamp) when both sides are cheap. Keep real branches when they skip a lot of work for whole regions (an early-out in a raymarch, a material that is mostly unlit), since coherent branches are fine.
  • Precompute what you can on the CPU or in the vertex shader. A value that is constant per draw belongs in a uniform, not recomputed per pixel.
  • Measure with the GPU profiler of your platform (Nsight, PIX, RGP, Xcode, RenderDoc's timings). Instruction counts in an editor are a hint, not the truth.
glsl
// Data-dependent branch: divergent along the edge of the mask
vec3 c;
if (mask > 0.5) c = colorA; else c = colorB;

// Branchless and identical in result: both sides are just constants
vec3 c2 = mix(colorB, colorA, step(0.5, mask));

Compilers already turn small branches like this into selects, so do not obsess over every if. Worry when the two sides are big, or contain texture fetches.

2. Precision matters on mobile

highp is a 32-bit float. mediump is at least 16-bit on most mobile GPUs: about 3 decimal digits and a maximum around 65504. Desktop GPUs usually ignore mediump and compute everything in 32 bits, so precision bugs only appear on phones. The playgrounds in this course use precision highp float; so they behave the same everywhere, but in shipped mobile shaders (and in Unity's half), these break first:

  • Time. sin(iTime * 10.0) in mediump gets choppy after a few minutes and visibly steps after an hour: a 16-bit float near 1000 can only move in steps of 0.5. Wrap time on the CPU (time % 3600.0, or a period that matches your animation) or keep it highp.
  • World positions and UVs on large textures. Texture coordinates on a 4096 texture need more than 11 bits of fraction; mediump UVs make textures wobble or block. Keep positions and UVs highp, use mediump for colors, normals and lighting terms.
  • Overflow. dot(v, v) of a 300-unit vector is 90000, past the mediump maximum: infinity, then NaN.
glsl
precision mediump float;           // default for this shader: fast on mobile
uniform highp float uTime;         // exceptions marked explicitly
in highp vec2 vUv;

3. Linear vs gamma: do the math in linear space

Displays apply a power curve (sRGB, roughly pow(x, 2.2)), so a stored value of 0.5 appears as about 22% brightness. Color textures and color pickers store gamma-encoded sRGB values. Lighting math (adding lights, blending, blurring, mixing) is only physically meaningful in linear space. The rule:

  1. Decode sRGB inputs to linear (the hardware does it for free when the texture's format is marked sRGB; engines handle it when a texture is marked as color).
  2. Do all lighting and blending in linear.
  3. Encode to sRGB once, at the very end (sRGB render target, or a final pow(c, vec3(1.0/2.2)) / exact sRGB curve).

The visible symptom of skipping this is mixing in the wrong space. The top half below blends red to green directly on the encoded values (the common mistake); the bottom half decodes, blends in linear and re-encodes. The top has a muddy, dark band in the middle:

glsl · try it yourself
vec3 toLinear(vec3 c) { return pow(c, vec3(2.2)); }
vec3 toSrgb(vec3 c)   { return pow(c, vec3(1.0 / 2.2)); }

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    vec3 a = vec3(1.0, 0.1, 0.1);           // sRGB-encoded colors, as typed in a color picker
    vec3 b = vec3(0.1, 0.9, 0.2);
    vec3 col;
    if (uv.y > 0.5) {
        col = mix(a, b, uv.x);                                  // wrong: mixing encoded values
    } else {
        col = toSrgb(mix(toLinear(a), toLinear(b), uv.x));      // right: mix in linear, encode once
    }
    col *= smoothstep(0.0, 0.004, abs(uv.y - 0.5));            // thin divider line
    fragColor = vec4(col, 1.0);
}

The same mistake makes lighting look harsh (falloffs too dark, light additions blown out), makes blurs darken edges, and makes anti-aliased edges look thin. Too dark everywhere? You probably decode twice (an sRGB texture flag plus a manual pow). Washed out? You encode twice (sRGB render target plus a manual pow), the classic Three.js and Unity color-space bug.

4. Matrix order and layout

gl_Position = projection * view * model * vec4(position, 1.0); reads right to left: model first. Three separate conventions decide whether that line is right:

  • Multiplication order: column vectors (M * v, GLSL, GLM, Three.js) versus row vectors (v * M, DirectXMath and much HLSL code). The same transform written in the other convention is the transpose.
  • Storage order when uploading 16 floats: column-major or row-major. glUniformMatrix4fv(loc, 1, GL_FALSE, data) expects column-major (WebGL requires transpose = false); HLSL cbuffer matrices are column-major by default unless declared row_major or compiled with -Zpr.
  • HLSL mul: mul(M, v) treats v as a column, mul(v, M) as a row. Mixing them up in a port silently transposes.

When something is "almost right" (rotations go backwards, translation does nothing, the object shears), suspect a transpose. Upload a pure translation matrix and check where the offset ends up; Math Libraries has a runnable demonstration.

5. NaNs spread: guard the usual suspects

A NaN in one pixel is a black or white dot. A NaN in a value that feeds a blur, bloom, TAA history or an exposure average spreads until the whole screen is black, sometimes minutes after the bug triggered. The usual sources, and the guards:

Undefined / NaN source Guard
normalize(v) with v = 0 v * inversesqrt(max(dot(v, v), 1e-8))
sqrt(x) with x < 0 sqrt(max(x, 0.0))
pow(x, y) with x < 0 (undefined) or x = 0, y ≤ 0 pow(max(x, 1e-6), y)
acos(x), asin(x) with ` x
a / b with b = 0 a / max(b, 1e-6) (or keep the sign)
log(x) with x ≤ 0 log(max(x, 1e-6))

This shader shows the most common case, normalizing a zero vector at the center of a radial effect, next to its guard. The left half normalizes p unguarded and paints NaN or Inf pixels magenta; the right half is safe:

glsl · try it yourself
vec3 debugNan(vec3 v) {
    bool bad = any(isnan(v)) || any(isinf(v));
    return bad ? vec3(1.0, 0.0, 1.0) : v;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    vec2 center = vec2(uv.x < 0.5 ? 0.25 : 0.75, 0.5);
    // Snap to a coarse grid so some pixels land exactly on the center (p = 0).
    vec2 cell = floor((uv - center) * 40.0 + 0.5) / 40.0;
    vec2 p = cell;
    vec2 dir;
    if (uv.x < 0.5) {
        dir = normalize(p);                                    // unguarded: undefined at p = 0
    } else {
        dir = p * inversesqrt(max(dot(p, p), 1e-8));           // guarded: (0, 0) at p = 0
    }
    vec3 col = vec3(dir * 0.5 + 0.5, 0.6);
    fragColor = vec4(debugNan(col), 1.0);
}

Whether the left half shows a magenta cell depends on your GPU: the result is undefined, so some drivers return NaN and others return 0 or a direction. That is the point: code that "works" on your machine can break on the next GPU, so guard it anyway.

6. Most black screens are a uniform or a matrix

The full checklist is in Debugging Shaders. The top three, in practice:

  • A uniform that was never set (misspelled name, set before useProgram, or optimized out because the shader doesn't use it yet) stays zero. A zero matrix collapses every vertex onto one point.
  • The matrix order is reversed or the matrix is transposed (see note 4).
  • The clear color or the shader output has alpha 0 with blending enabled.

Start every black-screen hunt by writing a constant bright color from the fragment shader. If it shows, the bug is in your math; if not, it is in the draw.

7. Smaller habits that save days

  • Name things by space: normalWS, posVS, lightDirTS. Half of all lighting bugs are a dot product between vectors in different spaces.
  • Re-normalize interpolated normals in the fragment shader; interpolation shortens them.
  • Never compare floats with == in a shader. Use step, smoothstep or a tolerance.
  • Anti-alias with fwidth: smoothstep(-w, w, d) with w = fwidth(d) gives one-pixel-wide edges at any zoom.
  • Keep a debug-view switch in every big shader (normals, UVs, albedo only, lighting only). It pays for itself the first time art says "it looks wrong".
  • Watch the shader variant count in engines: every keyword multiplies build time and memory.

Test yourself

When is an if in a fragment shader nearly free?

  1. Never
  2. When the condition is the same for all pixels in the draw (a uniform), so no group diverges
  3. When it contains a texture fetch
  4. When it is inside a loop

An effect mixes two sRGB colors with mix(a, b, t) and the middle looks dark and muddy. What's the fix?

  1. Use mediump
  2. Convert to linear, mix, then encode back to sRGB once
  3. Clamp t
  4. Multiply by 2.2

Why might a shader with mediump time look fine on a desktop GPU but stutter on a phone after an hour?

  1. Phones run shaders at lower frame rates
  2. Desktop GPUs usually compute mediump as 32-bit, while mobile GPUs use 16-bit floats that lose fractional precision at large values
  3. mediump is not allowed on desktop
  4. Time uniforms are reset on desktop