Mobile-First Adaptive Quality Tiers, Dynamic Resolution Scaling & GPU Watchdog Safety in Three.js
Keep Three.js r183 browser games smooth and crash-free on mid-range Android and iOS phones via measured 3-tier quality presets with boot-crash auto-step-down, hysteresis dynamic resolution scaling, chunked load-time baking, iOS RGBA16F 65504 NaN clamping, and live pass-isolation profiling.
- mobile
- optimization
- drs
- quality-tiers
- pixel-ratio
- half-float
- ios
- android
- watchdog
- chunked-bake
- profiler
- performance
No demo.
When to Use (and When Not To)
Use these mobile-first guardrails in every Three.js r183 game that targets phones alongside desktop browsers — a desktop GPU hides every failure mode that crashes or stalls mid-range Android and iOS devices:
- Boot crash-recovery tier step-down (
BootTierGuard): Persist an in-flight boot marker before building heavy shaders/geometries and clear it only after 3 healthy frames. If a mobile browser loses its GPU context or reloads mid-boot, the next visit automatically steps downhigh → medium → low. - Hysteresis Dynamic Resolution Scaler (
DynamicResolutionScaler): Measure smoothed EMA frame time against your target frame budget (33.3 msat 30 fps or16.7 msat 60 fps) and adjustrenderer.setPixelRatiosmoothly within[0.55, maxDpr]using a deadband and cooldown window so resolution never oscillates. - Chunked load-time baking (
ChunkedLoadBakery): Split procedural canvas textures, foliage atlases, and geometry builds into small<= 10 msper-frame slices insidegame.onUpdateinstead of one multi-second synchronous stall that triggers Android's GPU watchdog reset. - iOS half-float (
RGBA16F) NaN clamp (< 65504): Writing HDR values above65504into half-float render targets overflows toInfinity/NaNon iOS WebGL 2, creating permanent black tiles during bloom. Always clamp shader HDR outputs below65000. - Live pass-isolation "Measure" profiler (
PassIsolationProfiler): Toggle named scene groups (foliage,atmosphere,props,shadows) off one by one to identify real triangle/draw-call/ms bottlenecks on a phone without rebuilding.
Skip aggressive dynamic resolution downscaling for ultra-lightweight 2D/UI scenes that already finish in < 4 ms per frame.
Mathematical & Safety Core
- EMA frame smoothing:
t_n = (1 - α)\,t_n-1 + α\,t_n(α = 0.12). Scale DPR down by0.90×whent > 1.12\,T_target, up by1.06×whent < 0.80\,T_target, gated by a cooldown window of20frames. - IEEE 754 binary16 ceiling: Max finite
float16is65504. Clamping HDR output viamin(max(rgb, vec3(0.0)), vec3(65000.0))eliminates NaN/Inf bloom contamination.
Engine Implementation
Strict TypeScript Mobile Tiers, DRS, Chunked Bakery, Half-Float Clamp & Pass Profiler (Assets/Game/mobileQuality.ts)
import * as THREE from 'three';
export type QualityTier = 'high' | 'medium' | 'low';
export interface QualityPreset {
readonly tier: QualityTier;
readonly maxDpr: number;
readonly minDpr: number;
readonly shadowMapSize: number;
readonly shadowsEnabled: boolean;
readonly foliageScale: number;
readonly fogFar: number;
readonly windSway: boolean;
}
export const QUALITY_PRESETS: Record<QualityTier, QualityPreset> = {
high: { tier: 'high', maxDpr: 2.0, minDpr: 0.75, shadowMapSize: 1024, shadowsEnabled: true, foliageScale: 1.0, fogFar: 85, windSway: true },
medium: { tier: 'medium', maxDpr: 1.5, minDpr: 0.65, shadowMapSize: 512, shadowsEnabled: true, foliageScale: 0.65, fogFar: 62, windSway: true },
low: { tier: 'low', maxDpr: 1.1, minDpr: 0.55, shadowMapSize: 256, shadowsEnabled: false, foliageScale: 0.35, fogFar: 44, windSway: false },
};
/** Safe ceiling below IEEE 754 float16 max (65504) to prevent black NaN blocks in iOS WebGL 2 bloom targets. */
export const HALF_FLOAT_SAFE_MAX = 65000;
export const HALF_FLOAT_CLAMP_GLSL = /* glsl */ `
vec3 clampHalfFloat(vec3 color) {
return min(max(color, vec3(0.0)), vec3(65000.0));
}
`;
export function clampHalfFloatScalar(v: number): number {
if (!Number.isFinite(v) || v <= 0) return 0;
return Math.min(v, HALF_FLOAT_SAFE_MAX);
}
export interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
const TIER_ORDER: readonly QualityTier[] = ['high', 'medium', 'low'];
export function stepDownTier(tier: QualityTier): QualityTier {
const i = TIER_ORDER.indexOf(tier);
return i >= 0 && i < TIER_ORDER.length - 1 ? TIER_ORDER[i + 1] : 'low';
}
/**
* Crash-recovery quality selector: marks boot in-flight before heavy GPU init and clears the flag
* after 3 healthy frames. If a mobile browser dropped the GPU context on launch, reload steps down automatically.
*/
export class BootTierGuard {
readonly tierKey: string;
readonly bootKey: string;
tier: QualityTier;
steppedDownFrom?: QualityTier;
private healthyFrames = 0;
private confirmed = false;
private readonly store?: StorageLike;
constructor(storage?: StorageLike, prefix = 'ccgd_quality', defaultTier: QualityTier = 'high') {
this.store = storage;
this.tierKey = `${prefix}:tier`;
this.bootKey = `${prefix}:booting`;
const saved = (storage?.getItem(this.tierKey) as QualityTier | null) ?? defaultTier;
const base: QualityTier = TIER_ORDER.includes(saved) ? saved : defaultTier;
if (storage?.getItem(this.bootKey) === '1') {
this.steppedDownFrom = base;
this.tier = stepDownTier(base);
} else {
this.tier = base;
}
try {
storage?.setItem(this.tierKey, this.tier);
storage?.setItem(this.bootKey, '1');
} catch {
/* private-browsing storage quota fallback */
}
}
/** Call once per rendered frame; after 3 healthy frames the boot-crash sentinel is cleared. */
noteHealthyFrame(): boolean {
if (this.confirmed) return true;
this.healthyFrames++;
if (this.healthyFrames >= 3) {
this.confirmed = true;
try {
this.store?.removeItem(this.bootKey);
} catch {
/* ignore */
}
return true;
}
return false;
}
setTier(next: QualityTier): void {
this.tier = next;
try {
this.store?.setItem(this.tierKey, next);
} catch {
/* ignore */
}
}
}
/**
* Hysteresis Dynamic Resolution Scaler (DRS): holds target FPS on mobile by smoothly adjusting
* pixelRatio when EMA frame time stays outside the deadband past the cooldown window.
*/
export class DynamicResolutionScaler {
readonly targetMs: number;
readonly minDpr: number;
readonly maxDpr: number;
readonly cooldownFrames: number;
dpr: number;
emaMs: number;
adjustments = 0;
private framesSinceAdjust = 0;
constructor(opts: { targetFps?: number; minDpr?: number; maxDpr?: number; initialDpr?: number; cooldownFrames?: number } = {}) {
this.targetMs = 1000 / Math.max(15, opts.targetFps ?? 30);
this.minDpr = opts.minDpr ?? 0.6;
this.maxDpr = opts.maxDpr ?? 1.75;
this.cooldownFrames = opts.cooldownFrames ?? 20;
this.dpr = THREE.MathUtils.clamp(opts.initialDpr ?? this.maxDpr, this.minDpr, this.maxDpr);
this.emaMs = this.targetMs;
}
sample(frameMs: number, apply?: (dpr: number) => void): number {
const clamped = THREE.MathUtils.clamp(frameMs, 2, 150);
this.emaMs = this.emaMs * 0.88 + clamped * 0.12;
this.framesSinceAdjust++;
if (this.framesSinceAdjust < this.cooldownFrames) return this.dpr;
let next = this.dpr;
if (this.emaMs > this.targetMs * 1.12 && this.dpr > this.minDpr + 0.01) {
next = Math.max(this.minDpr, Number((this.dpr * 0.9).toFixed(3)));
} else if (this.emaMs < this.targetMs * 0.8 && this.dpr < this.maxDpr - 0.01) {
next = Math.min(this.maxDpr, Number((this.dpr * 1.06).toFixed(3)));
}
if (Math.abs(next - this.dpr) >= 0.01) {
this.dpr = next;
this.framesSinceAdjust = 0;
this.adjustments++;
apply?.(this.dpr);
}
return this.dpr;
}
}
/**
* Slices heavy load-time procedural bakes across frames (<= sliceBudgetMs per step) so mid-range
* Android GPUs never reset the context from a single multi-second blocking stall.
*/
export class ChunkedLoadBakery {
readonly total: number;
completed = 0;
private readonly tasks: (() => void)[];
constructor(tasks: (() => void)[]) {
this.tasks = [...tasks];
this.total = tasks.length;
}
get done(): boolean {
return this.completed >= this.total;
}
get progress(): number {
return this.total === 0 ? 1 : this.completed / this.total;
}
step(sliceBudgetMs = 10, maxTasksPerSlice = 4): number {
const start = typeof performance !== 'undefined' ? performance.now() : Date.now();
let ran = 0;
while (this.completed < this.total && ran < maxTasksPerSlice) {
this.tasks[this.completed]();
this.completed++;
ran++;
const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
if (now - start >= sliceBudgetMs) break;
}
return ran;
}
}
export interface PassIsolationReport {
readonly group: string;
readonly visibleBefore: boolean;
readonly drawCalls: number;
readonly triangles: number;
}
/** Toggles scene groups off in isolation so developers can measure per-group GPU cost live on device. */
export class PassIsolationProfiler {
private readonly groups = new Map<string, THREE.Object3D>();
register(name: string, root: THREE.Object3D): void {
this.groups.set(name, root);
}
setEnabled(name: string, enabled: boolean): boolean {
const g = this.groups.get(name);
if (!g) return false;
g.visible = enabled;
return true;
}
names(): string[] {
return [...this.groups.keys()];
}
/** Measures draw calls and triangles with each registered group disabled in turn (restores visibility afterward). */
measureIsolation(renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera): PassIsolationReport[] {
const results: PassIsolationReport[] = [];
for (const [name, obj] of this.groups) {
const prev = obj.visible;
obj.visible = false;
renderer.render(scene, camera);
results.push({
group: name,
visibleBefore: prev,
drawCalls: renderer.info.render.calls,
triangles: renderer.info.render.triangles,
});
obj.visible = prev;
}
renderer.render(scene, camera);
return results;
}
}
Performance & Platform Traps
- On Phones, Vertex Count Beats Pixel Count: Scenes dense with instanced foliage cards are often vertex-bound on Adreno 6xx GPUs; halving render resolution helps fill-rate, while tier-scaled
foliageScale(reducing visibleInstancedMesh.count) cuts vertex cost directly. - Never Bake Everything Synchronously in
start(): Painting a procedural atlas or generating hundreds of terrain chunks in one 2-second loop triggers Android GPU context loss. Feed work throughChunkedLoadBakeryacross frames. - Clamp Emissive & Sun Specular Below
65000: An unguardedpow(ndoth, 128) * 100000specular peak overflowsfloat16(65504) toNaNon iOS Safari WebGL 2 and spreads black tiles across bloom passes. - Always Test Tier Step-Down: Persist the boot-in-flight sentinel before compiling shaders so a crashed mobile start recovers cleanly into
mediumorlowon reload instead of crash-looping.
Verification Checklist
- Simulate an interrupted boot (
booting === '1'in storage) and assertBootTierGuardautomatically stepshigh → medium → low, then clears the sentinel after 3 healthy frames. - Feed high (
48 ms) then low (14 ms) frame times intoDynamicResolutionScalerand verify smooth clamped scaling with zero oscillation inside the deadband. - Verify
ChunkedLoadBakerycompletes all procedural bake tasks across bounded per-frame slices without stalling. - Confirm
PassIsolationProfiler.measureIsolationreports lower draw calls/triangles when foliage or prop groups are disabled and restores full visibility afterward.
Official references
- IEEE 754 Half-Precision Floating Point (max finite 65504)
- Khronos WebGL 2 Mobile GPU Best Practices
- Three.js WebGLRenderer PixelRatio & CompileAsync Manual
More Three.js games
Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.
More Three.js techniques
Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →
Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.
Octahedral Impostor Forests & Procedural Trees in Three.js →
Render thousands of 3D trees or distant props in a single Three.js r183 InstancedMesh draw call by baking an NxN hemisphere octahedral atlas at startup from a procedural ez-tree-style branching tree mesh.
Isolated-PRNG Seeded Worlds, Procedural Foliage Atlas, Drifting Weather & Canopy Light Shafts in Three.js →
Generate deterministic forests and worlds where each system (terrain, trees, rocks, water, cabins) owns an isolated PRNG stream so edits never shift existing placements, paired with a procedural canvas foliage atlas, drifting 4-state weather, and half-float-safe volumetric canopy light shafts.
Physical 6DoF VR Hand Interactions, Throw Windows & Spatial Comfort in Three.js →
Tactile 6DoF WebXR hand interactions in Three.js using game.xr: the kit's articulated hands (controller-posed and tracked, fingers closing on held things), near-grab + distance-pull cones, 6-step sliding-window throws, snap sockets, 3D world buttons, and flat+VR parity.
Read via free MCP — or sign in to add techniques & beta test
Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.
