Writing
3D modeling and rendering for browsers and mobile: inside Route Awakening
By Dylan J. Harris · Downloadable SKILL.md ↓Published
A 3D model that looks great in a desktop viewer can choke a mid-range phone in two seconds. On the web, smooth 3D comes down to separating two budgets that tutorials constantly blur together: download size (how fast bytes cross the network) and GPU cost (how much VRAM, draw-call work, and skinning math runs every single frame).
I learned most of these lessons the hard way while building Route Awakening: Living Arcade 369 — a live, walkable multiplayer 3D ship and holodeck arcade built in Three.js inside Punball (play live at punball.com/games/route-awakening). In our desktop Chrome production smoke check, the scene mounts WebGL in about 1.5 seconds with 34 playable crew skins (28 imported GLBs plus procedural crew), shared skeletal emotes, destructible voxel co-op missions, instanced outdoor scenery, zero-download Web Audio sound effects, and mobile touch controls.
If you are generating 3D characters with AI tools or shipping interactive Three.js experiences for desktop and mobile visitors, here is the exact engineering pipeline—what actually saves frames, what only saves download bytes, and the traps that burned us along the way.

Start with hard device budgets, not vibes
Most browser 3D projects get slow because nobody wrote down a ceiling before importing the tenth character. Set explicit budgets before touching Blender or an image-to-3D API:
| Budget dimension | Desktop target (60 fps) | Mid-range mobile target (30–60 fps) | Why it breaks first |
|---|---|---|---|
| Frame time (p95) | <= 16.7 ms | <= 33.3 ms | One 50 ms garbage-collection spike feels like a hitch |
| Pixel ratio (DPR) | Math.min(dpr, 2) | 1.0 – 1.5 (capped) | Retina phones push 9x pixels at dpr = 3 for almost no visible gain |
| Draw calls / frame | < 150 | < 80 | Individual props and unmerged trees saturate CPU driver overhead |
| Active triangles | Scene-dependent, bounded | Hard-capped (e.g., 32,256 max for voxel chunks) | Raw AI meshes routinely arrive at 80K–200K triangles each |
| Uncompressed GPU textures | Track resident VRAM | 1K maps or KTX2/Basis | One 2048×2048 PNG/WebP decodes to ~21.3 MiB (~22.4 MB) RGBA8 with mipmaps |
A single uncompressed 2K PNG looks tiny on disk—maybe 600 KB—and then explodes to roughly 21.3 MiB (~22.4 MB) inside GPU memory the instant Three.js uploads it (2048 × 2048 × 4 bytes × 4/3 for mipmaps). Put three 2K maps (albedo, normal, roughness) on ten characters and a mobile browser tab kills itself before the player takes a step.
AI 3D asset intake: verify the raw bytes before blaming Three.js
For character and prop generation, I use Pixio to run image-to-3D and rigging routes (including Hunyuan Rapid and Meshy workflows), and the same intake checklist works whether your meshes come from Pixio, local open-weight 3D generators, or Blender.
Three real intake bugs bit us in production—and none of them were Three.js bugs:
- A field named
textureis not automatically color paint. Across real Hunyuan Rapid character jobs, one finished download handed back a grayscale roughness map in the texture slot, a second returned an RGB normal map in the texture slot, and a third returned a real color atlas mapped cleanly tomap_Kdin the.mtlfile. Always inspect the.mtlslots and open the raw image pixels before binding a texture as albedo. A colored thumbnail on a provider dashboard does not guarantee the downloaded mesh has color paint. - File extensions lie; magic bytes do not. More than once, requesting a
.pngreturned valid JPEG bytes. Checking the file's magic header and pixel dimensions kept clean assets instead of burning credits regenerating something that already succeeded. - Upload limits can be stricter upstream than published. Even when a high-resolution character portrait passed the wrapper's file-size limit, an upstream 3D model rejected the encoded payload until we sent a clean 768 × 1024 JPEG delivery copy while keeping the full master untouched on disk.
Before admitting any AI mesh into your scene:
- Normalize units to meters, Y-up, +Z forward, origin sitting cleanly at the character's feet (
y = 0), with transforms applied. - Repair non-manifold edges, strip unseen interior faces, merge redundant materials, and decimate to your triangle ceiling.
- De-light baked shadows out of the albedo if the generator painted strong directional sunlight onto the texture; otherwise your character will look weirdly lit from two directions at once inside Three.js.
- Separate API success from rig, material, and visual acceptance. A HTTP 200 download with a broken hip weight or missing albedo is not ready to ship.

