Ship Cry Croc on an Android phone and the alligator's shadow does something ugly: as you pan the camera it flips — the whole body goes from fully shaded, to not shaded at all, to shaded again, frame after frame. The terrain and tree shadows stay rock solid. On desktop, nothing flickers at all. Two different bugs were hiding behind that one symptom.
1. Why I split the shadow map in two
A single directional shadow map has to cover the entire visible world. Covering the whole world at a resolution good enough for a close-up character shadow is far too expensive to re-render every frame, and covering it at a coarse resolution looks like mush up close. On a phone the fill and vertex budget is the whole game, so I split the problem along the one axis that actually differs: how often each group changes.
The static map covers terrain and trees. Those are enormous in pixel terms and essentially never move, so they get a big map and are re-rendered rarely. The dynamic map covers only the characters that can move — the alligator, rabbits, frogs, fish. Those are few and small, so they get a tight map and it re-renders every frame.
val staticShadowLight = DirectionalShadowLight(4096, 4096, 200f, 200f, sNear, sFar)
val dynamicShadowLight = DirectionalShadowLight(1024, 1024, 50f, 50f, dNear, dFar)
The static pass is throttled by distance, not time. As long as the player stays within a few world units, the static map is reused untouched:
val dx = playerPos.x - lastShadowLightX
val dz = playerPos.z - lastShadowLightZ
val needsUpdate = !shadowLightInitialized || (dx * dx + dz * dz) > updateThreshold * updateThreshold
if (!needsUpdate) return
So a huge 4096² map that would be ruinous every frame gets rebuilt maybe once every couple of seconds, while a cheap 1024² map tracks the moving animals in real time. That's the design the rest of this post is about.
2. How libGDX actually stores shadow depth
The mental model that trips people up: a libGDX shadow map is not a depth buffer you sample directly. The shadow pass renders the scene's depth into the RGBA colour buffer as a packed value, and the main shader compares against it. In the fragment shader I unpack those four bytes back into a float and compare with step():
const highp vec4 bitShifts = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);
highp vec4 smp = texture2D(u_dynamicShadowTexture, v_dynamicShadowMapUv.xy + offset);
return step(v_dynamicShadowMapUv.z, dot(smp, bitShifts) - shadowBias);
That comparison happens when shading the lit scene. The part that produces that packed texture in the first place is a separate depth render — and that is where the flicker was coming from.
3. Bug one: overlapping geometry, no hardware depth test
My dynamic shadow used a frame buffer I create myself. I built it without a depth attachment. The colour buffer then holds packed depth, and the comparison in the shader looked right, so it seemed fine. But the depth pass itself was drawing the alligator's body parts, several rabbits, and fish into the same texels. With no depth buffer attached, there is no occlusion test during that pass: whichever fragment is drawn last wins each texel. And the draw order changes as the camera moves, because frustum culling and batching change. So the packed depth written for a shared texel flips between "nearest thing" and "a limb behind it" frame to frame — which is exactly the whole-object invert-and-return flicker I was seeing on the characters. The static (terrain) map never flickered because it uses libGDX's own DirectionalShadowLight, which builds its frame buffer with a depth buffer.
The fix is the boolean everyone forgets — the fourth argument of FrameBuffer:
// hasDepth MUST be true: the depth pass writes packed depth into the colour
// buffer, but overlapping geometry still needs a hardware depth test so the
// nearest fragment wins each texel deterministically, independent of draw order.
dynamicShadowFrameBuffer = FrameBuffer(Pixmap.Format.RGBA8888, dynamicRes, dynamicRes, true)
With a real depth buffer, the nearest fragment wins by the GPU's own test rather than by accident of batching order. The flicker was gone.
4. Bug two: mediump on some drivers
That left a second, subtler artefact: a fine shimmering, only on some devices. My fragment shader declares a default precision of mediump float. On desktop that's irrelevant; on certain mobile GPUs mediump is genuinely low precision, and shadow lookups need more than that — the projected shadow coordinate and the unpacked depth are both large-ish numbers where a few lost bits flip a step() from light to dark. The driver-dependent behaviour was the giveaway.
The fix is explicit precision on everything shadow-related, regardless of the file default:
uniform highp sampler2D u_shadowTexture;
uniform highp sampler2D u_dynamicShadowTexture;
varying highp vec3 v_shadowMapUv;
varying highp vec3 v_dynamicShadowMapUv;
The highp also has to be on the unpack constant and the sampled value, not just the varyings — the precision of the multiply-and-add in the unpack and the texture2D result are part of the same calculation. A mediump sample with a highp coordinate still loses the bits:
const highp vec4 bitShifts = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);
highp vec4 smp = texture2D(u_dynamicShadowTexture, ...);
Forcing those to highp removed the shimmer across devices.
5. Combining two maps without artefacts
Two independent maps need a merge rule. A shadow only has to be dark in one of them, so the combine is a min() (lower value = darker), and each map does its own 3-sample PCF for a soft edge:
float getCombinedShadow() {
if (u_dynamicShadowEnabled > 0.5) {
// outside the small dynamic frustum, fall back to the static map
if (v_dynamicShadowMapUv.x >= 0.0 && v_dynamicShadowMapUv.x <= 1.0 &&
v_dynamicShadowMapUv.y >= 0.0 && v_dynamicShadowMapUv.y <= 1.0) {
return min(getShadow(), getDynamicShadow());
}
return getShadow();
}
return getShadow();
}
The bounds check matters: the dynamic map covers only a 50×50 area, so anything outside it must fall through to the static map, not sample garbage. And u_dynamicShadowEnabled lets devices that can't afford the second pass disable it cleanly and stay on the static map.
One last detail: matching the frustum to the light angle
The shadow camera is orthographic and the light points at an angle, so the far plane has to span the diagonal of the area, not just the area. I derive it instead of guessing it, so changing the coverage area keeps the range correct:
// far = area × √2 × safety / |lightDir.y| (smaller Y means a longer projection)
val far = area * 1.41421356f * 1.5f / abs(lightDir.y)
It was never the visible bug, but a hand-tuned far plane is the kind of thing that quietly clips high terrain and starts a new hunt months later.
Both problems showed up as "the shadow flickers," and chasing them as one bug would have wasted a lot of time. The real lessons: a packed-depth shadow pass still needs a hardware depth buffer during the pass, and on mobile you don't get to trust the shader's default precision for anything that compares against a large coordinate.