How We Built a ~500KB Zero-Dependency 3D Retro Dithered Tower Defense in Raw WebGL2 & Procedural WebAudio
Most web games in 2026 ship a 12MB–35MB WASM engine runtime plus megabytes of compressed PNG atlases and OGG stems—losing half their curious clicks to a loading progress bar. When we started Cinderkeep at Doghouse Studio, we set an uncompromising constraint: zero runtime dependencies, zero external image/audio files, and sub-second cold boot on both desktop browsers and mid-range mobile GPUs.
1. Where Every Kilobyte Goes (Zero Engines, Zero Assets)
Instead of pulling in Three.js (~600KB minified before game code) or Unity WebGL, the entire game is written against raw WebGL2RenderingContext (GLSL ES 3.00) and AudioContext in clean, zero-DOM ES2017 modules that compile into a single ~560KB bundle (~195KB Deflate/Brotli over the wire):
| Core Module | Raw Source | Responsibility |
|---|---|---|
src/core/engine.js |
~152 KB | Column-major mat4 math, instanced mesh batching, DEPTH_COMPONENT24 shadow pass, 8 procedural GLSL materials, ACES + 4×4 Bayer composite. |
src/core/world.js |
~157 KB | 48×48 heightfield partitioned into 6×6 = 36 animated diorama column chunks, bridges, ruins, waterfalls, icicles, and lava rivers. |
src/core/entities3d.js |
~217 KB | Procedural bevel-box/cylinder/cone mesh builders for 16 tower evolutions, 4 knight tiers, 13 monsters, and 6 animated bosses. |
src/core/sim.js + balance.js |
~362 KB | Deterministic combat loop, road spline pathing, boss tenacity state machine, early-call economy, and 30 campaign + Endless wave generators. |
src/core/sfx.js + hud2d.js |
~12 KB + HUD | Zero-asset WebAudio synthesizer + integer-grid 5×7 1-bit pixel font and palette-indexed 8×8..13×13 sprite stamper. |
Because src/core/* touches zero DOM APIs, the exact same simulation and renderer powers our desktop/mobile web build, a standalone 982KB Android WebView APK, and strict zero-DOM mini-game sandboxes that expose only a single hardware canvas.
2. Bitwise 4×4 Bayer Ordered Dithering & Anti-Shimmer Upscaling
Naively pixelating a 3D scene by rendering to a low-resolution FBO and blitting with gl.NEAREST creates two infamous artifacts when the camera orbits or columns ripple: sub-texel edge crawling and muddy dark-void banding. We solved both inside COMPOSITE_FS:
// Zero-LUT bitwise 4x4 Bayer threshold in GLSL ES 3.00 (engine.js)
float bayer4x4(ivec2 p) {
int x = p.x & 3, y = p.y & 3;
int x0 = x & 1, x1 = (x >> 1) & 1;
int y0 = y & 1, y1 = (y >> 1) & 1;
int v = (((x0 ^ y0) << 3) | (y0 << 2) | ((x1 ^ y1) << 1) | y1);
return (float(v) + 0.5) / 16.0;
}
// Sharp texel-interior sampling with 1-physical-pixel seam antialiasing
vec2 sharpPixelUv(vec2 uv, vec2 texSize, vec2 outSize) {
vec2 pix = uv * texSize;
vec2 scale = max(outSize / texSize, vec2(1.0)) * 1.55;
vec2 fl = floor(pix), fr = fract(pix);
vec2 aa = clamp(fr * scale, 0.0, 0.5) + clamp((fr - 1.0) * scale + 0.5, 0.0, 0.5);
return (fl + aa) / texSize;
}
- Luma-Gated Void Masking: Full-strength Bayer quantization across a dark `#090B11` abyss creates distracting checkerboard speckle. Computing a `smoothstep(0.012, 0.048, luma)` mask attenuates dither amplitude to `22%` in deep shadow voids while preserving crisp 27-to-56-level retro palette steps across lit masonry, torches, and foliage.
- Mobile TBDR Fast Path (
-91%SFU Cost): On high-DPI mobile screens (~2.59M Retina pixels), running ACES filmic tonemapping, `pow(col, 1.0/2.2)`, and multi-pass floating-point bloom at native resolution burns battery and bandwidth. On mobile tile-based deferred GPUs (`uMobileDirect == 1`), we fold bloom-lift, ACES, and gamma 2.2 directly into the low-res scene pass (~220k diorama texels into an AFBC-compressed `RGBA8` target—zero float FBOs!) and composite to screen in a single `sharpPixelUv` pass.
3. Procedural 6×6 Column Wave-Flipping & 8 Analytical Materials
To give stage transitions the tactile feel of mechanical tabletop blocks turning like pages, world.js subdivides the 15.0 × 15.0u island (`48×48` heightfield cells) into 6×6 = 36 independent column chunks (`ChunkGridBuilder`, `2.5 × 2.5u` each). Every static stone block, bridge timber, pine tree, glowing mushroom, or hanging snow icicle is baked relative to its column's `(cx, 0, cz)` pivot.
During a chapter transition, the CPU uploads a compact `uniform vec4 uChunkWave[36]` array—driving diagonal phase-delayed vertical drop, scale-bounce, and biome swap entirely in the vertex shader (`SCENE_VS` and `SHADOW_VS`) with zero dynamic vertex buffer re-uploads!
Instead of UV-mapped PNG textures, `SCENE_FS` shades 8 analytical 3D material IDs (`mId 0..8`) using world/local-space procedural noise and analytical height derivatives (`noised3` / `fbmd3Cal`) for bump-mapped normals:
- Voronoi Cobblestone Roads: 2-tap heightfield perturbation for beveled stone curb & mortar seams.
- Stratified Cliff Stone & Fluted Masonry: Layered FBM strata cracks with `0.015` normal-offset shadow bias to eliminate acne while keeping tight contact shadows (`4-tap` rotated grid PCF on mobile, `3×3` PCF on desktop).
- Weathered Wood Planks & Forged Plate Armor: Procedural plank-index variation (`mId == 4`) and high-metallic Blinn-Phong specular (`mId == 5`) that lets Lv.3 Golden Paladins gleam under dynamic point lights (up to `48` simultaneous culled point lights for arrows, fireballs, arcane chains, and torches!).
- Zero-Loop Gradient Canopy Foliage & Animated Liquids: Single-pass `voronoi2Grad` foliage tufts with subsurface backscatter (`dot(-N, Lkey)`), plus flowing water, Voronoi ice floes, and self-lit magma fissures.
4. 1-Bit 5×7 Pixel Typography & 340-Line WebAudio Synthesizer
Nothing breaks a retro pixel aesthetic faster than blurry anti-aliased TrueType UI overlays or silent combat waiting on MP3 network fetches:
- Integer-Grid Pixel HUD: Our Canvas HUD (`hud2d.js`) renders stepped notched borders (`zero border-radius`, `zero radial gradients`, `imageSmoothingEnabled = false`), `8×8` to `13×13` palette-indexed pixel icons, and a crisp `5×7` 1-bit ASCII bitmap stamper so numbers and badges align 1:1 with the dithered 3D viewport.
- 340-Line Procedural Retro SFX (`src/core/sfx.js`): Every combat cue is synthesized live on `AudioContext` using oscillators and a single 0.5-second white-noise buffer:
- Ranger Bow Twang: `triangle` oscillator sweeping `640Hz → 190Hz` exponentially over `75ms`.
- Siege Bombard Boom: White noise routed through a `BiquadFilter` (`lowpass`, `420Hz → 65Hz` over `280ms`).
- Arcane Obelisk Zap: `sawtooth` sweep `980Hz → 260Hz` in `130ms`.
- Tower Build & Upgrade Chime: Staggered `square`-wave `[330, 440, 660] Hz` triad arpeggio.
Mechanics & Economy Math →
How Early-Call Gold Rush (+44g + 18% Warhorn Haste) & 4.6u Warmth/Brace rings create spatial tension.
Combat MathLv.1–4 Tower Stat Tables →
Full numerical progression for Ranger, Bombard, Arcane, and 4 Garrison knight evolutions.
Anti-Cheese SystemsBoss Tenacity & Necromancer →
Why pure barracks or pure slow-towers fail against our 6 asymmetric bosses & Soul-Link summons.