Transfer bytes vs. GPU bytes: the lossless Meshopt reality check
Developers love recommending Meshopt (EXT_meshopt_compression) or Draco as a magic performance cure. They are great tools—for network download time only.
We ran a strict, byte-exact offline audit on a real rigged character GLB using meshoptimizer 0.22.0 and Three.js r180 with EXT_meshopt_compression (no quantization, no simplification, no index reordering):
| Metric | Uncompressed GLB (1K maps) | Lossless Meshopt GLB | What actually changed |
|---|---|---|---|
| File size on disk / wire | 4,812,256 bytes (4.81 MB) | 3,752,324 bytes (3.75 MB) | 22.0% smaller download |
| Decoder overhead | 0 bytes | 24,848 bytes (~24.8 KB) | Tiny one-time decoder load |
| Decoded buffer views & images | 41 views · 3 image streams | 41 views · 3 image streams | Byte-exact match |
| Skinned vertex poses checked | 42,245 rows × 7 poses | 42,245 rows × 7 poses | 0.000 diff across every pose |
| GPU VRAM textures, triangles & skinning | Identical | Identical | Zero GPU savings |
That last row is the entire engineering lesson: Meshopt shrinks transfer bytes, not GPU work. Once the browser decodes the buffer views, the GPU still holds the exact same uncompressed textures, shades the exact same live triangles, and runs the exact same bone skinning every frame.
To cut GPU cost, reach for the tools that change what the GPU actually stores and draws:
- Resize textures to 1K (or 512 px for distant props) and use KTX2 / Basis Universal (
KTX2Loader.detectSupport(renderer)) so textures stay compressed in VRAM (BC7,ASTC, orETC2). - Use
KHR_mesh_quantizationand decimation to shrink vertex buffers and triangle counts. - Batch repeated objects with
THREE.InstancedMeshso 80 trees cost 1 draw call instead of 80. - Call
.dispose()rigorously on geometries, materials, and textures whenever a room or mission unmounts.
Share one 113 KB skeleton-only GLB across 28+ character rigs
Embedding 10 full-body emote animations (dance, sit, cheer, wave, salute, bow, clap, sleep, heart, and panic) inside every character GLB is a classic bloat trap. Multiply 28 imported crew models by 10 clips and you ship hundreds of redundant animation tracks—and every time you tweak a dance loop, you have to re-export 28 files.
Route Awakening solves this with a two-layer, rig-agnostic skeletal emote engine:
- Layer 1 — One shared
113,092-byte skeleton-only glTF 2.0 library (humanoid-emotes-v1.glb): Generated reproducibly by a Node/Three.js build script (build-humanoid-emote-clips-glb.mjs), it holds 10 full-body clips across 13 canonical joints (Hips,Spine,Spine02,neck,Head,LeftArm,LeftForeArm,RightArm,RightForeArm,LeftUpLeg,LeftLeg,RightUpLeg,RightLeg) with zero mesh geometry. - Layer 2 — Instant zero-download procedural fallback: While the 113 KB GLB loads—or for custom creature rigs that lack human arms and legs—the engine runs lightweight procedural bone accents immediately with zero network wait.
Making one clip drive wildly different rigs
Across our 28 imported GLBs, 14 used standard Mixamo/Meshy non-identity rest poses, 5 used identity-rest toy-walk skeletons with mirrored Left/Right X axes, and several more used custom bone prefixes (mixamorig:, Chest/Neck, custom creature spines). Playing raw local quaternions on mixed rest poses twists arms backward instantly.
Instead, every keyframe in our shared GLB encodes canonical character-root deltas (+X character left, +Y up, +Z forward). At runtime, the retargeter converts each delta cleanly into each bone's own parent coordinate frame:
// Apply canonical character-space delta inside this bone's parent frame:
// bone.quaternion = parentWorld^-1 * charDelta * parentWorld * bone.quaternion
Combined with four small safeguards, one 113 KB file drives the whole cast identically:
- Bone alias matching across standard,
mixamorig:, and custom names. - Automatic Left/Right handedness detection so mirrored identity-rest rigs wave with the right arm instead of inverting.
- Torso-height hip scaling so centimeter-scale and meter-scale rigs drop the exact same visual proportion during a sit or dance bounce.
- Save-and-restore tokens around every touched bone quaternion and
Hipsposition before the nextAnimationMixerstep so emotes never leave permanent pose drift.
For looping emotes (sit, sleep, dance), choose sustain loop windows aligned to the animation's exact sine period (for example, 2.4s = three exact 0.8s beats at 2.5π rad/s) so loops repeat forever with zero wrap seam.
Greedy voxel meshing and instanced scenery with baked contact shadows
Inside Route Awakening's co-op Dig and Defend holodeck mission, players mine and fortify destructible voxel terrain. Naive cube rendering (six quads per solid block) wastes thousands of hidden interior faces and blows mobile budgets immediately.
Our voxel mesher (lounge-v9-voxel-mesher.ts, adapting Mikola Lysenko's classic greedy sweep) enforces three strict performance rules:
- Preallocated typed-array buffers: Every chunk reuses preallocated
Float32Arrayposition, normal, color, UV, and block-ID buffers plus a reusableInt16Array(256)slice mask—zero allocations during gameplay. - Hard triangle ceiling: Each chunk admits at most
MAX_VOXEL_CHUNK_QUADS = 1792quads. Across 9 chunks, the entire destructible world is hard-capped at 32,256 triangles total. - Integer-cursor slice budgeting: Instead of freezing the main thread to rebuild an entire 16×16×16 chunk in one frame (or even allocating a JS generator object per frame),
rebuildVoxelChunkSlice(terrain, chunkId, buffer, cursor)steps through all 51 boundary slices (0..50— 3 axes × 17 face boundaries from-1to15, including the neighboring-chunk seam) cleanly inside the frame budget while baking per-vertex ambient occlusion (sideU,sideV,diagonal) directly into vertex colors.
We used the same zero-waste mindset outdoors in the Greenfield meadow (lounge-meadow-scenery.ts): 42–78 pine trees and 26–48 mossy granite boulders each merge their trunk, canopy tiers, and a flat dark contact-shadow base skirt into a single vertex-colored BufferGeometry rendered through THREE.InstancedMesh. Every tree and rock sits visibly grounded on sloped terrain for zero extra draw calls and zero dynamic shadow-map cost.
Zero-download Web Audio SFX and mobile touch ergonomics
Audio files add network requests, decode delays, and codec edge cases across Safari and mobile Chrome. For responsive UI, locomotion, combat, and arcade table audio, Route Awakening synthesizes sound effects lazily on the client using the Web Audio API (OscillatorNode, filtered noise bursts, gain envelopes):
- Footsteps, pickaxe digs, ore chimes, combat slashes, dodge whooshes, beacon pentatonic chords, and casino SFX cost 0 KB of MP3 downloads and trigger with low latency.
- Create/unlock the
AudioContextstrictly on the first user pointer or keyboard gesture, resume lazily whenever audio plays (and add avisibilitychangeresume hook for persistent background music/radio channels) so audio recovers cleanly after switching apps on iOS.
For mobile controls, desktop WASD ports fail fast if you just slap translucent arrows on a phone screen:
- Use Pointer Events with
touch-action: none,setPointerCapture, and explicitpointerIdtracking so left-thumb movement and right-thumb camera look never steal each other's touches. - Make the left thumbstick auto-sprint at outer-rim deflection (
>= 85%) and walk inside—removing an awkward extra sprint button on small screens. - Let the right look pad accept direct swipe-delta turning alongside edge hold so camera turns feel immediate.
- Replace long compass sentences (
"14 m left") with compact directional arrow pills (14m ◀/▶/▲/▼) that fit cleanly in landscape mobile HUDs, and keepprefers-reduced-motionguards active so motion-sensitive users get calm zero-hop transitions.
Measure real frame times with opt-in telemetry (?routePerformance=1)
Average FPS hides stuttering. A scene running at "58 FPS average" with two 90 ms garbage-collection hitches every second feels broken.
Route Awakening ships an opt-in diagnostic overlay triggered strictly by ?routePerformance=1 (lounge-v9-performance.ts):
- Zero overhead when off: If the query param is absent,
createV9Performance()returnsnullimmediately—noperformance.mark, no allocations, no clock reads. - Multi-pass accuracy: In scenes with portals or render passes, wrapping
renderer.renderwithrenderer.info.autoReset = falsesums per-frame draw calls and triangles across every completed pass while keepingrenderer.info.memory.geometriesand.texturesstrictly as resident gauges (never accidentally summing resident counts across passes). - The metrics that catch real pain: A rolling 10-second window reporting
p50,p95,p99, andmaxframe times in milliseconds, exact hitch counts (>33msand>50ms),PerformanceObserver("longtask")stalls, physics step mean/max ms, JS heap usage, active DPR, and a one-click Copy report JSON button for reproducible before-and-after PR diffs.
Always run telemetry for several minutes on an actual phone—mobile GPUs start cool and can thermally throttle after a couple of minutes of sustained rendering.
Apply this checklist to your own 3D web project
| Symptom you see | Real root cause | First fix to run |
|---|---|---|
| Mobile browser reloads or crashes on load | Uncompressed 2K/4K textures blowing GPU VRAM | Resize textures to 1K, convert to KTX2/Basis, verify .dispose() on unmount |
| AI character renders flat gray or rainbow-purple | Roughness or normal map bound into albedo (map_Kd) | Inspect .mtl slots and raw image pixels before assigning materials |
| File shrank 22% with Meshopt, FPS did not move | Transfer shrank; GPU VRAM, triangles, and skinning stayed identical | Cut triangles, batch props into InstancedMesh, shrink textures |
| Shared animation twists half your characters' arms | Mixed rest poses or mirrored Left/Right skeleton axes | Apply deltas in character-root space (parentWorld^-1 delta parentWorld * q) |
| Stutter every time terrain or meshes rebuild | Per-frame buffer/generator allocation or full-chunk spike | Preallocate typed arrays and budget work per frame via integer slice cursors |
| Desktop works; mobile touch feels sluggish | dpr = 3 fill-rate overload or missing touch-action: none | Cap DPR (<= 1.5–2), track pointerId, add outer-rim auto-sprint |
You can explore the live build at punball.com/games/route-awakening, read the broader arcade case study on the Punball portfolio page, or see how we apply the same verification discipline to AI video production in How I make AI music videos. Grab the downloadable browser-3d-optimization/SKILL.md below to drop this full audit checklist straight into Claude Code, Codex, Grok Build, Hermes, or any local coding agent.
FAQ
Does Meshopt or Draco compression improve Three.js frame rate?
No. Meshopt (EXT_meshopt_compression) and Draco shrink network download size and load time, which helps first paint on mobile networks. Once decoded, live triangle counts, uncompressed textures, and skeletal skinning cost the same on the GPU unless you also optimize textures (1K or KTX2/Basis), decimate geometry, and instance repeated meshes.
How can one animation pack work across Mixamo, Meshy, and custom 3D rigs?
Store keyframed bone deltas in a canonical character-root coordinate space (+X left, +Y up, +Z forward) inside one lightweight skeleton-only GLB, then convert each delta into each bone's parent space at runtime (parentWorld^-1 charDelta parentWorld * bone.quaternion). Pairing that transform with bone-name aliases, mirrored-handedness detection, and torso-height hip scaling lets one ~113 KB file drive dozens of heterogeneous rigs.
Why use synthesized Web Audio SFX instead of MP3 files in a browser game?
Synthesized Web Audio effects require zero extra network downloads, avoid codec fallbacks across Safari and Chrome, and play with near-zero latency once the AudioContext is unlocked on the first user gesture. Keep recorded audio files for music or dialogue, and synthesize crisp repeatable UI, footstep, and impact cues in code.
Why track p95/p99 frame time instead of average FPS?
Average FPS hides short freezes that make a mobile 3D scene feel janky. Tracking rolling p50, p95, p99, and exact frame counts above 33 ms and 50 ms immediately exposes garbage-collection spikes, shader-compile stalls, and thermal throttling.