# 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.

- **Canonical page:** https://gamecrew.ai/techniques/three/mobile-adaptive-quality-drs
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** optimization
- **Tags:** `mobile`, `optimization`, `drs`, `quality-tiers`, `pixel-ratio`, `half-float`, `ios`, `android`, `watchdog`, `chunked-bake`, `profiler`, `performance`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-24)
- **Demo:** 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 down `high → medium → low`.
- **Hysteresis Dynamic Resolution Scaler (`DynamicResolutionScaler`):** Measure smoothed EMA frame time against your target frame budget (`33.3 ms` at 30 fps or `16.7 ms` at 60 fps) and adjust `renderer.setPixelRatio` smoothly 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 ms` per-frame slices inside `game.onUpdate` instead of one multi-second synchronous stall that triggers Android's GPU watchdog reset.
- **iOS half-float (`RGBA16F`) NaN clamp (`< 65504`):** Writing HDR values above `65504` into half-float render targets overflows to `Infinity/NaN` on iOS WebGL 2, creating permanent black tiles during bloom. Always clamp shader HDR outputs below `65000`.
- **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:** $\bar{t}_n = (1 - \alpha)\,\bar{t}_{n-1} + \alpha\,t_n$ ($\alpha = 0.12$). Scale DPR down by `0.90×` when $\bar{t} > 1.12\,T_{\text{target}}$, up by `1.06×` when $\bar{t} < 0.80\,T_{\text{target}}$, gated by a cooldown window of `20` frames.
- **IEEE 754 binary16 ceiling:** Max finite `float16` is `65504`. Clamping HDR output via `min(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`)

```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 visible `InstancedMesh.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 through `ChunkedLoadBakery` across frames.
- **Clamp Emissive & Sun Specular Below `65000`:** An unguarded `pow(ndoth, 128) * 100000` specular peak overflows `float16` (`65504`) to `NaN` on 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 `medium` or `low` on reload instead of crash-looping.

## Verification Checklist

1. Simulate an interrupted boot (`booting === '1'` in storage) and assert `BootTierGuard` automatically steps `high → medium → low`, then clears the sentinel after 3 healthy frames.
2. Feed high (`48 ms`) then low (`14 ms`) frame times into `DynamicResolutionScaler` and verify smooth clamped scaling with zero oscillation inside the deadband.
3. Verify `ChunkedLoadBakery` completes all procedural bake tasks across bounded per-frame slices without stalling.
4. Confirm `PassIsolationProfiler.measureIsolation` reports 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
