{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"fireworks-hdr","type":"registry:ui","title":"FireworksHdr","description":"GPU fireworks background with a deterministic, DOM-free physics core (rockets, peony/willow/ring/glyph shells, sparks, embers, smoke) rendered by a WebGPU engine into a wide-gamut, extended-tone-mapping canvas so bursts and comet trails burn brighter than SDR white on HDR displays, degrading silently through a WebGL2 fallback and a soft-knee SDR path everywhere else","author":"fancy-ui <https://fancy-ui.rama.app>","categories":["effects"],"devDependencies":["@webgpu/types@^0.1.71"],"registryDependencies":["https://fancy-ui.rama.app/r/internals-dom.json","https://fancy-ui.rama.app/r/utils.json"],"files":[{"path":"react/src/components/fireworks-hdr/FireworksHdr.tsx","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\nimport { cn } from \"../../utils\";\nimport { useEventCallback } from \"../../internals/dom/use-event-callback\";\nimport { useLiveRef } from \"../../internals/dom/use-live-ref\";\nimport { isDev } from \"./dev\";\nimport {\n\tcreateSim,\n\thexToLinearRgb,\n\tlinearToOklab,\n\tnextShellHue,\n\tshellHueColor,\n\tpoissonIntervalMs,\n\tsampleZone,\n\trectExpandedContains,\n\tresolveQualityTier,\n\tcreateAdaptiveState,\n\tadaptiveDowngradeStep,\n\tadaptiveLevel,\n\tAMBIENT_ZONES,\n\tAMBIENT_RADIUS_MAX,\n\tKEEP_CLEAR_DESKTOP,\n\tQUALITY,\n\tSHELL,\n\tSHELL_JITTER_DEG,\n\tEXPOSURE_AMBIENT,\n\ttype Sim,\n\ttype Rgb,\n\ttype Rect,\n\ttype ShellKind,\n\ttype FireworksHandle,\n\ttype FireworksRenderLevel,\n\ttype LaunchOptions,\n\ttype LaunchResult,\n} from \"./fireworks-shared\";\nimport { startWebGpuFireworks, type FireworksEngineHandle } from \"./webgpu-renderer\";\nimport { startWebGl2Fireworks } from \"./webgl2-renderer\";\n\n/** Props for {@link FireworksHdr}. */\nexport interface FireworksHdrProps {\n\t/**\n\t * Brand hues (hex). Order is irrelevant — they are parsed and sorted into\n\t * the canonical cool→warm ping-pong order (cyan, blue, violet, magenta)\n\t * so the shell sweep is stable however they are listed.\n\t */\n\tpalette?: string[];\n\t/**\n\t * Opt into the GPU engine: WebGPU HDR first, then a WebGL2 fallback\n\t * (display-p3 SDR where supported, else plain sRGB). When false, no engine\n\t * boots at all.\n\t */\n\thdr?: boolean;\n\t/** Display exposure multiplier, clamped [1,4]. */\n\texposure?: number;\n\t/** Run the ambient auto-scheduler. */\n\tambient?: boolean;\n\t/** Ambient intensity [0,1] — scales shell size/energy. */\n\tambientIntensity?: number;\n\t/**\n\t * Launch a shell toward the pointer on window pointerdown. Read once, when\n\t * the engine activates — a later change does not re-wire the listener.\n\t */\n\tinteractive?: boolean;\n\t/** Quality tier, or \"auto\" to pick from the render level + DPR. */\n\tquality?: \"auto\" | \"high\" | \"mid\" | \"low\";\n\t/**\n\t * Which shells the ambient scheduler is allowed to fire, picked uniformly.\n\t * Defaults to the weighted peony/willow/ring mix. Pattern shells (\"heart\",\n\t * \"star\") are valid here; \"glyph\" and \"shape\" are not — they need points\n\t * the scheduler has no way to invent, so they are ignored if listed.\n\t */\n\tambientShells?: ShellKind[];\n\t/** Force ambient off under prefers-reduced-motion (launches still work). */\n\trespectReducedMotion?: boolean;\n\t/** Extra classes on the canvas wrapper. */\n\tclassName?: string;\n\t/**\n\t * Called when the engine is live, with an imperative handle. Never called\n\t * when no GPU renderer comes up (the caller uses its own timeout). Called\n\t * again after a GPU context loss is recovered, with a fresh handle whose\n\t * `renderLevel` reflects the engine that came back (a lost WebGPU device\n\t * can return as the WebGL2 fallback).\n\t */\n\tonReady?: (handle: FireworksHandle) => void;\n\t/**\n\t * Called once when the GPU context is lost and cannot be brought back.\n\t * The component has torn itself down by then: the loop is stopped, the\n\t * listeners are gone, and any handle it handed out is inert. Use it to\n\t * swap in a static fallback.\n\t */\n\tonLost?: () => void;\n}\n\n// Largest instance buffer we might need — the engine is sized for the high\n// tier up front so the resolved (auto) quality can be any tier ≤ high.\nconst MAX_INSTANCES = QUALITY.high.maxParticles;\nconst DT_CLAMP = 0.05; // guards against huge dt after a tab switch\n// AD §4.3 / physics §6: \"ambient 2–3 (rare 4)\" — the scheduler's own cadence\n// stays gated at 2; a mirrored double (§5.2) may push a third shell in\n// flight, but never a fourth.\nconst MAX_AMBIENT_INFLIGHT_SOFT = 2;\nconst MAX_AMBIENT_INFLIGHT_HARD = 3;\n// How long a lost WebGL context is given to announce its restoration before\n// the component gives up and reports the failure through `onLost`.\nconst RESTORE_TIMEOUT_MS = 4000;\n\nfunction clampExposure(v: number): number {\n\treturn Number.isFinite(v) ? Math.max(1, Math.min(4, v)) : 1;\n}\n\n/** Parse palette hexes to linear RGB, sorted cool→warm by oklab hue angle. */\nfunction resolvePalette(hexes: string[]): Rgb[] {\n\tconst parsed = (hexes.length ? hexes : [\"#42cfff\", \"#3d5bff\", \"#a142ff\", \"#ff2fd6\"]).map(\n\t\thexToLinearRgb\n\t);\n\treturn parsed\n\t\t.map((c) => {\n\t\t\tconst o = linearToOklab(c);\n\t\t\t// Angle folded to [0,2π); cyan≈196°→…→magenta≈312° sort ascending.\n\t\t\tlet h = Math.atan2(o.b, o.a);\n\t\t\tif (h < 0) h += Math.PI * 2;\n\t\t\treturn { c, h };\n\t\t})\n\t\t.sort((a, b) => a.h - b.h)\n\t\t.map((x) => x.c);\n}\n\n/** Clamped device-pixel ratio, matching the renderers' MAX_DPR. */\nfunction currentDpr(): number {\n\treturn Math.min(typeof window !== \"undefined\" ? window.devicePixelRatio || 1 : 1, 2);\n}\n\n/**\n * A conservative low-power signal (modest RAM or few logical cores). Only ever\n * consulted on the WebGL2 fallback path (a weak-GPU signal already), where it\n * drops the auto tier from \"mid\" to \"low\". WebGPU machines are never affected.\n */\nfunction detectLowPower(): boolean {\n\tif (typeof navigator === \"undefined\") return false;\n\tconst mem = (navigator as Navigator & { deviceMemory?: number }).deviceMemory;\n\tconst cores = navigator.hardwareConcurrency;\n\treturn (typeof mem === \"number\" && mem <= 4) || (typeof cores === \"number\" && cores <= 4);\n}\n\nexport function FireworksHdr({\n\tpalette = [\"#ff2fd6\", \"#a142ff\", \"#3d5bff\", \"#42cfff\"],\n\thdr = true,\n\texposure = EXPOSURE_AMBIENT,\n\tambient = true,\n\tambientIntensity = 0.35,\n\tinteractive = true,\n\tquality = \"auto\",\n\tambientShells,\n\trespectReducedMotion = true,\n\tclassName = \"\",\n\tonReady,\n\tonLost,\n}: FireworksHdrProps) {\n\tconst canvasRef = useRef<HTMLCanvasElement>(null);\n\n\t// Two props are read again AFTER mount by closures the engine owns —\n\t// `quality` when a post-loss reboot re-resolves the tier, `interactive` when\n\t// the (asynchronous) engine activation decides whether to hook the pointer\n\t// listener. Teardown unhooks what was actually wired, not what the prop says\n\t// at unmount time, so a post-mount flip cannot strand the listener. They go through\n\t// live refs, the React counterpart of the reference implementation's\n\t// reactive prop reads; the callbacks go through identity-stable wrappers for\n\t// the same reason. Every other prop is read exactly once, at mount.\n\tconst qualityRef = useLiveRef(quality);\n\tconst interactiveRef = useLiveRef(interactive);\n\tconst handleReady = useEventCallback(onReady);\n\tconst handleLost = useEventCallback(onLost);\n\n\t// Mount/unmount only, matching the source's onMount + its returned teardown:\n\t// the engine is booted once and no prop change re-inits it. The refs above\n\t// are what keeps the long-lived closures current, so the dependency list is\n\t// honestly empty rather than artificially frozen.\n\tuseEffect(() => {\n\t\tconst node = canvasRef.current;\n\t\tif (!node) return;\n\t\t// Re-bound with a non-nullable declared type: the helpers below are hoisted\n\t\t// function declarations, which TypeScript analyses independently of the\n\t\t// guard above and would otherwise still see `HTMLCanvasElement | null`.\n\t\tconst canvas: HTMLCanvasElement = node;\n\n\t\tlet disposed = false;\n\t\tlet engine: FireworksEngineHandle | null = null;\n\t\tlet sim: Sim | null = null;\n\t\tlet instances: Float32Array<ArrayBuffer> | null = null;\n\t\tlet rafId = 0;\n\t\tlet running = false;\n\t\tlet lastTime = 0;\n\n\t\t// Adaptive downgrade: session-sticky quality ladder driven by an\n\t\t// EMA of frame time. Applied only on active frames (see `loop`).\n\t\tconst adaptive = createAdaptiveState();\n\t\tlet currentRenderScale = 1;\n\t\tlet currentSpawnScale = 1;\n\n\t\tlet currentExposure = clampExposure(exposure);\n\t\t// Reused per-frame uniforms object (no per-frame allocation in the loop).\n\t\tconst frameUniforms = { exposure: currentExposure };\n\t\tlet keepClear: Rect | null = KEEP_CLEAR_DESKTOP;\n\t\tconst paletteRgb = resolvePalette(palette);\n\n\t\tconst prefersReduced =\n\t\t\trespectReducedMotion &&\n\t\t\ttypeof window !== \"undefined\" &&\n\t\t\ttypeof window.matchMedia === \"function\" &&\n\t\t\twindow.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\n\t\t// Sampled once; only consulted on the WebGL2 fallback tier resolution.\n\t\tconst lowPower = detectLowPower();\n\n\t\tlet ambientOn = ambient && !prefersReduced;\n\t\tlet ambientLevel = Math.max(0, Math.min(1, ambientIntensity));\n\n\t\t// Ambient scheduling state.\n\t\tconst hueState = { i: 0, dir: 1 as 1 | -1 };\n\t\tlet ambientElapsed = 0;\n\t\tlet nextInterval = poissonIntervalMs(2200, Math.random, 900, 5200);\n\t\tlet ambientInFlight = 0;\n\t\tconst pendingDoubles: { at: number; mirror: boolean }[] = [];\n\n\t\tlet isVisible = true;\n\t\tlet observer: IntersectionObserver | null = null;\n\t\tlet resizeObs: ResizeObserver | null = null;\n\n\t\t// GPU context loss: one recovery attempt (WebGPU asks for a new device,\n\t\t// WebGL waits for `webglcontextrestored`), then a full teardown so the\n\t\t// caller can fall back instead of holding a dead handle.\n\t\tlet wired = false; // observers/listeners are registered exactly once\n\t\t// Latches whether the pointer listener was actually attached, so teardown\n\t\t// unhooks exactly what was hooked: reading the live `interactive` prop at\n\t\t// unmount would strand the listener on `window` after a true→false flip.\n\t\tlet pointerBound = false;\n\t\tlet recovering = false;\n\t\tlet recoveryUsed = false;\n\t\tlet restoreTimer = 0;\n\n\t\tfunction updateAspect() {\n\t\t\tif (!sim || !canvas) return;\n\t\t\tconst w = canvas.clientWidth || 1;\n\t\t\tconst h = canvas.clientHeight || 1;\n\t\t\tsim.setAspect(w / h);\n\t\t}\n\n\t\tfunction currentAspect(): number {\n\t\t\treturn (canvas.clientWidth || 1) / (canvas.clientHeight || 1);\n\t\t}\n\n\t\t// Shells the scheduler can fire unaided — \"glyph\" and \"shape\" need caller\n\t\t// points, so they are dropped from any list rather than breaking blank.\n\t\tconst SELF_DRAWING: ShellKind[] = [\"peony\", \"willow\", \"ring\", \"heart\", \"star\"];\n\t\tconst ambientMix = (ambientShells ?? []).filter((k) => SELF_DRAWING.includes(k));\n\n\t\t/** The stock weighted mix — what a launch uses when nothing overrides it. */\n\t\tfunction pickShell(): ShellKind {\n\t\t\tconst r = Math.random();\n\t\t\tif (r < 0.62) return \"peony\";\n\t\t\tif (r < 0.82) return \"willow\";\n\t\t\treturn \"ring\";\n\t\t}\n\n\t\t/**\n\t\t * The scheduler's own pick. `ambientShells` is scoped to the scheduler, so\n\t\t * pointer launches keep the stock mix — a prop named for the ambient loop\n\t\t * must not quietly rewrite what a click does.\n\t\t */\n\t\tfunction pickAmbientShell(): ShellKind {\n\t\t\tif (ambientMix.length) return ambientMix[Math.floor(Math.random() * ambientMix.length)]!;\n\t\t\treturn pickShell();\n\t\t}\n\n\t\tfunction ambientColor(): Rgb {\n\t\t\treturn shellHueColor(nextShellHue(hueState), paletteRgb, SHELL_JITTER_DEG, Math.random);\n\t\t}\n\n\t\t/**\n\t\t * AD §4.4: ambient bursts must stay within 0.10–0.20 (fraction of\n\t\t * min-dim) — distinct from the larger \"feature\" band reserved for\n\t\t * intro/feature shells. `SHELL[shell].radius[1]` is each shell's own\n\t\t * frozen max (willow runs a touch larger than peony/ring), so the scale\n\t\t * ceiling is derived per shell rather than shared, guaranteeing the\n\t\t * 0.20 cap holds at ambientLevel 1 for every shell kind.\n\t\t */\n\t\tfunction ambientScale(shell: ShellKind, level: number): number {\n\t\t\tconst raw = 0.7 + 0.4 * level;\n\t\t\tconst ceiling = AMBIENT_RADIUS_MAX / SHELL[shell].radius[1];\n\t\t\treturn Math.min(raw, ceiling);\n\t\t}\n\n\t\tfunction doAmbientLaunch(mirror: boolean) {\n\t\t\tif (!sim || ambientInFlight >= MAX_AMBIENT_INFLIGHT_HARD) return;\n\t\t\tlet picked = sampleZone(AMBIENT_ZONES, Math.random, keepClear);\n\t\t\tlet apex = picked.apex;\n\t\t\tif (mirror) {\n\t\t\t\tconst mirrored = { x: 1 - picked.apex.x, y: picked.apex.y };\n\t\t\t\t// sampleZone validated the ORIGINAL point; reflecting it can drop the\n\t\t\t\t// double straight into an asymmetric keep-clear rect. Re-test, and\n\t\t\t\t// take a freshly sampled (validated) apex when the mirror lands in it.\n\t\t\t\tif (keepClear && rectExpandedContains(keepClear, mirrored.x, mirrored.y)) {\n\t\t\t\t\tpicked = sampleZone(AMBIENT_ZONES, Math.random, keepClear);\n\t\t\t\t\tapex = picked.apex;\n\t\t\t\t} else {\n\t\t\t\t\tapex = mirrored;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst shell = pickAmbientShell();\n\t\t\tconst res = sim.launch({\n\t\t\t\tapex,\n\t\t\t\tshell,\n\t\t\t\tcolor: ambientColor(),\n\t\t\t\tdepth: picked.depth,\n\t\t\t\tscale: ambientScale(shell, ambientLevel),\n\t\t\t\tintensity: \"ambient\",\n\t\t\t});\n\t\t\tambientInFlight++;\n\t\t\t// Release the in-flight slot shortly after the shell detonates.\n\t\t\twindow.setTimeout(() => {\n\t\t\t\tambientInFlight = Math.max(0, ambientInFlight - 1);\n\t\t\t}, res.breakMs + 200);\n\t\t}\n\n\t\tfunction ambientTick(dtMs: number) {\n\t\t\tif (!ambientOn) return;\n\t\t\t// Fire any scheduled double-launches whose delay has elapsed.\n\t\t\tfor (let i = pendingDoubles.length - 1; i >= 0; i--) {\n\t\t\t\tconst pending = pendingDoubles[i]!;\n\t\t\t\tpending.at -= dtMs;\n\t\t\t\tif (pending.at <= 0) {\n\t\t\t\t\tdoAmbientLaunch(pending.mirror);\n\t\t\t\t\tpendingDoubles.splice(i, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tambientElapsed += dtMs;\n\t\t\tif (ambientElapsed >= nextInterval && ambientInFlight < MAX_AMBIENT_INFLIGHT_SOFT) {\n\t\t\t\tdoAmbientLaunch(false);\n\t\t\t\tambientElapsed = 0;\n\t\t\t\tnextInterval = poissonIntervalMs(2200, Math.random, 900, 5200);\n\t\t\t\t// 18% chance of a mirrored double, +120–320 ms later.\n\t\t\t\tif (Math.random() < 0.18) {\n\t\t\t\t\tpendingDoubles.push({ at: 120 + Math.random() * 200, mirror: true });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfunction applyAdaptiveLevel() {\n\t\t\tconst level = adaptiveLevel(adaptive);\n\t\t\tif (level.renderScale !== currentRenderScale) {\n\t\t\t\tcurrentRenderScale = level.renderScale;\n\t\t\t\tengine?.setRenderScale(currentRenderScale);\n\t\t\t}\n\t\t\tif (level.spawnScale !== currentSpawnScale) {\n\t\t\t\tcurrentSpawnScale = level.spawnScale;\n\t\t\t\tsim?.setSpawnScale(currentSpawnScale);\n\t\t\t}\n\t\t\tif (isDev()) {\n\t\t\t\tconsole.info(\n\t\t\t\t\t`[FireworksHdr] adaptive downgrade → step ${adaptive.step} ` +\n\t\t\t\t\t\t`(renderScale ${currentRenderScale}, spawnScale ${currentSpawnScale})`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tfunction loop(now: number) {\n\t\t\tif (!running || disposed || !sim || !engine || !instances) return;\n\t\t\t// A lost device/context never recovers on its own: reboot or tear down\n\t\t\t// rather than leave a live component driving a dead engine.\n\t\t\tif (engine.lost) {\n\t\t\t\thandleEngineLoss();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst rawFrameMs = now - lastTime;\n\t\t\tconst dt = Math.min((now - lastTime) / 1000, DT_CLAMP);\n\t\t\tlastTime = now;\n\n\t\t\tambientTick(dt * 1000);\n\t\t\tengine.resizeIfNeeded();\n\t\t\tsim.step(dt);\n\t\t\tconst n = sim.writeInstances(instances);\n\t\t\tframeUniforms.exposure = currentExposure;\n\t\t\tengine.frame(dt, instances, n, frameUniforms);\n\n\t\t\t// Fold only ACTIVE, foreground frames into the adaptive controller so\n\t\t\t// paused / reduced-motion-idle frames (n === 0) never skew the average.\n\t\t\tif (n > 0 && !document.hidden && adaptiveDowngradeStep(adaptive, rawFrameMs)) {\n\t\t\t\tapplyAdaptiveLevel();\n\t\t\t}\n\n\t\t\trafId = requestAnimationFrame(loop);\n\t\t}\n\n\t\tfunction startLoop() {\n\t\t\tif (running) return;\n\t\t\trunning = true;\n\t\t\tlastTime = performance.now();\n\t\t\trafId = requestAnimationFrame(loop);\n\t\t}\n\t\tfunction stopLoop() {\n\t\t\trunning = false;\n\t\t\tif (rafId) cancelAnimationFrame(rafId);\n\t\t\trafId = 0;\n\t\t}\n\n\t\t// --- pointer-driven launches -----------------------------------------\n\t\tfunction handlePointerDown(e: PointerEvent) {\n\t\t\tif (!sim) return;\n\t\t\tconst rect = canvas.getBoundingClientRect();\n\t\t\tif (rect.width <= 0 || rect.height <= 0) return;\n\t\t\tconst x = (e.clientX - rect.left) / rect.width;\n\t\t\tconst y = (e.clientY - rect.top) / rect.height;\n\t\t\tif (x < 0 || x > 1 || y < 0 || y > 1) return;\n\t\t\tsim.launch({\n\t\t\t\tapex: { x, y },\n\t\t\t\tshell: pickShell(),\n\t\t\t\tcolor: ambientColor(),\n\t\t\t\tintensity: \"ambient\",\n\t\t\t});\n\t\t}\n\n\t\tfunction handleVisibility() {\n\t\t\tif (document.hidden) stopLoop();\n\t\t\telse if (isVisible && !disposed && sim) startLoop();\n\t\t}\n\n\t\t// --- imperative handle (§1) ------------------------------------------\n\t\tfunction buildHandle(level: FireworksRenderLevel): FireworksHandle {\n\t\t\treturn {\n\t\t\t\tlaunch(o: LaunchOptions): LaunchResult {\n\t\t\t\t\tif (!sim) return { flightMs: 0, breakMs: 0 };\n\t\t\t\t\treturn sim.launch(o);\n\t\t\t\t},\n\t\t\t\tsetAmbient(on: boolean, intensity?: number) {\n\t\t\t\t\tambientOn = on && !prefersReduced;\n\t\t\t\t\tif (intensity !== undefined) ambientLevel = Math.max(0, Math.min(1, intensity));\n\t\t\t\t},\n\t\t\t\tsetKeepClear(rect: Rect | null) {\n\t\t\t\t\tkeepClear = rect;\n\t\t\t\t\t// Also drives the per-particle soft dim (AD §4.5) — apex sampling\n\t\t\t\t\t// alone only keeps burst origins clear, not drift-in trails/embers.\n\t\t\t\t\tsim?.setKeepClear(rect);\n\t\t\t\t},\n\t\t\t\tsetExposure(v: number) {\n\t\t\t\t\tcurrentExposure = clampExposure(v);\n\t\t\t\t},\n\t\t\t\trenderLevel: level,\n\t\t\t\tcleanup: teardown,\n\t\t\t};\n\t\t}\n\n\t\tfunction teardown() {\n\t\t\tdisposed = true;\n\t\t\tstopLoop();\n\t\t\tobserver?.disconnect();\n\t\t\tresizeObs?.disconnect();\n\t\t\tif (pointerBound) {\n\t\t\t\twindow.removeEventListener(\"pointerdown\", handlePointerDown);\n\t\t\t\tpointerBound = false;\n\t\t\t}\n\t\t\tdocument.removeEventListener(\"visibilitychange\", handleVisibility);\n\t\t\tcanvas.removeEventListener(\"webglcontextrestored\", onContextRestored);\n\t\t\tif (restoreTimer) window.clearTimeout(restoreTimer);\n\t\t\trestoreTimer = 0;\n\t\t\twired = false;\n\t\t\tengine?.destroy();\n\t\t\tengine = null;\n\t\t\tsim = null;\n\t\t\tinstances = null;\n\t\t}\n\n\t\t/** Drop the dead engine and its sim, keeping observers/listeners alive. */\n\t\tfunction releaseEngine() {\n\t\t\tstopLoop();\n\t\t\tengine?.destroy();\n\t\t\tengine = null;\n\t\t\tsim = null;\n\t\t\tinstances = null;\n\t\t}\n\n\t\tfunction giveUp() {\n\t\t\tif (disposed) return;\n\t\t\tteardown();\n\t\t\thandleLost();\n\t\t}\n\n\t\tasync function reboot() {\n\t\t\trecovering = true;\n\t\t\tlet revived = false;\n\t\t\ttry {\n\t\t\t\trevived = await boot();\n\t\t\t} catch (error) {\n\t\t\t\tif (isDev()) {\n\t\t\t\t\tconsole.warn(\"[FireworksHdr] engine reboot failed:\", error);\n\t\t\t\t}\n\t\t\t}\n\t\t\trecovering = false;\n\t\t\tif (!revived && !disposed) giveUp();\n\t\t}\n\n\t\tfunction onContextRestored() {\n\t\t\tif (restoreTimer) window.clearTimeout(restoreTimer);\n\t\t\trestoreTimer = 0;\n\t\t\tif (disposed) return;\n\t\t\tvoid reboot();\n\t\t}\n\n\t\t/**\n\t\t * A WebGPU device loss or a `webglcontextlost` leaves the engine dead: no\n\t\t * frame it draws lands. Reboot once (which also re-runs the WebGPU →\n\t\t * WebGL2 fallback), and if that fails tear the component down and report\n\t\t * it instead of leaving observers, listeners, and a handle wired to\n\t\t * nothing.\n\t\t */\n\t\tfunction handleEngineLoss() {\n\t\t\tif (disposed || recovering) return;\n\t\t\tconst wasWebgl = engine ? engine.renderLevel.startsWith(\"webgl\") : false;\n\t\t\treleaseEngine();\n\t\t\tif (recoveryUsed) {\n\t\t\t\tgiveUp();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\trecoveryUsed = true;\n\t\t\tif (wasWebgl) {\n\t\t\t\t// A lost WebGL context only vends a usable one again once the browser\n\t\t\t\t// fires webglcontextrestored — which it may never do.\n\t\t\t\trecovering = true;\n\t\t\t\tcanvas.addEventListener(\"webglcontextrestored\", onContextRestored, { once: true });\n\t\t\t\trestoreTimer = window.setTimeout(() => {\n\t\t\t\t\trestoreTimer = 0;\n\t\t\t\t\tcanvas.removeEventListener(\"webglcontextrestored\", onContextRestored);\n\t\t\t\t\trecovering = false;\n\t\t\t\t\tgiveUp();\n\t\t\t\t}, RESTORE_TIMEOUT_MS);\n\t\t\t} else {\n\t\t\t\t// WebGPU: a fresh device can be requested straight away.\n\t\t\t\tvoid reboot();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Wire the sim, observers, and listeners around a live engine and hand out\n\t\t * a handle. Shared by both the WebGPU and WebGL2 paths so the render level\n\t\t * flows through from whichever engine actually came up — and re-entrant,\n\t\t * so a post-loss reboot re-seats the sim without double-wiring the\n\t\t * observers and listeners it already owns.\n\t\t */\n\t\tfunction activate(eng: FireworksEngineHandle) {\n\t\t\tengine = eng;\n\t\t\tconst level = eng.renderLevel;\n\t\t\tconst minDim = Math.min(canvas.clientWidth, canvas.clientHeight);\n\t\t\tconst q = resolveQualityTier(qualityRef.current, level, currentDpr(), minDim, lowPower);\n\n\t\t\tsim = createSim({\n\t\t\t\tquality: q,\n\t\t\t\taspect: currentAspect(),\n\t\t\t\thdr: true,\n\t\t\t\tpalette: paletteRgb,\n\t\t\t});\n\t\t\tsim.setKeepClear(keepClear);\n\t\t\tinstances = new Float32Array(sim.capacity * 8);\n\n\t\t\tif (!wired) {\n\t\t\t\t// Observers: pause off-screen / when hidden; track aspect + resize.\n\t\t\t\tobserver = new IntersectionObserver(\n\t\t\t\t\t([entry]) => {\n\t\t\t\t\t\tisVisible = entry!.isIntersecting;\n\t\t\t\t\t\tif (isVisible && !document.hidden && !disposed) startLoop();\n\t\t\t\t\t\telse stopLoop();\n\t\t\t\t\t},\n\t\t\t\t\t{ threshold: 0 }\n\t\t\t\t);\n\t\t\t\tobserver.observe(canvas);\n\n\t\t\t\tresizeObs = new ResizeObserver(() => {\n\t\t\t\t\tupdateAspect();\n\t\t\t\t\tengine?.resizeIfNeeded();\n\t\t\t\t});\n\t\t\t\tresizeObs.observe(canvas);\n\n\t\t\t\tif (interactiveRef.current) {\n\t\t\t\t\twindow.addEventListener(\"pointerdown\", handlePointerDown);\n\t\t\t\t\tpointerBound = true;\n\t\t\t\t}\n\t\t\t\tdocument.addEventListener(\"visibilitychange\", handleVisibility);\n\t\t\t\twired = true;\n\t\t\t}\n\n\t\t\tupdateAspect();\n\t\t\tstartLoop();\n\t\t\t// Re-fired after a recovery: the level may have dropped to the WebGL2\n\t\t\t// fallback, and the caller needs a handle that says so.\n\t\t\thandleReady(buildHandle(level));\n\t\t}\n\n\t\t// --- boot the engine, then wire everything ---------------------------\n\t\t// WebGPU first (if present), then the WebGL2 fallback. Only if BOTH fail do\n\t\t// we stay silent — the app's own timeout then shows the static fallback\n\t\t// (renderLevel \"none\"). Resolves to whether an engine actually activated,\n\t\t// which is what the post-loss reboot decides on.\n\t\tasync function boot(): Promise<boolean> {\n\t\t\tlet eng: FireworksEngineHandle | null = null;\n\n\t\t\tif (typeof navigator !== \"undefined\" && \"gpu\" in navigator) {\n\t\t\t\teng = await startWebGpuFireworks(canvas, {\n\t\t\t\t\tmaxInstances: MAX_INSTANCES,\n\t\t\t\t\trenderScale: 1,\n\t\t\t\t\texposure: currentExposure,\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tif (isDev()) {\n\t\t\t\t\t\tconsole.warn(\"[FireworksHdr] WebGPU start failed:\", error);\n\t\t\t\t\t}\n\t\t\t\t\treturn null;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (disposed) {\n\t\t\t\teng?.destroy();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!eng) {\n\t\t\t\t// WebGL2 fallback. It only ever reports webgl-p3 / webgl-sdr, which\n\t\t\t\t// resolve to the same tier, so the tier is resolved up front to size\n\t\t\t\t// the instance buffer to the resolved tier (not high's 4096).\n\t\t\t\tconst minDim = Math.min(canvas.clientWidth, canvas.clientHeight);\n\t\t\t\tconst webglTier = resolveQualityTier(\n\t\t\t\t\tqualityRef.current,\n\t\t\t\t\t\"webgl-p3\",\n\t\t\t\t\tcurrentDpr(),\n\t\t\t\t\tminDim,\n\t\t\t\t\tlowPower\n\t\t\t\t);\n\t\t\t\teng = startWebGl2Fireworks(canvas, {\n\t\t\t\t\tmaxInstances: QUALITY[webglTier].maxParticles,\n\t\t\t\t\trenderScale: 1,\n\t\t\t\t\texposure: currentExposure,\n\t\t\t\t\thdr: true,\n\t\t\t\t});\n\t\t\t\tif (disposed) {\n\t\t\t\t\teng?.destroy();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Both paths exhausted: no GPU renderer. Stay silent (no onReady); the\n\t\t\t// app's timeout owns the static fallback.\n\t\t\tif (!eng) return false;\n\n\t\t\tactivate(eng);\n\t\t\treturn true;\n\t\t}\n\n\t\tif (hdr) {\n\t\t\tboot().catch((error) => {\n\t\t\t\tif (isDev()) {\n\t\t\t\t\tconsole.warn(\"[FireworksHdr] engine boot failed:\", error);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t});\n\t\t}\n\n\t\treturn teardown;\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, []);\n\n\treturn (\n\t\t<div\n\t\t\tclassName={cn(\"pointer-events-none absolute inset-0 h-full w-full\", className)}\n\t\t\taria-hidden=\"true\"\n\t\t>\n\t\t\t<canvas ref={canvasRef} className=\"block h-full w-full\" />\n\t\t</div>\n\t);\n}\n","type":"registry:ui","target":"@ui/fancy/components/fireworks-hdr/FireworksHdr.tsx"},{"path":"react/src/components/fireworks-hdr/dev.ts","content":"\"use client\";\n\n// Dev-only diagnostics gate.\n//\n// `process.env.NODE_ENV` is the one flag every React toolchain already\n// replaces statically, so it is read as that exact literal, inside try/catch:\n// where nothing rewrites it and no `process` exists the read throws, is caught,\n// and the gate reads false, the safe default for a published package. No\n// `typeof process` guard may sit in front: in a browser bundle it would\n// short-circuit before the rewritten literal is reached. `process` is declared\n// locally so no Node typings are needed.\n//\n// Read lazily, inside a function: nothing here may run at module scope, so the\n// value can never differ between a server render and its hydration.\ndeclare const process: { env: { NODE_ENV?: string } };\n\nexport function isDev(): boolean {\n\ttry {\n\t\treturn process.env.NODE_ENV !== \"production\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n","type":"registry:ui","target":"@ui/fancy/components/fireworks-hdr/dev.ts"},{"path":"react/src/components/fireworks-hdr/fireworks-shared.ts","content":"\"use client\";\n\n// Pure physics/animation core for FireworksHdr — DOM-free and GPU-free.\n//\n// Transcribes the frozen physics spec (§1–§7). Positions are normalized\n// [0,1] with a top-left, y-down origin. Velocities and accelerations are in\n// VISUAL units (screen-heights/sec, isotropic); aspect A = canvasW/canvasH is\n// applied only when integrating x (`pos.x += (vel.x / A) · dt`) and when\n// converting a normalized position error to visual units (seeker springs).\n//\n// Determinism invariant: everything reachable from `step()` derives its\n// randomness from stored per-particle seeds (hash-based value noise), never\n// `Math.random`. `Math.random` only ever appears behind an injectable `rng()`\n// used at spawn/schedule time (launch, ambient scheduling), so a fixed seed +\n// fixed rng reproduce a frame exactly. This is what makes the lib testable.\n\n// =============================================================================\n// §1 — Pool layout, field map, enums, public types\n// =============================================================================\n\n/** Floats per particle in the interleaved pool. */\nexport const STRIDE = 17;\n\n/** Field offsets inside one particle's STRIDE-float slot. */\nexport const F = {\n\tposX: 0,\n\tposY: 1,\n\tvelX: 2,\n\tvelY: 3,\n\tage: 4,\n\tttl: 5,\n\tsize: 6,\n\tr: 7,\n\tg: 8,\n\tb: 9,\n\tbrightness: 10,\n\ttype: 11,\n\tseed: 12,\n\ttargetX: 13,\n\ttargetY: 14,\n\tdragScale: 15,\n\t/**\n\t * Per-particle depth dim in (0,1] — the launch's `depth` folded into a\n\t * single multiplier applied to the resolved brightness every frame (§3.6).\n\t * Defaults to 1 for every spawn (see `appendParticle`), so only depth-aware\n\t * spawns need to write it.\n\t */\n\tdepthDim: 16,\n} as const;\n\nexport const TYPE = {\n\tROCKET: 0,\n\tSPARK: 1,\n\tEMBER: 2,\n\tSMOKE: 3,\n\tFLASH: 4,\n\tSEEKER: 5,\n} as const;\nexport type ParticleType = (typeof TYPE)[keyof typeof TYPE];\n\nexport interface Vec2 {\n\tx: number;\n\ty: number;\n}\n/** Linear RGB; channels may exceed 1.0 (HDR headroom). */\nexport interface Rgb {\n\tr: number;\n\tg: number;\n\tb: number;\n}\n\nexport type ShellKind = \"peony\" | \"willow\" | \"ring\" | \"glyph\" | \"heart\" | \"star\" | \"shape\";\nexport type Intensity = \"intro\" | \"ambient\";\nexport type QualityTier = \"high\" | \"mid\" | \"low\";\n\nexport interface LaunchOptions {\n\tapex: Vec2;\n\tfrom?: Vec2;\n\t/** @default 'peony' */\n\tshell?: ShellKind;\n\t/** Single hue or an adjacent duo; omitted → palette ping-pong sweep. */\n\tcolor?: Rgb | Rgb[];\n\t/** REQUIRED when `shell === 'glyph'`: normalized target points. */\n\tglyphPoints?: Vec2[];\n\t/**\n\t * REQUIRED when `shell === 'shape'`: the closed figure the burst is cut\n\t * from, as y-UP points around the origin. Scale is free — the outline is\n\t * normalized to the unit circle, then drawn at the shell's radius. Points are\n\t * walked in order and the figure is closed automatically, so a hand-written\n\t * polygon works as well as a sampled curve.\n\t */\n\tshapePoints?: Vec2[];\n\tscale?: number;\n\tflightMs?: number;\n\t/** @default 'ambient' */\n\tintensity?: Intensity;\n\t/** [0,1] — far shells render dimmer, smaller, less saturated. */\n\tdepth?: number;\n\tseed?: number;\n\t/** Glyph only: sim self-triggers seeker release at this time (ms after launch). */\n\treleaseAtMs?: number;\n}\n\nexport interface LaunchResult {\n\tflightMs: number;\n\t/** flightMs + fuse-hang; when the shell detonates. */\n\tbreakMs: number;\n}\n\n/**\n * How the fireworks are actually being rendered (sampled once at handle\n * creation; does not follow the window to another display):\n * - \"webgpu-hdr\": WebGPU with extended tone mapping active AND a display\n *   reporting `(dynamic-range: high)` — true brighter-than-white output.\n * - \"webgpu-sdr\": WebGPU float16 + P3, but the browser clamped tone mapping or\n *   the display is SDR.\n * - \"webgl-p3\":  WebGL2 fallback with a display-p3 drawing buffer.\n * - \"webgl-sdr\": WebGL2 fallback, plain sRGB.\n * - \"none\":      no GPU rendering available; the component never fires onReady.\n */\nexport type FireworksRenderLevel = \"webgpu-hdr\" | \"webgpu-sdr\" | \"webgl-p3\" | \"webgl-sdr\" | \"none\";\n\n/**\n * Imperative control surface handed to `FireworksHdr`'s `onReady` callback\n * (§1). Coordinates are normalized [0,1], top-left origin.\n */\nexport interface FireworksHandle {\n\t/** Fire a shell; returns the resolved flight/break timing. */\n\tlaunch(opts: LaunchOptions): LaunchResult;\n\t/** Toggle the ambient auto-scheduler; optionally set its intensity [0,1]. */\n\tsetAmbient(on: boolean, intensity?: number): void;\n\t/** Set (or clear) the keep-clear rect ambient apexes must avoid. */\n\tsetKeepClear(rect: Rect | null): void;\n\t/** Set the display exposure multiplier (clamped [1,4] by the renderer). */\n\tsetExposure(v: number): void;\n\treadonly renderLevel: FireworksRenderLevel;\n\t/** Stop the loop, remove listeners, and release GPU resources. */\n\tcleanup(): void;\n}\n\nexport interface Zone {\n\trect: Rect;\n\tweight: number;\n}\nexport interface Rect {\n\tx0: number;\n\ty0: number;\n\tx1: number;\n\ty1: number;\n}\n\nexport interface TierSpec {\n\tmaxParticles: number;\n\ttrailRate: number;\n}\nexport interface ShellRecipe {\n\tcounts: Record<QualityTier, number>;\n\temberFrac: number;\n\tsmoke: number;\n\tradius: [number, number];\n\tbuilder: BurstBuilderKind;\n\t/**\n\t * Pattern shells only: the unit outline the burst is cut from, sampled at\n\t * `t ∈ [0,1)`. Points are y-UP and bounded by the unit circle; the burst\n\t * converts to the sim's y-down convention.\n\t */\n\toutline?: Outline;\n\t/**\n\t * Pattern shells hold a readable figure, so they suppress the break\n\t * asymmetry, the stragglers and most of the embers that would smear it.\n\t */\n\tcrisp?: boolean;\n}\ntype BurstBuilderKind = \"sphere\" | \"willow\" | \"ring\" | \"glyph\" | \"outline\";\n\n/** A closed unit figure: `t ∈ [0,1)` → point, y-up, `|p| ≤ 1`. */\nexport type Outline = (t: number) => Vec2;\n\nexport interface Sim {\n\tlaunch(opts: LaunchOptions): LaunchResult;\n\tspawnFlash(pos: Vec2, brightness: number, sizeNorm: number, hue: Rgb): void;\n\t/** Advances the simulation; `dt` is clamped to DT_MAX internally. */\n\tstep(dtSeconds: number, wind?: Vec2): void;\n\t/** Writes 8-float instances into `out`; returns the live instance count. */\n\twriteInstances(out: Float32Array): number;\n\tsetAspect(aspect: number): void;\n\t/**\n\t * Set (or clear) the keep-clear rect. Detonation apexes are the scheduler's\n\t * job to steer away; here it only soft-dims stray particles (§4.5) that drift\n\t * inside so the area behind the card stays calm.\n\t */\n\tsetKeepClear(rect: Rect | null): void;\n\t/**\n\t * Scale new burst particle counts (spawn density) in [0,1]. The adaptive\n\t * downgrade uses this as its pop-free CPU lever; glyph seekers are driven by\n\t * explicit points and are never scaled. Default 1 (no change).\n\t */\n\tsetSpawnScale(scale: number): void;\n\treset(): void;\n\treadonly count: number;\n\treadonly capacity: number;\n\treadonly droppedSpawns: number;\n\t/** Interleaved pool, read-only view (first `count · STRIDE` floats live). */\n\treadonly data: Float32Array;\n}\n\nexport interface SimOptions {\n\tquality: QualityTier;\n\taspect: number;\n\thdr: boolean;\n\t/** Injectable spawn/schedule randomness; defaults to Math.random. */\n\trng?: () => number;\n\twind?: Vec2;\n\t/** Linear-RGB palette (ping-pong order); defaults to PALETTE. */\n\tpalette?: Rgb[];\n}\n\n// =============================================================================\n// §2 — Constants\n// =============================================================================\n\n// §2.1 World\nexport const G = 3.6; // visual gravity, +y down\nexport const DT_MAX = 0.033;\nexport const LAUNCH_Y: [number, number] = [1.02, 1.08];\nexport const LAUNCH_X: [number, number] = [0.08, 0.92];\n\n// §2.4 Render/exposure\nexport const EXPOSURE_AMBIENT = 2.2;\nexport const EXPOSURE_INTRO = 2.6;\nexport const SDR_KNEE_START = 0.8;\nexport const SDR_CORE_SCALE = 1.4;\nexport const SDR_SAT_BOOST = 0.12;\n\n// §7 instance velocity-stretch (seconds of motion baked into the quad's major\n// axis). Small on purpose — the accumulation trail already conveys motion, and\n// stacking a long stretch on top of it turns every spark into a needle.\nexport const STRETCH = 0.01;\n\n// §2.3 Brightness ladder (pre-exposure; 1.0 = SDR white)\nexport const B_FLASH_INTRO = 3.4;\nexport const B_FLASH_AMBIENT = 2.1;\nexport const B_SPARK_FRESH = 2.2;\nexport const B_SPARK_STEADY = 0.9;\nexport const B_SPARK_TERMINAL = 0.15;\nexport const B_ASCENT_HEAD = 2.8;\nexport const B_ASCENT_TAIL = 0.45;\nexport const B_BURST_STREAK = 0.5;\nexport const B_EMBER_MEAN = 0.35;\nexport const B_SMOKE_MIN = 0.05;\nexport const B_SMOKE_MAX = 0.12;\nexport const B_GLYPH_HOLD = 1.3;\nexport const B_GLYPH_RELEASE = 2.6;\nexport const B_HAZE_CEIL = 0.18;\nexport const CRACKLE_HZ = 24;\n\n// §2.5 Palette (ping-pong index order: cyan, blue, violet, magenta)\nexport const PALETTE_HEX = [\"#42cfff\", \"#3d5bff\", \"#a142ff\", \"#ff2fd6\"] as const;\nexport const COOL_END_HEX = \"#ffcf9c\";\nexport const MAGNESIUM_HEX = \"#f4f8ff\";\nexport const COMET_HEAD_HEX = \"#fff2e0\";\nexport const SMOKE_HEX = \"#0a0b10\";\n\n// Shell hue jitter (oklab degrees) and spark hue jitter — §2.5 / §1.6\nexport const SHELL_JITTER_DEG = 7;\nexport const SPARK_JITTER_DEG = 3;\n\n// Ascent wobble (§4): lateral drift rate and its frequency. Applied to the\n// rocket's position only — the velocity, and therefore the solved apex, is\n// untouched, so the wobble cannot walk a shell off its target.\nexport const ROCKET_WOBBLE_AMP = 0.045;\nexport const ROCKET_WOBBLE_HZ = 11;\n\n// Spark life-color schedule (§1.7): white → shell hue → cool end.\nexport const HUE_ARRIVES_AT = 0.34;\nexport const COOL_START = 0.72;\n// Share of a shell's sparks that crackle — a fast on/off flicker (CRACKLE_HZ)\n// on top of the normal decay. This is the \"silver\" chatter of a real break.\nexport const CRACKLE_FRAC = 0.06;\n\n// Depth response for `depth ∈ [0,1]`: a far shell is dimmer, smaller, less\n// saturated AND spatially tighter. Every term is applied at spawn (the dim as a\n// per-particle multiplier on the brightness curve) so the same shell reads as\n// \"further back\" on all of its debris — sparks, embers, smoke, flash, glyph.\nexport const DEPTH_DIM = 0.45; // brightness ×(1 − 0.45·d)\nexport const DEPTH_SIZE = 0.5; // particle size ×(1 − 0.5·d)\nexport const DEPTH_CHROMA = 0.35; // saturation ×(1 − 0.35·d)\nexport const DEPTH_RADIUS = 0.25; // burst radius ×(1 − 0.25·d)\n\n// §2.6 Wind: session vector magnitudes (visual accel)\nconst WIND_X: [number, number] = [0.02, 0.05];\nconst WIND_Y: [number, number] = [0.01, 0.02];\n\n// Per-type wind scale (§2.2 windScale column)\nconst WIND_SCALE: Record<ParticleType, number> = {\n\t[TYPE.ROCKET]: 0.05,\n\t[TYPE.SPARK]: 0.3,\n\t[TYPE.EMBER]: 0.7,\n\t[TYPE.SMOKE]: 1.0,\n\t[TYPE.FLASH]: 0,\n\t[TYPE.SEEKER]: 0.4,\n};\n\n// Per-type gravity scale (§2.2 gravScale column). Sparks and embers fall at a\n// small fraction of the rocket's gravity: at full G their terminal velocity\n// (g·G/drag) dwarfs the burst's own expansion speed, so a shell never opens\n// into a sphere — it rains straight down as a fountain. Keeping ember gravity\n// above spark gravity is what still separates a willow's droop from a peony.\nconst GRAV_SCALE: Record<ParticleType, number> = {\n\t[TYPE.ROCKET]: 1.0,\n\t[TYPE.SPARK]: 0.15,\n\t[TYPE.EMBER]: 0.3,\n\t[TYPE.SMOKE]: -0.05,\n\t[TYPE.FLASH]: 0,\n\t[TYPE.SEEKER]: 0, // gravity is phase-driven for seekers\n};\n\n// Per-type drag (1/s, §2.2 drag column)\nconst DRAG: Record<ParticleType, number> = {\n\t[TYPE.ROCKET]: 0.6,\n\t[TYPE.SPARK]: 2.2,\n\t[TYPE.EMBER]: 2.4,\n\t[TYPE.SMOKE]: 3.0,\n\t[TYPE.FLASH]: 0,\n\t[TYPE.SEEKER]: 1.2,\n};\n\n// Burst initial speed = radius · this (visual units). Under linear drag a spark\n// coasts v0/drag, so k ≈ drag makes the shell open to about its nominal radius\n// before the droop takes over. Not spec-pinned — a visual constant.\nconst BURST_SPEED_K = 3.0;\n\n// §3 Quality tiers\nexport const QUALITY: Record<QualityTier, TierSpec> = {\n\thigh: { maxParticles: 4096, trailRate: 180 },\n\tmid: { maxParticles: 2560, trailRate: 120 },\n\tlow: { maxParticles: 1280, trailRate: 60 },\n};\n\n// §3 Shell recipes\nexport const SHELL: Record<ShellKind, ShellRecipe> = {\n\tpeony: {\n\t\tcounts: { high: 320, mid: 200, low: 120 },\n\t\temberFrac: 0.15,\n\t\tsmoke: 1,\n\t\tradius: [0.1, 0.2],\n\t\tbuilder: \"sphere\",\n\t},\n\twillow: {\n\t\tcounts: { high: 200, mid: 130, low: 80 },\n\t\temberFrac: 0.8,\n\t\tsmoke: 1,\n\t\tradius: [0.14, 0.22],\n\t\tbuilder: \"willow\",\n\t},\n\tring: {\n\t\tcounts: { high: 180, mid: 120, low: 70 },\n\t\temberFrac: 0.1,\n\t\tsmoke: 0,\n\t\tradius: [0.12, 0.2],\n\t\tbuilder: \"ring\",\n\t},\n\tglyph: {\n\t\tcounts: { high: 0, mid: 0, low: 0 }, // driven by glyphPoints + garnish\n\t\temberFrac: 0,\n\t\tsmoke: 1,\n\t\tradius: [0.14, 0.14],\n\t\tbuilder: \"glyph\",\n\t},\n\t// Pattern shells: the figure IS the shell, so they run denser than a peony of\n\t// the same radius (an outline needs particles per unit of arc, not per unit of\n\t// volume) and suppress everything that would blur it.\n\theart: {\n\t\tcounts: { high: 260, mid: 170, low: 100 },\n\t\temberFrac: 0.05,\n\t\tsmoke: 1,\n\t\tradius: [0.13, 0.2],\n\t\tbuilder: \"outline\",\n\t\toutline: heartOutline,\n\t\tcrisp: true,\n\t},\n\tstar: {\n\t\tcounts: { high: 240, mid: 160, low: 95 },\n\t\temberFrac: 0.05,\n\t\tsmoke: 1,\n\t\tradius: [0.13, 0.2],\n\t\tbuilder: \"outline\",\n\t\toutline: starOutline(5, 0.45),\n\t\tcrisp: true,\n\t},\n\t// Caller-supplied figure — see LaunchOptions.shapePoints.\n\tshape: {\n\t\tcounts: { high: 260, mid: 170, low: 100 },\n\t\temberFrac: 0.05,\n\t\tsmoke: 1,\n\t\tradius: [0.13, 0.2],\n\t\tbuilder: \"outline\",\n\t\tcrisp: true,\n\t},\n};\n\n// §4.4 Ambient burst radius ceiling (fraction of min-dim). Distinct from the\n// larger \"feature\" band (0.24) reserved for non-ambient bursts — the ambient\n// scheduler derives its own scale per shell to respect this at any intensity.\nexport const AMBIENT_RADIUS_MAX = 0.2;\n\n// §4.2 Ambient apex zones (weights sum to 1.0)\nexport const AMBIENT_ZONES: Zone[] = [\n\t{ rect: { x0: 0.04, y0: 0.08, x1: 0.34, y1: 0.4 }, weight: 0.28 }, // UL\n\t{ rect: { x0: 0.66, y0: 0.08, x1: 0.96, y1: 0.4 }, weight: 0.28 }, // UR\n\t{ rect: { x0: 0.34, y0: 0.05, x1: 0.66, y1: 0.24 }, weight: 0.18 }, // TC\n\t{ rect: { x0: 0.02, y0: 0.34, x1: 0.2, y1: 0.62 }, weight: 0.13 }, // LM\n\t{ rect: { x0: 0.8, y0: 0.34, x1: 0.98, y1: 0.62 }, weight: 0.13 }, // RM\n];\n\n// §4.5 Keep-clear rects (desktop / mobile) — the card area apexes must avoid.\nexport const KEEP_CLEAR_DESKTOP: Rect = { x0: 0.28, y0: 0.3, x1: 0.72, y1: 0.82 };\nexport const KEEP_CLEAR_MOBILE: Rect = { x0: 0.1, y0: 0.22, x1: 0.9, y1: 0.9 };\n\n// §4.5 soft dim — brightness multiplier for stray particles that drift behind\n// the keep-clear card. Apexes are hard-rejected there, so this only ever bites\n// drift-ins (embers, smoke, spent sparks, rocket trails), keeping the haze\n// behind the card under the §4.6 ceiling.\nexport const KEEP_CLEAR_DIM = 0.35;\n\n// =============================================================================\n// §2.7 — Deterministic value noise\n// =============================================================================\n\n/** Sign-stable fract; matches the WGSL `fract`. */\nfunction fract(x: number): number {\n\treturn x - Math.floor(x);\n}\n\n/** hash11(x) = fract(sin(x·127.1)·43758.5453) — deterministic scalar hash. */\nexport function hash11(x: number): number {\n\treturn fract(Math.sin(x * 127.1) * 43758.5453);\n}\n\n/**\n * 1-D value noise in [0,1). Smooth-interpolated hash lattice sampled at\n * `age·freq`, offset by `seed`. Deterministic per (seed, age, freq).\n */\nexport function flickerNoise(seed: number, ageSec: number, freqHz: number): number {\n\tconst t = ageSec * freqHz;\n\tconst i = Math.floor(t);\n\tconst f = t - i;\n\tconst a = hash11(seed + i);\n\tconst b = hash11(seed + i + 1);\n\tconst u = f * f * (3 - 2 * f);\n\treturn a + (b - a) * u;\n}\n\n/** smoothstep with edge0 possibly > edge1 (used by the death gate). */\nexport function smoothstep(edge0: number, edge1: number, x: number): number {\n\tconst t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));\n\treturn t * t * (3 - 2 * t);\n}\n\n/**\n * Last-10%-of-life brightness gate (§2.1 / §3.6). Equals 1 up to lifeT 0.9,\n * eases to 0 at lifeT 1.0 — so a particle's brightness reaches 0 exactly when\n * it is removed, honoring \"nothing removed at nonzero brightness\".\n */\nexport function deathGate(lifeT: number): number {\n\treturn smoothstep(1.0, 0.9, lifeT);\n}\n\n// =============================================================================\n// Color: sRGB ↔ linear ↔ oklab, hue rotation, life ramps\n// =============================================================================\n\nfunction srgbToLinear(c: number): number {\n\treturn c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n}\nfunction linearToSrgb(c: number): number {\n\tconst x = Math.max(0, c);\n\treturn x <= 0.0031308 ? x * 12.92 : 1.055 * Math.pow(x, 1 / 2.4) - 0.055;\n}\n\n/** Parse `#rrggbb` to linear RGB. Falls back to white on malformed input. */\nexport function hexToLinearRgb(hex: string): Rgb {\n\tconst m = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n\tif (!m) return { r: 1, g: 1, b: 1 };\n\treturn {\n\t\tr: srgbToLinear(parseInt(m[1]!, 16) / 255),\n\t\tg: srgbToLinear(parseInt(m[2]!, 16) / 255),\n\t\tb: srgbToLinear(parseInt(m[3]!, 16) / 255),\n\t};\n}\n\ninterface Oklab {\n\tL: number;\n\ta: number;\n\tb: number;\n}\n\n// Alloc-free scratch for the color math. The hot path (writeInstances →\n// displayColor) reuses `*Into` variants so no oklab/RGB objects are minted per\n// particle per frame; the exported pure functions below delegate to the same\n// code so there is one arithmetic source of truth (determinism-preserving).\n// Safe as module-level singletons: the sim is single-threaded and one\n// writeInstances call fully unwinds before the next, so no two conversions are\n// ever in flight at once.\nconst _okA: Oklab = { L: 0, a: 0, b: 0 };\nconst _okB: Oklab = { L: 0, a: 0, b: 0 };\nconst _okMix: Oklab = { L: 0, a: 0, b: 0 };\nconst _sparkHue: Rgb = { r: 0, g: 0, b: 0 };\n\n/** Linear RGB → oklab, into `out` (no allocation). */\nfunction linearToOklabInto(c: Rgb, out: Oklab): void {\n\tconst l = 0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b;\n\tconst m = 0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b;\n\tconst s = 0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b;\n\tconst l_ = Math.cbrt(l);\n\tconst m_ = Math.cbrt(m);\n\tconst s_ = Math.cbrt(s);\n\tout.L = 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_;\n\tout.a = 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_;\n\tout.b = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_;\n}\n\n/** oklab → linear RGB, into `out` (no allocation). */\nfunction oklabToLinearInto(o: Oklab, out: Rgb): void {\n\tconst l_ = o.L + 0.3963377774 * o.a + 0.2158037573 * o.b;\n\tconst m_ = o.L - 0.1055613458 * o.a - 0.0638541728 * o.b;\n\tconst s_ = o.L - 0.0894841775 * o.a - 1.291485548 * o.b;\n\tconst l = l_ * l_ * l_;\n\tconst m = m_ * m_ * m_;\n\tconst s = s_ * s_ * s_;\n\tout.r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s;\n\tout.g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s;\n\tout.b = -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s;\n}\n\n/** hueRotate into `out` (no allocation). `out` may not alias `c`. */\nfunction hueRotateInto(c: Rgb, deg: number, out: Rgb): void {\n\tlinearToOklabInto(c, _okA);\n\tconst chroma = Math.hypot(_okA.a, _okA.b);\n\tconst h = Math.atan2(_okA.b, _okA.a) + (deg * Math.PI) / 180;\n\t_okMix.L = _okA.L;\n\t_okMix.a = chroma * Math.cos(h);\n\t_okMix.b = chroma * Math.sin(h);\n\toklabToLinearInto(_okMix, out);\n}\n\n/** mixOklab into `out` (no allocation). `out` may not alias `a` or `b`. */\nfunction mixOklabInto(a: Rgb, b: Rgb, t: number, out: Rgb): void {\n\tlinearToOklabInto(a, _okA);\n\tlinearToOklabInto(b, _okB);\n\t_okMix.L = _okA.L + (_okB.L - _okA.L) * t;\n\t_okMix.a = _okA.a + (_okB.a - _okA.a) * t;\n\t_okMix.b = _okA.b + (_okB.b - _okA.b) * t;\n\toklabToLinearInto(_okMix, out);\n}\n\n/** Linear RGB → oklab. */\nexport function linearToOklab(c: Rgb): Oklab {\n\tconst out: Oklab = { L: 0, a: 0, b: 0 };\n\tlinearToOklabInto(c, out);\n\treturn out;\n}\n\n/** oklab → linear RGB (may return negative channels for out-of-gamut hues). */\nexport function oklabToLinear(o: Oklab): Rgb {\n\tconst out: Rgb = { r: 0, g: 0, b: 0 };\n\toklabToLinearInto(o, out);\n\treturn out;\n}\n\n/** Rotate a linear-RGB color's oklab hue by `deg` degrees (chroma preserved). */\nexport function hueRotate(c: Rgb, deg: number): Rgb {\n\tconst out: Rgb = { r: 0, g: 0, b: 0 };\n\thueRotateInto(c, deg, out);\n\treturn out;\n}\n\n/** Scale a color's oklab chroma by `k` (desaturate when k<1). */\nfunction scaleChroma(c: Rgb, k: number): Rgb {\n\tconst o = linearToOklab(c);\n\treturn oklabToLinear({ L: o.L, a: o.a * k, b: o.b * k });\n}\n\n/** Perceptual mix of two linear-RGB colors in oklab. */\nexport function mixOklab(a: Rgb, b: Rgb, t: number): Rgb {\n\tconst out: Rgb = { r: 0, g: 0, b: 0 };\n\tmixOklabInto(a, b, t, out);\n\treturn out;\n}\n\n/** sparkColorAtLife into `out` (no allocation). `out` may not alias `shellHue`. */\nfunction sparkColorAtLifeInto(\n\tshellHue: Rgb,\n\tlifeT: number,\n\twhiteHold: number,\n\tseed: number,\n\tout: Rgb\n): void {\n\thueRotateInto(shellHue, (hash11(seed) * 2 - 1) * SPARK_JITTER_DEG, _sparkHue);\n\tif (lifeT <= whiteHold) {\n\t\tout.r = MAGNESIUM.r;\n\t\tout.g = MAGNESIUM.g;\n\t\tout.b = MAGNESIUM.b;\n\t\treturn;\n\t}\n\t// The magnesium flash reads as the detonation, not as the shell: it has to\n\t// hand over to the shell hue early (by ~a third of the life) or a burst is\n\t// a white ball for most of the time anyone is looking at it.\n\tif (lifeT < HUE_ARRIVES_AT) {\n\t\tconst t = (lifeT - whiteHold) / (HUE_ARRIVES_AT - whiteHold);\n\t\tmixOklabInto(MAGNESIUM, _sparkHue, Math.min(1, t), out);\n\t\treturn;\n\t}\n\tif (lifeT < COOL_START) {\n\t\tout.r = _sparkHue.r;\n\t\tout.g = _sparkHue.g;\n\t\tout.b = _sparkHue.b;\n\t\treturn;\n\t}\n\tconst t = (lifeT - COOL_START) / (1 - COOL_START);\n\tmixOklabInto(_sparkHue, COOL_END, Math.min(1, t), out);\n}\n\n// Resolved palette constants (linear).\nexport const PALETTE: Rgb[] = PALETTE_HEX.map(hexToLinearRgb);\nconst COOL_END = hexToLinearRgb(COOL_END_HEX);\nconst MAGNESIUM = hexToLinearRgb(MAGNESIUM_HEX);\nconst COMET_HEAD = hexToLinearRgb(COMET_HEAD_HEX);\nconst SMOKE_COLOR = hexToLinearRgb(SMOKE_HEX);\n// How far the ascent trail is pulled from the comet head toward the shell hue.\n// The blend is done once per launch (stored on the spec) so emitTrail never\n// re-mixes (3 oklab allocations) per emitted spark, and a branded palette gets\n// its own trail instead of the built-in cyan.\nexport const COMET_TRAIL_MIX = 0.25;\n// Fallback tint for a trail whose launch spec is already gone (the rocket\n// outlived its detonation record) — the built-in palette's cool end.\nconst COMET_TRAIL_HUE = mixOklab(COMET_HEAD, PALETTE[0]!, COMET_TRAIL_MIX);\n\n// =============================================================================\n// §1 pure helpers — kinematics, bursts, spring, hue sweep, scheduling\n// =============================================================================\n\n/**\n * The medium a solved launch actually flies through. Omit it (or pass zeroed\n * fields) for the textbook undamped, square-canvas trajectory; pass the sim's\n * own numbers and the solve inverts the SAME model `integrate` applies, so the\n * shell really peaks at `apex` instead of undershooting by the drag it was\n * never told about.\n */\nexport interface LaunchMedium {\n\t/** Linear drag on the rocket (1/s) — `DRAG[TYPE.ROCKET]`. 0 → ballistic. */\n\tdrag?: number;\n\t/** Canvas aspect W/H; x integrates as `pos.x += (vel.x / A) · dt`. */\n\taspect?: number;\n\t/** Horizontal wind accel, already scaled by the rocket's windScale. */\n\twindX?: number;\n\t/** Vertical wind accel (+y down), already scaled by the rocket's windScale. */\n\twindY?: number;\n}\n\n/** Rise height reached by an up-velocity `vu0` under gravity `g` and drag `k`. */\nfunction riseUnderDrag(vu0: number, g: number, k: number): number {\n\treturn vu0 / k - (g / (k * k)) * Math.log(1 + (k * vu0) / g);\n}\n\n/**\n * Solve a rocket's launch velocity (§4). With `flightMs` the timing wins\n * (vy = 0 exactly at flight, apex.y only targets x); without it the flight is\n * derived so the trajectory peaks at apex.y.\n *\n * `medium` makes the solve match the integrator: with drag `k` the vertical\n * motion is `vu(t) = (vu0 + g/k)·e^(−kt) − g/k` (apex where that hits 0) and\n * the horizontal one integrates to `(vx0 − ax/k)(1 − e^(−kt))/k + (ax/k)·t`,\n * divided by the aspect. Without it both collapse to the undamped forms.\n */\nexport function solveLaunch(\n\tfrom: Vec2,\n\tapex: Vec2,\n\tg: number,\n\tflightMs?: number,\n\tmedium?: LaunchMedium\n): { v0: Vec2; flightMs: number } {\n\tconst k = medium?.drag ?? 0;\n\tconst aspect = medium?.aspect ?? 1;\n\tconst ax = medium?.windX ?? 0;\n\t// Wind on y is a constant accel, so it just shifts effective gravity.\n\tconst gEff = Math.max(1e-4, g + (medium?.windY ?? 0));\n\tconst dy = Math.max(0, from.y - apex.y);\n\tconst dx = (apex.x - from.x) * aspect;\n\n\tif (k <= 0) {\n\t\tconst fs = flightMs !== undefined ? flightMs / 1000 : Math.sqrt((2 * dy) / gEff);\n\t\tconst safeFs = fs > 1e-4 ? fs : 1e-4;\n\t\t// Δx = vx0·t + ½·ax·t² → vx0 = Δx/t − ½·ax·t.\n\t\treturn {\n\t\t\tv0: { x: dx / safeFs - 0.5 * ax * safeFs, y: -gEff * fs },\n\t\t\tflightMs: fs * 1000,\n\t\t};\n\t}\n\n\tlet vu0: number;\n\tlet fs: number;\n\tif (flightMs !== undefined) {\n\t\tfs = flightMs / 1000;\n\t\t// vu(t) = 0 at t = fs  ⇒  vu0 = (g/k)·(e^(k·fs) − 1).\n\t\tvu0 = (gEff / k) * (Math.exp(k * Math.max(0, fs)) - 1);\n\t} else {\n\t\t// Invert rise(vu0) = dy by Newton (monotonic; rise' = vu0/(g + k·vu0)),\n\t\t// seeded with the undamped answer — converges in a handful of steps.\n\t\tvu0 = Math.sqrt(2 * gEff * dy);\n\t\tfor (let i = 0; i < 12; i++) {\n\t\t\tconst err = riseUnderDrag(vu0, gEff, k) - dy;\n\t\t\tconst slope = vu0 / (gEff + k * vu0);\n\t\t\tif (Math.abs(err) < 1e-9 || slope <= 0) break;\n\t\t\tvu0 = Math.max(0, vu0 - err / slope);\n\t\t}\n\t\tfs = (1 / k) * Math.log(1 + (k * vu0) / gEff);\n\t}\n\n\tconst safeFs = fs > 1e-4 ? fs : 1e-4;\n\t// Δx = (ax/k)·t + (vx0 − ax/k)·(1 − e^(−k·t))/k → solve for vx0.\n\tconst decay = 1 - Math.exp(-k * safeFs);\n\tconst drift = ax / k;\n\tconst vx0 = drift + ((dx - drift * safeFs) * k) / decay;\n\treturn { v0: { x: vx0, y: -vu0 }, flightMs: fs * 1000 };\n}\n\n/** Gravity that makes a launch from `from` peak at `apex.y` in `flightSec`. */\nexport function solveGravity(from: Vec2, apex: Vec2, flightSec: number): number {\n\treturn (2 * (from.y - apex.y)) / (flightSec * flightSec);\n}\n\nexport interface BurstDir {\n\tdir: Vec2;\n\tz: number;\n}\n\n/** Fibonacci-sphere burst (peony). `dir` is the in-plane projection, `z` depth. */\nexport function sphereBurst(n: number, seed: number): BurstDir[] {\n\tconst out: BurstDir[] = [];\n\tconst golden = Math.PI * (3 - Math.sqrt(5));\n\tconst phi0 = hash11(seed) * Math.PI * 2;\n\tfor (let i = 0; i < n; i++) {\n\t\tconst z = 1 - (2 * (i + 0.5)) / n;\n\t\tconst r = Math.sqrt(Math.max(0, 1 - z * z));\n\t\tconst phi = phi0 + i * golden;\n\t\tout.push({ dir: { x: r * Math.cos(phi), y: r * Math.sin(phi) }, z });\n\t}\n\treturn out;\n}\n\n/** Even ring of unit in-plane directions with a slight per-seed tilt (ring shell). */\nexport function ringBurst(n: number, seed: number): BurstDir[] {\n\tconst out: BurstDir[] = [];\n\tconst a0 = hash11(seed) * Math.PI * 2;\n\tconst tilt = 0.03 * (hash11(seed + 1) * 2 - 1);\n\tfor (let i = 0; i < n; i++) {\n\t\tconst a = a0 + (i / n) * Math.PI * 2;\n\t\tout.push({ dir: { x: Math.cos(a), y: Math.sin(a) }, z: tilt * Math.cos(a) });\n\t}\n\treturn out;\n}\n\n/**\n * Classic heart curve, normalized into the unit circle and y-up.\n * `x = 16sin³t`, `y = 13cos t − 5cos 2t − 2cos 3t − cos 4t` — the 17 divisor is\n * the curve's own extent, so the figure fills the shell radius without clipping.\n */\nexport function heartOutline(t: number): Vec2 {\n\tconst a = t * Math.PI * 2;\n\tconst s = Math.sin(a);\n\treturn {\n\t\tx: (16 * s * s * s) / 17,\n\t\ty: (13 * Math.cos(a) - 5 * Math.cos(2 * a) - 2 * Math.cos(3 * a) - Math.cos(4 * a)) / 17,\n\t};\n}\n\n/**\n * A `points`-pointed star walked along its edges (not just its vertices), so a\n * sparse particle count still draws the figure rather than a scatter of tips.\n * `inner` is the valley radius as a fraction of the tip radius.\n */\nexport function starOutline(points = 5, inner = 0.45): Outline {\n\tconst verts = points * 2;\n\treturn (t: number): Vec2 => {\n\t\tconst u = ((t % 1) + 1) % 1;\n\t\tconst scaled = u * verts;\n\t\tconst i = Math.floor(scaled);\n\t\tconst f = scaled - i;\n\t\tconst radiusAt = (k: number) => (k % 2 === 0 ? 1 : inner);\n\t\t// Vertices start at the top (−π/2 in y-up math) so a star sits point-up.\n\t\tconst angleAt = (k: number) => (k / verts) * Math.PI * 2 + Math.PI / 2;\n\t\tconst a0 = angleAt(i);\n\t\tconst a1 = angleAt(i + 1);\n\t\tconst r0 = radiusAt(i);\n\t\tconst r1 = radiusAt(i + 1);\n\t\tconst x0 = Math.cos(a0) * r0;\n\t\tconst y0 = Math.sin(a0) * r0;\n\t\tconst x1 = Math.cos(a1) * r1;\n\t\tconst y1 = Math.sin(a1) * r1;\n\t\treturn { x: lerp(x0, x1, f), y: lerp(y0, y1, f) };\n\t};\n}\n\n/**\n * Cut a burst from a closed unit figure (§3.7). Each direction keeps the\n * outline point's own magnitude, so the spawn speed is proportional to its\n * distance from the centre — under linear drag every spark coasts `v0/drag`,\n * which is what redraws the figure in the sky at `radius` scale.\n *\n * Points are y-up going in and y-down coming out, matching the sim.\n */\nexport function outlineBurst(n: number, seed: number, outline: Outline, jitter = 0.06): BurstDir[] {\n\tconst out: BurstDir[] = [];\n\tconst phase = hash11(seed) * 0.5;\n\tfor (let i = 0; i < n; i++) {\n\t\t// Half-step stagger keeps consecutive shells from sampling identically.\n\t\tconst t = (i + phase) / n;\n\t\tconst p = outline(t);\n\t\t// Radial jitter only — lateral jitter would fray the outline.\n\t\tconst j = 1 + (hash11(seed + i * 1.7) * 2 - 1) * jitter;\n\t\tout.push({\n\t\t\tdir: { x: p.x * j, y: -p.y * j },\n\t\t\t// A figure is a plane facing the viewer: keep z shallow so the burst\n\t\t\t// reads flat rather than as a sphere wearing the outline.\n\t\t\tz: (hash11(seed + i + 401) * 2 - 1) * 0.12,\n\t\t});\n\t}\n\treturn out;\n}\n\n/**\n * Turn caller points into an {@link Outline}: normalized to the unit circle\n * about their own centroid and walked as a closed polygon, so both a sampled\n * curve and a hand-written polygon draw correctly.\n */\nexport function polygonOutline(points: Vec2[]): Outline {\n\tif (!points.length) return () => ({ x: 0, y: 0 });\n\t// Centre on the bounding box, not the vertex mean: a mean moves when the\n\t// caller inserts a vertex mid-edge, which would silently re-aim the figure\n\t// around the break point even though the drawn shape is identical.\n\tlet minX = Infinity;\n\tlet maxX = -Infinity;\n\tlet minY = Infinity;\n\tlet maxY = -Infinity;\n\tfor (const p of points) {\n\t\tif (p.x < minX) minX = p.x;\n\t\tif (p.x > maxX) maxX = p.x;\n\t\tif (p.y < minY) minY = p.y;\n\t\tif (p.y > maxY) maxY = p.y;\n\t}\n\tconst cx = (minX + maxX) / 2;\n\tconst cy = (minY + maxY) / 2;\n\tlet max = 0;\n\tconst centered = points.map((p) => {\n\t\tconst v = { x: p.x - cx, y: p.y - cy };\n\t\tmax = Math.max(max, Math.hypot(v.x, v.y));\n\t\treturn v;\n\t});\n\tconst scale = max > 1e-6 ? 1 / max : 1;\n\tconst n = centered.length;\n\n\t// Walk by PERIMETER, not by vertex index: `t → segment t·n` hands every edge\n\t// the same share of the sparks, so a short edge comes out as dense as a long\n\t// one and inserting a vertex mid-edge changes the figure's density. Cumulative\n\t// edge lengths spread the particles evenly around the outline instead.\n\tconst cumulative: number[] = new Array(n + 1);\n\tcumulative[0] = 0;\n\tfor (let i = 0; i < n; i++) {\n\t\tconst a = centered[i]!;\n\t\tconst b = centered[(i + 1) % n]!;\n\t\tcumulative[i + 1] = cumulative[i]! + Math.hypot(b.x - a.x, b.y - a.y);\n\t}\n\tconst perimeter = cumulative[n]!;\n\n\treturn (t: number): Vec2 => {\n\t\tconst u = ((t % 1) + 1) % 1;\n\t\t// Degenerate outline (all points equal): every sample is the same point.\n\t\tif (perimeter <= 1e-9) return { x: centered[0]!.x * scale, y: centered[0]!.y * scale };\n\t\tconst target = u * perimeter;\n\t\t// Linear scan: outlines are a handful of points and this runs once per\n\t\t// spawned spark, not per frame.\n\t\tlet i = 0;\n\t\twhile (i < n - 1 && cumulative[i + 1]! <= target) i++;\n\t\tconst segLen = cumulative[i + 1]! - cumulative[i]!;\n\t\tconst f = segLen > 1e-9 ? (target - cumulative[i]!) / segLen : 0;\n\t\tconst a = centered[i]!;\n\t\tconst b = centered[(i + 1) % n]!;\n\t\treturn { x: lerp(a.x, b.x, f) * scale, y: lerp(a.y, b.y, f) * scale };\n\t};\n}\n\n/** Upward-biased, vertically compressed sphere (willow droop before gravity). */\nexport function willowBurst(n: number, seed: number): BurstDir[] {\n\treturn sphereBurst(n, seed).map((d) => ({\n\t\tdir: { x: d.dir.x, y: d.dir.y * 0.55 - 0.15 },\n\t\tz: d.z * 0.7,\n\t}));\n}\n\n/**\n * One semi-implicit Euler step of a damped spring toward `target`.\n * a = −ω²(p−target) − 2ζω·v (§5.2). Stable for the seeker's ω=6, ζ=0.9 at\n * dt up to 33 ms.\n */\nexport function springStep(\n\tpos: number,\n\tvel: number,\n\ttarget: number,\n\tdt: number,\n\tomega: number,\n\tzeta: number\n): { pos: number; vel: number } {\n\tconst a = -omega * omega * (pos - target) - 2 * zeta * omega * vel;\n\tconst v = vel + a * dt;\n\treturn { pos: pos + v * dt, vel: v };\n}\n\n/**\n * Ping-pong index over 0..3 (§1). Returns the current index, then advances,\n * reflecting at the ends: 0,1,2,3,2,1,0,1,…\n */\nexport function nextShellHue(state: { i: number; dir: 1 | -1 }): number {\n\tconst cur = state.i;\n\tlet ni = state.i + state.dir;\n\tif (ni > 3) {\n\t\tstate.dir = -1;\n\t\tni = state.i - 1;\n\t} else if (ni < 0) {\n\t\tstate.dir = 1;\n\t\tni = state.i + 1;\n\t}\n\tstate.i = ni;\n\treturn cur;\n}\n\n/** Palette color at a ping-pong index, jittered ±`jitterDeg` in oklab hue. */\nexport function shellHueColor(\n\thueIndex: number,\n\tpalette: Rgb[],\n\tjitterDeg: number,\n\trng: () => number\n): Rgb {\n\tconst base = palette[((hueIndex % palette.length) + palette.length) % palette.length]!;\n\tconst deg = (rng() * 2 - 1) * jitterDeg;\n\treturn hueRotate(base, deg);\n}\n\n/**\n * Spark color at life fraction (§1.3 / §3.1): pure white → hue crossfade →\n * full hue → cool warm-white. `whiteHold` is the life fraction the white core\n * holds before crossfading; `seed` adds a small deterministic hue jitter.\n */\nexport function sparkColorAtLife(\n\tshellHue: Rgb,\n\tlifeT: number,\n\twhiteHold: number,\n\tseed: number\n): Rgb {\n\tconst out: Rgb = { r: 0, g: 0, b: 0 };\n\tsparkColorAtLifeInto(shellHue, lifeT, whiteHold, seed, out);\n\treturn out;\n}\n\n/**\n * Poisson (exponential) inter-arrival time in ms, clamped to [min,max]. The\n * clamp (rather than truncation) keeps the sampled mean near `meanMs`.\n */\nexport function poissonIntervalMs(\n\tmeanMs: number,\n\trng: () => number,\n\tclampMin: number,\n\tclampMax: number\n): number {\n\tconst u = rng();\n\tconst x = -meanMs * Math.log(1 - Math.min(0.999999, u));\n\treturn Math.min(clampMax, Math.max(clampMin, x));\n}\n\n/** Margin the keep-clear rect is grown by before rejecting an apex (§6). */\nexport const KEEP_CLEAR_MARGIN = 0.02;\n\n/**\n * Whether `(x, y)` falls inside `rect` grown by `margin`. Exported so callers\n * that derive an apex from a sampled one (e.g. a mirrored double) can re-run\n * the same rejection test rather than assume the transform preserved it.\n */\nexport function rectExpandedContains(\n\trect: Rect,\n\tx: number,\n\ty: number,\n\tmargin = KEEP_CLEAR_MARGIN\n): boolean {\n\treturn (\n\t\tx >= rect.x0 - margin && x <= rect.x1 + margin && y >= rect.y0 - margin && y <= rect.y1 + margin\n\t);\n}\n\n/**\n * Sample an apex from weighted zones (§6). Rejects points inside the expanded\n * keep-clear rect (resampling up to `maxTries`), edge-biases x by depth, and\n * falls back to the zone farthest from the keep-clear center.\n */\nexport function sampleZone(\n\tzones: Zone[],\n\trng: () => number,\n\tkeepClear: Rect | null,\n\tmaxTries = 8\n): { apex: Vec2; depth: number } {\n\tconst total = zones.reduce((s, z) => s + z.weight, 0);\n\tconst pickZone = (): Zone => {\n\t\tlet t = rng() * total;\n\t\tfor (const z of zones) {\n\t\t\tt -= z.weight;\n\t\t\tif (t <= 0) return z;\n\t\t}\n\t\treturn zones[zones.length - 1]!;\n\t};\n\tconst KEEP_MARGIN = KEEP_CLEAR_MARGIN;\n\n\tfor (let attempt = 0; attempt < maxTries; attempt++) {\n\t\tconst z = pickZone();\n\t\tlet x = z.rect.x0 + rng() * (z.rect.x1 - z.rect.x0);\n\t\tconst y = z.rect.y0 + rng() * (z.rect.y1 - z.rect.y0);\n\t\tconst depth = rng();\n\t\t// Edge-bias: nudge x toward the zone's nearer outer edge as depth rises,\n\t\t// staying within the zone rect so zone weights are preserved.\n\t\tconst mid = (z.rect.x0 + z.rect.x1) / 2;\n\t\tconst edge = x < mid ? z.rect.x0 : z.rect.x1;\n\t\tx = x + (edge - x) * depth * 0.4;\n\t\tif (keepClear && rectExpandedContains(keepClear, x, y, KEEP_MARGIN)) continue;\n\t\treturn { apex: { x, y }, depth };\n\t}\n\n\t// Fallback: the zone whose center is farthest from the keep-clear center.\n\tconst cc = keepClear\n\t\t? { x: (keepClear.x0 + keepClear.x1) / 2, y: (keepClear.y0 + keepClear.y1) / 2 }\n\t\t: { x: 0.5, y: 0.5 };\n\tlet best = zones[0]!;\n\tlet bestD = -1;\n\tfor (const z of zones) {\n\t\tconst zx = (z.rect.x0 + z.rect.x1) / 2;\n\t\tconst zy = (z.rect.y0 + z.rect.y1) / 2;\n\t\tconst d = Math.hypot(zx - cc.x, zy - cc.y);\n\t\tif (d > bestD) {\n\t\t\tbestD = d;\n\t\t\tbest = z;\n\t\t}\n\t}\n\treturn {\n\t\tapex: { x: (best.rect.x0 + best.rect.x1) / 2, y: (best.rect.y0 + best.rect.y1) / 2 },\n\t\tdepth: rng(),\n\t};\n}\n\n/**\n * SDR soft-knee tone map (§7.2): identity below `knee`, then an asymptotic\n * approach to 1.0 so over-white energy compresses instead of hard-clipping.\n * Shared by the renderers (WGSL / GLSL inline the same formula) and unit-tested\n * here so the ladder has one canonical definition.\n */\nexport function softKnee(x: number, knee: number): number {\n\tif (x <= knee) return x;\n\tconst over = x - knee;\n\tconst span = Math.max(1 - knee, 1e-3);\n\treturn knee + span * (1 - Math.exp(-over / span));\n}\n\n/**\n * Resolve the effective quality tier for `quality=\"auto\"` (or pass a fixed tier\n * through unchanged). Extracted from the component so the ladder is testable:\n *\n * - an explicit tier (\"high\"/\"mid\"/\"low\") always wins;\n * - a small viewport (min-dim < 480 px) → \"low\" (covers phones);\n * - a low-power device on the WebGL2 fallback → \"low\" (weak GPU + modest\n *   CPU/RAM; only ever downgrades the fallback path, never WebGPU);\n * - \"webgpu-hdr\" → \"high\"; \"webgpu-sdr\" → \"high\" on a retina DPR, else \"mid\";\n * - the WebGL2 levels (\"webgl-p3\"/\"webgl-sdr\") → \"mid\" (the fallback renderer is\n *   fill-rate bound; \"none\" is unreachable here — no sim is built without an\n *   engine — but maps to \"mid\" for completeness).\n */\nexport function resolveQualityTier(\n\trequested: \"auto\" | QualityTier,\n\tlevel: FireworksRenderLevel,\n\tdpr: number,\n\tminDim: number,\n\tlowPower = false\n): QualityTier {\n\tif (requested !== \"auto\") return requested;\n\tif (minDim > 0 && minDim < 480) return \"low\";\n\tconst isWebGl = level === \"webgl-p3\" || level === \"webgl-sdr\";\n\tif (lowPower && isWebGl) return \"low\";\n\tif (level === \"webgpu-hdr\") return \"high\";\n\tif (level === \"webgpu-sdr\") return dpr >= 2 ? \"high\" : \"mid\";\n\treturn \"mid\";\n}\n\n// =============================================================================\n// Adaptive downgrade — a session-sticky, GPU-then-CPU quality ladder\n// =============================================================================\n//\n// The CPU sim has large headroom (benchmarked well under 2 ms/frame at 4k\n// particles); the real budget risk is GPU fill-rate on the HDR float path. So\n// the ladder sheds GPU cost first (accumulation renderScale 1 → 0.75 → 0.5),\n// then CPU/GPU cost (spawn density 1 → 0.66 → 0.4, which shrinks new burst\n// particle counts — glyph seekers are driven by explicit points and are never\n// scaled, so the intro word stays intact). It only ever downgrades: once a\n// notch drops it never returns within the session (no oscillation), matching a\n// user who would rather have a stable lower quality than a hunting one.\n//\n// The pool is fixed-size (capacity is frozen at createSim), so runtime tier\n// (capacity) changes are intentionally NOT supported — rebuilding the pool\n// mid-show would pop every live particle. Reducing spawn density is the cheap,\n// pop-free CPU lever and is what the ladder uses instead.\n\n/** One rung of the adaptive quality ladder. */\nexport interface AdaptiveLevel {\n\t/** Accumulation-buffer resolution scale relative to the canvas. */\n\trenderScale: number;\n\t/** Multiplier on new burst particle counts (spawn density). */\n\tspawnScale: number;\n}\n\n/** The fixed ladder. Index 0 is full quality; each step sheds more. */\nexport const ADAPTIVE_LADDER: AdaptiveLevel[] = [\n\t{ renderScale: 1, spawnScale: 1 }, // 0 — full\n\t{ renderScale: 0.75, spawnScale: 1 }, // 1 — GPU: 0.75× accum\n\t{ renderScale: 0.5, spawnScale: 1 }, // 2 — GPU: 0.5× accum\n\t{ renderScale: 0.5, spawnScale: 0.66 }, // 3 — CPU: 0.66× spawn\n\t{ renderScale: 0.5, spawnScale: 0.4 }, // 4 — CPU: 0.4× spawn (floor)\n];\n\nexport interface AdaptiveTuning {\n\t/** EMA smoothing factor (higher = more reactive). */\n\talpha: number;\n\t/** Frame-time (ms) above which frames count toward a downgrade. */\n\tthresholdMs: number;\n\t/** Consecutive over-threshold frames required to drop a notch. */\n\tsustainFrames: number;\n}\n\n/** Defaults: EMA α=0.1, downgrade when the average frame holds > 24 ms (~<42 fps) for ~60 frames (~1 s). */\nexport const ADAPTIVE_DEFAULTS: AdaptiveTuning = {\n\talpha: 0.1,\n\tthresholdMs: 24,\n\tsustainFrames: 60,\n};\n\nexport interface AdaptiveState {\n\t/** EMA of frame time (ms). */\n\temaMs: number;\n\t/** Consecutive frames the EMA has been over threshold. */\n\toverCount: number;\n\t/** Current ladder index (only ever increases). */\n\tstep: number;\n\t/** Whether the EMA has been seeded (avoids a ramp-up from 0). */\n\tstarted: boolean;\n}\n\nexport function createAdaptiveState(): AdaptiveState {\n\treturn { emaMs: 0, overCount: 0, step: 0, started: false };\n}\n\n/**\n * Fold one ACTIVE frame's wall time into the adaptive controller. The caller\n * must invoke this only for frames that actually did work (particles present,\n * not reduced-motion-idle, not `document.hidden`) so paused/quiet frames don't\n * skew the average. Mutates `state` (EMA, counter, step) and returns `true` on\n * the frame a downgrade fires — the caller then applies `adaptiveLevel(state)`.\n * Session-sticky: never upgrades; a no-op once at the ladder floor.\n */\nexport function adaptiveDowngradeStep(\n\tstate: AdaptiveState,\n\tframeMs: number,\n\ttuning: AdaptiveTuning = ADAPTIVE_DEFAULTS\n): boolean {\n\t// Seed on the first active frame so the EMA starts at the real cost.\n\tif (!state.started) {\n\t\tstate.emaMs = frameMs;\n\t\tstate.started = true;\n\t} else {\n\t\tstate.emaMs += tuning.alpha * (frameMs - state.emaMs);\n\t}\n\n\t// At the floor there is nothing left to shed.\n\tif (state.step >= ADAPTIVE_LADDER.length - 1) {\n\t\tstate.overCount = 0;\n\t\treturn false;\n\t}\n\n\tif (state.emaMs > tuning.thresholdMs) {\n\t\tstate.overCount++;\n\t\tif (state.overCount >= tuning.sustainFrames) {\n\t\t\tstate.step++;\n\t\t\tstate.overCount = 0; // give the new level time to take effect\n\t\t\treturn true;\n\t\t}\n\t} else {\n\t\tstate.overCount = 0;\n\t}\n\treturn false;\n}\n\n/** The current ladder rung for `state.step`. */\nexport function adaptiveLevel(state: AdaptiveState): AdaptiveLevel {\n\treturn ADAPTIVE_LADDER[Math.min(state.step, ADAPTIVE_LADDER.length - 1)]!;\n}\n\n// =============================================================================\n// §1 factory — createSim\n// =============================================================================\n\ninterface LaunchSpec {\n\tshell: ShellKind;\n\tcolors: Rgb[]; // one or two hues\n\t/** Ascent-trail hue for this shell (comet head mixed toward `colors[0]`). */\n\ttrailHue: Rgb;\n\tscale: number;\n\tdepth: number;\n\tseed: number;\n\tintensity: Intensity;\n\tglyphPoints?: Vec2[];\n\t/** Resolved figure for a pattern shell (built once per launch). */\n\toutline?: Outline;\n\treleaseAtMs?: number;\n\tbreakMs: number;\n}\n\ntype BurstReq = { origin: Vec2; spec: LaunchSpec };\ntype FlashReq = { pos: Vec2; brightness: number; size: number; hue: Rgb; dim?: number };\ntype SparkReq = {\n\tpos: Vec2;\n\tvel: Vec2;\n\tttl: number;\n\tsize: number;\n\thue: Rgb;\n\tseed: number;\n};\n\nconst clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\nconst rand = (rng: () => number, lo: number, hi: number) => lo + rng() * (hi - lo);\n\nexport function createSim(opts: SimOptions): Sim {\n\tconst tier = QUALITY[opts.quality];\n\tconst capacity = tier.maxParticles;\n\tconst palette = opts.palette ?? PALETTE;\n\tconst rng = opts.rng ?? Math.random;\n\n\tconst pool = new Float32Array(capacity * STRIDE);\n\tlet count = 0;\n\tlet droppedSpawns = 0;\n\tlet aspect = opts.aspect;\n\t// §4.5 soft-dim rect. Null until the caller sets it (the app only does so\n\t// once the card is on screen), so the intro glyph is never dimmed.\n\tlet keepClear: Rect | null = null;\n\t// Adaptive spawn-density lever (1 = full). Scales new burst counts only.\n\tlet spawnScale = 1;\n\n\t// Session wind (seeded once). `a += w · windScale[type]` each step.\n\tconst sessionWind: Vec2 = opts.wind ?? {\n\t\tx: (rng() < 0.5 ? -1 : 1) * rand(rng, WIND_X[0], WIND_X[1]),\n\t\ty: (rng() < 0.5 ? -1 : 1) * rand(rng, WIND_Y[0], WIND_Y[1]),\n\t};\n\n\t// Deferred spawns: enqueued during step (detonations, flashes, trail sparks),\n\t// drained at the top of the NEXT step so the pool is never grown mid-iterate.\n\tlet burstQueue: BurstReq[] = [];\n\tlet flashQueue: FlashReq[] = [];\n\tlet sparkQueue: SparkReq[] = [];\n\n\t// Monotonic seed for step-time randomness that has no stored particle seed\n\t// (keeps determinism: a fixed call order reproduces the same sequence).\n\tlet seq = 1;\n\tconst stepSeed = () => hash11(seq++ * 0.61803398875);\n\n\tfunction appendParticle(write: (base: number) => void): boolean {\n\t\tif (count >= capacity) {\n\t\t\tdroppedSpawns++;\n\t\t\treturn false;\n\t\t}\n\t\tconst base = count * STRIDE;\n\t\t// Zero the slot so unset fields are deterministic.\n\t\tfor (let k = 0; k < STRIDE; k++) pool[base + k] = 0;\n\t\t// Depth dim is a multiplier, so its neutral value is 1, not 0. Set before\n\t\t// the writer runs so depth-aware spawns can still override it.\n\t\tpool[base + F.depthDim] = 1;\n\t\twrite(base);\n\t\tcount++;\n\t\treturn true;\n\t}\n\n\tfunction setAspect(a: number) {\n\t\taspect = a;\n\t}\n\n\tfunction setKeepClear(rect: Rect | null) {\n\t\tkeepClear = rect;\n\t}\n\n\tfunction setSpawnScale(scale: number) {\n\t\tspawnScale = Number.isFinite(scale) ? Math.max(0, Math.min(1, scale)) : 1;\n\t}\n\n\tfunction reset() {\n\t\tcount = 0;\n\t\tdroppedSpawns = 0;\n\t\tburstQueue = [];\n\t\tflashQueue = [];\n\t\tsparkQueue = [];\n\t\tseq = 1;\n\t}\n\n\t// ---- launch (§4) --------------------------------------------------------\n\tfunction launch(o: LaunchOptions): LaunchResult {\n\t\tconst shell = o.shell ?? \"peony\";\n\t\tconst seed = o.seed ?? Math.floor(rng() * 1e6);\n\t\tconst from: Vec2 = o.from ?? {\n\t\t\tx: clamp(o.apex.x + (rng() * 2 - 1) * 0.04, LAUNCH_X[0], LAUNCH_X[1]),\n\t\t\ty: rand(rng, LAUNCH_Y[0], LAUNCH_Y[1]),\n\t\t};\n\t\t// Solve against the medium the rocket is actually integrated through\n\t\t// (drag, session wind, aspect) — a ballistic solve undershoots the apex by\n\t\t// ~25% of the rise and misses horizontally on non-square canvases.\n\t\tconst { v0, flightMs } = solveLaunch(from, o.apex, G * GRAV_SCALE[TYPE.ROCKET], o.flightMs, {\n\t\t\tdrag: DRAG[TYPE.ROCKET],\n\t\t\taspect,\n\t\t\twindX: sessionWind.x * WIND_SCALE[TYPE.ROCKET],\n\t\t\twindY: sessionWind.y * WIND_SCALE[TYPE.ROCKET],\n\t\t});\n\t\t// Fuse hang 80–140 ms (intro glyph \"?\" uses 140 via explicit releaseAtMs path).\n\t\tconst hangMs = o.intensity === \"intro\" ? 140 : rand(rng, 80, 140);\n\t\tconst breakMs = flightMs + hangMs;\n\n\t\tconst colors = resolveColors(o.color, seed);\n\t\tconst spec: LaunchSpec = {\n\t\t\tshell,\n\t\t\tcolors,\n\t\t\t// The ascent trail is tinted toward THIS shell's hue (§4) — mixed once\n\t\t\t// per launch, not per emitted spark, and never from the default palette.\n\t\t\ttrailHue: mixOklab(COMET_HEAD, colors[0]!, COMET_TRAIL_MIX),\n\t\t\tscale: o.scale ?? 1,\n\t\t\tdepth: clamp(o.depth ?? 0, 0, 1),\n\t\t\tseed,\n\t\t\tintensity: o.intensity ?? \"ambient\",\n\t\t\tglyphPoints: o.glyphPoints,\n\t\t\t// Resolved here, not per particle: normalizing the caller's points is\n\t\t\t// O(n) and the burst is expanded a frame later, once.\n\t\t\toutline: o.shapePoints?.length ? polygonOutline(o.shapePoints) : undefined,\n\t\t\treleaseAtMs: o.releaseAtMs,\n\t\t\tbreakMs,\n\t\t};\n\t\tconst launchId = registerSpec(spec);\n\n\t\tappendParticle((base) => {\n\t\t\tpool[base + F.posX] = from.x;\n\t\t\tpool[base + F.posY] = from.y;\n\t\t\tpool[base + F.velX] = v0.x;\n\t\t\tpool[base + F.velY] = v0.y;\n\t\t\tpool[base + F.ttl] = breakMs / 1000;\n\t\t\tpool[base + F.size] = 0.004;\n\t\t\tpool[base + F.r] = COMET_HEAD.r;\n\t\t\tpool[base + F.g] = COMET_HEAD.g;\n\t\t\tpool[base + F.b] = COMET_HEAD.b;\n\t\t\tpool[base + F.brightness] = B_ASCENT_HEAD;\n\t\t\tpool[base + F.type] = TYPE.ROCKET;\n\t\t\tpool[base + F.seed] = seed;\n\t\t\t// Field reuse for rockets: targetX = launchId, targetY = trail accumulator.\n\t\t\tpool[base + F.targetX] = launchId;\n\t\t\tpool[base + F.targetY] = 0;\n\t\t\tpool[base + F.dragScale] = 1;\n\t\t});\n\n\t\treturn { flightMs, breakMs };\n\t}\n\n\tfunction resolveColors(color: Rgb | Rgb[] | undefined, seed: number): Rgb[] {\n\t\tif (Array.isArray(color)) return color.length ? color : [PALETTE[0]!];\n\t\tif (color) return [color];\n\t\t// Omitted → ping-pong sweep seeded off the launch seed (deterministic).\n\t\tconst idx = Math.floor(hash11(seed) * palette.length) % palette.length;\n\t\treturn [hueRotate(palette[idx]!, (hash11(seed + 7) * 2 - 1) * SHELL_JITTER_DEG)];\n\t}\n\n\t// Active launch specs by id (freed at detonation). Tiny (≤ a few at once).\n\tconst specs = new Map<number, LaunchSpec>();\n\tlet specId = 1;\n\tfunction registerSpec(spec: LaunchSpec): number {\n\t\tconst id = specId++;\n\t\tspecs.set(id, spec);\n\t\treturn id;\n\t}\n\n\tfunction spawnFlash(pos: Vec2, brightness: number, sizeNorm: number, hue: Rgb): void {\n\t\tflashQueue.push({ pos: { ...pos }, brightness, size: sizeNorm, hue });\n\t}\n\n\t// ---- detonation → burst expansion --------------------------------------\n\tfunction expandBurst(req: BurstReq) {\n\t\tconst { origin, spec } = req;\n\t\tconst recipe = SHELL[spec.shell];\n\t\tif (spec.shell === \"glyph\") {\n\t\t\texpandGlyph(origin, spec);\n\t\t\treturn;\n\t\t}\n\t\t// Spawn-density lever (adaptive downgrade): scale burst counts, floor at 1.\n\t\tconst n = Math.max(1, Math.round(recipe.counts[opts.quality] * spawnScale));\n\t\t// Depth also pulls the burst in spatially, so a far shell is a smaller\n\t\t// bloom and not just a desaturated one at full size.\n\t\tconst radius =\n\t\t\trand(seededRng(spec.seed + 3), recipe.radius[0], recipe.radius[1]) *\n\t\t\tspec.scale *\n\t\t\t(1 - DEPTH_RADIUS * spec.depth);\n\t\tconst dim = depthDim(spec.depth);\n\t\tconst baseSpeed = radius * BURST_SPEED_K;\n\t\tconst outline = spec.outline ?? recipe.outline;\n\t\tlet dirs: BurstDir[];\n\t\tif (recipe.builder === \"outline\") {\n\t\t\t// A \"shape\" shell launched without points has no figure to draw; fall\n\t\t\t// back to a plain sphere so the shell still breaks instead of vanishing.\n\t\t\tdirs = outline ? outlineBurst(n, spec.seed, outline) : sphereBurst(n, spec.seed);\n\t\t} else if (recipe.builder === \"ring\") {\n\t\t\tdirs = ringBurst(n, spec.seed);\n\t\t} else if (recipe.builder === \"willow\") {\n\t\t\tdirs = willowBurst(n, spec.seed);\n\t\t} else {\n\t\t\tdirs = sphereBurst(n, spec.seed);\n\t\t}\n\n\t\tfor (let i = 0; i < dirs.length; i++) {\n\t\t\tconst { dir, z } = dirs[i]!;\n\t\t\t// Break asymmetry ±12% and 5% stragglers ×1.4 speed / dragScale×0.7.\n\t\t\t// A pattern shell keeps neither: both are read as a broken figure.\n\t\t\tconst asymAmount = recipe.crisp ? 0.03 : 0.12;\n\t\t\tconst asym = 1 + (hash11(spec.seed + i) * 2 - 1) * asymAmount;\n\t\t\tconst straggler = !recipe.crisp && hash11(spec.seed + i + 991) < 0.05;\n\t\t\tconst speed = baseSpeed * asym * (straggler ? 1.4 : 1);\n\t\t\tconst isEmber = hash11(spec.seed + i + 313) < recipe.emberFrac;\n\t\t\tconst type: ParticleType = isEmber ? TYPE.EMBER : TYPE.SPARK;\n\t\t\tconst crackles = !isEmber && hash11(spec.seed + i + 577) < CRACKLE_FRAC;\n\t\t\tconst hue = depthAdjust(pickShellColor(spec, i), spec.depth);\n\t\t\tconst ttl = isEmber\n\t\t\t\t? rand(seededRng(spec.seed + i + 17), 1.4, 2.4)\n\t\t\t\t: rand(seededRng(spec.seed + i + 17), 0.75, 1.3);\n\t\t\tconst size =\n\t\t\t\t(isEmber\n\t\t\t\t\t? rand(seededRng(spec.seed + i + 29), 0.002, 0.003)\n\t\t\t\t\t: rand(seededRng(spec.seed + i + 29), 0.0025, 0.004)) *\n\t\t\t\t(1 - DEPTH_SIZE * spec.depth);\n\t\t\tappendParticle((base) => {\n\t\t\t\tpool[base + F.posX] = origin.x;\n\t\t\t\tpool[base + F.posY] = origin.y;\n\t\t\t\tpool[base + F.velX] = dir.x * speed;\n\t\t\t\tpool[base + F.velY] = dir.y * speed;\n\t\t\t\tpool[base + F.ttl] = ttl;\n\t\t\t\tpool[base + F.size] = size;\n\t\t\t\tpool[base + F.r] = hue.r;\n\t\t\t\tpool[base + F.g] = hue.g;\n\t\t\t\tpool[base + F.b] = hue.b;\n\t\t\t\tpool[base + F.brightness] = B_SPARK_FRESH;\n\t\t\t\tpool[base + F.type] = type;\n\t\t\t\tpool[base + F.seed] = spec.seed + i;\n\t\t\t\t// z-parallax folded into dragScale as a mild size/brightness proxy is\n\t\t\t\t// avoided; dragScale carries the straggler multiplier and a per-spark\n\t\t\t\t// spread — identical drag makes every spark fall at one speed, which\n\t\t\t\t// combs the debris into a parallel curtain instead of a shell.\n\t\t\t\t//\n\t\t\t\t// A pattern shell gets NO spread: a spark coasts `v0 / (drag·dragScale)`,\n\t\t\t\t// so varying the scale scales each spark's reach independently and the\n\t\t\t\t// figure never expands as one shape. The ±6% radial jitter in\n\t\t\t\t// `outlineBurst` is the deliberate, bounded version of that.\n\t\t\t\tpool[base + F.dragScale] = recipe.crisp\n\t\t\t\t\t? 1\n\t\t\t\t\t: straggler\n\t\t\t\t\t\t? 0.7\n\t\t\t\t\t\t: 0.85 + 0.45 * hash11(spec.seed + i + 233);\n\t\t\t\tpool[base + F.depthDim] = dim;\n\t\t\t\t// Field reuse for sparks: targetX flags the cracklers.\n\t\t\t\tpool[base + F.targetX] = crackles ? 1 : 0;\n\t\t\t\t// Stash burst z in targetY (unused for sparks/embers) for future\n\t\t\t\t// parallax; harmless if ignored by the renderer.\n\t\t\t\tpool[base + F.targetY] = z;\n\t\t\t});\n\t\t}\n\n\t\t// Apex smoke puff(s) + one detonation flash.\n\t\tfor (let s = 0; s < recipe.smoke; s++) {\n\t\t\tspawnSmoke(origin, spec, s);\n\t\t}\n\t\tconst flashB = spec.intensity === \"intro\" ? B_FLASH_INTRO : B_FLASH_AMBIENT;\n\t\tflashQueue.push({\n\t\t\tpos: { ...origin },\n\t\t\tbrightness: flashB,\n\t\t\tsize: rand(seededRng(spec.seed + 5), 0.025, 0.05) * (1 - DEPTH_SIZE * spec.depth),\n\t\t\thue: depthAdjust(spec.colors[0]!, spec.depth),\n\t\t\tdim,\n\t\t});\n\t}\n\n\tfunction expandGlyph(origin: Vec2, spec: LaunchSpec) {\n\t\tconst points = spec.glyphPoints ?? [];\n\t\tconst releaseDelaySec = Math.max(\n\t\t\t0.3,\n\t\t\t((spec.releaseAtMs ?? spec.breakMs + 1500) - spec.breakMs) / 1000\n\t\t);\n\t\tconst hue = depthAdjust(spec.colors[0]!, spec.depth);\n\t\tconst dim = depthDim(spec.depth);\n\t\tfor (let i = 0; i < points.length; i++) {\n\t\t\tconst p = points[i]!;\n\t\t\tappendParticle((base) => {\n\t\t\t\tpool[base + F.posX] = origin.x;\n\t\t\t\tpool[base + F.posY] = origin.y;\n\t\t\t\t// Pop velocity toward target, magnitude dist/0.08 (§5.1).\n\t\t\t\tconst dx = (p.x - origin.x) * aspect;\n\t\t\t\tconst dy = p.y - origin.y;\n\t\t\t\tconst d = Math.hypot(dx, dy) || 1e-4;\n\t\t\t\tconst mag = d / 0.08;\n\t\t\t\tpool[base + F.velX] = (dx / d) * mag;\n\t\t\t\tpool[base + F.velY] = (dy / d) * mag;\n\t\t\t\tpool[base + F.ttl] = releaseDelaySec + 0.9; // hold window + release fade\n\t\t\t\tpool[base + F.size] = 0.003 * (1 - DEPTH_SIZE * spec.depth);\n\t\t\t\tpool[base + F.depthDim] = dim;\n\t\t\t\tpool[base + F.r] = hue.r;\n\t\t\t\tpool[base + F.g] = hue.g;\n\t\t\t\tpool[base + F.b] = hue.b;\n\t\t\t\tpool[base + F.brightness] = B_GLYPH_HOLD;\n\t\t\t\tpool[base + F.type] = TYPE.SEEKER;\n\t\t\t\tpool[base + F.seed] = spec.seed + i;\n\t\t\t\tpool[base + F.targetX] = p.x;\n\t\t\t\tpool[base + F.targetY] = p.y;\n\t\t\t\t// Field reuse for seekers: dragScale carries the release delay (s).\n\t\t\t\tpool[base + F.dragScale] = releaseDelaySec;\n\t\t\t});\n\t\t}\n\t}\n\n\tfunction spawnSmoke(origin: Vec2, spec: LaunchSpec, s: number) {\n\t\tappendParticle((base) => {\n\t\t\tpool[base + F.posX] = origin.x + (hash11(spec.seed + s + 41) * 2 - 1) * 0.01;\n\t\t\tpool[base + F.posY] = origin.y + (hash11(spec.seed + s + 43) * 2 - 1) * 0.01;\n\t\t\tpool[base + F.velX] = (hash11(spec.seed + s + 47) * 2 - 1) * 0.02;\n\t\t\tpool[base + F.velY] = -0.02;\n\t\t\tpool[base + F.ttl] = rand(seededRng(spec.seed + s + 51), 1.5, 3.0);\n\t\t\tpool[base + F.size] = 0.01;\n\t\t\tpool[base + F.r] = SMOKE_COLOR.r;\n\t\t\tpool[base + F.g] = SMOKE_COLOR.g;\n\t\t\tpool[base + F.b] = SMOKE_COLOR.b;\n\t\t\tpool[base + F.brightness] = B_SMOKE_MIN;\n\t\t\tpool[base + F.type] = TYPE.SMOKE;\n\t\t\tpool[base + F.seed] = spec.seed + s + 61;\n\t\t\tpool[base + F.dragScale] = 1;\n\t\t\tpool[base + F.depthDim] = depthDim(spec.depth);\n\t\t});\n\t}\n\n\tfunction pickShellColor(spec: LaunchSpec, i: number): Rgb {\n\t\tif (spec.colors.length === 1) return spec.colors[0]!;\n\t\t// Adjacent duo: split the shell between the two hues.\n\t\treturn hash11(spec.seed + i + 137) < 0.5 ? spec.colors[0]! : spec.colors[1]!;\n\t}\n\n\tfunction depthAdjust(hue: Rgb, depth: number): Rgb {\n\t\tif (depth <= 0) return hue;\n\t\treturn scaleChroma(hue, 1 - DEPTH_CHROMA * depth);\n\t}\n\n\t/** Brightness multiplier a launch's `depth` imposes on all of its debris. */\n\tfunction depthDim(depth: number): number {\n\t\treturn depth <= 0 ? 1 : 1 - DEPTH_DIM * depth;\n\t}\n\n\t// A small deterministic rng seeded off an integer, for spawn-time jitter\n\t// during a detonation (which happens inside step and must stay reproducible).\n\tfunction seededRng(seed: number): () => number {\n\t\tlet s = seed;\n\t\treturn () => {\n\t\t\ts += 1;\n\t\t\treturn hash11(s);\n\t\t};\n\t}\n\n\t// ---- step (§7) ----------------------------------------------------------\n\tfunction step(dtSeconds: number, wind?: Vec2) {\n\t\tconst dt = Math.min(dtSeconds, DT_MAX);\n\t\tconst w = wind ?? sessionWind;\n\n\t\t// 2. Drain the previous frame's deferred spawns.\n\t\tif (burstQueue.length) {\n\t\t\tconst q = burstQueue;\n\t\t\tburstQueue = [];\n\t\t\tfor (let bi = 0; bi < q.length; bi++) expandBurst(q[bi]!);\n\t\t}\n\t\tif (flashQueue.length) {\n\t\t\tconst q = flashQueue;\n\t\t\tflashQueue = [];\n\t\t\tfor (let fi = 0; fi < q.length; fi++) {\n\t\t\t\tconst f = q[fi]!;\n\t\t\t\tappendParticle((base) => {\n\t\t\t\t\tpool[base + F.posX] = f.pos.x;\n\t\t\t\t\tpool[base + F.posY] = f.pos.y;\n\t\t\t\t\tpool[base + F.ttl] = rand(seededRng(seq++ | 0), 0.06, 0.12);\n\t\t\t\t\tpool[base + F.size] = f.size;\n\t\t\t\t\tpool[base + F.r] = f.hue.r;\n\t\t\t\t\tpool[base + F.g] = f.hue.g;\n\t\t\t\t\tpool[base + F.b] = f.hue.b;\n\t\t\t\t\tpool[base + F.brightness] = f.brightness;\n\t\t\t\t\tpool[base + F.type] = TYPE.FLASH;\n\t\t\t\t\tpool[base + F.seed] = stepSeed() * 1000;\n\t\t\t\t\tpool[base + F.depthDim] = f.dim ?? 1;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (sparkQueue.length) {\n\t\t\tconst q = sparkQueue;\n\t\t\tsparkQueue = [];\n\t\t\tfor (let si = 0; si < q.length; si++) {\n\t\t\t\tconst sp = q[si]!;\n\t\t\t\tappendParticle((base) => {\n\t\t\t\t\tpool[base + F.posX] = sp.pos.x;\n\t\t\t\t\tpool[base + F.posY] = sp.pos.y;\n\t\t\t\t\tpool[base + F.velX] = sp.vel.x;\n\t\t\t\t\tpool[base + F.velY] = sp.vel.y;\n\t\t\t\t\tpool[base + F.ttl] = sp.ttl;\n\t\t\t\t\tpool[base + F.size] = sp.size;\n\t\t\t\t\tpool[base + F.r] = sp.hue.r;\n\t\t\t\t\tpool[base + F.g] = sp.hue.g;\n\t\t\t\t\tpool[base + F.b] = sp.hue.b;\n\t\t\t\t\tpool[base + F.brightness] = B_ASCENT_TAIL;\n\t\t\t\t\tpool[base + F.type] = TYPE.SPARK;\n\t\t\t\t\tpool[base + F.seed] = sp.seed;\n\t\t\t\t\tpool[base + F.dragScale] = 1;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// 3. Per-live update with swap-remove (re-examine i after a removal). Aging\n\t\t// happens exactly once per particle here; type routines only integrate.\n\t\tlet i = 0;\n\t\twhile (i < count) {\n\t\t\tconst base = i * STRIDE;\n\t\t\tconst type = pool[base + F.type]! as ParticleType;\n\n\t\t\tif (type === TYPE.ROCKET) {\n\t\t\t\temitTrail(base, dt);\n\t\t\t\tintegrate(base, type, dt, w);\n\t\t\t\t// Ascent wobble: a real shell corkscrews slightly on its way up, and\n\t\t\t\t// the perfectly straight column the integrator draws reads as a wire.\n\t\t\t\t// Positional only (velocity untouched), and small enough that the\n\t\t\t\t// apex the launch solved for still holds.\n\t\t\t\tconst wob = pool[base + F.seed]!;\n\t\t\t\tpool[base + F.posX] =\n\t\t\t\t\tpool[base + F.posX]! +\n\t\t\t\t\tMath.sin(pool[base + F.age]! * ROCKET_WOBBLE_HZ + hash11(wob) * 6.283) *\n\t\t\t\t\t\tROCKET_WOBBLE_AMP *\n\t\t\t\t\t\tdt;\n\t\t\t} else if (type === TYPE.SEEKER) {\n\t\t\t\tstepSeeker(base, dt);\n\t\t\t} else {\n\t\t\t\tintegrate(base, type, dt, w);\n\t\t\t\tif (type === TYPE.SMOKE) stepSmoke(base, dt);\n\t\t\t}\n\n\t\t\tpool[base + F.age] = pool[base + F.age]! + dt;\n\t\t\tconst lifeT = pool[base + F.ttl]! > 0 ? pool[base + F.age]! / pool[base + F.ttl]! : 1;\n\t\t\t// The launch's depth rides along as a per-particle multiplier: the type\n\t\t\t// curves stay the single source of the shape, depth only scales it.\n\t\t\tpool[base + F.brightness] =\n\t\t\t\tbrightnessCurve(type, base, lifeT) * deathGate(lifeT) * pool[base + F.depthDim]!;\n\n\t\t\t// §4.5 soft-dim: drift-ins behind the card fade to KEEP_CLEAR_DIM so the\n\t\t\t// haze there stays under the §4.6 ceiling (this brightness feeds the\n\t\t\t// additive accumulation write in writeInstances). Rockets transit and\n\t\t\t// glyph seekers are the show — both exempt — and the branch only runs\n\t\t\t// once a keep-clear rect is set.\n\t\t\tif (keepClear !== null && type !== TYPE.ROCKET && type !== TYPE.SEEKER) {\n\t\t\t\tconst px = pool[base + F.posX]!;\n\t\t\t\tconst py = pool[base + F.posY]!;\n\t\t\t\tif (px >= keepClear.x0 && px <= keepClear.x1 && py >= keepClear.y0 && py <= keepClear.y1) {\n\t\t\t\t\tpool[base + F.brightness] = pool[base + F.brightness]! * KEEP_CLEAR_DIM;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet removed = false;\n\t\t\tif (lifeT >= 1) {\n\t\t\t\t// A rocket reaching its ttl detonates: enqueue the shell at the head's\n\t\t\t\t// current position (drained next frame), then die like any particle.\n\t\t\t\tif (type === TYPE.ROCKET) {\n\t\t\t\t\tconst spec = specs.get(pool[base + F.targetX]!);\n\t\t\t\t\tif (spec) {\n\t\t\t\t\t\tburstQueue.push({\n\t\t\t\t\t\t\torigin: { x: pool[base + F.posX]!, y: pool[base + F.posY]! },\n\t\t\t\t\t\t\tspec,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tspecs.delete(pool[base + F.targetX]!);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tremoved = true;\n\t\t\t}\n\n\t\t\tif (removed) {\n\t\t\t\t// Swap-remove: copy the last live particle into slot i, shrink, and\n\t\t\t\t// re-examine i (do not advance).\n\t\t\t\tconst last = (count - 1) * STRIDE;\n\t\t\t\tif (base !== last) pool.copyWithin(base, last, last + STRIDE);\n\t\t\t\tcount--;\n\t\t\t} else {\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Generic semi-implicit Euler with per-type gravity, wind, and drag (§2.1).\n\tfunction integrate(base: number, type: ParticleType, dt: number, w: Vec2) {\n\t\tconst ax = w.x * WIND_SCALE[type];\n\t\tconst ay = G * GRAV_SCALE[type] + w.y * WIND_SCALE[type];\n\t\tlet vx = pool[base + F.velX]! + ax * dt;\n\t\tlet vy = pool[base + F.velY]! + ay * dt;\n\t\tconst damp = 1 + DRAG[type] * pool[base + F.dragScale]! * dt;\n\t\tvx /= damp;\n\t\tvy /= damp;\n\t\tpool[base + F.velX] = vx;\n\t\tpool[base + F.velY] = vy;\n\t\tpool[base + F.posX] = pool[base + F.posX]! + (vx / aspect) * dt;\n\t\tpool[base + F.posY] = pool[base + F.posY]! + vy * dt;\n\t}\n\n\t// Rocket ascent trail (§4): fractional accumulator in targetY, deferred\n\t// spawns so the pool is never grown while the per-live loop iterates.\n\tfunction emitTrail(base: number, dt: number) {\n\t\tlet emit = pool[base + F.targetY]! + tier.trailRate * dt;\n\t\tconst seed = pool[base + F.seed]!;\n\t\tconst px = pool[base + F.posX]!;\n\t\tconst py = pool[base + F.posY]!;\n\t\t// targetX carries the launch id: the trail wears the launched shell's hue.\n\t\tconst hue = specs.get(pool[base + F.targetX]!)?.trailHue ?? COMET_TRAIL_HUE;\n\t\tlet k = 0;\n\t\twhile (emit >= 1) {\n\t\t\temit -= 1;\n\t\t\tconst j = hash11(seed + pool[base + F.age]! * 1000 + k);\n\t\t\tsparkQueue.push({\n\t\t\t\tpos: { x: px, y: py },\n\t\t\t\t// Wider lateral scatter: a rigidly co-linear trail reads as a drawn\n\t\t\t\t// beam rather than a comet shedding sparks.\n\t\t\t\tvel: { x: (j * 2 - 1) * 0.035, y: (hash11(j) * 2 - 1) * 0.02 },\n\t\t\t\tttl: rand(seededRng(seed + k + 71), 0.22, 0.45),\n\t\t\t\tsize: 0.0018,\n\t\t\t\thue,\n\t\t\t\tseed: seed + k + 500,\n\t\t\t});\n\t\t\tk++;\n\t\t}\n\t\tpool[base + F.targetY] = emit;\n\t}\n\n\tfunction stepSeeker(base: number, dt: number) {\n\t\tconst age = pool[base + F.age]!;\n\t\tconst releaseDelay = pool[base + F.dragScale]!;\n\t\tconst tX = pool[base + F.targetX]!;\n\t\tconst tY = pool[base + F.targetY]!;\n\t\tconst seed = pool[base + F.seed]!;\n\n\t\tif (age < 0.08) {\n\t\t\t// Pop phase: ballistic toward target, mild drag, no gravity (§5.1).\n\t\t\tlet vx = pool[base + F.velX]!;\n\t\t\tlet vy = pool[base + F.velY]!;\n\t\t\tconst damp = 1 + DRAG[TYPE.SEEKER] * dt;\n\t\t\tvx /= damp;\n\t\t\tvy /= damp;\n\t\t\tpool[base + F.velX] = vx;\n\t\t\tpool[base + F.velY] = vy;\n\t\t\tpool[base + F.posX] = pool[base + F.posX]! + (vx / aspect) * dt;\n\t\t\tpool[base + F.posY] = pool[base + F.posY]! + vy * dt;\n\t\t} else if (age < releaseDelay) {\n\t\t\t// Spring phase, per axis in VISUAL units (errX = (targetX−posX)·A).\n\t\t\t// Inlined from springStep (a = −ω²(p−target) − 2ζω·v; v += a·dt;\n\t\t\t// p += v·dt) with ω=6, ζ=0.9 so the held-glyph hot loop mints no\n\t\t\t// per-seeker objects. Kept byte-identical to springStep.\n\t\t\tconst omega = 6;\n\t\t\tconst zeta = 0.9;\n\t\t\tconst px = pool[base + F.posX]! * aspect;\n\t\t\tconst ax = -omega * omega * (px - tX * aspect) - 2 * zeta * omega * pool[base + F.velX]!;\n\t\t\tconst nvx = pool[base + F.velX]! + ax * dt;\n\t\t\tpool[base + F.velX] = nvx;\n\t\t\tpool[base + F.posX] = (px + nvx * dt) / aspect;\n\t\t\tconst py = pool[base + F.posY]!;\n\t\t\tconst ay = -omega * omega * (py - tY) - 2 * zeta * omega * pool[base + F.velY]!;\n\t\t\tconst nvy = pool[base + F.velY]! + ay * dt;\n\t\t\tpool[base + F.velY] = nvy;\n\t\t\tpool[base + F.posY] = py + nvy * dt;\n\t\t} else {\n\t\t\t// Release phase: spring off, gravity on, ballistic fall.\n\t\t\tconst vy = pool[base + F.velY]! + G * 1.0 * dt;\n\t\t\tpool[base + F.velY] = vy;\n\t\t\tpool[base + F.posX] = pool[base + F.posX]! + (pool[base + F.velX]! / aspect) * dt;\n\t\t\tpool[base + F.posY] = pool[base + F.posY]! + vy * dt;\n\t\t}\n\t}\n\n\tfunction stepSmoke(base: number, _dt: number) {\n\t\t// Two-stage expand: grow size toward 0.05 over life (§2.2 / §3.5).\n\t\tconst lifeT = pool[base + F.ttl]! > 0 ? pool[base + F.age]! / pool[base + F.ttl]! : 1;\n\t\tpool[base + F.size] = lerp(0.01, 0.05, Math.min(1, lifeT));\n\t}\n\n\tfunction brightnessCurve(type: ParticleType, base: number, lifeT: number): number {\n\t\tconst seed = pool[base + F.seed]!;\n\t\tconst age = pool[base + F.age]!;\n\t\tswitch (type) {\n\t\t\tcase TYPE.FLASH:\n\t\t\t\t// Steep decay: the flash marks the break, it must not sit on top of\n\t\t\t\t// the shell as a white disc while the sparks are opening.\n\t\t\t\treturn pool[base + F.brightness]! > 0\n\t\t\t\t\t? Math.max(pool[base + F.brightness]!, B_FLASH_AMBIENT) * Math.exp(-5.5 * lifeT)\n\t\t\t\t\t: B_FLASH_AMBIENT * Math.exp(-5.5 * lifeT);\n\t\t\tcase TYPE.SPARK: {\n\t\t\t\t// Two-stage: fast drop 2.2→~0.9, then cubic ease-in to 0 past 0.7.\n\t\t\t\tlet b = B_SPARK_STEADY + (B_SPARK_FRESH - B_SPARK_STEADY) * Math.exp(-lifeT * 8);\n\t\t\t\tif (lifeT > 0.7) {\n\t\t\t\t\tconst u = (lifeT - 0.7) / 0.3;\n\t\t\t\t\tb = Math.max(B_SPARK_TERMINAL, b * (1 - u) * (1 - u) * (1 - u));\n\t\t\t\t}\n\t\t\t\t// Crackle: flagged sparks chatter on/off at CRACKLE_HZ instead of\n\t\t\t\t// fading smoothly (field reuse — targetX is free for sparks).\n\t\t\t\tif (pool[base + F.targetX]! > 0.5) {\n\t\t\t\t\tb *= flickerNoise(seed, age, CRACKLE_HZ) > 0.5 ? 1.9 : 0.25;\n\t\t\t\t}\n\t\t\t\treturn b;\n\t\t\t}\n\t\t\tcase TYPE.EMBER: {\n\t\t\t\t// Irregular flicker 8–14 Hz, ×0.6–2.0, over a slow near-linear fade.\n\t\t\t\tconst freq = 8 + 6 * hash11(seed);\n\t\t\t\tconst mul = 0.6 + 1.4 * flickerNoise(seed, age, freq);\n\t\t\t\treturn B_EMBER_MEAN * mul * (1 - 0.6 * lifeT);\n\t\t\t}\n\t\t\tcase TYPE.SMOKE:\n\t\t\t\t// Rise then fall within the haze ceiling.\n\t\t\t\treturn lerp(B_SMOKE_MIN, B_SMOKE_MAX, Math.sin(Math.min(1, lifeT) * Math.PI));\n\t\t\tcase TYPE.SEEKER: {\n\t\t\t\tconst releaseDelay = pool[base + F.dragScale]!;\n\t\t\t\tif (age < releaseDelay) {\n\t\t\t\t\treturn B_GLYPH_HOLD * (0.85 + 0.3 * flickerNoise(seed, age, 10));\n\t\t\t\t}\n\t\t\t\t// Release pop then decay.\n\t\t\t\tconst rt = (age - releaseDelay) / 0.9;\n\t\t\t\treturn B_GLYPH_RELEASE * Math.exp(-3 * Math.max(0, rt));\n\t\t\t}\n\t\t\tcase TYPE.ROCKET:\n\t\t\tdefault:\n\t\t\t\treturn B_ASCENT_HEAD;\n\t\t}\n\t}\n\n\t// ---- writeInstances (§7) -----------------------------------------------\n\t// Per-sim display scratch: `_dispHue` holds the raw pool hue, `_dispColor`\n\t// the resolved display color. Reused every particle every frame so the hot\n\t// loop mints zero objects.\n\tconst _dispHue: Rgb = { r: 0, g: 0, b: 0 };\n\tconst _dispColor: Rgb = { r: 0, g: 0, b: 0 };\n\n\tfunction writeInstances(out: Float32Array): number {\n\t\tlet n = 0;\n\t\tfor (let idx = 0; idx < count; idx++) {\n\t\t\tconst base = idx * STRIDE;\n\t\t\tconst type = pool[base + F.type]! as ParticleType;\n\t\t\tconst bright = pool[base + F.brightness]!;\n\t\t\tconst lifeT = pool[base + F.ttl]! > 0 ? pool[base + F.age]! / pool[base + F.ttl]! : 1;\n\t\t\tdisplayColorInto(type, base, lifeT, _dispColor);\n\t\t\tconst o = n * 8;\n\t\t\tout[o + 0] = pool[base + F.posX]!;\n\t\t\tout[o + 1] = pool[base + F.posY]!;\n\t\t\tout[o + 2] = pool[base + F.size]!;\n\t\t\tout[o + 3] = _dispColor.r * bright;\n\t\t\tout[o + 4] = _dispColor.g * bright;\n\t\t\tout[o + 5] = _dispColor.b * bright;\n\t\t\tout[o + 6] = pool[base + F.velX]! * STRETCH;\n\t\t\tout[o + 7] = pool[base + F.velY]! * STRETCH;\n\t\t\tn++;\n\t\t}\n\t\treturn n;\n\t}\n\n\t// Resolve a particle's display color into `out` (no allocation). `out` must\n\t// not alias `_dispHue`.\n\tfunction displayColorInto(type: ParticleType, base: number, lifeT: number, out: Rgb): void {\n\t\t_dispHue.r = pool[base + F.r]!;\n\t\t_dispHue.g = pool[base + F.g]!;\n\t\t_dispHue.b = pool[base + F.b]!;\n\t\tconst seed = pool[base + F.seed]!;\n\t\tswitch (type) {\n\t\t\tcase TYPE.SPARK: {\n\t\t\t\tconst whiteHold = 0.04 + 0.07 * hash11(seed);\n\t\t\t\tsparkColorAtLifeInto(_dispHue, lifeT, whiteHold, seed, out);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase TYPE.EMBER:\n\t\t\t\t// Cool toward warm-white only as it dims (§1.7).\n\t\t\t\tmixOklabInto(_dispHue, COOL_END, Math.min(1, lifeT) * 0.5, out);\n\t\t\t\treturn;\n\t\t\tcase TYPE.FLASH:\n\t\t\t\t// White core crossfading to hue as it decays (§3.2).\n\t\t\t\tmixOklabInto(MAGNESIUM, _dispHue, Math.min(1, lifeT), out);\n\t\t\t\treturn;\n\t\t\tcase TYPE.SMOKE:\n\t\t\t\tout.r = SMOKE_COLOR.r;\n\t\t\t\tout.g = SMOKE_COLOR.g;\n\t\t\t\tout.b = SMOKE_COLOR.b;\n\t\t\t\treturn;\n\t\t\tcase TYPE.SEEKER:\n\t\t\tcase TYPE.ROCKET:\n\t\t\tdefault:\n\t\t\t\tout.r = _dispHue.r;\n\t\t\t\tout.g = _dispHue.g;\n\t\t\t\tout.b = _dispHue.b;\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\treturn {\n\t\tlaunch,\n\t\tspawnFlash,\n\t\tstep,\n\t\twriteInstances,\n\t\tsetAspect,\n\t\tsetKeepClear,\n\t\tsetSpawnScale,\n\t\treset,\n\t\tget count() {\n\t\t\treturn count;\n\t\t},\n\t\tget capacity() {\n\t\t\treturn capacity;\n\t\t},\n\t\tget droppedSpawns() {\n\t\t\treturn droppedSpawns;\n\t\t},\n\t\tget data() {\n\t\t\treturn pool;\n\t\t},\n\t};\n}\n","type":"registry:ui","target":"@ui/fancy/components/fireworks-hdr/fireworks-shared.ts"},{"path":"react/src/components/fireworks-hdr/index.ts","content":"\"use client\";\n\nexport { FireworksHdr } from \"./FireworksHdr\";\nexport type { FireworksHdrProps } from \"./FireworksHdr\";\n// Figure helpers for pattern shells: build a `shapePoints` outline, or feed a\n// custom one straight to `outlineBurst`.\nexport { heartOutline, starOutline, polygonOutline, outlineBurst } from \"./fireworks-shared\";\nexport type {\n\tFireworksHandle,\n\tLaunchOptions,\n\tLaunchResult,\n\tFireworksRenderLevel,\n\tShellKind,\n\tQualityTier,\n\tOutline,\n\tBurstDir,\n\tVec2,\n} from \"./fireworks-shared\";\n","type":"registry:ui","target":"@ui/fancy/components/fireworks-hdr/index.ts"},{"path":"react/src/components/fireworks-hdr/webgl2-renderer.ts","content":"\"use client\";\n\n// WebGL2 fallback renderer for FireworksHdr.\n//\n// The counterpart to webgpu-renderer.ts: same `FireworksEngineHandle` seam,\n// same 8-float instance format, same renderer-agnostic Sim (fireworks-shared.ts)\n// — so FireworksHdr.svelte drives WebGPU and WebGL2 through one code path. This\n// is the path taken when WebGPU is unavailable or its canvas configuration is\n// rejected (Firefox/Safari without WebGPU, headless, blocked adapters, …).\n//\n// WebGL has no extended tone mapping: the drawing buffer clamps at 1.0, so the\n// output is ALWAYS SDR (the §7 soft-knee ladder, never over-white). The only\n// HDR-adjacent lever is a `display-p3` drawing buffer — a wider gamut, more\n// saturated, but still SDR luminance. Honesty invariant (mirrored from\n// fluid-cursor): the color space is READ BACK after assignment, because setting\n// an unsupported value silently leaves the buffer in sRGB; renderLevel is\n// \"webgl-p3\" only when the read-back confirms it, else \"webgl-sdr\".\n//\n// Two rendering strategies, chosen by float-buffer support:\n//\n//   Path A — float accumulation (EXT_color_buffer_float present):\n//     Ping-pong two RGBA16F textures, exactly like the WebGPU passes:\n//       (a) decay    accum.read × exp(-TRAIL_FADE_RATE·dt) → accum.write\n//       (b) particles additive (one/one) velocity-stretched two-lobe quads\n//                     into accum.write (kept, not cleared), then swap\n//       (c) display  accum.read → default framebuffer, SDR soft-knee ladder\n//                     applied to the ACCUMULATED sum (§7 done properly).\n//\n//   Path B — no float buffers (the honest cheapest fallback):\n//     There is no HDR buffer to accumulate into, so render straight to the\n//     default framebuffer with `preserveDrawingBuffer` and a blend-based decay:\n//       (a) a fullscreen quad multiplies the framebuffer (rgb+alpha) by\n//           exp(-TRAIL_FADE_RATE·dt) via blendFuncSeparate(ZERO, 1-SRC_ALPHA);\n//       (b) additive particles with the SDR ladder baked PER-PARTICLE (soft-knee\n//           + saturation lift) since there is no separate display pass.\n//     Trade-off: the tone map is per-particle rather than post-accumulation and\n//     the 8-bit buffer hard-clips where bright particles overlap, so trails are\n//     a touch weaker and dense cores clip — an accepted degradation (the frame\n//     is mostly deep black with surgical bright points, so overlap is rare).\n\nimport {\n\tSTRETCH,\n\tEXPOSURE_AMBIENT,\n\tSDR_KNEE_START,\n\tSDR_CORE_SCALE,\n\tSDR_SAT_BOOST,\n\ttype FireworksRenderLevel,\n} from \"./fireworks-shared\";\nimport {\n\tTRAIL_FADE_RATE,\n\ttype FireworksEngineHandle,\n\ttype FrameUniforms,\n} from \"./webgpu-renderer\";\n\n/** Device-pixel-ratio clamp (matches the WebGPU renderer — fill-rate is the cap). */\nconst MAX_DPR = 2;\n\nconst INSTANCE_FLOATS = 8;\nconst INSTANCE_STRIDE = INSTANCE_FLOATS * 4; // bytes\n\nexport interface WebGl2FireworksOptions {\n\t/** Max instances the buffer must hold (the resolved tier's capacity). */\n\tmaxInstances: number;\n\t/** Accumulation resolution scale relative to the canvas (default 1). */\n\trenderScale?: number;\n\t/** Initial display exposure — accepted for parity; SDR pins it to 1.0. */\n\texposure?: number;\n\t/** Attempt a `display-p3` drawing buffer (wide-gamut fallback). Default true. */\n\thdr?: boolean;\n}\n\nfunction scaleByPixelRatio(input: number): number {\n\tconst dpr = Math.min(typeof window !== \"undefined\" ? window.devicePixelRatio || 1 : 1, MAX_DPR);\n\treturn Math.floor(input * dpr);\n}\n\n/**\n * Whether RGBA16F is color-renderable (EXT_color_buffer_float) on this GPU,\n * checked on a throwaway context so the real canvas can be created with the\n * right `preserveDrawingBuffer` before its one-shot context attributes lock in.\n * Extension availability is a driver capability, so the probe generalizes to\n * the real context. Returns false (→ keep preserveDrawingBuffer) if anything is\n * unavailable, which is the safe default.\n */\nfunction probeFloatAccum(): boolean {\n\tif (typeof document === \"undefined\") return false;\n\ttry {\n\t\tconst probe = document.createElement(\"canvas\").getContext(\"webgl2\");\n\t\tif (!probe) return false;\n\t\tconst has = !!probe.getExtension(\"EXT_color_buffer_float\");\n\t\t// Free the probe context promptly rather than waiting for GC.\n\t\tprobe.getExtension(\"WEBGL_lose_context\")?.loseContext();\n\t\treturn has;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ---- GLSL ES 3.00 shaders ---------------------------------------------------\n// Ports of the WGSL in webgpu-renderer.ts. The velocity-stretch and two-lobe\n// gaussian math is identical; only the SDR ladder placement differs by path.\n\nconst FULLSCREEN_VS = /* glsl */ `#version 300 es\n// Fullscreen triangle from gl_VertexID; uv round-trips y consistently with the\n// particle pass (clip.y = 1 - 2·posY there, uv = clip·0.5+0.5 here), so nothing\n// is flipped and rockets rise upward.\nconst vec2 P[3] = vec2[3](vec2(-1.0, -3.0), vec2(-1.0, 1.0), vec2(3.0, 1.0));\nout vec2 vUv;\nvoid main() {\n\tvec2 p = P[gl_VertexID];\n\tgl_Position = vec4(p, 0.0, 1.0);\n\tvUv = p * 0.5 + 0.5;\n}`;\n\nconst DECAY_FS = /* glsl */ `#version 300 es\nprecision highp float;\nin vec2 vUv;\nuniform sampler2D uAccum;\nuniform float uFade;\nout vec4 frag;\nvoid main() {\n\tfrag = texture(uAccum, vUv) * uFade;\n}`;\n\n// Shared soft-knee — byte-for-byte the WGSL `softKnee` and the JS `softKnee`\n// in fireworks-shared.ts.\nconst SOFT_KNEE_GLSL = /* glsl */ `\nfloat softKnee(float x, float knee) {\n\tif (x <= knee) return x;\n\tfloat over = x - knee;\n\tfloat span = max(1.0 - knee, 1e-3);\n\treturn knee + span * (1.0 - exp(-over / span));\n}\nvec3 sdrLadder(vec3 c, float knee, float sat) {\n\tvec3 k = vec3(softKnee(c.r, knee), softKnee(c.g, knee), softKnee(c.b, knee));\n\tfloat luma = dot(k, vec3(0.2126, 0.7152, 0.0722));\n\treturn mix(vec3(luma), k, 1.0 + sat);\n}`;\n\nconst DISPLAY_FS = /* glsl */ `#version 300 es\nprecision highp float;\nin vec2 vUv;\nuniform sampler2D uAccum;\nuniform float uKnee;\nuniform float uSat;\nout vec4 frag;\n${SOFT_KNEE_GLSL}\nvoid main() {\n\t// SDR always: exposure pinned to 1.0, soft-knee on the accumulated sum,\n\t// saturation lift, alpha clamped for premultiplied compositing.\n\tvec3 c = max(texture(uAccum, vUv).rgb, vec3(0.0));\n\tvec3 k = sdrLadder(c, uKnee, uSat);\n\tfloat a = min(max(k.r, max(k.g, k.b)), 1.0);\n\tfrag = vec4(clamp(k, vec3(0.0), vec3(1.0)), a);\n}`;\n\nconst PARTICLE_VS = /* glsl */ `#version 300 es\nlayout(location = 0) in vec2 iPos;    // normalized [0,1], top-left origin\nlayout(location = 1) in float iSize;  // half-size in screen-heights\nlayout(location = 2) in vec3 iColor;  // linear RGB · brightness\nlayout(location = 3) in vec2 iVel;    // velocity · STRETCH (screen-height displacement)\nuniform float uAspect;\nuniform float uCoreScale; // SDR trades headroom for size (§7.4); always on in WebGL\nout vec2 vLocal;\nout vec3 vColor;\nconst vec2 C[4] = vec2[4](vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0));\n// Quad oversize so the halo can fall to zero before the geometry ends.\nconst float QUAD_PAD = 1.35;\nvoid main() {\n\tvec2 c = C[gl_VertexID];\n\tfloat size = iSize * uCoreScale;\n\tfloat velLen = length(iVel);\n\tvec2 dir = velLen > 1e-6 ? iVel / velLen : vec2(1.0, 0.0);\n\tvec2 perp = vec2(-dir.y, dir.x);\n\tfloat minorHalf = size * QUAD_PAD;\n\tfloat majorHalf = clamp(size + velLen, size, size * 2.5) * QUAD_PAD;\n\tvec2 off = dir * (majorHalf * c.x) + perp * (minorHalf * c.y);\n\tvec2 p01 = iPos + vec2(off.x / uAspect, off.y);\n\tvec2 ndc = vec2(p01.x * 2.0 - 1.0, 1.0 - p01.y * 2.0);\n\tgl_Position = vec4(ndc, 0.0, 1.0);\n\tvLocal = c * QUAD_PAD;\n\tvColor = iColor;\n}`;\n\n// Windowed to exactly zero at the quad edge — an unwindowed halo still carries\n// ~7% there, which additive blending shows as a hard-edged square.\nconst PARTICLE_LOBE_GLSL = /* glsl */ `\n\tconst float QUAD_PAD = 1.35;\n\tfloat r2 = dot(vLocal, vLocal);\n\tfloat core = exp(-r2 * 6.0);\n\tfloat halo = exp(-r2 * 1.6) * 0.35;\n\tfloat win = smoothstep(QUAD_PAD, QUAD_PAD * 0.6, sqrt(r2));\n\tfloat intensity = (core + halo) * win;`;\n\n// Path A particle fragment: raw premultiplied HDR contribution; the display\n// pass owns the SDR ladder.\nconst PARTICLE_FS_ACCUM = /* glsl */ `#version 300 es\nprecision highp float;\nin vec2 vLocal;\nin vec3 vColor;\nout vec4 frag;\nvoid main() {\n${PARTICLE_LOBE_GLSL}\n\tfrag = vec4(vColor * intensity, intensity);\n}`;\n\n// Path B particle fragment: no display pass, so the SDR ladder is baked in per\n// particle before the additive write clips against the 8-bit framebuffer.\nconst PARTICLE_FS_DIRECT = /* glsl */ `#version 300 es\nprecision highp float;\nin vec2 vLocal;\nin vec3 vColor;\nuniform float uKnee;\nuniform float uSat;\nout vec4 frag;\n${SOFT_KNEE_GLSL}\nvoid main() {\n${PARTICLE_LOBE_GLSL}\n\tvec3 c = sdrLadder(vColor * intensity, uKnee, uSat);\n\tfloat a = min(max(c.r, max(c.g, c.b)), 1.0);\n\tfrag = vec4(clamp(c, vec3(0.0), vec3(1.0)), a);\n}`;\n\n// Path B fade: a fullscreen black quad whose alpha carries the decay factor.\n// blendFuncSeparate(ZERO, 1-SRC_ALPHA) multiplies the whole framebuffer\n// (rgb AND alpha) by exp(-rate·dt), so empty sky decays back to transparent.\nconst FADE_FS = /* glsl */ `#version 300 es\nprecision highp float;\nuniform float uAlpha;\nout vec4 frag;\nvoid main() {\n\tfrag = vec4(0.0, 0.0, 0.0, uAlpha);\n}`;\n\nfunction compileShader(\n\tgl: WebGL2RenderingContext,\n\ttype: number,\n\tsource: string\n): WebGLShader | null {\n\tconst shader = gl.createShader(type);\n\tif (!shader) return null;\n\tgl.shaderSource(shader, source);\n\tgl.compileShader(shader);\n\tif (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n\t\tgl.deleteShader(shader);\n\t\treturn null;\n\t}\n\treturn shader;\n}\n\nfunction linkProgram(\n\tgl: WebGL2RenderingContext,\n\tvsSrc: string,\n\tfsSrc: string\n): WebGLProgram | null {\n\tconst vs = compileShader(gl, gl.VERTEX_SHADER, vsSrc);\n\tconst fs = compileShader(gl, gl.FRAGMENT_SHADER, fsSrc);\n\tif (!vs || !fs) {\n\t\tif (vs) gl.deleteShader(vs);\n\t\tif (fs) gl.deleteShader(fs);\n\t\treturn null;\n\t}\n\tconst program = gl.createProgram();\n\tif (!program) {\n\t\tgl.deleteShader(vs);\n\t\tgl.deleteShader(fs);\n\t\treturn null;\n\t}\n\tgl.attachShader(program, vs);\n\tgl.attachShader(program, fs);\n\tgl.linkProgram(program);\n\t// Shaders are flagged for deletion; they are freed once detached with the\n\t// program at destroy() (or immediately if linking failed).\n\tgl.deleteShader(vs);\n\tgl.deleteShader(fs);\n\tif (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n\t\tgl.deleteProgram(program);\n\t\treturn null;\n\t}\n\treturn program;\n}\n\ninterface DoubleFbo {\n\treadTex: WebGLTexture;\n\twriteTex: WebGLTexture;\n\treadFbo: WebGLFramebuffer;\n\twriteFbo: WebGLFramebuffer;\n\twidth: number;\n\theight: number;\n\tswap(): void;\n}\n\n/**\n * Build the WebGL2 fallback renderer, or `null` when WebGL2 is unavailable (no\n * context, missing programs) — the caller then gives up silently (no onReady).\n * Synchronous: WebGL has no async init, but the shape matches the WebGPU seam so\n * the component treats `await startWebGpu…` and `startWebGl2…` uniformly.\n */\nexport function startWebGl2Fireworks(\n\tcanvas: HTMLCanvasElement,\n\topts: WebGl2FireworksOptions\n): FireworksEngineHandle | null {\n\t// Only Path B (no float accumulation) reads the previous frame back for its\n\t// blend-based decay and therefore needs `preserveDrawingBuffer`; Path A never\n\t// touches the default framebuffer between frames. Context attributes are\n\t// fixed at creation and the extension query that selects the path needs a\n\t// context, so probe a throwaway context first (mirrors the WebGPU\n\t// detached-probe pattern in webgpu-renderer.ts). EXT_color_buffer_float is a\n\t// driver capability, so the probe and the real context agree on the same GPU.\n\tconst wantFloatAccum = probeFloatAccum();\n\n\tlet gl: WebGL2RenderingContext | null;\n\ttry {\n\t\tgl = canvas.getContext(\"webgl2\", {\n\t\t\talpha: true,\n\t\t\tantialias: false,\n\t\t\tdepth: false,\n\t\t\tstencil: false,\n\t\t\tpremultipliedAlpha: true,\n\t\t\t// False on Path A (the common HDR-float fallback) — a real fill-rate/\n\t\t\t// memory saving; true only where Path B's frame-to-frame readback needs it.\n\t\t\tpreserveDrawingBuffer: !wantFloatAccum,\n\t\t}) as WebGL2RenderingContext | null;\n\t} catch {\n\t\tgl = null;\n\t}\n\tif (!gl) return null;\n\tconst glc = gl; // non-null alias for closures\n\n\t// HDR-adjacent: a display-p3 drawing buffer. Assigning an unsupported value\n\t// silently no-ops, so the property is READ BACK to decide the honest level.\n\tconst wantP3 = opts.hdr ?? true;\n\tlet renderLevel: FireworksRenderLevel = \"webgl-sdr\";\n\tif (wantP3 && \"drawingBufferColorSpace\" in glc) {\n\t\ttry {\n\t\t\t(\n\t\t\t\tglc as WebGL2RenderingContext & { drawingBufferColorSpace: string }\n\t\t\t).drawingBufferColorSpace = \"display-p3\";\n\t\t\tif (\n\t\t\t\t(glc as WebGL2RenderingContext & { drawingBufferColorSpace: string })\n\t\t\t\t\t.drawingBufferColorSpace === \"display-p3\"\n\t\t\t) {\n\t\t\t\trenderLevel = \"webgl-p3\";\n\t\t\t}\n\t\t} catch {\n\t\t\t// Unsupported color space: the buffer stays sRGB (webgl-sdr).\n\t\t}\n\t}\n\n\t// Float accumulation needs RGBA16F to be color-renderable (this extension) —\n\t// its absence selects the blend-based Path B. RGBA16F is texture-filterable\n\t// in core WebGL2, so no linear-filter extension is required.\n\tconst floatAccum = !!glc.getExtension(\"EXT_color_buffer_float\");\n\n\t// Defensive: the probe and the real context should always agree on the same\n\t// GPU. If they somehow disagree such that we disabled preserveDrawingBuffer\n\t// (expecting Path A) but the real context lacks float — Path B without its\n\t// required readback — bail cleanly rather than render a flickering buffer.\n\t// (No listeners/resources are allocated yet at this point.)\n\tif (wantFloatAccum && !floatAccum) {\n\t\treturn null;\n\t}\n\n\tlet renderScale = opts.renderScale ?? 1;\n\tconst instanceCapacity = Math.max(1, opts.maxInstances);\n\t// Accepted for API parity; the SDR path never applies exposure (§7.1), so it\n\t// is only stored for potential diagnostics.\n\tlet exposure = clampExposure(opts.exposure ?? EXPOSURE_AMBIENT);\n\n\tlet destroyed = false;\n\tlet lost = false;\n\tfunction onContextLost(e: Event) {\n\t\te.preventDefault(); // a prevented default keeps restore possible; we just stop\n\t\tlost = true;\n\t}\n\tcanvas.addEventListener(\"webglcontextlost\", onContextLost, false);\n\n\t// --- GPU resources -------------------------------------------------------\n\t// All declared up front (and initialized to null) so `cleanupPartial` can run\n\t// at any early bail without tripping the temporal dead zone.\n\tlet accum: DoubleFbo | null = null;\n\tlet particleProgram: WebGLProgram | null = null;\n\tlet decayProgram: WebGLProgram | null = null;\n\tlet displayProgram: WebGLProgram | null = null;\n\tlet fadeProgram: WebGLProgram | null = null;\n\tlet instanceBuffer: WebGLBuffer | null = null;\n\tlet particleVao: WebGLVertexArrayObject | null = null;\n\tlet fullscreenVao: WebGLVertexArrayObject | null = null;\n\n\tfunction cleanupPartial() {\n\t\tcanvas.removeEventListener(\"webglcontextlost\", onContextLost, false);\n\t\tif (particleProgram) glc.deleteProgram(particleProgram);\n\t\tif (decayProgram) glc.deleteProgram(decayProgram);\n\t\tif (displayProgram) glc.deleteProgram(displayProgram);\n\t\tif (fadeProgram) glc.deleteProgram(fadeProgram);\n\t\tif (instanceBuffer) glc.deleteBuffer(instanceBuffer);\n\t\tif (particleVao) glc.deleteVertexArray(particleVao);\n\t\tif (fullscreenVao) glc.deleteVertexArray(fullscreenVao);\n\t\tdestroyAccum();\n\t}\n\n\t// --- programs ------------------------------------------------------------\n\tparticleProgram = linkProgram(\n\t\tglc,\n\t\tPARTICLE_VS,\n\t\tfloatAccum ? PARTICLE_FS_ACCUM : PARTICLE_FS_DIRECT\n\t);\n\tdecayProgram = floatAccum ? linkProgram(glc, FULLSCREEN_VS, DECAY_FS) : null;\n\tdisplayProgram = floatAccum ? linkProgram(glc, FULLSCREEN_VS, DISPLAY_FS) : null;\n\tfadeProgram = floatAccum ? null : linkProgram(glc, FULLSCREEN_VS, FADE_FS);\n\n\tconst programsOk = floatAccum\n\t\t? particleProgram && decayProgram && displayProgram\n\t\t: particleProgram && fadeProgram;\n\tif (!programsOk) {\n\t\tcleanupPartial();\n\t\treturn null;\n\t}\n\n\t// Uniform locations.\n\tconst uAspect = glc.getUniformLocation(particleProgram!, \"uAspect\");\n\tconst uCoreScale = glc.getUniformLocation(particleProgram!, \"uCoreScale\");\n\tconst uPartKnee = floatAccum ? null : glc.getUniformLocation(particleProgram!, \"uKnee\");\n\tconst uPartSat = floatAccum ? null : glc.getUniformLocation(particleProgram!, \"uSat\");\n\tconst uDecayFade = decayProgram ? glc.getUniformLocation(decayProgram, \"uFade\") : null;\n\tconst uDecayAccum = decayProgram ? glc.getUniformLocation(decayProgram, \"uAccum\") : null;\n\tconst uDispAccum = displayProgram ? glc.getUniformLocation(displayProgram, \"uAccum\") : null;\n\tconst uDispKnee = displayProgram ? glc.getUniformLocation(displayProgram, \"uKnee\") : null;\n\tconst uDispSat = displayProgram ? glc.getUniformLocation(displayProgram, \"uSat\") : null;\n\tconst uFadeAlpha = fadeProgram ? glc.getUniformLocation(fadeProgram, \"uAlpha\") : null;\n\n\t// --- geometry: instance VBO + VAOs --------------------------------------\n\tinstanceBuffer = glc.createBuffer();\n\tparticleVao = glc.createVertexArray();\n\tfullscreenVao = glc.createVertexArray(); // empty; fullscreen/fade draws\n\tif (!instanceBuffer || !particleVao || !fullscreenVao) {\n\t\tcleanupPartial();\n\t\treturn null;\n\t}\n\tglc.bindVertexArray(particleVao);\n\tglc.bindBuffer(glc.ARRAY_BUFFER, instanceBuffer);\n\tglc.bufferData(glc.ARRAY_BUFFER, instanceCapacity * INSTANCE_STRIDE, glc.DYNAMIC_DRAW);\n\t// All four attributes are per-instance (divisor 1); the quad corner comes\n\t// from gl_VertexID, so there is no per-vertex attribute.\n\tglc.enableVertexAttribArray(0);\n\tglc.vertexAttribPointer(0, 2, glc.FLOAT, false, INSTANCE_STRIDE, 0);\n\tglc.vertexAttribDivisor(0, 1);\n\tglc.enableVertexAttribArray(1);\n\tglc.vertexAttribPointer(1, 1, glc.FLOAT, false, INSTANCE_STRIDE, 8);\n\tglc.vertexAttribDivisor(1, 1);\n\tglc.enableVertexAttribArray(2);\n\tglc.vertexAttribPointer(2, 3, glc.FLOAT, false, INSTANCE_STRIDE, 12);\n\tglc.vertexAttribDivisor(2, 1);\n\tglc.enableVertexAttribArray(3);\n\tglc.vertexAttribPointer(3, 2, glc.FLOAT, false, INSTANCE_STRIDE, 24);\n\tglc.vertexAttribDivisor(3, 1);\n\tglc.bindVertexArray(null);\n\n\t// --- accumulation textures (Path A only) --------------------------------\n\tfunction makeAccumTex(w: number, h: number): WebGLTexture | null {\n\t\tconst tex = glc.createTexture();\n\t\tif (!tex) return null;\n\t\tglc.bindTexture(glc.TEXTURE_2D, tex);\n\t\tglc.texImage2D(glc.TEXTURE_2D, 0, glc.RGBA16F, w, h, 0, glc.RGBA, glc.HALF_FLOAT, null);\n\t\tglc.texParameteri(glc.TEXTURE_2D, glc.TEXTURE_MIN_FILTER, glc.LINEAR);\n\t\tglc.texParameteri(glc.TEXTURE_2D, glc.TEXTURE_MAG_FILTER, glc.LINEAR);\n\t\tglc.texParameteri(glc.TEXTURE_2D, glc.TEXTURE_WRAP_S, glc.CLAMP_TO_EDGE);\n\t\tglc.texParameteri(glc.TEXTURE_2D, glc.TEXTURE_WRAP_T, glc.CLAMP_TO_EDGE);\n\t\treturn tex;\n\t}\n\n\tfunction makeFbo(tex: WebGLTexture): WebGLFramebuffer | null {\n\t\tconst fbo = glc.createFramebuffer();\n\t\tif (!fbo) return null;\n\t\tglc.bindFramebuffer(glc.FRAMEBUFFER, fbo);\n\t\tglc.framebufferTexture2D(glc.FRAMEBUFFER, glc.COLOR_ATTACHMENT0, glc.TEXTURE_2D, tex, 0);\n\t\t// Clear to transparent black so the first decay reads a clean buffer.\n\t\tglc.clearColor(0, 0, 0, 0);\n\t\tglc.clear(glc.COLOR_BUFFER_BIT);\n\t\tif (glc.checkFramebufferStatus(glc.FRAMEBUFFER) !== glc.FRAMEBUFFER_COMPLETE) {\n\t\t\tglc.deleteFramebuffer(fbo);\n\t\t\treturn null;\n\t\t}\n\t\treturn fbo;\n\t}\n\n\tfunction destroyAccum() {\n\t\tif (!accum) return;\n\t\tglc.deleteTexture(accum.readTex);\n\t\tglc.deleteTexture(accum.writeTex);\n\t\tglc.deleteFramebuffer(accum.readFbo);\n\t\tglc.deleteFramebuffer(accum.writeFbo);\n\t\taccum = null;\n\t}\n\n\tfunction initAccum(w: number, h: number): boolean {\n\t\tif (!floatAccum) return true; // Path B keeps no accumulation textures\n\t\tconst aw = Math.max(1, Math.round(w * renderScale));\n\t\tconst ah = Math.max(1, Math.round(h * renderScale));\n\t\tif (accum && accum.width === aw && accum.height === ah) return true;\n\t\tdestroyAccum();\n\t\tconst rt = makeAccumTex(aw, ah);\n\t\tconst wt = makeAccumTex(aw, ah);\n\t\tif (!rt || !wt) {\n\t\t\tif (rt) glc.deleteTexture(rt);\n\t\t\tif (wt) glc.deleteTexture(wt);\n\t\t\treturn false;\n\t\t}\n\t\tconst rf = makeFbo(rt);\n\t\tconst wf = makeFbo(wt);\n\t\tif (!rf || !wf) {\n\t\t\tglc.deleteTexture(rt);\n\t\t\tglc.deleteTexture(wt);\n\t\t\tif (rf) glc.deleteFramebuffer(rf);\n\t\t\tif (wf) glc.deleteFramebuffer(wf);\n\t\t\treturn false;\n\t\t}\n\t\taccum = {\n\t\t\treadTex: rt,\n\t\t\twriteTex: wt,\n\t\t\treadFbo: rf,\n\t\t\twriteFbo: wf,\n\t\t\twidth: aw,\n\t\t\theight: ah,\n\t\t\tswap() {\n\t\t\t\tlet t: WebGLTexture | WebGLFramebuffer = this.readTex;\n\t\t\t\tthis.readTex = this.writeTex;\n\t\t\t\tthis.writeTex = t as WebGLTexture;\n\t\t\t\tt = this.readFbo;\n\t\t\t\tthis.readFbo = this.writeFbo;\n\t\t\t\tthis.writeFbo = t as WebGLFramebuffer;\n\t\t\t},\n\t\t};\n\t\treturn true;\n\t}\n\n\tfunction resizeIfNeeded() {\n\t\tif (destroyed || lost) return;\n\t\tconst w = scaleByPixelRatio(canvas.clientWidth);\n\t\tconst h = scaleByPixelRatio(canvas.clientHeight);\n\t\tif (w > 0 && h > 0 && (canvas.width !== w || canvas.height !== h)) {\n\t\t\tcanvas.width = w;\n\t\t\tcanvas.height = h;\n\t\t\tinitAccum(w, h);\n\t\t}\n\t}\n\n\tfunction setRenderScale(scale: number) {\n\t\tif (destroyed || lost) return;\n\t\tconst next = Number.isFinite(scale) ? Math.max(0.25, Math.min(1, scale)) : 1;\n\t\tif (next === renderScale) return;\n\t\trenderScale = next;\n\t\t// Only the float-accumulation path (A) has a resolution-scaled buffer to\n\t\t// rebuild; Path B renders straight to the (full-res) default framebuffer,\n\t\t// so renderScale is inert there — the adaptive controller then falls\n\t\t// through to the spawn-density lever for relief.\n\t\tif (floatAccum && canvas.width > 0 && canvas.height > 0) initAccum(canvas.width, canvas.height);\n\t}\n\n\tfunction frame(\n\t\tdt: number,\n\t\tinstanceData: Float32Array<ArrayBuffer>,\n\t\tliveCount: number,\n\t\tuniforms: FrameUniforms\n\t) {\n\t\tif (destroyed || lost) return;\n\t\texposure = clampExposure(uniforms.exposure);\n\t\tconst count = Math.max(0, Math.min(liveCount, instanceCapacity));\n\t\tconst fade = Math.exp(-TRAIL_FADE_RATE * Math.max(0, dt));\n\t\tconst aspect = canvas.width / Math.max(1, canvas.height);\n\n\t\t// Upload live instances once per frame. Orphan the buffer first\n\t\t// (reallocate its full store) so the driver doesn't stall waiting for the\n\t\t// previous frame's draw to finish reading it — the standard streaming-VBO\n\t\t// trick for a per-frame ~80–128 KB bufferSubData. Only [0,count) is drawn,\n\t\t// so the uninitialized tail is never sampled.\n\t\tif (count > 0) {\n\t\t\tglc.bindBuffer(glc.ARRAY_BUFFER, instanceBuffer);\n\t\t\tglc.bufferData(glc.ARRAY_BUFFER, instanceCapacity * INSTANCE_STRIDE, glc.DYNAMIC_DRAW);\n\t\t\tglc.bufferSubData(glc.ARRAY_BUFFER, 0, instanceData, 0, count * INSTANCE_FLOATS);\n\t\t}\n\n\t\tif (floatAccum) {\n\t\t\tif (!accum) return;\n\t\t\t// (a) decay: accum.read × fade → accum.write.\n\t\t\tglc.bindFramebuffer(glc.FRAMEBUFFER, accum.writeFbo);\n\t\t\tglc.viewport(0, 0, accum.width, accum.height);\n\t\t\tglc.disable(glc.BLEND);\n\t\t\tglc.useProgram(decayProgram!);\n\t\t\tglc.uniform1f(uDecayFade, fade);\n\t\t\tglc.activeTexture(glc.TEXTURE0);\n\t\t\tglc.bindTexture(glc.TEXTURE_2D, accum.readTex);\n\t\t\tglc.uniform1i(uDecayAccum, 0);\n\t\t\tglc.bindVertexArray(fullscreenVao);\n\t\t\tglc.drawArrays(glc.TRIANGLES, 0, 3);\n\n\t\t\t// (b) particles: additive into accum.write (kept, not cleared).\n\t\t\tif (count > 0) {\n\t\t\t\tglc.useProgram(particleProgram!);\n\t\t\t\tglc.uniform1f(uAspect, aspect);\n\t\t\t\tglc.uniform1f(uCoreScale, SDR_CORE_SCALE);\n\t\t\t\tglc.enable(glc.BLEND);\n\t\t\t\tglc.blendEquation(glc.FUNC_ADD);\n\t\t\t\tglc.blendFunc(glc.ONE, glc.ONE);\n\t\t\t\tglc.bindVertexArray(particleVao);\n\t\t\t\tglc.drawArraysInstanced(glc.TRIANGLE_STRIP, 0, 4, count);\n\t\t\t}\n\n\t\t\t// The freshly-written buffer becomes the read source for display and\n\t\t\t// for next frame's decay.\n\t\t\taccum.swap();\n\n\t\t\t// (c) display: accum.read → default framebuffer, SDR ladder.\n\t\t\tglc.bindFramebuffer(glc.FRAMEBUFFER, null);\n\t\t\tglc.viewport(0, 0, canvas.width, canvas.height);\n\t\t\tglc.disable(glc.BLEND);\n\t\t\tglc.useProgram(displayProgram!);\n\t\t\tglc.uniform1f(uDispKnee, SDR_KNEE_START);\n\t\t\tglc.uniform1f(uDispSat, SDR_SAT_BOOST);\n\t\t\tglc.activeTexture(glc.TEXTURE0);\n\t\t\tglc.bindTexture(glc.TEXTURE_2D, accum.readTex);\n\t\t\tglc.uniform1i(uDispAccum, 0);\n\t\t\tglc.bindVertexArray(fullscreenVao);\n\t\t\tglc.drawArrays(glc.TRIANGLES, 0, 3);\n\t\t\tglc.bindVertexArray(null);\n\t\t\treturn;\n\t\t}\n\n\t\t// Path B — straight to the default framebuffer.\n\t\tglc.bindFramebuffer(glc.FRAMEBUFFER, null);\n\t\tglc.viewport(0, 0, canvas.width, canvas.height);\n\n\t\t// (a) fade the whole buffer (rgb+alpha) by exp(-rate·dt).\n\t\tglc.useProgram(fadeProgram!);\n\t\tglc.uniform1f(uFadeAlpha, 1 - fade);\n\t\tglc.enable(glc.BLEND);\n\t\tglc.blendEquation(glc.FUNC_ADD);\n\t\tglc.blendFuncSeparate(glc.ZERO, glc.ONE_MINUS_SRC_ALPHA, glc.ZERO, glc.ONE_MINUS_SRC_ALPHA);\n\t\tglc.bindVertexArray(fullscreenVao);\n\t\tglc.drawArrays(glc.TRIANGLES, 0, 3);\n\n\t\t// (b) additive particles with the SDR ladder baked in.\n\t\tif (count > 0) {\n\t\t\tglc.useProgram(particleProgram!);\n\t\t\tglc.uniform1f(uAspect, aspect);\n\t\t\tglc.uniform1f(uCoreScale, SDR_CORE_SCALE);\n\t\t\tglc.uniform1f(uPartKnee, SDR_KNEE_START);\n\t\t\tglc.uniform1f(uPartSat, SDR_SAT_BOOST);\n\t\t\tglc.blendFunc(glc.ONE, glc.ONE);\n\t\t\tglc.bindVertexArray(particleVao);\n\t\t\tglc.drawArraysInstanced(glc.TRIANGLE_STRIP, 0, 4, count);\n\t\t}\n\t\tglc.bindVertexArray(null);\n\t}\n\n\t// Prime the drawing buffer + accumulation textures at the current size.\n\t{\n\t\tconst w = scaleByPixelRatio(canvas.clientWidth) || 1;\n\t\tconst h = scaleByPixelRatio(canvas.clientHeight) || 1;\n\t\tcanvas.width = w;\n\t\tcanvas.height = h;\n\t\tif (!initAccum(w, h)) {\n\t\t\t// Float path advertised but the FBOs would not complete: bail cleanly.\n\t\t\tcleanupPartial();\n\t\t\treturn null;\n\t\t}\n\t}\n\n\treturn {\n\t\tframe,\n\t\tresizeIfNeeded,\n\t\tsetRenderScale,\n\t\textendedToneMapping: false, // WebGL has no extended tone mapping — always SDR\n\t\trenderLevel,\n\t\tget lost() {\n\t\t\treturn lost;\n\t\t},\n\t\tinstanceCapacity,\n\t\tdestroy() {\n\t\t\tdestroyed = true;\n\t\t\tcleanupPartial();\n\t\t},\n\t};\n}\n\nfunction clampExposure(v: number): number {\n\tif (!Number.isFinite(v)) return 1;\n\treturn Math.max(1, Math.min(4, v));\n}\n\nexport { STRETCH };\n","type":"registry:ui","target":"@ui/fancy/components/fireworks-hdr/webgl2-renderer.ts"},{"path":"react/src/components/fireworks-hdr/webgpu-renderer.ts","content":"\"use client\";\n\n/// <reference types=\"@webgpu/types\" />\n// WebGPU HDR renderer for FireworksHdr.\n//\n// Consumes 8-float particle instances from the DOM/GPU-free Sim (see\n// fireworks-shared.ts §7) and renders them into an `rgba16float` accumulation\n// buffer, then to a canvas configured with `colorSpace: \"display-p3\"` and\n// `toneMapping: { mode: \"extended\" }`. On an HDR display the exposure boost\n// pushes encoded values above 1.0, which extended tone mapping renders brighter\n// than SDR white; browsers that ignore `toneMapping` clamp to SDR and the\n// effect still runs (just without the over-white separation).\n//\n// Honesty invariants (mirrored from fluid-cursor/webgpu-engine.ts):\n//   - the configuration is probed on a DETACHED canvas first, because a canvas\n//     that has vended a \"webgpu\" context can never provide a WebGL one — the\n//     WebGL2 fallback must stay possible if configure() fails;\n//   - `extendedToneMapping` is read back from getConfiguration() and surfaced\n//     as data so \"webgpu-hdr\" can be told apart from a clamped fallback;\n//   - renderLevel is \"webgpu-hdr\" only when extended tone mapping is active AND\n//     the display reports `(dynamic-range: high)`;\n//   - that same predicate drives the shaders' `sdr` uniform, so an SDR display\n//     always gets the exposure-1 soft-knee path even when the browser did keep\n//     extended tone mapping (otherwise its highlights clip to white).\n//\n// Three passes per frame:\n//   (a) decay:     accum.read → accum.write × exp(-TRAIL_FADE_RATE·dt)\n//   (b) particles: instanced velocity-stretched quads, additive (one/one),\n//                  two-lobe gaussian (hot core + soft halo), into accum.write\n//                  (loadOp \"load\"), then swap\n//   (c) display:   accum.read → canvas, HDR c·exposure premultiplied, or SDR\n//                  soft-knee (§7) + saturation boost.\n\nimport { STRETCH, EXPOSURE_AMBIENT, type FireworksRenderLevel } from \"./fireworks-shared\";\n\n/**\n * Single global accumulation fade rate (1/s). Per-frame factor is\n * exp(-TRAIL_FADE_RATE·dt); at 60 fps that is ≈0.889, fading a trail to 10% in\n * ~330 ms (AD §3.3 ascent range 350–500 ms). Held deliberately short: the\n * accumulation buffer is what smears a moving particle into a line, so a slower\n * fade turns falling debris into long straight filaments instead of sparks.\n */\nexport const TRAIL_FADE_RATE = 7.0;\n\n/** Device-pixel-ratio clamp — HDR float buffers are fill-rate heavy. */\nconst MAX_DPR = 2;\n\nexport interface WebGpuFireworksOptions {\n\t/** Max instances the buffer must hold (the Sim's capacity). */\n\tmaxInstances: number;\n\t/** Accumulation resolution scale relative to the canvas (default 1). */\n\trenderScale?: number;\n\t/** Initial display exposure multiplier (clamped [1,4]). */\n\texposure?: number;\n}\n\nexport interface FrameUniforms {\n\t/** Display exposure multiplier (clamped [1,4] internally). */\n\texposure: number;\n}\n\n/**\n * Renderer control surface owned by the component. The rAF loop lives in the\n * component; it calls `frame` once per tick with the live instance data.\n */\nexport interface FireworksEngineHandle {\n\t/** Render one frame: decay, additive particles, display. */\n\tframe(\n\t\tdt: number,\n\t\tinstanceData: Float32Array<ArrayBuffer>,\n\t\tliveCount: number,\n\t\tuniforms: FrameUniforms\n\t): void;\n\t/** Reconcile the drawing buffer + accumulation textures with the CSS size. */\n\tresizeIfNeeded(): void;\n\t/**\n\t * Set the accumulation-buffer resolution scale (relative to the canvas) and\n\t * rebuild the accumulation textures at the new scale. Used by the component's\n\t * adaptive downgrade to shed GPU fill-rate. No-op where there is no separate\n\t * accumulation buffer (WebGL2 Path B).\n\t */\n\tsetRenderScale(scale: number): void;\n\t/** Whether the browser actually kept extended tone mapping (true HDR path). */\n\treadonly extendedToneMapping: boolean;\n\t/** \"webgpu-hdr\" or \"webgpu-sdr\" (never a webgl-* / none level here). */\n\treadonly renderLevel: FireworksRenderLevel;\n\treadonly lost: boolean;\n\treadonly instanceCapacity: number;\n\tdestroy(): void;\n}\n\nconst ACCUM_FORMAT: GPUTextureFormat = \"rgba16float\";\nconst INSTANCE_FLOATS = 8;\nconst INSTANCE_STRIDE = INSTANCE_FLOATS * 4; // bytes\n\nconst WGSL = /* wgsl */ `\n// ---- shared fullscreen-triangle vertex ------------------------------------\nstruct FSOut {\n\t@builtin(position) pos: vec4f,\n\t@location(0) uv: vec2f,\n}\n\n@vertex\nfn vs_fullscreen(@builtin(vertex_index) i: u32) -> FSOut {\n\tvar p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(-1.0, 1.0), vec2f(3.0, 1.0));\n\tvar out: FSOut;\n\tout.pos = vec4f(p[i], 0.0, 1.0);\n\t// v=0 is the top texel row (top-left origin, matching normalized positions).\n\tout.uv = vec2f(p[i].x, -p[i].y) * 0.5 + 0.5;\n\treturn out;\n}\n\n// ---- (a) decay ------------------------------------------------------------\nstruct DecayU { fade: f32, _pad0: f32, _pad1: f32, _pad2: f32 }\n@group(0) @binding(0) var<uniform> du: DecayU;\n@group(0) @binding(1) var accumSmp: sampler;\n@group(0) @binding(2) var accumTex: texture_2d<f32>;\n\n@fragment\nfn fs_decay(in: FSOut) -> @location(0) vec4f {\n\treturn textureSample(accumTex, accumSmp, in.uv) * du.fade;\n}\n\n// ---- (b) particles --------------------------------------------------------\nstruct ParticleU { aspect: f32, sdr: f32, coreScale: f32, _pad: f32 }\n@group(0) @binding(0) var<uniform> pu: ParticleU;\n\n// Quad oversize so the halo can fall to zero before the geometry ends.\nconst QUAD_PAD: f32 = 1.35;\n\nstruct PVOut {\n\t@builtin(position) pos: vec4f,\n\t@location(0) local: vec2f,  // quad-local coords in [-1,1]\n\t@location(1) color: vec3f,\n}\n\n@vertex\nfn vs_particle(\n\t@builtin(vertex_index) vi: u32,\n\t@location(0) iPos: vec2f,     // normalized [0,1], top-left origin\n\t@location(1) iSize: f32,      // half-size in screen-heights\n\t@location(2) iColor: vec3f,   // linear RGB · brightness\n\t@location(3) iVel: vec2f,     // velocity · STRETCH (screen-height displacement)\n) -> PVOut {\n\t// 4-vertex triangle strip corners.\n\tvar corners = array<vec2f, 4>(\n\t\tvec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(-1.0, 1.0), vec2f(1.0, 1.0)\n\t);\n\tlet c = corners[vi];\n\n\t// SDR trades brightness headroom for size — bigger, not brighter (§7.4).\n\tlet size = iSize * select(1.0, pu.coreScale, pu.sdr > 0.5);\n\n\t// Velocity-stretch: major axis along velocity, clamped 1–2.5× the minor.\n\tlet velLen = length(iVel);\n\tvar dir = vec2f(1.0, 0.0);\n\tif (velLen > 1e-6) { dir = iVel / velLen; }\n\tlet perp = vec2f(-dir.y, dir.x);\n\t// QUAD_PAD gives the halo room to reach zero INSIDE the quad; the fragment\n\t// keeps the gaussian in un-padded units so the visible size is unchanged.\n\tlet minorHalf = size * QUAD_PAD;\n\tlet majorHalf = clamp(size + velLen, size, size * 2.5) * QUAD_PAD;\n\n\t// Offset in isotropic screen-height units, then map to [0,1] (x compressed\n\t// by aspect) and to NDC (flip y for the top-left origin).\n\tlet off = dir * (majorHalf * c.x) + perp * (minorHalf * c.y);\n\tlet p01 = iPos + vec2f(off.x / pu.aspect, off.y);\n\tlet ndc = vec2f(p01.x * 2.0 - 1.0, 1.0 - p01.y * 2.0);\n\n\tvar out: PVOut;\n\tout.pos = vec4f(ndc, 0.0, 1.0);\n\tout.local = c * QUAD_PAD;\n\tout.color = iColor;\n\treturn out;\n}\n\n@fragment\nfn fs_particle(in: PVOut) -> @location(0) vec4f {\n\t// Two-lobe gaussian: tight hot core + soft wide halo.\n\tlet r2 = dot(in.local, in.local);\n\tlet core = exp(-r2 * 6.0);\n\tlet halo = exp(-r2 * 1.6) * 0.35;\n\t// Window it to exactly zero at the quad edge. The halo alone still carries\n\t// ~7% of its peak there, and additive blending turns that step into a\n\t// hard-edged square around anything bright (a flash reads as a lit box).\n\tlet win = smoothstep(QUAD_PAD, QUAD_PAD * 0.6, sqrt(r2));\n\tlet intensity = (core + halo) * win;\n\t// Additive (one/one): premultiplied contribution.\n\treturn vec4f(in.color * intensity, intensity);\n}\n\n// ---- (c) display ----------------------------------------------------------\nstruct DisplayU { exposure: f32, sdr: f32, knee: f32, satBoost: f32 }\n@group(0) @binding(0) var<uniform> disp: DisplayU;\n@group(0) @binding(1) var dispSmp: sampler;\n@group(0) @binding(2) var dispTex: texture_2d<f32>;\n\nfn softKnee(x: f32, knee: f32) -> f32 {\n\t// Below the knee: identity. Above: asymptotic approach to 1.0 (§7.2).\n\tif (x <= knee) { return x; }\n\tlet over = x - knee;\n\tlet span = max(1.0 - knee, 1e-3);\n\treturn knee + span * (1.0 - exp(-over / span));\n}\n\n@fragment\nfn fs_display(in: FSOut) -> @location(0) vec4f {\n\tlet c = max(textureSample(dispTex, dispSmp, in.uv).rgb, vec3f(0.0));\n\n\tif (disp.sdr > 0.5) {\n\t\t// SDR: exposure pinned to 1.0, soft-knee compression, saturation lift.\n\t\tvar k = vec3f(softKnee(c.r, disp.knee), softKnee(c.g, disp.knee), softKnee(c.b, disp.knee));\n\t\tlet luma = dot(k, vec3f(0.2126, 0.7152, 0.0722));\n\t\tk = mix(vec3f(luma), k, 1.0 + disp.satBoost);\n\t\tlet a = min(max(k.r, max(k.g, k.b)), 1.0);\n\t\treturn vec4f(clamp(k, vec3f(0.0), vec3f(1.0)), a);\n\t}\n\n\t// HDR: encoded values above 1.0 render brighter than SDR white. Alpha stays\n\t// clamped for premultiplied compositing; color intentionally exceeds it.\n\tlet a = min(max(c.r, max(c.g, c.b)), 1.0);\n\treturn vec4f(c * disp.exposure, a);\n}\n`;\n\nfunction scaleByPixelRatio(input: number): number {\n\tconst dpr = Math.min(typeof window !== \"undefined\" ? window.devicePixelRatio || 1 : 1, MAX_DPR);\n\treturn Math.floor(input * dpr);\n}\n\ninterface DoubleTex {\n\tread: GPUTexture;\n\twrite: GPUTexture;\n\treadView: GPUTextureView;\n\twriteView: GPUTextureView;\n\twidth: number;\n\theight: number;\n\tswap(): void;\n}\n\n/**\n * Build the WebGPU renderer, or `null` when WebGPU is unavailable / rejected\n * (the caller then tries the WebGL2 path, or gives up silently).\n */\nexport async function startWebGpuFireworks(\n\tcanvas: HTMLCanvasElement,\n\topts: WebGpuFireworksOptions\n): Promise<FireworksEngineHandle | null> {\n\ttry {\n\t\tconst gpu = navigator.gpu;\n\t\tif (!gpu) return null;\n\t\tconst adapter = await gpu.requestAdapter();\n\t\tif (!adapter) return null;\n\t\tconst device = await adapter.requestDevice();\n\n\t\tconst configuration = {\n\t\t\tdevice,\n\t\t\tformat: ACCUM_FORMAT,\n\t\t\talphaMode: \"premultiplied\",\n\t\t\tcolorSpace: \"display-p3\",\n\t\t\ttoneMapping: { mode: \"extended\" },\n\t\t} as GPUCanvasConfiguration;\n\n\t\t// Probe on a detached canvas first (see file header — keeps the WebGL2\n\t\t// fallback possible if configure() throws).\n\t\ttry {\n\t\t\tconst probe = document.createElement(\"canvas\").getContext(\"webgpu\");\n\t\t\tif (!probe) {\n\t\t\t\tdevice.destroy();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tprobe.configure(configuration);\n\t\t\tprobe.unconfigure();\n\t\t} catch {\n\t\t\tdevice.destroy();\n\t\t\treturn null;\n\t\t}\n\n\t\tconst maybeContext = canvas.getContext(\"webgpu\");\n\t\tif (!maybeContext) {\n\t\t\tdevice.destroy();\n\t\t\treturn null;\n\t\t}\n\t\tconst context: GPUCanvasContext = maybeContext;\n\t\tcontext.configure(configuration);\n\n\t\t// Surface whether extended tone mapping actually stuck (data, not just a\n\t\t// DEV log) so the render level is honest.\n\t\tlet extendedToneMapping = false;\n\t\ttry {\n\t\t\tconst applied = context.getConfiguration?.() as\n\t\t\t\t| (GPUCanvasConfiguration & { toneMapping?: { mode?: string } })\n\t\t\t\t| null;\n\t\t\textendedToneMapping = applied?.toneMapping?.mode === \"extended\";\n\t\t} catch {\n\t\t\t// getConfiguration unsupported (e.g. Safari): assume clamped output.\n\t\t}\n\n\t\t// Extended tone mapping only proves the browser kept the configuration —\n\t\t// an SDR display still clamps — so true HDR output requires both. Sampled\n\t\t// once; it does not follow the window to another monitor.\n\t\tconst hdrDisplay =\n\t\t\ttypeof window !== \"undefined\" && typeof window.matchMedia === \"function\"\n\t\t\t\t? window.matchMedia(\"(dynamic-range: high)\").matches\n\t\t\t\t: false;\n\t\t// The single HDR predicate: the shaders' SDR path and the reported render\n\t\t// level must never disagree, or an SDR display gets HDR exposure and\n\t\t// clips its highlights while the handle claims \"webgpu-sdr\".\n\t\tconst hdrOutput = extendedToneMapping && hdrDisplay;\n\n\t\tlet destroyed = false;\n\t\tlet lost = false;\n\t\tdevice.lost.then(() => {\n\t\t\tlost = true;\n\t\t});\n\n\t\tconst module = device.createShaderModule({ code: WGSL });\n\t\tlet renderScale = opts.renderScale ?? 1;\n\t\tconst instanceCapacity = Math.max(1, opts.maxInstances);\n\t\tlet exposure = clampExposure(opts.exposure ?? EXPOSURE_AMBIENT);\n\n\t\t// --- layouts + pipelines ---------------------------------------------\n\t\tconst fsLayout = device.createBindGroupLayout({\n\t\t\tentries: [\n\t\t\t\t{ binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: \"uniform\" } },\n\t\t\t\t{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: \"filtering\" } },\n\t\t\t\t{ binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: \"float\" } },\n\t\t\t],\n\t\t});\n\t\tconst particleLayout = device.createBindGroupLayout({\n\t\t\tentries: [{ binding: 0, visibility: GPUShaderStage.VERTEX, buffer: { type: \"uniform\" } }],\n\t\t});\n\n\t\tconst decayPipeline = device.createRenderPipeline({\n\t\t\tlayout: device.createPipelineLayout({ bindGroupLayouts: [fsLayout] }),\n\t\t\tvertex: { module, entryPoint: \"vs_fullscreen\" },\n\t\t\tfragment: { module, entryPoint: \"fs_decay\", targets: [{ format: ACCUM_FORMAT }] },\n\t\t\tprimitive: { topology: \"triangle-list\" },\n\t\t});\n\n\t\tconst particlePipeline = device.createRenderPipeline({\n\t\t\tlayout: device.createPipelineLayout({ bindGroupLayouts: [particleLayout] }),\n\t\t\tvertex: {\n\t\t\t\tmodule,\n\t\t\t\tentryPoint: \"vs_particle\",\n\t\t\t\tbuffers: [\n\t\t\t\t\t{\n\t\t\t\t\t\tarrayStride: INSTANCE_STRIDE,\n\t\t\t\t\t\tstepMode: \"instance\",\n\t\t\t\t\t\tattributes: [\n\t\t\t\t\t\t\t{ shaderLocation: 0, offset: 0, format: \"float32x2\" }, // pos\n\t\t\t\t\t\t\t{ shaderLocation: 1, offset: 8, format: \"float32\" }, // size\n\t\t\t\t\t\t\t{ shaderLocation: 2, offset: 12, format: \"float32x3\" }, // color\n\t\t\t\t\t\t\t{ shaderLocation: 3, offset: 24, format: \"float32x2\" }, // vel\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\tfragment: {\n\t\t\t\tmodule,\n\t\t\t\tentryPoint: \"fs_particle\",\n\t\t\t\ttargets: [\n\t\t\t\t\t{\n\t\t\t\t\t\tformat: ACCUM_FORMAT,\n\t\t\t\t\t\tblend: {\n\t\t\t\t\t\t\tcolor: { srcFactor: \"one\", dstFactor: \"one\", operation: \"add\" },\n\t\t\t\t\t\t\talpha: { srcFactor: \"one\", dstFactor: \"one\", operation: \"add\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\tprimitive: { topology: \"triangle-strip\" },\n\t\t});\n\n\t\tconst displayPipeline = device.createRenderPipeline({\n\t\t\tlayout: device.createPipelineLayout({ bindGroupLayouts: [fsLayout] }),\n\t\t\tvertex: { module, entryPoint: \"vs_fullscreen\" },\n\t\t\tfragment: { module, entryPoint: \"fs_display\", targets: [{ format: ACCUM_FORMAT }] },\n\t\t\tprimitive: { topology: \"triangle-list\" },\n\t\t});\n\n\t\tconst sampler = device.createSampler({\n\t\t\tmagFilter: \"linear\",\n\t\t\tminFilter: \"linear\",\n\t\t\taddressModeU: \"clamp-to-edge\",\n\t\t\taddressModeV: \"clamp-to-edge\",\n\t\t});\n\n\t\t// --- buffers ----------------------------------------------------------\n\t\tconst decayU = device.createBuffer({\n\t\t\tsize: 16,\n\t\t\tusage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n\t\t});\n\t\tconst particleU = device.createBuffer({\n\t\t\tsize: 16,\n\t\t\tusage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n\t\t});\n\t\tconst displayU = device.createBuffer({\n\t\t\tsize: 16,\n\t\t\tusage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n\t\t});\n\t\tconst instanceBuffer = device.createBuffer({\n\t\t\tsize: instanceCapacity * INSTANCE_STRIDE,\n\t\t\tusage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,\n\t\t});\n\t\tconst particleBindGroup = device.createBindGroup({\n\t\t\tlayout: particleLayout,\n\t\t\tentries: [{ binding: 0, resource: { buffer: particleU } }],\n\t\t});\n\n\t\tconst scratch4 = new Float32Array(4);\n\n\t\t// --- accumulation textures -------------------------------------------\n\t\tlet accum: DoubleTex | null = null;\n\t\t// The ping-pong has exactly two orientations, so the decay/display bind\n\t\t// groups are precomputed once per texture generation (one pair per stable\n\t\t// view) and selected by reference each frame — no per-frame createBindGroup.\n\t\tlet accumViewA: GPUTextureView | null = null;\n\t\tlet bgDecayA: GPUBindGroup | null = null;\n\t\tlet bgDecayB: GPUBindGroup | null = null;\n\t\tlet bgDisplayA: GPUBindGroup | null = null;\n\t\tlet bgDisplayB: GPUBindGroup | null = null;\n\n\t\tfunction makeTexture(w: number, h: number): GPUTexture {\n\t\t\treturn device.createTexture({\n\t\t\t\tsize: { width: w, height: h },\n\t\t\t\tformat: ACCUM_FORMAT,\n\t\t\t\tusage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,\n\t\t\t});\n\t\t}\n\n\t\tfunction makeDoubleTex(w: number, h: number): DoubleTex {\n\t\t\tconst a = makeTexture(w, h);\n\t\t\tconst b = makeTexture(w, h);\n\t\t\treturn {\n\t\t\t\tread: a,\n\t\t\t\twrite: b,\n\t\t\t\treadView: a.createView(),\n\t\t\t\twriteView: b.createView(),\n\t\t\t\twidth: w,\n\t\t\t\theight: h,\n\t\t\t\tswap() {\n\t\t\t\t\tconst t = this.read;\n\t\t\t\t\tconst tv = this.readView;\n\t\t\t\t\tthis.read = this.write;\n\t\t\t\t\tthis.readView = this.writeView;\n\t\t\t\t\tthis.write = t;\n\t\t\t\t\tthis.writeView = tv;\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tfunction bindGroupFor(uniform: GPUBuffer, texView: GPUTextureView): GPUBindGroup {\n\t\t\treturn device.createBindGroup({\n\t\t\t\tlayout: fsLayout,\n\t\t\t\tentries: [\n\t\t\t\t\t{ binding: 0, resource: { buffer: uniform } },\n\t\t\t\t\t{ binding: 1, resource: sampler },\n\t\t\t\t\t{ binding: 2, resource: texView },\n\t\t\t\t],\n\t\t\t});\n\t\t}\n\n\t\tfunction initTextures(w: number, h: number) {\n\t\t\tconst aw = Math.max(1, Math.round(w * renderScale));\n\t\t\tconst ah = Math.max(1, Math.round(h * renderScale));\n\t\t\tif (accum && accum.width === aw && accum.height === ah) return;\n\t\t\taccum?.read.destroy();\n\t\t\taccum?.write.destroy();\n\t\t\taccum = makeDoubleTex(aw, ah);\n\t\t\t// Capture the two stable views (readView/writeView never change identity,\n\t\t\t// only which role they play), and build the decay/display bind group for\n\t\t\t// each. `frame` picks the pair matching the current read view.\n\t\t\taccumViewA = accum.readView;\n\t\t\tbgDecayA = bindGroupFor(decayU, accum.readView);\n\t\t\tbgDecayB = bindGroupFor(decayU, accum.writeView);\n\t\t\tbgDisplayA = bindGroupFor(displayU, accum.readView);\n\t\t\tbgDisplayB = bindGroupFor(displayU, accum.writeView);\n\t\t}\n\n\t\tfunction resizeIfNeeded() {\n\t\t\tif (destroyed || lost) return;\n\t\t\tconst w = scaleByPixelRatio(canvas.clientWidth);\n\t\t\tconst h = scaleByPixelRatio(canvas.clientHeight);\n\t\t\tif (w > 0 && h > 0 && (canvas.width !== w || canvas.height !== h)) {\n\t\t\t\tcanvas.width = w;\n\t\t\t\tcanvas.height = h;\n\t\t\t\tinitTextures(w, h);\n\t\t\t}\n\t\t}\n\n\t\tfunction setRenderScale(scale: number) {\n\t\t\tif (destroyed || lost) return;\n\t\t\tconst next = Number.isFinite(scale) ? Math.max(0.25, Math.min(1, scale)) : 1;\n\t\t\tif (next === renderScale) return;\n\t\t\trenderScale = next;\n\t\t\t// Rebuild the accumulation textures at the new scale (initTextures sees a\n\t\t\t// different aw/ah and swaps in fresh textures).\n\t\t\tif (canvas.width > 0 && canvas.height > 0) initTextures(canvas.width, canvas.height);\n\t\t}\n\n\t\tfunction frame(\n\t\t\tdt: number,\n\t\t\tinstanceData: Float32Array<ArrayBuffer>,\n\t\t\tliveCount: number,\n\t\t\tuniforms: FrameUniforms\n\t\t) {\n\t\t\tif (destroyed || lost || !accum) return;\n\t\t\texposure = clampExposure(uniforms.exposure);\n\t\t\tconst sdr = hdrOutput ? 0 : 1;\n\t\t\tconst count = Math.max(0, Math.min(liveCount, instanceCapacity));\n\n\t\t\t// Upload live instances (float count must be a multiple of 4 for\n\t\t\t// writeBuffer; INSTANCE_FLOATS=8 keeps that true).\n\t\t\tif (count > 0) {\n\t\t\t\tdevice.queue.writeBuffer(instanceBuffer, 0, instanceData, 0, count * INSTANCE_FLOATS);\n\t\t\t}\n\n\t\t\t// Decay uniform: per-frame multiplicative fade.\n\t\t\tscratch4.fill(0);\n\t\t\tscratch4[0] = Math.exp(-TRAIL_FADE_RATE * Math.max(0, dt));\n\t\t\tdevice.queue.writeBuffer(decayU, 0, scratch4);\n\n\t\t\t// Particle uniform: aspect + SDR flags.\n\t\t\tscratch4.fill(0);\n\t\t\tscratch4[0] = canvas.width / Math.max(1, canvas.height);\n\t\t\tscratch4[1] = sdr;\n\t\t\tscratch4[2] = 1.4; // SDR_CORE_SCALE\n\t\t\tdevice.queue.writeBuffer(particleU, 0, scratch4);\n\n\t\t\t// Display uniform.\n\t\t\tscratch4.fill(0);\n\t\t\tscratch4[0] = exposure;\n\t\t\tscratch4[1] = sdr;\n\t\t\tscratch4[2] = 0.8; // SDR_KNEE_START\n\t\t\tscratch4[3] = 0.12; // SDR_SAT_BOOST\n\t\t\tdevice.queue.writeBuffer(displayU, 0, scratch4);\n\n\t\t\tconst encoder = device.createCommandEncoder();\n\n\t\t\t// (a) decay: accum.read → accum.write. Pick the precomputed bind group\n\t\t\t// whose bound texture is the current read view (reference compare — the\n\t\t\t// swap only reassigns roles, never the view identities).\n\t\t\tconst readIsA = accum.readView === accumViewA;\n\t\t\tconst decayBindGroup = readIsA ? bgDecayA! : bgDecayB!;\n\t\t\trunFullscreen(encoder, decayPipeline, decayBindGroup, accum.writeView, \"clear\");\n\n\t\t\t// (b) particles: additive into accum.write, preserving the decayed copy.\n\t\t\tif (count > 0) {\n\t\t\t\tconst pass = encoder.beginRenderPass({\n\t\t\t\t\tcolorAttachments: [{ view: accum.writeView, loadOp: \"load\", storeOp: \"store\" }],\n\t\t\t\t});\n\t\t\t\tpass.setPipeline(particlePipeline);\n\t\t\t\tpass.setBindGroup(0, particleBindGroup);\n\t\t\t\tpass.setVertexBuffer(0, instanceBuffer);\n\t\t\t\tpass.draw(4, count);\n\t\t\t\tpass.end();\n\t\t\t}\n\n\t\t\t// The freshly-written buffer becomes the read buffer for display and for\n\t\t\t// next frame's decay. After the swap the read view has flipped, so the\n\t\t\t// display bind group is the OTHER orientation.\n\t\t\taccum.swap();\n\t\t\tconst displayBindGroup = readIsA ? bgDisplayB! : bgDisplayA!;\n\n\t\t\t// (c) display: accum.read → canvas.\n\t\t\trunFullscreen(\n\t\t\t\tencoder,\n\t\t\t\tdisplayPipeline,\n\t\t\t\tdisplayBindGroup,\n\t\t\t\tcontext.getCurrentTexture().createView(),\n\t\t\t\t\"clear\"\n\t\t\t);\n\n\t\t\tdevice.queue.submit([encoder.finish()]);\n\t\t}\n\n\t\tfunction runFullscreen(\n\t\t\tencoder: GPUCommandEncoder,\n\t\t\tpipeline: GPURenderPipeline,\n\t\t\tbindGroup: GPUBindGroup,\n\t\t\ttarget: GPUTextureView,\n\t\t\tloadOp: GPULoadOp\n\t\t) {\n\t\t\tconst pass = encoder.beginRenderPass({\n\t\t\t\tcolorAttachments: [\n\t\t\t\t\t{ view: target, loadOp, storeOp: \"store\", clearValue: { r: 0, g: 0, b: 0, a: 0 } },\n\t\t\t\t],\n\t\t\t});\n\t\t\tpass.setPipeline(pipeline);\n\t\t\tpass.setBindGroup(0, bindGroup);\n\t\t\tpass.draw(3);\n\t\t\tpass.end();\n\t\t}\n\n\t\tconst renderLevel: FireworksRenderLevel = hdrOutput ? \"webgpu-hdr\" : \"webgpu-sdr\";\n\n\t\t// Prime the drawing buffer + accumulation textures at the current size.\n\t\t{\n\t\t\tconst w = scaleByPixelRatio(canvas.clientWidth) || 1;\n\t\t\tconst h = scaleByPixelRatio(canvas.clientHeight) || 1;\n\t\t\tcanvas.width = w;\n\t\t\tcanvas.height = h;\n\t\t\tinitTextures(w, h);\n\t\t}\n\n\t\treturn {\n\t\t\tframe,\n\t\t\tresizeIfNeeded,\n\t\t\tsetRenderScale,\n\t\t\textendedToneMapping,\n\t\t\trenderLevel,\n\t\t\tget lost() {\n\t\t\t\treturn lost;\n\t\t\t},\n\t\t\tinstanceCapacity,\n\t\t\tdestroy() {\n\t\t\t\tdestroyed = true;\n\t\t\t\taccum?.read.destroy();\n\t\t\t\taccum?.write.destroy();\n\t\t\t\tdevice.destroy();\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction clampExposure(v: number): number {\n\tif (!Number.isFinite(v)) return 1;\n\treturn Math.max(1, Math.min(4, v));\n}\n\n// STRETCH is re-exported for callers that build instance data by hand; the\n// component uses the Sim's writeInstances which already bakes it in.\nexport { STRETCH };\n","type":"registry:ui","target":"@ui/fancy/components/fireworks-hdr/webgpu-renderer.ts"}],"meta":{"license":"MIT","package":"fancy-ui-react","version":"0.7.0","source":"https://fancy-ui.rama.app/docs/components/fireworks-hdr?framework=react"}}