@viggle/splat-engine-three 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +42 -3
- package/dist/chunks/{chunk-BHNNSHJG.js → chunk-SASRTGRD.js} +1095 -71
- package/dist/chunks/chunk-SASRTGRD.js.map +7 -0
- package/dist/index.js +15 -1
- package/dist/types/character.d.ts +3 -1
- package/dist/types/index.d.ts +5 -3
- package/dist/types/math.d.ts +191 -13
- package/dist/types/physics/ammo.d.ts +7 -0
- package/dist/types/physics/index.d.ts +2 -2
- package/dist/types/physics/joints.d.ts +49 -0
- package/dist/types/physics/physics-world.d.ts +2 -1
- package/dist/types/relight/splat-relight.d.ts +19 -0
- package/dist/types/scene.d.ts +57 -7
- package/dist/types/splat/backend.d.ts +10 -1
- package/dist/types/splat/quality.d.ts +45 -0
- package/dist/types/splat/splat-mesh.d.ts +14 -1
- package/dist/types/splat/splat.d.ts +6 -0
- package/dist/types/splat/webgl/shaders.d.ts +1 -1
- package/dist/types/splat/webgl/splat-mesh.d.ts +1 -0
- package/dist/types/splat/webgpu/splat-mesh.d.ts +1 -0
- package/dist/webgpu.js +76 -28
- package/dist/webgpu.js.map +3 -3
- package/package.json +1 -1
- package/dist/chunks/chunk-BHNNSHJG.js.map +0 -7
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../src/three/splat-character.ts", "../../src/character.ts", "../../src/math.ts", "../../src/loader/skeleton/skeleton-data.ts", "../../src/loader/skeleton/skeleton-data-441.ts", "../../src/loader/skeleton/index.ts", "../../src/anim/animation-conversion.ts", "../../src/loader/animation/animation-glb.ts", "../../src/loader/shared/asset-fetch.ts", "../../src/loader/shared/bin-cache.ts", "../../src/animation.ts", "../../src/armature.ts", "../../src/anim/bind-pose.ts", "../../src/anim/rest-relative.ts", "../../src/anim/spline.ts", "../../src/anim/keyframe-splines.ts", "../../src/skeletal/pose.ts", "../../src/skeletal/animation-player.ts", "../../src/skeletal/bone-stretch.ts", "../../src/skeletal/skeleton.ts", "../../src/splat/bone-binding.ts", "../../src/skeletal/splat-skinning.ts", "../../src/splat/reveal-bake.ts", "../../src/engine.ts", "../../src/splat/packed-splats.ts", "../../src/splat/importance.ts", "../../src/splat/quality.ts", "../../src/splat/prune.ts", "../../src/splat/splat.ts", "../../src/splat/cut-groups.ts", "../../src/splat/reveal-look.ts", "../../src/splat/splat-mesh.ts", "../../src/splat/webgl/splat-mesh.ts", "../../src/splat/depth-sort.ts", "../../src/splat/color-modifier.ts", "../../src/splat/transform-palette.ts", "../../src/splat/webgl/shaders.ts", "../../src/splat/webgl/backend.ts", "../../src/loader/environment/ply.ts", "../../src/loader/shared/inflate.ts", "../../src/loader/environment/spz-decode.ts", "../../src/loader/shared/pack-splats-task.ts", "../../src/loader/shared/sog-decode.ts", "../../src/loader/shared/decode-worker.ts", "../../src/loader/environment/spz.ts", "../../src/loader/shared/sog.ts", "../../src/loader/shared/asset-loader.ts", "../../src/loader/character/types.ts", "../../src/loader/character/legacy/interleaved-splat.ts", "../../src/loader/character/legacy/planar-splat.ts", "../../src/loader/character/legacy/index.ts", "../../src/loader/character/v1/decode.ts", "../../src/loader/character/index.ts", "../../src/loader/character/load.ts", "../../src/skeletal/bone-mask.ts", "../../src/three/loaders.ts", "../../src/scene.ts", "../../src/effects/postfx/camera-frame.ts", "../../src/effects/postfx/frame-shaders.ts", "../../src/effects/postfx/program.ts", "../../src/effects/postfx/webgl-program.ts", "../../src/effects/postfx/uniforms.ts", "../../src/effects/postfx/frame-renderer.ts", "../../src/effects/postfx/postfx.ts", "../../src/physics/physics-world.ts", "../../src/physics/ammo.ts", "../../src/physics/rigid-body.ts", "../../src/effects/postfx/base-capturing-pass.ts", "../../src/effects/postfx/mask.ts", "../../src/effects/pixelart/pixelart-shaders.ts", "../../src/effects/pixelart/pixelart-effect.ts", "../../src/effects/outlines/outline-shaders.ts", "../../src/effects/outlines/outline-effect.ts", "../../src/physics/joints.ts", "../../src/skeletal/ragdoll.ts", "../../src/skeletal/ragdoll-config.ts", "../../src/environment.ts", "../../src/loader/environment/lod-bundle.ts", "../../src/three/spz-loader.ts", "../../src/lighting/sun-light.ts", "../../src/lighting/color.ts", "../../src/lighting/sky-light.ts", "../../src/lighting/point-light.ts", "../../src/effects/vfx/pool.ts", "../../src/effects/vfx/json-vfx-prefab.ts", "../../src/effects/vfx/layers/mesh.ts", "../../src/effects/vfx/layers/shared.ts", "../../src/effects/vfx/layers/particle.ts", "../../src/effects/vfx/layers/sprite.ts", "../../src/effects/vfx/layers/shader.ts", "../../src/effects/vfx/layer-renderer.ts", "../../src/effects/vfx/stage.ts", "../../src/effects/vfx/prewarm.ts", "../../src/presets/camera/third-person-camera.ts", "../../src/presets/character/character-reveal.ts", "../../src/skeletal/body-parts.ts", "../../src/presets/character/body-shape.ts", "../../src/presets/character/socket-loadout.ts", "../../src/presets/visual/bone-overlay.ts", "../../src/presets/vfx/mesh-flash.ts", "../../src/loader/shared/glb.ts", "../../src/relight/splat-relight.ts", "../../src/proxy/environment-input.ts", "../../src/proxy/environment-source.ts", "../../src/proxy/splat-source.ts", "../../src/proxy/proxy-debug.ts", "../../src/proxy/voxelizer.ts", "../../src/relight/relight-pass.ts", "../../src/splat/relight-binding.ts", "../../src/relight/backend.ts", "../../src/relight/relight-placeholder.ts", "../../src/relight/shadow-bias.ts", "../../src/relight/webgl-backend.ts", "../../src/relight/relight-shaders.ts"],
|
|
4
|
-
"sourcesContent": ["import { Color, Matrix3, Matrix4, Object3D, SRGBColorSpace, Vector3 } from 'three';\nimport type { ColorRepresentation, Object3DEventMap } from 'three';\n\nimport type { Animation } from '../animation';\nimport type { Armature } from '../armature';\nimport { Character } from '../character';\nimport type { SplatEngine } from '../engine';\nimport type { CharacterBundle } from '../loader/character/load';\nimport type { BodyRegion, BoneMask } from '../skeletal/bone-mask';\nimport type { SplatColorModifier } from '../splat/color-modifier';\nimport type { RevealLook } from '../splat/reveal-look';\nimport type { Splat } from '../splat/splat';\n\n/**\n * What a clip's horizontal travel does to the character.\n *\n * - `'off'` - the clip plays in place.\n * - `'apply'` - the character's body moves with the clip, beneath\n * {@link SplatCharacter.position}, which stays where you put it.\n * - `'extract'` - the clip plays in place and its travel is handed to you by\n * {@link SplatCharacter.consumeRootMotion}, to feed a controller or physics.\n *\n * @group Characters & Animation\n */\nexport type SplatRootMotion = 'off' | 'apply' | 'extract';\n\n/** @group Characters & Animation */\nexport interface SplatPlayOptions {\n /** Repeat when the clip ends. Default `true`. */\n loop?: boolean;\n}\n\n/** @group Characters & Animation */\nexport interface SplatCrossFadeOptions extends SplatPlayOptions {\n /** Start the new clip at the same fraction of its length the old one had reached. Default `false`. */\n preserveTime?: boolean;\n}\n\n/** @group Characters & Animation */\nexport interface SplatLayerOptions {\n /** The bones the layer drives, as a named region. Give this or `mask`. */\n region?: BodyRegion;\n /** The bones the layer drives, as an explicit mask. Give this or `region`. */\n mask?: BoneMask;\n /** Repeat when the clip ends. Default `true`. */\n loop?: boolean;\n /** Seconds to blend the layer in. Default `0`. */\n fadeDuration?: number;\n /** How strongly the layer overrides the base pose, 0..1. Default `1`. */\n weight?: number;\n}\n\n/**\n * Events a {@link SplatCharacter} dispatches, alongside the usual `Object3D` ones.\n * @group Characters & Animation\n */\nexport interface SplatCharacterEventMap extends Object3DEventMap {\n /** A non-looping clip reached its last frame. */\n finished: { clip: Animation };\n /** A looping clip wrapped around to its start. */\n loop: { clip: Animation };\n /** An event authored into the clip was crossed. */\n clipevent: { clip: Animation | null; name: string; frame: number; payload?: unknown };\n}\n\nconst _color = new Color();\nconst _rgb = { r: 0, g: 0, b: 0 };\nconst _groundDelta = new Vector3();\nconst _parentInverseLinear = new Matrix3();\nlet _clipSerial = 0;\n\n/**\n * A gaussian-splat character, as a three.js object.\n *\n * Add it to a scene, move it with `position` / `rotation` / `scale`, and call\n * {@link SplatCharacter.update} once per frame - the role `AnimationMixer.update`\n * plays for a skinned mesh. Create one with {@link VSplatLoader}.\n *\n * ```ts\n * const character = await new VSplatLoader().loadAsync('/assets/hero.vsplat');\n * scene.add(character);\n * character.position.set(1, 0, 0);\n *\n * const run = await new SplatClipLoader().loadAsync('/assets/run.glb');\n * character.play(run);\n *\n * renderer.setAnimationLoop(() => {\n * character.update(clock.getDelta());\n * renderer.render(scene, camera);\n * });\n * ```\n *\n * `position` is the model origin. A character in its rest pose stands on it;\n * how closely a clip keeps the feet on it depends on the clip.\n *\n * Animation is driven by this class rather than by `AnimationMixer`: a splat\n * character has no `Bone` hierarchy for a mixer to write to. Clips are\n * {@link Animation} objects from {@link SplatClipLoader}.\n *\n * @group Characters & Animation\n */\nexport class SplatCharacter extends Object3D<SplatCharacterEventMap> {\n /** Type flag, in the three.js manner. */\n readonly isSplatCharacter = true;\n override readonly type: string = 'SplatCharacter';\n\n /**\n * The engine-level character this object wraps. Everything not surfaced\n * here - multi-level LOD, variant splats, animation LOD - is reachable\n * through it.\n */\n readonly character: Character;\n\n private readonly _engine: SplatEngine;\n private readonly _bundles: CharacterBundle[];\n private _clip: Animation | null = null;\n private _loop = true;\n private _finishedSent = false;\n private _rootMotion: SplatRootMotion = 'off';\n /** Optional world-space floor height. When set, the lowest visible splats\n * are aligned to it after each pose. Useful for dances with no airborne\n * phase; leave null for clips with intentional jumps or flight. */\n groundLockY: number | null = null;\n private _disposed = false;\n\n /**\n * @param bundles - Decoded character bundles, finest level of detail first.\n * They are read, never modified, so clones share them.\n * @internal Use {@link VSplatLoader}.\n */\n constructor(engine: SplatEngine, bundles: CharacterBundle[], name = 'character') {\n super();\n this.name = name;\n this._engine = engine;\n this._bundles = bundles;\n\n const character = Character.fromBundles(engine, bundles, name);\n // This object's own update() drives the character, and this object is its\n // parent - not the engine's update loop or its content root.\n character.detachAutoUpdate();\n this.add(character.armature.object3D);\n this.character = character;\n\n character.onAnimEvent((e) => {\n this.dispatchEvent({ type: 'clipevent', clip: this._clip, name: e.name, frame: e.frame, payload: e.payload });\n });\n }\n\n /** The rig: bone names, bone matrices, bone-length scaling. */\n get armature(): Armature {\n return this.character.armature;\n }\n\n /** The splats that draw this character, one per level of detail. */\n get splats(): readonly Splat[] {\n return this.character.splats;\n }\n\n // \u2500\u2500 Per-frame \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Advance the animation by `delta` seconds and pose the splats. Call once\n * per frame, before rendering.\n */\n update(delta: number): void {\n if (this._disposed) return;\n const armature = this.character.armature;\n const before = armature.animationTime;\n this.character.update(delta);\n\n if (this.groundLockY !== null) {\n const low = this.character.getLowestWorldY();\n if (low !== null && Number.isFinite(low)) {\n _groundDelta.set(0, this.groundLockY - low, 0);\n if (this.parent) {\n this.parent.updateWorldMatrix(true, false);\n _parentInverseLinear.setFromMatrix4(this.parent.matrixWorld).invert();\n _groundDelta.applyMatrix3(_parentInverseLinear);\n }\n this.position.add(_groundDelta);\n }\n }\n\n const clip = this._clip;\n if (!clip || !armature.isPlaying) return;\n if (this._loop) {\n // A looping clip wraps its time; nothing else moves it backwards.\n if (delta > 0 && !armature.paused && armature.animationTime < before) {\n this.dispatchEvent({ type: 'loop', clip });\n }\n } else if (armature.isFinished && !this._finishedSent) {\n this._finishedSent = true;\n this.dispatchEvent({ type: 'finished', clip });\n }\n }\n\n // \u2500\u2500 Playback \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Start `clip` from its first frame, cutting from whatever was playing. */\n play(clip: Animation, options?: SplatPlayOptions): this {\n const loop = options?.loop ?? true;\n const armature = this.character.armature;\n armature.frameRate = clip.frameRate;\n this.character.playAnimation(this._keyFor(clip), { loop, rootMotion: this._rootMotion === 'apply' });\n this._started(clip, loop);\n return this;\n }\n\n /** Blend from the current pose into `clip` over `duration` seconds. */\n crossFadeTo(clip: Animation, duration = 0.3, options?: SplatCrossFadeOptions): this {\n const loop = options?.loop ?? true;\n const armature = this.character.armature;\n armature.frameRate = clip.frameRate;\n this.character.crossfadeTo(this._keyFor(clip), {\n duration,\n loop,\n rootMotion: this._rootMotion === 'apply',\n preserveTime: options?.preserveTime,\n });\n this._started(clip, loop);\n return this;\n }\n\n /** Stop playback and return to the rest pose, blending over `fadeDuration` seconds. */\n stop(fadeDuration = 0): this {\n this.character.stop(fadeDuration);\n this._clip = null;\n return this;\n }\n\n /**\n * Play `clip` on a named layer that overrides part of the body - an upper\n * body wave over a full-body run, say. Calling it again with the same layer\n * name replaces what that layer plays.\n */\n playLayer(layer: string, clip: Animation, options: SplatLayerOptions): this {\n this.character.playLayer(layer, this._keyFor(clip), {\n region: options.region,\n mask: options.mask,\n loop: options.loop,\n crossfade: options.fadeDuration,\n weight: options.weight,\n });\n return this;\n }\n\n setLayerWeight(layer: string, weight: number): this {\n this.character.setLayerWeight(layer, weight);\n return this;\n }\n\n stopLayer(layer: string, fadeDuration = 0): this {\n this.character.stopLayer(layer, fadeDuration);\n return this;\n }\n\n /** The clip the base track is playing, or `null`. */\n get clip(): Animation | null {\n return this.character.isPlaying ? this._clip : null;\n }\n\n get isPlaying(): boolean {\n return this.character.isPlaying;\n }\n\n get paused(): boolean {\n return this.character.armature.paused;\n }\n\n set paused(value: boolean) {\n this.character.armature.paused = value;\n this.character.setAllLayersPaused(value);\n }\n\n /** Playback speed multiplier. `1` is the authored speed. */\n get timeScale(): number {\n return this.character.playbackSpeed;\n }\n\n set timeScale(value: number) {\n this.character.playbackSpeed = value;\n }\n\n /** Position in the current clip, in seconds. */\n get time(): number {\n const armature = this.character.armature;\n return armature.animationTime / armature.frameRate;\n }\n\n set time(seconds: number) {\n const armature = this.character.armature;\n armature.animationTime = seconds * armature.frameRate;\n if (!this._loop) this._finishedSent = armature.isFinished;\n }\n\n /** Length of the current clip in seconds, or `0` when nothing is playing. */\n get duration(): number {\n const armature = this.character.armature;\n return armature.animationDuration / armature.frameRate;\n }\n\n // \u2500\u2500 Root motion \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** See {@link SplatRootMotion}. Applies to the current clip and every later one. */\n get rootMotion(): SplatRootMotion {\n return this._rootMotion;\n }\n\n set rootMotion(mode: SplatRootMotion) {\n this._rootMotion = mode;\n this.character.armature.rootMotionMode = mode;\n }\n\n /**\n * The clip's horizontal travel since the last call, in this object's local\n * space. Non-zero only in `'extract'` mode. `y` is always `0`.\n */\n consumeRootMotion(target: Vector3 = new Vector3()): Vector3 {\n const { dx, dz } = this.character.consumeRootMotionDelta();\n return target.set(dx, 0, dz);\n }\n\n // \u2500\u2500 Appearance \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Blend the character's colour toward `color` by `amount` (0..1) - a hit\n * flash, a selection highlight. `amount = 0` restores the authored colour.\n */\n setTint(color: ColorRepresentation, amount = 1): this {\n // Splat colour is display-referred, so the tint is taken in sRGB.\n _color.set(color).getRGB(_rgb, SRGBColorSpace);\n this.character.setTint(amount, _rgb);\n return this;\n }\n\n /**\n * Multiply the character's colour by `color`, by `amount` (0..1): darkens or\n * browns while keeping the character's own variation. {@link setTint}\n * returns to the blend.\n */\n setTintMultiply(color: ColorRepresentation, amount = 1): this {\n _color.set(color).getRGB(_rgb, SRGBColorSpace);\n this.character.setTintMultiply(amount, _rgb);\n return this;\n }\n\n /** Contrast and saturation multipliers for the character's colour. `(1, 1)` is unchanged. */\n setGrade(contrast: number, saturation: number): this {\n for (const splat of this.character.splats) splat.setGrade(contrast, saturation);\n return this;\n }\n\n /** Alpha multiplier for the whole character, 0..1. `1` draws it unchanged. */\n get opacity(): number {\n return this.character.splats[0]?.opacity ?? 1;\n }\n\n set opacity(value: number) {\n this.character.setOpacity(value);\n }\n\n /**\n * Reveal the character with a bright front walking from feet to head:\n * `amount` 0 is hidden, 1 is the character unchanged. `inverse` keeps the\n * part ahead of the front, for a character going out. The first call below\n * 1 prepares the effect, which costs a frame on a large character; call\n * {@link prepareReveal} after loading to pay it up front.\n */\n setReveal(amount: number, inverse = false): this {\n this.character.setReveal(amount, inverse);\n return this;\n }\n\n /** How the reveal looks; unset fields keep their value. See {@link RevealLook}. */\n setRevealLook(look: RevealLook): this {\n this.character.setRevealLook(look);\n return this;\n }\n\n /** Pay the reveal's one-time setup now rather than on its first frame. */\n prepareReveal(): this {\n this.character.prepareReveal();\n return this;\n }\n\n /**\n * Run a colour function of your own on every splat after the engine's\n * colour work; `null` removes it. See {@link SplatColorModifier}.\n */\n setColorModifier(modifier: SplatColorModifier | null): this {\n this.character.setColorModifier(modifier);\n return this;\n }\n\n // \u2500\u2500 Performance \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Draw fewer of this character's splats as it gets further away.\n *\n * `nearFraction` of them at `nearDist` and closer, `farFraction` at\n * `farDist` and beyond, interpolated in between. Which splats those are is\n * decided by importance within each 4 cm cell, so the character thins evenly\n * rather than losing a region of itself. See {@link Character.setSplatCountLod}.\n *\n * Needs a camera on the engine to measure distance from - the same one the\n * other distance throttles use:\n *\n * ```ts\n * SplatEngine.shared.camera = camera;\n * character.setSplatCountLod({ nearDist: 4, farDist: 16, farFraction: 0.25 });\n * ```\n */\n setSplatCountLod(opts: {\n nearDist: number;\n farDist: number;\n nearFraction?: number;\n farFraction?: number;\n }): this {\n this.character.setSplatCountLod(opts);\n return this;\n }\n\n /** Stop thinning: every splat is drawn again, at any distance. */\n disableSplatCountLod(): this {\n this.character.disableSplatCountLod();\n return this;\n }\n\n // \u2500\u2500 Rig \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Bone names, in rig order. */\n get boneNames(): readonly string[] {\n return this.character.armature.rigBoneNames;\n }\n\n /**\n * World matrix of a bone as of the last {@link SplatCharacter.update} - for\n * attaching a prop to a hand, or aiming a camera at a head.\n *\n * @returns `target`, or `null` when the rig has no bone of that name.\n */\n getBoneWorldMatrix(name: string, target: Matrix4 = new Matrix4()): Matrix4 | null {\n const armature = this.character.armature;\n const index = armature.rigBoneNames.indexOf(name);\n const matrix = index < 0 ? null : armature.getBoneWorldMatrix(index);\n return matrix ? target.fromArray(matrix.data) : null;\n }\n\n // \u2500\u2500 Lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * A second character from the same decoded data, at the same transform. The\n * copy starts in the rest pose with nothing playing; it does not share this\n * one's animation state.\n */\n override clone(): this {\n const copy = new SplatCharacter(this._engine, this._bundles, this.name);\n copy.position.copy(this.position);\n copy.quaternion.copy(this.quaternion);\n copy.scale.copy(this.scale);\n copy.visible = this.visible;\n copy.renderOrder = this.renderOrder;\n copy.layers.mask = this.layers.mask;\n copy.userData = { ...this.userData };\n copy.rootMotion = this._rootMotion;\n copy.groundLockY = this.groundLockY;\n return copy as this;\n }\n\n /**\n * Release every GPU resource the character holds. The object stays in the\n * scene graph, empty; remove it yourself if you no longer want it there.\n */\n override dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this.character.destroy();\n super.dispose();\n }\n\n private _keyFor(clip: Animation): string {\n // The engine addresses clips by name; give each clip object one of its own.\n if (!clip.registeredName || this._engine.skeletalAnimationLibrary.get(clip.registeredName) === undefined) {\n clip.register(this._engine, `clip:${++_clipSerial}:${clip.name}`);\n }\n return clip.registeredName!;\n }\n\n private _started(clip: Animation, loop: boolean): void {\n this._clip = clip;\n this._loop = loop;\n this._finishedSent = false;\n // Starting a clip resets the armature to in-place or applied; restore 'extract'.\n this.character.armature.rootMotionMode = this._rootMotion;\n }\n}\n", "import { Euler, MathUtils, Vector3 } from 'three';\nimport type { Object3D } from 'three';\n\nimport { Animation, clearAnimRootRotation } from './animation';\nimport { Armature } from './armature';\nimport type { SplatEngine } from './engine';\nimport type { SplatColorModifier } from './splat/color-modifier';\nimport { EngineDisposedError } from './engine';\nimport { loadCharacterBundle, loadCharacterBundleFromBytes, prefetchCharacterBundle } from './loader/character/load';\nimport type { CharacterBundle } from './loader/character/load';\nimport { Vec3 } from './math';\nimport type { AnimEventCallback } from './skeletal/animation-player';\nimport { makeRegionMask } from './skeletal/bone-mask';\nimport type { BodyRegion, BoneMask } from './skeletal/bone-mask';\nimport { Splat } from './splat/splat';\nimport type { RevealLook } from './splat/reveal-look';\n\n/**\n * Options for {@link Character.load}.\n *\n * @group Characters & Animation\n */\nexport interface LoadCharacterOptions {\n /**\n * Name used for the armature and any embedded animation registered on the\n * engine. Defaults to the file basename (stripped of extension).\n */\n name?: string;\n /** Initial position, `y` at GROUND CONTACT - same convention as\n * {@link Character.setPosition}. Defaults to the origin. */\n position?: { x: number; y: number; z: number };\n /**\n * Which rest translations pose the rig.\n *\n * - `'auto'` (default) - `'bundled'` for a bundle carrying a correction\n * receipt, `'builtin'` for one without. Apps should pass nothing: the\n * discriminator lives in the file, so the decision belongs here rather than\n * in each consuming app, where the copies would otherwise drift apart.\n * - `'builtin'` - the canonical std-male tables from the skeleton library.\n * Every character is posed on one shared skeleton.\n * - `'bundled'` - the per-character `joints` array for BODY bones, canonical\n * for `FACIAL_*` ones and for toes. See `keepsCanonicalRest` for the\n * measurements behind both exclusions.\n *\n * The explicit values exist for the comparison scenes, which show one\n * character both ways on purpose.\n *\n * The body tables disagree, and not subtly: on a sample character 81 of 86\n * body bones differ by more than 1 mm, worst 36 mm at `foot_r`, with the\n * canonical limbs uniformly SHORTER (thigh -14.7 mm, calf -36.4 mm). That\n * leaves the canonical knee ~36 mm high and the canonical foot floating\n * ~72 mm off the ground on a character whose own skeleton reaches it.\n *\n * At rest the choice is invisible - skinning cancels `worldPose \u00B7 inverseBind`\n * to identity either way. It only shows once a joint ROTATES, because the\n * rotation happens about the chosen pivot: a splat at the true knee swung\n * about a centre 36 mm away lands ~51 mm off through a 90\u00B0 bend.\n *\n * Clips are authored on the canonical rig - their body translations match\n * `REST_TRANSLATIONS_441` to 0.0007 mm - which USED to make a canonical bind\n * the only one that agreed with the pose, and `'bundled'` a diagnostic.\n * That is no longer so: a bone whose translation never changes across a clip\n * is now read as a rest declaration and left to the character\n * (`Animation`'s `translationMask`, derived for `.anim`, GLB and the\n * `.bin`-embedded clip alike). Playback is effectively rotation-only for\n * every bone the clip does not actually translate - 341 of 342 on the body\n * rig, 829 of 1185 on the full one - so `'bundled'` now inherits the\n * character's own lengths instead of having them overwritten.\n *\n * Bundles carry translations only, never rotations, so `'bundled'` yields\n * per-character bone LENGTHS with canonical joint ORIENTATIONS - a hybrid.\n * Falls back to `'builtin'` when the bundle has no joints (older files) or\n * the array length disagrees with the bone count. A 119-bone expression\n * bundle keeps its first 86 body rest translations when posed on Body86;\n * its 33 facial influences are attached to the head separately.\n */\n restSource?: 'auto' | 'builtin' | 'bundled';\n}\n\n/**\n * High-level facade around an {@link Armature} + one or more {@link Splat}s\n * loaded from a character bundle, of any container the reader implements.\n * Construct via {@link Character.load} - the constructor is only used\n * internally.\n *\n * Exposes transform setters (which automatically trigger splat re-sorts) and\n * simple playback verbs ({@link Character.playAnimation}, {@link Character.crossfadeTo},\n * {@link Character.stop}) that delegate to the underlying armature.\n *\n * @group Characters & Animation\n */\n/**\n * Bones whose per-character rest translation is NOT trustworthy, so `'bundled'`\n * keeps the canonical value for them. Both groups were picked on measurement\n * across four generated characters, not by anatomy.\n *\n * `FACIAL_*` - 160-181 mm from canonical at worst, against a face only ~200 mm\n * tall, and clips are authored on the canonical rig, so a per-character facial\n * bind fights the pose (143 mm of displacement measured; 0 mm at rest).\n *\n * `*toe_*` - error relative to BONE LENGTH is what shows here, and absolute\n * numbers hide it. Toes run a median 35% and up to 323% of their own length\n * (`indextoe_01_l`: 17 mm long, displaced 54.8 mm), against a median 14% and\n * max 56% for the rest of the body.\n *\n * Finger tips are the next candidates on the same measure - `index_03_l` 56%,\n * `middle_03_l` 47%, `ring_03_l` 44% - an order of magnitude better than the\n * worst toes but well above the body median. Left in deliberately; revisit if\n * hands are seen to distort.\n */\nfunction keepsCanonicalRest(name: string | undefined): boolean {\n if (!name) return false;\n return name.startsWith('FACIAL_') || name.includes('toe_');\n}\n\nexport class Character {\n /** Render-LOD level pyramid - when more than one entry, only one is\n * enabled at a time (the active level). `splats[0]` is always the\n * highest-fidelity (L0). Single-LOD characters have `splats.length === 1`. */\n public splats: Splat[];\n\n /**\n * The currently-rendered splat. For single-bin characters this is\n * always `splats[0]`; for multi-LOD characters it tracks the active\n * render-LOD level and flips with `setRenderLod` / `setRenderLevel`.\n *\n * Safe for read-only queries (`.numSplats`, `.object3D`, `.isInFrustum`,\n * etc.). For **state mutations** that should persist across LOD swaps\n * (tint, sort, visibility) prefer the Character-level helpers\n * ({@link setTint}, {@link requestSort}) - writing to a single splat\n * here only affects whichever level is active right now and the change\n * vanishes when the active level swaps.\n */\n get splat(): Splat {\n return this.splats[this._activeLevel];\n }\n\n // Splat-count LOD configuration (see setSplatCountLod). Off by default.\n private _countLodEnabled = false;\n private _countLodNearDist = 0;\n private _countLodFarDist = Infinity;\n private _countLodNearFraction = 1;\n private _countLodFarFraction = 0.3;\n\n // Render LOD configuration.\n private _renderLodEnabled = false;\n private _renderLodNearDist = Infinity;\n private _renderLodFarDist = Infinity;\n private _activeLevel = 0;\n\n // Linked splats that live OUTSIDE the LOD pyramid - added via\n // {@link addVariantSplat} and managed by higher-level systems (e.g. the\n // DamageVariant preset). They share the armature, animate every frame,\n // and stay enabled by default. Character ownership covers lifecycle\n // (destroy / setActive) but not visibility - that's the variant system's\n // job, via per-splat variant masks.\n private _variantSplats: Splat[] = [];\n\n /** Layer ids applied by {@link setLayers}; null = PC default (World). */\n private _layerIds: number[] | null = null;\n\n /** See-through copies from {@link addOverlaySplat}. Own their layers, so\n * {@link setLayers} leaves them alone; lifecycle is the character's. */\n private _overlaySplats: Splat[] = [];\n\n /** Set by {@link setOpacity}; a later overlay copy starts at it. */\n private _opacity = 1;\n private _colorModifier: SplatColorModifier | null = null;\n\n /** Whether this character is live (ticking + rendering). Toggled by\n * {@link setActive} for object pooling - a deactivated character keeps all\n * its GPU resources (splats, textures, compiled shaders) but stops\n * updating and rendering, so it can be reactivated at a new position with\n * none of the ~tens-of-ms `new Splat` setup cost. */\n private _active = true;\n\n /** Set by {@link destroy}. Async loaders that resolve afterwards (LOD\n * upgrades, variant splats) check this so they don't re-add splats that\n * nothing owns or ticks anymore - without it, a character destroyed while\n * a finer LOD is still downloading leaks that splat into the scene as a\n * frozen, orphaned figure. */\n private _destroyed = false;\n\n /** True once {@link destroy} has run. Progressive-load choreography\n * (coarse-first upgrade loops) should stop streaming when this flips. */\n get destroyed(): boolean {\n return this._destroyed;\n }\n\n // \u2500\u2500\u2500 TEMPORARY: `VIGGCHAR` v1 \u2192 legacy ground-convention shim \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // DELETE THIS WHOLE BLOCK - the field, the two converters, and the one line\n // in `_buildFromLoadResult` that fills it - when `.bin` retires. The shift is\n // then always 0, every method here is the identity, and removing them cannot\n // move anything.\n //\n // WHY IT EXISTS. The two character containers disagree about where a\n // character's feet sit relative to its model origin:\n //\n // legacy `.bin` feet 7-21 cm BELOW the origin. No ground pass ever ran;\n // they bind wherever the rig put them, and (measured across\n // the 13 assets shipped in this container) they disagree with\n // EACH OTHER by up to 14 cm.\n // VIGGCHAR v1 feet ON the origin. The bake lifts the splats until the\n // lowest visible gaussian (alpha >= 0.02) lands on y = 0 and\n // records that lift in the root joint row - per character,\n // not a constant (0.0432 .. 0.16207 m on real assets).\n //\n // Game code universally assumes \"model origin == ground contact\". That is\n // true for legacy - the canonical rest root row is exactly [0,0,0], which\n // `loader/skeleton/ground-convention.test.ts` pins - and false for v1, so a\n // `.vsplat` character rendered its whole bake shift too high and floated.\n //\n // WHAT IT IS NOT. This is a DE-correction, not a fix: it puts v1 back onto\n // legacy's (wrong, but shipped) convention so that nothing already on screen\n // moves. Normalising ground contact for real - measuring the lowest splat per\n // character at runtime - would move every legacy character and is a separate,\n // product-level call. Do not turn this into that.\n private _bakedGroundShiftY = 0;\n\n /**\n * The ground shift a `VIGGCHAR` v1 bake folded into this character, in\n * metres. `0` for legacy `.bin` bundles and for anything without one.\n *\n * Diagnostics and ground-snap tooling only. {@link setPosition},\n * {@link getPosition} and {@link Character.load}'s `position` option already\n * apply it, so game code should not need to read this - and code that\n * measures ground contact empirically (a {@link getLowestWorldY} probe) must\n * NOT apply it, because such a probe observes the shift's result already and\n * would double-correct.\n */\n get bakedGroundShiftY(): number {\n return this._bakedGroundShiftY;\n }\n\n /**\n * Convert a ground-contact Y - the convention {@link setPosition} takes -\n * into the raw Y to write on `armature.object3D`.\n *\n * For hot paths that must bypass {@link setPosition} and write the pivot\n * directly (a per-frame sync with a pooled `Vec3`, say). Everything else\n * should use {@link setPosition} and never see this.\n */\n groundToEntityY(groundY: number): number {\n return groundY - this._bakedGroundShiftY;\n }\n\n /**\n * Exact inverse of {@link groundToEntityY}: a raw `armature.object3D` Y back\n * into the ground-contact convention.\n *\n * Read positions back through this (or through {@link getPosition}) so that a\n * read/modify/write round-trip - a motor integrating velocity, a tween\n * sampling its own start value - can never apply the shift twice.\n */\n entityToGroundY(entityY: number): number {\n return entityY + this._bakedGroundShiftY;\n }\n // \u2500\u2500\u2500 end temporary shim \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _updateHandler!: (dt: number) => void;\n /** The host wants the per-frame tick (`disableAutoUpdate` clears it). */\n private _autoUpdate = true;\n /** The tick is registered on `app` right now. */\n private _updateAttached = false;\n\n /** Skeleton + animation controller. */\n armature: Armature;\n private _engine: SplatEngine;\n\n /**\n * The three.js object for the whole character - the armature's pivot, with\n * the character's splats parented under it. Already added to the engine's\n * content root; reparent it if you need the character under something else.\n */\n get object3D(): Object3D {\n return this.armature.object3D;\n }\n\n // Fields are declared and assigned explicitly rather than via TypeScript\n // parameter properties: this file is consumed as raw TS by apps that build\n // with `erasableSyntaxOnly`, which rejects parameter properties outright.\n constructor(\n armature: Armature,\n splats: Splat[],\n engine: SplatEngine,\n ) {\n this.armature = armature;\n this._engine = engine;\n if (splats.length === 0) throw new Error('Character: at least one Splat required');\n this.splats = splats;\n // Render-LOD characters start with only L0 visible; the rest are\n // pre-disabled so updatePositions never runs on them at startup. Use\n // `setRenderingEnabled` not raw `object3D.visible` - see the helper's\n // docstring for why both flags must be toggled together.\n splats[0].setRenderingEnabled(true);\n for (let i = 1; i < splats.length; i++) splats[i].setRenderingEnabled(false);\n }\n\n /**\n * Load a character bundle and add it to the engine's content root.\n *\n * The bundle's bone count selects the rig: 441 bones = full body + facial\n * rig, otherwise the 86-bone standard-male body rig. If the bundle contains\n * an embedded animation, it is registered on the engine under\n * {@link LoadCharacterOptions.name} (or the file basename).\n *\n * @param engine - Target engine.\n * @param urlOrUrls - One bundle URL, or an array of LOD levels for the same\n * character, finest first. Every level shares the armature and animation\n * from the FIRST entry; see {@link setRenderLod} for how a level is picked\n * at runtime and {@link addLodLevel} for adding one later.\n * @param opts - See {@link LoadCharacterOptions}.\n * @returns A fully-wired character whose armature drives the splat every frame.\n *\n * @example\n * ```ts\n * const character = await Character.load(engine, '/assets/hero.vsplat');\n * character.playAnimation('idle', { loop: true });\n * ```\n */\n static async load(\n engine: SplatEngine,\n urlOrUrls: string | string[],\n opts?: LoadCharacterOptions,\n ): Promise<Character> {\n const urls = Array.isArray(urlOrUrls) ? urlOrUrls : [urlOrUrls];\n if (urls.length === 0) throw new Error('Character.load: urls is empty');\n const results = await Character.fetchParsed(engine, urls);\n const defaultName = urls[0].split('/').pop()?.replace(/\\.\\w+$/, '') ?? 'character';\n return Character._buildFromLoadResult(engine, results, defaultName, opts);\n }\n\n /**\n * Start downloading a character bundle now; a later {@link Character.load}\n * of the same URL reuses the bytes.\n */\n static prefetch(url: string): void {\n prefetchCharacterBundle(url);\n }\n\n /**\n * The async first half of {@link Character.load}: download and decode the\n * bundle(s), building no scene objects. Pair it with\n * {@link Character.buildFromLoadResults} to choose WHEN the synchronous\n * half (GPU upload, `new Splat`) runs: a game that spawns several characters\n * in one frame can build them together.\n *\n * Each result is one character's: build it once.\n */\n static async fetchParsed(\n _engine: SplatEngine,\n urlOrUrls: string | string[],\n ): Promise<CharacterBundle[]> {\n const urls = Array.isArray(urlOrUrls) ? urlOrUrls : [urlOrUrls];\n if (urls.length === 0) throw new Error('Character.fetchParsed: urls is empty');\n return Promise.all(urls.map((u) => loadCharacterBundle(u)));\n }\n\n /**\n * The synchronous second half of {@link Character.load}: build the armature\n * and splat(s) from {@link Character.fetchParsed}'s results. `defaultName`\n * names the embedded animation when `opts.name` doesn't.\n */\n static buildFromLoadResults(\n engine: SplatEngine,\n results: CharacterBundle[],\n defaultName: string,\n opts?: LoadCharacterOptions,\n ): Character {\n return Character._buildFromLoadResult(engine, results, defaultName, opts);\n }\n\n /**\n * Load a `.bin` character bundle from in-memory bytes.\n *\n * Same shape as {@link Character.load} but consumes bytes directly. Use for\n * runtime-generated content (an offline generation pipeline's output, hot\n * swaps, tests) where there is no fetchable URL.\n *\n * @param engine - Target engine.\n * @param bytes - Raw `.bin` bundle bytes.\n * @param opts - See {@link LoadCharacterOptions}. `opts.name` is required for\n * anim registration since there is no URL basename to fall back on.\n * @returns A fully-wired character whose armature drives the splat every frame.\n *\n * @example\n * ```ts\n * const character = await Character.loadFromBytes(engine, generatedBundle, { name: 'hero' });\n * character.playAnimation('idle', { loop: true });\n * ```\n */\n static async loadFromBytes(\n engine: SplatEngine,\n bytes: Uint8Array,\n opts?: LoadCharacterOptions,\n ): Promise<Character> {\n const result = await loadCharacterBundleFromBytes(bytes);\n return Character._buildFromLoadResult(engine, [result], 'character', opts);\n }\n\n /**\n * Load a `.vsplat` bundle.\n *\n * The extension is advisory: the bytes go to the same magic-dispatching\n * reader {@link Character.load} uses, so a `.vsplat` may be a `VIGGCHAR`\n * version 1 bundle or one of the legacy planar containers. None of those\n * carries an animation chunk, so the character comes up in its rest pose;\n * register clips separately with {@link Animation.loadGlb} if you need motion.\n *\n * Differs from {@link Character.load} only in skipping the in-memory\n * `ArrayBuffer` cache - see `loader/shared/asset-loader.ts`.\n *\n * @param engine - Target engine.\n * @param source - URL, or raw `.vsplat` bytes.\n * @param opts - See {@link LoadCharacterOptions}.\n */\n static async loadVsplat(\n engine: SplatEngine,\n source: string | Uint8Array,\n opts?: LoadCharacterOptions,\n ): Promise<Character> {\n const result = typeof source === 'string'\n ? await loadCharacterBundle(source)\n : await loadCharacterBundleFromBytes(source);\n const defaultName = typeof source === 'string'\n ? source.split('/').pop()?.replace(/\\.\\w+$/, '') ?? 'character'\n : 'character';\n return Character._buildFromLoadResult(engine, [result], defaultName, opts);\n }\n\n /**\n * Build a character from bundles that are already decoded. The bundles are\n * read, never modified, so the same ones can back any number of characters.\n * @internal\n */\n static fromBundles(\n engine: SplatEngine,\n bundles: CharacterBundle[],\n defaultName: string,\n opts?: LoadCharacterOptions,\n ): Character {\n return Character._buildFromLoadResult(engine, bundles, defaultName, opts);\n }\n\n private static _buildFromLoadResult(\n engine: SplatEngine,\n results: CharacterBundle[],\n defaultName: string,\n opts?: LoadCharacterOptions,\n ): Character {\n // The funnel for `load`, `loadFromBytes` and `loadVsplat` alike, and the\n // first thing after their awaits that touches the GPU - `linkSplat` below\n // uploads the bone palette. If the engine was disposed while the bytes were\n // in flight, stop here: past this point the failure is a null-dereference\n // inside a texture upload, which reads as a corrupt asset rather than a\n // cancelled load. A caller's own post-await guard cannot cover this,\n // because the throw would happen before its `await` ever returns.\n if (engine.destroyed) {\n throw new EngineDisposedError('Character.load');\n }\n\n const library = engine.skeletonLibrary;\n if (!library?.stdMaleRestTranslations || !library.stdMaleRestRotations || !library.stdMaleParents) {\n throw new Error('Skeleton library not loaded on engine');\n }\n\n // Armature + animation come from results[0] - the LOD pyramid shares\n // one skeleton across all levels; additional results contribute only\n // their splat data. Skeleton / animation in tail bins are duplicates\n // of L0 and are intentionally ignored.\n const primary = results[0];\n\n if (primary.animationData) {\n // Same matrix block and root convention as a `.anim` (see\n // `clearAnimRootRotation`). Idempotent, so a shared parse result is safe.\n clearAnimRootRotation(\n primary.animationData.data,\n primary.animationData.numFrames,\n primary.animationData.numBones,\n );\n const animation = new Animation(\n primary.animationData.data,\n primary.animationData.numFrames,\n primary.animationData.numBones,\n primary.animationData.keyframeFrames,\n );\n animation.register(engine, opts?.name ?? defaultName);\n }\n\n // Pick armature rig to match bin bone count. 441 = full body+facial rig;\n // anything else defaults to std male 86-bone body rig.\n const binBoneCount = primary.armatureData?.numBones;\n const use441 = binBoneCount === 441 && library.parents441 && library.restTranslations441 && library.restRotations441;\n const builtinRest = use441 ? library.restTranslations441! : library.stdMaleRestTranslations;\n\n // `restSource: 'bundled'` takes the per-character `joints` for BODY bones and\n // keeps the canonical rest for the bones `keepsCanonicalRest` names - FACIAL_*\n // and toes. Only translations move - bundles carry no rotations - and only\n // when the array is present and sized to the rig, so older bundles silently\n // keep today's behaviour.\n //\n // The face is excluded deliberately, on measurement. Per-character facial\n // joints are unreliable: across four characters they run 160\u2013181 mm from\n // canonical at worst against a ~200 mm-tall face, while the body stays a\n // plausible 45\u201360 mm. And clips are authored on the canonical rig, so a\n // facial clip poses in canonical space while a per-character bind sits\n // elsewhere - measured at 143 mm of facial displacement, 7x more than with\n // facial channels removed, and exactly 0 mm at rest.\n //\n // Body joints are kept because they ARE trustworthy and are what a future\n // rotation-only animation path would need.\n const bundledJoints = primary.armatureData?.joints;\n const boneNames = use441 ? library.boneNames441 : library.boneNames;\n\n // `'auto'` (the default) resolves per bundle, which is the whole point: one\n // build has to render corrected characters on their own rig AND leave every\n // character made before corrections exactly as it renders today. A bundle\n // that was corrected had the ankle and the ground shift baked into its\n // splats and into joint 0; only `'bundled'` reads that root shift back, so\n // posing such a character from the shared tables moves the skin and leaves\n // the skeleton behind. A bundle that was NOT corrected has joints that no\n // pipeline ever vetted, so it keeps the canonical tables.\n const restSource = opts?.restSource ?? 'auto';\n const wantsBundled = restSource === 'auto'\n ? primary.armatureData?.corrected === true\n : restSource === 'bundled';\n const bodyRestCount = builtinRest.length;\n const expressionOnBody = binBoneCount === 119 && !use441 && bodyRestCount === 86 * 3;\n const canBundle =\n wantsBundled &&\n bundledJoints instanceof Float32Array &&\n (bundledJoints.length === bodyRestCount ||\n (expressionOnBody && bundledJoints.length === 119 * 3));\n\n let restTranslations = builtinRest;\n if (canBundle) {\n const joints = bundledJoints as Float32Array;\n const merged = new Float32Array(builtinRest);\n const n = merged.length / 3;\n for (let b = 0; b < n; b++) {\n // No names (unknown rig) => trust the bundle for every bone; the 86-bone\n // rig has no facial bones and its toes are named the same way anyway.\n if (keepsCanonicalRest(boneNames?.[b])) continue;\n merged[b * 3] = joints[b * 3];\n merged[b * 3 + 1] = joints[b * 3 + 1];\n merged[b * 3 + 2] = joints[b * 3 + 2];\n }\n restTranslations = merged;\n }\n\n // Report what was DONE on the armature: true only when this character is\n // posed from its own (bundled) rest, so a game can ask the rig rather than\n // re-derive it from the container (e.g. eyelid amplitudes tuned per rest).\n const restIsPerCharacter = canBundle;\n const armature = use441\n ? new Armature(opts?.name ?? defaultName, {\n numBones: 441,\n restIsPerCharacter,\n stdMaleRestTranslations: restTranslations,\n stdMaleRestRotations: library.restRotations441,\n stdMaleParents: library.parents441,\n })\n : new Armature(opts?.name ?? defaultName, {\n numBones: library.stdMaleRestTranslations.length / 3,\n restIsPerCharacter,\n stdMaleRestTranslations: restTranslations,\n stdMaleRestRotations: library.stdMaleRestRotations,\n stdMaleParents: library.stdMaleParents,\n });\n armature.addToScene(engine);\n\n // One Splat per LOD level. All link to the same armature \u2192 all get the\n // same per-frame bone palette upload. SplatSkinning.pushTransforms\n // skips disabled splats, so hidden LODs pay no CPU.\n const splats: Splat[] = results.map((r) => {\n const s = new Splat(engine, r.source);\n armature.linkSplat(s);\n return s;\n });\n\n // Row 0 of a v1 joints block IS the baked ground shift: the lift is added\n // to the root, because shifting the root moves every bone below it, so no\n // other row carries any of it. The decoder has already de-interleaved the\n // component-major file block into row-major `[x,y,z]` triples, so index 1\n // is the root row's Y. (Verified on real assets: x and z are exactly 0.)\n //\n // Gated on the CONTAINER via `restIsPerCharacter`, never on the\n // `armatureData.corrected` receipt - some legacy bundles carry that receipt\n // and keying on it would move characters that already render correctly.\n // Taken from the bundle whenever it is v1, independent of which rest table\n // the merge above chose: the shift lives in the GEOMETRY, so it applies\n // even when the canonical rest was kept. See the shim block on the class.\n const bakedGroundShiftY =\n primary.armatureData?.restIsPerCharacter === true && bundledJoints instanceof Float32Array\n ? bundledJoints[1]\n : 0;\n\n if (opts?.position) {\n // `position.y` is ground contact, the same convention `setPosition` takes\n // - spelled out here rather than deferred, because the Character that\n // owns the conversion does not exist yet.\n armature.move(new Vec3(\n opts.position.x,\n opts.position.y - bakedGroundShiftY,\n opts.position.z,\n ));\n }\n\n const character = new Character(armature, splats, engine);\n character._bakedGroundShiftY = bakedGroundShiftY;\n character._wireUpdate();\n return character;\n }\n\n /** Build + register the per-frame update handler. Called once at\n * construction; kept separate so the handler can close over `this`. */\n private _wireUpdate(): void {\n this._updateHandler = (dt: number) => {\n if (this._renderLodEnabled && this.splats.length > 1) {\n const next = this._pickRenderLevel();\n if (next !== this._activeLevel) {\n this.splats[this._activeLevel].setRenderingEnabled(false);\n this.splats[next].setRenderingEnabled(true);\n this._activeLevel = next;\n }\n }\n if (this._countLodEnabled) this._applyCountLod();\n this.armature.update(dt);\n };\n this._syncUpdateHook();\n }\n\n /** Register the per-frame tick exactly when the character is active, the\n * host hasn't taken the tick over, and it isn't destroyed. */\n private _syncUpdateHook(): void {\n const want = this._active && this._autoUpdate && !this._destroyed;\n if (want === this._updateAttached) return;\n if (want) this._engine.addUpdater(this._updateHandler);\n else this._engine.removeUpdater(this._updateHandler);\n this._updateAttached = want;\n }\n\n /** Pick the render-LOD level for this frame based on camera distance.\n * near band \u2192 L0; far band \u2192 last; in between \u2192 intermediate level. */\n private _pickRenderLevel(): number {\n const N = this.splats.length;\n if (N < 2) return 0;\n const distSq = this.armature.cameraDistanceSq();\n if (distSq === null) return this._activeLevel;\n const near = this._renderLodNearDist;\n const far = this._renderLodFarDist;\n if (distSq < near * near) return 0;\n if (distSq >= far * far) return N - 1;\n // Divide [near, far] into (N-1) equal sub-bands; band i renders L(i+1).\n const dist = Math.sqrt(distSq);\n const bands = N - 1;\n const t = (dist - near) / (far - near);\n return 1 + Math.min(bands - 1, Math.floor(t * bands));\n }\n\n /**\n * Enable distance-based render LOD. Per frame, the character switches\n * between the loaded LOD splats (`splats[0..N-1]`, from finest to\n * coarsest). Near the camera \u2192 L0 (full); beyond `farDist` \u2192 last level;\n * in between \u2192 intermediate levels split evenly across the band.\n *\n * Composes with {@link Armature.setAnimationLod} / {@link Armature.setSortLod}:\n * render LOD throws away splats at distance, the other two throttle\n * animation / sort work - stack all three for maximum CPU savings.\n *\n * No-op if only one LOD level was loaded.\n *\n * @example\n * ```ts\n * const c = await Character.load(engine, ['hero.l0.vsplat', 'hero.l1.vsplat', 'hero.l2.vsplat']);\n * c.setRenderLod({ nearDist: 8, farDist: 20 });\n * ```\n */\n setRenderLod(opts: { nearDist: number; farDist: number }): void {\n if (this.splats.length < 2) return;\n this._renderLodNearDist = opts.nearDist;\n this._renderLodFarDist = opts.farDist;\n this._renderLodEnabled = true;\n }\n\n /** Disable render LOD - pins the character to the highest-fidelity level\n * (L0). Other loaded LOD splats remain in memory but are not rendered. */\n disableRenderLod(): void {\n this._renderLodEnabled = false;\n if (this._activeLevel !== 0) {\n this.splats[this._activeLevel].setRenderingEnabled(false);\n this.splats[0].setRenderingEnabled(true);\n this._activeLevel = 0;\n }\n }\n\n /** Force a specific render-LOD level, bypassing distance bands. Useful\n * for debugging / A-B comparisons in the profiling scene. */\n setRenderLevel(level: number): void {\n const N = this.splats.length;\n if (N < 2) return;\n const clamped = Math.max(0, Math.min(N - 1, Math.floor(level)));\n if (clamped === this._activeLevel) return;\n this.splats[this._activeLevel].setRenderingEnabled(false);\n this.splats[clamped].setRenderingEnabled(true);\n this._activeLevel = clamped;\n }\n\n /**\n * Thin the character with distance by processing fewer of its splats, rather\n * than by switching to a different file.\n *\n * At `nearDist` and closer, `nearFraction` of the splats are skinned, sorted\n * and drawn; at `farDist` and beyond, `farFraction` of them; in between, the\n * fraction is interpolated. Which splats those are is decided by importance\n * inside each 4 cm cell (see {@link Splat.setCountLod}), so the character\n * thins evenly instead of losing a region.\n *\n * The dynamic counterpart of {@link SplatQuality.pruneRatio}, and the one to\n * reach for when the splats are still wanted close up. It composes with\n * everything else: {@link Character.setRenderLod} switches between loaded\n * files, {@link Armature.setAnimationLod} and {@link Armature.setSortLod}\n * drop frames of pose and sort work, and this one changes how much of the\n * character each of those frames covers.\n *\n * `WebGLRenderer` only - see {@link Splat.setCountLod} for why.\n *\n * ```ts\n * character.setSplatCountLod({ nearDist: 4, farDist: 16, farFraction: 0.25 });\n * ```\n */\n setSplatCountLod(opts: {\n nearDist: number;\n farDist: number;\n /** Fraction kept at `nearDist` and closer. Default 1. */\n nearFraction?: number;\n /** Fraction kept at `farDist` and beyond. Default 0.3. */\n farFraction?: number;\n }): void {\n this._countLodNearDist = Math.max(0, opts.nearDist);\n this._countLodFarDist = Math.max(this._countLodNearDist + 1e-6, opts.farDist);\n this._countLodNearFraction = Math.min(1, Math.max(0.01, opts.nearFraction ?? 1));\n this._countLodFarFraction = Math.min(1, Math.max(0.01, opts.farFraction ?? 0.3));\n this._countLodEnabled = true;\n // Build the importance ordering here rather than on the frame the LOD\n // first engages, which is a frame where the camera is already moving.\n for (const splat of this.splats) splat.prepareCountLod();\n }\n\n /** Stop thinning: every splat is processed again, on every level. */\n disableSplatCountLod(): void {\n if (!this._countLodEnabled) return;\n this._countLodEnabled = false;\n for (const splat of this.splats) splat.setCountLod(null);\n }\n\n /** Pick this frame's splat fraction from camera distance and apply it. */\n private _applyCountLod(): void {\n const distSq = this.armature.cameraDistanceSq();\n if (distSq === null) return;\n const near = this._countLodNearDist;\n const far = this._countLodFarDist;\n const nearF = this._countLodNearFraction;\n const farF = this._countLodFarFraction;\n const dist = Math.sqrt(distSq);\n let fraction: number;\n if (dist <= near) fraction = nearF;\n else if (dist >= far) fraction = farF;\n else fraction = nearF + ((farF - nearF) * (dist - near)) / (far - near);\n // Quantized to 64ths so a camera creeping forward does not rebuild the\n // drawn set on every frame for a handful of splats.\n const steps = Math.max(1, Math.round(fraction * 64));\n const splat = this.splat;\n splat.setCountLod(Math.round((steps / 64) * splat.numSplats));\n }\n\n /** Number of LOD levels loaded for this character (>=1). */\n get renderLodLevels(): number {\n return this.splats.length;\n }\n\n /** Active render-LOD level (0 = highest fidelity). */\n get activeRenderLevel(): number {\n return this._activeLevel;\n }\n\n /**\n * Tint every LOD splat. Fans out to `splats[*]` so the tint persists\n * across render-LOD swaps - writing to a single splat (e.g. the legacy\n * `c.splat.setTint(...)`) only affects that level, and the tint\n * \"vanishes\" the next time `setRenderLod` swaps the visible level.\n *\n * Same signature as {@link Splat.setTint}.\n */\n setTint(\n intensity: number,\n color?: { r: number; g: number; b: number },\n ): void {\n for (const s of this.splats) {\n if (color) s.setTint(intensity, color);\n else s.setTint(intensity);\n }\n }\n\n /**\n * {@link Splat.setTintMultiply} for every LOD level: multiply the colour\n * by `color` with `strength` 0..1. {@link setTint} goes back to the mix.\n */\n setTintMultiply(strength: number, color?: { r: number; g: number; b: number }): void {\n for (const s of this.splats) s.setTintMultiply(strength, color);\n }\n\n /**\n * {@link Splat.setColorModifier} for every LOD level, variant and overlay\n * splat, including ones added later. `null` removes it.\n */\n setColorModifier(modifier: SplatColorModifier | null): void {\n this._colorModifier = modifier;\n for (const s of this.splats) s.setColorModifier(modifier);\n for (const s of this._variantSplats) s.setColorModifier(modifier);\n for (const s of this._overlaySplats) s.setColorModifier(modifier);\n }\n\n /**\n * Opacity in [0, 1] for every LOD level, variant and overlay splat - see\n * {@link Splat.setOpacity}. 1, the default, draws the character unchanged.\n */\n setOpacity(opacity: number): void {\n this._opacity = opacity;\n for (const s of this.splats) s.setOpacity(opacity);\n for (const s of this._variantSplats) s.setOpacity(opacity);\n for (const s of this._overlaySplats) s.setOpacity(opacity);\n }\n\n /**\n * Reveal amount in [0, 1] for every LOD level, variant and overlay splat - see\n * {@link Splat.setReveal}. 0 hides the character entirely (without\n * touching entity enabled state, so no placement recompile), 1 renders it\n * unchanged. `inverse` keeps the area ahead of the moving front instead,\n * which is useful when handing off between two characters.\n */\n setReveal(amount: number, inverse = false): void {\n for (const s of this.splats) s.setReveal(amount, inverse);\n for (const s of this._variantSplats) s.setReveal(amount, inverse);\n for (const s of this._overlaySplats) s.setReveal(amount, inverse);\n }\n\n /** {@link Splat.setRevealLook} for every LOD level, variant and overlay splat. */\n setRevealLook(look: RevealLook): void {\n for (const s of this.splats) s.setRevealLook(look);\n for (const s of this._variantSplats) s.setRevealLook(look);\n for (const s of this._overlaySplats) s.setRevealLook(look);\n }\n\n /**\n * Pay the reveal's one-time setup now instead of on its first frame - see\n * {@link Armature.prepareReveal}.\n */\n prepareReveal(): void {\n this.armature.prepareReveal();\n }\n\n /**\n * Re-sort every LOD splat. Cheap when called on inactive splats (no GPU\n * sort runs there), and necessary for the active one to reflect a fresh\n * transform on the next frame. Fans out so a swap to a previously-\n * inactive LOD doesn't render with a stale sort order.\n */\n requestSort(): void {\n for (const s of this.splats) s.requestSort();\n }\n\n /**\n * Put every LOD and variant splat on the given three.js layers (see\n * {@link Splat.setLayers}). Remembered so variants attached later land on\n * the same layers. `[0]` restores the default.\n */\n setLayers(layerIds: number[]): void {\n this._layerIds = [...layerIds];\n for (const s of this.splats) s.setLayers(this._layerIds);\n for (const s of this._variantSplats) s.setLayers(this._layerIds);\n }\n\n /**\n * Add a second cloud of the active LOD, sharing this armature (so it\n * animates in lockstep) but on `layerIds`. With the body occluded by real\n * objects, this copy is what shows through obstacles: give it a see-through\n * look with its own {@link Splat.setOpacity} or {@link Splat.setColorModifier}\n * (the PlayCanvas build's `applyOverlaySplatStyle` is not ported).\n * Synchronous: reuses the decoded data.\n */\n addOverlaySplat(layerIds: number[]): Splat {\n const source = this.splats[this._activeLevel] ?? this.splats[0];\n const splat = new Splat(this._engine, {\n packed: source.packed,\n splatWeights: source.splatWeights,\n sourceBoneCount: source.sourceBoneCount,\n });\n this.armature.linkSplat(splat);\n splat.setLayers(layerIds);\n splat.setRenderingEnabled(this._active);\n this._applyLook(splat);\n this._overlaySplats.push(splat);\n return splat;\n }\n\n /** Carry the character-wide opacity and colour hook onto a splat added after they were set. */\n private _applyLook(splat: Splat): void {\n if (this._opacity !== 1) splat.setOpacity(this._opacity);\n if (this._colorModifier) splat.setColorModifier(this._colorModifier);\n }\n\n /** Read-only view of the overlay copies from {@link addOverlaySplat}. */\n get overlaySplats(): readonly Splat[] {\n return this._overlaySplats;\n }\n\n /**\n * Take one overlay copy back off, the inverse of {@link addOverlaySplat}.\n *\n * It exists so a caller can stop compositing a character against an\n * environment WITHOUT reloading the character. Adding an overlay was already\n * synchronous and in place; removing one was not possible at all, so the only\n * way back was to destroy the body and load it again - a reload of the one\n * thing on screen that had not changed.\n *\n * A splat that is not one of this character's overlays is ignored.\n */\n removeOverlaySplat(splat: Splat): void {\n const i = this._overlaySplats.indexOf(splat);\n if (i < 0) return;\n this._overlaySplats.splice(i, 1);\n this.armature.unlinkSplat(splat);\n splat.destroy();\n }\n\n /**\n * World-space Y of the character's lowest point, using\n * {@link Splat.getGroundWorldY}'s noise-robust low-quantile estimate across\n * every enabled splat (the active render-LOD level, plus any variant splats\n * that are currently visible). Returns `null` if no splat is enabled (e.g.\n * mid-load). Ground-snap tooling only - the per-frame render path doesn't\n * use it.\n *\n * This is a MEASUREMENT of where the character actually renders, so it\n * already includes {@link bakedGroundShiftY}. A caller that snaps to ground\n * from this number must not also apply that shift, or it corrects twice.\n */\n getLowestWorldY(quantile = 0.005): number | null {\n let min = Infinity;\n for (const s of this.splats) {\n if (!s.renderingEnabled) continue;\n const y = s.getGroundWorldY(quantile);\n if (y < min) min = y;\n }\n return min === Infinity ? null : min;\n }\n\n /**\n * Async primitive: load one more LOD level from `url` and link it to this\n * character's armature, leaving it disabled (not rendered) until the caller\n * explicitly picks it via {@link setRenderLevel}.\n *\n * Lets game code compose its own LOD-loading policy on top of an existing\n * Character without the engine deciding when to swap. Typical pattern is\n * progressive: load the smallest LOD via {@link Character.load} for instant\n * first-frame, then background-load finer levels with `addLodLevel` and\n * `setRenderLevel(splats.length - 1)` each time one arrives.\n *\n * Skeleton + animation are shared with the existing armature - any joints\n * / animation data inside the additional `.bin` is intentionally ignored\n * (it must match the original; only the splat + bone-weights chunks are\n * consumed). The newly loaded `Splat` is pushed onto `this.splats` and\n * starts in the disabled state.\n *\n * @param url - URL of another `.bin` (any LOD level of the same character).\n * @returns Resolves once the splat is fully loaded, linked, and GPU-uploaded.\n *\n * @example\n * ```ts\n * // Progressive: start at L2 (smallest), upgrade as finer levels arrive.\n * const c = await Character.load(engine, urls[2], opts);\n * (async () => {\n * await c.addLodLevel(urls[1]);\n * c.setRenderLevel(c.splats.length - 1);\n * await c.addLodLevel(urls[0]);\n * c.setRenderLevel(c.splats.length - 1);\n * })();\n * ```\n */\n async addLodLevel(url: string): Promise<void> {\n const result = await loadCharacterBundle(url);\n // Destroyed while the level was downloading (e.g. a rapid character swap)\n // - adding the splat now would orphan it in the scene with nothing\n // ticking or owning it. Drop the bytes instead.\n if (this._destroyed) return;\n const splat = new Splat(this._engine, result.source);\n this.armature.linkSplat(splat);\n splat.setRenderingEnabled(false);\n if (this._layerIds) splat.setLayers(this._layerIds);\n this._applyLook(splat);\n this.splats.push(splat);\n }\n\n /**\n * Load an additional splat cloud, link it to this character's armature,\n * and leave it ENABLED so it renders alongside the LOD pyramid. Returns\n * the newly-created {@link Splat} so higher-level systems can drive it\n * directly (typically via {@link Splat.setSplatGroups} +\n * {@link Splat.setVariantMask}).\n *\n * Use case: damage / outfit / state variants where two skinned clouds\n * share one skeleton and per-region visibility masks decide which\n * gaussians each cloud contributes. See the `DamageVariant` preset for\n * the body-part scheme built on top of this primitive.\n *\n * The variant splat's lifecycle is owned by this Character - it is\n * destroyed in {@link destroy} and enabled/disabled by {@link setActive}.\n * Call {@link removeVariantSplat} to retire one early.\n *\n * @param url - URL of a `.bin` rigged to the same skeleton as this\n * character. The skeleton/animation chunks (if present) are ignored.\n */\n async addVariantSplat(url: string): Promise<Splat> {\n const result = await loadCharacterBundle(url);\n // Same guard as addLodLevel: a variant landing after destroy() would be\n // an unowned orphan. Reject so the awaiting caller's flow (itself tied\n // to the destroyed character) fails loudly instead of leaking.\n if (this._destroyed) {\n throw new Error('Character destroyed while variant splat was loading');\n }\n const splat = new Splat(this._engine, result.source);\n this.armature.linkSplat(splat);\n splat.setRenderingEnabled(true);\n if (this._layerIds) splat.setLayers(this._layerIds);\n this._applyLook(splat);\n this._variantSplats.push(splat);\n return splat;\n }\n\n /** Remove and destroy a splat previously added via {@link addVariantSplat}.\n * No-op if `splat` was not from this character. */\n removeVariantSplat(splat: Splat): void {\n const idx = this._variantSplats.indexOf(splat);\n if (idx < 0) return;\n this._variantSplats.splice(idx, 1);\n this.armature.unlinkSplat(splat);\n splat.destroy();\n }\n\n /** Read-only view of currently-attached variant splats (in insertion order). */\n get variantSplats(): readonly Splat[] {\n return this._variantSplats;\n }\n\n /**\n * Set the character's position, with `y` measured at GROUND CONTACT: pass the\n * floor height and the feet land on it, whichever container the character\n * came from. Triggers a splat re-sort.\n *\n * `y` goes through {@link groundToEntityY} on the way to the pivot. That is\n * the identity for every legacy `.bin` character, so this is byte-identical\n * to the historical \"y is the model origin\" behaviour for everything already\n * shipped; only `VIGGCHAR` v1 bundles move. Read the position back with\n * {@link getPosition}, never with `armature.object3D.position`, or a\n * round-trip will double-apply the shift.\n */\n setPosition(x: number, y: number, z: number) {\n this.armature.move(new Vec3(x, this.groundToEntityY(y), z));\n }\n\n /**\n * The character's current position in the armature pivot's parent space, in\n * the same convention {@link setPosition} takes (`y` at ground contact).\n *\n * The exact inverse of {@link setPosition}: reading a position and writing it\n * straight back is a no-op. That is the property to preserve - it is what\n * lets a caller integrate velocity, tween, or clamp against a position it\n * read without the ground shim compounding once per frame.\n *\n * Returns a fresh {@link Vec3}; the pivot's own vector is not exposed.\n */\n getPosition(out: Vector3 = new Vector3()): Vector3 {\n const p = this.armature.object3D.position;\n return out.set(p.x, this.entityToGroundY(p.y), p.z);\n }\n\n /** Set the character's rotation in Euler degrees. Triggers a splat re-sort. */\n setRotation(xDeg: number, yDeg: number, zDeg: number) {\n // 'ZYX' is the order that reproduces the PlayCanvas build's euler convention.\n this.armature.object3D.quaternion.setFromEuler(\n _euler.set(xDeg * MathUtils.DEG2RAD, yDeg * MathUtils.DEG2RAD, zDeg * MathUtils.DEG2RAD, 'ZYX'),\n );\n this.requestSort();\n }\n\n /** Set non-uniform scale. Triggers a splat re-sort. */\n setScale(x: number, y: number, z: number) {\n this.armature.object3D.scale.set(x, y, z);\n this.requestSort();\n }\n\n /**\n * Immediately start a registered animation (no crossfade).\n *\n * The animation must have been registered on the engine via\n * {@link Animation.register} or embedded in the `.bin` bundle.\n *\n * @param animName - Animation name in `engine.skeletalAnimationLibrary`.\n * @param opts.loop - Loop playback. Default `true`.\n * @param opts.rootMotion - Drive the armature position from the pelvis X/Z channel. Default `false`.\n * @returns `true` if the animation was found and started; `false` otherwise.\n */\n playAnimation(animName: string, opts?: { loop?: boolean; rootMotion?: boolean }): boolean {\n return this.armature.playAnimation(\n animName,\n opts?.rootMotion ?? false,\n opts?.loop ?? true,\n );\n }\n\n /**\n * Smoothly blend from the current pose to a new animation.\n *\n * Snapshots the current bone poses and interpolates toward the new\n * animation over `duration` seconds. Safe to call mid-crossfade - always\n * starts from wherever bones actually are.\n *\n * @param animName - Animation name in `engine.skeletalAnimationLibrary`.\n * @param opts.duration - Crossfade length in seconds. Default `0.08`.\n * @param opts.loop - Loop the target animation. Default `true`.\n * @param opts.rootMotion - Drive the armature position from the pelvis X/Z channel. Default `false`.\n * @returns `true` if the animation was found and the blend started; `false` otherwise.\n */\n crossfadeTo(\n animName: string,\n opts?: { duration?: number; loop?: boolean; rootMotion?: boolean; preserveTime?: boolean; continueSource?: boolean; easing?: 'linear' | 'smoothstep' },\n ): boolean {\n return this.armature.crossfadeTo(animName, opts);\n }\n\n /**\n * Play `animName` on the named overlay layer, restricted to a bone mask.\n * Layers compose over the base animation each frame - masked bones blend\n * toward the overlay by `opts.weight` (defaults to `1`).\n *\n * Pass `opts.region: 'upperBody' | 'lowerBody'` to use the built-in masks\n * (canonical 86-bone rig), or `opts.mask` directly to supply your own.\n *\n * Typical use: `character.playAnimation('walk_loop'); character.playLayer('aim', 'aim_rifle', { region: 'upperBody' });`\n */\n playLayer(\n layerName: string,\n animName: string,\n opts?: {\n region?: BodyRegion;\n mask?: BoneMask;\n loop?: boolean;\n crossfade?: number;\n weight?: number;\n },\n ): boolean {\n let mask = opts?.mask;\n if (!mask && opts?.region) mask = makeRegionMask(opts.region, this.armature.boneNames);\n if (!mask) return false;\n return this.armature.playLayerAnimation(layerName, animName, mask, opts);\n }\n\n /** Set the overlay weight (0..1) on a layer. */\n setLayerWeight(layerName: string, weight: number): void {\n this.armature.setLayerWeight(layerName, weight);\n }\n\n /** Stop and tear down a layer; ramps weight to zero over `fadeDuration` if > 0. */\n stopLayer(layerName: string, fadeDuration = 0): void {\n this.armature.stopLayer(layerName, fadeDuration);\n }\n\n /** Pause or resume every active overlay layer at once. */\n setAllLayersPaused(paused: boolean): void {\n this.armature.setAllLayersPaused(paused);\n }\n\n /**\n * Name of the currently-playing animation, or `null` if no animation is\n * active. Mirrors {@link Armature.currentAnimationName}.\n */\n get currentAnimationName(): string | null {\n return this.armature.currentAnimationName;\n }\n\n /** `true` if an animation is currently active. */\n get isPlaying(): boolean {\n return this.armature.isPlaying;\n }\n\n /**\n * Playback-speed multiplier for the active clip (`1` = author speed, `2` =\n * double speed). Scales only how fast animation time advances, not the\n * authored frame rate or crossfade timing. Mirrors\n * {@link Armature.playbackSpeed}. Use it to tie a locomotion clip's speed\n * to the pivot's movement speed.\n */\n get playbackSpeed(): number {\n return this.armature.playbackSpeed;\n }\n\n /** Position in the base clip, in frames (30 fps by convention). Set it to\n * seek - e.g. to a clip's touchdown frame when the physics lands. */\n get animationTime(): number {\n return this.armature.animationTime;\n }\n set animationTime(v: number) {\n this.armature.animationTime = v;\n }\n set playbackSpeed(v: number) {\n this.armature.playbackSpeed = v;\n }\n\n /**\n * `true` when a non-looping animation has reached its last frame and is no\n * longer advancing.\n */\n get isFinished(): boolean {\n return this.armature.isFinished;\n }\n\n /**\n * Subscribe to frame-aligned animation events fired as `animTime` advances.\n * The active animation's {@link Animation.events} array is the source; the\n * engine doesn't interpret `name` or `payload` - games define their own\n * vocabulary and route inside the callback.\n *\n * Listeners persist across animation switches. Returns an unsubscribe handle.\n *\n * @example\n * ```ts\n * character.onAnimEvent((e) => {\n * if (e.name === 'footstep') playFootstepSfx(e.payload);\n * });\n * ```\n */\n onAnimEvent(cb: AnimEventCallback): () => void {\n return this.armature.onAnimEvent(cb);\n }\n\n /**\n * Stop playback.\n *\n * With `fadeDuration = 0` (the default), snaps immediately to the rest\n * pose. A positive value crossfades back to rest over that many seconds.\n */\n stop(fadeDuration = 0) {\n this.armature.stop(fadeDuration);\n }\n\n /**\n * Read and reset the pelvis X/Z delta the animation produced since the\n * last call. Only meaningful when\n * {@link Armature.rootMotionMode | armature.rootMotionMode} is `'extract'`;\n * returns `{0, 0}` otherwise.\n *\n * Typical use: a motor / character controller reads this each tick and\n * feeds it into its own velocity integration, so animation root motion\n * composes cleanly with physics, networking, or input.\n *\n * ```ts\n * // in your render loop, after engine.update(dt):\n * const { dx, dz } = character.consumeRootMotionDelta();\n * motor.setMoveVelocity(dx / dt, dz / dt);\n * motor.update(dt);\n * ```\n */\n consumeRootMotionDelta(): { dx: number; dz: number } {\n return this.armature.consumeRootMotionDelta();\n }\n\n /** True while the character is ticking + rendering (see {@link setActive}). */\n get active(): boolean { return this._active; }\n\n /**\n * Activate / deactivate this character WITHOUT releasing GPU resources -\n * the basis for object pooling. Deactivating detaches the per-frame update\n * handler and disables every splat object and the armature pivot, so the\n * character stops animating and rendering but keeps all its splats,\n * textures and compiled shaders alive. Reactivating re-attaches the update\n * handler and re-enables the armature; render-LOD then re-picks which splat\n * shows on the next frame (so we only force the current level visible to\n * cover the LOD-disabled case).\n *\n * Reactivate is the cheap path that skips the entire `new Splat` setup cost\n * (texture creation + bone upload + shader compile, ~tens of ms per\n * character) that a fresh {@link load} pays. Callers reposition via\n * `armature.move(...)` and restart animation via `playAnimation(...)` after\n * reactivating.\n *\n * Idempotent.\n */\n setActive(on: boolean): void {\n if (on === this._active) return;\n this._active = on;\n if (on) {\n this.armature.object3D.visible = true;\n // Show the current LOD level; render-LOD (if enabled) re-evaluates and\n // fixes this on the next update. With LOD off, splats.length === 1 and\n // this is the only one.\n this.splats[this._activeLevel]?.setRenderingEnabled(true);\n for (const s of this._variantSplats) s.setRenderingEnabled(true);\n for (const s of this._overlaySplats) s.setRenderingEnabled(true);\n this._syncUpdateHook();\n } else {\n this._syncUpdateHook();\n for (const s of this.splats) s.setRenderingEnabled(false);\n for (const s of this._variantSplats) s.setRenderingEnabled(false);\n for (const s of this._overlaySplats) s.setRenderingEnabled(false);\n this.armature.object3D.visible = false;\n }\n }\n\n /**\n * Detach the per-frame playback tick without touching rendering/GPU\n * resources (unlike {@link setActive}). For hosts that drive the armature's\n * clock themselves and apply their own per-frame pose edits, the auto-tick\n * would re-evaluate and overwrite those edits. Idempotent. The same as\n * {@link disableAutoUpdate}.\n */\n detachAutoUpdate(): void {\n this.disableAutoUpdate();\n }\n\n /**\n * Stop the automatic per-frame update, for a host that drives it itself\n * with {@link update}; otherwise the character would update twice a frame.\n * Stays off across `setActive` until {@link enableAutoUpdate}. Idempotent.\n */\n disableAutoUpdate(): void {\n this._autoUpdate = false;\n this._syncUpdateHook();\n }\n\n /** Give the per-frame update back to the engine. Idempotent. */\n enableAutoUpdate(): void {\n this._autoUpdate = true;\n this._syncUpdateHook();\n }\n\n /**\n * Advance this character by `dt` seconds: pick the render LOD, evaluate the\n * pose, push it to the splats. `engine.update()` calls this for every\n * character still on auto-update; call it yourself after\n * {@link disableAutoUpdate}.\n */\n update(dt: number): void {\n this._updateHandler(dt);\n }\n\n /**\n * Release all GPU/CPU resources: removes the engine update handler, unlinks\n * the splat from the armature, destroys both, and removes the armature\n * pivot from the scene graph.\n */\n destroy() {\n if (this._destroyed) return;\n this._destroyed = true;\n this._syncUpdateHook();\n for (const s of this.splats) {\n s.setRenderingEnabled(false);\n this.armature.unlinkSplat(s);\n s.destroy();\n }\n for (const s of this._variantSplats) {\n s.setRenderingEnabled(false);\n this.armature.unlinkSplat(s);\n s.destroy();\n }\n this._variantSplats.length = 0;\n for (const s of this._overlaySplats) {\n s.setRenderingEnabled(false);\n this.armature.unlinkSplat(s);\n s.destroy();\n }\n this._overlaySplats.length = 0;\n this.armature.destroy();\n }\n}\n\nconst _euler = new Euler();\n", "/**\n * Internal math kernel for the skeletal core.\n *\n * The rig, animation and skinning code is shared with the PlayCanvas build of\n * this engine and was written against that engine's `Vec3` / `Quat` / `Mat4`.\n * These classes keep the same method names, argument orders and formulas, so\n * the shared files compile unchanged and the bone matrices they produce match\n * the PlayCanvas build to float precision - which is what the A/B suite checks.\n *\n * Deliberately NOT `THREE.Vector3` and friends: the conventions differ in ways\n * that silently change results (`lerp(a, b, t)` vs `lerp(v, t)`, a two-argument\n * `cross`, a `Float32Array`-backed matrix), and a port that swapped them by\n * hand would be a port nobody could diff against the original.\n *\n * Nothing here is part of the public API. Values cross into three.js types at\n * the `Character` / `Armature` boundary.\n */\n\nexport class Vec3 {\n x: number;\n y: number;\n z: number;\n\n constructor(x = 0, y = 0, z = 0) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n set(x: number, y: number, z: number): this {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n }\n\n copy(rhs: { x: number; y: number; z: number }): this {\n this.x = rhs.x;\n this.y = rhs.y;\n this.z = rhs.z;\n return this;\n }\n\n clone(): Vec3 {\n return new Vec3(this.x, this.y, this.z);\n }\n\n add(rhs: Vec3): this {\n this.x += rhs.x;\n this.y += rhs.y;\n this.z += rhs.z;\n return this;\n }\n\n add2(lhs: Vec3, rhs: Vec3): this {\n this.x = lhs.x + rhs.x;\n this.y = lhs.y + rhs.y;\n this.z = lhs.z + rhs.z;\n return this;\n }\n\n sub(rhs: Vec3): this {\n this.x -= rhs.x;\n this.y -= rhs.y;\n this.z -= rhs.z;\n return this;\n }\n\n sub2(lhs: Vec3, rhs: Vec3): this {\n this.x = lhs.x - rhs.x;\n this.y = lhs.y - rhs.y;\n this.z = lhs.z - rhs.z;\n return this;\n }\n\n mulScalar(scalar: number): this {\n this.x *= scalar;\n this.y *= scalar;\n this.z *= scalar;\n return this;\n }\n\n dot(rhs: Vec3): number {\n return this.x * rhs.x + this.y * rhs.y + this.z * rhs.z;\n }\n\n cross(lhs: Vec3, rhs: Vec3): this {\n const lx = lhs.x, ly = lhs.y, lz = lhs.z;\n const rx = rhs.x, ry = rhs.y, rz = rhs.z;\n this.x = ly * rz - ry * lz;\n this.y = lz * rx - rz * lx;\n this.z = lx * ry - rx * ly;\n return this;\n }\n\n length(): number {\n return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);\n }\n\n normalize(): this {\n const lengthSq = this.x * this.x + this.y * this.y + this.z * this.z;\n if (lengthSq > 0) {\n const invLength = 1 / Math.sqrt(lengthSq);\n this.x *= invLength;\n this.y *= invLength;\n this.z *= invLength;\n }\n return this;\n }\n\n lerp(lhs: Vec3, rhs: Vec3, alpha: number): this {\n this.x = lhs.x + alpha * (rhs.x - lhs.x);\n this.y = lhs.y + alpha * (rhs.y - lhs.y);\n this.z = lhs.z + alpha * (rhs.z - lhs.z);\n return this;\n }\n}\n\nexport class Quat {\n x: number;\n y: number;\n z: number;\n w: number;\n\n constructor(x = 0, y = 0, z = 0, w = 1) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n\n set(x: number, y: number, z: number, w: number): this {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n }\n\n copy(rhs: { x: number; y: number; z: number; w: number }): this {\n this.x = rhs.x;\n this.y = rhs.y;\n this.z = rhs.z;\n this.w = rhs.w;\n return this;\n }\n\n clone(): Quat {\n return new Quat(this.x, this.y, this.z, this.w);\n }\n\n conjugate(): this {\n this.x *= -1;\n this.y *= -1;\n this.z *= -1;\n return this;\n }\n\n dot(other: Quat): number {\n return this.x * other.x + this.y * other.y + this.z * other.z + this.w * other.w;\n }\n\n length(): number {\n return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n }\n\n mulScalar(scalar: number): this {\n this.x *= scalar;\n this.y *= scalar;\n this.z *= scalar;\n this.w *= scalar;\n return this;\n }\n\n normalize(): this {\n let len = this.length();\n if (len === 0) {\n this.x = this.y = this.z = 0;\n this.w = 1;\n } else {\n len = 1 / len;\n this.x *= len;\n this.y *= len;\n this.z *= len;\n this.w *= len;\n }\n return this;\n }\n\n /** `this = lhs * rhs`. Safe when `this` aliases either operand. */\n mul2(lhs: Quat, rhs: Quat): this {\n const q1x = lhs.x, q1y = lhs.y, q1z = lhs.z, q1w = lhs.w;\n const q2x = rhs.x, q2y = rhs.y, q2z = rhs.z, q2w = rhs.w;\n this.x = q1w * q2x + q1x * q2w + q1y * q2z - q1z * q2y;\n this.y = q1w * q2y + q1y * q2w + q1z * q2x - q1x * q2z;\n this.z = q1w * q2z + q1z * q2w + q1x * q2y - q1y * q2x;\n this.w = q1w * q2w - q1x * q2x - q1y * q2y - q1z * q2z;\n return this;\n }\n\n mul(rhs: Quat): this {\n return this.mul2(this, rhs);\n }\n\n slerp(lhs: Quat, rhs: Quat, alpha: number): this {\n const lx = lhs.x, ly = lhs.y, lz = lhs.z, lw = lhs.w;\n let rx = rhs.x, ry = rhs.y, rz = rhs.z, rw = rhs.w;\n\n let cosHalfTheta = lw * rw + lx * rx + ly * ry + lz * rz;\n if (cosHalfTheta < 0) {\n rw = -rw;\n rx = -rx;\n ry = -ry;\n rz = -rz;\n cosHalfTheta = -cosHalfTheta;\n }\n\n if (Math.abs(cosHalfTheta) >= 1) {\n this.w = lw;\n this.x = lx;\n this.y = ly;\n this.z = lz;\n return this;\n }\n\n const halfTheta = Math.acos(cosHalfTheta);\n const sinHalfTheta = Math.sqrt(1 - cosHalfTheta * cosHalfTheta);\n\n if (Math.abs(sinHalfTheta) < 0.001) {\n this.w = lw * 0.5 + rw * 0.5;\n this.x = lx * 0.5 + rx * 0.5;\n this.y = ly * 0.5 + ry * 0.5;\n this.z = lz * 0.5 + rz * 0.5;\n return this;\n }\n\n const ratioA = Math.sin((1 - alpha) * halfTheta) / sinHalfTheta;\n const ratioB = Math.sin(alpha * halfTheta) / sinHalfTheta;\n this.w = lw * ratioA + rw * ratioB;\n this.x = lx * ratioA + rx * ratioB;\n this.y = ly * ratioA + ry * ratioB;\n this.z = lz * ratioA + rz * ratioB;\n return this;\n }\n\n /** Rotate `vec` by this quaternion. */\n transformVector(vec: { x: number; y: number; z: number }, res: Vec3 = new Vec3()): Vec3 {\n const x = vec.x, y = vec.y, z = vec.z;\n const qx = this.x, qy = this.y, qz = this.z, qw = this.w;\n const ix = qw * x + qy * z - qz * y;\n const iy = qw * y + qz * x - qx * z;\n const iz = qw * z + qx * y - qy * x;\n const iw = -qx * x - qy * y - qz * z;\n res.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n res.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n res.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n return res;\n }\n\n /** Rotation of the upper 3x3 of `m`, with any scale (and a mirror) divided out. */\n setFromMat4(m: Mat4): this {\n const d = m.data;\n let m00 = d[0], m01 = d[1], m02 = d[2];\n let m10 = d[4], m11 = d[5], m12 = d[6];\n let m20 = d[8], m21 = d[9], m22 = d[10];\n\n const det = m00 * (m11 * m22 - m12 * m21) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20);\n if (det < 0) {\n m00 = -m00;\n m01 = -m01;\n m02 = -m02;\n }\n\n let l: number;\n l = m00 * m00 + m01 * m01 + m02 * m02;\n if (l === 0) return this.set(0, 0, 0, 1);\n l = 1 / Math.sqrt(l);\n m00 *= l;\n m01 *= l;\n m02 *= l;\n\n l = m10 * m10 + m11 * m11 + m12 * m12;\n if (l === 0) return this.set(0, 0, 0, 1);\n l = 1 / Math.sqrt(l);\n m10 *= l;\n m11 *= l;\n m12 *= l;\n\n l = m20 * m20 + m21 * m21 + m22 * m22;\n if (l === 0) return this.set(0, 0, 0, 1);\n l = 1 / Math.sqrt(l);\n m20 *= l;\n m21 *= l;\n m22 *= l;\n\n if (m22 < 0) {\n if (m00 > m11) {\n this.set(1 + m00 - m11 - m22, m01 + m10, m20 + m02, m12 - m21);\n } else {\n this.set(m01 + m10, 1 - m00 + m11 - m22, m12 + m21, m20 - m02);\n }\n } else {\n if (m00 < -m11) {\n this.set(m20 + m02, m12 + m21, 1 - m00 - m11 + m22, m01 - m10);\n } else {\n this.set(m12 - m21, m20 - m02, m01 - m10, 1 + m00 + m11 + m22);\n }\n }\n\n return this.mulScalar(1.0 / this.length());\n }\n}\n\n/** Column-major 4x4, `Float32Array`-backed. Same element layout as `THREE.Matrix4.elements`. */\nexport class Mat4 {\n data: Float32Array;\n\n constructor() {\n const data = new Float32Array(16);\n data[0] = data[5] = data[10] = data[15] = 1;\n this.data = data;\n }\n\n copy(rhs: Mat4): this {\n this.data.set(rhs.data);\n return this;\n }\n\n clone(): Mat4 {\n return new Mat4().copy(this);\n }\n\n setIdentity(): this {\n const m = this.data;\n m.fill(0);\n m[0] = m[5] = m[10] = m[15] = 1;\n return this;\n }\n\n /** Copy from any 16-element column-major source (e.g. `THREE.Matrix4.elements`). */\n setFromArray(src: ArrayLike<number>): this {\n const m = this.data;\n for (let i = 0; i < 16; i++) m[i] = src[i];\n return this;\n }\n\n setTRS(t: Vec3, r: Quat, s: Vec3): this {\n const qx = r.x, qy = r.y, qz = r.z, qw = r.w;\n const sx = s.x, sy = s.y, sz = s.z;\n\n const x2 = qx + qx;\n const y2 = qy + qy;\n const z2 = qz + qz;\n const xx = qx * x2;\n const xy = qx * y2;\n const xz = qx * z2;\n const yy = qy * y2;\n const yz = qy * z2;\n const zz = qz * z2;\n const wx = qw * x2;\n const wy = qw * y2;\n const wz = qw * z2;\n\n const m = this.data;\n m[0] = (1 - (yy + zz)) * sx;\n m[1] = (xy + wz) * sx;\n m[2] = (xz - wy) * sx;\n m[3] = 0;\n m[4] = (xy - wz) * sy;\n m[5] = (1 - (xx + zz)) * sy;\n m[6] = (yz + wx) * sy;\n m[7] = 0;\n m[8] = (xz + wy) * sz;\n m[9] = (yz - wx) * sz;\n m[10] = (1 - (xx + yy)) * sz;\n m[11] = 0;\n m[12] = t.x;\n m[13] = t.y;\n m[14] = t.z;\n m[15] = 1;\n return this;\n }\n\n /** `this = lhs * rhs`. Safe when `this` aliases either operand. */\n mul2(lhs: Mat4, rhs: Mat4): this {\n const a = lhs.data;\n const b = rhs.data;\n const r = this.data;\n\n const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];\n const a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];\n const a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];\n const a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];\n\n let b0: number, b1: number, b2: number, b3: number;\n\n b0 = b[0]; b1 = b[1]; b2 = b[2]; b3 = b[3];\n r[0] = a00 * b0 + a10 * b1 + a20 * b2 + a30 * b3;\n r[1] = a01 * b0 + a11 * b1 + a21 * b2 + a31 * b3;\n r[2] = a02 * b0 + a12 * b1 + a22 * b2 + a32 * b3;\n r[3] = a03 * b0 + a13 * b1 + a23 * b2 + a33 * b3;\n\n b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];\n r[4] = a00 * b0 + a10 * b1 + a20 * b2 + a30 * b3;\n r[5] = a01 * b0 + a11 * b1 + a21 * b2 + a31 * b3;\n r[6] = a02 * b0 + a12 * b1 + a22 * b2 + a32 * b3;\n r[7] = a03 * b0 + a13 * b1 + a23 * b2 + a33 * b3;\n\n b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];\n r[8] = a00 * b0 + a10 * b1 + a20 * b2 + a30 * b3;\n r[9] = a01 * b0 + a11 * b1 + a21 * b2 + a31 * b3;\n r[10] = a02 * b0 + a12 * b1 + a22 * b2 + a32 * b3;\n r[11] = a03 * b0 + a13 * b1 + a23 * b2 + a33 * b3;\n\n b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];\n r[12] = a00 * b0 + a10 * b1 + a20 * b2 + a30 * b3;\n r[13] = a01 * b0 + a11 * b1 + a21 * b2 + a31 * b3;\n r[14] = a02 * b0 + a12 * b1 + a22 * b2 + a32 * b3;\n r[15] = a03 * b0 + a13 * b1 + a23 * b2 + a33 * b3;\n return this;\n }\n\n mul(rhs: Mat4): this {\n return this.mul2(this, rhs);\n }\n\n invert(): this {\n const s = this.data;\n const a00 = s[0], a01 = s[1], a02 = s[2], a03 = s[3];\n const a10 = s[4], a11 = s[5], a12 = s[6], a13 = s[7];\n const a20 = s[8], a21 = s[9], a22 = s[10], a23 = s[11];\n const a30 = s[12], a31 = s[13], a32 = s[14], a33 = s[15];\n\n const b00 = a00 * a11 - a01 * a10;\n const b01 = a00 * a12 - a02 * a10;\n const b02 = a00 * a13 - a03 * a10;\n const b03 = a01 * a12 - a02 * a11;\n const b04 = a01 * a13 - a03 * a11;\n const b05 = a02 * a13 - a03 * a12;\n const b06 = a20 * a31 - a21 * a30;\n const b07 = a20 * a32 - a22 * a30;\n const b08 = a20 * a33 - a23 * a30;\n const b09 = a21 * a32 - a22 * a31;\n const b10 = a21 * a33 - a23 * a31;\n const b11 = a22 * a33 - a23 * a32;\n\n const det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n if (det === 0) {\n this.setIdentity();\n } else {\n const invDet = 1 / det;\n const t = this.data;\n t[0] = (a11 * b11 - a12 * b10 + a13 * b09) * invDet;\n t[1] = (-a01 * b11 + a02 * b10 - a03 * b09) * invDet;\n t[2] = (a31 * b05 - a32 * b04 + a33 * b03) * invDet;\n t[3] = (-a21 * b05 + a22 * b04 - a23 * b03) * invDet;\n t[4] = (-a10 * b11 + a12 * b08 - a13 * b07) * invDet;\n t[5] = (a00 * b11 - a02 * b08 + a03 * b07) * invDet;\n t[6] = (-a30 * b05 + a32 * b02 - a33 * b01) * invDet;\n t[7] = (a20 * b05 - a22 * b02 + a23 * b01) * invDet;\n t[8] = (a10 * b10 - a11 * b08 + a13 * b06) * invDet;\n t[9] = (-a00 * b10 + a01 * b08 - a03 * b06) * invDet;\n t[10] = (a30 * b04 - a31 * b02 + a33 * b00) * invDet;\n t[11] = (-a20 * b04 + a21 * b02 - a23 * b00) * invDet;\n t[12] = (-a10 * b09 + a11 * b07 - a12 * b06) * invDet;\n t[13] = (a00 * b09 - a01 * b07 + a02 * b06) * invDet;\n t[14] = (-a30 * b03 + a31 * b01 - a32 * b00) * invDet;\n t[15] = (a20 * b03 - a21 * b01 + a22 * b00) * invDet;\n }\n return this;\n }\n\n getTranslation(t: Vec3 = new Vec3()): Vec3 {\n return t.set(this.data[12], this.data[13], this.data[14]);\n }\n\n getScale(scale: Vec3 = new Vec3()): Vec3 {\n const d = this.data;\n return scale.set(\n Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]),\n Math.sqrt(d[4] * d[4] + d[5] * d[5] + d[6] * d[6]),\n Math.sqrt(d[8] * d[8] + d[9] * d[9] + d[10] * d[10]),\n );\n }\n}\n", "// Auto-generated skeleton data - do not edit manually.\n\nexport const NUM_BONES = 86;\n\nexport const BONE_NAMES: string[] = [\"root\",\"pelvis\",\"spine_01\",\"spine_02\",\"spine_03\",\"spine_04\",\"spine_05\",\"neck_01\",\"neck_02\",\"head\",\"clavicle_l\",\"upperarm_l\",\"lowerarm_l\",\"hand_l\",\"pinky_metacarpal_l\",\"pinky_01_l\",\"pinky_02_l\",\"pinky_03_l\",\"ring_metacarpal_l\",\"ring_01_l\",\"ring_02_l\",\"ring_03_l\",\"thumb_01_l\",\"thumb_02_l\",\"thumb_03_l\",\"middle_metacarpal_l\",\"middle_01_l\",\"middle_02_l\",\"middle_03_l\",\"index_metacarpal_l\",\"index_01_l\",\"index_02_l\",\"index_03_l\",\"clavicle_r\",\"upperarm_r\",\"lowerarm_r\",\"hand_r\",\"pinky_metacarpal_r\",\"pinky_01_r\",\"pinky_02_r\",\"pinky_03_r\",\"ring_metacarpal_r\",\"ring_01_r\",\"ring_02_r\",\"ring_03_r\",\"thumb_01_r\",\"thumb_02_r\",\"thumb_03_r\",\"middle_metacarpal_r\",\"middle_01_r\",\"middle_02_r\",\"middle_03_r\",\"index_metacarpal_r\",\"index_01_r\",\"index_02_r\",\"index_03_r\",\"thigh_r\",\"calf_r\",\"foot_r\",\"ball_r\",\"littletoe_01_r\",\"littletoe_02_r\",\"ringtoe_01_r\",\"ringtoe_02_r\",\"middletoe_01_r\",\"middletoe_02_r\",\"bigtoe_01_r\",\"bigtoe_02_r\",\"indextoe_01_r\",\"indextoe_02_r\",\"calf_twist_01_r\",\"thigh_l\",\"calf_l\",\"foot_l\",\"ball_l\",\"indextoe_01_l\",\"indextoe_02_l\",\"bigtoe_01_l\",\"bigtoe_02_l\",\"littletoe_01_l\",\"littletoe_02_l\",\"middletoe_01_l\",\"middletoe_02_l\",\"ringtoe_01_l\",\"ringtoe_02_l\",\"calf_twist_01_l\"];\n\nexport const SKELETON_1185_NAMES: string[] = [\"root\",\"pelvis\",\"spine_01\",\"spine_02\",\"spine_03\",\"spine_04\",\"spine_05\",\"neck_01\",\"neck_02\",\"head\",\"clavicle_l\",\"upperarm_l\",\"upperarm_correctiveRoot_l\",\"upperarm_bck_l\",\"upperarm_fwd_l\",\"upperarm_in_l\",\"upperarm_out_l\",\"lowerarm_l\",\"hand_l\",\"pinky_metacarpal_l\",\"pinky_01_l\",\"pinky_02_l\",\"pinky_03_l\",\"pinky_03_bulge_l\",\"pinky_03_half_l\",\"pinky_03_in_l\",\"pinky_02_dip_l\",\"pinky_02_bulge_l\",\"pinky_02_side_out_l\",\"pinky_02_side_inn_l\",\"pinky_02_half_l\",\"pinky_02_in_l\",\"pinky_02_pip_l\",\"pinky_01_palmMid_l\",\"pinky_01_bulge_l\",\"pinky_01_side_out_l\",\"pinky_01_side_inn_l\",\"pinky_01_half_l\",\"pinky_01_mcp_l\",\"pinky_01_palm_l\",\"pinky_metacarpal_slide_l\",\"ring_metacarpal_l\",\"ring_01_l\",\"ring_02_l\",\"ring_03_l\",\"ring_03_bulge_l\",\"ring_03_half_l\",\"ring_02_dip_l\",\"ring_03_in_l\",\"ring_02_bulge_l\",\"ring_02_side_out_l\",\"ring_02_side_inn_l\",\"ring_02_half_l\",\"ring_02_in_l\",\"ring_02_pip_l\",\"ring_01_palmMid_l\",\"ring_01_bulge_l\",\"ring_01_side_out_l\",\"ring_01_side_inn_l\",\"ring_01_half_l\",\"ring_01_mcp_l\",\"ring_01_palm_l\",\"ring_metacarpal_slide_l\",\"thumb_01_l\",\"thumb_02_l\",\"thumb_03_l\",\"thumb_03_bulge_l\",\"thumb_03_side_out_l\",\"thumb_03_side_inn_l\",\"thumb_03_half_l\",\"thumb_03_pip_l\",\"thumb_03_in_l\",\"thumb_02_bulge_l\",\"thumb_02_side_out_l\",\"thumb_02_side_inn_l\",\"thumb_02_half_l\",\"thumb_02_in_l\",\"thumb_02_mcp_l\",\"thumb_01_side_out_l\",\"thumb_01_side_inn_l\",\"middle_metacarpal_l\",\"middle_01_l\",\"middle_02_l\",\"middle_03_l\",\"middle_03_bulge_l\",\"middle_03_half_l\",\"middle_03_in_l\",\"middle_02_dip_l\",\"middle_02_bulge_l\",\"middle_02_side_out_l\",\"middle_02_side_inn_l\",\"middle_02_half_l\",\"middle_02_pip_l\",\"middle_02_in_l\",\"middle_01_palmMid_l\",\"middle_01_bulge_l\",\"middle_01_side_out_l\",\"middle_01_side_inn_l\",\"middle_01_half_l\",\"middle_01_mcp_l\",\"middle_01_palm_l\",\"middle_metacarpal_slide_l\",\"index_metacarpal_l\",\"index_01_l\",\"index_02_l\",\"index_03_l\",\"index_03_bulge_l\",\"index_03_half_l\",\"index_02_dip_l\",\"index_03_in_l\",\"index_02_bulge_l\",\"index_02_side_out_l\",\"index_02_side_inn_l\",\"index_02_half_l\",\"index_02_in_l\",\"index_02_pip_l\",\"index_01_palmMid_l\",\"index_01_bulge_l\",\"index_01_side_out_l\",\"index_01_side_inn_l\",\"index_01_half_l\",\"index_01_mcp_l\",\"index_01_palm_l\",\"index_metacarpal_slide_l\",\"wrist_inner_l\",\"wrist_outer_l\",\"lowerarm_twist_02_l\",\"lowerarm_twist_01_l\",\"lowerarm_correctiveRoot_l\",\"lowerarm_in_l\",\"lowerarm_out_l\",\"lowerarm_fwd_l\",\"lowerarm_bck_l\",\"upperarm_twist_01_l\",\"upperarm_twistCor_01_l\",\"upperarm_twist_02_l\",\"upperarm_tricep_l\",\"upperarm_bicep_l\",\"upperarm_twistCor_02_l\",\"clavicle_out_l\",\"clavicle_scap_l\",\"clavicle_r\",\"upperarm_r\",\"upperarm_correctiveRoot_r\",\"upperarm_bck_r\",\"upperarm_in_r\",\"upperarm_fwd_r\",\"upperarm_out_r\",\"lowerarm_r\",\"hand_r\",\"pinky_metacarpal_r\",\"pinky_01_r\",\"pinky_02_r\",\"pinky_03_r\",\"pinky_03_bulge_r\",\"pinky_03_half_r\",\"pinky_03_in_r\",\"pinky_02_dip_r\",\"pinky_02_bulge_r\",\"pinky_02_side_out_r\",\"pinky_02_side_inn_r\",\"pinky_02_half_r\",\"pinky_02_in_r\",\"pinky_02_pip_r\",\"pinky_01_palmMid_r\",\"pinky_01_bulge_r\",\"pinky_01_side_out_r\",\"pinky_01_side_inn_r\",\"pinky_01_half_r\",\"pinky_01_mcp_r\",\"pinky_01_palm_r\",\"pinky_metacarpal_slide_r\",\"ring_metacarpal_r\",\"ring_01_r\",\"ring_02_r\",\"ring_03_r\",\"ring_03_bulge_r\",\"ring_03_half_r\",\"ring_02_dip_r\",\"ring_03_in_r\",\"ring_02_bulge_r\",\"ring_02_side_out_r\",\"ring_02_side_inn_r\",\"ring_02_half_r\",\"ring_02_in_r\",\"ring_02_pip_r\",\"ring_01_palmMid_r\",\"ring_01_bulge_r\",\"ring_01_side_out_r\",\"ring_01_side_inn_r\",\"ring_01_half_r\",\"ring_01_mcp_r\",\"ring_01_palm_r\",\"ring_metacarpal_slide_r\",\"thumb_01_r\",\"thumb_02_r\",\"thumb_03_r\",\"thumb_03_bulge_r\",\"thumb_03_side_out_r\",\"thumb_03_side_inn_r\",\"thumb_03_half_r\",\"thumb_03_pip_r\",\"thumb_03_in_r\",\"thumb_02_bulge_r\",\"thumb_02_side_out_r\",\"thumb_02_side_inn_r\",\"thumb_02_half_r\",\"thumb_02_in_r\",\"thumb_02_mcp_r\",\"thumb_01_side_out_r\",\"thumb_01_side_inn_r\",\"middle_metacarpal_r\",\"middle_01_r\",\"middle_02_r\",\"middle_03_r\",\"middle_03_bulge_r\",\"middle_03_half_r\",\"middle_03_in_r\",\"middle_02_dip_r\",\"middle_02_bulge_r\",\"middle_02_side_out_r\",\"middle_02_side_inn_r\",\"middle_02_half_r\",\"middle_02_pip_r\",\"middle_02_in_r\",\"middle_01_palmMid_r\",\"middle_01_bulge_r\",\"middle_01_side_out_r\",\"middle_01_side_inn_r\",\"middle_01_half_r\",\"middle_01_mcp_r\",\"middle_01_palm_r\",\"middle_metacarpal_slide_r\",\"index_metacarpal_r\",\"index_01_r\",\"index_02_r\",\"index_03_r\",\"index_03_bulge_r\",\"index_03_half_r\",\"index_02_dip_r\",\"index_03_in_r\",\"index_02_bulge_r\",\"index_02_side_out_r\",\"index_02_side_inn_r\",\"index_02_half_r\",\"index_02_in_r\",\"index_02_pip_r\",\"index_01_palmMid_r\",\"index_01_bulge_r\",\"index_01_side_out_r\",\"index_01_side_inn_r\",\"index_01_half_r\",\"index_01_mcp_r\",\"index_01_palm_r\",\"index_metacarpal_slide_r\",\"wrist_inner_r\",\"wrist_outer_r\",\"lowerarm_twist_02_r\",\"lowerarm_twist_01_r\",\"lowerarm_correctiveRoot_r\",\"lowerarm_out_r\",\"lowerarm_in_r\",\"lowerarm_fwd_r\",\"lowerarm_bck_r\",\"upperarm_twist_01_r\",\"upperarm_twistCor_01_r\",\"upperarm_twist_02_r\",\"upperarm_tricep_r\",\"upperarm_bicep_r\",\"upperarm_twistCor_02_r\",\"clavicle_out_r\",\"clavicle_scap_r\",\"clavicle_pec_r\",\"spine_04_latissimus_l\",\"spine_04_latissimus_r\",\"clavicle_pec_l\",\"thigh_r\",\"calf_r\",\"foot_r\",\"ball_r\",\"littletoe_01_r\",\"littletoe_02_r\",\"ringtoe_01_r\",\"ringtoe_02_r\",\"middletoe_01_r\",\"middletoe_02_r\",\"bigtoe_01_r\",\"bigtoe_02_r\",\"indextoe_01_r\",\"indextoe_02_r\",\"ankle_bck_r\",\"ankle_fwd_r\",\"calf_twist_02_r\",\"calf_twistCor_02_r\",\"calf_twist_01_r\",\"calf_correctiveRoot_r\",\"calf_kneeBack_r\",\"calf_knee_r\",\"thigh_twist_01_r\",\"thigh_twistCor_01_r\",\"thigh_twist_02_r\",\"thigh_twistCor_02_r\",\"thigh_correctiveRoot_r\",\"thigh_fwd_r\",\"thigh_bck_r\",\"thigh_out_r\",\"thigh_in_r\",\"thigh_bck_lwr_r\",\"thigh_fwd_lwr_r\",\"thigh_l\",\"calf_l\",\"foot_l\",\"ball_l\",\"indextoe_01_l\",\"indextoe_02_l\",\"bigtoe_01_l\",\"bigtoe_02_l\",\"littletoe_01_l\",\"littletoe_02_l\",\"middletoe_01_l\",\"middletoe_02_l\",\"ringtoe_01_l\",\"ringtoe_02_l\",\"ankle_bck_l\",\"ankle_fwd_l\",\"calf_twist_02_l\",\"calf_twistCor_02_l\",\"calf_twist_01_l\",\"calf_correctiveRoot_l\",\"calf_kneeBack_l\",\"calf_knee_l\",\"thigh_twist_01_l\",\"thigh_twistCor_01_l\",\"thigh_twist_02_l\",\"thigh_twistCor_02_l\",\"thigh_correctiveRoot_l\",\"thigh_bck_l\",\"thigh_fwd_l\",\"thigh_out_l\",\"thigh_bck_lwr_l\",\"thigh_in_l\",\"thigh_fwd_lwr_l\",\"FACIAL_C_Neck1Root\",\"FACIAL_C_NeckB\",\"FACIAL_L_NeckB1\",\"FACIAL_R_NeckB1\",\"FACIAL_L_NeckB2\",\"FACIAL_R_NeckB2\",\"FACIAL_C_12IPV_NeckB1\",\"FACIAL_C_12IPV_NeckB2\",\"FACIAL_L_12IPV_NeckB3\",\"FACIAL_R_12IPV_NeckB3\",\"FACIAL_L_12IPV_NeckB4\",\"FACIAL_R_12IPV_NeckB4\",\"FACIAL_L_12IPV_NeckB5\",\"FACIAL_R_12IPV_NeckB5\",\"FACIAL_L_12IPV_NeckB6\",\"FACIAL_R_12IPV_NeckB6\",\"FACIAL_L_12IPV_NeckB7\",\"FACIAL_R_12IPV_NeckB7\",\"FACIAL_C_NeckBackB\",\"FACIAL_L_NeckBackB\",\"FACIAL_R_NeckBackB\",\"FACIAL_C_12IPV_NeckBackB1\",\"FACIAL_C_12IPV_NeckBackB2\",\"FACIAL_L_12IPV_NeckBackB1\",\"FACIAL_R_12IPV_NeckBackB1\",\"FACIAL_L_12IPV_NeckBackB2\",\"FACIAL_R_12IPV_NeckBackB2\",\"FACIAL_C_Neck2Root\",\"FACIAL_C_AdamsApple\",\"FACIAL_C_12IPV_AdamsA1\",\"FACIAL_C_12IPV_AdamsA2\",\"FACIAL_L_NeckA1\",\"FACIAL_R_NeckA1\",\"FACIAL_L_NeckA2\",\"FACIAL_R_NeckA2\",\"FACIAL_L_NeckA3\",\"FACIAL_R_NeckA3\",\"FACIAL_L_12IPV_NeckA1\",\"FACIAL_R_12IPV_NeckA1\",\"FACIAL_L_12IPV_NeckA2\",\"FACIAL_R_12IPV_NeckA2\",\"FACIAL_L_12IPV_NeckA3\",\"FACIAL_R_12IPV_NeckA3\",\"FACIAL_L_12IPV_NeckA4\",\"FACIAL_R_12IPV_NeckA4\",\"FACIAL_L_12IPV_NeckA5\",\"FACIAL_R_12IPV_NeckA5\",\"FACIAL_L_12IPV_NeckA6\",\"FACIAL_R_12IPV_NeckA6\",\"FACIAL_C_NeckBackA\",\"FACIAL_L_NeckBackA\",\"FACIAL_R_NeckBackA\",\"FACIAL_C_12IPV_NeckBackA1\",\"FACIAL_C_12IPV_NeckBackA2\",\"FACIAL_L_12IPV_NeckBackA1\",\"FACIAL_R_12IPV_NeckBackA1\",\"FACIAL_L_12IPV_NeckBackA2\",\"FACIAL_R_12IPV_NeckBackA2\",\"FACIAL_C_FacialRoot\",\"FACIAL_C_Hair1\",\"FACIAL_L_12IPV_Hair1\",\"FACIAL_R_12IPV_Hair1\",\"FACIAL_C_Hair2\",\"FACIAL_C_Hair3\",\"FACIAL_C_Hair4\",\"FACIAL_C_Hair5\",\"FACIAL_C_Hair6\",\"FACIAL_L_HairA1\",\"FACIAL_R_HairA1\",\"FACIAL_L_HairA2\",\"FACIAL_R_HairA2\",\"FACIAL_L_HairA3\",\"FACIAL_R_HairA3\",\"FACIAL_L_HairA4\",\"FACIAL_R_HairA4\",\"FACIAL_L_HairA5\",\"FACIAL_R_HairA5\",\"FACIAL_L_HairA6\",\"FACIAL_R_HairA6\",\"FACIAL_L_HairB1\",\"FACIAL_R_HairB1\",\"FACIAL_L_HairB2\",\"FACIAL_R_HairB2\",\"FACIAL_L_HairB3\",\"FACIAL_R_HairB3\",\"FACIAL_L_HairB4\",\"FACIAL_R_HairB4\",\"FACIAL_L_HairB5\",\"FACIAL_R_HairB5\",\"FACIAL_L_Temple\",\"FACIAL_R_Temple\",\"FACIAL_L_12IPV_Temple1\",\"FACIAL_R_12IPV_Temple1\",\"FACIAL_L_12IPV_Temple2\",\"FACIAL_R_12IPV_Temple2\",\"FACIAL_L_12IPV_Temple3\",\"FACIAL_R_12IPV_Temple3\",\"FACIAL_L_12IPV_Temple4\",\"FACIAL_R_12IPV_Temple4\",\"FACIAL_L_HairC1\",\"FACIAL_R_HairC1\",\"FACIAL_L_HairC2\",\"FACIAL_R_HairC2\",\"FACIAL_L_HairC3\",\"FACIAL_R_HairC3\",\"FACIAL_L_HairC4\",\"FACIAL_R_HairC4\",\"FACIAL_L_Sideburn1\",\"FACIAL_R_Sideburn1\",\"FACIAL_L_Sideburn2\",\"FACIAL_R_Sideburn2\",\"FACIAL_L_Sideburn3\",\"FACIAL_R_Sideburn3\",\"FACIAL_L_Sideburn4\",\"FACIAL_R_Sideburn4\",\"FACIAL_L_Sideburn5\",\"FACIAL_R_Sideburn5\",\"FACIAL_L_Sideburn6\",\"FACIAL_R_Sideburn6\",\"FACIAL_C_ForeheadSkin\",\"FACIAL_L_ForeheadInSkin\",\"FACIAL_R_ForeheadInSkin\",\"FACIAL_L_12IPV_ForeheadSkin1\",\"FACIAL_R_12IPV_ForeheadSkin1\",\"FACIAL_L_12IPV_ForeheadSkin2\",\"FACIAL_R_12IPV_ForeheadSkin2\",\"FACIAL_L_12IPV_ForeheadSkin3\",\"FACIAL_R_12IPV_ForeheadSkin3\",\"FACIAL_L_12IPV_ForeheadSkin4\",\"FACIAL_R_12IPV_ForeheadSkin4\",\"FACIAL_L_12IPV_ForeheadSkin5\",\"FACIAL_R_12IPV_ForeheadSkin5\",\"FACIAL_L_12IPV_ForeheadSkin6\",\"FACIAL_R_12IPV_ForeheadSkin6\",\"FACIAL_L_ForeheadMidSkin\",\"FACIAL_R_ForeheadMidSkin\",\"FACIAL_L_ForeheadOutSkin\",\"FACIAL_R_ForeheadOutSkin\",\"FACIAL_C_Skull\",\"FACIAL_C_Forehead\",\"FACIAL_C_Forehead1\",\"FACIAL_L_Forehead1\",\"FACIAL_R_Forehead1\",\"FACIAL_C_Forehead2\",\"FACIAL_L_Forehead2\",\"FACIAL_R_Forehead2\",\"FACIAL_C_Forehead3\",\"FACIAL_L_Forehead3\",\"FACIAL_R_Forehead3\",\"FACIAL_C_12IPV_Forehead1\",\"FACIAL_L_12IPV_Forehead1\",\"FACIAL_R_12IPV_Forehead1\",\"FACIAL_C_12IPV_Forehead2\",\"FACIAL_L_12IPV_Forehead2\",\"FACIAL_R_12IPV_Forehead2\",\"FACIAL_C_12IPV_Forehead3\",\"FACIAL_L_12IPV_Forehead3\",\"FACIAL_R_12IPV_Forehead3\",\"FACIAL_C_12IPV_Forehead4\",\"FACIAL_L_12IPV_Forehead4\",\"FACIAL_R_12IPV_Forehead4\",\"FACIAL_C_12IPV_Forehead5\",\"FACIAL_L_12IPV_Forehead5\",\"FACIAL_R_12IPV_Forehead5\",\"FACIAL_C_12IPV_Forehead6\",\"FACIAL_L_12IPV_Forehead6\",\"FACIAL_R_12IPV_Forehead6\",\"FACIAL_L_ForeheadIn\",\"FACIAL_L_ForeheadInA1\",\"FACIAL_L_ForeheadInA2\",\"FACIAL_L_ForeheadInA3\",\"FACIAL_L_ForeheadInB1\",\"FACIAL_L_ForeheadInB2\",\"FACIAL_L_12IPV_ForeheadIn1\",\"FACIAL_L_12IPV_ForeheadIn2\",\"FACIAL_L_12IPV_ForeheadIn3\",\"FACIAL_L_12IPV_ForeheadIn4\",\"FACIAL_L_12IPV_ForeheadIn5\",\"FACIAL_L_12IPV_ForeheadIn6\",\"FACIAL_L_12IPV_ForeheadIn7\",\"FACIAL_L_12IPV_ForeheadIn8\",\"FACIAL_L_12IPV_ForeheadIn9\",\"FACIAL_L_12IPV_ForeheadIn10\",\"FACIAL_L_12IPV_ForeheadIn11\",\"FACIAL_L_12IPV_ForeheadIn12\",\"FACIAL_L_12IPV_ForeheadIn13\",\"FACIAL_L_12IPV_ForeheadIn14\",\"FACIAL_R_ForeheadIn\",\"FACIAL_R_ForeheadInA1\",\"FACIAL_R_ForeheadInA2\",\"FACIAL_R_ForeheadInA3\",\"FACIAL_R_ForeheadInB1\",\"FACIAL_R_ForeheadInB2\",\"FACIAL_R_12IPV_ForeheadIn1\",\"FACIAL_R_12IPV_ForeheadIn2\",\"FACIAL_R_12IPV_ForeheadIn3\",\"FACIAL_R_12IPV_ForeheadIn5\",\"FACIAL_R_12IPV_ForeheadIn4\",\"FACIAL_R_12IPV_ForeheadIn6\",\"FACIAL_R_12IPV_ForeheadIn7\",\"FACIAL_R_12IPV_ForeheadIn8\",\"FACIAL_R_12IPV_ForeheadIn9\",\"FACIAL_R_12IPV_ForeheadIn10\",\"FACIAL_R_12IPV_ForeheadIn12\",\"FACIAL_R_12IPV_ForeheadIn11\",\"FACIAL_R_12IPV_ForeheadIn13\",\"FACIAL_R_12IPV_ForeheadIn14\",\"FACIAL_L_ForeheadMid\",\"FACIAL_L_ForeheadMid1\",\"FACIAL_L_ForeheadMid2\",\"FACIAL_L_12IPV_ForeheadMid15\",\"FACIAL_L_12IPV_ForeheadMid16\",\"FACIAL_L_12IPV_ForeheadMid17\",\"FACIAL_L_12IPV_ForeheadMid18\",\"FACIAL_L_12IPV_ForeheadMid19\",\"FACIAL_L_12IPV_ForeheadMid20\",\"FACIAL_L_12IPV_ForeheadMid21\",\"FACIAL_L_12IPV_ForeheadMid22\",\"FACIAL_R_ForeheadMid\",\"FACIAL_R_ForeheadMid1\",\"FACIAL_R_ForeheadMid2\",\"FACIAL_R_12IPV_ForeheadMid15\",\"FACIAL_R_12IPV_ForeheadMid16\",\"FACIAL_R_12IPV_ForeheadMid17\",\"FACIAL_R_12IPV_ForeheadMid18\",\"FACIAL_R_12IPV_ForeheadMid19\",\"FACIAL_R_12IPV_ForeheadMid20\",\"FACIAL_R_12IPV_ForeheadMid21\",\"FACIAL_R_12IPV_ForeheadMid22\",\"FACIAL_L_ForeheadOut\",\"FACIAL_L_ForeheadOutA1\",\"FACIAL_L_ForeheadOutA2\",\"FACIAL_L_ForeheadOutB1\",\"FACIAL_L_ForeheadOutB2\",\"FACIAL_L_12IPV_ForeheadOut23\",\"FACIAL_L_12IPV_ForeheadOut24\",\"FACIAL_L_12IPV_ForeheadOut25\",\"FACIAL_L_12IPV_ForeheadOut26\",\"FACIAL_L_12IPV_ForeheadOut27\",\"FACIAL_L_12IPV_ForeheadOut28\",\"FACIAL_L_12IPV_ForeheadOut29\",\"FACIAL_L_12IPV_ForeheadOut30\",\"FACIAL_L_12IPV_ForeheadOut31\",\"FACIAL_L_12IPV_ForeheadOut32\",\"FACIAL_R_ForeheadOut\",\"FACIAL_R_ForeheadOutA1\",\"FACIAL_R_ForeheadOutA2\",\"FACIAL_R_ForeheadOutB1\",\"FACIAL_R_ForeheadOutB2\",\"FACIAL_R_12IPV_ForeheadOut23\",\"FACIAL_R_12IPV_ForeheadOut24\",\"FACIAL_R_12IPV_ForeheadOut25\",\"FACIAL_R_12IPV_ForeheadOut26\",\"FACIAL_R_12IPV_ForeheadOut27\",\"FACIAL_R_12IPV_ForeheadOut28\",\"FACIAL_R_12IPV_ForeheadOut29\",\"FACIAL_R_12IPV_ForeheadOut30\",\"FACIAL_R_12IPV_ForeheadOut31\",\"FACIAL_R_12IPV_ForeheadOut32\",\"FACIAL_L_12IPV_EyesackU0\",\"FACIAL_R_12IPV_EyesackU0\",\"FACIAL_L_EyesackUpper\",\"FACIAL_L_EyesackUpper1\",\"FACIAL_L_EyesackUpper2\",\"FACIAL_L_EyesackUpper3\",\"FACIAL_R_EyesackUpper\",\"FACIAL_R_EyesackUpper1\",\"FACIAL_R_EyesackUpper2\",\"FACIAL_R_EyesackUpper3\",\"FACIAL_L_EyesackUpper4\",\"FACIAL_R_EyesackUpper4\",\"FACIAL_L_EyelidUpperFurrow\",\"FACIAL_L_EyelidUpperFurrow1\",\"FACIAL_L_EyelidUpperFurrow2\",\"FACIAL_L_EyelidUpperFurrow3\",\"FACIAL_R_EyelidUpperFurrow\",\"FACIAL_R_EyelidUpperFurrow1\",\"FACIAL_R_EyelidUpperFurrow2\",\"FACIAL_R_EyelidUpperFurrow3\",\"FACIAL_L_EyelidUpperB\",\"FACIAL_L_EyelidUpperB1\",\"FACIAL_L_EyelidUpperB2\",\"FACIAL_L_EyelidUpperB3\",\"FACIAL_R_EyelidUpperB\",\"FACIAL_R_EyelidUpperB1\",\"FACIAL_R_EyelidUpperB2\",\"FACIAL_R_EyelidUpperB3\",\"FACIAL_L_EyelidUpperA\",\"FACIAL_L_EyelidUpperA1\",\"FACIAL_L_EyelashesUpperA1\",\"FACIAL_L_EyelidUpperA2\",\"FACIAL_L_EyelashesUpperA2\",\"FACIAL_L_EyelidUpperA3\",\"FACIAL_L_EyelashesUpperA3\",\"FACIAL_R_EyelidUpperA\",\"FACIAL_R_EyelidUpperA1\",\"FACIAL_R_EyelashesUpperA1\",\"FACIAL_R_EyelidUpperA2\",\"FACIAL_R_EyelashesUpperA2\",\"FACIAL_R_EyelidUpperA3\",\"FACIAL_R_EyelashesUpperA3\",\"FACIAL_L_Eye\",\"FACIAL_L_EyeParallel\",\"FACIAL_L_Pupil\",\"FACIAL_R_Eye\",\"FACIAL_R_EyeParallel\",\"FACIAL_R_Pupil\",\"FACIAL_L_EyelidLowerA\",\"FACIAL_L_EyelidLowerA1\",\"FACIAL_L_EyelidLowerA2\",\"FACIAL_L_EyelidLowerA3\",\"FACIAL_R_EyelidLowerA\",\"FACIAL_R_EyelidLowerA1\",\"FACIAL_R_EyelidLowerA2\",\"FACIAL_R_EyelidLowerA3\",\"FACIAL_L_EyelidLowerB\",\"FACIAL_L_EyelidLowerB1\",\"FACIAL_L_EyelidLowerB2\",\"FACIAL_L_EyelidLowerB3\",\"FACIAL_R_EyelidLowerB\",\"FACIAL_R_EyelidLowerB1\",\"FACIAL_R_EyelidLowerB2\",\"FACIAL_R_EyelidLowerB3\",\"FACIAL_L_EyeCornerInner\",\"FACIAL_L_EyeCornerInner1\",\"FACIAL_L_EyeCornerInner2\",\"FACIAL_R_EyeCornerInner\",\"FACIAL_R_EyeCornerInner1\",\"FACIAL_R_EyeCornerInner2\",\"FACIAL_L_EyeCornerOuter\",\"FACIAL_L_EyeCornerOuter1\",\"FACIAL_L_EyelashesCornerOuter1\",\"FACIAL_L_EyeCornerOuter2\",\"FACIAL_R_EyeCornerOuter\",\"FACIAL_R_EyeCornerOuter1\",\"FACIAL_R_EyelashesCornerOuter1\",\"FACIAL_R_EyeCornerOuter2\",\"FACIAL_L_12IPV_EyeCornerO1\",\"FACIAL_R_12IPV_EyeCornerO1\",\"FACIAL_L_12IPV_EyeCornerO2\",\"FACIAL_R_12IPV_EyeCornerO2\",\"FACIAL_L_EyesackLower\",\"FACIAL_L_EyesackLower1\",\"FACIAL_L_EyesackLower2\",\"FACIAL_L_12IPV_EyesackL1\",\"FACIAL_L_12IPV_EyesackL2\",\"FACIAL_L_12IPV_EyesackL3\",\"FACIAL_L_12IPV_EyesackL4\",\"FACIAL_L_12IPV_EyesackL5\",\"FACIAL_L_12IPV_EyesackL6\",\"FACIAL_L_12IPV_EyesackL7\",\"FACIAL_L_12IPV_EyesackL8\",\"FACIAL_R_EyesackLower\",\"FACIAL_R_EyesackLower1\",\"FACIAL_R_EyesackLower2\",\"FACIAL_R_12IPV_EyesackL1\",\"FACIAL_R_12IPV_EyesackL2\",\"FACIAL_R_12IPV_EyesackL3\",\"FACIAL_R_12IPV_EyesackL4\",\"FACIAL_R_12IPV_EyesackL5\",\"FACIAL_R_12IPV_EyesackL6\",\"FACIAL_R_12IPV_EyesackL7\",\"FACIAL_R_12IPV_EyesackL8\",\"FACIAL_L_CheekInner\",\"FACIAL_L_CheekInner1\",\"FACIAL_L_CheekInner2\",\"FACIAL_L_CheekInner3\",\"FACIAL_L_CheekInner4\",\"FACIAL_R_CheekInner\",\"FACIAL_R_CheekInner1\",\"FACIAL_R_CheekInner2\",\"FACIAL_R_CheekInner3\",\"FACIAL_R_CheekInner4\",\"FACIAL_L_CheekOuter\",\"FACIAL_L_CheekOuter1\",\"FACIAL_L_CheekOuter2\",\"FACIAL_L_CheekOuter3\",\"FACIAL_R_CheekOuter\",\"FACIAL_R_CheekOuter1\",\"FACIAL_R_CheekOuter2\",\"FACIAL_R_CheekOuter3\",\"FACIAL_L_CheekOuter4\",\"FACIAL_R_CheekOuter4\",\"FACIAL_L_12IPV_CheekOuter1\",\"FACIAL_R_12IPV_CheekOuter1\",\"FACIAL_L_12IPV_CheekOuter2\",\"FACIAL_R_12IPV_CheekOuter2\",\"FACIAL_L_12IPV_CheekOuter3\",\"FACIAL_R_12IPV_CheekOuter3\",\"FACIAL_L_12IPV_CheekOuter4\",\"FACIAL_R_12IPV_CheekOuter4\",\"FACIAL_C_NoseBridge\",\"FACIAL_C_12IPV_NoseBridge1\",\"FACIAL_L_12IPV_NoseBridge1\",\"FACIAL_R_12IPV_NoseBridge1\",\"FACIAL_C_12IPV_NoseBridge2\",\"FACIAL_L_12IPV_NoseBridge2\",\"FACIAL_R_12IPV_NoseBridge2\",\"FACIAL_L_NoseBridge\",\"FACIAL_R_NoseBridge\",\"FACIAL_C_NoseUpper\",\"FACIAL_L_NoseUpper\",\"FACIAL_R_NoseUpper\",\"FACIAL_C_12IPV_NoseUpper1\",\"FACIAL_C_12IPV_NoseUpper2\",\"FACIAL_L_12IPV_NoseUpper1\",\"FACIAL_R_12IPV_NoseUpper1\",\"FACIAL_L_12IPV_NoseUpper2\",\"FACIAL_R_12IPV_NoseUpper2\",\"FACIAL_L_12IPV_NoseUpper3\",\"FACIAL_R_12IPV_NoseUpper3\",\"FACIAL_L_12IPV_NoseUpper4\",\"FACIAL_R_12IPV_NoseUpper4\",\"FACIAL_L_12IPV_NoseUpper5\",\"FACIAL_R_12IPV_NoseUpper5\",\"FACIAL_L_12IPV_NoseUpper6\",\"FACIAL_R_12IPV_NoseUpper6\",\"FACIAL_L_NasolabialBulge1\",\"FACIAL_R_NasolabialBulge1\",\"FACIAL_L_12IPV_NasolabialB13\",\"FACIAL_R_12IPV_NasolabialB13\",\"FACIAL_L_12IPV_NasolabialB14\",\"FACIAL_R_12IPV_NasolabialB14\",\"FACIAL_L_12IPV_NasolabialB15\",\"FACIAL_R_12IPV_NasolabialB15\",\"FACIAL_L_NasolabialBulge\",\"FACIAL_L_NasolabialBulge2\",\"FACIAL_L_NasolabialBulge3\",\"FACIAL_L_12IPV_NasolabialB1\",\"FACIAL_L_12IPV_NasolabialB2\",\"FACIAL_L_12IPV_NasolabialB3\",\"FACIAL_L_12IPV_NasolabialB4\",\"FACIAL_L_12IPV_NasolabialB5\",\"FACIAL_L_12IPV_NasolabialB6\",\"FACIAL_L_12IPV_NasolabialB7\",\"FACIAL_L_12IPV_NasolabialB8\",\"FACIAL_L_12IPV_NasolabialB9\",\"FACIAL_L_12IPV_NasolabialB10\",\"FACIAL_L_12IPV_NasolabialB11\",\"FACIAL_L_12IPV_NasolabialB12\",\"FACIAL_R_NasolabialBulge\",\"FACIAL_R_NasolabialBulge2\",\"FACIAL_R_NasolabialBulge3\",\"FACIAL_R_12IPV_NasolabialB1\",\"FACIAL_R_12IPV_NasolabialB2\",\"FACIAL_R_12IPV_NasolabialB3\",\"FACIAL_R_12IPV_NasolabialB4\",\"FACIAL_R_12IPV_NasolabialB5\",\"FACIAL_R_12IPV_NasolabialB6\",\"FACIAL_R_12IPV_NasolabialB7\",\"FACIAL_R_12IPV_NasolabialB8\",\"FACIAL_R_12IPV_NasolabialB9\",\"FACIAL_R_12IPV_NasolabialB10\",\"FACIAL_R_12IPV_NasolabialB11\",\"FACIAL_R_12IPV_NasolabialB12\",\"FACIAL_L_NasolabialFurrow\",\"FACIAL_R_NasolabialFurrow\",\"FACIAL_L_12IPV_NasolabialF1\",\"FACIAL_R_12IPV_NasolabialF1\",\"FACIAL_L_12IPV_NasolabialF2\",\"FACIAL_R_12IPV_NasolabialF2\",\"FACIAL_L_12IPV_NasolabialF3\",\"FACIAL_R_12IPV_NasolabialF3\",\"FACIAL_L_12IPV_NasolabialF4\",\"FACIAL_R_12IPV_NasolabialF4\",\"FACIAL_L_12IPV_NasolabialF5\",\"FACIAL_R_12IPV_NasolabialF5\",\"FACIAL_L_12IPV_NasolabialF6\",\"FACIAL_R_12IPV_NasolabialF6\",\"FACIAL_L_12IPV_NasolabialF7\",\"FACIAL_R_12IPV_NasolabialF7\",\"FACIAL_L_12IPV_NasolabialF8\",\"FACIAL_R_12IPV_NasolabialF8\",\"FACIAL_L_12IPV_NasolabialF9\",\"FACIAL_R_12IPV_NasolabialF9\",\"FACIAL_L_CheekLower\",\"FACIAL_L_CheekLower1\",\"FACIAL_L_CheekLower2\",\"FACIAL_L_12IPV_CheekL1\",\"FACIAL_L_12IPV_CheekL2\",\"FACIAL_L_12IPV_CheekL3\",\"FACIAL_L_12IPV_CheekL4\",\"FACIAL_R_CheekLower\",\"FACIAL_R_CheekLower1\",\"FACIAL_R_CheekLower2\",\"FACIAL_R_12IPV_CheekL1\",\"FACIAL_R_12IPV_CheekL2\",\"FACIAL_R_12IPV_CheekL3\",\"FACIAL_R_12IPV_CheekL4\",\"FACIAL_L_Ear\",\"FACIAL_L_Ear1\",\"FACIAL_L_Ear2\",\"FACIAL_L_Ear3\",\"FACIAL_L_Ear4\",\"FACIAL_R_Ear\",\"FACIAL_R_Ear1\",\"FACIAL_R_Ear2\",\"FACIAL_R_Ear3\",\"FACIAL_R_Ear4\",\"FACIAL_C_Nose\",\"FACIAL_C_NoseLower\",\"FACIAL_L_NostrilThickness3\",\"FACIAL_R_NostrilThickness3\",\"FACIAL_C_12IPV_NoseL1\",\"FACIAL_C_12IPV_NoseL2\",\"FACIAL_C_NoseTip\",\"FACIAL_C_12IPV_NoseTip1\",\"FACIAL_C_12IPV_NoseTip2\",\"FACIAL_C_12IPV_NoseTip3\",\"FACIAL_L_12IPV_NoseTip1\",\"FACIAL_R_12IPV_NoseTip1\",\"FACIAL_L_12IPV_NoseTip2\",\"FACIAL_R_12IPV_NoseTip2\",\"FACIAL_L_12IPV_NoseTip3\",\"FACIAL_R_12IPV_NoseTip3\",\"FACIAL_L_Nostril\",\"FACIAL_L_NostrilThickness1\",\"FACIAL_L_NostrilThickness2\",\"FACIAL_L_12IPV_Nostril1\",\"FACIAL_L_12IPV_Nostril2\",\"FACIAL_L_12IPV_Nostril3\",\"FACIAL_L_12IPV_Nostril4\",\"FACIAL_L_12IPV_Nostril5\",\"FACIAL_L_12IPV_Nostril6\",\"FACIAL_L_12IPV_Nostril7\",\"FACIAL_L_12IPV_Nostril8\",\"FACIAL_L_12IPV_Nostril9\",\"FACIAL_L_12IPV_Nostril10\",\"FACIAL_L_12IPV_Nostril11\",\"FACIAL_L_12IPV_Nostril12\",\"FACIAL_L_12IPV_Nostril13\",\"FACIAL_L_12IPV_Nostril14\",\"FACIAL_R_Nostril\",\"FACIAL_R_NostrilThickness1\",\"FACIAL_R_NostrilThickness2\",\"FACIAL_R_12IPV_Nostril1\",\"FACIAL_R_12IPV_Nostril2\",\"FACIAL_R_12IPV_Nostril3\",\"FACIAL_R_12IPV_Nostril4\",\"FACIAL_R_12IPV_Nostril5\",\"FACIAL_R_12IPV_Nostril6\",\"FACIAL_R_12IPV_Nostril7\",\"FACIAL_R_12IPV_Nostril8\",\"FACIAL_R_12IPV_Nostril9\",\"FACIAL_R_12IPV_Nostril10\",\"FACIAL_R_12IPV_Nostril11\",\"FACIAL_R_12IPV_Nostril12\",\"FACIAL_R_12IPV_Nostril13\",\"FACIAL_R_12IPV_Nostril14\",\"FACIAL_C_LipUpperSkin\",\"FACIAL_L_LipUpperSkin\",\"FACIAL_R_LipUpperSkin\",\"FACIAL_L_LipUpperOuterSkin\",\"FACIAL_R_LipUpperOuterSkin\",\"FACIAL_C_12IPV_LipUpperSkin1\",\"FACIAL_C_12IPV_LipUpperSkin2\",\"FACIAL_L_12IPV_LipUpperSkin\",\"FACIAL_R_12IPV_LipUpperSkin\",\"FACIAL_L_12IPV_LipUpperOuterSkin1\",\"FACIAL_R_12IPV_LipUpperOuterSkin1\",\"FACIAL_L_12IPV_LipUpperOuterSkin2\",\"FACIAL_R_12IPV_LipUpperOuterSkin2\",\"FACIAL_L_12IPV_MouthInteriorUpper1\",\"FACIAL_R_12IPV_MouthInteriorUpper1\",\"FACIAL_L_12IPV_MouthInteriorUpper2\",\"FACIAL_R_12IPV_MouthInteriorUpper2\",\"FACIAL_C_MouthUpper\",\"FACIAL_C_LipUpper\",\"FACIAL_C_LipUpper1\",\"FACIAL_C_LipUpper2\",\"FACIAL_C_LipUpper3\",\"FACIAL_L_12IPV_LipUpper1\",\"FACIAL_R_12IPV_LipUpper1\",\"FACIAL_L_12IPV_LipUpper2\",\"FACIAL_R_12IPV_LipUpper2\",\"FACIAL_L_12IPV_LipUpper3\",\"FACIAL_R_12IPV_LipUpper3\",\"FACIAL_L_12IPV_LipUpper4\",\"FACIAL_R_12IPV_LipUpper4\",\"FACIAL_L_12IPV_LipUpper5\",\"FACIAL_R_12IPV_LipUpper5\",\"FACIAL_L_LipUpper\",\"FACIAL_L_LipUpper1\",\"FACIAL_L_LipUpper2\",\"FACIAL_L_LipUpper3\",\"FACIAL_L_12IPV_LipUpper6\",\"FACIAL_L_12IPV_LipUpper7\",\"FACIAL_L_12IPV_LipUpper8\",\"FACIAL_L_12IPV_LipUpper9\",\"FACIAL_L_12IPV_LipUpper10\",\"FACIAL_L_12IPV_LipUpper11\",\"FACIAL_L_12IPV_LipUpper12\",\"FACIAL_L_12IPV_LipUpper13\",\"FACIAL_L_12IPV_LipUpper14\",\"FACIAL_L_12IPV_LipUpper15\",\"FACIAL_R_LipUpper\",\"FACIAL_R_LipUpper1\",\"FACIAL_R_LipUpper2\",\"FACIAL_R_LipUpper3\",\"FACIAL_R_12IPV_LipUpper6\",\"FACIAL_R_12IPV_LipUpper7\",\"FACIAL_R_12IPV_LipUpper8\",\"FACIAL_R_12IPV_LipUpper9\",\"FACIAL_R_12IPV_LipUpper10\",\"FACIAL_R_12IPV_LipUpper11\",\"FACIAL_R_12IPV_LipUpper12\",\"FACIAL_R_12IPV_LipUpper13\",\"FACIAL_R_12IPV_LipUpper14\",\"FACIAL_R_12IPV_LipUpper15\",\"FACIAL_L_LipUpperOuter\",\"FACIAL_L_LipUpperOuter1\",\"FACIAL_L_LipUpperOuter2\",\"FACIAL_L_LipUpperOuter3\",\"FACIAL_L_12IPV_LipUpper16\",\"FACIAL_L_12IPV_LipUpper17\",\"FACIAL_L_12IPV_LipUpper18\",\"FACIAL_L_12IPV_LipUpper19\",\"FACIAL_L_12IPV_LipUpper20\",\"FACIAL_L_12IPV_LipUpper21\",\"FACIAL_L_12IPV_LipUpper22\",\"FACIAL_L_12IPV_LipUpper23\",\"FACIAL_L_12IPV_LipUpper24\",\"FACIAL_R_LipUpperOuter\",\"FACIAL_R_LipUpperOuter1\",\"FACIAL_R_LipUpperOuter2\",\"FACIAL_R_LipUpperOuter3\",\"FACIAL_R_12IPV_LipUpper16\",\"FACIAL_R_12IPV_LipUpper17\",\"FACIAL_R_12IPV_LipUpper18\",\"FACIAL_R_12IPV_LipUpper19\",\"FACIAL_R_12IPV_LipUpper20\",\"FACIAL_R_12IPV_LipUpper21\",\"FACIAL_R_12IPV_LipUpper22\",\"FACIAL_R_12IPV_LipUpper23\",\"FACIAL_R_12IPV_LipUpper24\",\"FACIAL_L_LipCorner\",\"FACIAL_L_LipCorner1\",\"FACIAL_L_LipCorner2\",\"FACIAL_L_LipCorner3\",\"FACIAL_L_12IPV_LipCorner1\",\"FACIAL_L_12IPV_LipCorner2\",\"FACIAL_L_12IPV_LipCorner3\",\"FACIAL_R_LipCorner\",\"FACIAL_R_LipCorner1\",\"FACIAL_R_LipCorner2\",\"FACIAL_R_LipCorner3\",\"FACIAL_R_12IPV_LipCorner1\",\"FACIAL_R_12IPV_LipCorner2\",\"FACIAL_R_12IPV_LipCorner3\",\"FACIAL_L_JawBulge\",\"FACIAL_R_JawBulge\",\"FACIAL_L_JawRecess\",\"FACIAL_R_JawRecess\",\"FACIAL_L_Masseter\",\"FACIAL_R_Masseter\",\"FACIAL_C_UnderChin\",\"FACIAL_L_12IPV_UnderChin1\",\"FACIAL_R_12IPV_UnderChin1\",\"FACIAL_L_12IPV_UnderChin2\",\"FACIAL_R_12IPV_UnderChin2\",\"FACIAL_L_UnderChin\",\"FACIAL_R_UnderChin\",\"FACIAL_L_12IPV_UnderChin3\",\"FACIAL_R_12IPV_UnderChin3\",\"FACIAL_L_12IPV_UnderChin4\",\"FACIAL_R_12IPV_UnderChin4\",\"FACIAL_L_12IPV_UnderChin5\",\"FACIAL_R_12IPV_UnderChin5\",\"FACIAL_L_12IPV_UnderChin6\",\"FACIAL_R_12IPV_UnderChin6\",\"FACIAL_C_TeethUpper\",\"FACIAL_C_LowerLipRotation\",\"FACIAL_C_LipLowerSkin\",\"FACIAL_L_LipLowerSkin\",\"FACIAL_R_LipLowerSkin\",\"FACIAL_L_LipLowerOuterSkin\",\"FACIAL_R_LipLowerOuterSkin\",\"FACIAL_C_12IPV_LipLowerSkin1\",\"FACIAL_C_12IPV_LipLowerSkin2\",\"FACIAL_L_12IPV_LipLowerSkin\",\"FACIAL_R_12IPV_LipLowerSkin\",\"FACIAL_L_12IPV_LipLowerOuterSkin1\",\"FACIAL_R_12IPV_LipLowerOuterSkin1\",\"FACIAL_L_12IPV_LipLowerOuterSkin2\",\"FACIAL_R_12IPV_LipLowerOuterSkin2\",\"FACIAL_L_12IPV_LipLowerOuterSkin3\",\"FACIAL_R_12IPV_LipLowerOuterSkin3\",\"FACIAL_L_12IPV_MouthInteriorLower1\",\"FACIAL_R_12IPV_MouthInteriorLower1\",\"FACIAL_L_12IPV_MouthInteriorLower2\",\"FACIAL_R_12IPV_MouthInteriorLower2\",\"FACIAL_C_MouthLower\",\"FACIAL_C_LipLower\",\"FACIAL_C_LipLower1\",\"FACIAL_C_LipLower2\",\"FACIAL_C_LipLower3\",\"FACIAL_L_12IPV_LipLower1\",\"FACIAL_R_12IPV_LipLower1\",\"FACIAL_L_12IPV_LipLower2\",\"FACIAL_R_12IPV_LipLower2\",\"FACIAL_L_12IPV_LipLower3\",\"FACIAL_R_12IPV_LipLower3\",\"FACIAL_L_12IPV_LipLower4\",\"FACIAL_R_12IPV_LipLower4\",\"FACIAL_L_12IPV_LipLower5\",\"FACIAL_R_12IPV_LipLower5\",\"FACIAL_L_LipLower\",\"FACIAL_L_LipLower1\",\"FACIAL_L_LipLower2\",\"FACIAL_L_LipLower3\",\"FACIAL_L_12IPV_LipLower6\",\"FACIAL_L_12IPV_LipLower7\",\"FACIAL_L_12IPV_LipLower8\",\"FACIAL_L_12IPV_LipLower9\",\"FACIAL_L_12IPV_LipLower10\",\"FACIAL_L_12IPV_LipLower11\",\"FACIAL_L_12IPV_LipLower12\",\"FACIAL_L_12IPV_LipLower13\",\"FACIAL_L_12IPV_LipLower14\",\"FACIAL_L_12IPV_LipLower15\",\"FACIAL_R_LipLower\",\"FACIAL_R_LipLower1\",\"FACIAL_R_LipLower2\",\"FACIAL_R_LipLower3\",\"FACIAL_R_12IPV_LipLower6\",\"FACIAL_R_12IPV_LipLower7\",\"FACIAL_R_12IPV_LipLower8\",\"FACIAL_R_12IPV_LipLower9\",\"FACIAL_R_12IPV_LipLower10\",\"FACIAL_R_12IPV_LipLower11\",\"FACIAL_R_12IPV_LipLower12\",\"FACIAL_R_12IPV_LipLower13\",\"FACIAL_R_12IPV_LipLower14\",\"FACIAL_R_12IPV_LipLower15\",\"FACIAL_L_LipLowerOuter\",\"FACIAL_L_LipLowerOuter1\",\"FACIAL_L_LipLowerOuter2\",\"FACIAL_L_LipLowerOuter3\",\"FACIAL_L_12IPV_LipLower16\",\"FACIAL_L_12IPV_LipLower17\",\"FACIAL_L_12IPV_LipLower18\",\"FACIAL_L_12IPV_LipLower19\",\"FACIAL_L_12IPV_LipLower20\",\"FACIAL_L_12IPV_LipLower21\",\"FACIAL_L_12IPV_LipLower22\",\"FACIAL_L_12IPV_LipLower23\",\"FACIAL_L_12IPV_LipLower24\",\"FACIAL_R_LipLowerOuter\",\"FACIAL_R_LipLowerOuter1\",\"FACIAL_R_LipLowerOuter2\",\"FACIAL_R_LipLowerOuter3\",\"FACIAL_R_12IPV_LipLower16\",\"FACIAL_R_12IPV_LipLower17\",\"FACIAL_R_12IPV_LipLower18\",\"FACIAL_R_12IPV_LipLower19\",\"FACIAL_R_12IPV_LipLower20\",\"FACIAL_R_12IPV_LipLower21\",\"FACIAL_R_12IPV_LipLower22\",\"FACIAL_R_12IPV_LipLower23\",\"FACIAL_R_12IPV_LipLower24\",\"FACIAL_C_TeethLower\",\"FACIAL_C_Tongue1\",\"FACIAL_C_TongueUpper1\",\"FACIAL_L_TongueSide1\",\"FACIAL_R_TongueSide1\",\"FACIAL_C_Tongue2\",\"FACIAL_C_TongueUpper2\",\"FACIAL_L_TongueSide2\",\"FACIAL_R_TongueSide2\",\"FACIAL_C_Tongue3\",\"FACIAL_C_TongueUpper3\",\"FACIAL_C_TongueLower3\",\"FACIAL_L_TongueSide3\",\"FACIAL_R_TongueSide3\",\"FACIAL_C_Tongue4\",\"FACIAL_L_TongueSide4\",\"FACIAL_R_TongueSide4\",\"FACIAL_C_Jaw\",\"FACIAL_C_Jawline\",\"FACIAL_L_12IPV_Jawline1\",\"FACIAL_R_12IPV_Jawline1\",\"FACIAL_L_12IPV_Jawline2\",\"FACIAL_R_12IPV_Jawline2\",\"FACIAL_L_Jawline\",\"FACIAL_L_Jawline1\",\"FACIAL_L_Jawline2\",\"FACIAL_L_12IPV_Jawline3\",\"FACIAL_L_12IPV_Jawline4\",\"FACIAL_L_12IPV_Jawline5\",\"FACIAL_L_12IPV_Jawline6\",\"FACIAL_R_Jawline\",\"FACIAL_R_Jawline1\",\"FACIAL_R_Jawline2\",\"FACIAL_R_12IPV_Jawline3\",\"FACIAL_R_12IPV_Jawline4\",\"FACIAL_R_12IPV_Jawline5\",\"FACIAL_R_12IPV_Jawline6\",\"FACIAL_L_ChinSide\",\"FACIAL_R_ChinSide\",\"FACIAL_L_12IPV_ChinS1\",\"FACIAL_R_12IPV_ChinS1\",\"FACIAL_L_12IPV_ChinS2\",\"FACIAL_R_12IPV_ChinS2\",\"FACIAL_L_12IPV_ChinS3\",\"FACIAL_R_12IPV_ChinS3\",\"FACIAL_L_12IPV_ChinS4\",\"FACIAL_R_12IPV_ChinS4\",\"FACIAL_C_Chin1\",\"FACIAL_L_Chin1\",\"FACIAL_R_Chin1\",\"FACIAL_C_Chin2\",\"FACIAL_L_Chin2\",\"FACIAL_R_Chin2\",\"FACIAL_C_Chin3\",\"FACIAL_L_Chin3\",\"FACIAL_R_Chin3\",\"FACIAL_L_12IPV_Chin1\",\"FACIAL_R_12IPV_Chin1\",\"FACIAL_L_12IPV_Chin2\",\"FACIAL_R_12IPV_Chin2\",\"FACIAL_C_12IPV_Chin3\",\"FACIAL_C_12IPV_Chin4\",\"FACIAL_L_12IPV_Chin5\",\"FACIAL_R_12IPV_Chin5\",\"FACIAL_L_12IPV_Chin6\",\"FACIAL_R_12IPV_Chin6\",\"FACIAL_L_12IPV_Chin7\",\"FACIAL_R_12IPV_Chin7\",\"FACIAL_L_12IPV_Chin8\",\"FACIAL_R_12IPV_Chin8\",\"FACIAL_L_12IPV_Chin9\",\"FACIAL_R_12IPV_Chin9\",\"FACIAL_L_12IPV_Chin10\",\"FACIAL_R_12IPV_Chin10\",\"FACIAL_L_12IPV_Chin11\",\"FACIAL_R_12IPV_Chin11\",\"FACIAL_L_12IPV_Chin12\",\"FACIAL_R_12IPV_Chin12\",\"FACIAL_L_12IPV_Chin13\",\"FACIAL_R_12IPV_Chin13\",\"FACIAL_L_12IPV_Chin14\",\"FACIAL_R_12IPV_Chin14\",\"FACIAL_C_Chin\"];\n\n// 86 bones \u00D7 3 floats (x, y, z)\nexport const REST_TRANSLATIONS: number[] = [0,0,0,0.0233437,0.9007828,0,-0.0015207,0,-0.0356119,0,2e-7,-0.063712,0,3e-7,-0.0712212,0,9e-7,-0.0904171,0,0.0000012,-0.1286658,0.0057265,0.0000015,-0.1590279,0,5e-7,-0.052265,-0.0000358,5e-7,-0.0541058,-0.0093304,-0.0114715,-0.1015913,0.0000012,-0.0012262,-0.1655814,2e-7,0,-0.2716819,1e-7,-3e-7,-0.2593559,-0.0044057,0.0185658,-0.0276724,1e-7,0,-0.0463796,0,0,-0.0292089,0,0,-0.0187035,-0.0025285,0.0069261,-0.0286998,-1e-7,0,-0.0493868,0,0,-0.0407549,0,0,-0.0313077,-0.0135881,-0.0229554,-0.0166282,0,-1e-7,-0.04589,0,0,-0.0280468,-0.0013554,-0.003889,-0.0289802,0,0,-0.054799,-1e-7,-1e-7,-0.0465886,-1e-7,-1e-7,-0.0294016,-0.0021233,-0.0205175,-0.0314949,0,0,-0.0518244,0,0,-0.042275,0,0,-0.0229874,-0.0093304,0.0114733,-0.101591,0.0000013,0.0012213,0.1655815,3e-7,0,0.271682,3e-7,-2e-7,0.2593558,0.0044056,-0.0185658,0.0276723,0,0,0.0463795,0,0,0.0292088,0,0,0.0187035,0.0025285,-0.0069261,0.0286997,0,0,0.0493868,0,0,0.040755,0,0,0.0313077,0.013588,0.0229554,0.0166282,0,-2e-7,0.04589,0,0,0.0280468,0.0013553,0.003889,0.0289802,0,0,0.054799,1e-7,0,0.0465887,0,1e-7,0.0294016,0.0021231,0.0205174,0.0314949,-2e-7,0,0.0518244,0,0,0.042275,-1e-7,0,0.0229876,0.0018911,0.0949354,0.0108068,0.0000013,0,-0.4183219,-1e-7,0,-0.392278,-0.1390173,0.0029359,-0.0656343,0.005855,0.0473655,-0.0110311,0.0016728,0.0006973,0.0154311,0.0110356,0.0320973,-0.0011842,0.0003611,0.0039117,0.0209273,0.0133392,0.0163956,0.0058485,-0.0010228,0.0035978,0.0242602,0.0118184,-0.0286874,0.0098808,-0.0015024,0.0007765,0.0313131,0.0150648,-0.00248,0.0074855,-0.0016026,0.0029361,0.0303304,-0.0000021,-7e-7,-0.2618881,0.0018912,-0.0949353,0.0108068,-0.0000013,0,0.4183218,1e-7,0,0.392278,0.1390174,-0.0029358,0.0656343,-0.0150648,0.00248,-0.0074855,0.0016026,-0.0029361,-0.0303304,-0.0118184,0.0286874,-0.0098808,0.0015024,-0.0007765,-0.0313131,-0.005855,-0.0473656,0.0110311,-0.0016728,-0.0006973,-0.0154311,-0.0133392,-0.0163956,-0.0058485,0.0010228,-0.0035978,-0.0242602,-0.0110356,-0.0320974,0.0011842,-0.0003611,-0.0039117,-0.0209273,0.0000021,7e-7,0.261888];\n\n// 86 bones \u00D7 4 floats (qx, qy, qz, qw)\nexport const REST_ROTATIONS: number[] = [0,0,0,-1,-0.7069933,0.012667,0.0126671,-0.7069933,0.0000019,0.0954121,4e-7,-0.9954379,0,-0.0638428,0,-0.99796,0.0000031,-0.0828618,-3e-7,-0.9965611,0,-0.0743946,0,-0.9972289,-1e-7,0.0133748,2e-7,-0.9999105,-1e-7,0.2006889,-1e-7,-0.979655,0,-0.0078937,0,-0.9999688,0,-0.099543,0,-0.9950333,0.7475424,0.0537591,0.078301,-0.6573883,0.3846423,0.0111753,-0.0260349,-0.9226308,2e-7,0.3143818,-1e-7,-0.9492966,1e-7,-1e-7,-0.7071068,-0.7071068,-0.1810116,-0.0874972,-0.0672794,-0.9772679,0,-0.1045285,0,-0.9945219,0,-0.1736482,0,-0.9848077,0,-0.0348995,0,-0.9993908,-0.1045125,0.0018243,-0.0173568,-0.9943704,0,-0.1564345,0,-0.9876884,0,-0.2164396,0,-0.976296,0,-0.0436194,0,-0.9990482,0.3371452,0.0446987,0.5606716,-0.7549719,0,-0.1736482,0,-0.9848077,0,-0.0871558,0,-0.9961947,-0.0090226,0.0435558,0.0065938,-0.9989885,0,-0.2079117,0,-0.9781476,0,-0.1736482,0,-0.9848077,0,-0.0348995,0,-0.9993908,0.0522085,0.0036507,0.0696609,-0.9961969,0,-0.1736481,0,-0.9848078,0,-0.1045285,0,-0.9945219,0,-0.0348995,0,-0.9993908,0.0782987,-0.6573692,-0.7475592,-0.0537623,0.3846281,0.0111704,-0.0260382,-0.9226367,-2e-7,0.3143817,2e-7,-0.9492967,-1e-7,0,-0.7071068,-0.7071068,-0.1810116,-0.0874972,-0.0672793,-0.9772679,0,-0.1045284,0,-0.9945219,0,-0.1736482,0,-0.9848077,0,-0.0348995,0,-0.9993908,-0.1045125,0.0018243,-0.0173568,-0.9943704,0,-0.1564345,0,-0.9876884,0,-0.2164396,0,-0.976296,0,-0.0436194,0,-0.9990482,0.3371452,0.0446988,0.5606716,-0.7549718,0,-0.1736482,0,-0.9848077,0,-0.0871557,0,-0.9961947,-0.0090226,0.0435558,0.006594,-0.9989885,0,-0.2079117,0,-0.9781476,0,-0.1736482,0,-0.9848077,0,-0.0348995,0,-0.9993908,0.0522085,0.0036508,0.069661,-0.9961969,0,-0.1736482,0,-0.9848077,0,-0.1045285,0,-0.9945219,0,-0.0348995,0,-0.9993908,-0.0740464,0.9969521,-0.0227449,-0.0092877,1e-7,0.0090163,2e-7,-0.9999593,0.0246332,0,2e-7,-0.9996966,0,0.7071068,-2e-7,-0.7071068,0.0067881,0.11322,-0.03924,-0.9927716,1e-7,0.0871557,2e-7,-0.9961947,0.0067881,0.11322,-0.03924,-0.9927716,1e-7,0.0871557,2e-7,-0.9961947,0.0067881,0.11322,-0.03924,-0.9927716,1e-7,0.0871557,2e-7,-0.9961947,0.0372693,0.0284231,-0.0022392,-0.9988984,0,0,0,-1,0.0319268,0.0741281,-0.0043309,-0.9967281,-1e-7,0.1045285,-1e-7,-0.9945219,0,0,0,-1,-0.0227449,-0.0092877,0.0740464,-0.9969521,1e-7,0.0090163,2e-7,-0.9999593,0.0246332,0,3e-7,-0.9996966,0,0.7071068,-2e-7,-0.7071068,0.0319268,0.0741281,-0.0043309,-0.9967281,-1e-7,0.1045285,-1e-7,-0.9945219,0.0372693,0.0284231,-0.0022392,-0.9988984,0,0,0,-1,0.0067881,0.11322,-0.03924,-0.9927716,1e-7,0.0871557,2e-7,-0.9961947,0.0067881,0.11322,-0.03924,-0.9927716,1e-7,0.0871557,2e-7,-0.9961947,0.0067881,0.11322,-0.03924,-0.9927716,1e-7,0.0871557,2e-7,-0.9961947,0,0,0,-1];\n\n// 86 bone parent indices (-1 = root)\nexport const PARENTS: number[] = [-1,0,1,2,3,4,5,6,7,8,6,10,11,12,13,14,15,16,13,18,19,20,13,22,23,13,25,26,27,13,29,30,31,6,33,34,35,36,37,38,39,36,41,42,43,36,45,46,36,48,49,50,36,52,53,54,1,56,57,58,59,60,59,62,59,64,59,66,59,68,57,1,71,72,73,74,75,74,77,74,79,74,81,74,83,72];\n", "// Auto-generated canonical 441-bone skeleton data.\n// Source (out-of-tree authoring inputs, not part of this package):\n// std_male_skeleton_readable.json + _BONE_NAMES_441 from pkl_to_glb.\n// Do not edit manually.\n\nexport const NUM_BONES_441 = 441;\n\nexport const BONE_NAMES_441: string[] = [\"root\",\"pelvis\",\"spine_01\",\"spine_02\",\"spine_03\",\"spine_04\",\"spine_05\",\"neck_01\",\"neck_02\",\"head\",\"clavicle_l\",\"upperarm_l\",\"lowerarm_l\",\"hand_l\",\"pinky_metacarpal_l\",\"pinky_01_l\",\"pinky_02_l\",\"pinky_03_l\",\"ring_metacarpal_l\",\"ring_01_l\",\"ring_02_l\",\"ring_03_l\",\"thumb_01_l\",\"thumb_02_l\",\"thumb_03_l\",\"middle_metacarpal_l\",\"middle_01_l\",\"middle_02_l\",\"middle_03_l\",\"index_metacarpal_l\",\"index_01_l\",\"index_02_l\",\"index_03_l\",\"clavicle_r\",\"upperarm_r\",\"lowerarm_r\",\"hand_r\",\"pinky_metacarpal_r\",\"pinky_01_r\",\"pinky_02_r\",\"pinky_03_r\",\"ring_metacarpal_r\",\"ring_01_r\",\"ring_02_r\",\"ring_03_r\",\"thumb_01_r\",\"thumb_02_r\",\"thumb_03_r\",\"middle_metacarpal_r\",\"middle_01_r\",\"middle_02_r\",\"middle_03_r\",\"index_metacarpal_r\",\"index_01_r\",\"index_02_r\",\"index_03_r\",\"thigh_r\",\"calf_r\",\"foot_r\",\"ball_r\",\"littletoe_01_r\",\"littletoe_02_r\",\"ringtoe_01_r\",\"ringtoe_02_r\",\"middletoe_01_r\",\"middletoe_02_r\",\"bigtoe_01_r\",\"bigtoe_02_r\",\"indextoe_01_r\",\"indextoe_02_r\",\"calf_twist_01_r\",\"thigh_l\",\"calf_l\",\"foot_l\",\"ball_l\",\"indextoe_01_l\",\"indextoe_02_l\",\"bigtoe_01_l\",\"bigtoe_02_l\",\"littletoe_01_l\",\"littletoe_02_l\",\"middletoe_01_l\",\"middletoe_02_l\",\"ringtoe_01_l\",\"ringtoe_02_l\",\"calf_twist_01_l\",\"FACIAL_C_Neck2Root\",\"FACIAL_L_12IPV_NeckA1\",\"FACIAL_R_12IPV_NeckA1\",\"FACIAL_L_12IPV_NeckA3\",\"FACIAL_R_12IPV_NeckA3\",\"FACIAL_C_FacialRoot\",\"FACIAL_C_Hair3\",\"FACIAL_C_Hair4\",\"FACIAL_C_Hair5\",\"FACIAL_C_Hair6\",\"FACIAL_L_12IPV_Temple1\",\"FACIAL_R_12IPV_Temple1\",\"FACIAL_L_12IPV_Temple2\",\"FACIAL_R_12IPV_Temple2\",\"FACIAL_L_HairC1\",\"FACIAL_R_HairC1\",\"FACIAL_L_Sideburn2\",\"FACIAL_R_Sideburn2\",\"FACIAL_L_Sideburn3\",\"FACIAL_R_Sideburn3\",\"FACIAL_L_Sideburn4\",\"FACIAL_R_Sideburn4\",\"FACIAL_L_Sideburn5\",\"FACIAL_R_Sideburn5\",\"FACIAL_L_Sideburn6\",\"FACIAL_R_Sideburn6\",\"FACIAL_C_Forehead\",\"FACIAL_L_12IPV_Forehead4\",\"FACIAL_R_12IPV_Forehead4\",\"FACIAL_L_12IPV_Forehead5\",\"FACIAL_R_12IPV_Forehead5\",\"FACIAL_L_12IPV_Forehead6\",\"FACIAL_R_12IPV_Forehead6\",\"FACIAL_L_ForeheadIn\",\"FACIAL_L_12IPV_ForeheadIn2\",\"FACIAL_L_12IPV_ForeheadIn3\",\"FACIAL_L_12IPV_ForeheadIn4\",\"FACIAL_L_12IPV_ForeheadIn6\",\"FACIAL_L_12IPV_ForeheadIn7\",\"FACIAL_L_12IPV_ForeheadIn8\",\"FACIAL_L_12IPV_ForeheadIn10\",\"FACIAL_L_12IPV_ForeheadIn11\",\"FACIAL_L_12IPV_ForeheadIn12\",\"FACIAL_L_12IPV_ForeheadIn13\",\"FACIAL_L_12IPV_ForeheadIn14\",\"FACIAL_R_ForeheadIn\",\"FACIAL_R_12IPV_ForeheadIn2\",\"FACIAL_R_12IPV_ForeheadIn3\",\"FACIAL_R_12IPV_ForeheadIn4\",\"FACIAL_R_12IPV_ForeheadIn6\",\"FACIAL_R_12IPV_ForeheadIn7\",\"FACIAL_R_12IPV_ForeheadIn8\",\"FACIAL_R_12IPV_ForeheadIn10\",\"FACIAL_R_12IPV_ForeheadIn12\",\"FACIAL_R_12IPV_ForeheadIn11\",\"FACIAL_R_12IPV_ForeheadIn13\",\"FACIAL_R_12IPV_ForeheadIn14\",\"FACIAL_L_ForeheadMid\",\"FACIAL_L_12IPV_ForeheadMid16\",\"FACIAL_L_12IPV_ForeheadMid17\",\"FACIAL_L_12IPV_ForeheadMid18\",\"FACIAL_L_12IPV_ForeheadMid20\",\"FACIAL_L_12IPV_ForeheadMid21\",\"FACIAL_L_12IPV_ForeheadMid22\",\"FACIAL_R_ForeheadMid\",\"FACIAL_R_12IPV_ForeheadMid16\",\"FACIAL_R_12IPV_ForeheadMid17\",\"FACIAL_R_12IPV_ForeheadMid18\",\"FACIAL_R_12IPV_ForeheadMid20\",\"FACIAL_R_12IPV_ForeheadMid21\",\"FACIAL_R_12IPV_ForeheadMid22\",\"FACIAL_L_ForeheadOut\",\"FACIAL_L_12IPV_ForeheadOut23\",\"FACIAL_L_12IPV_ForeheadOut24\",\"FACIAL_L_12IPV_ForeheadOut25\",\"FACIAL_L_12IPV_ForeheadOut28\",\"FACIAL_L_12IPV_ForeheadOut29\",\"FACIAL_L_12IPV_ForeheadOut31\",\"FACIAL_R_ForeheadOut\",\"FACIAL_R_12IPV_ForeheadOut23\",\"FACIAL_R_12IPV_ForeheadOut24\",\"FACIAL_R_12IPV_ForeheadOut25\",\"FACIAL_R_12IPV_ForeheadOut28\",\"FACIAL_R_12IPV_ForeheadOut29\",\"FACIAL_R_12IPV_ForeheadOut31\",\"FACIAL_L_12IPV_EyesackU0\",\"FACIAL_R_12IPV_EyesackU0\",\"FACIAL_L_EyesackUpper\",\"FACIAL_L_EyesackUpper1\",\"FACIAL_L_EyesackUpper2\",\"FACIAL_L_EyesackUpper3\",\"FACIAL_R_EyesackUpper\",\"FACIAL_R_EyesackUpper1\",\"FACIAL_R_EyesackUpper2\",\"FACIAL_R_EyesackUpper3\",\"FACIAL_L_EyelidUpperFurrow\",\"FACIAL_L_EyelidUpperFurrow2\",\"FACIAL_L_EyelidUpperFurrow3\",\"FACIAL_R_EyelidUpperFurrow\",\"FACIAL_R_EyelidUpperFurrow3\",\"FACIAL_L_EyelidUpperB\",\"FACIAL_L_EyelidUpperB2\",\"FACIAL_L_EyelidUpperB3\",\"FACIAL_R_EyelidUpperB\",\"FACIAL_R_EyelidUpperB3\",\"FACIAL_L_EyelidUpperA\",\"FACIAL_L_EyelidUpperA1\",\"FACIAL_L_EyelidUpperA2\",\"FACIAL_L_EyelidUpperA3\",\"FACIAL_R_EyelidUpperA\",\"FACIAL_R_EyelidUpperA1\",\"FACIAL_R_EyelidUpperA2\",\"FACIAL_R_EyelidUpperA3\",\"FACIAL_L_Eye\",\"FACIAL_L_EyeParallel\",\"FACIAL_L_Pupil\",\"FACIAL_R_Eye\",\"FACIAL_R_EyeParallel\",\"FACIAL_R_Pupil\",\"FACIAL_L_EyelidLowerA\",\"FACIAL_L_EyelidLowerA1\",\"FACIAL_L_EyelidLowerA2\",\"FACIAL_L_EyelidLowerA3\",\"FACIAL_R_EyelidLowerA\",\"FACIAL_R_EyelidLowerA1\",\"FACIAL_R_EyelidLowerA2\",\"FACIAL_R_EyelidLowerA3\",\"FACIAL_L_EyelidLowerB\",\"FACIAL_L_EyelidLowerB3\",\"FACIAL_R_EyelidLowerB\",\"FACIAL_R_EyelidLowerB1\",\"FACIAL_R_EyelidLowerB2\",\"FACIAL_L_EyeCornerInner\",\"FACIAL_L_EyeCornerInner1\",\"FACIAL_L_EyeCornerInner2\",\"FACIAL_R_EyeCornerInner\",\"FACIAL_R_EyeCornerInner1\",\"FACIAL_R_EyeCornerInner2\",\"FACIAL_L_EyeCornerOuter\",\"FACIAL_L_EyeCornerOuter1\",\"FACIAL_L_EyeCornerOuter2\",\"FACIAL_R_EyeCornerOuter\",\"FACIAL_R_EyeCornerOuter1\",\"FACIAL_R_EyeCornerOuter2\",\"FACIAL_L_12IPV_EyeCornerO1\",\"FACIAL_R_12IPV_EyeCornerO1\",\"FACIAL_L_EyesackLower\",\"FACIAL_L_12IPV_EyesackL5\",\"FACIAL_L_12IPV_CheekOuter3\",\"FACIAL_R_12IPV_CheekOuter3\",\"FACIAL_L_12IPV_NoseBridge1\",\"FACIAL_R_12IPV_NoseBridge1\",\"FACIAL_C_12IPV_NoseBridge2\",\"FACIAL_L_12IPV_NoseBridge2\",\"FACIAL_R_12IPV_NoseBridge2\",\"FACIAL_L_NoseBridge\",\"FACIAL_R_NoseBridge\",\"FACIAL_C_12IPV_NoseUpper1\",\"FACIAL_C_12IPV_NoseUpper2\",\"FACIAL_L_12IPV_NoseUpper1\",\"FACIAL_R_12IPV_NoseUpper1\",\"FACIAL_L_12IPV_NoseUpper2\",\"FACIAL_R_12IPV_NoseUpper2\",\"FACIAL_L_12IPV_NoseUpper3\",\"FACIAL_R_12IPV_NoseUpper3\",\"FACIAL_L_12IPV_NoseUpper4\",\"FACIAL_R_12IPV_NoseUpper4\",\"FACIAL_L_NasolabialBulge\",\"FACIAL_L_12IPV_NasolabialB6\",\"FACIAL_L_12IPV_NasolabialB9\",\"FACIAL_L_12IPV_NasolabialB10\",\"FACIAL_R_NasolabialBulge\",\"FACIAL_R_12IPV_NasolabialB6\",\"FACIAL_R_12IPV_NasolabialB9\",\"FACIAL_R_12IPV_NasolabialB10\",\"FACIAL_L_12IPV_NasolabialF3\",\"FACIAL_R_12IPV_NasolabialF3\",\"FACIAL_L_CheekLower\",\"FACIAL_L_12IPV_CheekL2\",\"FACIAL_L_12IPV_CheekL4\",\"FACIAL_R_CheekLower\",\"FACIAL_R_12IPV_CheekL2\",\"FACIAL_R_12IPV_CheekL4\",\"FACIAL_L_Ear\",\"FACIAL_L_Ear1\",\"FACIAL_L_Ear4\",\"FACIAL_R_Ear\",\"FACIAL_R_Ear1\",\"FACIAL_R_Ear4\",\"FACIAL_C_Nose\",\"FACIAL_C_NoseLower\",\"FACIAL_L_NostrilThickness3\",\"FACIAL_R_NostrilThickness3\",\"FACIAL_C_12IPV_NoseL1\",\"FACIAL_C_12IPV_NoseL2\",\"FACIAL_C_NoseTip\",\"FACIAL_C_12IPV_NoseTip1\",\"FACIAL_C_12IPV_NoseTip2\",\"FACIAL_C_12IPV_NoseTip3\",\"FACIAL_R_12IPV_NoseTip1\",\"FACIAL_R_12IPV_NoseTip2\",\"FACIAL_R_12IPV_NoseTip3\",\"FACIAL_L_Nostril\",\"FACIAL_L_12IPV_Nostril8\",\"FACIAL_L_12IPV_Nostril10\",\"FACIAL_L_12IPV_Nostril11\",\"FACIAL_L_12IPV_Nostril12\",\"FACIAL_L_12IPV_Nostril14\",\"FACIAL_R_Nostril\",\"FACIAL_R_12IPV_Nostril4\",\"FACIAL_R_12IPV_Nostril6\",\"FACIAL_R_12IPV_Nostril8\",\"FACIAL_R_12IPV_Nostril10\",\"FACIAL_R_12IPV_Nostril11\",\"FACIAL_R_12IPV_Nostril12\",\"FACIAL_R_12IPV_Nostril14\",\"FACIAL_C_12IPV_LipUpperSkin1\",\"FACIAL_C_12IPV_LipUpperSkin2\",\"FACIAL_L_12IPV_LipUpperSkin\",\"FACIAL_R_12IPV_LipUpperSkin\",\"FACIAL_C_MouthUpper\",\"FACIAL_C_LipUpper\",\"FACIAL_L_12IPV_LipUpper1\",\"FACIAL_R_12IPV_LipUpper1\",\"FACIAL_L_12IPV_LipUpper2\",\"FACIAL_R_12IPV_LipUpper2\",\"FACIAL_L_12IPV_LipUpper3\",\"FACIAL_R_12IPV_LipUpper3\",\"FACIAL_L_12IPV_LipUpper4\",\"FACIAL_R_12IPV_LipUpper4\",\"FACIAL_L_LipUpper\",\"FACIAL_L_12IPV_LipUpper6\",\"FACIAL_L_12IPV_LipUpper7\",\"FACIAL_L_12IPV_LipUpper8\",\"FACIAL_L_12IPV_LipUpper9\",\"FACIAL_L_12IPV_LipUpper10\",\"FACIAL_L_12IPV_LipUpper11\",\"FACIAL_L_12IPV_LipUpper12\",\"FACIAL_L_12IPV_LipUpper14\",\"FACIAL_R_LipUpper\",\"FACIAL_R_12IPV_LipUpper6\",\"FACIAL_R_12IPV_LipUpper7\",\"FACIAL_R_12IPV_LipUpper8\",\"FACIAL_R_12IPV_LipUpper9\",\"FACIAL_R_12IPV_LipUpper10\",\"FACIAL_R_12IPV_LipUpper11\",\"FACIAL_R_12IPV_LipUpper12\",\"FACIAL_R_12IPV_LipUpper14\",\"FACIAL_L_LipUpperOuter\",\"FACIAL_L_12IPV_LipUpper16\",\"FACIAL_L_12IPV_LipUpper17\",\"FACIAL_L_12IPV_LipUpper18\",\"FACIAL_L_12IPV_LipUpper19\",\"FACIAL_L_12IPV_LipUpper20\",\"FACIAL_R_LipUpperOuter\",\"FACIAL_R_12IPV_LipUpper16\",\"FACIAL_R_12IPV_LipUpper17\",\"FACIAL_R_12IPV_LipUpper18\",\"FACIAL_R_12IPV_LipUpper19\",\"FACIAL_R_12IPV_LipUpper20\",\"FACIAL_L_LipCorner\",\"FACIAL_L_LipCorner1\",\"FACIAL_L_LipCorner2\",\"FACIAL_L_LipCorner3\",\"FACIAL_L_12IPV_LipCorner1\",\"FACIAL_L_12IPV_LipCorner2\",\"FACIAL_L_12IPV_LipCorner3\",\"FACIAL_R_LipCorner\",\"FACIAL_R_LipCorner1\",\"FACIAL_R_LipCorner2\",\"FACIAL_R_LipCorner3\",\"FACIAL_R_12IPV_LipCorner1\",\"FACIAL_R_12IPV_LipCorner2\",\"FACIAL_R_12IPV_LipCorner3\",\"FACIAL_L_JawBulge\",\"FACIAL_R_JawBulge\",\"FACIAL_L_JawRecess\",\"FACIAL_R_JawRecess\",\"FACIAL_L_Masseter\",\"FACIAL_R_Masseter\",\"FACIAL_L_12IPV_UnderChin3\",\"FACIAL_R_12IPV_UnderChin3\",\"FACIAL_L_12IPV_UnderChin5\",\"FACIAL_R_12IPV_UnderChin5\",\"FACIAL_L_12IPV_UnderChin6\",\"FACIAL_R_12IPV_UnderChin6\",\"FACIAL_C_LowerLipRotation\",\"FACIAL_C_12IPV_LipLowerSkin1\",\"FACIAL_L_12IPV_LipLowerSkin\",\"FACIAL_R_12IPV_LipLowerSkin\",\"FACIAL_L_12IPV_LipLowerOuterSkin1\",\"FACIAL_R_12IPV_LipLowerOuterSkin1\",\"FACIAL_C_MouthLower\",\"FACIAL_C_LipLower\",\"FACIAL_L_12IPV_LipLower1\",\"FACIAL_R_12IPV_LipLower1\",\"FACIAL_L_12IPV_LipLower2\",\"FACIAL_R_12IPV_LipLower2\",\"FACIAL_L_12IPV_LipLower3\",\"FACIAL_R_12IPV_LipLower3\",\"FACIAL_L_12IPV_LipLower4\",\"FACIAL_R_12IPV_LipLower4\",\"FACIAL_L_LipLower\",\"FACIAL_L_12IPV_LipLower6\",\"FACIAL_L_12IPV_LipLower7\",\"FACIAL_L_12IPV_LipLower8\",\"FACIAL_L_12IPV_LipLower9\",\"FACIAL_L_12IPV_LipLower10\",\"FACIAL_L_12IPV_LipLower11\",\"FACIAL_L_12IPV_LipLower12\",\"FACIAL_R_LipLower\",\"FACIAL_R_12IPV_LipLower6\",\"FACIAL_R_12IPV_LipLower7\",\"FACIAL_R_12IPV_LipLower8\",\"FACIAL_R_12IPV_LipLower9\",\"FACIAL_R_12IPV_LipLower10\",\"FACIAL_R_12IPV_LipLower11\",\"FACIAL_R_12IPV_LipLower12\",\"FACIAL_L_LipLowerOuter\",\"FACIAL_L_12IPV_LipLower16\",\"FACIAL_L_12IPV_LipLower17\",\"FACIAL_L_12IPV_LipLower18\",\"FACIAL_L_12IPV_LipLower19\",\"FACIAL_L_12IPV_LipLower20\",\"FACIAL_R_LipLowerOuter\",\"FACIAL_R_12IPV_LipLower16\",\"FACIAL_R_12IPV_LipLower17\",\"FACIAL_R_12IPV_LipLower18\",\"FACIAL_R_12IPV_LipLower19\",\"FACIAL_R_12IPV_LipLower20\",\"FACIAL_C_Jaw\",\"FACIAL_L_12IPV_Jawline1\",\"FACIAL_R_12IPV_Jawline1\",\"FACIAL_L_12IPV_Jawline2\",\"FACIAL_R_12IPV_Jawline2\",\"FACIAL_L_Jawline\",\"FACIAL_L_12IPV_Jawline3\",\"FACIAL_L_12IPV_Jawline4\",\"FACIAL_L_12IPV_Jawline5\",\"FACIAL_L_12IPV_Jawline6\",\"FACIAL_R_Jawline\",\"FACIAL_R_12IPV_Jawline3\",\"FACIAL_R_12IPV_Jawline4\",\"FACIAL_R_12IPV_Jawline5\",\"FACIAL_R_12IPV_Jawline6\",\"FACIAL_L_12IPV_ChinS4\",\"FACIAL_R_12IPV_ChinS4\",\"FACIAL_L_12IPV_Chin2\",\"FACIAL_R_12IPV_Chin2\",\"FACIAL_C_12IPV_Chin3\",\"FACIAL_C_12IPV_Chin4\",\"FACIAL_L_12IPV_Chin8\",\"FACIAL_L_12IPV_Chin13\",\"FACIAL_L_12IPV_Chin14\",\"FACIAL_R_12IPV_Chin14\"];\n\nexport const PARENTS_441: number[] = [-1,0,1,2,3,4,5,6,7,8,6,10,11,12,13,14,15,16,13,18,19,20,13,22,23,13,25,26,27,13,29,30,31,6,33,34,35,36,37,38,39,36,41,42,43,36,45,46,36,48,49,50,36,52,53,54,1,56,57,58,59,60,59,62,59,64,59,66,59,68,57,1,71,72,73,74,75,74,77,74,79,74,81,74,83,72,8,86,86,86,86,9,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,112,112,112,112,112,112,91,119,119,119,119,119,119,119,119,119,119,119,91,131,131,131,131,131,131,131,131,131,131,131,91,143,143,143,143,143,143,91,150,150,150,150,150,150,91,157,157,157,157,157,157,91,164,164,164,164,164,164,91,91,91,173,173,173,91,177,177,177,91,181,181,91,184,91,186,186,91,189,91,191,191,191,91,195,195,195,91,199,200,91,202,203,91,205,205,205,91,209,209,209,91,213,91,215,215,91,218,218,91,221,221,91,224,224,91,227,227,91,91,91,232,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,91,253,253,253,91,257,257,257,91,91,91,263,263,91,266,266,91,269,269,91,272,272,91,275,276,276,276,276,275,281,281,281,281,281,281,275,288,288,288,288,288,275,294,294,294,294,294,294,294,91,91,91,91,91,306,307,307,307,307,307,307,307,307,306,316,316,316,316,316,316,316,316,306,325,325,325,325,325,325,325,325,306,334,334,334,334,334,306,340,340,340,340,340,306,346,346,346,346,346,346,306,353,353,353,353,353,353,91,91,91,91,91,91,91,91,91,91,91,91,91,372,372,372,372,372,372,378,379,379,379,379,379,379,379,379,378,388,388,388,388,388,388,388,378,396,396,396,396,396,396,396,378,404,404,404,404,404,378,410,410,410,410,410,91,416,416,416,416,416,421,421,421,421,416,426,426,426,426,416,416,416,416,416,416,416,416,416,416];\n\nexport const REST_TRANSLATIONS_441: number[] = [0,-0,-0,0.023344,0.900783,-0,-0.001521,-0,-0.035612,-0,0,-0.063712,-0,0,-0.071221,-0,1e-06,-0.090417,-0,1e-06,-0.128666,0.005727,1e-06,-0.159028,0,1e-06,-0.052265,-3.6e-05,1e-06,-0.054106,-0.00933,-0.011471,-0.101591,1e-06,-0.001226,-0.165581,0,0,-0.271682,0,-0,-0.259356,-0.004406,0.018566,-0.027672,0,-0,-0.04638,0,0,-0.029209,0,0,-0.018704,-0.002529,0.006926,-0.0287,-0,-0,-0.049387,-0,-0,-0.040755,-0,-0,-0.031308,-0.013588,-0.022955,-0.016628,0,-0,-0.04589,0,0,-0.028047,-0.001355,-0.003889,-0.02898,0,-0,-0.054799,-0,-0,-0.046589,-0,-0,-0.029402,-0.002123,-0.020517,-0.031495,-0,-0,-0.051824,0,-0,-0.042275,0,0,-0.022987,-0.00933,0.011473,-0.101591,1e-06,0.001221,0.165582,0,0,0.271682,0,-0,0.259356,0.004406,-0.018566,0.027672,0,-0,0.04638,-0,0,0.029209,-0,0,0.018704,0.002529,-0.006926,0.0287,-0,-0,0.049387,0,-0,0.040755,-0,0,0.031308,0.013588,0.022955,0.016628,-0,-0,0.04589,0,0,0.028047,0.001355,0.003889,0.02898,0,-0,0.054799,0,0,0.046589,-0,0,0.029402,0.002123,0.020517,0.031495,-0,0,0.051824,-0,-0,0.042275,-0,-0,0.022988,0.001891,0.094935,0.010807,1e-06,-0,-0.418322,-0,-0,-0.392278,-0.139017,0.002936,-0.065634,0.005855,0.047366,-0.011031,0.001673,0.000697,0.015431,0.011036,0.032097,-0.001184,0.000361,0.003912,0.020927,0.013339,0.016396,0.005849,-0.001023,0.003598,0.02426,0.011818,-0.028687,0.009881,-0.001502,0.000777,0.031313,0.015065,-0.00248,0.007485,-0.001603,0.002936,0.03033,-2e-06,-1e-06,-0.261888,0.001891,-0.094935,0.010807,-1e-06,-0,0.418322,0,0,0.392278,0.139017,-0.002936,0.065634,-0.015065,0.00248,-0.007485,0.001603,-0.002936,-0.03033,-0.011818,0.028687,-0.009881,0.001502,-0.000776,-0.031313,-0.005855,-0.047366,0.011031,-0.001673,-0.000697,-0.015431,-0.013339,-0.016396,-0.005849,0.001023,-0.003598,-0.02426,-0.011036,-0.032097,0.001184,-0.000361,-0.003912,-0.020927,2e-06,1e-06,0.261888,0.026874,4e-06,-0.002962,0.006313,0.03091,-0.025065,0.006275,0.030867,0.025048,-0.011196,0.011833,-0.048657,-0.011328,0.011698,0.048782,-0.009899,5e-06,-0.040012,-0.11661,0.077932,-5.9e-05,-0.128862,0.048206,-1.3e-05,-0.133137,0.008422,2.1e-05,-0.121244,-0.034068,4.6e-05,-0.044079,0.083333,-0.061966,-0.044096,0.083246,0.061837,-0.036218,0.074804,-0.066002,-0.036234,0.074759,0.065998,-0.051973,0.051465,-0.073208,-0.051888,0.051468,0.073015,-0.027945,0.046024,-0.073847,-0.027937,0.046006,0.073747,-0.027355,0.025024,-0.076776,-0.027373,0.025055,0.076999,-0.004736,0.066318,-0.071697,-0.00474,0.066323,0.071715,-0.005354,0.049423,-0.074053,-0.005383,0.049457,0.073901,-0.005335,0.032464,-0.073732,-0.005363,0.032514,0.073961,-0.043356,0.110559,0.000237,0.004231,0.010024,-0.006377,0.004226,0.010127,0.005855,0.00675,0.009423,-0.006186,0.00674,0.009518,0.005672,0.013076,0.007203,-0.005153,0.013151,0.007556,0.004735,-0.044192,0.108085,-0.017441,-0.003452,0.011842,0.010352,-0.000266,0.01179,0.010523,0.008139,0.009798,0.010885,-0.003851,0.012237,0.003465,-0.000716,0.012148,0.003706,0.008262,0.010239,0.003889,-0.004805,0.011573,-0.005662,-0.001797,0.011831,-0.005203,0.006271,0.010252,-0.004264,0.014911,0.004617,0.00637,0.009354,0.007038,-0.003791,-0.04397,0.108374,0.016549,-0.003713,0.011772,-0.009511,-0.000514,0.011736,-0.009667,0.007859,0.009628,-0.010002,-0.004119,0.012189,-0.002592,-0.000955,0.012082,-0.002827,0.007851,0.009851,-0.003011,-0.005058,0.011504,0.006596,0.005891,0.010106,0.005131,-0.002037,0.011622,0.006109,0.014837,0.004686,-0.005407,0.009275,0.007089,0.004746,-0.048965,0.10091,-0.032655,0.000251,0.012773,0.004337,0.00309,0.013531,0.004935,0.010382,0.012194,0.005993,9.6e-05,0.010819,-0.005956,0.002537,0.011894,-0.005308,0.009384,0.012217,-0.003328,-0.048747,0.100187,0.031474,0.000171,0.013687,-0.003488,0.002985,0.014316,-0.004104,0.010257,0.013387,-0.005181,0.000104,0.011533,0.006665,0.00246,0.012713,0.006078,0.009311,0.01343,0.00419,-0.044651,0.092698,-0.046338,-0.005197,0.009368,0.00158,0.002266,0.01155,0.003174,0.004541,0.012468,0.003594,0.004306,0.006555,-0.00914,0.007815,0.009752,-0.004401,0.010869,0.002709,-0.015058,-0.04404,0.092692,0.045906,-0.005769,0.009416,-0.001444,0.001665,0.011667,-0.003034,0.003866,0.012614,-0.003427,0.003689,0.006894,0.009322,0.007206,0.010271,0.004653,0.010248,0.002999,0.015227,-0.027106,0.110394,-0.016668,-0.027101,0.110471,0.016676,-0.034431,0.110252,-0.034322,0.003868,0.000686,0.010512,0.000958,0.001653,-6.2e-05,0.002419,-0.001088,-0.012043,-0.034395,0.110258,0.03446,0.003862,0.000688,-0.010731,0.000904,0.001637,-8.8e-05,0.002359,-0.001079,0.011928,-0.031782,0.108184,-0.033039,0.000439,0.000866,0.000219,0.001221,-0.000103,-0.011184,-0.031718,0.108238,0.033032,0.001105,-8.6e-05,0.011223,-0.022654,0.095825,-0.031836,0.0004,0.016401,-0.001299,0.000704,0.012668,-0.010221,-0.022663,0.095706,0.031881,0.000747,0.012799,0.010162,-0.022663,0.095822,-0.03184,0.001837,0.01395,0.006634,0.000557,0.01641,-0.001307,0.001427,0.012514,-0.0097,-0.022665,0.095704,0.031888,0.001905,0.013957,-0.006721,0.000589,0.016487,0.001178,0.001377,0.012651,0.009637,-0.022666,0.095837,-0.031841,2e-06,7e-06,-3e-06,0.000437,0.012141,-0.000701,-0.022654,0.095745,0.031905,-0,0,-0,0.000388,0.012188,0.000712,-0.022656,0.095826,-0.031846,-0.001933,0.013811,0.006137,-0.001165,0.015033,-0.001647,-0.000441,0.011692,-0.009329,-0.022665,0.095704,0.031888,-0.001924,0.013866,-0.006169,-0.001165,0.015101,0.001601,-0.000481,0.011823,0.009337,-0.022666,0.095821,-0.031839,0.002146,0.013233,-0.010271,-0.022671,0.095709,0.031884,-0.000661,0.015993,-0.005946,0.00059,0.016511,0.002057,-0.018861,0.106402,-0.018159,-0.002238,0.000348,-0.001337,0.001457,0.000548,-0.00246,-0.018642,0.10623,0.018044,-0.002387,0.000508,0.001454,0.001282,0.000665,0.002586,-0.020522,0.100477,-0.045451,-0.001583,0.00183,0.001373,0.001202,0.000479,0.000282,-0.020661,0.099826,0.045568,-0.001567,0.002217,-0.001886,0.001299,0.000947,-0.000752,-0.020172,0.098095,-0.048848,-0.020234,0.098049,0.048835,-0.008836,0.1028,-0.035528,-0.001019,0.00386,-0.002949,-0.02807,0.08347,-0.062583,-0.028069,0.083439,0.062601,-0.032975,0.119318,-0.005309,-0.032931,0.119656,0.005339,-0.024691,0.120183,-4.9e-05,-0.024071,0.119121,-0.004049,-0.024084,0.119358,0.004075,-0.020829,0.109562,-0.012152,-0.020936,0.109426,0.012017,-0.019389,0.122187,-4.9e-05,-0.007826,0.129767,-8.2e-05,-0.018297,0.120549,-0.00516,-0.018311,0.120608,0.00511,-0.007032,0.128249,-0.005421,-0.007051,0.128274,0.005305,-0.015172,0.116382,-0.009218,-0.015198,0.116425,0.009224,-0.004615,0.12374,-0.009834,-0.004617,0.123792,0.009808,0.049129,0.096631,-0.03713,-0.001243,0.0073,0.014302,0.003829,0.005895,0.013934,0.018528,0.00491,0.00115,0.050119,0.097303,0.036212,-0.002115,0.007359,-0.01315,0.002932,0.005914,-0.012756,0.017608,0.004995,-8e-06,0.026135,0.114987,-0.02213,0.026266,0.115159,0.021986,0.043391,0.082007,-0.048853,0.015543,0.005661,0.006178,0.013463,0.003991,-0.009665,0.04574,0.083647,0.047902,0.013434,0.005413,-0.004009,0.011294,0.003505,0.011859,0.004762,0.009472,-0.071052,0,-0,-0,0.021144,0.011921,-0.007121,0.004829,0.009528,0.071128,0,-0,-0,0.021066,0.011921,0.007004,-0.005446,0.120997,-1.9e-05,0.031558,-0.002201,0.000108,-0.003152,-0.000407,-0.005733,-0.003213,-0.00045,0.005652,-0.001177,0.006603,-2.3e-05,0.004874,-0.000493,-6.1e-05,0.022215,0.007442,0.000502,-0.010205,0.004842,-0.000501,-0.002376,0.008496,-0.000482,0.005429,0.007026,-0.000443,-0.010055,0.000288,0.007985,-0.002922,0.002642,0.009997,0.00312,0.001051,0.010678,0.022921,-0.002186,-0.014186,-0.000107,-0.010578,-0.002407,0.003769,0.000219,-0.003097,0.005797,-0.008801,7.7e-05,0.008395,-0.002484,0.004991,0.013831,-0.005613,0.001558,0.022617,-0.001818,0.013771,-0.009532,0.007031,-0.000416,-0.002937,0.009141,0.001418,0.000283,-0.010902,0.002779,0.003949,-0.000336,0.003508,0.006058,-0.009189,0.000396,0.008584,-0.003016,-0.004644,0.014072,-0.006087,-0.001283,0.032767,0.126467,3.6e-05,0.03778,0.127802,1.7e-05,0.034508,0.123885,-0.013513,0.034433,0.123875,0.013516,0.048252,0.093357,9.4e-05,-0.005301,0.030169,-9.4e-05,-0.006138,0.005803,-0.004074,-0.006183,0.005836,0.004095,0.002511,0.005655,-0.004223,0.002502,0.005664,0.004211,0.006877,8.4e-05,-0.003463,0.00685,7.1e-05,0.003445,0.003084,-0.005263,-0.002925,0.003081,-0.005258,0.002973,-0.004195,0.026608,-0.012188,-0.006598,0.006588,0.005386,0.001817,0.006497,0.004839,-0.005083,0.005141,-0.004678,0.003424,0.004013,-0.003428,0.00621,0.00123,0.0045,0.00592,-0.000336,-0.002252,0.002751,-0.003917,0.004196,0.00228,-0.004713,-0.001789,-0.004668,0.027018,0.011648,-0.006267,0.006279,-0.004874,0.002183,0.006117,-0.004352,-0.004711,0.004705,0.005106,0.003772,0.003623,0.003893,0.006519,0.000851,-0.00401,0.00623,-0.000693,0.002734,0.003119,-0.004207,-0.003643,0.002614,-0.005007,0.00231,-0.002163,0.021478,-0.019756,-0.003344,0.00596,-0.002601,0.003905,0.003813,0.001287,0.003988,0.000731,-0.003433,0.005359,-0.000105,0.002383,0.004522,-0.00226,-0.001601,-0.002783,0.021683,0.019446,-0.002681,0.005692,0.002794,0.004446,0.003559,-0.000962,0.004601,0.000476,0.003796,0.005858,-0.000341,-0.002057,0.00509,-0.002497,0.001951,0.002965,0.014554,-0.025806,-4.7e-05,0.005676,-0.003435,-0.003501,-0.007577,-0.000567,0.004246,-0.007402,0.001802,0.000253,0.002557,0.002701,-0.001198,0.006051,0.000126,0.003126,0.004012,4e-06,0.003103,0.014129,0.02575,-0.000138,0.005992,0.003102,-0.003694,-0.007314,0.000207,0.004052,-0.007102,-0.002161,0.000274,0.002886,-0.002942,-0.001253,0.006279,-0.000463,0.003095,0.004334,-0.000224,0.037145,0.045724,-0.068915,0.037196,0.045755,0.068858,0.00945,0.036355,-0.073302,0.009485,0.036511,0.073432,0.015698,0.057461,-0.07068,0.015661,0.057466,0.070567,0.093906,0.076728,-0.024185,0.094238,0.076679,0.024255,0.077759,0.067926,-0.048138,0.077681,0.06788,0.048149,0.081184,0.047982,-0.04592,0.081197,0.047893,0.046068,0.022711,0.035839,0.000937,-0.022568,0.092507,-0.000899,-0.018216,0.091304,-0.015145,-0.018222,0.091469,0.013357,-0.021996,0.086003,-0.022726,-0.021872,0.086086,0.020952,-0.016141,0.061257,-0.00092,0.007685,0.027902,-0.000215,0.00724,0.001064,-0.004565,0.007285,0.001074,0.005022,-0.001345,0.0064,-0.004536,-0.001377,0.00644,0.005003,-0.007508,0.001178,-0.00344,-0.007551,0.001175,0.003879,-0.004332,-0.005021,-0.002724,-0.004355,-0.005042,0.003195,0.006884,0.025082,-0.009973,0.007759,0.003419,4e-05,-0.001495,0.007266,0.001074,0.007003,0.003011,-0.006975,-0.001828,0.004741,-0.005203,-0.007355,0.00228,0.001951,-0.006548,0.000798,-0.003499,-0.003938,-0.003661,0.002166,0.006949,0.025205,0.01041,0.007776,0.003108,-0.000422,-0.001621,0.007127,-0.001481,0.007071,0.002688,0.006611,-0.001908,0.004557,0.00473,-0.007454,0.002042,-0.002372,-0.006633,0.000548,0.003046,-0.004044,-0.003945,-0.002523,0.005915,0.021084,-0.017959,0.004628,0.003873,-0.003218,-0.002172,0.004193,0.000784,-0.002806,0.00152,-0.004243,-0.005573,0.001325,0.001984,-0.004517,-0.000888,-0.002442,0.006402,0.020331,0.018205,0.00412,0.004362,0.002758,-0.002794,0.00468,-0.001365,-0.003378,0.00198,0.003679,-0.00619,0.001779,-0.00256,-0.005099,-0.000441,0.001884,0.022711,0.035839,0.000937,0.009503,0.099572,-0.015498,0.009578,0.0997,0.013607,0.023235,0.08711,-0.0176,0.023355,0.087235,0.015672,0.008208,0.050305,-0.053218,-0.001654,0.007963,-0.005192,0.011921,0.012655,-8.2e-05,-0.00597,-0.020915,-0.007104,0.012227,-0.018867,-0.001766,0.00867,0.050943,0.049277,-0.002363,0.006762,0.006923,0.011216,0.011498,0.001889,-0.006728,-0.022019,0.008591,0.011292,-0.020094,0.003079,0.005563,0.091083,-0.029372,0.005616,0.091094,0.027552,-0.008111,0.102913,-0.007436,-0.008178,0.103057,0.005551,-0.002789,0.104789,-0.000974,0.00472,0.104023,-0.000986,-0.004408,0.103616,-0.010336,-0.002448,0.103151,-0.013064,0.00528,0.101868,-0.014763,0.005266,0.101768,0.012807];\n\nexport const REST_ROTATIONS_441: number[] = [0,-0,-0,-1,-0.706993,0.012667,0.012667,-0.706993,2e-06,0.095412,0,-0.995438,0,-0.063843,0,-0.99796,3e-06,-0.082862,-0,-0.996561,0,-0.074395,0,-0.997229,-0,0.013375,0,-0.999911,-0,0.200689,-0,-0.979655,-0,-0.007894,-0,-0.999969,0,-0.099543,-0,-0.995033,0.747542,0.053759,0.078301,-0.657388,0.384642,0.011175,-0.026035,-0.922631,0,0.314382,-0,-0.949297,0,-0,-0.707107,-0.707107,-0.181012,-0.087497,-0.067279,-0.977268,-0,-0.104528,0,-0.994522,0,-0.173648,-0,-0.984808,-0,-0.034899,0,-0.999391,-0.104513,0.001824,-0.017357,-0.99437,0,-0.156434,-0,-0.987688,-0,-0.21644,-0,-0.976296,-0,-0.043619,-0,-0.999048,0.337145,0.044699,0.560672,-0.754972,0,-0.173648,-0,-0.984808,0,-0.087156,0,-0.996195,-0.009023,0.043556,0.006594,-0.998989,-0,-0.207912,0,-0.978148,-0,-0.173648,0,-0.984808,-0,-0.034899,-0,-0.999391,0.052208,0.003651,0.069661,-0.996197,0,-0.173648,0,-0.984808,0,-0.104528,-0,-0.994522,-0,-0.034899,-0,-0.999391,0.078299,-0.657369,-0.747559,-0.053762,0.384628,0.01117,-0.026038,-0.922637,-0,0.314382,0,-0.949297,-0,0,-0.707107,-0.707107,-0.181012,-0.087497,-0.067279,-0.977268,0,-0.104528,0,-0.994522,-0,-0.173648,0,-0.984808,0,-0.034899,0,-0.999391,-0.104513,0.001824,-0.017357,-0.99437,0,-0.156434,-0,-0.987688,-0,-0.21644,-0,-0.976296,0,-0.043619,-0,-0.999048,0.337145,0.044699,0.560672,-0.754972,-0,-0.173648,0,-0.984808,0,-0.087156,-0,-0.996195,-0.009023,0.043556,0.006594,-0.998989,0,-0.207912,-0,-0.978148,0,-0.173648,-0,-0.984808,0,-0.034899,0,-0.999391,0.052209,0.003651,0.069661,-0.996197,0,-0.173648,0,-0.984808,-0,-0.104528,0,-0.994522,0,-0.034899,-0,-0.999391,-0.074046,0.996952,-0.022745,-0.009288,0,0.009016,0,-0.999959,0.024633,0,0,-0.999697,0,0.707107,-0,-0.707107,0.006788,0.11322,-0.03924,-0.992772,0,0.087156,0,-0.996195,0.006788,0.11322,-0.03924,-0.992772,0,0.087156,0,-0.996195,0.006788,0.11322,-0.03924,-0.992772,0,0.087156,0,-0.996195,0.037269,0.028423,-0.002239,-0.998898,0,-0,-0,-1,0.031927,0.074128,-0.004331,-0.996728,-0,0.104528,-0,-0.994522,0,-0,-0,-1,-0.022745,-0.009288,0.074046,-0.996952,0,0.009016,0,-0.999959,0.024633,0,0,-0.999697,0,0.707107,-0,-0.707107,0.031927,0.074128,-0.004331,-0.996728,-0,0.104528,-0,-0.994522,0.037269,0.028423,-0.002239,-0.998898,-0,-0,0,-1,0.006788,0.11322,-0.03924,-0.992772,0,0.087156,0,-0.996195,0.006788,0.11322,-0.03924,-0.992772,0,0.087156,0,-0.996195,0.006788,0.11322,-0.03924,-0.992772,0,0.087156,0,-0.996195,0,-0,0,-1,0.547286,0.447743,0.447747,-0.547291,0.242088,-0.09698,0.128375,-0.956822,-0.242088,0.09698,0.128375,-0.956822,0.40361,-0.117599,0.128959,-0.898131,-0.40361,0.117599,0.128959,-0.898131,0.499997,0.499998,0.500002,-0.500003,0,-0,0.382683,-0.92388,0,-0,0.258819,-0.965926,0,-0,0.087156,-0.996195,-0,-0,-0.087156,-0.996195,-0.086551,-0.072775,0.303122,-0.946219,0.086551,0.072775,0.303122,-0.946219,-0.094233,-0.062509,0.194059,-0.974451,0.094233,0.062509,0.194059,-0.974451,-0.094233,-0.062509,0.194059,-0.974451,0.094233,0.062509,0.194059,-0.974451,-0.079983,0.007709,0.120116,-0.989503,0.079983,-0.007709,0.120116,-0.989503,-0.034866,-0.001522,0.043593,-0.99844,0.034866,0.001522,0.043593,-0.99844,-0.087126,-0.002281,0.026077,-0.995853,0.087126,0.002281,0.026077,-0.995853,0,-0,0.026177,-0.999657,0,-0,0.026177,-0.999657,0,-0,0.043619,-0.999048,0,-0,0.043619,-0.999048,-0,-0,-0.043619,-0.999048,-0,-0,0.043619,-0.999048,-0,-0,0.043619,-0.999048,0,-0,0.087156,-0.996195,0,-0,0.087156,-0.996195,0,-0,0.087156,-0.996195,0,-0,0.087156,-0.996195,0.069626,-0.004259,-0.0609,-0.995703,-0,-0,0.026177,-0.999657,-0.036644,0.01338,0.112512,-0.992884,-0.036644,0.01338,0.112512,-0.992884,-0,-0,0.026177,-0.999657,-0.036644,0.01338,0.112512,-0.992884,-0.036644,0.01338,0.112512,-0.992884,0.121753,0.005316,0.043294,-0.991601,0,-0,0.052336,-0.99863,0,0,0.207912,-0.978148,-0.081275,-0.266854,0.266854,-0.922482,-0.033411,-0.073002,0.277817,-0.957273,-0.069626,0.004259,-0.0609,-0.995703,0,0,0.026177,-0.999657,0.036644,-0.01338,0.112512,-0.992884,0.036644,-0.01338,0.112512,-0.992884,0,0,0.026177,-0.999657,0.036644,-0.01338,0.112512,-0.992884,0.036644,-0.01338,0.112512,-0.992884,-0.121753,-0.005316,0.043294,-0.991601,0,-0,0.207912,-0.978148,-0,-0,0.052336,-0.99863,0.081275,0.266854,0.266854,-0.922482,0.033411,0.073002,0.277818,-0.957273,0.175704,0.020647,-0.071179,-0.981649,0.061368,0.043004,-0.006039,-0.99717,0.061368,0.043004,-0.006039,-0.99717,0.050121,0.055707,0.21843,-0.972971,0.061368,0.043004,-0.006039,-0.99717,0.061368,0.043004,-0.006039,-0.99717,0.050121,0.055707,0.21843,-0.972971,-0.175704,-0.020647,-0.071179,-0.981649,-0.061368,-0.043004,-0.006039,-0.99717,-0.061368,-0.043004,-0.006039,-0.99717,-0.050121,-0.055707,0.21843,-0.972971,-0.061368,-0.043004,-0.006039,-0.99717,-0.061368,-0.043004,-0.006039,-0.99717,-0.050121,-0.055707,0.21843,-0.972971,0.255661,0.079231,-0.121536,-0.955818,0.04564,0.03214,-0.059434,-0.99667,0.04564,0.03214,-0.059434,-0.99667,0.102602,0.0264,0.088483,-0.990428,0.091963,0.081362,-0.053003,-0.991017,0.09618,0.095424,0.095424,-0.986173,0.09618,0.095424,0.095424,-0.986173,-0.255661,-0.079231,-0.121536,-0.955819,-0.04564,-0.03214,-0.059434,-0.99667,-0.04564,-0.03214,-0.059434,-0.99667,-0.102602,-0.0264,0.088482,-0.990428,-0.091963,-0.081362,-0.053003,-0.991017,-0.09618,-0.095424,0.095424,-0.986173,-0.09618,-0.095424,0.095424,-0.986173,-0.008996,-0.14974,0.115766,-0.981884,0.008996,0.14974,0.115766,-0.981884,0.084258,0.064553,0.048688,-0.993158,-0.078936,-0.103521,-0.000451,-0.99149,-0,-0,0,-1,0.086993,0.060816,0.005321,-0.994337,-0.084258,-0.064553,0.048688,-0.993158,0.078936,0.103521,-0.000451,-0.99149,-0,0,-0,-1,-0.086993,-0.060816,0.005321,-0.994337,0.150867,0.079694,-0.030106,-0.984877,-0.087488,-0.00412,-0.051375,-0.994831,0.071004,0.022428,-0.050367,-0.995951,-0.150867,-0.079694,-0.030106,-0.984877,-0.071004,-0.022428,-0.050367,-0.995951,-0,-0,-0.224951,-0.97437,-0,-0,-0,-1,0.165697,0.048734,-0.008553,-0.984935,-0,-0,-0.224951,-0.97437,-0.165697,-0.048734,-0.008553,-0.984935,-0,-0,-0.147809,-0.989016,-0.121406,-0.086506,0.010622,-0.988769,0,-0,-0,-1,0.165697,0.048734,-0.008553,-0.984935,-0,-0,-0.147809,-0.989016,0.121406,0.086506,0.010622,-0.988769,0,-0,-0,-1,-0.165697,-0.048734,-0.008553,-0.984935,0,-0,-0,-1,0,-0,-0,-1,-0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,-0,-0,-0,-1,0,-0,0.284015,-0.95882,-0.078459,-0,0,-0.996917,0,-0,0,-1,0.182236,0,0,-0.983255,0,-0,0.284015,-0.95882,0.078459,-0,-0,-0.996917,0,-0,0,-1,-0.182236,0,-0,-0.983255,0,-0,0.317305,-0.948324,0.182236,0,0,-0.983255,0,-0,0.317305,-0.948324,0.078459,0,0,-0.996917,-0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0.382683,-0,-0,-0.92388,0,-0,-0,-1,0,-0,-0,-1,-0.382683,-0,-0,-0.92388,0,-0,-0,-1,0,-0,-0,-1,0.252684,0.209065,0.056019,-0.94303,-0.252684,-0.209065,0.056019,-0.94303,0.139756,0.022271,-0.022271,-0.989685,0.088482,-0.102602,0.008182,-0.990746,-0.215028,-0.035072,0.263565,-0.939716,0.215028,0.035072,0.263565,-0.939716,0,-0,0.043619,-0.999048,0,-0,0.043619,-0.999048,0,-0,0.043619,-0.999048,0,-0,0.043619,-0.999048,0,-0,0.043619,-0.999048,0.293995,0.122907,0.007616,-0.947841,-0.293995,-0.122906,0.007616,-0.947841,-0,-0,-0.21644,-0.976296,-0,-0,-0.21644,-0.976296,0.300095,0.066686,-0.206707,-0.928853,-0.300095,-0.066686,-0.206707,-0.928853,0.300095,0.066686,-0.206707,-0.928853,-0.300095,-0.066686,-0.206707,-0.928853,0.311524,0.099017,-0.217569,-0.91968,-0.311524,-0.099017,-0.217569,-0.91968,0.311524,0.099017,-0.217569,-0.91968,-0.311524,-0.099017,-0.217569,-0.91968,0.377418,-0.0238,0.057877,-0.923926,-0.041021,-0.057036,-0.102151,-0.992285,-0.017217,0.113333,-0.009179,-0.993365,-0.016801,0.069895,-0.009921,-0.997364,-0.377418,0.0238,0.057876,-0.923926,0.041021,0.057036,-0.102151,-0.992285,0.017217,-0.113333,-0.009179,-0.993365,0.016801,-0.069895,-0.009921,-0.997364,0.125849,0.363802,-0.033311,-0.922334,-0.125849,-0.363802,-0.033311,-0.922334,0.42696,-0.057743,0.03455,-0.901763,-0.087156,-0,0,-0.996195,0.087156,-0,-0,-0.996195,-0.42696,0.057743,0.03455,-0.901763,0.087156,-0,-0,-0.996195,-0.087156,0,-0,-0.996195,0.000685,0.026168,-0.026168,-0.999315,-0,-0,-0,-1,-0,-0,-0,-1,-0.000685,-0.026168,-0.026168,-0.999315,0,-0,-0,-1,0,-0,-0,-1,-0,-0,-0.130526,-0.991445,0,-0,0.130526,-0.991445,-0.172987,0.015134,-0.085832,-0.98106,0.172987,-0.015134,-0.085832,-0.98106,0,-0,-0,-1,0,-0,-0,-1,0,-0,0.087156,-0.996195,0,-0,-0.173648,-0.984808,0,-0,-0,-1,-0,0,0.173648,-0.984808,-0.292801,-0.053279,-0.16461,-0.94039,-0.367254,-0.038092,0.037577,-0.92858,-0.361912,-0.073116,0.126405,-0.920704,-0.130506,-0.002278,0.017303,-0.991294,0.156381,0.004095,0.025855,-0.98735,0.094592,-0.062428,-0.02319,-0.993286,0.29633,-0.082024,0.027557,-0.951158,0.29633,-0.082024,0.027557,-0.951158,0.29633,-0.082024,0.027557,-0.951158,0.130506,0.002278,0.017303,-0.991294,0.069661,-0.003651,-0.052208,-0.996197,0.069661,-0.003651,-0.052208,-0.996197,-0.156381,-0.004095,0.025855,-0.98735,-0.094592,0.062428,-0.02319,-0.993286,-0.29633,0.082024,0.027557,-0.951158,-0.29633,0.082024,0.027557,-0.951158,-0.29633,0.082024,0.027557,-0.951158,-0,-0,-0.043619,-0.999048,-0,-0,-0.043619,-0.999048,0.117487,0.061262,-0.061262,-0.989288,-0.117487,-0.061262,-0.061262,-0.989288,0,-0,-0,-1,0,-0,-0.087156,-0.996195,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0.160131,0.037879,-0.077809,-0.983295,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,-0.160131,-0.037879,-0.077809,-0.983295,-0,-0,-0,-1,-0,-0,-0,-1,-0,-0,-0,-1,-0,-0,-0,-1,-0,-0,-0,-1,-0,-0,-0,-1,-0,-0,-0,-1,-0,-0,-0,-1,0.229385,0.098333,-0.098333,-0.96335,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,-0.229385,-0.098333,-0.098333,-0.96335,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0.207912,-0,0,-0.978148,-0.087156,-0,-0,-0.996195,-0.258819,0,-0,-0.965926,-0.258819,0,-0,-0.965926,-0.258819,0,-0,-0.965926,-0.258819,0,-0,-0.965926,-0.258819,0,-0,-0.965926,-0.207912,-0,-0,-0.978148,0.087156,0,0,-0.996195,0.258819,-0,-0,-0.965926,0.258819,-0,-0,-0.965926,0.258819,-0,-0,-0.965926,0.258819,-0,-0,-0.965926,0.258819,-0,-0,-0.965926,-0.086824,-0.007596,0.086824,-0.992404,0.086824,0.007596,0.086824,-0.992404,0.017442,0.034894,0.000609,-0.999239,-0.017442,-0.034894,0.000609,-0.999239,-0.112927,-0.007897,0.069308,-0.991152,0.112928,0.007897,0.069308,-0.991152,0.256508,-0.029158,0.417475,-0.871245,-0.256508,0.029158,0.417474,-0.871245,0.354972,-0.082338,0.402471,-0.839781,-0.354972,0.082338,0.402471,-0.839781,0.354972,-0.082338,0.402471,-0.839781,-0.354972,0.082338,0.402471,-0.839781,0,-0,0.34202,-0.939693,0,-0,-0.21644,-0.976296,0.134957,-0.00034,-0.252048,-0.958258,-0.134957,0.00034,-0.252048,-0.958258,0.252897,-0.002125,-0.280862,-0.925827,-0.252897,0.002125,-0.280862,-0.925827,-0,-0,-0.34202,-0.939693,0,-0,0.087156,-0.996195,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0.129488,-0.027254,0.092741,-0.986858,-0,-0,0,-1,-0,-0,0,-1,-0,-0,0,-1,-0,-0,0,-1,-0,-0,0,-1,-0,-0,0,-1,-0,-0,0,-1,-0.129488,0.027254,0.092741,-0.986858,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0.232208,-0.03184,0.091272,-0.967851,-0,0,-0,-1,-0,0,-0,-1,-0,0,-0,-1,-0,0,-0,-1,-0,0,-0,-1,-0.232208,0.03184,0.091272,-0.967851,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,0.34202,-0.939693,0.095352,-0.019437,0.253917,-0.962318,-0.095353,0.019437,0.253917,-0.962318,0.056937,-0.023584,0.380197,-0.92285,-0.056937,0.023584,0.380197,-0.92285,-0.166979,-0.002604,-0.132939,-0.976954,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0,-0,-0,-1,0.166979,0.002604,-0.132939,-0.976954,-0,0,-0,-1,-0,0,-0,-1,-0,0,-0,-1,-0,0,-0,-1,0.373906,-0.049951,-0.220707,-0.899438,-0.373905,0.049951,-0.220707,-0.899438,-0,-0,-0.300706,-0.953717,-0,-0,-0.300706,-0.953717,-0,-0,0.043619,-0.999048,-0,-0,0.043619,-0.999048,0.15634,0.004979,-0.289618,-0.944275,0.145646,0.04954,0.04954,-0.986853,0.145646,0.04954,0.04954,-0.986853,-0.145646,-0.04954,0.04954,-0.986853];\n", "import {\n BONE_NAMES,\n SKELETON_1185_NAMES,\n REST_TRANSLATIONS,\n REST_ROTATIONS,\n PARENTS,\n} from './skeleton-data';\nimport {\n BONE_NAMES_441,\n PARENTS_441,\n REST_TRANSLATIONS_441,\n REST_ROTATIONS_441,\n} from './skeleton-data-441';\n\n/** @group Characters & Animation */\nexport interface SkeletonLibrary {\n boneNames?: string[];\n skeleton1185Names?: string[];\n skeleton1185StrippedNames?: string[];\n stdMaleRestTranslations?: Float32Array;\n stdMaleRestRotations?: Float32Array;\n stdMaleParents?: Int32Array;\n // Full 441-bone rig (body + facial). Used when a bin declares numBones=441.\n boneNames441?: string[];\n restTranslations441?: Float32Array;\n restRotations441?: Float32Array;\n parents441?: Int32Array;\n}\n\nconst FACIAL_PREFIX = 'FACIAL_';\n\nexport function getStripped1185Names(library: SkeletonLibrary): string[] | undefined {\n if (!library.skeleton1185Names) return undefined;\n if (!library.skeleton1185StrippedNames) {\n library.skeleton1185StrippedNames = library.skeleton1185Names.filter(\n (n) => !n.startsWith(FACIAL_PREFIX),\n );\n }\n return library.skeleton1185StrippedNames;\n}\n\n/**\n * Build the skeleton library from inlined data.\n * No network requests - all data is bundled in the engine.\n */\nexport function loadSkeletonLibrary(): SkeletonLibrary {\n return {\n boneNames: BONE_NAMES,\n skeleton1185Names: SKELETON_1185_NAMES,\n stdMaleRestTranslations: new Float32Array(REST_TRANSLATIONS),\n stdMaleRestRotations: new Float32Array(REST_ROTATIONS),\n stdMaleParents: new Int32Array(PARENTS),\n boneNames441: BONE_NAMES_441,\n restTranslations441: new Float32Array(REST_TRANSLATIONS_441),\n restRotations441: new Float32Array(REST_ROTATIONS_441),\n parents441: new Int32Array(PARENTS_441),\n };\n}\n", "import { Mat4, Quat, Vec3 } from '../math';\n\nimport { Animation } from '../animation';\nimport type { SkeletalKeyframeEntry } from '../animation';\nimport { getStripped1185Names } from '../loader/skeleton';\nimport type { SkeletonLibrary } from '../types';\n\nconst _mat = new Mat4();\nconst _pos = new Vec3();\nconst _rot = new Quat();\nconst _scale = new Vec3();\nconst _delta = new Quat();\n\n/** Frames to key, ascending: in-range `keyframeFrames` (duplicates kept), else every frame. */\nfunction sourceFrames(animationData: Animation): Float32Array {\n const numFrames = animationData.numFrames;\n if (!animationData.keyframeFrames?.length) {\n const frames = new Float32Array(numFrames);\n for (let f = 0; f < numFrames; f++) frames[f] = f;\n return frames;\n }\n return Float32Array.from(animationData.keyframeFrames.filter((f) => f >= 0 && f < numFrames)).sort();\n}\n\n/**\n * Decompose one bone's matrices at `frames` into flat keys. `extract` reads\n * each matrix (rigid for FBX clips); `reference`, for a reference-pose clip,\n * re-bases every key from the clip's frame 0 onto the target pose.\n */\nfunction decomposeBone(\n data: Float32Array,\n numBones: number,\n bone: number,\n frames: Float32Array,\n extract: ExtractBonePose = extractBonePose,\n reference: BoneReference | null = null,\n): SkeletalKeyframeEntry {\n const n = frames.length;\n const positions = new Float32Array(n * 3);\n const rotations = new Float32Array(n * 4);\n const scales = new Float32Array(n * 3);\n for (let k = 0; k < n; k++) {\n const offset = (frames[k] * numBones + bone) * 16;\n for (let i = 0; i < 16; i++) _mat.data[i] = data[offset + i];\n extract(_mat, _pos, _rot, _scale);\n if (reference) {\n _pos.sub(reference.position).add(reference.targetPosition);\n _delta.mul2(reference.inverseRotation, _rot);\n _rot.mul2(reference.targetRotation, _delta);\n _rot.normalize();\n }\n positions[k * 3] = _pos.x; positions[k * 3 + 1] = _pos.y; positions[k * 3 + 2] = _pos.z;\n rotations[k * 4] = _rot.x; rotations[k * 4 + 1] = _rot.y;\n rotations[k * 4 + 2] = _rot.z; rotations[k * 4 + 3] = _rot.w;\n scales[k * 3] = _scale.x; scales[k * 3 + 1] = _scale.y; scales[k * 3 + 2] = _scale.z;\n }\n return { frames, positions, rotations, scales };\n}\n\n// --- FBX clips ------------------------------------------------------------\n\nconst BASIS_EPSILON = 1e-8;\n\ninterface ReferencePoseSource {\n translations: Float32Array;\n rotations: Float32Array;\n baseAnimation?: Animation;\n}\n\n/** How one bone matrix is read into a pose. */\ntype ExtractBonePose = (mat: Mat4, position: Vec3, rotation: Quat, scale: Vec3) => void;\n\n/** A reference-pose clip's per-bone re-basing: frame 0's pose, and the target it maps onto. */\ninterface BoneReference {\n position: Vec3;\n inverseRotation: Quat;\n targetPosition: Vec3;\n targetRotation: Quat;\n}\n\nfunction normalizeVector(x: number, y: number, z: number): [number, number, number] {\n const len = Math.hypot(x, y, z);\n if (len <= BASIS_EPSILON) return [0, 0, 0];\n return [x / len, y / len, z / len];\n}\n\nfunction fallbackOrthogonalAxis(x: number, y: number, z: number): [number, number, number] {\n const ax = Math.abs(x);\n const ay = Math.abs(y);\n const az = Math.abs(z);\n if (ax <= ay && ax <= az) return [1, 0, 0];\n if (ay <= az) return [0, 1, 0];\n return [0, 0, 1];\n}\n\nfunction orthonormalizeBasis(mat: Mat4): void {\n const d = mat.data;\n let [x0, x1, x2] = normalizeVector(d[0], d[1], d[2]);\n if (x0 === 0 && x1 === 0 && x2 === 0) x0 = 1;\n\n let y0 = d[4];\n let y1 = d[5];\n let y2 = d[6];\n const xy = x0 * y0 + x1 * y1 + x2 * y2;\n y0 -= xy * x0;\n y1 -= xy * x1;\n y2 -= xy * x2;\n let [ny0, ny1, ny2] = normalizeVector(y0, y1, y2);\n if (ny0 === 0 && ny1 === 0 && ny2 === 0) {\n const [a0, a1, a2] = fallbackOrthogonalAxis(x0, x1, x2);\n const dot = x0 * a0 + x1 * a1 + x2 * a2;\n [ny0, ny1, ny2] = normalizeVector(a0 - dot * x0, a1 - dot * x1, a2 - dot * x2);\n }\n\n const z0 = x1 * ny2 - x2 * ny1;\n const z1 = x2 * ny0 - x0 * ny2;\n const z2 = x0 * ny1 - x1 * ny0;\n\n d[0] = x0; d[1] = x1; d[2] = x2;\n d[4] = ny0; d[5] = ny1; d[6] = ny2;\n d[8] = z0; d[9] = z1; d[10] = z2;\n}\n\n/** Whether a clip opted into rigid bones (see `AnimationLoadOptions`); a reference-pose clip always is. */\nfunction wantsRigidBones(animationData: Animation): boolean {\n return animationData.rigidBones === true || animationData.referenceFrameMode === 'first-frame';\n}\n\n/** The default extraction: translation, scale and rotation taken from the matrix as stored. */\nfunction extractBonePose(mat: Mat4, position: Vec3, rotation: Quat, scale: Vec3): void {\n mat.getTranslation(position);\n mat.getScale(scale);\n rotation.setFromMat4(mat);\n rotation.normalize();\n}\n\nfunction extractRigidBonePose(mat: Mat4, position: Vec3, rotation: Quat, scale: Vec3): void {\n mat.getTranslation(position);\n // FBX-converted clips can carry conversion shear/non-uniform scale in the\n // 3x3 basis. Splat skinning expects rigid bones, so strip that before\n // deriving the quaternion and keep authored bone scale neutral.\n orthonormalizeBasis(mat);\n rotation.setFromMat4(mat);\n rotation.normalize();\n scale.set(1, 1, 1);\n}\n\nfunction restPoseArraysForAnimation(\n animationData: Animation,\n skeletonLibrary: SkeletonLibrary,\n): ReferencePoseSource | null {\n if (animationData.numBones === skeletonLibrary.boneNames?.length && skeletonLibrary.stdMaleRestTranslations && skeletonLibrary.stdMaleRestRotations) {\n return {\n translations: skeletonLibrary.stdMaleRestTranslations,\n rotations: skeletonLibrary.stdMaleRestRotations,\n baseAnimation: animationData.referenceBaseAnimation?.numBones === animationData.numBones\n ? animationData.referenceBaseAnimation\n : undefined,\n };\n }\n if (animationData.numBones === skeletonLibrary.boneNames441?.length && skeletonLibrary.restTranslations441 && skeletonLibrary.restRotations441) {\n return {\n translations: skeletonLibrary.restTranslations441,\n rotations: skeletonLibrary.restRotations441,\n baseAnimation: animationData.referenceBaseAnimation?.numBones === animationData.numBones\n ? animationData.referenceBaseAnimation\n : undefined,\n };\n }\n return null;\n}\n\nfunction setReferenceTargetPose(\n referenceRest: ReferencePoseSource,\n boneIdx: number,\n position: Vec3,\n rotation: Quat,\n): void {\n const basePose = referenceRest.baseAnimation?.skeletalStore?.keyframes.get(boneIdx);\n if (basePose?.frames.length) {\n const p = basePose.positions;\n const r = basePose.rotations;\n position.set(p[0], p[1], p[2]);\n rotation.set(r[0], r[1], r[2], r[3]);\n return;\n }\n\n const restTranslationOffset = boneIdx * 3;\n position.set(\n referenceRest.translations[restTranslationOffset],\n referenceRest.translations[restTranslationOffset + 1],\n referenceRest.translations[restTranslationOffset + 2],\n );\n const restRotationOffset = boneIdx * 4;\n rotation.set(\n referenceRest.rotations[restRotationOffset],\n referenceRest.rotations[restRotationOffset + 1],\n referenceRest.rotations[restRotationOffset + 2],\n referenceRest.rotations[restRotationOffset + 3],\n );\n}\n\n/** Rigid extraction for FBX clips, the stored matrix as-is otherwise. */\nfunction extractorFor(animationData: Animation): ExtractBonePose {\n return wantsRigidBones(animationData) ? extractRigidBonePose : extractBonePose;\n}\n\n/** Frame 0 of `bone` (the import reference pose) and the target pose it maps onto. */\nfunction boneReference(data: Float32Array, bone: number, referenceRest: ReferencePoseSource): BoneReference {\n const reference: BoneReference = {\n position: new Vec3(),\n inverseRotation: new Quat(),\n targetPosition: new Vec3(),\n targetRotation: new Quat(),\n };\n // Frame 0's matrices come first, so bone N's sits at N * 16.\n for (let i = 0; i < 16; i++) _mat.data[i] = data[bone * 16 + i];\n extractRigidBonePose(_mat, reference.position, reference.inverseRotation, _scale);\n reference.inverseRotation.conjugate();\n setReferenceTargetPose(referenceRest, bone, reference.targetPosition, reference.targetRotation);\n return reference;\n}\n\n/**\n * Walk the raw 4\u00D74 bone matrices stored in `animationData.data` and produce\n * the per-bone keys used at playback time.\n *\n * Idempotent - subsequent calls on the same `Animation` are no-ops (guarded\n * by `Animation.skeletalConverted`). {@link Animation.register} calls this\n * for you.\n *\n * Side effect: clears `animationData.data` once converted, since the raw\n * matrices are no longer needed and would otherwise hold ~16 floats per bone\n * per frame in memory for the lifetime of the animation.\n */\nexport function convertSkeletalAnimation(\n animationData: Animation,\n skeletonLibrary?: SkeletonLibrary,\n): void {\n if (animationData.skeletalConverted) return;\n\n if (animationData.numBones === 0 || animationData.numFrames === 0 || animationData.data.length === 0) {\n animationData.skeletalConverted = true;\n animationData.data = new Float32Array(0);\n return;\n }\n\n const store = animationData.skeletalStore ?? {\n keyframes: new Map<number, SkeletalKeyframeEntry>(),\n manualBones: new Set<number>(),\n source: 'imported',\n };\n animationData.skeletalStore = store;\n store.keyframes.clear();\n\n const numBones = animationData.numBones;\n const frames = sourceFrames(animationData);\n const extract = extractorFor(animationData);\n // Reference-pose clips re-base onto the target rig's rest, so they need the\n // library; without it (the shared converted cache) they convert as stored.\n const referenceRest = animationData.referenceFrameMode === 'first-frame' && skeletonLibrary\n ? restPoseArraysForAnimation(animationData, skeletonLibrary)\n : null;\n for (let boneIdx = 0; boneIdx < numBones; boneIdx++) {\n const reference = referenceRest ? boneReference(animationData.data, boneIdx, referenceRest) : null;\n store.keyframes.set(boneIdx, decomposeBone(animationData.data, numBones, boneIdx, frames, extract, reference));\n }\n\n animationData.skeletalConverted = true;\n animationData.data = new Float32Array(0);\n}\n\n/**\n * Return a view of `animationData` remapped to the target armature's bone\n * count, handling rig mismatches (e.g. a 1185-bone source animation played on\n * an 86-bone body rig). Target bones with no matching source bone stay at\n * rest pose during playback.\n *\n * Result is cached on the input via `Animation.filteredForBones`, so repeated\n * calls for the same target bone count reuse the filtered copy.\n */\nexport function filterAnimationForArmature(\n animationData: Animation,\n targetBoneCount: number,\n skeletonLibrary: SkeletonLibrary,\n): Animation {\n const cacheMap = animationData.filteredForBones;\n const cached = cacheMap?.get(targetBoneCount);\n if (cached) return cached;\n\n // Resolve target names from skeleton library (86-bone std male or 441-bone full rig).\n let targetNames: string[] | undefined;\n if (targetBoneCount === skeletonLibrary?.boneNames?.length) {\n targetNames = skeletonLibrary.boneNames;\n } else if (targetBoneCount === skeletonLibrary?.boneNames441?.length) {\n targetNames = skeletonLibrary.boneNames441;\n }\n if (!targetNames) return animationData;\n\n // Resolve source names by bone count: full 1185, stripped (1185 minus\n // facial), 441, or 86.\n let sourceNames: string[] | undefined;\n const fullNames = skeletonLibrary.skeleton1185Names;\n if (fullNames && animationData.numBones === fullNames.length) {\n sourceNames = fullNames;\n } else if (animationData.numBones === skeletonLibrary.boneNames441?.length) {\n sourceNames = skeletonLibrary.boneNames441;\n } else if (animationData.numBones === skeletonLibrary.boneNames?.length) {\n sourceNames = skeletonLibrary.boneNames;\n } else {\n const stripped = getStripped1185Names(skeletonLibrary);\n if (stripped && stripped.length === animationData.numBones) sourceNames = stripped;\n }\n if (!sourceNames) return animationData;\n\n // Build target \u2192 source remap (-1 when target has no matching source bone).\n const sourceByName = new Map<string, number>();\n sourceNames.forEach((n, i) => sourceByName.set(n, i));\n const mapIndices = new Int32Array(targetBoneCount);\n let identity = targetBoneCount === sourceNames.length;\n for (let i = 0; i < targetBoneCount; i++) {\n const s = sourceByName.get(targetNames[i]);\n mapIndices[i] = s === undefined ? -1 : s;\n if (identity && mapIndices[i] !== i) identity = false;\n }\n if (identity) {\n const cache = cacheMap ?? new Map<number, Animation>();\n cache.set(targetBoneCount, animationData);\n animationData.filteredForBones = cache;\n return animationData;\n }\n\n // Emit pre-converted output: only mapped target bones get keyframe entries.\n // Unmapped bones stay at rest pose at playback (see getAnimSample fallback).\n const numFrames = animationData.numFrames;\n const filtered = new Animation(new Float32Array(0), numFrames, targetBoneCount);\n const keyframes = new Map<number, SkeletalKeyframeEntry>();\n\n // Carry the translation mask across the bone remap. It is indexed by bone, so\n // it has to follow the same target->source mapping as the keyframes; losing\n // it here would silently reinstate the source rig's bone lengths. Target bones\n // with no source bone stay 0 - they have no keyframes either, so playback\n // falls back to rest regardless.\n if (animationData.translationMask) {\n const sourceMask = animationData.translationMask;\n const targetMask = new Uint8Array(targetBoneCount);\n for (let i = 0; i < targetBoneCount; i++) {\n const srcIdx = mapIndices[i];\n if (srcIdx >= 0) targetMask[i] = sourceMask[srcIdx];\n }\n filtered.translationMask = targetMask;\n }\n\n if (animationData.data.length === 0) {\n // Source is already converted: its entries are read-only, so share them.\n const sourceStore = animationData.skeletalStore;\n if (sourceStore?.keyframes) {\n for (let i = 0; i < targetBoneCount; i++) {\n const srcIdx = mapIndices[i];\n if (srcIdx < 0) continue;\n const entry = sourceStore.keyframes.get(srcIdx);\n if (entry?.frames.length) keyframes.set(i, entry);\n }\n }\n } else {\n // Source is raw matrices - convert the mapped target bones only.\n const frames = sourceFrames(animationData);\n const extract = extractorFor(animationData);\n for (let i = 0; i < targetBoneCount; i++) {\n const srcIdx = mapIndices[i];\n if (srcIdx < 0) continue;\n keyframes.set(i, decomposeBone(animationData.data, animationData.numBones, srcIdx, frames, extract));\n }\n }\n\n filtered.skeletalConverted = true;\n filtered.skeletalStore = { keyframes, manualBones: new Set<number>(), source: 'imported' };\n\n const cache = cacheMap ?? new Map<number, Animation>();\n cache.set(targetBoneCount, filtered);\n animationData.filteredForBones = cache;\n return filtered;\n}\n", "import type { SkeletalKeyframeEntry } from '../../animation';\nimport { BONE_NAMES, SKELETON_1185_NAMES } from '../skeleton/skeleton-data';\nimport { BONE_NAMES_441 } from '../skeleton/skeleton-data-441';\n\n/**\n * Decoded contents of an *armature GLB* - a glTF 2.0 binary carrying a bone\n * hierarchy, a skin, and one animation clip. Produced by the offline MetaHuman\n * GLB exporter, and readable back after a Blender round-trip.\n *\n * @internal\n */\nexport interface ArmatureGlbAnimation {\n /** Per-bone keys, every bone keyed on every frame. The frames array is shared. */\n keyframes: Map<number, SkeletalKeyframeEntry>;\n numFrames: number;\n numBones: number;\n /** Bone names in bone-index order (canonical rig order when recognised). */\n boneNames: string[];\n /**\n * Per bone: `1` if the clip drives that bone's translation, `0` if the bone\n * must inherit the armature's rest translation. `undefined` when every bone\n * is driven - which is what a `.anim` file means, since that format cannot\n * say anything else.\n *\n * Derived from the DATA, not from which channels exist: a translation\n * channel whose keys are all equal declares a rest pose, and a channel that\n * varies is motion. See {@link parseArmatureGlbAnimation}.\n */\n translationMask?: Uint8Array;\n /** Source frame rate derived from the main timestamp accessor. */\n frameRate: number;\n /** Clip name as stored in the GLB. */\n animationName: string;\n}\n\nconst GLB_MAGIC = 0x46546c67; // 'glTF'\nconst CHUNK_JSON = 0x4e4f534a; // 'JSON'\nconst CHUNK_BIN = 0x004e4942; // 'BIN\\0'\nconst COMPONENT_FLOAT = 5126;\nconst COMPONENT_SHORT = 5122;\nconst COMPONENTS_PER_TYPE: Record<string, number> = { SCALAR: 1, VEC3: 3, VEC4: 4 };\n/** glTF 2.0 dequantization divisor for `normalized: true` SHORT. */\nconst SHORT_SCALE = 32767;\n\n/** Minimal shape of the glTF JSON fields this reader consumes. */\ninterface Gltf {\n asset?: { version?: string };\n nodes?: Array<{ name?: string; translation?: number[] }>;\n skins?: Array<{ joints?: number[] }>;\n accessors?: Array<{\n bufferView?: number;\n byteOffset?: number;\n componentType?: number;\n normalized?: boolean;\n count?: number;\n type?: string;\n }>;\n bufferViews?: Array<{ byteOffset?: number; byteLength?: number; byteStride?: number }>;\n animations?: Array<{\n name?: string;\n samplers: Array<{ input: number; output: number; interpolation?: string }>;\n channels: Array<{ sampler: number; target: { node?: number; path: string } }>;\n }>;\n}\n\n/**\n * Split a `.glb` container into its JSON chunk and its binary chunk.\n *\n * @throws If the magic, version or chunk layout is not glTF 2.0 binary.\n */\nfunction splitGlb(buffer: ArrayBuffer): { json: Gltf; binOffset: number; binLength: number } {\n if (buffer.byteLength < 20) throw new Error('Not a GLB: file is too short');\n const view = new DataView(buffer);\n if (view.getUint32(0, true) !== GLB_MAGIC) throw new Error('Not a GLB: bad magic');\n const version = view.getUint32(4, true);\n if (version !== 2) throw new Error(`Unsupported GLB version ${version} (expected 2)`);\n\n let json: Gltf | null = null;\n let binOffset = -1;\n let binLength = 0;\n\n let offset = 12;\n while (offset + 8 <= buffer.byteLength) {\n const chunkLength = view.getUint32(offset, true);\n const chunkType = view.getUint32(offset + 4, true);\n const dataStart = offset + 8;\n if (dataStart + chunkLength > buffer.byteLength) throw new Error('Corrupt GLB: chunk overruns file');\n\n if (chunkType === CHUNK_JSON) {\n json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, dataStart, chunkLength))) as Gltf;\n } else if (chunkType === CHUNK_BIN) {\n binOffset = dataStart;\n binLength = chunkLength;\n }\n offset = dataStart + chunkLength;\n }\n\n if (!json) throw new Error('Corrupt GLB: no JSON chunk');\n if (binOffset < 0) throw new Error('GLB has no BIN chunk - external buffers are not supported');\n return { json, binOffset, binLength };\n}\n\n/**\n * Read accessor `index` as a flat `Float32Array` of `count * components`.\n *\n * Two encodings are accepted, matching what the MetaHuman GLB exporter\n * emits: plain FLOAT, and `normalized: true` SHORT, dequantized per the glTF\n * rule `f = max(c / 32767, -1)`. Anything else throws by name rather than\n * being reinterpreted as float garbage.\n *\n * Accessors may share a bufferView and address their slice with `byteOffset`.\n * FLOAT takes a zero-copy view when 4-byte aligned (the writer guarantees it);\n * the unaligned path and every SHORT path copy.\n */\nfunction readFloatAccessor(\n json: Gltf,\n buffer: ArrayBuffer,\n binOffset: number,\n index: number,\n expectedType: string,\n): Float32Array {\n const accessor = json.accessors?.[index];\n if (!accessor) throw new Error(`GLB accessor ${index} is missing`);\n if (accessor.type !== expectedType) {\n throw new Error(`GLB accessor ${index} must be ${expectedType} (got ${accessor.type})`);\n }\n if (accessor.bufferView === undefined) {\n throw new Error(`GLB accessor ${index} has no bufferView - sparse accessors are not supported`);\n }\n const bufferView = json.bufferViews?.[accessor.bufferView];\n if (!bufferView) throw new Error(`GLB bufferView ${accessor.bufferView} is missing`);\n if (bufferView.byteStride !== undefined && bufferView.byteStride !== 0) {\n throw new Error('Interleaved (byteStride) animation accessors are not supported');\n }\n\n const components = COMPONENTS_PER_TYPE[expectedType];\n const count = accessor.count ?? 0;\n const length = count * components;\n const start = binOffset + (bufferView.byteOffset ?? 0) + (accessor.byteOffset ?? 0);\n\n if (accessor.componentType === COMPONENT_SHORT) {\n if (!accessor.normalized) {\n throw new Error(`GLB accessor ${index} is SHORT but not normalized - refusing to guess a scale`);\n }\n if (start + length * 2 > buffer.byteLength) {\n throw new Error(`GLB accessor ${index} overruns the BIN chunk`);\n }\n const raw = (start & 1) === 0\n ? new Int16Array(buffer, start, length)\n : new Int16Array(buffer.slice(start, start + length * 2));\n const out = new Float32Array(length);\n for (let i = 0; i < length; i++) out[i] = Math.max(raw[i] / SHORT_SCALE, -1);\n return out;\n }\n\n if (accessor.componentType !== COMPONENT_FLOAT) {\n throw new Error(\n `GLB accessor ${index} must be FLOAT or normalized SHORT (got componentType ${accessor.componentType})`,\n );\n }\n if (start + length * 4 > buffer.byteLength) {\n throw new Error(`GLB accessor ${index} overruns the BIN chunk`);\n }\n if ((start & 3) === 0) return new Float32Array(buffer, start, length);\n // Unaligned: copy into a fresh buffer so the typed-array view is legal.\n return new Float32Array(buffer.slice(start, start + length * 4));\n}\n\n/** Rigs the engine knows by name. Order inside each table IS the bone order. */\nconst KNOWN_RIGS: readonly (readonly string[])[] = [BONE_NAMES, BONE_NAMES_441, SKELETON_1185_NAMES];\n\n/**\n * If `jointNames` is one of the engine's known rigs, return the permutation\n * that puts it in that rig's canonical order (`order[bone]` indexes\n * `jointNames`). Returns `null` when no rig matches, in which case the file's\n * own joint order stands.\n *\n * This matters because downstream `filterAnimationForArmature` resolves rigs by\n * NAME but assumes source bone index order matches the engine's table. A\n * Blender round-trip is free to reorder joints, so index order cannot be\n * trusted - the name set can.\n */\nfunction canonicalBoneOrder(jointNames: string[]): number[] | null {\n const indexByName = new Map<string, number>();\n for (let i = 0; i < jointNames.length; i++) indexByName.set(jointNames[i], i);\n if (indexByName.size !== jointNames.length) return null; // duplicate names\n\n for (const table of KNOWN_RIGS) {\n if (table.length !== jointNames.length) continue;\n const order: number[] = [];\n for (const name of table) {\n const i = indexByName.get(name);\n if (i === undefined) break;\n order.push(i);\n }\n if (order.length === table.length) return order;\n }\n return null;\n}\n\n/**\n * How a sampler's output is laid out, per its interpolation mode.\n *\n * CUBICSPLINE stores `[inTangent, value, outTangent]` per keyframe. The Hermite\n * spline passes exactly through `value` at the key's own time, and this reader\n * samples only at key times, so taking the middle element is exact rather than\n * an approximation. Reading it as LINEAR would consume tangents as poses and\n * produce a plausible-but-wrong result, which is why the mode is resolved\n * explicitly and anything unrecognised throws.\n */\nfunction samplerLayout(\n interpolation: string | undefined,\n label: string,\n): { stride: number; offset: number; step: boolean } {\n switch (interpolation ?? 'LINEAR') {\n case 'LINEAR':\n return { stride: 1, offset: 0, step: false };\n case 'STEP':\n return { stride: 1, offset: 0, step: true };\n case 'CUBICSPLINE':\n return { stride: 3, offset: 1, step: false };\n default:\n throw new Error(`${label} uses unsupported interpolation \"${interpolation}\"`);\n }\n}\n\n/** One decoded animation channel, with its own timeline. */\ninterface DecodedChannel {\n values: Float32Array;\n times: Float32Array;\n keys: number;\n stride: number;\n offset: number;\n comps: number;\n step: boolean;\n /** True when key `i` is exactly frame `i` of the main timeline. */\n aligned: boolean;\n}\n\n/** Component `c` of keyframe `k`. */\nfunction keyValue(ch: DecodedChannel, k: number, c: number): number {\n return ch.values[(k * ch.stride + ch.offset) * ch.comps + c];\n}\n\n/**\n * How far a translation channel may wander and still count as a declaration of\n * rest rather than motion: 10 \u00B5m.\n *\n * The distinction cannot be drawn from channel *presence*, because a\n * conformant writer emits a channel for every bone and Blender re-exports\n * dense channels for everything it imports. It is drawn from the values, which\n * survive that round trip: a constant track stays constant however densely it\n * is written.\n *\n * The bound is empirical and has room on both sides. Below it: a Blender\n * 4.2.18 import\u2192export of our own files re-derives every bone through its own\n * matrix pipeline and perturbs a constant translation by at most 7.96e-7 m,\n * 12x under this. Above it: the smallest genuinely moving channel in the same\n * files drifts 3.06e-4 m, 30x over. The writer's own collapse threshold\n * (the exporter's own `TRANSLATION_EPS`, 1e-6 m) sits inside\n * that gap too, so everything it calls constant still reads as constant here,\n * before and after a round trip.\n *\n * Shared with the `.anim` reader ({@link Animation.parse}), which asks the same\n * question of the same quantity, so one number keeps the two formats from ever\n * disagreeing about what \"constant\" means. It has even more room there: a v3\n * `.anim` stores float16, whose decode is deterministic, so a constant track\n * comes back bit-identical (deviation exactly 0) while the smallest moving bone\n * across `test_full` / `test_stripped` / `test_blend_*` drifts 2.69e-4 m. Motion\n * finer than this bound is not representable at bone-offset magnitudes in\n * float16 anyway (one ulp at 0.4 m is 2.4e-4 m), so it has already been\n * quantized flat before the test sees it.\n *\n * @internal\n */\nexport const CONSTANT_TRANSLATION_EPS = 1e-5;\n\n/**\n * The same test for scale, which is dimensionless, so the tolerance stands\n * against the identity it is being compared with. 1e-4 is far above float32\n * noise - Blender writes a scale channel for every bone it exports and ours\n * come back within 3.6e-7 of `1,1,1` - and far below any scale a rig author\n * would notice.\n */\nconst CONSTANT_SCALE_EPS = 1e-4;\n\n/**\n * True when every key of `ch` sits within `eps` of the first - i.e. the channel\n * holds one value for the whole clip.\n *\n * For CUBICSPLINE the tangents are checked too: equal values with a non-zero\n * tangent still bulge between keys, so that is motion, not a constant.\n */\nfunction isConstantChannel(ch: DecodedChannel, eps: number): boolean {\n for (let c = 0; c < ch.comps; c++) {\n const first = keyValue(ch, 0, c);\n for (let k = 1; k < ch.keys; k++) {\n if (Math.abs(keyValue(ch, k, c) - first) > eps) return false;\n }\n }\n if (ch.stride === 3) {\n for (let k = 0; k < ch.keys; k++) {\n for (let c = 0; c < ch.comps; c++) {\n if (Math.abs(ch.values[(k * 3) * ch.comps + c]) > eps) return false; // inTangent\n if (Math.abs(ch.values[(k * 3 + 2) * ch.comps + c]) > eps) return false; // outTangent\n }\n }\n }\n return true;\n}\n\n/**\n * Evaluate a channel at time `t` into `out`.\n *\n * Needed because a channel is not obliged to share the main timeline: Blender\n * collapses a constant track to two STEP keys on a two-entry timeline of its\n * own, and hand-authored files may key anything anywhere. Resampling here is\n * what lets frame `f` mean one instant across every bone downstream.\n */\nfunction evalChannel(ch: DecodedChannel, t: number, out: Float32Array): void {\n const n = ch.keys;\n if (n === 1 || t <= ch.times[0]) {\n for (let c = 0; c < ch.comps; c++) out[c] = keyValue(ch, 0, c);\n return;\n }\n if (t >= ch.times[n - 1]) {\n for (let c = 0; c < ch.comps; c++) out[c] = keyValue(ch, n - 1, c);\n return;\n }\n let lo = 0;\n let hi = n - 1;\n while (hi - lo > 1) {\n const mid = (lo + hi) >> 1;\n if (ch.times[mid] <= t) lo = mid; else hi = mid;\n }\n const t0 = ch.times[lo];\n const t1 = ch.times[lo + 1];\n const dt = t1 - t0;\n const u = dt > 0 ? (t - t0) / dt : 0;\n\n if (ch.stride === 3) {\n // CUBICSPLINE: Hermite between the two keys, using key `lo`'s outTangent\n // and key `lo+1`'s inTangent. Tangents are stored scaled by 1/dt.\n const u2 = u * u;\n const u3 = u2 * u;\n const h00 = 2 * u3 - 3 * u2 + 1;\n const h10 = u3 - 2 * u2 + u;\n const h01 = -2 * u3 + 3 * u2;\n const h11 = u3 - u2;\n for (let c = 0; c < ch.comps; c++) {\n const p0 = ch.values[(lo * 3 + 1) * ch.comps + c];\n const m0 = ch.values[(lo * 3 + 2) * ch.comps + c] * dt;\n const p1 = ch.values[((lo + 1) * 3 + 1) * ch.comps + c];\n const m1 = ch.values[((lo + 1) * 3) * ch.comps + c] * dt;\n out[c] = h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1;\n }\n return;\n }\n if (ch.step) {\n for (let c = 0; c < ch.comps; c++) out[c] = keyValue(ch, lo, c);\n return;\n }\n // LINEAR. Quaternions get a sign fix so the short way round is taken; the\n // caller renormalizes, which turns this into an nlerp.\n let sign = 1;\n if (ch.comps === 4) {\n let dot = 0;\n for (let c = 0; c < 4; c++) dot += keyValue(ch, lo, c) * keyValue(ch, lo + 1, c);\n if (dot < 0) sign = -1;\n }\n for (let c = 0; c < ch.comps; c++) {\n const a = keyValue(ch, lo, c);\n const b = keyValue(ch, lo + 1, c) * sign;\n out[c] = a + (b - a) * u;\n }\n}\n\nfunction decodeChannel(\n json: Gltf,\n buffer: ArrayBuffer,\n binOffset: number,\n sampler: { input: number; output: number; interpolation?: string },\n type: 'VEC3' | 'VEC4',\n label: string,\n mainInput: number,\n numFrames: number,\n): DecodedChannel {\n const { stride, offset, step } = samplerLayout(sampler.interpolation, label);\n const comps = COMPONENTS_PER_TYPE[type];\n const values = readFloatAccessor(json, buffer, binOffset, sampler.output, type);\n const times = readFloatAccessor(json, buffer, binOffset, sampler.input, 'SCALAR');\n const keys = values.length / comps / stride;\n if (!Number.isInteger(keys) || keys !== times.length) {\n throw new Error(\n `${label} has ${values.length / comps} output elements for ${times.length} timestamps `\n + `(interpolation ${sampler.interpolation ?? 'LINEAR'})`,\n );\n }\n if (keys === 0) throw new Error(`${label} has no keyframes`);\n const aligned = sampler.input === mainInput && keys === numFrames;\n return { values, times, keys, stride, offset, comps, step, aligned };\n}\n\n/**\n * Parse an armature GLB into the per-bone keys {@link Animation} plays from.\n *\n * **Bones are resolved by NAME, never by node index.** The joint set comes from\n * `skins[0].joints` when a skin is present (files we write, and anything\n * Blender exports), falling back to \"every node is a bone\" for older files\n * that carried no skin. If the joint names match one of the engine's known rigs the bones are\n * re-ordered into that rig's canonical order; otherwise the file's joint order\n * stands. Nodes that are not joints - the armature parent, mesh nodes, cameras,\n * anything a DCC tool adds - are ignored, and so are channels targeting them.\n *\n * What it accepts:\n *\n * - `translation`, `rotation` and `scale` channels; `weights` is ignored,\n * there being no morph targets on an armature.\n * - Rotations as FLOAT or `normalized: true` SHORT (dequantized + renormalized).\n * - `LINEAR`, `STEP` and `CUBICSPLINE` samplers. Other modes throw by name.\n * - Per-channel timelines: each sampler rides either the main timeline - the\n * longest, so frame `f` is the same instant for every bone - or a one-key\n * timeline of its own, meaning a constant channel held for the whole clip.\n * - Accessors sharing one bufferView via `byteOffset`, and absent `min`/`max`.\n *\n * What it requires: exactly one rotation channel per bone, timestamps on a\n * uniform grid (the engine indexes animations by frame, so key `i` must be\n * frame `i`), and no duplicate channels.\n *\n * **Constant translation is a rest declaration, not motion.** A translation\n * channel whose keys are all equal (within {@link CONSTANT_TRANSLATION_EPS})\n * states the rig's own bone length; a channel that varies is real motion -\n * root motion at the pelvis, and the face, which is translation-driven. The\n * former is reported through {@link ArmatureGlbAnimation.translationMask} as a\n * `0`, so playback keeps the TARGET character's rest translation and its limbs\n * do not resize mid-clip. On our own clips that lands on 85 of 441 bones\n * without a single bone name being mentioned anywhere.\n *\n * The test reads the data rather than the channel list on purpose. Absence\n * could carry the same message, but only in a file nobody has touched: a\n * conformant reader is entitled to use `nodes[b].translation` when a channel\n * is missing, and Blender re-exports dense channels for every bone, which\n * erases the distinction. Constancy survives both. Files that genuinely omit\n * the channel - everything written before 2026-08 - are still read the old\n * way, as `0`.\n *\n * Scale gets the same treatment, and resolves at parse time: a constant scale\n * is a rest declaration, and every rig this engine builds rests at scale\n * `1,1,1`, so a constant channel simply resolves to identity here and needs no\n * mask of its own. A varying scale is honoured. Our writers emit no scale\n * channels at all, so this only ever fires for a bone somebody scaled by hand\n * in a DCC tool.\n *\n * @throws If the container, the layout, or an accessor is invalid.\n * @internal\n */\nexport function parseArmatureGlbAnimation(\n buffer: ArrayBuffer,\n animationName?: string,\n): ArmatureGlbAnimation {\n const { json, binOffset } = splitGlb(buffer);\n\n const declaredVersion = json.asset?.version;\n if (declaredVersion !== undefined && !declaredVersion.startsWith('2')) {\n throw new Error(`Unsupported glTF asset version \"${declaredVersion}\"`);\n }\n\n const nodes = json.nodes ?? [];\n if (nodes.length === 0) throw new Error('Armature GLB has no nodes');\n\n // Joint set: the skin when there is one, otherwise every node (the skinless\n // layout this loader shipped with, before the skin was added for Blender).\n const skin = json.skins?.[0];\n let jointNodes = skin?.joints;\n if (jointNodes === undefined) {\n jointNodes = Array.from({ length: nodes.length }, (_, i) => i);\n }\n if (jointNodes.length === 0) throw new Error('Armature GLB skin has no joints');\n for (const node of jointNodes) {\n if (node < 0 || node >= nodes.length) throw new Error(`Skin references node ${node}, out of range`);\n }\n\n const jointNames = jointNodes.map((node, i) => nodes[node].name ?? `#${i}`);\n const order = canonicalBoneOrder(jointNames);\n const boneToNode = order\n ? order.map((jointIdx) => jointNodes[jointIdx])\n : jointNodes.slice();\n const numBones = boneToNode.length;\n // Bone order, which is canonical order when the rig was recognised.\n const boneNames = boneToNode.map((node, i) => nodes[node].name ?? `#${i}`);\n const nodeToBone = new Map<number, number>();\n boneToNode.forEach((node, bone) => nodeToBone.set(node, bone));\n\n const animations = json.animations ?? [];\n if (animations.length === 0) throw new Error('Armature GLB has no animations');\n const animation = animationName === undefined\n ? animations[0]\n : animations.find((a) => a.name === animationName);\n if (!animation) {\n const available = animations.map((a) => a.name ?? '<unnamed>').join(', ');\n throw new Error(`Animation \"${animationName}\" not found in GLB (have: ${available})`);\n }\n\n // Resolve channels by target. Channels aimed at non-joint nodes are skipped,\n // not fatal - a DCC tool may animate the armature object or a camera.\n const translationOf = new Int32Array(numBones).fill(-1);\n const rotationOf = new Int32Array(numBones).fill(-1);\n const scaleOf = new Int32Array(numBones).fill(-1);\n for (const channel of animation.channels) {\n const node = channel.target.node;\n if (node === undefined) continue;\n const bone = nodeToBone.get(node);\n if (bone === undefined) continue;\n const sampler = animation.samplers[channel.sampler];\n if (!sampler) throw new Error(`Animation channel references missing sampler ${channel.sampler}`);\n const slot = channel.target.path === 'translation' ? translationOf\n : channel.target.path === 'rotation' ? rotationOf\n : channel.target.path === 'scale' ? scaleOf\n : null; // 'weights' ignored - no morph targets here\n if (slot === null) continue;\n if (slot[bone] >= 0) {\n throw new Error(`Bone ${bone} (\"${boneNames[bone]}\") has two ${channel.target.path} channels`);\n }\n slot[bone] = channel.sampler;\n }\n\n // A rotation channel is mandatory; translation and scale are not. The mask is\n // filled in below, once each channel has been decoded and can be asked\n // whether it varies - absence is only one of the two ways a bone ends up\n // inheriting its rest translation.\n const translationMask = new Uint8Array(numBones);\n let restBones = 0;\n for (let bone = 0; bone < numBones; bone++) {\n if (rotationOf[bone] < 0) {\n throw new Error(`Bone ${bone} (\"${boneNames[bone]}\") is missing a rotation channel`);\n }\n }\n\n // The main timeline is the longest sampler input. Constant channels ride a\n // one-key timeline of their own; anything else would make frame `f` mean\n // different instants for different bones.\n let timeAccessor = -1;\n let numFrames = 0;\n for (const sampler of animation.samplers) {\n const count = json.accessors?.[sampler.input]?.count ?? 0;\n if (count > numFrames) {\n numFrames = count;\n timeAccessor = sampler.input;\n }\n }\n if (timeAccessor < 0 || numFrames === 0) throw new Error('Animation has no keyframes');\n\n const times = readFloatAccessor(json, buffer, binOffset, timeAccessor, 'SCALAR');\n const span = numFrames > 1 ? times[numFrames - 1] - times[0] : 0;\n const frameRate = span > 0 ? (numFrames - 1) / span : 30;\n\n // Playback is frame-indexed: key `i` must BE frame `i`. A non-uniform grid\n // would still load, but every frame after the first irregular key would sit\n // at the wrong instant, so refuse it instead.\n if (numFrames > 2 && span > 0) {\n const step = span / (numFrames - 1);\n let worst = 0;\n for (let i = 0; i < numFrames; i++) {\n worst = Math.max(worst, Math.abs(times[i] - (times[0] + i * step)));\n }\n if (worst > step * 0.5) {\n throw new Error(\n `Animation timestamps are not on a uniform grid (off by up to ${worst.toFixed(4)}s `\n + `against a ${step.toFixed(4)}s step); resampling is not supported`,\n );\n }\n }\n\n // Parent-local TRS per bone; every bone shares one frames array.\n const frames = new Float32Array(numFrames);\n for (let frame = 0; frame < numFrames; frame++) frames[frame] = frame;\n const keyframes = new Map<number, SkeletalKeyframeEntry>();\n const scratch = new Float32Array(4);\n\n for (let bone = 0; bone < numBones; bone++) {\n const name = boneNames[bone];\n const rot = decodeChannel(\n json, buffer, binOffset, animation.samplers[rotationOf[bone]], 'VEC4',\n `Bone ${bone} (\"${name}\") rotation`, timeAccessor, numFrames,\n );\n const trans = translationOf[bone] >= 0\n ? decodeChannel(\n json, buffer, binOffset, animation.samplers[translationOf[bone]], 'VEC3',\n `Bone ${bone} (\"${name}\") translation`, timeAccessor, numFrames,\n )\n : null;\n let scaleCh = scaleOf[bone] >= 0\n ? decodeChannel(\n json, buffer, binOffset, animation.samplers[scaleOf[bone]], 'VEC3',\n `Bone ${bone} (\"${name}\") scale`, timeAccessor, numFrames,\n )\n : null;\n\n // Here is the whole decision. A channel that varies drives the bone; a\n // channel that holds still is stating the source rig's rest, which the\n // target character's own rest must override.\n if (trans !== null && !isConstantChannel(trans, CONSTANT_TRANSLATION_EPS)) {\n translationMask[bone] = 1;\n } else {\n restBones++;\n }\n // A constant scale resolves to identity right here rather than to a mask:\n // every rig the engine builds rests at scale 1,1,1 (see `Skeleton.restPose`),\n // so there is no per-character value to defer to and nothing to carry.\n if (scaleCh !== null && isConstantChannel(scaleCh, CONSTANT_SCALE_EPS)) scaleCh = null;\n\n // Every key needs a translation. A present channel is used verbatim, as a\n // conformant glTF reader would, and `translationMask` overrides it at\n // playback. Without one (files written before 2026-08) the node's rest\n // translation stands in.\n const rest = nodes[boneToNode[bone]].translation;\n const restX = rest?.[0] ?? 0;\n const restY = rest?.[1] ?? 0;\n const restZ = rest?.[2] ?? 0;\n\n const positions = new Float32Array(numFrames * 3);\n const rotations = new Float32Array(numFrames * 4);\n const scales = new Float32Array(numFrames * 3).fill(1);\n for (let frame = 0; frame < numFrames; frame++) {\n const t = times[frame];\n const o3 = frame * 3;\n if (!trans) {\n positions[o3] = restX; positions[o3 + 1] = restY; positions[o3 + 2] = restZ;\n } else if (trans.aligned) {\n const i = (frame * trans.stride + trans.offset) * trans.comps;\n positions[o3] = trans.values[i]; positions[o3 + 1] = trans.values[i + 1]; positions[o3 + 2] = trans.values[i + 2];\n } else {\n evalChannel(trans, t, scratch);\n positions[o3] = scratch[0]; positions[o3 + 1] = scratch[1]; positions[o3 + 2] = scratch[2];\n }\n\n if (scaleCh?.aligned) {\n const i = (frame * scaleCh.stride + scaleCh.offset) * scaleCh.comps;\n scales[o3] = scaleCh.values[i]; scales[o3 + 1] = scaleCh.values[i + 1]; scales[o3 + 2] = scaleCh.values[i + 2];\n } else if (scaleCh) {\n evalChannel(scaleCh, t, scratch);\n scales[o3] = scratch[0]; scales[o3 + 1] = scratch[1]; scales[o3 + 2] = scratch[2];\n }\n\n // glTF stores quaternions xyzw, the same order as `Quat`.\n // Dequantized int16 and interpolated values sit slightly off the unit\n // sphere - renormalize. A no-op for an already-unit FLOAT quaternion.\n let x: number, y: number, z: number, w: number;\n if (rot.aligned) {\n const j = (frame * rot.stride + rot.offset) * rot.comps;\n x = rot.values[j]; y = rot.values[j + 1]; z = rot.values[j + 2]; w = rot.values[j + 3];\n } else {\n evalChannel(rot, t, scratch);\n x = scratch[0]; y = scratch[1]; z = scratch[2]; w = scratch[3];\n }\n const len = Math.sqrt(x * x + y * y + z * z + w * w);\n const o4 = frame * 4;\n if (len === 0) {\n rotations[o4 + 3] = 1;\n } else {\n rotations[o4] = x / len; rotations[o4 + 1] = y / len; rotations[o4 + 2] = z / len; rotations[o4 + 3] = w / len;\n }\n }\n keyframes.set(bone, { frames, positions, rotations, scales });\n }\n\n return {\n keyframes,\n numFrames,\n numBones,\n boneNames,\n // Every bone genuinely translates: say nothing, which is what `.anim` means\n // and what every consumer already treats as \"drive them all\".\n translationMask: restBones === 0 ? undefined : translationMask,\n frameRate,\n animationName: animation.name ?? '<unnamed>',\n };\n}\n", "/** Host-supplied transport, e.g. for renewing expiring URLs before a download. */\nexport type AssetFetch = (url: string, init?: RequestInit) => Promise<Response>;\n\n// The page's own fetch, once `installFetchInterceptor` has replaced the global\n// with a wrapper that routes back into the cache. Read at call time, not\n// captured at import, so a test stub of `fetch` still applies.\nlet pageFetch: typeof fetch | null = null;\nlet transport: AssetFetch = (url, init) => (pageFetch ?? globalThis.fetch)(url, init);\n\n/**\n * Replace the network transport under the asset cache. A transport that calls\n * the global `fetch` while `installFetchInterceptor` is active reaches the\n * interceptor again and recurses: capture `fetch` before installing it.\n */\nexport function setAssetFetch(fetcher: AssetFetch): void { transport = fetcher; }\n\n/** @internal Called by the fetch interceptor before it replaces `globalThis.fetch`. */\nexport function setPageFetch(fetcher: typeof fetch | null): void { pageFetch = fetcher; }\n\nexport function fetchAsset(url: string, init?: RequestInit): Promise<Response> {\n return transport(url, init);\n}\n", "import { fetchAsset, setPageFetch } from './asset-fetch';\n\nconst CACHE_NAME = 'viggle-asset-cache';\n\n// A host-installed fetch for asset bytes (`setBinFetch`), used in place of the\n// engine's own Cache API layer when set.\nlet _hostFetch: ((url: string) => Promise<Response>) | null = null;\nconst MAX_TTL_MS = 60 * 60 * 1000;\nconst EXPIRES_HEADER = 'X-Viggle-Cache-Expires';\n\n// Extensions that must never be persisted (bypass all caching). Empty now that\n// `.ply` character/map splats are cached like `.spz` - kept as the hook for any\n// future no-store asset type.\nconst NO_STORE_EXTENSIONS = new Set<string>([]);\n\n// Extensions whose assets share one cache entry across rotating CDN URLs (e.g.\n// Cloudflare query-string cache busters): for these, a signed URL's query\n// string is dropped from the cache key, so the same bytes re-signed under a\n// fresh token still hit. Anything else is cached under its full URL including\n// query string.\nconst PATH_NORMALIZED_EXTENSIONS = new Set([\n '.anim',\n '.bin',\n '.glb',\n '.gltf',\n '.jpg',\n '.jpeg',\n '.mp3',\n '.ogg',\n '.opus',\n '.ply',\n '.png',\n '.spz',\n // VIGGCHAR v1 character bundles. Without this a signed `.vsplat` URL is\n // keyed on its rotating token, so the Cache API never hits AND (see the\n // store gate below) the bytes are never persisted at all - every reload\n // re-downloads a multi-MB character.\n '.vsplat',\n '.webp',\n]);\n\nlet cachePromise: Promise<Cache | null> | null = null;\n\n// Expiry stamp per cache key, filled by `indexAssetCache`. Once it is loaded,\n// a key missing from it is known to be uncached, so `cachedFetch` can start\n// the download at once: the Cache API lookup needs the main thread to answer,\n// and a viewer opening keeps it busy for 100 ms or more.\nlet cacheIndex: Map<string, number> | null = null;\nlet buildingIndex: Map<string, number> | null = null;\n\nfunction indexKey(key: string): string {\n try {\n return new URL(key, globalThis.location?.href).href;\n } catch {\n return key;\n }\n}\n\nfunction noteStored(key: string, expiry: number): void {\n cacheIndex?.set(indexKey(key), expiry);\n buildingIndex?.set(indexKey(key), expiry);\n}\n\nfunction noteDeleted(key: string): void {\n cacheIndex?.delete(indexKey(key));\n buildingIndex?.delete(indexKey(key));\n}\n\nfunction knownUncached(key: string): boolean {\n if (!cacheIndex) return false;\n const expiry = cacheIndex.get(indexKey(key));\n return !expiry || Date.now() >= expiry;\n}\n\nfunction getCache(): Promise<Cache | null> {\n if (!cachePromise) {\n cachePromise = (typeof caches !== 'undefined')\n ? caches.open(CACHE_NAME).catch(() => null)\n : Promise.resolve(null);\n }\n return cachePromise;\n}\n\nfunction getPathname(url: string): string {\n return (() => {\n try {\n return new URL(url, globalThis.location?.href).pathname;\n } catch {\n return url.split(/[?#]/, 1)[0] ?? url;\n }\n })().toLowerCase();\n}\n\nfunction hasExtension(url: string, extensions: Set<string>): boolean {\n const pathname = getPathname(url);\n for (const ext of extensions) {\n if (pathname.endsWith(ext)) return true;\n }\n return false;\n}\n\nfunction isNoStoreAsset(url: string): boolean {\n return hasExtension(url, NO_STORE_EXTENSIONS);\n}\n\n/** Detect signed CDN URLs that rotate tokens (Cloudflare ?verify=, AWS S3 ?X-Amz-, Google Cloud CDN ?Signature=). */\nfunction hasSignedQueryParams(url: string): boolean {\n const q = url.indexOf('?');\n if (q === -1) return false;\n const query = url.slice(q + 1).toLowerCase();\n return query.includes('verify=') || query.includes('x-amz-')\n || (query.includes('keyname=') && query.includes('signature='));\n}\n\nfunction cacheKeyFor(url: string): string {\n const pathname = getPathname(url);\n // Only strip query params for signed CDN URLs with rotating tokens\n const isSignedUrl = hasSignedQueryParams(url);\n const normalize = isSignedUrl && hasExtension(pathname, PATH_NORMALIZED_EXTENSIONS);\n if (normalize && typeof globalThis.location !== 'undefined') {\n return new URL(`/__viggle_asset_cache__${pathname}`, globalThis.location.href).href;\n }\n return url;\n}\n\nfunction stripCacheControlHeaders(init?: RequestInit): Headers {\n const headers = new Headers(init?.headers);\n headers.delete('If-None-Match');\n headers.delete('If-Modified-Since');\n headers.set('Cache-Control', 'no-store');\n headers.set('Pragma', 'no-cache');\n return headers;\n}\n\n/**\n * Absolute ms timestamp when a freshly-fetched response should expire.\n * Honors positive `Cache-Control: max-age=N` and `Expires:` values from the\n * server, capped at 1 hour. Returns 0 only for `no-store` (the server\n * explicitly forbids persisting the bytes anywhere) - never persisted.\n *\n * `no-cache` is deliberately NOT treated the same as `no-store`: per HTTP\n * semantics it means \"store this, but revalidate with the server before\n * reusing it\", not \"don't store it\". This loader is an app-owned asset\n * byte-cache, not an HTTP-spec-compliant shared cache, and every asset it\n * handles is immutable (a given URL's bytes never change), so revalidation\n * has no purpose here - the default 1-hour TTL is safe to apply instead of\n * refusing to cache at all. This matters in practice: dev servers (e.g.\n * Vite's static middleware) commonly send `Cache-Control: no-cache` on\n * every asset, which - before this fix - meant a cache-presence check could\n * never return true and any \"reload finer detail once cached\" flow was\n * permanently a no-op in local dev, regardless of how many times the same\n * URL was fetched.\n *\n * CDN asset URLs sometimes send `private,max-age=0`; those are also safe to\n * keep in our app-owned Cache API store for the default TTL, and already\n * fall through to it below (ageMs=0 skips the max-age branch).\n */\nfunction computeExpiryMs(res: Response): number {\n const cc = res.headers.get('cache-control') ?? '';\n const lower = cc.toLowerCase();\n if (lower.includes('no-store')) return 0;\n\n const maxAgeMatch = /(?:^|,)\\s*max-age\\s*=\\s*(\\d+)/i.exec(cc);\n if (maxAgeMatch) {\n const ageMs = Number(maxAgeMatch[1]) * 1000;\n if (ageMs > 0) return Date.now() + Math.min(ageMs, MAX_TTL_MS);\n }\n\n const expires = res.headers.get('expires');\n if (expires) {\n const t = Date.parse(expires);\n if (Number.isFinite(t)) {\n const ttl = t - Date.now();\n if (ttl <= 0) return 0;\n return Date.now() + Math.min(ttl, MAX_TTL_MS);\n }\n }\n\n return Date.now() + MAX_TTL_MS;\n}\n\n/** A buffered response, re-issuable: a `Response` body reads once, and these\n * bytes are handed to the store, to the caller that asked for them, and to\n * anyone who joined the download late. */\ntype Reissue = () => Response;\n\nasync function stampWithExpiry(res: Response, expiry: number): Promise<Reissue> {\n const headers = new Headers(res.headers);\n headers.set(EXPIRES_HEADER, String(expiry));\n const body = await res.arrayBuffer();\n return () => new Response(body, {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n}\n\n/**\n * Downloads whose bytes have not reached the store yet, keyed as the store is.\n *\n * WHY: an asset is sometimes asked for BEFORE the code that decodes it asks.\n * The scene viewer starts a capture downloading the moment a scene is picked\n * and hands the engine its url only once the panel has finished sliding, so\n * the decode lands outside the entrance animation (`useEnvironmentSlot`).\n * Without this the second ask would miss - `cache.put` cannot land until the\n * whole body has been buffered, which on a cold 8.6 MB capture is over a\n * second - and start a SECOND download of the same file. Signed CDN URLs\n * carry `private,max-age=0`, so the browser's own HTTP cache would not save\n * it either.\n *\n * Not a general request cache: an entry lives only from the moment the\n * request goes out until the store has the bytes, after which `cache.match`\n * answers. The first caller's own `Response` is left streaming, untouched;\n * only a joiner is handed the buffered copy. That buffer is the one\n * `stampWithExpiry` has to make for the store anyway, so sharing it costs no\n * extra read of the body.\n *\n * An entry REJECTS when the response turns out not to be storable (not ok, or\n * `no-store`), which is a joiner's signal to go and ask for itself rather than\n * inherit a failure it cannot see into.\n */\nconst inflight = new Map<string, Promise<{ reissue: Reissue; expiry: number }>>();\n\n/** Start a download and publish it for anyone who asks for the same object\n * while it is still coming down. Returns the first caller's own response. */\nfunction shareDownload(cacheKey: string, started: Promise<Response>): Promise<Response> {\n const buffering = started.then(async (res) => {\n const expiry = res.ok ? computeExpiryMs(res) : 0;\n if (expiry <= 0) throw new Error('[bin-cache] response is not storable');\n // Cloned while the body is still untouched. This callback is registered\n // before the first caller awaits the same promise, so it runs first.\n return { reissue: await stampWithExpiry(res.clone(), expiry), expiry };\n });\n inflight.set(cacheKey, buffering);\n // Nothing to share and nothing to store: drop the entry rather than leave a\n // rejected promise every later ask has to catch.\n buffering.catch(() => forgetShared(cacheKey, buffering));\n return started;\n}\n\n/** Store lookups under way. Until the index can answer for a key, a second ask\n * in this window would miss too and start its own download; it waits instead,\n * then joins the one the miss starts. */\nconst looking = new Map<string, Promise<unknown>>();\n\nfunction forgetShared(cacheKey: string, entry: Promise<unknown>): void {\n if (inflight.get(cacheKey) === entry) inflight.delete(cacheKey);\n}\n\n/** Write a shared download's bytes to the store, then stop sharing them. */\nfunction storeShared(cache: Cache | null, cacheKey: string): void {\n const entry = inflight.get(cacheKey);\n if (!entry) return;\n // No store to hand them to (no Cache API): the sharing window closes with\n // this call instead of with the write, so the buffer is not held for the\n // life of the page.\n if (!cache) {\n forgetShared(cacheKey, entry);\n return;\n }\n entry\n .then(({ reissue, expiry }) =>\n cache.put(cacheKey, reissue()).then(() => noteStored(cacheKey, expiry)))\n .catch(() => {})\n .finally(() => forgetShared(cacheKey, entry));\n}\n\nfunction expiryOf(cached: Response): number {\n return Number(cached.headers.get(EXPIRES_HEADER) ?? 0);\n}\n\nfunction isExpired(cached: Response): boolean {\n const stamp = expiryOf(cached);\n if (!stamp) return true;\n return Date.now() >= stamp;\n}\n\n/**\n * Fetch through a persistent Cache API layer with a 1-hour TTL.\n * - Assets with cacheable extensions (.bin, .vsplat, .anim, .ply, \u2026) \u2192\n * cached in Cache API\n * - Signed URLs (?verify=, ?X-Amz-, ?Signature=) \u2192 query stripped for cache key\n * - No-store assets \u2192 never persisted. `NO_STORE_EXTENSIONS` is empty\n * today, so nothing takes this branch; see its declaration.\n * Server `Cache-Control: max-age` and `Expires` headers are honored as a cap\n * when they provide a positive TTL.\n * On network error, a stale cached copy is returned in preference to throwing.\n * After {@link indexAssetCache}, an asset known to be uncached skips the\n * lookup and its download starts synchronously.\n */\nasync function engineCachedFetch(url: string, init?: RequestInit): Promise<Response> {\n // No-store assets bypass all caching\n if (isNoStoreAsset(url)) {\n return fetchAsset(url, {\n ...init,\n cache: 'no-store',\n headers: stripCacheControlHeaders(init),\n });\n }\n\n // Only cache assets with known cacheable extensions\n if (!hasExtension(url, PATH_NORMALIZED_EXTENSIONS)) {\n return fetchAsset(url, init);\n }\n\n // Cache API with query-stripped key for signed URLs, full URL otherwise\n const cacheKey = cacheKeyFor(url);\n\n // Already coming down for someone else - take their bytes rather than ask\n // the network for the same object twice. Checked synchronously, before any\n // await, so two asks in the same turn share too. See `inflight`.\n const joined = inflight.get(cacheKey);\n if (joined) {\n try {\n return (await joined).reissue();\n } catch {\n // Not storable, so there are no bytes to inherit: ask for ourselves.\n }\n }\n\n const early = knownUncached(cacheKey) ? shareDownload(cacheKey, fetchAsset(url, init)) : null;\n const cache = await getCache();\n\n if (!cache) {\n if (early) storeShared(null, cacheKey);\n return early ?? fetchAsset(url, init);\n }\n\n let cached: Response | undefined;\n // Lets a waiting ask go once this one's hit or download is known.\n let release = () => {};\n if (!early) {\n // After the await above, so an ask from the same turn sees the first one's.\n const lookup = looking.get(cacheKey);\n if (lookup) {\n await lookup;\n return cachedFetch(url, init);\n }\n let done!: () => void;\n const settled = new Promise<void>((resolve) => { done = resolve; });\n looking.set(cacheKey, settled);\n release = () => {\n if (looking.get(cacheKey) === settled) looking.delete(cacheKey);\n done();\n };\n try {\n cached = await cache.match(cacheKey);\n } catch (err) {\n release();\n throw err;\n }\n }\n if (cached && !isExpired(cached)) {\n release();\n return cached;\n }\n\n let res: Response;\n try {\n const download = early ?? shareDownload(cacheKey, fetchAsset(url, init));\n release();\n res = await download;\n } catch (err) {\n const stale = cached ?? await cache.match(cacheKey);\n if (stale) return stale;\n throw err;\n }\n\n if (res.ok) {\n if (computeExpiryMs(res) > 0) {\n storeShared(cache, cacheKey);\n } else if (cached) {\n cache.delete(cacheKey).catch(() => {});\n noteDeleted(cacheKey);\n }\n }\n return res;\n}\n\nlet indexing: Promise<number> | null = null;\n\n/**\n * Delete expired entries and index the rest, so {@link cachedFetch} can start\n * an uncached download without waiting on a Cache API lookup. Call once when\n * the page is idle, before the first load; later calls share the first run.\n * Resolves to the number of entries removed.\n */\nfunction indexAssetCache(): Promise<number> {\n if (!indexing) {\n indexing = (async () => {\n const cache = await getCache();\n if (!cache) return 0;\n const index = new Map<string, number>();\n buildingIndex = index;\n let removed = 0;\n try {\n await Promise.all((await cache.keys()).map(async (req) => {\n const res = await cache.match(req);\n if (!res) return;\n if (isExpired(res)) {\n if (await cache.delete(req)) removed++;\n } else if (!index.has(req.url)) {\n index.set(req.url, expiryOf(res));\n }\n }));\n cacheIndex = index;\n } finally {\n buildingIndex = null;\n }\n return removed;\n })().catch(() => 0);\n }\n return indexing;\n}\n\n/**\n * The fetch the engine downloads asset bytes with (`.bin` / `.vsplat`\n * bundles, `.spz` / `.ply` splats, VFX sprite sheets). By default it is the\n * engine's persistent Cache API layer (`engineCachedFetch` above); a host that\n * installs its own with {@link setBinFetch} gets that instead.\n */\nfunction cachedFetch(url: string, init?: RequestInit): Promise<Response> {\n return _hostFetch && !init ? _hostFetch(url) : engineCachedFetch(url, init);\n}\n\n/**\n * Install the fetch the engine uses for asset bytes, in place of its own\n * Cache API layer: for a host with its own caching stack. Call once at boot, before any asset loads. Pass `null`\n * to go back to the engine's own.\n */\nfunction setBinFetch(fetchImpl: ((url: string) => Promise<Response>) | null): void {\n _hostFetch = fetchImpl;\n}\n\n/**\n * Route every cacheable asset request made with `fetch` or `XMLHttpRequest`,\n * including PlayCanvas's own (LOD octree chunks, textures, GLBs), through the\n * persistent Cache API layer. Opt-in and global: it replaces\n * `globalThis.fetch` and patches `XMLHttpRequest`. Requests for other URLs\n * pass through untouched. A routed request keeps its headers, credentials\n * mode and abort signal. Call once at boot; safe to call again.\n * {@link uninstallFetchInterceptor} puts both back.\n */\nfunction installFetchInterceptor(): void {\n installFetchHook();\n installXHRHook();\n}\n\n/** Undo {@link installFetchInterceptor}: restore `fetch` and `XMLHttpRequest`. No-op when not installed. */\nfunction uninstallFetchInterceptor(): void {\n _uninstallFetch?.();\n _uninstallFetch = null;\n _uninstallXHR?.();\n _uninstallXHR = null;\n}\n\nlet _uninstallFetch: (() => void) | null = null;\nlet _uninstallXHR: (() => void) | null = null;\n\n/** The parts of a request a cached fetch passes on to the network. */\nfunction requestInitOf(request: Request, init?: RequestInit): RequestInit {\n return {\n headers: request.headers,\n credentials: request.credentials,\n cache: request.cache,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n integrity: request.integrity,\n signal: request.signal,\n ...init,\n };\n}\n\n/**\n * A cached fetch that still answers to `init.signal`, which a cache hit would\n * not otherwise read. Not started at all when the signal is already aborted,\n * so no request is left to reject unheard.\n */\nfunction abortable(start: () => Promise<Response>, signal: AbortSignal | null | undefined): Promise<Response> {\n if (!signal) return start();\n if (signal.aborted) return Promise.reject(signal.reason ?? new DOMException('The operation was aborted.', 'AbortError'));\n const response = start();\n return new Promise((resolve, reject) => {\n const onAbort = () => reject(signal.reason ?? new DOMException('The operation was aborted.', 'AbortError'));\n signal.addEventListener('abort', onAbort, { once: true });\n response.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));\n });\n}\n\nfunction installFetchHook(): void {\n const current = globalThis.fetch as typeof fetch & { __viggleCached?: boolean };\n if (!current || current.__viggleCached) return;\n const realFetch = current.bind(globalThis);\n // The default transport must keep reaching the network, not this wrapper.\n setPageFetch(realFetch);\n let active = true;\n const intercepted = ((input: RequestInfo | URL, init?: RequestInit) => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n if (active && method === 'GET' && hasExtension(url, PATH_NORMALIZED_EXTENSIONS) && !isNoStoreAsset(url)) {\n const options = input instanceof Request ? requestInitOf(input, init) : init;\n return abortable(() => engineCachedFetch(url, options), options?.signal);\n }\n return realFetch(input, init);\n }) as typeof fetch & { __viggleCached?: boolean };\n intercepted.__viggleCached = true;\n globalThis.fetch = intercepted;\n _uninstallFetch = () => {\n // A wrapper installed over this one still calls it, so it cannot be taken\n // out of the chain: it passes everything straight through instead.\n // Otherwise the transport, back on the global `fetch`, would reach it\n // again and recurse.\n active = false;\n if (globalThis.fetch === intercepted) globalThis.fetch = current;\n setPageFetch(null);\n };\n}\n\nfunction installXHRHook(): void {\n const XHR = globalThis.XMLHttpRequest as (typeof XMLHttpRequest & { __viggleCached?: boolean }) | undefined;\n if (!XHR || XHR.__viggleCached) return;\n type Tagged = XMLHttpRequest & {\n __viggleUrl?: string;\n __viggleMethod?: string;\n __viggleHeaders?: [string, string][];\n __viggleAborted?: boolean;\n /** Sent through the cache and not finished: the native request never went out. */\n __vigglePending?: boolean;\n };\n let active = true;\n /** Properties a routed request shadows on its instance; `open` clears them. */\n const SHADOWED = ['readyState', 'status', 'statusText', 'response', 'responseText'] as const;\n const shadow = (xhr: XMLHttpRequest, prop: string, value: unknown) =>\n Object.defineProperty(xhr, prop, { get: () => value, configurable: true });\n const unshadow = (xhr: XMLHttpRequest) => {\n for (const prop of SHADOWED) delete (xhr as unknown as Record<string, unknown>)[prop];\n };\n const proto = XHR.prototype;\n const origOpen = proto.open as (this: XMLHttpRequest, ...args: unknown[]) => void;\n const origSend = proto.send as (this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null) => void;\n const origSetRequestHeader = proto.setRequestHeader;\n const origAbort = proto.abort;\n\n const open = function (this: Tagged, method: string, url: string | URL, ...rest: unknown[]) {\n // A reused request reports its own state again, not the last routed one's.\n unshadow(this);\n this.__viggleUrl = typeof url === 'string' ? url : url.toString();\n this.__viggleMethod = method;\n this.__viggleHeaders = [];\n this.__viggleAborted = false;\n this.__vigglePending = false;\n return origOpen.apply(this, [method, url, ...rest]);\n } as typeof proto.open;\n proto.open = open;\n\n const setRequestHeader = function (this: Tagged, name: string, value: string) {\n this.__viggleHeaders?.push([name, value]);\n return origSetRequestHeader.call(this, name, value);\n };\n proto.setRequestHeader = setRequestHeader;\n\n const abort = function (this: Tagged) {\n this.__viggleAborted = true;\n if (!this.__vigglePending) return origAbort.call(this);\n // The native request was never sent, so its own abort is silent: report\n // what aborting a real one does - readystatechange at DONE, `abort`,\n // `loadend` - and end UNSENT.\n this.__vigglePending = false;\n origAbort.call(this);\n shadow(this, 'readyState', 4);\n shadow(this, 'status', 0);\n shadow(this, 'statusText', '');\n shadow(this, 'response', this.responseType === '' || this.responseType === 'text' ? '' : null);\n this.dispatchEvent(new Event('readystatechange'));\n this.dispatchEvent(new ProgressEvent('abort'));\n this.dispatchEvent(new ProgressEvent('loadend'));\n shadow(this, 'readyState', 0);\n };\n proto.abort = abort;\n\n const send = function (this: Tagged, body?: Document | XMLHttpRequestBodyInit | null) {\n const url = this.__viggleUrl ?? '';\n const method = (this.__viggleMethod ?? 'GET').toUpperCase();\n if (!active || method !== 'GET' || !hasExtension(url, PATH_NORMALIZED_EXTENSIONS) || isNoStoreAsset(url)) {\n return origSend.call(this, body);\n }\n const xhr = this;\n const responseType = xhr.responseType;\n xhr.__vigglePending = true;\n xhr.dispatchEvent(new ProgressEvent('loadstart'));\n engineCachedFetch(url, {\n headers: xhr.__viggleHeaders,\n credentials: xhr.withCredentials ? 'include' : 'same-origin',\n })\n .then((res) => {\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n return res.arrayBuffer();\n })\n .then((buf) => {\n // An aborted request already told its listeners so; say nothing more.\n if (xhr.__viggleAborted) return;\n xhr.__vigglePending = false;\n // Shadow the prototype getters on this instance, so PlayCanvas reads\n // a finished 200 with the cached bytes.\n const def = (prop: string, value: unknown) => shadow(xhr, prop, value);\n def('readyState', 4);\n def('status', 200);\n def('statusText', 'OK');\n def('response',\n responseType === 'blob' ? new Blob([buf])\n : responseType === 'text' || responseType === '' ? new TextDecoder().decode(buf)\n : responseType === 'json' ? JSON.parse(new TextDecoder().decode(buf))\n : buf);\n if (responseType === 'text' || responseType === '') def('responseText', new TextDecoder().decode(buf));\n const size = buf.byteLength;\n xhr.dispatchEvent(new Event('readystatechange'));\n xhr.dispatchEvent(new ProgressEvent('load', { loaded: size, total: size, lengthComputable: true }));\n xhr.dispatchEvent(new ProgressEvent('loadend', { loaded: size, total: size, lengthComputable: true }));\n })\n .catch(() => {\n if (xhr.__viggleAborted) return;\n // Over to the network, which now reports for itself.\n xhr.__vigglePending = false;\n origSend.call(xhr, body);\n });\n } as typeof proto.send;\n proto.send = send;\n\n XHR.__viggleCached = true;\n _uninstallXHR = () => {\n // As with fetch: a method patched again over this one keeps calling it,\n // so it stays in place, passing through.\n active = false;\n if (proto.open === open) proto.open = origOpen as typeof proto.open;\n if (proto.send === send) proto.send = origSend as typeof proto.send;\n if (proto.setRequestHeader === setRequestHeader) proto.setRequestHeader = origSetRequestHeader;\n if (proto.abort === abort) proto.abort = origAbort;\n XHR.__viggleCached = false;\n };\n}\n\n/**\n * Whether a URL is in the persistent cache (and not expired), without\n * fetching it. False for URLs the cache never stores, or with no Cache API.\n */\nasync function isCached(url: string): Promise<boolean> {\n if (isNoStoreAsset(url) || !hasExtension(url, PATH_NORMALIZED_EXTENSIONS)) return false;\n const cache = await getCache();\n if (!cache) return false;\n const cached = await cache.match(cacheKeyFor(url));\n return cached !== undefined && !isExpired(cached);\n}\n\n/**\n * Former name of {@link indexAssetCache}, kept for compatibility: it\n * still deletes expired entries and resolves to how many it removed.\n *\n * @deprecated Use {@link indexAssetCache}.\n */\nconst evictExpired = indexAssetCache;\n\nexport {\n cacheKeyFor, cachedFetch, evictExpired, indexAssetCache, installFetchInterceptor, isCached, setBinFetch,\n uninstallFetchInterceptor,\n};\n", "import { convertSkeletalAnimation } from './anim/animation-conversion';\nimport { CONSTANT_TRANSLATION_EPS, parseArmatureGlbAnimation } from './loader/animation/animation-glb';\nimport { cachedFetch } from './loader/shared/bin-cache';\nimport type { SplatEngine } from './engine';\n\n/**\n * A frame-aligned event attached to an {@link Animation}. Events are fired by\n * {@link AnimationPlayer} as `animTime` crosses each `frame`, dispatched\n * through {@link Armature.onAnimEvent} / {@link Character.onAnimEvent}.\n *\n * The engine treats `name` and `payload` as opaque - games define their own\n * vocabulary (e.g. `'footstep'`, `'hit-impact'`, `'screen-shake'`) and route\n * via the listener.\n *\n * @group Characters & Animation\n */\nexport interface AnimationEvent {\n /** Frame index (integer, `0 .. numFrames-1`). */\n frame: number;\n /** Game-defined event name. */\n name: string;\n /** Optional game-defined payload, opaque to the engine. */\n payload?: unknown;\n}\n\n/**\n * How {@link Animation.load} reads a clip, for clips converted from FBX.\n *\n * - `referenceFrameMode: 'first-frame'`: frame 0 is an import reference pose,\n * not part of the motion. Each bone plays only its delta from frame 0, on\n * top of the target rig's rest pose (or `referenceBaseAnimation`'s first\n * frame when given, e.g. an idle clip). Implies `rigidBones`.\n * - `rigidBones`: strip shear and non-uniform scale from every bone matrix\n * before taking its rotation, and keep bone scale at 1. FBX conversion can\n * leave both in the 3x3 basis; splat skinning expects rigid bones.\n *\n * All default off: a clip loaded without options plays exactly as before.\n */\nexport interface AnimationLoadOptions {\n referenceFrameMode?: 'first-frame';\n referenceBaseAnimation?: Animation;\n rigidBones?: boolean;\n}\n\n/** Whether a load asks for a conversion the shared converted-clip cache can't serve. */\nfunction hasConversionOptions(options: AnimationLoadOptions): boolean {\n return !!(options.referenceFrameMode || options.referenceBaseAnimation || options.rigidBones);\n}\n\n/**\n * One bone's keys inside a {@link SkeletalStore}, ascending by frame. Flat\n * arrays because a clip can hold ~135k keys. Read-only: cached copies of a\n * clip share them.\n * @internal\n */\nexport interface SkeletalKeyframeEntry {\n /** Frame per key. `length` is the key count. */\n frames: Float32Array;\n /** `[x,y,z]` per key. */\n positions: Float32Array;\n /** `[x,y,z,w]` per key. */\n rotations: Float32Array;\n /** `[x,y,z]` per key. */\n scales: Float32Array;\n}\n\n/**\n * Per-bone keys of an {@link Animation}: read from a GLB, or converted from\n * `.anim` matrices by {@link convertSkeletalAnimation}. Playback reads these,\n * not `data`.\n *\n * @internal\n */\nexport interface SkeletalStore {\n keyframes: Map<number, SkeletalKeyframeEntry>;\n manualBones: Set<number>;\n source: string;\n}\n\n/** Private converted source; never registered or used as a playback-cache key. */\ntype ConvertedSource = Pick<Animation,\n 'numFrames' | 'numBones' | 'keyframeFrames' | 'translationMask' | 'events' | 'skeletalStore' | 'name' | 'frameRate'>;\n\n/**\n * Expand Float16 (IEEE 754 half-precision) stored as Uint16 into Float32.\n */\nfunction float16ToFloat32(u16: Uint16Array): Float32Array {\n const out = new Float32Array(u16.length);\n for (let i = 0; i < u16.length; i++) {\n const h = u16[i];\n const sign = (h >>> 15) & 0x1;\n const exp = (h >>> 10) & 0x1f;\n const mant = h & 0x3ff;\n\n let val: number;\n if (exp === 0) {\n val = mant === 0 ? 0 : 5.960464477539063e-8 * mant;\n } else if (exp === 31) {\n val = mant === 0 ? Infinity : NaN;\n } else {\n val = Math.pow(2, exp - 15) * (1 + mant / 1024);\n }\n out[i] = sign ? -val : val;\n }\n return out;\n}\n\n/**\n * Reset the root bone (bone 0) to identity rotation in every frame of a\n * `.anim` matrix block, keeping its translation. Exported for tests.\n *\n * A `.anim` does not state a facing on its root: the engine reset the root's\n * rotation every frame until the rig clamp started keeping it (so a MetaHuman\n * GLB's constant 180\u00B0 root yaw could survive), and `.anim` clips were authored\n * against that reset. Some library clips carry a stray constant 90\u00B0 there\n * (`idle_relax`, `walk_forward_relax`, `idle2`) that used to be discarded, and\n * would now turn the character 90\u00B0. Dropping it here keeps every `.anim`\n * playing as it always has; a GLB clip's root yaw is untouched.\n */\nexport function clearAnimRootRotation(data: Float32Array, numFrames: number, numBones: number): void {\n if (numBones === 0 || data.length < numFrames * numBones * 16) return;\n for (let f = 0; f < numFrames; f++) {\n // Column-major 4x4; the upper 3x3 is the rotation (the root's scale is 1).\n const o = f * numBones * 16;\n data[o] = 1; data[o + 1] = 0; data[o + 2] = 0;\n data[o + 4] = 0; data[o + 5] = 1; data[o + 6] = 0;\n data[o + 8] = 0; data[o + 9] = 0; data[o + 10] = 1;\n }\n}\n\n/**\n * Element offset of the translation inside one packed column-major 4x4 bone\n * matrix: the layout `convertSkeletalAnimation` reads back with\n * `Mat4.getTranslation`, which is `data[12..14]`.\n */\nconst MATRIX_TRANSLATION = 12;\n\n/**\n * Derive {@link Animation.translationMask} from decoded `.anim` matrices.\n *\n * Same question the armature-GLB reader asks of its translation channels, asked\n * of the same quantity in its other storage form: does this bone's translation\n * *move* over the clip? A track that holds still is not motion, it is the source\n * rig stating its own bone length, and the target character's rest must win.\n *\n * A `.anim` frame carries a full local matrix per bone, so every bone always has\n * a translation and the \"channel absent\" half of the GLB test has no analogue\n * here, so constancy is the whole test. On our own clips it lands on the pelvis\n * alone for a body rig, and on the pelvis plus the translation-driven face for a\n * facial rig, without naming a single bone.\n *\n * Sparse clips are scanned on `keyframeFrames` only, matching the frames\n * `convertSkeletalAnimation` converts; the gaps between keyframes hold nothing\n * anyone reads.\n *\n * Degenerate clips fall out of the same rule rather than being special-cased: a\n * single-frame clip, or one where nothing translates at all, has no evidence of\n * motion anywhere, so every bone reads as a rest declaration and the whole mask\n * is `0`. The pose still plays, and every bone length comes from the character.\n * Returns `undefined` when every bone genuinely translates, which is the \"drive\n * them all\" the mask's absence has always meant.\n */\nfunction deriveTranslationMask(\n data: Float32Array,\n numFrames: number,\n numBones: number,\n keyframeFrames?: number[],\n): Uint8Array | undefined {\n const frames = keyframeFrames?.length\n ? keyframeFrames.filter((f) => f >= 0 && f < numFrames)\n : Array.from({ length: numFrames }, (_, i) => i);\n if (numBones === 0 || frames.length === 0) return undefined;\n // A pre-converted clip carries its poses in `skeletalStore` and an EMPTY data\n // array (`filterAnimationForArmature`). Reading it would compare `undefined`s,\n // every comparison would be false, and the clip would come back \"nothing\n // translates\" - freezing every bone at rest. No data means no evidence, which\n // is `undefined`, not an all-rest mask.\n if (data.length === 0) return undefined;\n\n const mask = new Uint8Array(numBones);\n let restBones = 0;\n for (let bone = 0; bone < numBones; bone++) {\n const first = (frames[0] * numBones + bone) * 16 + MATRIX_TRANSLATION;\n const x = data[first];\n const y = data[first + 1];\n const z = data[first + 2];\n let varies = false;\n for (let i = 1; i < frames.length; i++) {\n const o = (frames[i] * numBones + bone) * 16 + MATRIX_TRANSLATION;\n if (Math.abs(data[o] - x) > CONSTANT_TRANSLATION_EPS\n || Math.abs(data[o + 1] - y) > CONSTANT_TRANSLATION_EPS\n || Math.abs(data[o + 2] - z) > CONSTANT_TRANSLATION_EPS) {\n varies = true;\n break;\n }\n }\n if (varies) mask[bone] = 1;\n else restBones++;\n }\n return restBones === 0 ? undefined : mask;\n}\n\n/**\n * Parsed skeletal animation data.\n *\n * An `Animation` is the deserialized form of one clip, whatever it was\n * authored as: per-bone position, rotation and scale keys. Once registered on\n * an engine under a name, characters can play it via\n * {@link Character.playAnimation} / {@link Character.crossfadeTo}.\n *\n * The primary entry point is {@link Animation.loadGlb}, which fetches a\n * MetaHuman GLB, parses and registers it in one call. For custom fetch\n * pipelines, use {@link Animation.fromGlb} on an already-fetched\n * `ArrayBuffer`, then {@link Animation#register} to attach it to the engine.\n * The `.anim` container is still read, by {@link Animation.load} and\n * {@link Animation.parse}.\n *\n * @group Characters & Animation\n */\nexport class Animation {\n /** Column-major bone matrices (translation at `[12..14]`, the layout\n * `THREE.Matrix4.elements` uses), length `numFrames * numBones * 16`.\n * Empty for a GLB clip and once registered. */\n data: Float32Array;\n /** Number of animation frames. */\n numFrames: number;\n /** Number of bones per frame. */\n numBones: number;\n /** Optional sparse keyframe indices. If present, frames between keyframes are interpolated. */\n keyframeFrames?: number[];\n /**\n * Per bone: `1` if this clip drives the bone's translation, `0` if the bone\n * must keep the armature's own rest translation.\n *\n * A constant translation track is not motion - it is the source rig's bone\n * length. Applied to a character whose skeleton differs, it silently replaces\n * that character's bone lengths mid-clip while the bind pose keeps the\n * originals, which compresses the skin. Both readers are built with that in\n * mind and set a `0` for every bone whose translation holds still, judged from\n * the decoded data: {@link Animation.fromGlb} per channel, {@link Animation.parse}\n * across the per-frame matrices. `undefined` means every bone genuinely\n * translates, and every bone drives its own translation.\n *\n * Set once, at parse time, and never mutated afterwards. Playback caches\n * keyframes per `Animation` object, so a mask that could change would go stale\n * inside them. `filterAnimationForArmature` remaps rather than edits, onto a\n * new `Animation` that is its own cache key.\n *\n * Consumed by `buildArmatureKeyframes`, which zeroes the position delta for\n * masked bones so `fromRestRelative` yields `pose.position = restPosition`.\n */\n translationMask?: Uint8Array;\n /**\n * Frame-aligned events fired as `animTime` advances. Set by\n * {@link Animation.parse} from the `.anim` header's optional `events` array,\n * or assigned directly by game code before {@link Animation.register}.\n */\n events?: AnimationEvent[];\n /**\n * Treat frame 0 as an import reference pose and apply only each bone's\n * motion delta from it on top of the target rig's rest pose. Set from the\n * `.anim` header's `referenceFrameMode`, or by {@link Animation.load}'s\n * options; must be set before {@link Animation#register}.\n */\n referenceFrameMode?: 'first-frame';\n /** The target neutral pose used when `referenceFrameMode` is set (its frame 0 per bone). */\n referenceBaseAnimation?: Animation;\n /** Strip shear/scale from bone matrices on conversion (see {@link AnimationLoadOptions}). */\n rigidBones?: boolean;\n /** The clip's own name, where its file gave one. Not the name it is registered under. */\n name = '';\n /** Frames per second the clip was authored at. `30` unless the file says otherwise. */\n frameRate = 30;\n /** The name of the most recent {@link Animation.register}, if any. */\n registeredName?: string;\n private _registeredIn: SplatEngine | null = null;\n\n /** Length in seconds at the authored frame rate. */\n get duration(): number {\n return this.frameRate > 0 ? this.numFrames / this.frameRate : 0;\n }\n\n /** @internal Set by convertSkeletalAnimation on first registration. */\n skeletalConverted = false;\n /** @internal Per-bone keyframe cache produced by convertSkeletalAnimation. */\n skeletalStore?: SkeletalStore;\n /** @internal Per-target-bone-count cache of `filterAnimationForArmature` outputs. */\n filteredForBones?: Map<number, Animation>;\n\n constructor(data: Float32Array, numFrames: number, numBones: number, keyframeFrames?: number[]) {\n this.data = data;\n this.numFrames = numFrames;\n this.numBones = numBones;\n this.keyframeFrames = keyframeFrames;\n // Derived HERE, not at each call site, so \"an Animation knows which bones it\n // actually drives\" holds by construction. It was previously set only by\n // `parse` and `fromGlb`, which left the `.bin`-embedded clip built in\n // `Character._buildFromLoadResult` with no mask at all - under\n // `restSource: 'bundled'` that clip silently reimposed the canonical bone\n // lengths on a character whose bind is its own.\n //\n // Callers that know better still override on the next line: `fromGlb` has\n // the real glTF channel list (a channel that is absent differs from one\n // whose keys happen to be equal), and `filterAnimationForArmature` remaps\n // the source mask through its bone mapping. Both assign unconditionally, so\n // this pass is at worst redundant for them, never wrong.\n this.translationMask = deriveTranslationMask(data, numFrames, numBones, keyframeFrames);\n }\n\n /**\n * Parse an in-memory `.anim` buffer.\n *\n * Accepts both v2 (float32) and v3 (float16) data encodings. Use this when\n * fetching through a custom pipeline; pair with {@link Animation#register}\n * to make the result playable. Otherwise prefer {@link Animation.load}, the\n * fetching wrapper around this one. For a MetaHuman GLB, the current\n * container, the pair is {@link Animation.fromGlb} / {@link Animation.loadGlb}.\n *\n * Also derives {@link Animation#translationMask} from the decoded matrices, so\n * bones whose translation never moves keep the *target* character's bone\n * lengths instead of the source rig's.\n *\n * @throws If the header is missing, malformed, or not of type `skeletal_animation`.\n */\n static parse(buffer: ArrayBuffer): Animation {\n const view = new DataView(buffer);\n const headerLength = view.getUint32(0, true);\n\n if (headerLength > 10000 || headerLength > buffer.byteLength - 4) {\n throw new Error(`Invalid animation file: header length ${headerLength} out of range`);\n }\n\n const headerBytes = new Uint8Array(buffer, 4, headerLength);\n const headerJson = new TextDecoder().decode(headerBytes);\n\n let header: {\n type?: string;\n version?: number;\n numFrames: number;\n numBones: number;\n dataType?: string;\n keyframeFrames?: number[];\n events?: AnimationEvent[];\n referenceFrameMode?: 'first-frame';\n };\n try {\n header = JSON.parse(headerJson);\n } catch {\n throw new Error('Invalid animation file: header is not valid JSON');\n }\n\n if (header.type !== 'skeletal_animation') {\n throw new Error(`Invalid animation type: '${header.type}'`);\n }\n\n const dataOffset = 4 + headerLength;\n const dataLength = buffer.byteLength - dataOffset;\n if (dataLength <= 0) throw new Error('Animation file has no data');\n\n const dataBytes = new Uint8Array(buffer, dataOffset, dataLength);\n const alignedBuffer = new ArrayBuffer(dataLength);\n new Uint8Array(alignedBuffer).set(dataBytes);\n\n let animData: Float32Array;\n if (header.dataType === 'float16') {\n animData = float16ToFloat32(new Uint16Array(alignedBuffer));\n } else {\n animData = new Float32Array(alignedBuffer);\n }\n\n clearAnimRootRotation(animData, header.numFrames, header.numBones);\n\n // The constructor derives `translationMask` from exactly these arguments.\n const anim = new Animation(animData, header.numFrames, header.numBones, header.keyframeFrames);\n if (header.referenceFrameMode === 'first-frame') anim.referenceFrameMode = 'first-frame';\n if (Array.isArray(header.events) && header.events.length > 0) {\n anim.events = header.events;\n }\n return anim;\n }\n\n /**\n * Parse an in-memory *MetaHuman GLB* - a glTF 2.0 binary holding a bone\n * hierarchy and one animation clip, carrying no real geometry (as produced\n * by the offline MetaHuman GLB exporter).\n *\n * Reads the clip's parent-local TRS into the same per-bone keys a `.anim`\n * is converted to, so both play identically. `data` stays empty.\n *\n * `animationName` selects a clip by name when the GLB holds more than one;\n * omitted, the first clip is used. Pair with {@link Animation#register} to\n * make the result playable, or use {@link Animation.loadGlb}.\n *\n * @throws If the container is not GLB 2.0, or the clip does not supply a\n * translation and a rotation channel for every bone on one shared timeline.\n */\n static fromGlb(buffer: ArrayBuffer, animationName?: string): Animation {\n const animation = Animation.parseGlb(buffer, animationName);\n if (Math.abs(animation.frameRate - 30) > 0.5) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Animation] GLB \"${animation.name}\" is authored at ${animation.frameRate.toFixed(2)} fps; ` +\n 'playback is frame-indexed and defaults to 30 - set `armature.frameRate` to match.',\n );\n }\n return animation;\n }\n\n /**\n * {@link Animation.fromGlb} without the frame-rate warning: the clip's own\n * rate is recorded on {@link Animation.frameRate} for a caller that applies it.\n * @internal\n */\n static parseGlb(buffer: ArrayBuffer, animationName?: string): Animation {\n const parsed = parseArmatureGlbAnimation(buffer, animationName);\n const animation = new Animation(new Float32Array(0), parsed.numFrames, parsed.numBones);\n animation.translationMask = parsed.translationMask;\n animation.skeletalStore = { keyframes: parsed.keyframes, manualBones: new Set(), source: 'imported' };\n animation.skeletalConverted = true;\n // Key times are float32 seconds, so 30 fps comes back as 29.999998. Snap\n // to the whole rate the clip was plainly authored at.\n const whole = Math.round(parsed.frameRate);\n animation.frameRate = Math.abs(parsed.frameRate - whole) < 0.01 ? whole : parsed.frameRate;\n animation.name = parsed.animationName;\n return animation;\n }\n\n /**\n * Fetch, parse, and register a `.anim` file on the engine under `name`.\n * Loaded keys are shared read-only; metadata and registration\n * are local to the returned Animation. Use `parse` for editable source poses.\n *\n * After this resolves, characters can play it via\n * `character.playAnimation(name)` / `character.crossfadeTo(name)`.\n *\n * @throws If the network request fails or the file is not a valid animation.\n * @example\n * ```ts\n * await Animation.load(engine, '/assets/idle.anim', 'idle');\n * character.playAnimation('idle', { loop: true });\n * ```\n * `options` reads a clip converted from FBX (see {@link AnimationLoadOptions}).\n */\n static async load(engine: SplatEngine, url: string, name: string, options: AnimationLoadOptions = {}): Promise<Animation> {\n const animation = hasConversionOptions(options)\n ? Animation._withConversionOptions(Animation.parse(await Animation._fetchBuffer(url)), options)\n : await Animation._loadConverted(url, 'anim');\n animation.register(engine, name);\n return animation;\n }\n\n /**\n * A clip loaded with {@link AnimationLoadOptions} gets its own unconverted\n * copy: `register` converts it against the engine's rig, which a reference\n * pose needs, and its keys differ from the shared plain conversion.\n */\n private static _withConversionOptions(animation: Animation, options: AnimationLoadOptions): Animation {\n if (options.referenceFrameMode) animation.referenceFrameMode = options.referenceFrameMode;\n if (options.referenceBaseAnimation) animation.referenceBaseAnimation = options.referenceBaseAnimation;\n if (options.rigidBones) animation.rigidBones = true;\n return animation;\n }\n\n /**\n * Fetch, parse, and register a MetaHuman GLB on the engine under `name`.\n * The GLB counterpart of {@link Animation.load}.\n * Like `load`, returns a local wrapper over shared read-only keys.\n * Use `fromGlb` directly when an unshared copy is needed.\n *\n * `animationName` selects a clip inside the GLB by name; omitted, the first\n * clip is used. After this resolves, characters can play it via\n * `character.playAnimation(name)` / `character.crossfadeTo(name)` - the\n * source format is invisible from that point on.\n *\n * @throws If the network request fails or the GLB is not a valid armature clip.\n * @example\n * ```ts\n * await Animation.loadGlb(engine, '/assets/metahuman_full.glb', 'walk');\n * character.playAnimation('walk', { loop: true });\n * ```\n */\n static async loadGlb(\n engine: SplatEngine,\n url: string,\n name: string,\n animationName?: string,\n ): Promise<Animation> {\n const animation = await Animation._loadConverted(url, 'glb', animationName);\n animation.register(engine, name);\n return animation;\n }\n\n /** Start downloading now; a later `load` of the same URL reuses the bytes. */\n static prefetch(url: string): void {\n Animation._fetchBuffer(url).catch(() => {});\n }\n\n private static readonly _convertedLimit = 8;\n private static _convertedCache = new Map<string, ConvertedSource>();\n private static _convertedLoading = new Map<string, Promise<ConvertedSource | null>>();\n\n private static async _loadConverted(\n url: string,\n format: 'anim' | 'glb',\n animationName?: string,\n ): Promise<Animation> {\n // Same immutable-asset identity contract as the byte cache: query strings\n // carry rotating signatures, not content versions. Include the clip selector\n // and reader explicitly; scene registration names are intentionally absent.\n const key = JSON.stringify([format, url.split('?')[0], animationName ?? null]);\n let source = Animation._convertedCache.get(key);\n if (source) {\n Animation._convertedCache.delete(key);\n Animation._convertedCache.set(key, source);\n } else {\n let pending = Animation._convertedLoading.get(key);\n if (!pending) {\n pending = (async () => {\n const buffer = await Animation._fetchBuffer(url);\n const parsed = format === 'glb'\n ? Animation.fromGlb(buffer, animationName)\n : Animation.parse(buffer);\n // A header-declared reference pose converts against the engine's\n // rig at register, so it never enters the shared cache.\n if (parsed.referenceFrameMode) return null;\n convertSkeletalAnimation(parsed);\n // Every wrapper below shares these entries, so freeze them against\n // swapped arrays (typed-array contents can't be frozen). Maps, masks\n // and events are copied per wrapper.\n for (const entry of parsed.skeletalStore?.keyframes.values() ?? []) Object.freeze(entry);\n const converted: ConvertedSource = {\n numFrames: parsed.numFrames,\n numBones: parsed.numBones,\n keyframeFrames: parsed.keyframeFrames,\n translationMask: parsed.translationMask,\n events: parsed.events,\n skeletalStore: parsed.skeletalStore,\n name: parsed.name,\n frameRate: parsed.frameRate,\n };\n Animation._convertedCache.set(key, converted);\n if (Animation._convertedCache.size > Animation._convertedLimit) {\n const oldest = Animation._convertedCache.keys().next().value!;\n Animation._convertedCache.delete(oldest);\n }\n return converted;\n })().finally(() => Animation._convertedLoading.delete(key));\n Animation._convertedLoading.set(key, pending);\n }\n const converted = await pending;\n if (!converted) return Animation.parse(await Animation._fetchBuffer(url));\n source = converted;\n }\n\n // A fresh wrapper keeps filtering and the WeakMap playback cache local to\n // the caller's lifetime. In particular, the LRU never retains rest-relative\n // keyframes belonging to characters from previously destroyed scenes.\n const animation = new Animation(new Float32Array(0), source.numFrames, source.numBones);\n animation.keyframeFrames = source.keyframeFrames?.slice();\n animation.translationMask = source.translationMask?.slice();\n animation.events = source.events ? structuredClone(source.events) : undefined;\n animation.skeletalConverted = true;\n animation.name = source.name;\n animation.frameRate = source.frameRate;\n if (source.skeletalStore) {\n animation.skeletalStore = {\n keyframes: new Map(source.skeletalStore.keyframes),\n manualBones: new Set(source.skeletalStore.manualBones),\n source: source.skeletalStore.source,\n };\n }\n return animation;\n }\n\n /**\n * Process-wide ArrayBuffer cache for .anim URLs. Each `SplatEngine` still\n * gets its own `Animation` wrapper; converted source data is shared by the\n * bounded cache above. Avoids re-downloading the same\n * idle/walk clips every time the app swaps one engine for another.\n */\n private static _bufferCache = new Map<string, ArrayBuffer>();\n private static _bufferLoading = new Map<string, Promise<ArrayBuffer>>();\n\n private static async _fetchBuffer(url: string): Promise<ArrayBuffer> {\n // Strip query for in-memory cache key (signed CDN URLs rotate tokens)\n const key = url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?'));\n\n const cached = Animation._bufferCache.get(key);\n if (cached) return cached;\n const inflight = Animation._bufferLoading.get(key);\n if (inflight) return inflight;\n\n // Use cachedFetch for persistent caching (Cache API), then store in-memory\n const promise = cachedFetch(url).then(async (res) => {\n if (!res.ok) throw new Error(`Failed to fetch animation: ${res.statusText}`);\n const buf = await res.arrayBuffer();\n Animation._bufferCache.set(key, buf);\n return buf;\n }).finally(() => {\n Animation._bufferLoading.delete(key);\n });\n Animation._bufferLoading.set(key, promise);\n return promise;\n }\n\n /**\n * Convert the animation data against the engine's skeleton library and\n * register it under `name` so characters can play it.\n *\n * Must be called before {@link Character.playAnimation} / {@link Character.crossfadeTo}\n * reference this animation.\n */\n register(engine: SplatEngine, name: string): void {\n convertSkeletalAnimation(this, engine.skeletonLibrary);\n engine.skeletalAnimationLibrary.set(name, this);\n this.registeredName = name;\n this._registeredIn = engine;\n }\n\n /**\n * Remove the clip from the engine it is registered with, so it can be\n * garbage-collected once nothing is playing it. A character already playing\n * the clip keeps playing; starting it again registers it afresh.\n */\n dispose(): void {\n if (this._registeredIn && this.registeredName !== undefined) {\n this._registeredIn.skeletalAnimationLibrary.delete(this.registeredName);\n }\n this._registeredIn = null;\n this.registeredName = undefined;\n }\n}\n", "import { Group, Matrix4, Quaternion, Vector3 } from 'three';\nimport type { Frustum, Object3D } from 'three';\n\nimport { Mat4, Quat, Vec3 } from './math';\n\nimport {\n convertSkeletalAnimation,\n filterAnimationForArmature,\n} from './anim/animation-conversion';\nimport { computeBindPoseTransforms } from './anim/bind-pose';\nimport type { SplatEngine } from './engine';\nimport { AnimationPlayer } from './skeletal/animation-player';\nimport type { AnimEventCallback, AnimationProvider } from './skeletal/animation-player';\nimport type { BoneMask } from './skeletal/bone-mask';\nimport { computeBoneStretch } from './skeletal/bone-stretch';\nimport type { BoneScaleInput } from './skeletal/bone-stretch';\nimport { Pose } from './skeletal/pose';\nimport { Skeleton } from './skeletal/skeleton';\nimport { SplatSkinning } from './skeletal/splat-skinning';\nimport { buildSourceBoneRemap } from './splat/bone-binding';\nimport { buildRevealSkeleton } from './splat/reveal-bake';\nimport type { RevealSkeleton } from './splat/reveal-bake';\nimport type { Splat } from './splat/splat';\nimport type { ArmatureData } from './types';\n\n/** \"pelvis\" on the bundled rigs; \"Hips\" on Mixamo-style ones, any prefix or separator. */\nfunction isPelvisName(lower: string): boolean {\n return lower.includes('pelvis') || lower.replace(/^.*:/, '').replace(/^mixamorig/, '').replace(/[^a-z0-9]/g, '') === 'hips';\n}\n\n/**\n * Distance-based animation-LOD knobs. Used as the engine-wide preset\n * (`SplatEngine.animLodPreset`) and as the per-armature override shape in\n * {@link Armature.setAnimationLod}.\n */\nexport interface AnimLodPreset {\n /** World-space distance (m) below which the armature animates full rate. */\n nearDist?: number;\n /** World-space distance (m) beyond which `farStride` applies. */\n farDist?: number;\n /** Frames-per-update between `nearDist` and `farDist`. 1 = every frame. */\n nearStride?: number;\n /** Frames-per-update beyond `farDist`. */\n farStride?: number;\n}\n\n/** Built-in fallback used by `setAnimationLod()` (no-arg) when the engine\n * has no `animLodPreset`. Full rate \u226412 m, every-2nd \u226424 m, every-4th\n * beyond. */\nconst DEFAULT_ANIM_LOD_PRESET: AnimLodPreset = {\n nearDist: 12,\n farDist: 24,\n nearStride: 2,\n farStride: 4,\n};\n\n/**\n * Pluggable override that drives the per-frame pose in place of\n * animation. The Armature has no knowledge of what's on the other end -\n * ragdoll physics, an IK solver, an AI behavior tree's pose output, a\n * network-replicated remote character - they all attach the same way.\n *\n * When `armature.poseProvider` is non-null, the Armature's animation\n * player is **not advanced** that frame; the provider has total control\n * of the pose. The Armature still owns the skinning pipeline (LOD,\n * frustum cull, world-transform composition, GPU palette upload), so a\n * provider only needs to fill `pose`.\n *\n * Implementations: {@link Ragdoll}.\n *\n * @group Characters & Animation\n */\nexport interface PoseProvider {\n /**\n * Fill `pose` (per-bone TRS in armature-local bone space) for this\n * frame. The Armature runs this between its LOD/frustum gate and the\n * `Skeleton.applyLocal` composition step. To restore animation,\n * detach by setting `armature.poseProvider = null`.\n */\n writePose(pose: Pose, armature: Armature, dt: number): void;\n\n /**\n * Optional teardown hook fired when the Armature is destroyed (or\n * when a new provider replaces this one). Use to release external\n * resources - e.g. ragdoll physics bodies.\n */\n onDetach?(): void;\n}\n\n/**\n * How the armature handles the pelvis X/Z motion extracted from the active\n * animation.\n *\n * - `'off'` - Pelvis X/Z is clamped to bind in bone space. The character\n * looks \"in-place\" regardless of whether the underlying clip is\n * locomotive. The pivot is not touched by animation. **Default.**\n * - `'apply'` - The pivot tracks the pelvis as an absolute offset from a captured\n * baseline: `object3D.position = baseline + (pelvis_pose \u2212 bind)` each\n * frame. Switching `off \u2192 apply` captures the current pivot position as\n * the baseline; switching `apply \u2192 off` snaps the pivot back to the\n * baseline. Best for toggling-on/off demos and in-place looping animations\n * (pelvis returns to bind at loop end \u2192 no teleport). Locomotive clips\n * visibly snap at loop wrap; use `'extract'` for those.\n * - `'extract'` - Engine computes the per-frame pelvis \u0394\n * (`pelvis(t) \u2212 pelvis(t \u2212 dt)`) and accumulates it into an internal\n * buffer; the caller reads it via {@link Armature.consumeRootMotionDelta}\n * and feeds it to a motor / physics body / network layer. Unity-style\n * `OnAnimatorMove` pattern. The engine does **not** write to the pivot in\n * this mode. Loop wraps and hard `play` calls suppress the resulting\n * pelvis discontinuity so the next \u0394 is `0`.\n *\n * In every mode the pelvis bone itself is clamped to bind X/Z in bone space -\n * the motion lives on the pivot (or in the consumed delta), never on the\n * bone.\n *\n * @group Characters & Animation\n */\nexport type RootMotionMode = 'off' | 'apply' | 'extract';\n\n/**\n * Supplies a corrective pivot translation for one frame. Installed via\n * {@link Armature.rootOffsetProvider} and called once per {@link Armature.update}\n * with the current animation frame time, after the pose is evaluated and before\n * bone transforms are composed - so the offset lands in the same frame's bone\n * matrices with no lag.\n *\n * Return `null` for \"no offset this frame\". The returned vector is read\n * immediately and not retained, so returning a reused scratch object is fine.\n *\n * @group Characters & Animation\n */\nexport type RootOffsetProvider = (frameTime: number) => { x: number; y: number; z: number } | null;\n\n/**\n * Refines the freshly-evaluated pose in place, once per {@link Armature.update}.\n *\n * Unlike {@link PoseProvider}, which REPLACES animation, a modifier runs on top\n * of it: the player has already written `pose`, overlay layers have already been\n * composed, and the modifier gets the last word before the rig-convention clamps\n * and the world-transform composition. Return nothing - edit `pose` in place.\n *\n * This is the hook for corrections that are a function of the animated pose\n * rather than a replacement for it: an additive limb offset, a loop-seam\n * dissolve, a look-at, a blink. `dt` is the seconds the clip advanced this\n * evaluation (0 for {@link Armature.forcePoseRefresh}). `null` (the default)\n * is no modifier and costs nothing.\n *\n * Deliberately NOT run by {@link Armature.probeBoneWorldPositions}: a probe\n * measures the clip, and a correction derived from a probe that already\n * contained it would feed back into itself.\n *\n * @group Characters & Animation\n */\nexport type PoseModifier = (pose: Pose, armature: Armature, dt: number) => void;\n\n/**\n * Composition root for one character: holds the three.js pivot object and\n * wires together a {@link Skeleton}, an {@link AnimationPlayer}, a working\n * {@link Pose}, and a {@link SplatSkinning} unit.\n *\n * Thin facade - `playAnimation` / `crossfadeTo` / `stop` / `update` delegate\n * to the underlying modules. The rig-convention rules (pelvis X/Z clamp,\n * pelvis-Y lock, root-bone clamp, root-motion extraction) live here, because\n * they're a *character-setup* concern, not a pose-evaluation concern.\n *\n * Most users won't construct this directly - {@link Character.load} builds\n * one automatically. It's exported for custom pipelines that need direct\n * control over skeletal evaluation.\n *\n * @group Characters & Animation\n */\nexport class Armature {\n /** Pivot object; all linked splats become children of this. */\n object3D: Group;\n /** Rig data (bone count, rest translations/rotations, parents). */\n armatureData: ArmatureData;\n /** Number of bones in the rig. */\n numBones: number;\n\n private readonly _skeleton: Skeleton;\n /**\n * Cap on how far one {@link update} may advance the clip, in seconds.\n * `Infinity` (the default) tracks the wall clock.\n *\n * PlayCanvas clamps a long frame to `app.maxDeltaTime` (100ms), which a\n * 30fps clip crosses three frames at once - a visible lurch. Cap it across\n * an expected stall, then restore: capping drifts behind real time, which a\n * loop hides but steady-state playback should not.\n */\n maxAnimDt = Infinity;\n\n /**\n * Corrective per-frame pivot translation, or `null` (the default) for none.\n * See {@link RootOffsetProvider}.\n *\n * The offset composes ON TOP of whatever {@link rootMotionMode} routing\n * produced and is measured from the base position {@link move} last set, so it\n * cannot ratchet: every frame writes an absolute position, never an increment.\n * `move` keeps owning the base placement; the provider only ever nudges.\n *\n * Used by callers that precompute a corrective root path from a clip - ground\n * snap and foot pinning being the obvious ones - and want it applied every\n * frame without fighting the base placement for ownership of the entity.\n */\n rootOffsetProvider: RootOffsetProvider | null = null;\n\n /**\n * Per-frame refinement of the animated pose, or `null` (the default) for\n * none. See {@link PoseModifier}.\n */\n poseModifier: PoseModifier | null = null;\n\n /**\n * Former name of {@link poseModifier}, kept for compatibility. Same hook, same slot in the frame.\n *\n * @deprecated Use {@link poseModifier}.\n */\n get posePostProcess(): PoseModifier | null {\n return this.poseModifier;\n }\n\n set posePostProcess(fn: PoseModifier | null) {\n this.poseModifier = fn;\n }\n\n private readonly _currentPose: Pose;\n private readonly _snapshotPose: Pose;\n private readonly _worldTransforms: Mat4[] = [];\n // Probe scratch. Allocated on the first probe call, never before.\n private _probePose: Pose | null = null;\n // Set by prepareReveal; splats linked afterwards are baked as they link.\n private _revealPrepared = false;\n // Shared by every splat this armature drives; see _bakeReveal.\n private _revealSkeleton: RevealSkeleton | null = null;\n private readonly _probeTransforms: Mat4[] = [];\n\n private _engine: SplatEngine | null = null;\n private readonly _worldMatrix = new Mat4();\n private _player: AnimationPlayer | null = null;\n private _skinning: SplatSkinning | null = null;\n private _provider: AnimationProvider | null = null;\n private readonly _layers = new Map<string, AnimationLayer>();\n private readonly _layerTmpQ = new Quat();\n private _drivenNodes: readonly Object3D[] | null = null;\n private _evaluatedBones: readonly number[] | null = null;\n /** {@link _evaluatedBones} with ancestors, root and pelvis, parents first. */\n private _evaluatedOrder: Int32Array | null = null;\n private readonly _nodeTmpV = new Vec3();\n private readonly _nodeTmpQ = new Quat();\n\n /**\n * Optional override that drives the pose in place of animation.\n * Setting this to a non-null value skips animation evaluation; the\n * provider has full control of `_currentPose`. Setting back to `null`\n * resumes animation immediately. See {@link PoseProvider}.\n *\n * Replacing the provider (set non-null while another is attached)\n * fires the outgoing provider's `onDetach()` first.\n */\n get poseProvider(): PoseProvider | null { return this._poseProvider; }\n set poseProvider(p: PoseProvider | null) {\n if (p === this._poseProvider) return;\n const prev = this._poseProvider;\n this._poseProvider = p;\n try { prev?.onDetach?.(); } catch { /* keep going */ }\n }\n private _poseProvider: PoseProvider | null = null;\n\n // Rig-convention bone indices. `-2` = unresolved, `-1` = absent in rig.\n private _rootBoneIndex = -2;\n private _pelvisBoneIndex = -2;\n\n\n /**\n * When true, {@link update} advances the animation player (so timers,\n * crossfade, and event callbacks still fire) but skips pose evaluation\n * and the skinning push. The previous frame's pose stays on the GPU\n * palette and the splat keeps rendering at its last bone state.\n *\n * Use for dynamic animation LOD - e.g. when fps drops, set true on\n * every other (or every Nth) frame to halve the per-frame skeletal\n * cost. Cleared when fps recovers.\n */\n skipPose = false;\n\n /**\n * When true, {@link update} still pushes bone transforms to the GPU\n * palette (so items, hitboxes, and outlines tracking bones still move\n * correctly) but skips the CPU-side `splat.updatePositions(...)` call\n * that recomputes sort centers from the deformed mesh. The depth-sort\n * order lags one frame behind the visual pose.\n *\n * Use for alternate-frame throttling - `updatePositions` is the heavy\n * call (full center buffer re-upload to the sort worker), and most\n * frames don't visibly need a fresh sort.\n */\n skipPositions = false;\n\n /**\n * Update rate divider. `1` = pose evaluation runs on every {@link update}\n * call (default - one pose update per `engine.update()`).\n * Set to N>1 to advance the animation player every call but only do the\n * heavy pose-eval + skinning push every Nth call.\n *\n * `dt` from skipped frames is accumulated and passed to the next\n * evaluated frame, so animation time stays correct - only the GPU\n * palette refresh rate drops.\n *\n * Typical use: set to `2` on background characters so the per-character\n * armature cost halves while the engine still ticks at 30 Hz.\n */\n updateInterval = 1;\n\n private _updateCounter = 0;\n private _updateAccumDt = 0;\n\n // Pelvis-lock state.\n private _lockPelvisY = false;\n\n // Root motion.\n private _rootMotionMode: RootMotionMode = 'off';\n // 'apply' mode: baseline pivot position captured on off \u2192 apply.\n private _baseLocalPosition = new Vec3();\n // 'extract' mode: delta tracker for Unity-style per-frame \u0394.\n private _lastPelvisPos = new Vec3();\n private _hasLastPelvis = false;\n private _rootMotionAccumDx = 0;\n private _rootMotionAccumDz = 0;\n // Scratch for the bone-space -> entity-space rotation of the pelvis offset.\n private readonly _rootMotionTmp = new Vec3();\n // Unset: follow the engine's {@link SplatEngine.legacyRootRotation}.\n private _legacyRootRotation: boolean | null = null;\n\n // \u2500\u2500 Distance-based animation LOD \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Throttle skinning updates by distance from the camera: near\n // characters update every frame, far ones every Nth. `tick(dt)` still\n // advances animation time every frame (so clip timing stays correct);\n // only the expensive pose-evaluate + skinning push is skipped on\n // throttled frames, freezing the rendered pose until the next update.\n //\n // OFF BY DEFAULT - distances start at Infinity so `_lodStride()` always\n // returns 1 (full rate). Opt in per-armature via `setAnimationLod()`\n // (no-arg form pulls the engine's `animLodPreset`), or set the engine\n // preset once and call `setAnimationLod()` on each character you want\n // throttled. Player / important characters: just never opt in.\n private _lodNearDist = Infinity;\n private _lodFarDist = Infinity;\n private _lodNearStride = 2; // frames-per-update between near and far\n private _lodFarStride = 4; // frames-per-update beyond far\n private _lodFrameCounter = 0;\n\n // \u2500\u2500 Distance-based SORT LOD \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Complement to animation LOD. Throttles ONLY the CPU-side sort center\n // re-upload (`splat.updatePositions`, ~88% of per-character CPU at high\n // counts) by setting `skipPositions=true` on throttled frames. The GPU\n // palette still uploads, so the visible pose is correct - only the\n // depth-sort order lags one frame.\n //\n // Composes with anim LOD: on frames where anim LOD throttles, the whole\n // block returns and sort LOD is irrelevant. On frames where anim LOD\n // evaluates, sort LOD can still decide to skip the positions push.\n // Typical setup: tight bands so even mid-distance characters skip sort\n // most frames, while pose stays at full rate.\n //\n // OFF BY DEFAULT - opt in per-armature via `setSortLod()`.\n private _sortLodNearDist = Infinity;\n private _sortLodFarDist = Infinity;\n private _sortLodNearStride = 2;\n private _sortLodFarStride = 4;\n private _sortLodFrameCounter = 0;\n\n constructor(name: string, armatureData: ArmatureData) {\n this.armatureData = armatureData;\n this.numBones = armatureData.numBones;\n this.object3D = new Group();\n this.object3D.name = name;\n this._skeleton = new Skeleton(armatureData);\n this._currentPose = new Pose(this.numBones);\n this._snapshotPose = new Pose(this.numBones);\n this._currentPose.setToBind(this._skeleton.bindT, this._skeleton.bindR);\n }\n\n /**\n * Drive scene-graph nodes from this armature's pose: a skinned mesh's bones,\n * index-aligned with the rig and listed parents first. Each update writes the\n * bone world transforms onto them, and the armature evaluates whenever nodes\n * are attached - it otherwise poses only while a linked splat is in view.\n * `null` detaches.\n */\n driveNodes(nodes: readonly Object3D[] | null): void {\n if (nodes && nodes.length !== this.numBones) {\n throw new Error(`[Armature] driveNodes: ${nodes.length} nodes for ${this.numBones} bones`);\n }\n this._drivenNodes = nodes;\n if (nodes) this._pushPose();\n }\n\n /**\n * Pose only these bones (with their ancestors, the root and the pelvis) on\n * each {@link update}; every other bone keeps its last bone matrix and\n * driven-node pose. For a reader of a few bones of a large rig. `null` (the\n * default) poses every bone.\n */\n evaluateOnly(bones: readonly number[] | null): void {\n this._evaluatedBones = bones;\n this._applyEvaluatedBones();\n }\n\n private _applyEvaluatedBones(): void {\n if (!this._player) return;\n const bones = this._evaluatedBones;\n let order: Int32Array | null = null;\n if (bones) {\n this._resolveRigIndices();\n const rig = [this._rootBoneIndex, this._pelvisBoneIndex].filter((i) => i >= 0);\n order = this._skeleton.subsetOrder([...bones, ...rig]);\n }\n this._evaluatedOrder = order;\n this._player.bones = order;\n }\n\n /**\n * Per-bone inverse bind-pose matrices (bind space to bone-local), for\n * load-time passes over splat weights that need each bone's joint origin in\n * the splats' rest space. Read-only.\n */\n get inverseBindPose(): readonly Mat4[] {\n return this._skeleton.inverseBindPose;\n }\n\n /** Splats currently being driven by this armature. */\n get linkedSplats(): Set<Splat> {\n if (this._skinning) return this._skinning.linkedSplats;\n return _EMPTY_SET;\n }\n\n /**\n * Detach the armature from its engine and remove its pivot object. Splats\n * still linked at the time of destroy are also destroyed so they stop\n * holding GPU resources alive. The armature itself is not safe to\n * reuse after this call.\n *\n * Use {@link Character.destroy} instead if you have the owning\n * {@link Character} - it disposes both the armature and its primary splat.\n */\n destroy(): void {\n try { this._poseProvider?.onDetach?.(); } catch { /* keep tearing down */ }\n this._poseProvider = null;\n this._drivenNodes = null;\n if (this._skinning) {\n for (const splat of Array.from(this._skinning.linkedSplats)) {\n try { splat.destroy(); } catch { /* ignore cleanup errors */ }\n }\n }\n this.object3D.removeFromParent();\n this._engine = null;\n this._skinning = null;\n this._player = null;\n this._provider = null;\n this._layers.clear();\n }\n\n // \u2500\u2500 Engine integration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Attach this armature to an engine. Required before playback. Adds the\n * armature pivot as a child of `engine.contentRoot` and wires up the\n * animation provider + splat skinning.\n */\n addToScene(engine: SplatEngine): void {\n this._engine = engine;\n engine.contentRoot.add(this.object3D);\n\n const provider: AnimationProvider = (name: string) => {\n let anim = engine.skeletalAnimationLibrary.get(name);\n if (!anim) return null;\n anim = filterAnimationForArmature(anim, this.numBones, engine.skeletonLibrary);\n engine.skeletalAnimationLibrary.set(name, anim);\n convertSkeletalAnimation(anim, engine.skeletonLibrary);\n return anim;\n };\n this._provider = provider;\n\n this._player = new AnimationPlayer({\n skeleton: this._skeleton,\n animationProvider: provider,\n snapshotPose: this._snapshotPose,\n });\n this._skinning = new SplatSkinning(this._skeleton, engine.skeletonLibrary);\n this._applyEvaluatedBones();\n\n this._pushPose();\n }\n\n /**\n * Register a {@link Splat} to be driven by this armature.\n *\n * Reparents the splat under the armature's pivot and pushes the current\n * bone transforms so the splat appears in the correct pose immediately.\n */\n linkSplat(splat: Splat): void {\n if (!this._skinning) return;\n this._skinning.link(splat);\n splat.linkedArmature = this;\n\n this.object3D.add(splat.object3D);\n\n if (this._revealPrepared || splat.revealEnabled) this._bakeReveal(splat);\n this._pushPose();\n }\n\n /**\n * Opt every linked splat into the reveal ahead of time - see\n * {@link Splat.setReveal}. Bakes each splat's feet-to-head distances (about\n * 10 ms per 50k splats on a desktop) and recompiles its shader once, so\n * call it after loading rather than when the reveal starts. Splats linked\n * later are baked as they link.\n */\n prepareReveal(): void {\n this._revealPrepared = true;\n for (const splat of this.linkedSplats) this._bakeReveal(splat);\n }\n\n /**\n * {@link Splat.bakeReveal} for one splat. The distances depend\n * only on the skeleton, so they are derived once and shared - a character\n * links one splat per LOD plus any variants.\n */\n private _bakeReveal(splat: Splat): void {\n if (splat.revealBaked) return;\n const reveal = this._revealSkeleton ?? this._buildRevealSkeleton(splat);\n if (!reveal) return;\n this._revealSkeleton = reveal;\n const remap = buildSourceBoneRemap(splat, this._skeleton.numBones, this._engine?.skeletonLibrary);\n splat.bakeReveal(reveal, remap);\n }\n\n /** This rig's {@link buildRevealSkeleton}, from its bind pose. */\n private _buildRevealSkeleton(splat: Splat): RevealSkeleton | null {\n const sk = this._skeleton;\n const n = sk.numBones;\n if (n === 0) return null;\n const bind = computeBindPoseTransforms(n, sk.bindT, sk.bindR, sk.parents);\n const pos = new Float32Array(n * 3);\n const tmp = new Vec3();\n for (let i = 0; i < n; i++) {\n bind[i].getTranslation(tmp);\n pos[i * 3] = tmp.x; pos[i * 3 + 1] = tmp.y; pos[i * 3 + 2] = tmp.z;\n }\n return buildRevealSkeleton(pos, sk.parents, this.rigBoneNames, splat.localBounds.getCenter(_nodePos));\n }\n\n /**\n * Stop driving the given splat. The splat is not destroyed; it just no\n * longer receives bone transform updates.\n */\n unlinkSplat(splat: Splat): void {\n this._skinning?.unlink(splat);\n if (splat.linkedArmature === this) {\n splat.linkedArmature = null;\n }\n }\n\n /**\n * Apply any combination of position, rotation, and scale to the armature\n * pivot. All linked splats are requested to re-sort.\n */\n move(position?: Vec3, rotation?: Quat, scale?: Vec3): void {\n if (position) {\n this._baseLocalPosition.copy(position);\n this.object3D.position.set(position.x, position.y, position.z);\n }\n if (rotation) this.object3D.quaternion.set(rotation.x, rotation.y, rotation.z, rotation.w);\n if (scale) this.object3D.scale.set(scale.x, scale.y, scale.z);\n this._skinning?.requestSortAll();\n }\n\n // \u2500\u2500 Root motion \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * How pelvis X/Z motion is routed each frame. See {@link RootMotionMode}.\n * Default `'off'`.\n *\n * Transitions are coordinated so toggling is well-behaved:\n *\n * - `off \u2192 apply` captures the current pivot position as the baseline.\n * The pivot then tracks `baseline + (pelvis \u2212 bind)` each frame.\n * - `apply \u2192 off` (or `apply \u2192 extract`) snaps the pivot back to the\n * baseline so the apply-mode offset doesn't leak into the next mode.\n * This is what prevents the toggle-ratchet bug.\n * - `* \u2192 extract` resets the per-frame \u0394 tracker so the next \u0394 is `0`.\n */\n get rootMotionMode(): RootMotionMode { return this._rootMotionMode; }\n set rootMotionMode(m: RootMotionMode) {\n if (m === this._rootMotionMode) return;\n const prev = this._rootMotionMode;\n if (prev === 'apply') {\n this.object3D.position.set(this._baseLocalPosition.x, this._baseLocalPosition.y, this._baseLocalPosition.z);\n this._skinning?.requestSortAll();\n }\n if (m === 'apply') {\n const p = this.object3D.position;\n this._baseLocalPosition.set(p.x, p.y, p.z);\n }\n this._hasLastPelvis = false;\n this._rootMotionAccumDx = 0;\n this._rootMotionAccumDz = 0;\n this._rootMotionMode = m;\n }\n\n /**\n * Convenience boolean alias for {@link rootMotionMode}.\n * `true` \u21D4 `'apply'`, `false` \u21D4 `'off'`. To use `'extract'`, set\n * {@link rootMotionMode} directly.\n */\n get rootMotion(): boolean { return this._rootMotionMode === 'apply'; }\n set rootMotion(v: boolean) { this.rootMotionMode = v ? 'apply' : 'off'; }\n\n /**\n * The entity position root motion applies off - see {@link rootMotionMode}.\n * Set by {@link move}. Read-only; the vector is live.\n */\n get rootMotionBase(): Readonly<Vec3> { return this._baseLocalPosition; }\n\n /**\n * Return the pelvis X/Z delta accumulated since the previous call (or since\n * the armature was created / `rootMotionMode` was changed), and reset the\n * accumulator. The delta is in the pivot's parent space - feed it directly\n * to a motor's velocity input or to a physics body.\n *\n * Returns `{ dx: 0, dz: 0 }` in `'off'` or `'apply'` modes. In `'apply'`\n * mode the delta has already been written to {@link object3D}, so consumers\n * shouldn't read and re-apply it.\n */\n consumeRootMotionDelta(): { dx: number; dz: number } {\n const dx = this._rootMotionAccumDx;\n const dz = this._rootMotionAccumDz;\n this._rootMotionAccumDx = 0;\n this._rootMotionAccumDz = 0;\n return { dx, dz };\n }\n\n /**\n * When `true`, clamp the pelvis bone's Y translation to bind each frame.\n * Use for in-place idle / gesture captures where vertical bob would push\n * the character out of a tightly-framed thumbnail.\n */\n get lockPelvisY(): boolean { return this._lockPelvisY; }\n set lockPelvisY(v: boolean) { this._lockPelvisY = v; }\n\n /**\n * When `true`, the root bone's rotation is pinned to bind each frame and\n * root motion is read straight off the pelvis, as in 0.1.1: a GLB clip whose\n * root carries a yaw (every MetaHuman preset carries 180\u00B0) does not turn the\n * character. When `false`, the clip's root rotation is kept and root motion\n * is turned with it, as in the PlayCanvas build 0.3.2.\n *\n * Defaults to the engine's {@link SplatEngine.legacyRootRotation}: `true` on\n * a `SplatEngine`, `false` on a `Scene`. Assign `null` to follow the engine\n * again. `.anim` clips look the same either way; their root rotation is\n * reset at parse.\n *\n * Set it before a clip plays: changed mid-clip under root-motion `'apply'`,\n * the character jumps by twice its current pelvis offset.\n */\n get legacyRootRotation(): boolean {\n return this._legacyRootRotation ?? this._engine?.legacyRootRotation ?? true;\n }\n set legacyRootRotation(v: boolean | null) { this._legacyRootRotation = v ?? null; }\n\n // \u2500\u2500 Playback accessors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n get isPlaying(): boolean { return this._player?.isPlaying ?? false; }\n get isFinished(): boolean { return this._player?.isFinished ?? false; }\n\n get paused(): boolean { return this._player?.paused ?? false; }\n set paused(v: boolean) { if (this._player) this._player.paused = v; }\n\n get animationTime(): number { return this._player?.animationTime ?? 0; }\n set animationTime(v: number) { if (this._player) this._player.animationTime = v; }\n\n get animationDuration(): number { return this._player?.animationDuration ?? 0; }\n\n /**\n * Crossfade progress in `[0, 1]`. `0` when no crossfade is active; `1`\n * once the active crossfade has fully blended into the target animation.\n */\n get crossfadeProgress(): number { return this._player?.crossfadeProgress ?? 0; }\n\n get frameRate(): number { return this._player?.frameRate ?? 30; }\n set frameRate(v: number) { if (this._player) this._player.frameRate = v; }\n\n /** Playback-speed multiplier (`1` = author speed). Scales how fast the\n * active clip advances without touching its authored frame rate or\n * crossfade timing. See {@link AnimationPlayer.playbackSpeed}. */\n get playbackSpeed(): number { return this._player?.playbackSpeed ?? 1; }\n set playbackSpeed(v: number) { if (this._player) this._player.playbackSpeed = v; }\n\n hasAnimation(animName: string): boolean {\n return !!this._engine?.skeletalAnimationLibrary.get(animName);\n }\n\n /**\n * Bone names from the attached engine's skeleton library, or an empty array\n * if the armature isn't bound yet. Consumers that need bone-name lookup\n * (bone-tracked colliders, attachments, debug overlays) read from here\n * instead of reaching into private armature state.\n */\n get boneNames(): readonly string[] {\n return this.armatureData.boneNames ?? this._engine?.skeletonLibrary?.boneNames ?? [];\n }\n\n /**\n * Bone names matching THIS armature's rig size. {@link boneNames} always\n * returns the 86-bone std-male list; the 441-bone facial rig has its own\n * name table (`boneNames441`). Name-keyed per-bone features (bone stretch,\n * body-part classification) must use this accessor or they silently\n * misclassify every bone on the large rig.\n */\n get rigBoneNames(): readonly string[] {\n if (this.armatureData.boneNames) return this.armatureData.boneNames;\n const lib = this._engine?.skeletonLibrary;\n if (this.numBones === 441 && lib?.boneNames441) return lib.boneNames441;\n return lib?.boneNames ?? [];\n }\n\n /** The engine this armature is attached to, or `null` if not yet attached. */\n get engine(): SplatEngine | null { return this._engine; }\n\n /** The skeleton owned by this armature (rest pose, parents, bind data). */\n get skeleton(): Skeleton { return this._skeleton; }\n\n /**\n * Live reference to the per-bone world-transform array filled in by\n * the most recent {@link update}. Same Mat4 instances are reused\n * across frames - callers may hold the array reference and re-read,\n * or call {@link getBoneWorldMatrix} for a single bone. Empty until\n * the first update.\n */\n get boneWorldMatrices(): readonly Mat4[] { return this._worldTransforms; }\n\n /** Index of the pelvis bone (a Mixamo `Hips` counts), or -1 for none. */\n get pelvisBoneIndex(): number {\n // Resolved against the scene's skeleton library, so not before it has one.\n if (this._pelvisBoneIndex === -2 && this._engine) this._resolveRigIndices();\n return Math.max(-1, this._pelvisBoneIndex);\n }\n\n /**\n * Sample the world-space POSITION of selected bones at an explicit animation\n * frame time, writing `x, y, z` triples into `out` in the order the indices\n * were given. `out` must hold at least `boneIndices.length * 3` numbers; an\n * out-of-range index writes zeroes.\n *\n * This is the precompute probe. {@link Armature.update} is the wrong tool for\n * sweeping a clip: it advances time, it pushes to linked splats, and it bails\n * out before evaluating anything at all when the character is outside the\n * camera frustum - so an off-screen character cannot be measured through it.\n * This call skips culling and skinning entirely, leaves playback state\n * untouched (time, crossfade, event cursor), and can be run for every frame of\n * a clip back to back.\n *\n * The same rig-convention clamps the live path applies (pelvis X/Z to bind,\n * pelvis-Y lock, root-bone translation / scale clamp) are applied to the\n * probed pose, so sampled positions line up with rendered ones - the clip's\n * root ORIENTATION is preserved in both, so a sweep and the render agree on\n * which way the character faces. Root-motion ROUTING is deliberately\n * not run: probing must not move the entity or feed the extract accumulator.\n * {@link poseModifier} is not run either - see the note on that type.\n *\n * Positions include the pivot's current world transform, so they are in the\n * same world space {@link getBoneWorldMatrix} reports. The pelvis X/Z clamp\n * means what a sweep measures is the clip's IN-PLACE motion, whatever\n * {@link rootMotionMode} is doing to the entity live.\n *\n * Plain numbers cross the boundary on purpose: consumers can sweep a clip\n * without depending on PlayCanvas types.\n *\n * Returns `false` when the armature is not attached to a scene or no animation\n * is active.\n */\n probeBoneWorldPositions(\n frameTime: number,\n boneIndices: readonly number[],\n out: Float32Array | number[],\n ): boolean {\n if (!this._player) return false;\n this._resolveRigIndices();\n if (!this._probePose) this._probePose = new Pose(this.numBones);\n const pose = this._probePose;\n if (!this._player.evaluateAt(frameTime, pose)) return false;\n this._clampPoseToRigConventions(pose);\n this._skeleton.applyLocal(pose, this._worldTransform(), this._probeTransforms);\n\n for (let i = 0; i < boneIndices.length; i++) {\n const bi = boneIndices[i];\n const m = bi >= 0 && bi < this.numBones ? this._probeTransforms[bi] : null;\n out[i * 3] = m ? m.data[12] : 0;\n out[i * 3 + 1] = m ? m.data[13] : 0;\n out[i * 3 + 2] = m ? m.data[14] : 0;\n }\n return true;\n }\n\n /**\n * Evaluate the active clip at an explicit frame time into `outPose`, with no\n * crossfade and no playback-state mutation. The pose-level counterpart of\n * {@link probeBoneWorldPositions}: parent-local TRS rather than world\n * positions, for callers that want to blend toward a sampled pose (a loop\n * seam) rather than measure one.\n *\n * The rig-convention clamps are applied, matching what the live path renders.\n * Returns `false` when no animation is active.\n */\n probePose(frameTime: number, outPose: Pose): boolean {\n if (!this._player) return false;\n this._resolveRigIndices();\n if (!this._player.evaluateAt(frameTime, outPose)) return false;\n this._clampPoseToRigConventions(outPose);\n return true;\n }\n\n /**\n * Snap any active crossfade to its terminal state (target pose fully\n * applied) on the next {@link Armature.update}. Useful when scrubbing\n * through animation frames for precompute, where the per-frame pose\n * needs to be the pure animation evaluation without crossfade blend.\n */\n endCrossfade(): void {\n this._player?.endCrossfade();\n }\n\n /**\n * Return the world-space transform of bone `boneIdx` as computed by the\n * most recent {@link Armature.update}. Returns a live reference into the\n * armature's internal array - callers must not mutate it; copy first if\n * you need to retain.\n *\n * Returns `null` if `boneIdx` is out of range, or if the bone transform\n * array has not been populated yet (no `update()` has run, or the armature\n * isn't attached to an engine).\n *\n * Used by per-bone attachments - bone-tracked colliders, weapon GLBs\n * mounted to a bone, particle emitters following a bone, etc.\n */\n getBoneWorldMatrix(boneIdx: number): Mat4 | null {\n if (boneIdx < 0 || boneIdx >= this.numBones) return null;\n return this._worldTransforms[boneIdx] ?? null;\n }\n\n /**\n * Recompose the bone world-transform array from the current pose and entity\n * transform immediately, bypassing the frustum/LOD gates that {@link update}\n * applies. Use when you need {@link boneWorldMatrices} to reflect a fresh\n * entity transform *right now* even if the armature is off-screen - e.g. after\n * teleporting a character to a spot the camera isn't looking at and then\n * sampling its bones (building a ragdoll, snapping an attachment). No-op if the\n * armature isn't attached to a scene yet.\n */\n refreshBoneTransforms(): void {\n if (!this._skinning) return;\n this._skeleton.applyLocal(\n this._currentPose,\n this._worldTransform(),\n this._worldTransforms,\n );\n }\n\n /**\n * Evaluate the playing clip and push the pose to the splats NOW, bypassing\n * every {@link update} throttle (rate divider, frustum gate, animation LOD).\n * Call after reactivating or teleporting a pooled character, so its first\n * visible frame shows the clip instead of the stale pose the throttles left\n * (often the bind pose). The full form of {@link refreshBoneTransforms},\n * which only recomposes the bone matrices from the current pose. Runs the\n * layers and {@link poseModifier} with `dt` 0. No-op with no clip or\n * before the armature has splats.\n */\n forcePoseRefresh(): void {\n if (!this._player || !this._skinning) return;\n this._resolveRigIndices();\n this._player.evaluate(this._currentPose);\n if (this._layers.size > 0) this._evaluateLayers(0);\n this.poseModifier?.(this._currentPose, this, 0);\n this._applyRigPostClamps();\n this._skeleton.applyLocal(this._currentPose, this._worldTransform(), this._worldTransforms);\n this._skinning.pushTransforms(this._worldTransforms, this._worldTransform());\n }\n\n /**\n * Name of the currently-playing animation, or `null` if no animation is\n * active. Mirrors {@link AnimationPlayer.currentAnimationName}.\n */\n get currentAnimationName(): string | null {\n return this._player?.currentAnimationName ?? null;\n }\n\n /**\n * Subscribe to frame-aligned {@link AnimationEvent}s on the currently-\n * playing animation. Events come from the active animation's\n * {@link Animation.events} array; the engine doesn't interpret `name` or\n * `payload` - games define their own vocabulary and route inside the\n * callback.\n *\n * Listeners are kept across animation switches; one subscription is enough\n * for the armature's lifetime. Returns an unsubscribe handle.\n */\n onAnimEvent(cb: AnimEventCallback): () => void {\n return this._player?.onAnimEvent(cb) ?? (() => {});\n }\n\n // \u2500\u2500 Playback verbs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Start playing an animation immediately (no crossfade). Restarts from\n * frame 0. Returns `false` if not registered, or if the armature isn't\n * attached to an engine yet.\n *\n * Passing `rootMotion: true` sets {@link rootMotionMode} to `'apply'`;\n * passing `false` sets it to `'off'`. For `'extract'`, set the mode\n * separately and pass `rootMotion: false` (or omit) here - the per-clip\n * flag is just a convenience shortcut for the common case.\n */\n playAnimation(animName: string, rootMotion = false, loop = true): boolean {\n if (!this._player) return false;\n this.rootMotion = rootMotion;\n this._hasLastPelvis = false; // hard switch - pelvis pose discontinuity\n return this._player.play(animName, { loop });\n }\n\n /**\n * Crossfade from the current pose to a new animation over `opts.duration`\n * seconds. Snapshots current bone poses, then blends toward the new\n * animation target. Pelvis motion stays continuous across the blend.\n *\n * `opts.rootMotion` is mapped to {@link rootMotionMode} the same way as\n * {@link playAnimation}.\n */\n crossfadeTo(\n animName: string,\n opts?: { duration?: number; rootMotion?: boolean; loop?: boolean; preserveTime?: boolean; continueSource?: boolean; easing?: 'linear' | 'smoothstep' },\n ): boolean {\n if (!this._player) return false;\n this.rootMotion = opts?.rootMotion ?? false;\n // Crossfade is a smooth pose blend - _hasLastPelvis stays valid, so the\n // pelvis delta on the first cross-fade frame is the small differential\n // between the snapshot pelvis and the (blended) target pelvis.\n return this._player.crossfadeTo(animName, this._currentPose, opts);\n }\n\n // \u2500\u2500 Animation layers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Play `animName` on the named overlay layer, gated to `mask`'s bone set.\n * Layers compose on top of the base animation in {@link update} - for each\n * bone in the mask, the current pose is interpolated toward the overlay's\n * pose by the layer weight.\n *\n * Creates the layer lazily on first use (allocates a per-layer\n * {@link AnimationPlayer} sharing the same skeleton and animation provider\n * as the base). Subsequent calls reuse the same player.\n */\n playLayerAnimation(\n layerName: string,\n animName: string,\n mask: BoneMask,\n opts?: { loop?: boolean; crossfade?: number; weight?: number },\n ): boolean {\n if (!this._provider) return false;\n let layer = this._layers.get(layerName);\n if (!layer) {\n const snapshot = new Pose(this.numBones);\n snapshot.setToBind(this._skeleton.bindT, this._skeleton.bindR);\n const player = new AnimationPlayer({\n skeleton: this._skeleton,\n animationProvider: this._provider,\n snapshotPose: snapshot,\n });\n const pose = new Pose(this.numBones);\n pose.setToBind(this._skeleton.bindT, this._skeleton.bindR);\n layer = { player, mask: mask.boneIndices, pose, snapshot, weight: opts?.weight ?? 1 };\n this._layers.set(layerName, layer);\n } else {\n layer.mask = mask.boneIndices;\n if (opts?.weight !== undefined) layer.weight = opts.weight;\n layer.fadingOut = undefined;\n }\n const loop = opts?.loop ?? true;\n const xf = opts?.crossfade ?? 0;\n return xf > 0\n ? layer.player.crossfadeTo(animName, layer.pose, { duration: xf, loop })\n : layer.player.play(animName, { loop });\n }\n\n /** Set the overlay weight for a layer in `[0, 1]`. No-op if the layer doesn't exist. */\n setLayerWeight(layerName: string, weight: number): void {\n const l = this._layers.get(layerName);\n if (l) {\n l.weight = Math.max(0, Math.min(1, weight));\n l.fadingOut = undefined;\n }\n }\n\n /**\n * Pause or resume every active overlay layer. The base animation is\n * controlled separately via {@link paused}. Useful so a single play/pause\n * toggle in an editor or pause menu freezes the whole stack together.\n */\n setAllLayersPaused(paused: boolean): void {\n for (const layer of this._layers.values()) {\n layer.player.paused = paused;\n }\n }\n\n /**\n * Stop and remove the named layer. With `fadeDuration > 0`, ramps the\n * layer weight to zero over `fadeDuration` seconds before tearing down.\n */\n stopLayer(layerName: string, fadeDuration = 0): void {\n const l = this._layers.get(layerName);\n if (!l) return;\n if (fadeDuration <= 0) {\n this._layers.delete(layerName);\n return;\n }\n l.fadingOut = { from: l.weight, t: 0, duration: fadeDuration };\n }\n\n /** Stop with optional crossfade back to rest pose. */\n stop(fadeDuration = 0): void {\n if (!this._player) return;\n if (fadeDuration > 0 && this._player.isPlaying) {\n this._player.stop(this._currentPose, fadeDuration);\n return;\n }\n this._player.stop(this._currentPose, 0);\n this._currentPose.setToBind(this._skeleton.bindT, this._skeleton.bindR);\n this._hasLastPelvis = false; // hard stop - pelvis snaps to bind\n this._pushPose();\n }\n\n // \u2500\u2500 Per-frame update \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Advance animation time by `dt` seconds, evaluate pose, and push bone\n * transforms to linked splats. Called for you by `engine.update()` unless auto-update is detached.\n */\n update(dt: number): void {\n if (!this._player || !this._skinning) return;\n\n // External pose-provider path: animation is fully replaced. The\n // provider writes the pose; the skinning pipeline (LOD's frustum\n // cull, applyLocal, push-transforms) is unchanged. Animation-LOD\n // strides and the player tick are bypassed - providers handle\n // their own throttling if they need to.\n if (this._poseProvider) {\n if (!this._drivenNodes && !this._skinning.anyVisible(this._cameraFrustum())) return;\n this._poseProvider.writePose(this._currentPose, this, dt);\n this._skeleton.applyLocal(\n this._currentPose,\n this._worldTransform(),\n this._worldTransforms,\n );\n this._skinning.pushTransforms(\n this._worldTransforms,\n this._worldTransform(),\n this.skipPositions,\n );\n this._writeDrivenNodes();\n return;\n }\n\n // Always advance animation time so clip timing / events stay correct\n // even on LOD-throttled frames.\n // Layers share the base clip's clock.\n const animDt = Math.min(dt, this.maxAnimDt);\n const { wrapped } = this._player.tick(animDt);\n if (wrapped) this._hasLastPelvis = false;\n\n // Four layered throttles, cheapest-first, each an early-out. Animation\n // time already advanced above, so every skip just freezes the rendered\n // pose at its last evaluated value - clip timing / events stay correct.\n //\n // 1. Manual escape hatch: caller-driven hard skip (fps-adaptive, etc).\n if (this.skipPose) return;\n\n // 2. Manual rate divider: do the heavy work every Nth call only.\n if (this.updateInterval > 1) {\n this._updateAccumDt += dt;\n if (++this._updateCounter < this.updateInterval) return;\n this._updateCounter = 0;\n this._updateAccumDt = 0;\n }\n\n // 3. Off-screen: skip skinning entirely (frustum gate). With root motion\n // the pose places the body, so it is still evaluated and only the push\n // is gated, below - else an off-screen body never walks into view.\n const gated = !this._drivenNodes;\n const placesBody = this._rootMotionMode !== 'off';\n if (gated && !placesBody && !this._skinning.anyVisible(this._cameraFrustum())) return;\n\n // 4. Distance LOD: throttle by camera distance (off by default; armature\n // opts in via setAnimationLod). On throttled frames the pose stays\n // frozen until the next due frame.\n this._lodFrameCounter++;\n const stride = this._lodStride();\n if (stride > 1 && this._lodFrameCounter % stride !== 0) return;\n\n this._resolveRigIndices();\n const order = this._evaluatedOrder;\n this._player.evaluate(this._currentPose);\n if (this._layers.size > 0) this._evaluateLayers(animDt);\n // Last word on the pose before the rig conventions clamp it and the\n // hierarchy is composed, so a modifier sees the fully blended animation and\n // cannot violate the pelvis / root clamps.\n if (this.poseModifier) this.poseModifier(this._currentPose, this, animDt);\n this._applyRigPostClamps();\n // Bone matrices stay current for attachments and pelvis reads; only the\n // per-splat push is worth skipping. Tested where root motion just put it.\n this._skeleton.applyLocal(this._currentPose, this._worldTransform(), this._worldTransforms, order);\n if (gated && placesBody && !this._skinning.anyVisible(this._cameraFrustum())) return;\n\n // Reaching here means the pose is actually being pushed. Stamp the engine's\n // frame marker so pose-mirroring consumers (PixelartEffect's mask camera)\n // know a character moved this frame and a mask rebuild is warranted. On\n // throttled or off-screen frames we return early above and never stamp,\n // so the mask consumer can skip its rebuild entirely.\n if (this._engine) this._engine.characterPoseUpdatedFrame = this._engine.frame;\n\n // Sort LOD: independent of anim LOD, decides per-frame whether to skip\n // the expensive CPU sort re-upload. ORs with the manual `skipPositions`\n // flag so callers can hard-force a skip regardless of LOD bands.\n const skipPos = this.skipPositions || this._sortLodSkipThisFrame();\n this._skinning.pushTransforms(this._worldTransforms, this._worldTransform(), skipPos);\n this._writeDrivenNodes(order);\n }\n\n // \u2500\u2500 Internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Resolve named rig conventions once skeleton library is available.\n * If `boneNames` is present, looks up \"root\" and any name containing\n * \"pelvis\" (or a Mixamo-style \"Hips\"); otherwise falls back to bone index 0\n * as root. The rig's own names win over the scene library's.\n */\n private _resolveRigIndices(): void {\n if (this._pelvisBoneIndex !== -2) return;\n this._rootBoneIndex = -1;\n this._pelvisBoneIndex = -1;\n const boneNames = this.armatureData.boneNames ?? this._engine?.skeletonLibrary?.boneNames;\n if (boneNames && boneNames.length > 0) {\n for (let i = 0; i < this.numBones; i++) {\n const name = boneNames[i]?.toLowerCase();\n if (!name) continue;\n if (name === 'root') this._rootBoneIndex = i;\n if (this._pelvisBoneIndex < 0 && isPelvisName(name)) this._pelvisBoneIndex = i;\n }\n } else {\n this._rootBoneIndex = 0;\n }\n }\n\n /**\n * Advance every overlay layer's clock, crossfade and fade-out by `dt`\n * without evaluating. {@link update} does this itself; call it directly\n * when driving the pose with `update(0)` (e.g. an editor scrubbing the base\n * clip), or the layers never move.\n */\n tickLayers(dt: number): void {\n for (const [name, layer] of this._layers) {\n layer.player.tick(dt);\n if (layer.fadingOut) {\n layer.fadingOut.t += dt;\n const k = Math.min(1, layer.fadingOut.t / layer.fadingOut.duration);\n layer.weight = layer.fadingOut.from * (1 - k);\n if (k >= 1) this._layers.delete(name);\n }\n }\n }\n\n /**\n * Compose overlay layers onto `_currentPose`. Each layer ticks its own\n * player, evaluates a full pose into a scratch buffer, then per masked\n * bone interpolates the current pose toward the overlay by the layer\n * weight. Runs before `_applyRigPostClamps` so pelvis/root clamps stay\n * authoritative.\n */\n private _evaluateLayers(dt: number): void {\n this.tickLayers(dt);\n const out = this._currentPose;\n const lp = out.positions, lr = out.rotations, ls = out.scales;\n const tmpQ = this._layerTmpQ;\n for (const layer of this._layers.values()) {\n layer.player.evaluate(layer.pose);\n const w = layer.weight;\n if (w <= 0) continue;\n\n const op = layer.pose.positions, or = layer.pose.rotations, os = layer.pose.scales;\n const mask = layer.mask;\n for (let i = 0; i < mask.length; i++) {\n const bi = mask[i];\n lp[bi].lerp(lp[bi], op[bi], w);\n tmpQ.copy(or[bi]);\n if (lr[bi].dot(tmpQ) < 0) tmpQ.mulScalar(-1);\n lr[bi].slerp(lr[bi], tmpQ, w);\n ls[bi].lerp(ls[bi], os[bi], w);\n }\n }\n }\n\n /**\n * Apply rig-convention rules to the freshly-evaluated pose:\n * - root-motion routing - `'apply'` writes `baseline + (pelvis \u2212 bind)`\n * to the pivot; `'extract'` accumulates the per-frame pelvis \u0394;\n * `'off'` does nothing.\n * - the {@link rootOffsetProvider} correction, composed on top of whatever\n * routing produced.\n * - pelvis X/Z clamp to bind in bone space (always - the motion lives on\n * the pivot / in the consumed delta, not on the bone).\n * - pelvis-Y lock to bind (when {@link lockPelvisY} is set).\n * - root-bone translation / scale clamp to bind.\n */\n private _applyRigPostClamps(): void {\n const bindT = this._skeleton.bindT;\n const pose = this._currentPose;\n const pelvisIdx = this._pelvisBoneIndex;\n const off = this.rootOffsetProvider\n ? this.rootOffsetProvider(this._player?.animationTime ?? 0)\n : null;\n\n if (pelvisIdx >= 0) {\n const pelvisPos = pose.positions[pelvisIdx];\n\n if (this._rootMotionMode === 'apply') {\n const base = this._baseLocalPosition;\n const o = this._pelvisOffsetToEntitySpace(\n pose,\n pelvisPos.x - bindT[pelvisIdx * 3],\n pelvisPos.z - bindT[pelvisIdx * 3 + 2],\n );\n const ox = o.x;\n const oz = o.z;\n if (off) {\n // Absolute write off the base every frame, so a per-frame offset can\n // never accumulate into itself.\n this.object3D.position.set(base.x + ox + off.x, base.y + off.y, base.z + oz + off.z);\n } else {\n const cur = this.object3D.position;\n cur.set(base.x + ox, cur.y, base.z + oz);\n }\n } else if (this._rootMotionMode === 'extract') {\n if (this._hasLastPelvis) {\n const d = this._pelvisOffsetToEntitySpace(\n pose,\n pelvisPos.x - this._lastPelvisPos.x,\n pelvisPos.z - this._lastPelvisPos.z,\n );\n this._rootMotionAccumDx += d.x;\n this._rootMotionAccumDz += d.z;\n }\n this._lastPelvisPos.copy(pelvisPos);\n this._hasLastPelvis = true;\n }\n }\n\n // 'off' / 'extract' leave the entity alone, so the offset is the only thing\n // writing it - still absolute, still off the base.\n if (off && this._rootMotionMode !== 'apply') {\n const base = this._baseLocalPosition;\n this.object3D.position.set(base.x + off.x, base.y + off.y, base.z + off.z);\n }\n\n this._clampPoseToRigConventions(pose);\n }\n\n /**\n * Take a horizontal pelvis offset measured in BONE space and return it in the\n * entity's parent space, which is where {@link consumeRootMotionDelta} and the\n * `'apply'` entity write both promise to deliver it.\n *\n * The pelvis is a child of the root bone, so its parent-local X/Z live in the\n * root's frame, not the entity's. Those two frames coincide only while the\n * root's rotation is identity - which used to be guaranteed by the root clamp\n * resetting rotation, and is no longer: a clip whose root carries a yaw (every\n * MetaHuman GLB preset carries a constant 180\u00B0) now keeps it, so the offset has\n * to be rotated to stay in the frame the contract names. Rotating by identity\n * is a no-op, so clips whose root is identity - every `.anim`, whose root\n * rotation `Animation.parse` resets - route exactly as before.\n *\n * Y is deliberately dropped on the way in: root motion is a ground-plane\n * concept here, and the caller only ever reads X/Z back out.\n *\n * Returns a reused scratch vector - read it immediately, do not retain.\n */\n private _pelvisOffsetToEntitySpace(pose: Pose, x: number, z: number): Vec3 {\n const out = this._rootMotionTmp.set(x, 0, z);\n const rootIdx = this._rootBoneIndex;\n if (rootIdx >= 0 && !this.legacyRootRotation) pose.rotations[rootIdx].transformVector(out, out);\n return out;\n }\n\n /**\n * Pelvis X/Z (and optionally Y) plus root-bone clamps - the bone-space half of\n * the rig conventions, with no routing side effects. Shared by the live update\n * and by the probes, which must not move the entity.\n *\n * The root bone is pinned to its bind TRANSLATION and to unit scale, so a clip\n * cannot slide or resize the whole character behind the pelvis clamp's back:\n * root translation would move the character in world space without ever\n * showing up in the pelvis delta that root-motion routing measures, and the\n * \"in-place\" guarantee this method and the probes advertise would be a lie.\n *\n * Its ROTATION is deliberately left alone. A yaw on the root is orientation,\n * not motion - it is how a clip states which way the character faces, and it\n * is constant for the whole clip in every artifact we ship (all 57 MetaHuman\n * GLB presets carry exactly 180\u00B0 about Y; a `.anim`'s root is reset to\n * identity at parse, see `clearAnimRootRotation`).\n * Resetting it used to delete that statement and render preset clips facing\n * backwards. What the reset was really protecting - pelvis bone space and\n * entity space agreeing - is kept by {@link _pelvisOffsetToEntitySpace}\n * instead, which is the frame conversion the routing actually needed.\n *\n * Under {@link legacyRootRotation} (a `SplatEngine`'s default) the rotation\n * is still pinned to bind, as in 0.1.1, so existing apps keep their facing.\n */\n private _clampPoseToRigConventions(pose: Pose): void {\n const bindT = this._skeleton.bindT;\n const pelvisIdx = this._pelvisBoneIndex;\n const rootIdx = this._rootBoneIndex;\n\n if (pelvisIdx >= 0) {\n const pelvisPos = pose.positions[pelvisIdx];\n pelvisPos.x = bindT[pelvisIdx * 3];\n pelvisPos.z = bindT[pelvisIdx * 3 + 2];\n if (this._lockPelvisY) pelvisPos.y = bindT[pelvisIdx * 3 + 1];\n }\n\n if (rootIdx >= 0) {\n pose.positions[rootIdx].set(bindT[rootIdx * 3], bindT[rootIdx * 3 + 1], bindT[rootIdx * 3 + 2]);\n if (this.legacyRootRotation) {\n const bindR = this._skeleton.bindR;\n pose.rotations[rootIdx].set(bindR[rootIdx * 4], bindR[rootIdx * 4 + 1], bindR[rootIdx * 4 + 2], bindR[rootIdx * 4 + 3]);\n }\n pose.scales[rootIdx].set(1, 1, 1);\n }\n }\n\n /**\n * Apply runtime bone scaling. Each entry scales a bone's flesh + segment in\n * its own frame - `{ along, width, thickness }` (each defaulting to `1`), or\n * a bare number for uniform scale. e.g. `{ thigh_l: { along: 1.3 }, calf_l:\n * { along: 1.3 } }` \u2192 a 1.3\u00D7 longer left leg; `{ upperarm_l: { width: 1.4,\n * thickness: 1.4 } }` \u2192 a beefier arm. Bones not listed stay at `1`. Pass\n * `null` to clear. Works for any bone set (limbs, spine, \u2026); see\n * {@link computeBoneStretch} for the model. Recompute only when factors\n * change - the result is applied every frame by the skeleton + skinning.\n */\n setBoneStretch(factors: Record<string, BoneScaleInput> | null): void {\n if (!factors) {\n this._skeleton.lengthScale = null;\n this._skinning?.setCovStretch(null);\n return;\n }\n const { lengthScale, covStretch, any } = computeBoneStretch(\n this._skeleton,\n this.rigBoneNames,\n factors,\n );\n this._skeleton.lengthScale = any ? lengthScale : null;\n this._skinning?.setCovStretch(any ? covStretch : null);\n }\n\n /** Push the current pose through skeleton + skinning. Called at link time. */\n private _pushPose(): void {\n if (!this._skinning) return;\n this._skeleton.applyLocal(this._currentPose, this._worldTransform(), this._worldTransforms);\n this._skinning.pushTransforms(this._worldTransforms, this._worldTransform());\n this._writeDrivenNodes();\n }\n\n /**\n * World transforms onto the driven nodes, parents first so each write reads\n * an already-placed parent. Rotation is taken scale-free; each node keeps its\n * own local scale.\n */\n private _writeDrivenNodes(bones?: Int32Array | null): void {\n const nodes = this._drivenNodes;\n if (!nodes) return;\n const count = bones ? bones.length : nodes.length;\n for (let k = 0; k < count; k++) {\n const i = bones ? bones[k] : k;\n const m = this._worldTransforms[i];\n const node = nodes[i];\n const t = m.getTranslation(this._nodeTmpV);\n const q = this._nodeTmpQ.setFromMat4(m);\n _nodeWorld.compose(_nodePos.set(t.x, t.y, t.z), _nodeQuat.set(q.x, q.y, q.z, q.w), _unitScale);\n if (node.parent) _nodeWorld.premultiply(_nodeParentInv.copy(node.parent.matrixWorld).invert());\n _nodeWorld.decompose(node.position, node.quaternion, _nodeScale);\n node.updateMatrixWorld();\n }\n }\n\n private _cameraFrustum(): Frustum | undefined {\n return this._engine?.cameraFrustum;\n }\n\n /**\n * The pivot's world matrix in the skeletal core's own matrix type. Refreshes\n * the three.js world matrix first, so a transform set this frame is seen\n * this frame.\n */\n private _worldTransform(): Mat4 {\n this.object3D.updateWorldMatrix(true, false);\n return this._worldMatrix.setFromArray(this.object3D.matrixWorld.elements);\n }\n\n /**\n * Squared distance from the pivot's world origin to the engine camera, or\n * `null` when the engine has no camera. Drives the distance-LOD bands.\n * @internal\n */\n cameraDistanceSq(): number | null {\n const camPos = this._engine?.cameraWorldPosition;\n if (!camPos) return null;\n this.object3D.updateWorldMatrix(true, false);\n const e = this.object3D.matrixWorld.elements;\n const dx = e[12] - camPos.x;\n const dy = e[13] - camPos.y;\n const dz = e[14] - camPos.z;\n return dx * dx + dy * dy + dz * dz;\n }\n\n /**\n * Enable / configure distance-based animation LOD for THIS armature.\n * LOD is off by default (full rate); calling this is the opt-in.\n *\n * - **No args**: pull the engine's `animLodPreset` (set via\n * `SplatEngine.animLodPreset`). If the engine has no preset, fall back to a\n * built-in default (full rate \u226412 m, every-2nd \u226424 m, every-4th\n * beyond). Typical gameplay use: set the preset once, then call\n * `armature.setAnimationLod()` on each throttle-able character.\n * - **Partial opts**: tweak individual knobs on top of current values.\n *\n * `nearDist` / `farDist` are world-space distances (m) from the camera;\n * `nearStride` / `farStride` are frames-per-update in the mid / far\n * bands. A stride of 1 means every frame.\n */\n setAnimationLod(opts?: {\n nearDist?: number;\n farDist?: number;\n nearStride?: number;\n farStride?: number;\n }): void {\n // No-arg form: seed from the engine preset (or the built-in fallback),\n // then continue so any explicit knobs below can still override.\n const resolved = opts ?? this._engine?.animLodPreset ?? DEFAULT_ANIM_LOD_PRESET;\n if (resolved.nearDist !== undefined) this._lodNearDist = resolved.nearDist;\n if (resolved.farDist !== undefined) this._lodFarDist = resolved.farDist;\n if (resolved.nearStride !== undefined) this._lodNearStride = Math.max(1, Math.floor(resolved.nearStride));\n if (resolved.farStride !== undefined) this._lodFarStride = Math.max(1, Math.floor(resolved.farStride));\n }\n\n /** Disable LOD throttling - every character animates at full rate\n * regardless of distance (frustum cull still applies). */\n disableAnimationLod(): void {\n this._lodNearDist = Infinity;\n this._lodFarDist = Infinity;\n }\n\n /**\n * Enable / configure distance-based SORT LOD for THIS armature.\n *\n * Throttles only the CPU-side `splat.updatePositions` call (the dominant\n * cost - ~88% of per-character CPU at high counts) without freezing the\n * rendered pose. On throttled frames the GPU palette still uploads, so\n * animation looks correct; only the depth-sort order lags one frame.\n *\n * Composes with {@link setAnimationLod} - when anim LOD throttles a\n * frame, sort LOD is moot for that frame; when anim LOD evaluates, sort\n * LOD can independently decide to skip the positions push.\n *\n * Typical use: tighter near band than anim LOD (e.g. 5\u201310 m) so even\n * mid-distance characters skip the sort re-upload most frames.\n *\n * - **No args**: enable with a built-in default\n * (nearDist=5, farDist=15, nearStride=2, farStride=4).\n * - **Partial opts**: tweak individual knobs on top of current values.\n */\n setSortLod(opts?: {\n nearDist?: number;\n farDist?: number;\n nearStride?: number;\n farStride?: number;\n }): void {\n const defaults = { nearDist: 5, farDist: 15, nearStride: 2, farStride: 4 };\n const resolved = opts ?? defaults;\n if (resolved.nearDist !== undefined) this._sortLodNearDist = resolved.nearDist;\n if (resolved.farDist !== undefined) this._sortLodFarDist = resolved.farDist;\n if (resolved.nearStride !== undefined) this._sortLodNearStride = Math.max(1, Math.floor(resolved.nearStride));\n if (resolved.farStride !== undefined) this._sortLodFarStride = Math.max(1, Math.floor(resolved.farStride));\n }\n\n /** Disable sort LOD - every character does the full updatePositions\n * every frame (still gated by `skipPositions` and anim LOD). */\n disableSortLod(): void {\n this._sortLodNearDist = Infinity;\n this._sortLodFarDist = Infinity;\n }\n\n /** Frames-per-update for this armature this frame, based on camera\n * distance. 1 = full rate. Returns 1 when no camera is available so\n * we never freeze a character due to missing engine state. */\n private _lodStride(): number {\n // The pivot's world origin is a good-enough \"where is this body\" proxy for\n // a distance bucket - no need for the AABB center.\n const distSq = this.cameraDistanceSq();\n if (distSq === null) return 1;\n if (distSq >= this._lodFarDist * this._lodFarDist) return this._lodFarStride;\n if (distSq >= this._lodNearDist * this._lodNearDist) return this._lodNearStride;\n return 1;\n }\n\n /** True when sort LOD says \"skip the CPU positions re-upload this frame\".\n * Uses the same camera-distance bands shape as anim LOD, but a separate\n * counter so the two strides don't lock-step. */\n private _sortLodSkipThisFrame(): boolean {\n const distSq = this.cameraDistanceSq();\n if (distSq === null) return false;\n let stride = 1;\n if (distSq >= this._sortLodFarDist * this._sortLodFarDist) stride = this._sortLodFarStride;\n else if (distSq >= this._sortLodNearDist * this._sortLodNearDist) stride = this._sortLodNearStride;\n if (stride <= 1) return false;\n this._sortLodFrameCounter++;\n return this._sortLodFrameCounter % stride !== 0;\n }\n}\n\nconst _EMPTY_SET: Set<Splat> = new Set();\n\ninterface AnimationLayer {\n player: AnimationPlayer;\n mask: Int32Array;\n pose: Pose;\n snapshot: Pose;\n weight: number;\n fadingOut?: { from: number; t: number; duration: number };\n}\n\nconst _nodeWorld = new Matrix4();\nconst _nodeParentInv = new Matrix4();\nconst _nodePos = new Vector3();\nconst _nodeQuat = new Quaternion();\nconst _nodeScale = new Vector3();\nconst _unitScale = new Vector3(1, 1, 1);\n", "import { Mat4, Quat, Vec3 } from '../math';\n\n/**\n * Walk the rig's rest pose to produce world-space bind-pose matrices, one per\n * bone. Parents are expected to come before their children in index order (the\n * skeleton library's bone arrays satisfy this).\n *\n * Returns `null` if any of the three arrays is missing - the armature's\n * `armatureData` carries them as optional fields.\n */\nexport function computeBindPoseTransforms(\n numBones: number,\n restTranslations: Float32Array,\n restRotations: Float32Array,\n parents: Int32Array,\n): Mat4[] {\n const wt = Array.from({ length: numBones }, () => new Mat4());\n\n const tmpPos = new Vec3();\n const tmpRot = new Quat();\n const tmpScale = new Vec3(1, 1, 1);\n const tmpLocal = new Mat4();\n\n for (let i = 0; i < numBones; i++) {\n tmpPos.set(restTranslations[i * 3], restTranslations[i * 3 + 1], restTranslations[i * 3 + 2]);\n tmpRot.set(restRotations[i * 4], restRotations[i * 4 + 1], restRotations[i * 4 + 2], restRotations[i * 4 + 3]);\n tmpLocal.setTRS(tmpPos, tmpRot, tmpScale);\n\n const pi = parents[i];\n if (pi >= 0 && pi < numBones) {\n wt[i].mul2(wt[pi], tmpLocal);\n } else {\n wt[i].copy(tmpLocal);\n }\n }\n return wt;\n}\n\n/**\n * Compute the inverse of each matrix in `bindPose`. Returns a new array; the\n * input is left untouched.\n */\nexport function invertBindPose(bindPose: Mat4[]): Mat4[] {\n return bindPose.map((m) => {\n const inv = new Mat4();\n inv.copy(m);\n inv.invert();\n return inv;\n });\n}\n", "import { Quat } from '../math';\nimport type { Vec3 } from '../math';\n\n/**\n * Rest pose for a rig, stored as parallel arrays indexed by bone. An empty\n * `positions` array marks an uninitialized rest pose - the rest-relative\n * conversion functions pass poses through unchanged in that case.\n */\nexport interface RestPose {\n positions: Vec3[];\n rotations: Quat[];\n scales: Vec3[];\n}\n\n/** A bone-space transform: position, rotation (as quaternion), and scale. */\nexport interface BonePose {\n position: Vec3;\n rotation: Quat;\n scale: Vec3;\n}\n\nconst _conjScratch = new Quat();\n\n/**\n * Express `pose` relative to the bone's rest transform. Writes the result\n * into `out`. Safe to call with `out === pose` (in-place).\n *\n * If `boneIndex` is out of range or `rest` is uninitialized, `pose` is copied\n * to `out` unchanged.\n */\nexport function toRestRelative(\n boneIndex: number,\n pose: BonePose,\n rest: RestPose,\n out: BonePose,\n): void {\n if (boneIndex < 0 || boneIndex >= rest.positions.length) {\n if (out !== pose) {\n out.position.copy(pose.position);\n out.rotation.copy(pose.rotation);\n out.scale.copy(pose.scale);\n }\n return;\n }\n const restPos = rest.positions[boneIndex];\n const restRot = rest.rotations[boneIndex];\n const restScale = rest.scales[boneIndex];\n\n // out.position = pose.position - restPos\n out.position.sub2(pose.position, restPos);\n // out.rotation = conj(restRot) * pose.rotation\n _conjScratch.copy(restRot).conjugate();\n out.rotation.mul2(_conjScratch, pose.rotation);\n // out.scale = pose.scale / restScale (component-wise, guarding divide-by-zero)\n out.scale.set(\n restScale.x !== 0 ? pose.scale.x / restScale.x : pose.scale.x,\n restScale.y !== 0 ? pose.scale.y / restScale.y : pose.scale.y,\n restScale.z !== 0 ? pose.scale.z / restScale.z : pose.scale.z,\n );\n}\n\n/**\n * Inverse of {@link toRestRelative}: compose a rest-relative `delta` back into\n * an absolute bone pose. Writes the result into `out`. Safe to call with\n * `out === delta` (in-place).\n */\nexport function fromRestRelative(\n boneIndex: number,\n delta: BonePose,\n rest: RestPose,\n out: BonePose,\n): void {\n if (boneIndex < 0 || boneIndex >= rest.positions.length) {\n if (out !== delta) {\n out.position.copy(delta.position);\n out.rotation.copy(delta.rotation);\n out.scale.copy(delta.scale);\n }\n return;\n }\n const restPos = rest.positions[boneIndex];\n const restRot = rest.rotations[boneIndex];\n const restScale = rest.scales[boneIndex];\n\n out.position.add2(restPos, delta.position);\n out.rotation.mul2(restRot, delta.rotation);\n out.scale.set(\n restScale.x * delta.scale.x,\n restScale.y * delta.scale.y,\n restScale.z * delta.scale.z,\n );\n}\n", "class CubicSpline {\n // control times\n times: number[];\n\n // control data: in-tangent, point, out-tangent\n knots: number[];\n\n // dimension of the knot points\n dim: number;\n\n // For looping splines built via fromPointsLooping, the original keyframe at\n // index i lives at spline segment i+2 (due to two ghost entries prepended).\n // Pass this offset to evaluateSegment when you already know the keyframe index.\n readonly keyframeOffset: number;\n\n constructor(times: number[], knots: number[], keyframeOffset = 0) {\n this.times = times;\n this.knots = knots;\n this.dim = knots.length / times.length / 3;\n this.keyframeOffset = keyframeOffset;\n }\n\n evaluate(time: number, result: number[]) {\n const { times } = this;\n const last = times.length - 1;\n\n if (time <= times[0]) {\n this.getKnot(0, result);\n } else if (time >= times[last]) {\n this.getKnot(last, result);\n } else {\n // Binary search: find largest seg where times[seg] <= time.\n let lo = 0, hi = last - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (time >= times[mid]) lo = mid;\n else hi = mid - 1;\n }\n this.evaluateSegment(\n lo,\n (time - times[lo]) / (times[lo + 1] - times[lo]),\n result,\n );\n }\n }\n\n getKnot(index: number, result: number[]) {\n const { knots, dim } = this;\n const idx = index * 3 * dim;\n for (let i = 0; i < dim; ++i) {\n result[i] = knots[idx + i * 3 + 1];\n }\n }\n\n evaluateSegment(segment: number, t: number, result: number[]) {\n const { knots, dim } = this;\n\n const t2 = t * t;\n const twot = t + t;\n const omt = 1 - t;\n const omt2 = omt * omt;\n\n let idx = segment * dim * 3;\n for (let i = 0; i < dim; ++i) {\n const p0 = knots[idx + 1];\n const m0 = knots[idx + 2];\n const m1 = knots[idx + dim * 3];\n const p1 = knots[idx + dim * 3 + 1];\n idx += 3;\n\n result[i] =\n p0 * ((1 + twot) * omt2) +\n m0 * (t * omt2) +\n p1 * (t2 * (3 - twot)) +\n m1 * (t2 * (t - 1));\n }\n }\n\n static calcKnots(times: number[], points: number[], smoothness: number) {\n const n = times.length;\n const dim = points.length / n;\n const knots: number[] = Array.from({ length: n * dim * 3 });\n\n for (let i = 0; i < n; i++) {\n const t = times[i];\n\n for (let j = 0; j < dim; j++) {\n const idx = i * dim + j;\n const p = points[idx];\n\n let tangent;\n if (i === 0) {\n tangent = (points[idx + dim] - p) / (times[i + 1] - t);\n } else if (i === n - 1) {\n tangent = (p - points[idx - dim]) / (t - times[i - 1]);\n } else {\n tangent =\n (points[idx + dim] - points[idx - dim]) /\n (times[i + 1] - times[i - 1]);\n }\n\n const inScale = i > 0 ? times[i] - times[i - 1] : times[1] - times[0];\n const outScale =\n i < n - 1 ? times[i + 1] - times[i] : times[i] - times[i - 1];\n\n knots[idx * 3] = tangent * inScale * smoothness;\n knots[idx * 3 + 1] = p;\n knots[idx * 3 + 2] = tangent * outScale * smoothness;\n }\n }\n\n return knots;\n }\n\n static fromPoints(times: number[], points: number[], smoothness = 1) {\n return new CubicSpline(\n times,\n CubicSpline.calcKnots(times, points, smoothness),\n 0,\n );\n }\n\n static fromPointsLooping(\n length: number,\n times: number[],\n points: number[],\n smoothness = 1,\n ) {\n if (times.length < 2) {\n return CubicSpline.fromPoints(times, points);\n }\n\n const dim = points.length / times.length;\n const newTimes = times.slice();\n const newPoints = points.slice();\n\n newTimes.push(length + times[0], length + times[1]);\n newPoints.push(...points.slice(0, dim * 2));\n\n newTimes.splice(\n 0,\n 0,\n times[times.length - 2] - length,\n times[times.length - 1] - length,\n );\n newPoints.splice(0, 0, ...points.slice(points.length - dim * 2));\n\n // keyframeOffset=2: two ghost entries are prepended, so keyframe[i] lives\n // at spline segment i+2. Callers that know the keyframe index can skip the\n // segment search by calling evaluateSegment(i + 2, t, result) directly.\n return new CubicSpline(\n newTimes,\n CubicSpline.calcKnots(newTimes, newPoints, smoothness),\n 2,\n );\n }\n}\n\nexport { CubicSpline };\n", "import { Quat, Vec3 } from '../math';\n\nimport type { SkeletalKeyframeEntry } from '../animation';\n\nimport { toRestRelative } from './rest-relative';\nimport type { BonePose, RestPose } from './rest-relative';\nimport { CubicSpline } from './spline';\n\n/**\n * Per-bone curve as {@link buildArmatureKeyframes} emits it. Flat, not per-key\n * objects: at 441 bones x 495 keys that allocation dominates the build.\n */\nexport interface ArmatureKeyframeEntry {\n /** Frame time per key, ascending. `length` is the key count. */\n frames: Float32Array;\n /** `[x,y,z]` per key. */\n positions: Float32Array;\n /** `[x,y,z,w]` per key, in the hemisphere the clip authored. */\n rotations: Float32Array;\n /** `[x,y,z]` per key. */\n scales: Float32Array;\n /** Null below two keys, or when the bone is dense enough not to need one. */\n spline: CubicSpline | null;\n}\n\n/**\n * True when no two consecutive keys are more than a frame apart. The epsilon\n * covers non-integral frame stamps; judging a dense bone sparse only costs a\n * spline, which is the safe direction to be wrong in.\n */\nfunction isDenselyKeyed(frames: Float32Array): boolean {\n for (let k = 1; k < frames.length; k++) {\n if (frames[k] - frames[k - 1] > 1.0001) return false;\n }\n return true;\n}\n\n/**\n * Build the per-bone keyframe array an armature samples from at playback time.\n *\n * For each bone in `libraryKeyframes` whose index is below `numBones`:\n * 1. convert every pose into the bone's rest-relative space (so playback can\n * blend a delta on top of the rest pose), and\n * 2. build the cubic spline that interpolates them, unless the bone is keyed\n * densely enough not to need one.\n *\n * Result is a sparse array of length `numBones`; bones not referenced by the\n * source map stay `null` and fall back to rest pose at evaluation time.\n *\n * If `restPose.positions` is empty (rig has no rest data), keys are emitted\n * unchanged - the rest-relative conversion no-ops.\n */\nexport function buildArmatureKeyframes(\n libraryKeyframes: Map<number, SkeletalKeyframeEntry>,\n numFrames: number,\n numBones: number,\n restPose: RestPose,\n looping: boolean,\n translationMask?: Uint8Array,\n bones?: ArrayLike<number> | null,\n): Array<ArmatureKeyframeEntry | null> {\n const out: Array<ArmatureKeyframeEntry | null> = Array.from({ length: numBones }, () => null);\n let only: Uint8Array | null = null;\n if (bones) {\n only = new Uint8Array(numBones);\n for (let k = 0; k < bones.length; k++) only[bones[k]] = 1;\n }\n // Reused for every key, so the build allocates no per-key object.\n const key: BonePose = { position: new Vec3(), rotation: new Quat(), scale: new Vec3() };\n const scratch: BonePose = { position: new Vec3(), rotation: new Quat(), scale: new Vec3() };\n\n libraryKeyframes.forEach((entry, boneIdx) => {\n if (boneIdx >= numBones || (only && !only[boneIdx])) return;\n // A `0` in the mask means the clip carries no MOTION for this bone, only a\n // declaration of the source rig's rest: hold the position delta at zero so\n // `fromRestRelative` reproduces the armature's own rest translation, i.e.\n // THIS character's bone length, rather than the source rig's. Absent mask =\n // every bone animates, which is what a pre-mask clip means.\n //\n // Only when there IS a rest to inherit: with no rest data `toRestRelative`\n // passes the pose through, so a zeroed position would not decode back to a\n // rest translation, it would collapse the bone onto its parent.\n const inheritsRestPosition = translationMask !== undefined\n && translationMask[boneIdx] === 0\n && boneIdx < restPose.positions.length;\n\n // Shared with the store: already ascending, and read-only.\n const { frames } = entry;\n const n = frames.length;\n // Safe to skip when dense: the spline feeds position and scale only\n // (rotation is slerped regardless) and playback clamps it to the\n // neighbouring keys, so over one frame it cannot deviate perceptibly.\n const wantsSpline = n > 1 && !isDenselyKeyed(frames);\n const positions = new Float32Array(n * 3);\n const rotations = new Float32Array(n * 4);\n const scales = new Float32Array(n * 3);\n // eslint-disable-next-line unicorn/no-new-array\n const times: number[] = wantsSpline ? new Array(n) : [];\n // eslint-disable-next-line unicorn/no-new-array\n const points: number[] = wantsSpline ? new Array(n * 10) : [];\n let prevX = 0;\n let prevY = 0;\n let prevZ = 0;\n let prevW = 0;\n\n for (let k = 0; k < n; k++) {\n const i3 = k * 3;\n const i4 = k * 4;\n key.position.set(entry.positions[i3], entry.positions[i3 + 1], entry.positions[i3 + 2]);\n key.rotation.set(entry.rotations[i4], entry.rotations[i4 + 1], entry.rotations[i4 + 2], entry.rotations[i4 + 3]);\n key.scale.set(entry.scales[i3], entry.scales[i3 + 1], entry.scales[i3 + 2]);\n toRestRelative(boneIdx, key, restPose, scratch);\n if (inheritsRestPosition) scratch.position.set(0, 0, 0);\n\n const { position: sp, rotation: sr, scale: ss } = scratch;\n positions[i3] = sp.x; positions[i3 + 1] = sp.y; positions[i3 + 2] = sp.z;\n rotations[i4] = sr.x; rotations[i4 + 1] = sr.y;\n rotations[i4 + 2] = sr.z; rotations[i4 + 3] = sr.w;\n scales[i3] = ss.x; scales[i3 + 1] = ss.y; scales[i3 + 2] = ss.z;\n\n if (wantsSpline) {\n times[k] = frames[k];\n // Short arc: unflipped, the spline takes the long way round wherever a\n // sample changed hemisphere. Compared as authored, not as flipped.\n const flip = k > 0 && prevX * sr.x + prevY * sr.y + prevZ * sr.z + prevW * sr.w < 0;\n const o = k * 10;\n points[o] = sp.x; points[o + 1] = sp.y; points[o + 2] = sp.z;\n points[o + 3] = flip ? -sr.x : sr.x;\n points[o + 4] = flip ? -sr.y : sr.y;\n points[o + 5] = flip ? -sr.z : sr.z;\n points[o + 6] = flip ? -sr.w : sr.w;\n points[o + 7] = ss.x; points[o + 8] = ss.y; points[o + 9] = ss.z;\n prevX = sr.x; prevY = sr.y; prevZ = sr.z; prevW = sr.w;\n }\n }\n\n let spline: CubicSpline | null = null;\n if (wantsSpline) {\n spline = looping\n ? CubicSpline.fromPointsLooping(numFrames, times, points, 1)\n : CubicSpline.fromPoints(times, points, 1);\n }\n out[boneIdx] = { frames, positions, rotations, scales, spline };\n });\n\n return out;\n}\n\n", "import { Quat, Vec3 } from '../math';\n\n/**\n * Per-bone local TRS for a whole rig. The seam between\n * {@link AnimationPlayer} (which writes pose values) and\n * {@link Skeleton} (which composes them into world transforms).\n *\n * Three parallel arrays of length `numBones`. Values live in armature-local\n * bone space - absolute, not rest-relative. Allocation happens once;\n * AnimationPlayer mutates entries in place each frame.\n *\n * @group Characters & Animation\n */\nexport class Pose {\n readonly positions: Vec3[];\n readonly rotations: Quat[];\n readonly scales: Vec3[];\n\n constructor(numBones: number) {\n this.positions = Array.from({ length: numBones }, () => new Vec3());\n this.rotations = Array.from({ length: numBones }, () => new Quat());\n this.scales = Array.from({ length: numBones }, () => new Vec3(1, 1, 1));\n }\n\n get numBones(): number {\n return this.positions.length;\n }\n\n /** Copy every bone from `other` into this pose. */\n copyFrom(other: Pose): void {\n const n = this.positions.length;\n for (let i = 0; i < n; i++) {\n this.positions[i].copy(other.positions[i]);\n this.rotations[i].copy(other.rotations[i]);\n this.scales[i].copy(other.scales[i]);\n }\n }\n\n /**\n * Reset every bone to the bind-pose values held in `bindT` (flat\n * `[x,y,z]*numBones`) and `bindR` (flat `[x,y,z,w]*numBones`). Scales reset\n * to unit.\n */\n setToBind(bindT: Float32Array, bindR: Float32Array): void {\n const n = this.positions.length;\n for (let i = 0; i < n; i++) {\n this.positions[i].set(bindT[i * 3], bindT[i * 3 + 1], bindT[i * 3 + 2]);\n this.rotations[i].set(bindR[i * 4], bindR[i * 4 + 1], bindR[i * 4 + 2], bindR[i * 4 + 3]);\n this.scales[i].set(1, 1, 1);\n }\n }\n}\n", "import { Quat, Vec3 } from '../math';\n\nimport { buildArmatureKeyframes } from '../anim/keyframe-splines';\nimport type { ArmatureKeyframeEntry } from '../anim/keyframe-splines';\nimport { fromRestRelative } from '../anim/rest-relative';\nimport type { BonePose } from '../anim/rest-relative';\nimport type { Animation, AnimationEvent } from '../animation';\n\nimport { Pose } from './pose';\nimport type { Skeleton } from './skeleton';\n\ntype KeyframeEntry = ArmatureKeyframeEntry | null;\n\n// Global shared keyframe cache. buildArmatureKeyframes is pure and deterministic\n// for a given (filtered Animation object, numBones, loop, REST POSE) tuple - all\n// enemies on the same rig playing the same animation produce identical output, so\n// we allocate once and share the arrays across every AnimationPlayer.\n// WeakMap on the Animation object means entries are GC'd automatically when\n// the animation is removed from the engine's library.\n//\n// The rest pose is part of the key because the keyframes it builds are\n// REST-RELATIVE (`toRestRelative`): a bone's stored delta is measured against\n// the rest that was current at build time. Two characters can now disagree on\n// that rest - `LoadCharacterOptions.restSource: 'bundled'` swaps in the\n// per-character joints - so keying on bone count alone would hand a character\n// deltas encoded against somebody else's rest, and `fromRestRelative` would\n// decode them into a pose that is neither rig's. Identity, not contents: rest\n// arrays are built once per armature and never mutated in place.\nconst _sharedKeyframeCache = new WeakMap<Animation, Map<string, Array<KeyframeEntry | null>>>();\n\n// Stable per-object id, so the cache key can name a rest pose or bone list\n// without hashing its arrays on every play() call.\nlet _nextObjectId = 0;\nconst _objectIds = new WeakMap<object, number>();\nfunction objectId(obj: object | null | undefined): number {\n if (!obj) return -1;\n let id = _objectIds.get(obj);\n if (id === undefined) {\n id = _nextObjectId++;\n _objectIds.set(obj, id);\n }\n return id;\n}\n\n/**\n * Resolves an animation by name and returns an already-filtered/converted\n * {@link Animation}, or `null` if not registered. Lets {@link AnimationPlayer}\n * stay free of `SplatEngine` and `SkeletonLibrary`.\n *\n * @group Characters & Animation\n */\nexport type AnimationProvider = (name: string) => Animation | null;\n\n/**\n * Options for {@link AnimationPlayer.crossfadeTo}.\n *\n * @group Characters & Animation\n */\nexport interface CrossfadeOptions {\n /** Blend duration in seconds. Defaults to `defaultCrossfadeDuration`. */\n duration?: number;\n /** Loop the target animation. Default `true`. */\n loop?: boolean;\n /**\n * Preserve the current animation's normalized phase\n * (`animTime / numFrames`) when crossfading. Useful for \"style change\"\n * crossfades where the new looping animation should start at the same\n * cycle position as the outgoing one (e.g. switching idle variants\n * mid-cycle without a snap). Default `false` - new anim starts at\n * frame 0.\n */\n preserveTime?: boolean;\n /** Keep the outgoing clip moving during the blend. Interrupted blends use the visible pose. */\n continueSource?: boolean;\n /** Ease the blend weight at both ends. Default is linear for existing callers. */\n easing?: 'linear' | 'smoothstep';\n}\n\n/**\n * Callback fired when {@link AnimationPlayer.tick} crosses a frame that has\n * one or more {@link AnimationEvent}s on the active animation.\n *\n * @group Characters & Animation\n */\nexport type AnimEventCallback = (event: AnimationEvent) => void;\n\n/**\n * Skeletal animation state machine. Owns playback state (current animation,\n * time, loop flag, crossfade window) and writes the per-bone target pose into\n * a caller-owned {@link Pose} each `update`.\n *\n * Knows nothing about splats, entities, or bone names. Output is a raw\n * crossfaded pose; rig-convention clamps (pelvis X/Z lock, root-bone clamp,\n * root-motion extraction onto the armature pivot) are the\n * {@link Armature} facade's job.\n *\n * @group Characters & Animation\n */\nexport class AnimationPlayer {\n /** Default crossfade duration when {@link CrossfadeOptions.duration} is omitted. */\n defaultCrossfadeDuration = 0.08;\n /** Frame rate used to convert `dt` (seconds) to frame time. Default `30`. */\n frameRate = 30;\n /**\n * Playback-speed multiplier applied to `dt` in {@link tick}. `1` = author\n * speed, `2` = double speed, `0.5` = half. Unlike {@link frameRate} this\n * scales only how fast time advances - the clip's authored frame rate (and\n * thus event-frame mapping) is unchanged. Lets a game tie a locomotion\n * clip's speed to the pivot's actual movement speed. Crossfade blending is\n * deliberately NOT sped up (it runs on real `dt`), so style swaps stay\n * smooth regardless of playback speed.\n */\n playbackSpeed = 1;\n\n private readonly _skeleton: Skeleton;\n private readonly _provider: AnimationProvider;\n\n private _active = false;\n private _animName: string | null = null;\n private _animData: Animation | null = null;\n private _keyframes: Array<KeyframeEntry | null> = [];\n private _keyframesReady = false;\n private _animTime = 0;\n private _loop = true;\n private _paused = false;\n private _blendToRest = false;\n\n private _crossfadeTime = 0;\n private _crossfadeDuration = 0;\n private readonly _snapshot: Pose;\n private _outgoing: AnimationPlayer | null = null;\n private _easing: 'linear' | 'smoothstep' = 'linear';\n private readonly _evalResult = { blendToRestComplete: false };\n\n private _lastTickFrame = -1;\n private readonly _eventListeners = new Set<AnimEventCallback>();\n\n // Per-instance cache removed - keyframes are now shared globally via\n // _sharedKeyframeCache; see _prepareKeyframes.\n\n // Scratch\n private readonly _tmpPos = new Vec3();\n private readonly _tmpRot = new Quat();\n private readonly _tmpScale = new Vec3();\n private readonly _tmpSlerpRot = new Quat();\n // The key on the low side of the current segment, boxed for `Quat.slerp`.\n private readonly _tmpKeyRot = new Quat();\n private readonly _tmpToRot = new Quat();\n private readonly _restIn: BonePose = { position: new Vec3(), rotation: new Quat(), scale: new Vec3() };\n private readonly _restOut: BonePose = { position: new Vec3(), rotation: new Quat(), scale: new Vec3() };\n private readonly _splineValues: number[] = [];\n private _bones: Int32Array | null = null;\n\n constructor(opts: { skeleton: Skeleton; animationProvider: AnimationProvider; snapshotPose: Pose }) {\n this._skeleton = opts.skeleton;\n this._provider = opts.animationProvider;\n this._snapshot = opts.snapshotPose;\n }\n\n // \u2500\u2500 State accessors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * The bones {@link evaluate} writes, or `null` (the default) for all. Clips\n * convert keyframes for these bones only; the rest keep their last pose.\n */\n set bones(v: Int32Array | null) {\n this._bones = v;\n if (this._active && !this._blendToRest && this._animName) {\n const kf = this._prepareKeyframes(this._animName, this._loop);\n if (kf) this._keyframes = kf;\n }\n }\n\n get isPlaying(): boolean {\n return this._active;\n }\n\n get isFinished(): boolean {\n if (!this._active || !this._animData || this._loop || this._blendToRest) return false;\n const nf = this._animData.numFrames;\n return nf > 0 && this._animTime >= nf - 0.01;\n }\n\n get paused(): boolean {\n return this._paused;\n }\n set paused(v: boolean) {\n this._paused = v;\n }\n\n get animationTime(): number {\n return this._animTime;\n }\n set animationTime(v: number) {\n this._animTime = v;\n if (this._animData) {\n const nf = this._animData.numFrames;\n if (nf > 0) {\n if (this._loop) {\n while (this._animTime >= nf) this._animTime -= nf;\n while (this._animTime < 0) this._animTime += nf;\n } else {\n this._animTime = Math.max(0, Math.min(this._animTime, nf - 0.001));\n }\n }\n }\n }\n\n get animationDuration(): number {\n return this._animData?.numFrames ?? 0;\n }\n\n /**\n * Crossfade alpha in `[0, 1]`. `0` when no crossfade is active or one just\n * started; `1` when the in-progress crossfade has reached its terminal\n * blend. Useful for games that want to gate logic on \"the rig has fully\n * committed to the new pose\" without reaching into player internals.\n */\n get crossfadeProgress(): number {\n if (this._crossfadeDuration <= 0) return 0;\n return Math.min(1, this._crossfadeTime / this._crossfadeDuration);\n }\n\n /**\n * Name of the currently-playing animation, or `null` if no animation is\n * active (after {@link AnimationPlayer.stop} with `fadeDuration: 0`, or\n * before the first {@link AnimationPlayer.play}).\n */\n get currentAnimationName(): string | null {\n return this._animName;\n }\n\n // \u2500\u2500 Event dispatch \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Subscribe to frame-aligned {@link AnimationEvent}s on the currently-\n * playing animation. The callback fires once per crossed frame, after the\n * `tick` advances `animTime`.\n *\n * @returns an unsubscribe handle.\n */\n onAnimEvent(cb: AnimEventCallback): () => void {\n this._eventListeners.add(cb);\n return () => { this._eventListeners.delete(cb); };\n }\n\n private _dispatchEventsForFrameTransition(prevFrame: number, curFrame: number, wrapped: boolean, nf: number): void {\n if (this._eventListeners.size === 0) return;\n const events = this._animData?.events;\n if (!events || events.length === 0) return;\n if (curFrame === prevFrame) return;\n\n if (wrapped) {\n // Looping anim wrapped: fire events from prevFrame+1..nf-1, then 0..curFrame.\n for (const e of events) if (e.frame > prevFrame && e.frame < nf) this._fireEvent(e);\n for (const e of events) if (e.frame >= 0 && e.frame <= curFrame) this._fireEvent(e);\n } else if (curFrame > prevFrame) {\n // Normal forward step.\n for (const e of events) if (e.frame > prevFrame && e.frame <= curFrame) this._fireEvent(e);\n }\n }\n\n private _fireEvent(e: AnimationEvent): void {\n for (const cb of this._eventListeners) {\n try { cb(e); } catch (err) {\n // Don't let one listener's throw stop the rest.\n // eslint-disable-next-line no-console\n console.error('[AnimationPlayer] event listener threw:', err);\n }\n }\n }\n\n // \u2500\u2500 Playback verbs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Start an animation immediately (no crossfade). Restarts from frame 0.\n * Returns `false` if `name` isn't resolvable through the provider.\n */\n play(name: string, opts?: { loop?: boolean }): boolean {\n const loop = opts?.loop ?? true;\n\n if (this._active && !this._blendToRest && this._animName === name && this._loop === loop) {\n return true;\n }\n\n const kf = this._prepareKeyframes(name, loop);\n if (!kf) return false;\n\n this._outgoing = null;\n this._activate(name, kf, loop, 0);\n this._crossfadeTime = 0;\n this._crossfadeDuration = 0;\n return true;\n }\n\n /**\n * Crossfade from `currentPose` to `name` over `opts.duration` seconds. The\n * current pose is captured into the internal snapshot - caller can keep\n * mutating `currentPose` after the call returns.\n */\n crossfadeTo(name: string, currentPose: Pose, opts?: CrossfadeOptions): boolean {\n const duration = opts?.duration ?? this.defaultCrossfadeDuration;\n const loop = opts?.loop ?? true;\n const preserveTime = opts?.preserveTime ?? false;\n\n if (this._active && !this._blendToRest && this._animName === name && this._loop === loop) {\n return true;\n }\n\n const kf = this._prepareKeyframes(name, loop);\n if (!kf) return false;\n\n let startTime = 0;\n if (preserveTime && this._active && !this._blendToRest && this._animData && this._loop) {\n const prevNf = this._animData.numFrames;\n const newAnim = this._provider(name);\n if (prevNf > 0 && newAnim && newAnim.numFrames > 0) {\n const phase = (this._animTime % prevNf) / prevNf;\n startTime = phase * newAnim.numFrames;\n }\n }\n\n // Only continue an unblended source. On interruption, capture the actual\n // displayed mixture so an obsolete source can never pop back into view.\n const source = opts?.continueSource && this._active && !this._blendToRest\n && this._animName && this._crossfadeTime >= this._crossfadeDuration\n ? new AnimationPlayer({ skeleton: this._skeleton, animationProvider: this._provider,\n snapshotPose: new Pose(this._skeleton.numBones) }) : null;\n if (source && this._animName) {\n source._activate(this._animName, this._keyframes, this._loop, this._animTime);\n source.frameRate = this.frameRate;\n source.playbackSpeed = this.playbackSpeed;\n source.paused = this.paused;\n source._bones = this._bones;\n }\n this._outgoing = source;\n this._easing = opts?.easing ?? 'linear';\n this._snapshot.copyFrom(currentPose);\n this._crossfadeTime = 0;\n this._crossfadeDuration = duration;\n this._activate(name, kf, loop, startTime);\n return true;\n }\n\n /**\n * Evaluate the active animation at an explicit `frameTime` into `outPose`,\n * with no crossfade blending, and leave every scrap of playback state exactly\n * as it was - current time, crossfade window, loop flag, event cursor.\n *\n * This is the read-only probe a caller needs to sweep a clip for precompute\n * (foot heights, root paths, a loop-start pose) while it keeps playing.\n * {@link AnimationPlayer.evaluate} cannot serve: it reads the live time and\n * folds in whatever blend is in flight.\n *\n * Returns `false` when nothing is active or keyframes are not ready.\n */\n evaluateAt(frameTime: number, outPose: Pose): boolean {\n if (!this._active || this._blendToRest || !this._keyframesReady) return false;\n\n const savedTime = this._animTime;\n this._animTime = frameTime;\n\n const numBones = this._skeleton.numBones;\n const bindT = this._skeleton.bindT;\n const bindR = this._skeleton.bindR;\n const lp = outPose.positions;\n const lr = outPose.rotations;\n const ls = outPose.scales;\n\n for (let bi = 0; bi < numBones; bi++) {\n this._evalTargetPose(bi, bindT, bindR, lp[bi], lr[bi], ls[bi]);\n }\n\n this._animTime = savedTime;\n return true;\n }\n\n /**\n * Snap any active crossfade to its terminal state (alpha = 1, target pose\n * fully applied) on the next {@link AnimationPlayer.evaluate}. No-op if no\n * crossfade is active. Useful when a game scrubs through animation frames\n * for precompute and wants per-frame poses without the blend artefacts of\n * a still-in-progress crossfade.\n */\n endCrossfade(): void {\n if (this._crossfadeDuration > 0) {\n this._crossfadeTime = this._crossfadeDuration;\n }\n }\n\n /**\n * Stop playback. With `fadeDuration > 0`, snapshots `currentPose` and\n * crossfades back to bind over `fadeDuration` seconds. With `0`, deactivates\n * immediately (the caller is expected to reset the pose to bind).\n */\n stop(currentPose: Pose, fadeDuration = 0): void {\n this._outgoing = null;\n this._easing = 'linear';\n if (fadeDuration > 0 && this._active) {\n this._snapshot.copyFrom(currentPose);\n this._crossfadeTime = 0;\n this._crossfadeDuration = fadeDuration;\n this._blendToRest = true;\n return;\n }\n this._deactivate();\n }\n\n // \u2500\u2500 Per-frame update \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Advance animation time by `dt` seconds. Always cheap - call every frame\n * even for off-screen characters so they resume at the correct frame when\n * the camera pans back. Does **not** write to any `Pose`.\n *\n * Returns `wrapped: true` if `animTime` rolled past the end of a looping\n * animation on this tick. The facade uses that signal to suppress the\n * end-to-start pelvis discontinuity when extracting root motion.\n */\n tick(dt: number): { wrapped: boolean } {\n let wrapped = false;\n if (this._active && !this._paused && !this._blendToRest && this._animData && this._keyframesReady) {\n const prevFrame = this._lastTickFrame;\n this._animTime += dt * this.frameRate * this.playbackSpeed;\n const nf = this._animData.numFrames;\n if (nf > 0) {\n if (this._loop) {\n while (this._animTime >= nf) {\n this._animTime -= nf;\n wrapped = true;\n }\n } else if (this._animTime >= nf) {\n this._animTime = nf - 0.001;\n }\n }\n const curFrame = Math.floor(this._animTime);\n this._dispatchEventsForFrameTransition(prevFrame, curFrame, wrapped, nf);\n this._lastTickFrame = curFrame;\n }\n this._outgoing?.tick(dt);\n this._crossfadeTime += dt;\n return { wrapped };\n }\n\n /**\n * Evaluate the current pose at the current `animTime` into `outPose`,\n * applying the crossfade blend with the internal snapshot if one is active.\n *\n * Returns `blendToRestComplete: true` once on the tick a previously-\n * scheduled `stop(_, fade > 0)` reaches alpha 1 - the facade uses that to\n * snap pose to bind and reset rootMotion baseline. The result object is\n * reused by the next call; read it before evaluating again.\n *\n * Skip this call when the character is off-screen; `tick` keeps time\n * advancing in the meantime, so the next on-screen frame evaluates straight\n * to the correct pose with no visible pop. Only {@link bones} are written.\n */\n evaluate(outPose: Pose): { blendToRestComplete: boolean } {\n const progress = this._crossfadeDuration > 0\n ? Math.min(1, this._crossfadeTime / this._crossfadeDuration)\n : 1;\n const alpha = this._easing === 'smoothstep' ? progress * progress * (3 - 2 * progress) : progress;\n const inCrossfade = progress < 1;\n if (inCrossfade) this._outgoing?.evaluate(this._snapshot);\n else this._outgoing = null;\n\n const numBones = this._skeleton.numBones;\n const bindT = this._skeleton.bindT;\n const bindR = this._skeleton.bindR;\n const lp = outPose.positions;\n const lr = outPose.rotations;\n const ls = outPose.scales;\n const fp = this._snapshot.positions;\n const fr = this._snapshot.rotations;\n const fs = this._snapshot.scales;\n const tPos = this._tmpPos;\n const tRot = this._tmpRot;\n const tScale = this._tmpScale;\n const toRot = this._tmpToRot;\n\n const bones = this._bones;\n const count = bones ? bones.length : numBones;\n if (inCrossfade) {\n for (let k = 0; k < count; k++) {\n const bi = bones ? bones[k] : k;\n this._evalTargetPose(bi, bindT, bindR, tPos, tRot, tScale);\n lp[bi].lerp(fp[bi], tPos, alpha);\n toRot.copy(tRot);\n if (fr[bi].dot(toRot) < 0) toRot.mulScalar(-1);\n lr[bi].slerp(fr[bi], toRot, alpha);\n ls[bi].lerp(fs[bi], tScale, alpha);\n }\n } else {\n for (let k = 0; k < count; k++) {\n const bi = bones ? bones[k] : k;\n this._evalTargetPose(bi, bindT, bindR, lp[bi], lr[bi], ls[bi]);\n }\n }\n\n const blendToRestComplete = this._blendToRest && alpha >= 1;\n if (blendToRestComplete) this._deactivate();\n // One reused result object: this runs per character per frame.\n this._evalResult.blendToRestComplete = blendToRestComplete;\n return this._evalResult;\n }\n\n // \u2500\u2500 Internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _activate(name: string, kf: KeyframeEntry[], loop: boolean, startTime = 0): void {\n this._active = true;\n this._blendToRest = false;\n this._animName = name;\n this._animData = this._provider(name);\n this._keyframes = kf;\n this._keyframesReady = true;\n this._animTime = startTime;\n this._loop = loop;\n // Frame transition tracking restarts at the activation frame so the first\n // tick after activation doesn't fire all events from frame 0 in one go.\n this._lastTickFrame = Math.floor(startTime);\n }\n\n private _deactivate(): void {\n this._outgoing = null;\n this._active = false;\n this._blendToRest = false;\n this._animName = null;\n this._animData = null;\n this._keyframesReady = false;\n this._animTime = 0;\n this._lastTickFrame = -1;\n }\n\n private _prepareKeyframes(name: string, loop: boolean): Array<KeyframeEntry | null> | null {\n const animData = this._provider(name);\n if (!animData) {\n // eslint-disable-next-line no-console\n console.warn(`[AnimationPlayer] Animation \"${name}\" not found`);\n return null;\n }\n const store = animData.skeletalStore;\n if (!store) {\n // eslint-disable-next-line no-console\n console.warn(`[AnimationPlayer] Animation \"${name}\" has no keyframes`);\n return null;\n }\n\n // Global cache: all players on the same filtered Animation object + same\n // bone count produce identical buildArmatureKeyframes output, so one build\n // is shared across every enemy of the same rig type.\n const bonesKey = this._bones ? `:${objectId(this._bones)}` : '';\n const innerKey = `${this._skeleton.numBones}:${loop ? 1 : 0}:${objectId(this._skeleton.restPose)}${bonesKey}`;\n let perAnim = _sharedKeyframeCache.get(animData);\n if (!perAnim) {\n perAnim = new Map();\n _sharedKeyframeCache.set(animData, perAnim);\n }\n let kf = perAnim.get(innerKey);\n if (!kf) {\n // `translationMask` needs no place in `innerKey`: the cache is keyed by\n // the Animation object itself, and an Animation's mask is set once at\n // parse time and never mutated, so one object can never present two\n // different masks. `filterAnimationForArmature` produces a *new*\n // Animation with its own remapped mask, which is a different cache key.\n kf = buildArmatureKeyframes(\n store.keyframes,\n animData.numFrames,\n this._skeleton.numBones,\n this._skeleton.restPose,\n loop,\n animData.translationMask,\n this._bones,\n );\n perAnim.set(innerKey, kf);\n }\n return kf;\n }\n\n private _evalTargetPose(\n boneIdx: number,\n bindT: Float32Array,\n bindR: Float32Array,\n outPos: Vec3,\n outRot: Quat,\n outScale: Vec3,\n ): void {\n if (!this._active || !this._keyframesReady || this._blendToRest) {\n outPos.set(bindT[boneIdx * 3], bindT[boneIdx * 3 + 1], bindT[boneIdx * 3 + 2]);\n outRot.set(bindR[boneIdx * 4], bindR[boneIdx * 4 + 1], bindR[boneIdx * 4 + 2], bindR[boneIdx * 4 + 3]);\n outScale.set(1, 1, 1);\n return;\n }\n\n const entry = this._keyframes[boneIdx];\n const numKeys = entry ? entry.frames.length : 0;\n if (entry && numKeys > 1) {\n this._evaluateSpline(entry, this._animTime, outPos, outRot, outScale);\n this._applyFromRest(boneIdx, outPos, outRot, outScale, outPos, outRot, outScale);\n } else if (entry && numKeys === 1) {\n // Constant bone: its one key IS the pose, so decode it in place.\n outPos.set(entry.positions[0], entry.positions[1], entry.positions[2]);\n outRot.set(entry.rotations[0], entry.rotations[1], entry.rotations[2], entry.rotations[3]);\n outScale.set(entry.scales[0], entry.scales[1], entry.scales[2]);\n this._applyFromRest(boneIdx, outPos, outRot, outScale, outPos, outRot, outScale);\n } else {\n outPos.set(bindT[boneIdx * 3], bindT[boneIdx * 3 + 1], bindT[boneIdx * 3 + 2]);\n outRot.set(bindR[boneIdx * 4], bindR[boneIdx * 4 + 1], bindR[boneIdx * 4 + 2], bindR[boneIdx * 4 + 3]);\n outScale.set(1, 1, 1);\n }\n }\n\n private _evaluateSpline(\n entry: NonNullable<KeyframeEntry>,\n frameTime: number,\n outPos: Vec3,\n outRot: Quat,\n outScale: Vec3,\n ): void {\n const { frames, positions, rotations, scales } = entry;\n\n let low = 0;\n let high = frames.length - 1;\n while (low <= high) {\n const mid = (low + high) >> 1;\n if (frames[mid] === frameTime) {\n const m3 = mid * 3;\n const m4 = mid * 4;\n outPos.set(positions[m3], positions[m3 + 1], positions[m3 + 2]);\n outRot.set(rotations[m4], rotations[m4 + 1], rotations[m4 + 2], rotations[m4 + 3]);\n outScale.set(scales[m3], scales[m3 + 1], scales[m3 + 2]);\n return;\n }\n if (frames[mid] < frameTime) low = mid + 1;\n else high = mid - 1;\n }\n\n const i1 = Math.min(Math.max(low, 1), frames.length - 1);\n const i0 = i1 - 1;\n const a3 = i0 * 3;\n const a4 = i0 * 4;\n const b3 = i1 * 3;\n const b4 = i1 * 4;\n const span = Math.max(1e-5, frames[i1] - frames[i0]);\n const t = Math.min(Math.max((frameTime - frames[i0]) / span, 0), 1);\n\n const q0 = this._tmpKeyRot;\n q0.set(rotations[a4], rotations[a4 + 1], rotations[a4 + 2], rotations[a4 + 3]);\n const sr = this._tmpSlerpRot;\n sr.set(rotations[b4], rotations[b4 + 1], rotations[b4 + 2], rotations[b4 + 3]);\n if (q0.dot(sr) < 0) sr.mulScalar(-1);\n outRot.slerp(q0, sr, t);\n\n if (entry.spline) {\n // i0 indexes the same keyframe in the spline's times array (plus any\n // ghost-entry offset for looping splines). Skip the spline's own segment\n // search - we already found the segment above.\n entry.spline.evaluateSegment(i0 + entry.spline.keyframeOffset, t, this._splineValues);\n const v = this._splineValues;\n const cl = (val: number, a: number, b: number) =>\n Math.min(Math.max(val, Math.min(a, b)), Math.max(a, b));\n outPos.set(\n cl(v[0], positions[a3], positions[b3]),\n cl(v[1], positions[a3 + 1], positions[b3 + 1]),\n cl(v[2], positions[a3 + 2], positions[b3 + 2]),\n );\n outScale.set(\n cl(v[7], scales[a3], scales[b3]),\n cl(v[8], scales[a3 + 1], scales[b3 + 1]),\n cl(v[9], scales[a3 + 2], scales[b3 + 2]),\n );\n return;\n }\n outPos.set(\n positions[a3] + (positions[b3] - positions[a3]) * t,\n positions[a3 + 1] + (positions[b3 + 1] - positions[a3 + 1]) * t,\n positions[a3 + 2] + (positions[b3 + 2] - positions[a3 + 2]) * t,\n );\n outScale.set(\n scales[a3] + (scales[b3] - scales[a3]) * t,\n scales[a3 + 1] + (scales[b3 + 1] - scales[a3 + 1]) * t,\n scales[a3 + 2] + (scales[b3 + 2] - scales[a3 + 2]) * t,\n );\n }\n\n private _applyFromRest(\n boneIdx: number,\n srcPos: Vec3, srcRot: Quat, srcScale: Vec3,\n outPos: Vec3, outRot: Quat, outScale: Vec3,\n ): void {\n this._restIn.position = srcPos;\n this._restIn.rotation = srcRot;\n this._restIn.scale = srcScale;\n this._restOut.position = outPos;\n this._restOut.rotation = outRot;\n this._restOut.scale = outScale;\n fromRestRelative(boneIdx, this._restIn, this._skeleton.restPose, this._restOut);\n }\n}\n", "import { Mat4, Vec3 } from '../math';\n\nimport type { Skeleton } from './skeleton';\n\n/**\n * Per-axis scale for a single bone, in a frame aligned to the bone:\n * - `along` - scale down the bone's own axis (lengthen / shorten),\n * - `width` / `thickness` - scale across the bone (the two cross-section axes;\n * their world orientation is bone-dependent, so treat them as \"the two\n * perpendicular directions\" rather than a fixed front/side).\n *\n * Each defaults to `1`. A bare `number` is shorthand for a uniform scale on all\n * three axes.\n *\n * @group Characters & Animation\n */\nexport interface BoneScale {\n along: number;\n width: number;\n thickness: number;\n}\n\n/** A bone scale, or a number meaning uniform scale on all three axes. */\nexport type BoneScaleInput = Partial<BoneScale> | number;\n\n/**\n * Per-bone data that realizes a set of bone scales. Produced by\n * {@link computeBoneStretch}, consumed by {@link Skeleton} (lengthening) and\n * {@link SplatSkinning} (flesh/covariance stretch).\n *\n * @group Characters & Animation\n */\nexport interface BoneStretch {\n /**\n * Per-bone multiplier on the local rest translation. A bone's local\n * translation is its offset from its parent (the parent segment's vector),\n * so scaling it lengthens that segment by the parent's `along` factor.\n * Translation-only \u2192 never inflates covariance, never compounds down a\n * chain. Indexed by bone; `1` = unchanged.\n */\n lengthScale: Float32Array;\n /**\n * Per-bone local stretch matrix (`F\u00B7diag(along,width,thickness)\u00B7F\u1D40` in the\n * bone-aligned frame `F`), folded into the skinning palette so the bone's\n * Gaussians scale on all three axes and their covariances follow. Identity\n * for unscaled bones. Indexed by bone.\n */\n covStretch: Mat4[];\n /** True when at least one bone is actually scaled. */\n any: boolean;\n}\n\nconst IDENT: BoneScale = { along: 1, width: 1, thickness: 1 };\n\nfunction normalize(v: BoneScaleInput): BoneScale {\n if (typeof v === 'number') return { along: v, width: v, thickness: v };\n return {\n along: v.along ?? 1,\n width: v.width ?? 1,\n thickness: v.thickness ?? 1,\n };\n}\n\nfunction isIdentity(s: BoneScale): boolean {\n return s.along === 1 && s.width === 1 && s.thickness === 1;\n}\n\n/**\n * Translate a map of per-bone scales into the {@link BoneStretch} arrays.\n * `factors[boneName]` scales that bone's flesh + segment (e.g.\n * `{ thigh_l: { along: 1.3 }, calf_l: { along: 1.3 } }` \u2192 a 1.3\u00D7 longer left\n * leg; `{ upperarm_l: { width: 1.4, thickness: 1.4 } }` \u2192 a beefier arm).\n * Bones not listed stay at `1`.\n *\n * Correct for arbitrary bone sets (limbs, spine, \u2026) with no boundary\n * compensation: lengthening lives in per-segment translations (no cumulative\n * scale), and the flesh scale is per-bone in the palette (non-propagating).\n * Each bone scales in ITS OWN frame, so bones at any orientation scale\n * correctly.\n *\n * @param skeleton Rig to read the rest pose / hierarchy from.\n * @param boneNames Bone names in index order (from the armature).\n * @param factors Per-bone scales keyed by bone name.\n */\nexport function computeBoneStretch(\n skeleton: Skeleton,\n boneNames: readonly string[],\n factors: Record<string, BoneScaleInput>,\n): BoneStretch {\n const n = skeleton.numBones;\n const parents = skeleton.parents;\n const restT = skeleton.restPose.positions; // local rest translations (per bone)\n\n const scaleOf: BoneScale[] = Array.from({ length: n }, () => IDENT);\n let any = false;\n for (const name in factors) {\n const s = normalize(factors[name]);\n if (isIdentity(s)) continue;\n const idx = boneNames.indexOf(name);\n if (idx >= 0) {\n scaleOf[idx] = s;\n any = true;\n }\n }\n\n const children = buildChildren(parents, n);\n\n // Lengthening: a parent's `along` scale lengthens the offsets of its children.\n const lengthScale = new Float32Array(n).fill(1);\n for (let i = 0; i < n; i++) {\n const p = parents[i];\n if (p >= 0 && p < n) lengthScale[i] = scaleOf[p].along;\n }\n\n // Flesh stretch: per-bone 3-axis scale in a frame aligned to the bone.\n const covStretch: Mat4[] = Array.from({ length: n }, () => new Mat4());\n const e0 = new Vec3();\n const e1 = new Vec3();\n const e2 = new Vec3();\n for (let b = 0; b < n; b++) {\n const s = scaleOf[b];\n if (isIdentity(s)) continue;\n if (!boneAxis(b, children, scaleOf, restT, e0)) continue; // no axis \u2192 skip\n perpendicularFrame(e0, e1, e2);\n setFrameScale(covStretch[b], e0, e1, e2, s);\n }\n\n return { lengthScale, covStretch, any };\n}\n\nfunction buildChildren(parents: Int32Array, n: number): number[][] {\n const children: number[][] = Array.from({ length: n }, () => []);\n for (let i = 0; i < n; i++) {\n const p = parents[i];\n if (p >= 0 && p < n) children[p].push(i);\n }\n return children;\n}\n\n/**\n * Write the bone's local axis (the \"along\" direction) into `out`. A bone spans\n * from its joint to its child's, so the axis is the (primary) child's offset;\n * for a leaf bone, fall back to the bone's own offset from its parent. Returns\n * false if neither yields a usable direction.\n */\nfunction boneAxis(\n b: number,\n children: number[][],\n scaleOf: BoneScale[],\n restT: { x: number; y: number; z: number }[],\n out: Vec3,\n): boolean {\n const child = primaryChild(b, children, scaleOf, restT);\n const off = child >= 0 ? restT[child] : restT[b];\n out.set(off.x, off.y, off.z);\n if (out.length() < 1e-6) return false;\n out.normalize();\n return true;\n}\n\n/**\n * Pick the child that defines a bone's axis. Single-child bones are\n * unambiguous; for a branch (e.g. the top spine bone, parent of both clavicles\n * and the neck) prefer a scaled child (the region's continuation), else the\n * child with the longest offset.\n */\nfunction primaryChild(\n b: number,\n children: number[][],\n scaleOf: BoneScale[],\n restT: { x: number; y: number; z: number }[],\n): number {\n const kids = children[b];\n if (kids.length === 0) return -1;\n if (kids.length === 1) return kids[0];\n let best = -1;\n let bestLen = -1;\n for (const c of kids) {\n if (!isIdentity(scaleOf[c])) return c;\n const o = restT[c];\n const len = o.x * o.x + o.y * o.y + o.z * o.z;\n if (len > bestLen) {\n bestLen = len;\n best = c;\n }\n }\n return best;\n}\n\n/** Complete `e0` to an orthonormal basis (e1, e2) with a stable seed choice. */\nfunction perpendicularFrame(e0: Vec3, e1: Vec3, e2: Vec3): void {\n // Seed with whichever cardinal axis is least parallel to e0, then Gram-Schmidt.\n if (Math.abs(e0.x) <= Math.abs(e0.y) && Math.abs(e0.x) <= Math.abs(e0.z)) {\n e1.set(1, 0, 0);\n } else if (Math.abs(e0.y) <= Math.abs(e0.z)) {\n e1.set(0, 1, 0);\n } else {\n e1.set(0, 0, 1);\n }\n const d = e1.dot(e0);\n e1.set(e1.x - d * e0.x, e1.y - d * e0.y, e1.z - d * e0.z).normalize();\n e2.cross(e0, e1); // already unit (e0, e1 orthonormal)\n}\n\n/** In-place: m's 3\u00D73 = F\u00B7diag(along,width,thickness)\u00B7F\u1D40, F = [e0 e1 e2]. */\nfunction setFrameScale(\n m: Mat4,\n e0: Vec3,\n e1: Vec3,\n e2: Vec3,\n s: BoneScale,\n): void {\n const { along: a, width: w, thickness: t } = s;\n const d = m.data; // identity to start (column-major; the matrix is symmetric)\n for (let i = 0; i < 3; i++) {\n const c0 = i === 0 ? e0.x : i === 1 ? e0.y : e0.z;\n const c1 = i === 0 ? e1.x : i === 1 ? e1.y : e1.z;\n const c2 = i === 0 ? e2.x : i === 1 ? e2.y : e2.z;\n for (let j = 0; j < 3; j++) {\n const r0 = j === 0 ? e0.x : j === 1 ? e0.y : e0.z;\n const r1 = j === 0 ? e1.x : j === 1 ? e1.y : e1.z;\n const r2 = j === 0 ? e2.x : j === 1 ? e2.y : e2.z;\n d[i * 4 + j] = a * c0 * r0 + w * c1 * r1 + t * c2 * r2;\n }\n }\n}\n", "import { Mat4, Quat, Vec3 } from '../math';\n\nimport { computeBindPoseTransforms, invertBindPose } from '../anim/bind-pose';\nimport type { RestPose } from '../anim/rest-relative';\nimport type { ArmatureData } from '../types';\n\nimport type { Pose } from './pose';\n\n/**\n * Rig data and skeletal math for one character. Owns the bone hierarchy, the\n * rest pose, and the (lazy) inverse-bind pose. Composes per-bone local\n * transforms into world-space matrices.\n *\n * Pure data + math - no three.js object, no `SplatEngine`, no `Splat`. Safe to\n * construct in tests with a fixture rig.\n *\n * @group Characters & Animation\n */\nexport class Skeleton {\n readonly numBones: number;\n /** Parent bone index per bone. `-1` for root bones. */\n readonly parents: Int32Array;\n /** Flat bind-pose translations: `[x,y,z]*numBones`. */\n readonly bindT: Float32Array;\n /** Flat bind-pose rotations (quaternions): `[x,y,z,w]*numBones`. */\n readonly bindR: Float32Array;\n /** Rest pose as parallel `Vec3`/`Quat` arrays. */\n readonly restPose: RestPose;\n\n /**\n * Optional per-bone multiplier on the local rest translation, applied during\n * FK. A bone's local translation is its offset from its parent, so scaling\n * it lengthens that segment - this is the lengthening half of bone-length\n * scaling (see {@link computeBoneStretch}). It deliberately affects only the\n * translation, not the bone's orientation/scale, so it never inflates\n * Gaussian covariance and never compounds down a chain. `null` = unscaled\n * (the normal path). The bind/inverse-bind are intentionally NOT rescaled,\n * so the palette carries the standard\u2192stretched delta.\n */\n lengthScale: Float32Array | null = null;\n\n private readonly _children: number[][];\n private readonly _rootBones: number[];\n private _inverseBindPose: Mat4[] | null = null;\n private readonly _tmpLocalMat = new Mat4();\n private readonly _tmpPos = new Vec3();\n private readonly _kfStack: number[] = [];\n\n constructor(armatureData: ArmatureData) {\n const { stdMaleRestTranslations: bt, stdMaleRestRotations: br, stdMaleParents: parents } = armatureData;\n if (!bt || !br || !parents) {\n throw new Error('Skeleton requires stdMaleRestTranslations/Rotations/Parents on ArmatureData');\n }\n\n this.numBones = armatureData.numBones;\n this.bindT = bt;\n this.bindR = br;\n this.parents = parents;\n\n // Hierarchy\n const children: number[][] = Array.from({ length: this.numBones }, () => []);\n const roots: number[] = [];\n for (let i = 0; i < this.numBones; i++) {\n const pi = parents[i];\n if (pi >= 0 && pi < this.numBones) {\n children[pi].push(i);\n } else {\n roots.push(i);\n }\n }\n if (roots.length === 0) roots.push(0);\n this._children = children;\n this._rootBones = roots;\n\n // Rest pose (decomposed bind for rest-relative animation evaluation).\n const positions: Vec3[] = [];\n const rotations: Quat[] = [];\n const scales: Vec3[] = [];\n for (let i = 0; i < this.numBones; i++) {\n positions.push(new Vec3(bt[i * 3], bt[i * 3 + 1], bt[i * 3 + 2]));\n rotations.push(new Quat(br[i * 4], br[i * 4 + 1], br[i * 4 + 2], br[i * 4 + 3]));\n scales.push(new Vec3(1, 1, 1));\n }\n this.restPose = { positions, rotations, scales };\n }\n\n /**\n * World-space inverse-bind pose, one matrix per bone. Lazy - bind pose is\n * only needed once splat skinning starts pushing transforms.\n */\n get inverseBindPose(): Mat4[] {\n if (!this._inverseBindPose) {\n const bindPose = computeBindPoseTransforms(this.numBones, this.bindT, this.bindR, this.parents);\n this._inverseBindPose = invertBindPose(bindPose);\n }\n return this._inverseBindPose;\n }\n\n /**\n * Compose local-space `pose` into world-space matrices, prefixed by\n * `entityWorldTransform`. Walks the hierarchy parent-first so child world\n * transforms read the freshly-written parent.\n *\n * `out` is reused - entries are created lazily if missing, but the caller\n * owns the buffer (no per-frame allocation). Given `bones` (from\n * {@link subsetOrder}), only those entries are written.\n */\n applyLocal(pose: Pose, entityWorldTransform: Mat4, out: Mat4[], bones?: Int32Array | null): void {\n const numBones = this.numBones;\n for (let i = out.length; i < numBones; i++) out[i] = new Mat4();\n if (bones) {\n for (let k = 0; k < bones.length; k++) this._composeBone(bones[k], pose, entityWorldTransform, out);\n return;\n }\n\n const stack = this._kfStack;\n for (const rootIdx of this._rootBones) {\n stack.length = 0;\n stack.push(rootIdx);\n while (stack.length > 0) {\n const bi = stack.pop()!;\n this._composeBone(bi, pose, entityWorldTransform, out);\n const kids = this._children[bi];\n for (let ci = 0; ci < kids.length; ci++) stack.push(kids[ci]);\n }\n }\n }\n\n /**\n * `bones` and all their ancestors, parents first: the order\n * {@link applyLocal} composes a subset in.\n */\n subsetOrder(bones: Iterable<number>): Int32Array {\n const keep = new Uint8Array(this.numBones);\n for (let b of bones) {\n while (b >= 0 && b < this.numBones && !keep[b]) {\n keep[b] = 1;\n b = this.parents[b];\n }\n }\n const order: number[] = [];\n const stack = this._kfStack;\n for (const rootIdx of this._rootBones) {\n stack.length = 0;\n stack.push(rootIdx);\n while (stack.length > 0) {\n const bi = stack.pop()!;\n if (!keep[bi]) continue;\n order.push(bi);\n const kids = this._children[bi];\n for (let ci = 0; ci < kids.length; ci++) stack.push(kids[ci]);\n }\n }\n return Int32Array.from(order);\n }\n\n private _composeBone(bi: number, pose: Pose, entityWorldTransform: Mat4, out: Mat4[]): void {\n const localMat = this._tmpLocalMat;\n const ls = this.lengthScale;\n if (ls && ls[bi] !== 1) {\n // Lengthen this bone's segment: scale only its local translation.\n const p = pose.positions[bi];\n const f = ls[bi];\n this._tmpPos.set(p.x * f, p.y * f, p.z * f);\n localMat.setTRS(this._tmpPos, pose.rotations[bi], pose.scales[bi]);\n } else {\n localMat.setTRS(pose.positions[bi], pose.rotations[bi], pose.scales[bi]);\n }\n const pi = this.parents[bi];\n if (pi < 0 || pi >= this.numBones) {\n out[bi].mul2(entityWorldTransform, localMat);\n } else {\n out[bi].mul2(out[pi], localMat);\n }\n }\n}\n", "import { getStripped1185Names } from '../loader/skeleton';\nimport type { SkeletonLibrary } from '../types';\n\nimport type { Splat } from './splat';\n\n/**\n * Build the source\u2192target bone remap when the splat's `.bin` bundle was\n * authored against a wider skeleton than the armature uses (e.g. a 1185-bone\n * source on the 86-bone std-male rig, or a 441-bone full body+facial source\n * on the 86-bone body rig).\n *\n * Returns `null` when no remap is needed (source and target bone counts\n * match) or when the skeleton library doesn't carry enough naming metadata to\n * resolve the mapping. Unmapped bones in the result are `-1`, except facial\n * bones (`FACIAL_*`), which fall back to the `head` bone so the splats track\n * head motion rather than snapping to root.\n */\nexport function buildSourceBoneRemap(\n splat: Splat,\n numBones: number,\n skeletonLibrary: SkeletonLibrary | undefined,\n): Int32Array | null {\n const sourceCount = splat.sourceBoneCount;\n if (!sourceCount || sourceCount === numBones) return null;\n if (!skeletonLibrary) return null;\n\n // Expression bundles use the same first 86 body bones as Body86, then 33\n // facial bones. Their face names/hierarchy are not in the v1 container or\n // this library. Keep every facial influence on the head instead of dropping\n // it: the whole face follows head motion, without unsupported facial poses.\n if (sourceCount === 119 && numBones === 86) {\n const head = skeletonLibrary.boneNames?.indexOf('head') ?? -1;\n if (head < 0) return null;\n const remap = new Int32Array(sourceCount);\n for (let i = 0; i < 86; i++) remap[i] = i;\n remap.fill(head, 86);\n return remap;\n }\n\n let targetNames: string[] | undefined;\n if (skeletonLibrary.boneNames?.length === numBones) targetNames = skeletonLibrary.boneNames;\n else if (skeletonLibrary.boneNames441?.length === numBones) targetNames = skeletonLibrary.boneNames441;\n if (!targetNames) return null;\n\n let sourceNames: string[] | undefined;\n const fullNames = skeletonLibrary.skeleton1185Names;\n if (fullNames && sourceCount === fullNames.length) {\n sourceNames = fullNames;\n } else if (fullNames && sourceCount === fullNames.length - 1 && fullNames[0] === 'joints_grp') {\n sourceNames = fullNames.slice(1);\n } else if (sourceCount === skeletonLibrary.boneNames441?.length) {\n sourceNames = skeletonLibrary.boneNames441;\n } else if (sourceCount === skeletonLibrary.boneNames?.length) {\n sourceNames = skeletonLibrary.boneNames;\n } else {\n const stripped = getStripped1185Names(skeletonLibrary);\n if (stripped && stripped.length === sourceCount) sourceNames = stripped;\n }\n if (!sourceNames) return null;\n\n const targetByName = new Map<string, number>();\n targetNames.forEach((n, i) => targetByName.set(n, i));\n\n // Fallback target for facial bones when target armature has no facial\n // bones (e.g. 86-bone std male rig loaded with a 441-bone full bin) -\n // facial splats track head motion rather than snapping to root.\n const facialFallback = targetByName.get('head') ?? -1;\n\n const remap = new Int32Array(sourceCount);\n for (let i = 0; i < sourceCount; i++) {\n const name = sourceNames[i];\n const t = targetByName.get(name);\n if (t !== undefined) {\n remap[i] = t;\n } else if (name.startsWith('FACIAL_')) {\n remap[i] = facialFallback;\n } else {\n remap[i] = -1;\n }\n }\n return remap;\n}\n\n/**\n * Allocate the splat's slice of the shared transform palette and rewrite its\n * bone-index texture so each splat's K influences point at the palette slots\n * the armature will write into.\n *\n * Splats with no resolvable target bone (typically facial influences on a\n * body-only rig that can't fall back to `head`) get weight 0 - they stay at\n * rest instead of snapping to bone 0.\n *\n * Returns the first palette index allocated for this splat's bone block.\n * Palette slot for bone `i` is always `firstIdx + i`.\n */\nexport function initializeSplatBoneMapping(\n splat: Splat,\n numBones: number,\n skeletonLibrary: SkeletonLibrary | undefined,\n): number {\n const weights = splat.splatWeights;\n if (!weights) throw new Error('No weights data');\n\n const boneIndices = weights.indices;\n const boneWeights = weights.weights;\n const numSplats = boneIndices.length / 4;\n const palette = splat.transformPalette;\n const firstIdx = palette.alloc(numBones);\n\n const srcToTarget = buildSourceBoneRemap(splat, numBones, skeletonLibrary);\n\n const indicesData = splat.boneIndicesData;\n const weightsData = splat.boneWeightsData;\n if (!indicesData || !weightsData) {\n throw new Error('Bone textures not initialized');\n }\n\n for (let s = 0; s < numSplats; s++) {\n for (let j = 0; j < 4; j++) {\n const rawIdx = boneIndices[s * 4 + j];\n const targetIdx = srcToTarget ? srcToTarget[rawIdx] ?? -1 : rawIdx;\n if (targetIdx < 0 || targetIdx >= numBones) {\n indicesData[s * 4 + j] = firstIdx;\n weightsData[s * 4 + j] = 0;\n } else {\n indicesData[s * 4 + j] = firstIdx + targetIdx;\n weightsData[s * 4 + j] = boneWeights[s * 4 + j];\n }\n }\n }\n\n splat.syncMappedCpuInfluences(firstIdx);\n splat.markBoneTexturesDirty();\n\n // So a later re-upload (privatize / weight mutation) writes these same\n // palette indices instead of the raw source ones.\n splat.rememberBoneMapping(firstIdx, numBones, srcToTarget);\n\n return firstIdx;\n}\n\n/**\n * Walk the splat's per-influence bone-index buffer and return the sorted list\n * of distinct bone indices it actually references. Used to skip palette writes\n * for bones no splat influences (e.g. a 441-bone rig where ~half the bones are\n * facial and the splat has no facial weights).\n *\n * Returns an empty `Int32Array` when the splat has no weights data - callers\n * treat that as \"fall back to walking every bone.\"\n */\nexport function buildSplatBoneIndexList(splat: Splat, numBones: number, firstPaletteIdx: number): Int32Array {\n const weights = splat.splatWeights;\n if (!weights) return new Int32Array(0);\n const used = new Uint8Array(numBones);\n const indices = splat.boneIndicesData;\n const mappedWeights = splat.boneWeightsData;\n if (!indices || !mappedWeights) return new Int32Array(0);\n for (let i = 0; i < weights.indices.length; i++) {\n if (mappedWeights[i] <= 0.001) continue;\n const idx = (indices[i] - firstPaletteIdx) | 0;\n if (idx >= 0 && idx < numBones) used[idx] = 1;\n }\n let count = 0;\n for (let i = 0; i < numBones; i++) if (used[i]) count++;\n const list = new Int32Array(count);\n let j = 0;\n for (let i = 0; i < numBones; i++) if (used[i]) list[j++] = i;\n return list;\n}\n", "import type { Frustum } from 'three';\n\nimport { Mat4 } from '../math';\nimport {\n buildSplatBoneIndexList,\n initializeSplatBoneMapping,\n} from '../splat/bone-binding';\nimport type { Splat } from '../splat/splat';\nimport type { SkeletonLibrary } from '../types';\n\nimport type { Skeleton } from './skeleton';\n\n/**\n * Per-character splat skinning coordinator. Owns the set of {@link Splat}s\n * driven by an armature, their palette-slot maps, and the GPU push that\n * uploads bone matrices each frame.\n *\n * Also owns the frustum-visibility gate: the armature can skip the expensive\n * pose-eval + skinning path when no linked splat is on-screen.\n *\n * @group Characters & Animation\n */\nexport class SplatSkinning {\n /** Splats currently driven by this skinning unit. */\n readonly linkedSplats = new Set<Splat>();\n\n /**\n * Optional per-bone local stretch matrices (the covariance half of\n * bone-length scaling - see {@link computeBoneStretch}). When set, each\n * bone's palette entry gets this stretch folded in, the per-bone scale is\n * NOT normalized out of the palette, and linked splats render with the\n * `USE_NONRIGID_COV` shader path so Gaussian covariances follow the stretch.\n * `null` = rigid skinning (the normal path). Set via {@link setCovStretch}.\n */\n covStretch: Mat4[] | null = null;\n\n private readonly _skeleton: Skeleton;\n private readonly _skeletonLibrary: SkeletonLibrary | undefined;\n\n // firstPaletteIdx[splat] - palette slot for bone i is firstIdx + i (linear, no Map lookup needed)\n private readonly _bonePaletteFirstIdx = new Map<Splat, number>();\n private readonly _boneIndexLists = new Map<Splat, Int32Array>();\n\n private readonly _finalBoneTransforms: Mat4[];\n private readonly _armatureWorldToLocal = new Mat4();\n\n constructor(skeleton: Skeleton, skeletonLibrary: SkeletonLibrary | undefined) {\n this._skeleton = skeleton;\n this._skeletonLibrary = skeletonLibrary;\n const n = skeleton.numBones;\n this._finalBoneTransforms = Array.from({ length: n }, () => new Mat4());\n }\n\n link(splat: Splat): void {\n this.linkedSplats.add(splat);\n }\n\n unlink(splat: Splat): void {\n this.linkedSplats.delete(splat);\n this._bonePaletteFirstIdx.delete(splat);\n this._boneIndexLists.delete(splat);\n }\n\n /**\n * Set (or clear with `null`) the per-bone covariance-stretch matrices for\n * bone-length scaling. Also flips the `USE_NONRIGID_COV` shader path on every\n * linked splat so covariances follow the stretch. Pass `null` to return to\n * rigid skinning.\n */\n setCovStretch(mats: Mat4[] | null): void {\n this.covStretch = mats;\n for (const splat of this.linkedSplats) splat.setNonRigidCovariance(!!mats);\n }\n\n /**\n * Returns `true` when at least one linked splat's bounding sphere intersects\n * the camera frustum. Used by the armature to short-circuit the per-frame\n * skinning math for off-screen characters.\n *\n * When `frustum` is missing (e.g. before the first `engine.update()`) returns `true` -\n * the conservative choice is to do the extra work rather than freeze a\n * character's pose.\n */\n anyVisible(frustum: Frustum | undefined): boolean {\n if (this.linkedSplats.size === 0) return false;\n if (!frustum) return true;\n for (const splat of this.linkedSplats) {\n if (splat.isInFrustum(frustum)) return true;\n }\n return false;\n }\n\n /**\n * Compose `worldTransforms` (one per bone) with the pivot's inverse world\n * transform and the inverse-bind pose, then upload the resulting palette to\n * every linked splat. `worldTransforms[i]` is the i-th bone's matrix in\n * world space, as produced by {@link Skeleton.applyLocal}.\n *\n * Strips scale from the per-bone linear part before composing with the\n * inverse bind. Without this, any net scale (from `splat.object3D` world scale\n * or animated bone scale) inflates Gaussian sigmas on the GPU via the\n * palette's column lengths - visible as radial streaks on hands/fists, and\n * desyncs CPU-computed centers from GPU-rendered positions.\n */\n pushTransforms(worldTransforms: Mat4[], entityWorldTransform: Mat4, skipPositions = false): void {\n if (this.linkedSplats.size === 0) return;\n\n const inverseBindPose = this._skeleton.inverseBindPose;\n if (inverseBindPose.length === 0) return;\n\n const armatureWorldToLocal = this._armatureWorldToLocal;\n // Fast inverse for TRS matrices (no shear). Transpose the 3\u00D73 rotation\n // block after normalizing out scale, then compute the rotated-negated\n // translation. ~2\u00D7 fewer ops than the general Mat4 cofactor expansion.\n {\n const ed = entityWorldTransform.data;\n const ad = armatureWorldToLocal.data;\n const sx2 = 1 / Math.max(ed[0]*ed[0] + ed[1]*ed[1] + ed[2]*ed[2], 1e-16);\n const sy2 = 1 / Math.max(ed[4]*ed[4] + ed[5]*ed[5] + ed[6]*ed[6], 1e-16);\n const sz2 = 1 / Math.max(ed[8]*ed[8] + ed[9]*ed[9] + ed[10]*ed[10], 1e-16);\n ad[0] = ed[0]*sx2; ad[1] = ed[4]*sy2; ad[2] = ed[8]*sz2; ad[3] = 0;\n ad[4] = ed[1]*sx2; ad[5] = ed[5]*sy2; ad[6] = ed[9]*sz2; ad[7] = 0;\n ad[8] = ed[2]*sx2; ad[9] = ed[6]*sy2; ad[10] = ed[10]*sz2; ad[11] = 0;\n const tx = ed[12], ty = ed[13], tz = ed[14];\n ad[12] = -(ad[0]*tx + ad[4]*ty + ad[8]*tz);\n ad[13] = -(ad[1]*tx + ad[5]*ty + ad[9]*tz);\n ad[14] = -(ad[2]*tx + ad[6]*ty + ad[10]*tz);\n ad[15] = 1;\n }\n\n const numBones = this._skeleton.numBones;\n const finalBoneTransforms = this._finalBoneTransforms;\n for (let boneIdx = 0; boneIdx < numBones; boneIdx++) {\n const ft = finalBoneTransforms[boneIdx];\n ft.mul2(armatureWorldToLocal, worldTransforms[boneIdx]);\n\n const ld = ft.data;\n // Bone-length scaling: when covStretch is set we WANT the scale\n // preserved (the deformation IS a stretch), so skip the normalization.\n if (!this.covStretch) {\n // Inline sqrt - Math.hypot is variadic and ~3-4\u00D7 slower than the\n // inline Math.sqrt(x*x+y*y+z*z) form. Called numBones \u00D7 3 per\n // character per frame; the spread shows up in CPU profiles.\n const l0 = ld[0] * ld[0] + ld[1] * ld[1] + ld[2] * ld[2];\n const l1 = ld[4] * ld[4] + ld[5] * ld[5] + ld[6] * ld[6];\n const l2 = ld[8] * ld[8] + ld[9] * ld[9] + ld[10] * ld[10];\n const il0 = 1 / Math.max(Math.sqrt(l0), 1e-8);\n const il1 = 1 / Math.max(Math.sqrt(l1), 1e-8);\n const il2 = 1 / Math.max(Math.sqrt(l2), 1e-8);\n ld[0] *= il0; ld[1] *= il0; ld[2] *= il0;\n ld[4] *= il1; ld[5] *= il1; ld[6] *= il1;\n ld[8] *= il2; ld[9] *= il2; ld[10] *= il2;\n }\n\n // Bone-length scaling: fold in this bone's local along-axis stretch\n // (between the world transform and the inverse bind, so it acts in the\n // bone's own frame and affects only this bone's Gaussians).\n if (this.covStretch) ft.mul(this.covStretch[boneIdx]);\n\n // In-place: ft = ft * inverseBindPose[boneIdx]\n ft.mul(inverseBindPose[boneIdx]);\n }\n\n for (const splat of this.linkedSplats) {\n if (!splat.splatWeights) continue;\n // Skip inactive LODs entirely - for a multi-level character only one\n // linked splat is enabled at a time. Saves the dominant CPU cost\n // (palette upload + updatePositions) on hidden levels.\n if (!splat.renderingEnabled) continue;\n\n let firstPaletteIdx = this._bonePaletteFirstIdx.get(splat);\n if (firstPaletteIdx === undefined) {\n firstPaletteIdx = initializeSplatBoneMapping(splat, numBones, this._skeletonLibrary);\n this._bonePaletteFirstIdx.set(splat, firstPaletteIdx);\n }\n let boneIndexList = this._boneIndexLists.get(splat);\n if (!boneIndexList) {\n boneIndexList = buildSplatBoneIndexList(splat, numBones, firstPaletteIdx);\n this._boneIndexLists.set(splat, boneIndexList);\n }\n\n const palette = splat.transformPalette;\n if (boneIndexList.length > 0) {\n for (let j = 0; j < boneIndexList.length; j++) {\n const boneIdx = boneIndexList[j];\n palette.setTransform(firstPaletteIdx + boneIdx, finalBoneTransforms[boneIdx]);\n }\n } else {\n for (let boneIdx = 0; boneIdx < numBones; boneIdx++) {\n palette.setTransform(firstPaletteIdx + boneIdx, finalBoneTransforms[boneIdx]);\n }\n }\n\n const uploaded = palette.upload();\n if (uploaded) {\n // skipPositions: the GPU palette is still uploaded (so the visible\n // pose is current), but the CPU re-skin of the centres is skipped.\n // The depth-sort order lags until the next full update.\n if (!skipPositions) {\n splat.updatePositions(this._finalBoneTransforms);\n }\n }\n }\n }\n\n /** Request a re-sort on every linked splat (e.g. after a transform change). */\n requestSortAll(): void {\n for (const splat of this.linkedSplats) splat.requestSort();\n }\n}\n", "/**\n * The reveal's per-splat bake: a continuous feet-to-head coordinate along the\n * skeleton, so the front of {@link Splat.setReveal} walks up the body rather\n * than sweeping a flat plane. Pure, so it runs without a GPU.\n */\n\n/** Skeleton distances shared by every splat of one character. */\nexport interface RevealSkeleton {\n /** Bind-pose bone positions, `numBones * 3`. */\n pos: Float32Array;\n /** Distance from the nearest foot; `-1` = off the body graph. */\n chain: Float32Array;\n /** Parents, with deformation helpers flattened out. */\n parents: Int32Array;\n}\n\n/**\n * Distances along the body graph, measured from the nearest foot. Pelvis is\n * `pelvisHint` when given, else from the rig's bone names; failing both, the\n * bone nearest `centre`.\n */\nexport function buildRevealSkeleton(\n pos: Float32Array,\n parents: ArrayLike<number>,\n names: readonly string[],\n centre: { x: number; y: number; z: number },\n pelvisHint = -1,\n): RevealSkeleton | null {\n const n = parents.length;\n if (n === 0) return null;\n\n let pelvis = pelvisHint >= 0 && pelvisHint < n ? pelvisHint : -1;\n const isRevealHelper = (index: number): boolean => {\n const name = names[index]?.toLowerCase() ?? '';\n return name.includes('twist') || name === 'facial_c_facialroot';\n };\n for (let i = 0; pelvis < 0 && i < n && i < names.length; i++) {\n if (names[i]?.toLowerCase().includes('pelvis')) pelvis = i;\n }\n if (pelvis < 0) {\n let best = Infinity;\n for (let i = 0; i < n; i++) {\n const dx = pos[i * 3] - centre.x;\n const dy = pos[i * 3 + 1] - centre.y;\n const dz = pos[i * 3 + 2] - centre.z;\n const d = dx * dx + dy * dy + dz * dz;\n if (d < best) { best = d; pelvis = i; }\n }\n }\n\n // Flatten deformation helpers out of the reveal-only hierarchy.\n const revealParents = Int32Array.from(parents);\n for (let i = 0; i < n; i++) {\n let p = revealParents[i];\n while (p >= 0 && p < n && isRevealHelper(p)) p = revealParents[p];\n revealParents[i] = p;\n }\n const children: number[][] = Array.from({ length: n }, () => []);\n for (let i = 0; i < n; i++) {\n if (isRevealHelper(i)) continue;\n const p = revealParents[i];\n if (p >= 0 && p < n) children[p].push(i);\n }\n const body = new Uint8Array(n);\n body[pelvis] = 1;\n const queue = [pelvis];\n for (let q = 0; q < queue.length; q++) {\n const a = queue[q];\n for (const b of children[a]) {\n if (body[b]) continue;\n body[b] = 1;\n queue.push(b);\n }\n }\n // Measure the body graph from the nearest foot.\n const chain = new Float32Array(n).fill(-1);\n const sources: number[] = [];\n for (let i = 0; i < n && i < names.length; i++) {\n const nm = names[i]?.toLowerCase() ?? '';\n if (body[i] && nm.includes('foot') && !nm.includes('ik')) sources.push(i);\n }\n if (sources.length === 0) {\n // No named feet: the lowest body bone stands in.\n let low = -1;\n let lowY = Infinity;\n for (let i = 0; i < n; i++) {\n if (body[i] && pos[i * 3 + 1] < lowY) { lowY = pos[i * 3 + 1]; low = i; }\n }\n if (low >= 0) sources.push(low);\n }\n if (sources.length > 0) {\n // The rig has only a few hundred bones, so a linear Dijkstra is enough.\n const dist = new Float64Array(n).fill(Infinity);\n const settled = new Uint8Array(n);\n for (const src of sources) dist[src] = 0;\n const relax = (a: number, b: number) => {\n if (!body[b] || settled[b]) return;\n const dx = pos[a * 3] - pos[b * 3];\n const dy = pos[a * 3 + 1] - pos[b * 3 + 1];\n const dz = pos[a * 3 + 2] - pos[b * 3 + 2];\n const nd = dist[a] + Math.sqrt(dx * dx + dy * dy + dz * dz);\n if (nd < dist[b]) dist[b] = nd;\n };\n for (;;) {\n let a = -1;\n let best = Infinity;\n for (let i = 0; i < n; i++) {\n if (!settled[i] && dist[i] < best) { best = dist[i]; a = i; }\n }\n if (a < 0) break;\n settled[a] = 1;\n const p = revealParents[a];\n if (p >= 0 && p < n) relax(a, p);\n for (const b of children[a]) relax(a, b);\n }\n for (let i = 0; i < n; i++) {\n chain[i] = settled[i] ? dist[i] : -1;\n }\n }\n // Helper influences resolve through their anatomical parent.\n for (let i = 0; i < n && i < names.length; i++) {\n if (isRevealHelper(i)) chain[i] = -1;\n }\n return { pos, chain, parents: revealParents };\n}\n\n/** A splat cloud's rest positions and its `k` bone influences per splat. */\nexport interface RevealSplats {\n x: ArrayLike<number>;\n y: ArrayLike<number>;\n z: ArrayLike<number>;\n indices: ArrayLike<number>;\n weights: ArrayLike<number>;\n numSplats: number;\n}\n\n/**\n * Write each splat's normalized distance, 0 at the feet and 1 at the far end\n * of the body, into `out`: its position projected onto the nearest bone\n * segment of its influences, interpolated along {@link RevealSkeleton.chain}.\n * Returns false, leaving `out` untouched, when the skeleton has no length.\n *\n * @param boneRemap - Splat bone index to skeleton bone, `-1` when unmapped,\n * or `null` when they already agree.\n */\nexport function bakeRevealDistances(\n out: Float32Array,\n splats: RevealSplats,\n skeleton: RevealSkeleton,\n boneRemap: ArrayLike<number> | null,\n): boolean {\n const { pos: bindPositions, chain: chainDistance, parents } = skeleton;\n const n = chainDistance.length;\n if (n === 0 || bindPositions.length < n * 3 || parents.length < n) return false;\n let maxChain = 0;\n for (let i = 0; i < n; i++) if (chainDistance[i] > maxChain) maxChain = chainDistance[i];\n if (!(maxChain > 0)) return false;\n\n const { x: rx, y: ry, z: rz, indices, weights, numSplats } = splats;\n const k = Math.floor(indices.length / numSplats);\n const incidentEdges: number[][] = Array.from({ length: n }, () => []);\n const revealBone = (index: number): number => {\n let bone = boneRemap ? boneRemap[index] ?? -1 : index;\n while (bone >= 0 && bone < n && chainDistance[bone] < 0) bone = parents[bone];\n return bone;\n };\n for (let b = 0; b < n; b++) {\n const p = parents[b];\n if (p < 0 || p >= n || chainDistance[p] < 0 || chainDistance[b] < 0) continue;\n incidentEdges[p].push(p, b);\n incidentEdges[b].push(p, b);\n }\n for (let si = 0; si < numSplats; si++) {\n let bestDistanceSq = Infinity;\n let bestPathDistance = maxChain;\n let fallbackPathDistance = maxChain;\n for (let j = 0; j < k; j++) {\n const slot = si * k + j;\n if (weights[slot] <= 0.001) continue;\n const b = revealBone(indices[slot]);\n if (b < 0 || b >= n || chainDistance[b] < 0) continue;\n fallbackPathDistance = Math.min(fallbackPathDistance, chainDistance[b]);\n const edges = incidentEdges[b];\n for (let e = 0; e < edges.length; e += 2) {\n const a = edges[e];\n const c = edges[e + 1];\n const ax = bindPositions[a * 3];\n const ay = bindPositions[a * 3 + 1];\n const az = bindPositions[a * 3 + 2];\n const dx = bindPositions[c * 3] - ax;\n const dy = bindPositions[c * 3 + 1] - ay;\n const dz = bindPositions[c * 3 + 2] - az;\n const lengthSq = dx * dx + dy * dy + dz * dz;\n if (lengthSq <= 1e-8) continue;\n const t = Math.min(1, Math.max(0,\n ((rx[si] - ax) * dx + (ry[si] - ay) * dy + (rz[si] - az) * dz) / lengthSq,\n ));\n const qx = ax + dx * t;\n const qy = ay + dy * t;\n const qz = az + dz * t;\n const ex = rx[si] - qx;\n const ey = ry[si] - qy;\n const ez = rz[si] - qz;\n const distanceSq = ex * ex + ey * ey + ez * ez;\n if (distanceSq < bestDistanceSq) {\n bestDistanceSq = distanceSq;\n bestPathDistance = chainDistance[a] + (chainDistance[c] - chainDistance[a]) * t;\n }\n }\n }\n out[si] = Math.min(1, Math.max(0,\n (bestDistanceSq < Infinity ? bestPathDistance : fallbackPathDistance) / maxChain,\n ));\n }\n return true;\n}\n", "import {\n ClampToEdgeWrapping,\n DataTexture,\n FloatType,\n Frustum,\n Group,\n Matrix4,\n NearestFilter,\n RGBAFormat,\n Vector3,\n} from 'three';\nimport type { Camera, IUniform, Object3D } from 'three';\n\nimport type { Animation } from './animation';\nimport type { AnimLodPreset } from './armature';\nimport type { PointLight } from './lighting/point-light';\nimport type { SkyLight } from './lighting/sky-light';\nimport type { SunLight } from './lighting/sun-light';\nimport { loadSkeletonLibrary } from './loader/skeleton';\nimport type { SkeletonLibrary } from './loader/skeleton';\nimport type { SplatBackend } from './splat/backend';\n\n/**\n * Lights that splats respond to. Splats carry baked colour, so this is a\n * multiplier on that colour rather than a shading model: ambient plus sun plus\n * distance-attenuated point lights, evaluated at each splat's centre.\n *\n * With no sun and no sky the factor is exactly 1 and splats render as authored.\n *\n * @group Lighting\n */\nexport interface SceneLighting {\n sun: SunLight | null;\n sky: SkyLight | null;\n points: PointLight[];\n}\n\n/** @group Engine */\nexport interface SplatEngineOptions {\n /**\n * Parent for everything the engine creates. When given, the engine's\n * {@link SplatEngine.contentRoot} is added to it, so loaded characters and\n * environments appear without a further `scene.add`.\n */\n scene?: Object3D;\n /** Camera used for visibility gating and distance LOD. Can also be passed to {@link SplatEngine.update}. */\n camera?: Camera;\n /**\n * Force a particular splat backend. Leave unset: each splat then picks the\n * backend matching the renderer that first draws it.\n */\n backend?: SplatBackend;\n /** Initial {@link SplatEngine.legacyRootRotation}. Default `true`. */\n legacyRootRotation?: boolean;\n}\n\nfunction createPointLightTexture(capacity: number): DataTexture {\n const w = Math.max(capacity, 1);\n const texture = new DataTexture(new Float32Array(w * 2 * 4), w, 2, RGBAFormat, FloatType);\n texture.name = 'lightingPointLights';\n texture.minFilter = NearestFilter;\n texture.magFilter = NearestFilter;\n texture.wrapS = ClampToEdgeWrapping;\n texture.wrapT = ClampToEdgeWrapping;\n texture.generateMipmaps = false;\n texture.needsUpdate = true;\n return texture;\n}\n\n/**\n * Shared state for a set of splat characters and environments: the skeleton\n * library, the registry of named animation clips, the lights, and the\n * per-frame update that advances every character.\n *\n * This is the three.js counterpart of the PlayCanvas build's `Scene`, minus\n * everything three.js already owns. It creates no renderer, canvas or camera:\n * you keep your own `WebGLRenderer`, `Scene` and render loop, and call\n * {@link SplatEngine.update} once per frame before rendering.\n *\n * ```ts\n * const engine = new SplatEngine({ scene, camera });\n * const character = await Character.load(engine, '/assets/hero.vsplat');\n * await Animation.loadGlb(engine, '/assets/idle.glb', 'idle');\n * character.playAnimation('idle', { loop: true });\n *\n * renderer.setAnimationLoop(() => {\n * engine.update(clock.getDelta());\n * renderer.render(scene, camera);\n * });\n * ```\n *\n * @group Engine\n */\nexport class SplatEngine {\n /** Parent of every character and environment loaded through this engine. */\n readonly contentRoot: Group;\n /** A forced splat backend, or `null` to pick per renderer (the default). */\n readonly backend: SplatBackend | null;\n readonly skeletonLibrary: SkeletonLibrary;\n /** Clips by name. Populated by {@link Animation.register} and the `Animation.load*` helpers. */\n readonly skeletalAnimationLibrary = new Map<string, Animation>();\n readonly lighting: SceneLighting = { sun: null, sky: null, points: [] };\n\n /** Camera used for visibility gating and distance LOD. `null` disables both. */\n camera: Camera | null;\n /** Default animation-LOD bands for `Armature.setAnimationLod()` called with no arguments. */\n animLodPreset?: AnimLodPreset;\n /**\n * {@link Splat.minPixelSize} for every splat created through this engine\n * from now on: splats smaller than this many pixels on screen are skipped.\n * `0` (the default) draws all.\n */\n subPixelCull = 0;\n /**\n * Default {@link Armature.legacyRootRotation} for this engine's characters:\n * `true` pins the root bone's rotation to bind, as 0.1.1 did, so GLB clips\n * face the way they always have here; `false` keeps the clip's root\n * rotation, as the PlayCanvas build 0.3.2 does. A {@link Scene} defaults to\n * `false`. An armature's own setting wins. Read every frame, so a change\n * applies to the characters already loaded too; make it before their clips\n * play (see {@link Armature.legacyRootRotation}).\n */\n legacyRootRotation: boolean;\n /** Number of {@link SplatEngine.update} calls so far. */\n frame = 0;\n /** {@link SplatEngine.frame} of the most recent character pose evaluation. */\n characterPoseUpdatedFrame = -1;\n\n /**\n * Lighting uniforms shared by every splat material this engine creates.\n * Refreshed by {@link SplatEngine.syncLighting}.\n * @internal\n */\n readonly lightingUniforms: {\n uSunColor: IUniform<Vector3>;\n uSunIntensity: IUniform<number>;\n uAmbientColor: IUniform<Vector3>;\n uPointLightCount: IUniform<number>;\n uPointLightTex: IUniform<DataTexture>;\n };\n\n private readonly _updaters = new Set<(dt: number) => void>();\n private readonly _frustum = new Frustum();\n private readonly _projScreen = new Matrix4();\n private readonly _cameraPosition = new Vector3();\n private _frustumValid = false;\n private _pointLightCapacity = 1;\n private _destroyed = false;\n\n constructor(opts?: SplatEngineOptions) {\n this.contentRoot = new Group();\n this.contentRoot.name = 'splatEngineContent';\n opts?.scene?.add(this.contentRoot);\n this.camera = opts?.camera ?? null;\n this.backend = opts?.backend ?? null;\n this.legacyRootRotation = opts?.legacyRootRotation ?? true;\n this.skeletonLibrary = loadSkeletonLibrary();\n this.lightingUniforms = {\n uSunColor: { value: new Vector3(0, 0, 0) },\n uSunIntensity: { value: 0 },\n uAmbientColor: { value: new Vector3(1, 1, 1) },\n uPointLightCount: { value: 0 },\n uPointLightTex: { value: createPointLightTexture(this._pointLightCapacity) },\n };\n }\n\n get destroyed(): boolean {\n return this._destroyed;\n }\n\n private static _shared: SplatEngine | null = null;\n\n /**\n * The engine the loaders use when none is given: one shared skeleton\n * library, animation registry and set of lights for the whole page. Created\n * on first use, attached to no scene.\n */\n static get shared(): SplatEngine {\n if (!SplatEngine._shared || SplatEngine._shared.destroyed) SplatEngine._shared = new SplatEngine();\n return SplatEngine._shared;\n }\n\n /**\n * Advance every auto-updating character by `dt` seconds. Call once per\n * frame, before rendering.\n *\n * @param camera - Optional; replaces {@link SplatEngine.camera} when given.\n */\n update(dt: number, camera?: Camera): void {\n if (this._destroyed) return;\n if (camera) this.camera = camera;\n this.frame++;\n\n const cam = this.camera;\n if (cam) {\n cam.updateMatrixWorld();\n this._projScreen.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse);\n this._frustum.setFromProjectionMatrix(this._projScreen, cam.coordinateSystem, cam.reversedDepth);\n this._cameraPosition.setFromMatrixPosition(cam.matrixWorld);\n this._frustumValid = true;\n } else {\n this._frustumValid = false;\n }\n\n for (const fn of this._updaters) fn(dt);\n }\n\n /**\n * Register a per-frame callback run by {@link SplatEngine.update}.\n * @returns A function that removes it.\n * @internal\n */\n addUpdater(fn: (dt: number) => void): () => void {\n this._updaters.add(fn);\n return () => this._updaters.delete(fn);\n }\n\n /** @internal */\n removeUpdater(fn: (dt: number) => void): void {\n this._updaters.delete(fn);\n }\n\n /**\n * The camera frustum as of the last {@link SplatEngine.update}, or\n * `undefined` when no camera is set - callers treat that as \"visible\".\n * @internal\n */\n get cameraFrustum(): Frustum | undefined {\n return this._frustumValid ? this._frustum : undefined;\n }\n\n /**\n * World-space camera position as of the last {@link SplatEngine.update}, or\n * `null` when no camera is set.\n * @internal\n */\n get cameraWorldPosition(): Vector3 | null {\n return this._frustumValid ? this._cameraPosition : null;\n }\n\n /**\n * Incremented whenever {@link SplatEngine.syncLighting} finds the lights\n * changed. Lets a backend skip work that depends on lighting.\n * @internal\n */\n lightingVersion = 0;\n\n /**\n * Copy {@link SplatEngine.lighting} into the shared uniforms. Called per\n * draw, so it only compares numbers and writes on change.\n * @internal\n */\n syncLighting(): void {\n const { sun, sky, points } = this.lighting;\n const u = this.lightingUniforms;\n const sunActive = !!sun && sun.enabled;\n const skyActive = !!sky && sky.enabled;\n let changed = false;\n\n const sunR = sunActive ? sun!.color.r : 0;\n const sunG = sunActive ? sun!.color.g : 0;\n const sunB = sunActive ? sun!.color.b : 0;\n const sunI = sunActive ? sun!.intensity : 0;\n const sunColor = u.uSunColor.value;\n if (sunColor.x !== sunR || sunColor.y !== sunG || sunColor.z !== sunB || u.uSunIntensity.value !== sunI) {\n sunColor.set(sunR, sunG, sunB);\n u.uSunIntensity.value = sunI;\n changed = true;\n }\n\n // No lights at all means \"render as authored\", not \"render black\".\n let ambR = 0, ambG = 0, ambB = 0;\n if (skyActive) {\n ambR = sky!.color.r * sky!.intensity;\n ambG = sky!.color.g * sky!.intensity;\n ambB = sky!.color.b * sky!.intensity;\n } else if (!sunActive) {\n ambR = ambG = ambB = 1;\n }\n const ambient = u.uAmbientColor.value;\n if (ambient.x !== ambR || ambient.y !== ambG || ambient.z !== ambB) {\n ambient.set(ambR, ambG, ambB);\n changed = true;\n }\n\n let count = 0;\n for (let i = 0; i < points.length; i++) if (points[i].enabled) count++;\n if (count > this._pointLightCapacity) {\n this._pointLightCapacity = Math.max(this._pointLightCapacity * 2, count);\n u.uPointLightTex.value.dispose();\n u.uPointLightTex.value = createPointLightTexture(this._pointLightCapacity);\n changed = true;\n }\n if (count !== u.uPointLightCount.value) {\n u.uPointLightCount.value = count;\n changed = true;\n }\n\n // Row 0: position + range. Row 1: colour + intensity.\n const texture = u.uPointLightTex.value;\n const data = texture.image.data as Float32Array;\n const row1 = this._pointLightCapacity * 4;\n let textureChanged = false;\n let w = 0;\n for (let i = 0; i < points.length; i++) {\n const p = points[i];\n if (!p.enabled) continue;\n const a = w * 4;\n const b = row1 + w * 4;\n if (\n data[a] !== p.position.x || data[a + 1] !== p.position.y || data[a + 2] !== p.position.z || data[a + 3] !== p.range ||\n data[b] !== p.color.r || data[b + 1] !== p.color.g || data[b + 2] !== p.color.b || data[b + 3] !== p.intensity\n ) {\n data[a] = p.position.x;\n data[a + 1] = p.position.y;\n data[a + 2] = p.position.z;\n data[a + 3] = p.range;\n data[b] = p.color.r;\n data[b + 1] = p.color.g;\n data[b + 2] = p.color.b;\n data[b + 3] = p.intensity;\n textureChanged = true;\n }\n w++;\n }\n if (textureChanged) {\n texture.needsUpdate = true;\n changed = true;\n }\n\n if (changed) this.lightingVersion++;\n }\n\n /**\n * Detach the engine's content from the scene and stop updating. Characters\n * and environments are not destroyed for you - destroy them first if you\n * want their GPU resources released.\n */\n dispose(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n this._updaters.clear();\n this.contentRoot.removeFromParent();\n this.lightingUniforms.uPointLightTex.value.dispose();\n }\n}\n\n/**\n * Thrown when an asset finishes loading onto an engine that has already been\n * disposed.\n *\n * This is a CANCELLATION, not a failure: the bytes were fine and the engine is\n * simply gone. It exists as its own type so a caller can tell the two apart.\n *\n * @group Engine\n */\nexport class EngineDisposedError extends Error {\n constructor(what: string) {\n super(`${what}: the engine was disposed while the asset was loading`);\n this.name = 'EngineDisposedError';\n }\n}\n", "import { DataUtils } from 'three';\n\nimport type { SplatAttributes } from '../loader/character/types';\n\nconst SH_C0 = 0.28209479177387814;\n\n/**\n * Splat attributes packed into the three texel streams the shaders read.\n *\n * Renderer-agnostic on purpose: these are plain typed arrays laid out as\n * `width x height` RGBA texels, so the WebGL and WebGPU backends wrap the same\n * bytes in their own texture objects.\n *\n * The layout is 32 bytes per splat:\n *\n * - `color` RGBA16F - `rgb` display-referred colour, `a` opacity (post-sigmoid).\n * - `transformA` RGBA32UI - `xyz` the centre as raw float32 bits, `w` two packed\n * half floats: rotation `x` (low 16) and `y` (high 16).\n * - `transformB` RGBA16F - `xyz` linear scale, `w` rotation `z`.\n *\n * Rotation `w` is not stored: quaternions are normalised and flipped to\n * `w >= 0` here, so the shader recovers it as `sqrt(1 - |xyz|^2)`.\n */\nexport interface PackedSplats {\n numSplats: number;\n width: number;\n height: number;\n color: Uint16Array;\n transformA: Uint32Array;\n transformB: Uint16Array;\n /** Rest-pose centres, flat `[x,y,z] * numSplats`. The depth sort reads these. */\n centers: Float32Array;\n boundsMin: [number, number, number];\n boundsMax: [number, number, number];\n}\n\n/** Texture dimensions for `count` texels: near-square, wide enough to hold every row. */\nexport function textureSizeFor(count: number): { width: number; height: number } {\n const width = Math.max(1, Math.ceil(Math.sqrt(count)));\n const height = Math.max(1, Math.ceil(count / width));\n return { width, height };\n}\n\nexport function packSplats(numSplats: number, s: SplatAttributes): PackedSplats {\n const { width, height } = textureSizeFor(numSplats);\n const texels = width * height;\n const color = new Uint16Array(texels * 4);\n const transformA = new Uint32Array(texels * 4);\n const transformAFloat = new Float32Array(transformA.buffer);\n const transformB = new Uint16Array(texels * 4);\n const centers = new Float32Array(numSplats * 3);\n const toHalf = DataUtils.toHalfFloat;\n\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n\n for (let i = 0; i < numSplats; i++) {\n const o = i * 4;\n\n color[o] = toHalf(s.f_dc_0[i] * SH_C0 + 0.5);\n color[o + 1] = toHalf(s.f_dc_1[i] * SH_C0 + 0.5);\n color[o + 2] = toHalf(s.f_dc_2[i] * SH_C0 + 0.5);\n color[o + 3] = toHalf(1 / (1 + Math.exp(-s.opacity[i])));\n\n const x = s.x[i], y = s.y[i], z = s.z[i];\n transformAFloat[o] = x;\n transformAFloat[o + 1] = y;\n transformAFloat[o + 2] = z;\n centers[i * 3] = x;\n centers[i * 3 + 1] = y;\n centers[i * 3 + 2] = z;\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n if (z < minZ) minZ = z;\n if (z > maxZ) maxZ = z;\n\n // Source order is wxyz. Normalise, then flip onto the w >= 0 hemisphere so\n // w is recoverable from xyz alone.\n let qw = s.rot_0[i], qx = s.rot_1[i], qy = s.rot_2[i], qz = s.rot_3[i];\n const len = Math.sqrt(qx * qx + qy * qy + qz * qz + qw * qw);\n if (len === 0) {\n qx = qy = qz = 0;\n qw = 1;\n } else {\n const inv = (qw < 0 ? -1 : 1) / len;\n qx *= inv;\n qy *= inv;\n qz *= inv;\n }\n transformA[o + 3] = (toHalf(qx) | (toHalf(qy) << 16)) >>> 0;\n\n transformB[o] = toHalf(Math.exp(s.scale_0[i]));\n transformB[o + 1] = toHalf(Math.exp(s.scale_1[i]));\n transformB[o + 2] = toHalf(Math.exp(s.scale_2[i]));\n transformB[o + 3] = toHalf(qz);\n }\n\n if (numSplats === 0) {\n minX = minY = minZ = maxX = maxY = maxZ = 0;\n }\n\n return {\n numSplats,\n width,\n height,\n color,\n transformA,\n transformB,\n centers,\n boundsMin: [minX, minY, minZ],\n boundsMax: [maxX, maxY, maxZ],\n };\n}\n", "/**\n * Ranking splats by how much they contribute, and the spatial bucketing both\n * users of that ranking share.\n *\n * Two features are built on it. {@link pruneSplats} throws the weakest splats\n * away at load; the count LOD ({@link Splat.setCountLod}) keeps them all and\n * processes a prefix of the ranking that shrinks with distance. The ranking\n * has to be the same one in both cases, which is why it lives here rather than\n * in either of them.\n */\n\nimport { DataUtils } from 'three';\n\nimport type { PackedSplats } from './packed-splats';\n\n/**\n * Group indices by spatial cell without a comparison sort: hash the cells to\n * dense ids, count, prefix-sum, scatter.\n *\n * O(n) with one map probe per splat, against the O(n log n) a sort over a\n * composite key would cost - which measured 11-16 ms of a ~40 ms character\n * load in the Unity build this is ported from.\n */\nexport function bucketByCell(\n cellKey: Float64Array,\n n: number,\n): { order: Uint32Array; start: Uint32Array; cells: number } {\n const id = new Map<number, number>();\n const dense = new Uint32Array(n);\n let cells = 0;\n for (let i = 0; i < n; i++) {\n const key = cellKey[i];\n let d = id.get(key);\n if (d === undefined) {\n d = cells++;\n id.set(key, d);\n }\n dense[i] = d;\n }\n\n const start = new Uint32Array(cells + 1);\n for (let i = 0; i < n; i++) start[dense[i] + 1]++;\n for (let c = 0; c < cells; c++) start[c + 1] += start[c];\n\n const order = new Uint32Array(n);\n const cursor = new Uint32Array(cells);\n for (let i = 0; i < n; i++) {\n const d = dense[i];\n order[start[d] + cursor[d]++] = i;\n }\n return { order, start, cells };\n}\n\n/**\n * Cells per axis in a cell key. 1024 at 4 cm covers a 40 m character, and\n * three indices of that size multiply out to 2^30, well inside the 2^53 a\n * double holds exactly.\n */\nconst CELL_STRIDE = 1024;\n\n/**\n * One splat's cell key on a `1 / voxelSize` grid whose origin is `min`.\n *\n * The one definition of the grid. Both users of it have to agree - a splat\n * pruned by one rule and ranked by another would be thinned twice in the same\n * place - and they walk different layouts, so what they share is this rather\n * than a loop.\n */\nexport function cellKeyOf(\n x: number, y: number, z: number,\n minX: number, minY: number, minZ: number,\n invVoxel: number,\n): number {\n const cx = Math.floor((x - minX) * invVoxel);\n const cy = Math.floor((y - minY) * invVoxel);\n const cz = Math.floor((z - minZ) * invVoxel);\n return (cx * CELL_STRIDE + cy) * CELL_STRIDE + cz;\n}\n\n/**\n * Cell keys for `centers`, with the grid origin at the actual minimum of the\n * positions rather than at any declared bounds, which can carry a margin the\n * grid should not inherit.\n */\nexport function cellKeysFor(centers: Float32Array, count: number, voxelSize: number): Float64Array {\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n for (let i = 0, c = 0; i < count; i++, c += 3) {\n if (centers[c] < minX) minX = centers[c];\n if (centers[c + 1] < minY) minY = centers[c + 1];\n if (centers[c + 2] < minZ) minZ = centers[c + 2];\n }\n const inv = 1 / voxelSize;\n const keys = new Float64Array(count);\n for (let i = 0, c = 0; i < count; i++, c += 3) {\n keys[i] = cellKeyOf(centers[c], centers[c + 1], centers[c + 2], minX, minY, minZ, inv);\n }\n return keys;\n}\n\n/**\n * Splat indices ordered so that any prefix of the result is a good-looking\n * subset of the whole: the most important splat of every cell first, then the\n * second of every cell, and so on.\n *\n * Importance within a cell is opacity times the two largest gaussian axes -\n * the area the splat actually paints, which the Unity build measured as\n * ranking 0.80 with the ink each splat deposits, at no cost to compute.\n *\n * The round-robin across cells is what makes this usable as a prefix, and it\n * is the same decision the load-time prune makes for the same reason: ranked\n * globally, a prefix would be every strong splat on the jacket and none of the\n * many individually-faint ones that make up a face, so the face would be the\n * first thing to go. Taken a rank at a time across cells, every region thins\n * by the same proportion at every prefix length, so a character at 30% looks\n * like a sparser version of itself rather than a damaged one.\n *\n * Costs one pass over the splats plus a small sort inside each cell, and is\n * built once, the first time a count LOD asks for it.\n */\nexport function buildImportanceOrder(packed: PackedSplats, voxelSize: number): Uint32Array {\n const n = packed.numSplats;\n const out = new Uint32Array(n);\n if (n === 0) return out;\n\n const { color, transformB, centers } = packed;\n const half = DataUtils.fromHalfFloat;\n const score = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const o = i * 4;\n const alpha = half(color[o + 3]);\n const s0 = half(transformB[o]);\n const s1 = half(transformB[o + 1]);\n const s2 = half(transformB[o + 2]);\n const mx = s0 > s1 ? (s0 > s2 ? s0 : s2) : (s1 > s2 ? s1 : s2);\n const mn = s0 < s1 ? (s0 < s2 ? s0 : s2) : (s1 < s2 ? s1 : s2);\n score[i] = alpha * mx * (s0 + s1 + s2 - mx - mn);\n }\n\n const { order, start, cells } = bucketByCell(cellKeysFor(centers, n, voxelSize), n);\n\n // Strongest first inside each cell. Cells hold tens of splats, so the\n // generic sort over a small slice is cheaper than anything hand-written.\n let widest = 0;\n const scratch: number[] = [];\n for (let c = 0; c < cells; c++) {\n const lo = start[c];\n const hi = start[c + 1];\n const size = hi - lo;\n if (size > widest) widest = size;\n if (size < 2) continue;\n scratch.length = 0;\n for (let k = lo; k < hi; k++) scratch.push(order[k]);\n scratch.sort((a, b) => score[b] - score[a]);\n for (let k = 0; k < size; k++) order[lo + k] = scratch[k];\n }\n\n // Rank by rank, across every cell that still has one.\n let w = 0;\n for (let rank = 0; rank < widest; rank++) {\n for (let c = 0; c < cells; c++) {\n const at = start[c] + rank;\n if (at < start[c + 1]) out[w++] = order[at];\n }\n }\n return out;\n}\n", "/**\n * Runtime quality knobs, and the per-stage timings that say whether they\n * worked.\n *\n * These are decisions an application makes from its own quality menu, per\n * platform or per device tier, so they are module-level state rather than\n * constructor options: an option could only be read at exactly one moment, and\n * a quality menu changes its mind at any moment. Every knob here is read per\n * frame (or per load, where it says so), so writing one takes effect from the\n * next frame without rebuilding anything.\n *\n * Ported from the Unity build's `SplatQuality`, which is where the measured\n * numbers in these docs come from: a Mali-G57 phone and an A17 Pro iPhone,\n * both of them tile-based GPUs that are bound by the number of blended\n * fragments. A desktop immediate-mode GPU is bound differently and will not\n * reproduce those ratios - which is what `ab/run-quality-ab.mjs` is for.\n *\n * Two of them ship with a non-zero default - {@link SplatQuality.quadAlphaCutoff}\n * at 8/255 and {@link SplatQuality.minOpacity} at 0.05 - because the package\n * is aimed at phones, and a setting that every consumer has to understand the\n * renderer to switch on is one most of them never will. Both are documented\n * with the value to use per device tier. Everything else is off, and off\n * means the behaviour this package had before these knobs existed.\n *\n * @group Engine\n */\n/**\n * The hard ceiling on {@link SplatQuality.minOpacity}.\n *\n * A limit rather than a recommendation, so it is enforced in the setter: this\n * knob is the one a per-device tuning pass is most likely to keep winding up,\n * because every increment buys real frame time and the cost arrives gradually\n * and everywhere at once rather than as an obvious artefact. Past this point a\n * character is losing the faint splats that soft edges and skin shading are\n * actually made of, and no device's frame budget is worth that.\n */\nconst MAX_MIN_OPACITY = 0.1;\n\nlet _quadAlphaCutoff = 8 / 255;\nlet _screenSizeCull = 0;\nlet _minOpacity = 0.05;\nlet _pruneRatio = 0;\nlet _pruneVoxelSize = 0.04;\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\n\nlet warnedAboutCap = false;\n\nexport const SplatQuality = {\n /**\n * Alpha at which a splat's quad is allowed to end, so each one is sized to\n * the radius its own opacity actually reaches instead of to the worst case.\n * **The first knob to reach for on a weak GPU.**\n *\n * The fragment stage multiplies a gaussian falloff by the splat's opacity\n * and discards anything below 1/255, so a quad drawn out to where that\n * product is already below the cutoff spends fragments on a ring that\n * cannot put ink on the screen. Raising the cutoff shrinks every quad. What\n * it costs is a harder edge on each splat, which shows first on soft things\n * - hair, fabric, anything semi-transparent.\n *\n * Takes effect on the next frame; nothing is reloaded and nothing is lost,\n * so it is safe to drive from a frame-rate governor.\n *\n * | Value | What it is for |\n * |---|---|\n * | `1 / 255` | Exactly the behaviour before this knob existed. Changes nothing at all: below it a fragment is discarded anyway, so the quad it trims was drawing nothing. |\n * | `8 / 255` | What the Unity build ships. The conservative end. |\n * | `12 / 255` | **The default here.** |\n * | `16 / 255` | **Low-end phones, and the floor.** Still 43.7 dB overall and 34.8 dB on the face, which the Unity build calls invisible at arm's length. |\n * | above `16 / 255` | Not on this project. The Unity build measures a further -7% at 24/255, but the edges are visibly harder by then; a device that needs more should spend it on {@link SplatQuality.pruneRatio}, the renderer's pixel ratio, or a distance LOD, none of which harden every silhouette in the frame. |\n *\n * Measured on a Mali-G57 with three characters, against 8/255: 12/255 -7%,\n * 16/255 -12%, 24/255 -19%. Measured here on an Apple GPU where fragments\n * are the bottleneck, against 1/255: 8/255 -29%, 16/255 -42%, 24/255 -50%.\n * Where the main thread is the bottleneck instead - the WebGL backend with\n * animated characters - it is free but buys nothing; see the README's\n * Tuning section for which case a scene is in.\n */\n get quadAlphaCutoff(): number {\n return _quadAlphaCutoff;\n },\n set quadAlphaCutoff(value: number) {\n _quadAlphaCutoff = clamp(value, 0, 1);\n },\n\n /**\n * Drop splats whose projected size falls below this radius in pixels, for\n * every splat at once. `0` (the default) draws everything.\n *\n * The same test as the per-splat {@link Splat.minPixelSize}; the larger of\n * the two wins, so a global floor cannot un-cull a splat an application\n * already asked to cull. Removes distant crowd splats that cannot contribute\n * more than a fraction of a pixel.\n */\n get screenSizeCull(): number {\n return _screenSizeCull;\n },\n set screenSizeCull(value: number) {\n _screenSizeCull = Math.max(0, value);\n },\n\n /**\n * Peak opacity a splat must reach to be kept when a character or scene is\n * loaded. `0` keeps everything.\n *\n * A splat's alpha at its centre IS its opacity - the gaussian only falls\n * off from there - so the faintest splats in a bundle are ones that paint\n * almost nothing from any camera while still costing memory, a skinning\n * pass, a sort slot and a quad. This removes them outright, which is what\n * separates it from {@link SplatQuality.quadAlphaCutoff}: the cutoff\n * shrinks a splat's quad and saves rasterisation alone, this saves\n * everything, but it cannot half-remove one.\n *\n * **Applied during the decode of a CHARACTER bundle**, so it only affects\n * what is loaded afterwards - set it before the first `load()`, and changing\n * it later does nothing to characters already in the scene. It does not\n * touch `.ply` scenes, matching the Unity build, which applies it in the\n * skinned renderer and nowhere else: a scene's opacity distribution is a\n * different thing, and 0.05 measured as 8.7% of a character against 41.8%\n * of a 1M-splat room. {@link pruneSplats} is exported for an application\n * that wants to make the trade on a scene of its own. It also changes\n * {@link Splat.numSplats}, so an application that hands back a per-splat\n * array ({@link Splat.setSplatGroups}) must size that array from\n * `numSplats` after loading rather than from the file.\n *\n * | Value | What it is for |\n * |---|---|\n * | `0` | Keep every splat. The behaviour before this knob existed. |\n * | `1 / 255` | Free in the strict sense: provably pixel-identical, because a splat under the fragment shader's own discard cannot produce a pixel. Worth about 2% of a character. |\n * | `0.05` | **The default here, and what the Unity build ships.** Removes ~13% of a typical character for a difference of at most 11/255 on 1.3% of it - 58-62 dB, which does not read as a quality loss. |\n * | above `0.05` | Untested. Prefer {@link SplatQuality.pruneRatio} to go further: it is measured, and it thins every region by the same share instead of taking the faintest splats wherever they happen to be - which is disproportionately the face. |\n */\n get minOpacity(): number {\n return _minOpacity;\n },\n set minOpacity(value: number) {\n if (value > MAX_MIN_OPACITY && !warnedAboutCap) {\n warnedAboutCap = true;\n console.warn(\n `[splat-engine-three] SplatQuality.minOpacity is capped at ${MAX_MIN_OPACITY}; ` +\n `${value} was requested and ${MAX_MIN_OPACITY} applied. Past the cap a character ` +\n 'loses the faint splats its soft edges are made of. To go further, use pruneRatio, ' +\n \"the renderer's pixel ratio, or a distance LOD.\",\n );\n }\n _minOpacity = clamp(value, 0, MAX_MIN_OPACITY);\n },\n\n /**\n * Fraction of splats removed at load by voxel-local importance, on top of\n * {@link SplatQuality.minOpacity}. `0` (the default) keeps everything, `0.5`\n * drops the least-important half of every cell.\n *\n * Importance is opacity times a splat's two largest axes - the area it\n * actually paints - ranked separately inside each spatial cell so a dense\n * region loses the same share as a sparse one rather than being deleted\n * wholesale. That per-cell quota is what keeps the face: a global ranking\n * puts the many faint facial splats at the bottom and smears it. Measured on\n * the Unity build's reference character at 0.5: 25,826 of 50,267 splats\n * remain, the frame falls 24.5% on a Mali-G57, and the face holds 43.5 dB\n * where a global rank gives 37.6.\n *\n * Applied during the decode of a character bundle, like\n * {@link SplatQuality.minOpacity}, with the same scope and the same reason\n * for being off by default.\n */\n get pruneRatio(): number {\n return _pruneRatio;\n },\n set pruneRatio(value: number) {\n _pruneRatio = clamp(value, 0, 1);\n },\n\n /**\n * Cell size, in metres, for {@link SplatQuality.pruneRatio}'s per-voxel\n * quota.\n *\n * 4 cm gives ~19 splats per occupied cell on the Unity build's reference\n * character - small enough that the face and the jacket are ranked apart,\n * large enough that a cell has a population to rank. A tuning constant\n * rather than a per-title knob, exposed because a character authored at a\n * different scale needs a different one.\n */\n get pruneVoxelSize(): number {\n return _pruneVoxelSize;\n },\n set pruneVoxelSize(value: number) {\n _pruneVoxelSize = Math.max(1e-4, value);\n },\n\n /**\n * Test each splat against the depth buffer, so opaque geometry hides the\n * splats behind it. On by default.\n *\n * Unlike the Unity build, where turning this off was the single largest\n * mobile saving, this is a correctness switch here and not a performance\n * one: that build renders splats into an offscreen target and pays for the\n * test by sampling a depth texture per fragment, where this package draws\n * straight into the camera's target and gets the hardware depth test for\n * free. Turning it off makes characters draw through walls and saves\n * nothing. It is here because the behaviour is occasionally what an\n * application wants - a character deliberately drawn over the scene.\n */\n depthOcclusion: true,\n\n /**\n * Collect {@link SplatQuality.timings}. Off by default.\n *\n * The CPU stages are timed with `performance.now()`, which is cheap but not\n * free at a few calls per splat per frame, and a shipping application that\n * never reads the numbers should not pay for them.\n */\n passTimings: false,\n\n /**\n * Per-stage cost of the last frame in which {@link SplatQuality.passTimings}\n * was on, in milliseconds, summed over every splat that ran that stage.\n *\n * These are main-thread times, which is the measurement that matters for\n * this package: under `WebGLRenderer` the per-character CPU cost - skinning\n * every centre to feed the sort, then the sort - is what limits how many\n * characters a scene can carry, and neither stage exists on the GPU\n * timeline. `skin` and `sort` are zero under `WebGPURenderer`, where both\n * happen in compute; `splatsDrawn` and `splatsTotal` are meaningful on both,\n * and differ when {@link SplatQuality.screenSizeCull} or a count LOD is\n * reducing what is submitted.\n *\n * These describe the most recent pass in which any splat drew, so read them\n * after your render call. A pass that drew no splats leaves the previous\n * numbers in place rather than zeroing them - a zero and \"nothing happened\"\n * would otherwise read the same, which is the mistake the Unity build's\n * equivalent made and spent a long time chasing.\n */\n timings: {\n /** CPU skinning of splat centres, i.e. `Splat.ensureCenters`. */\n skin: 0,\n /** The depth sort, where it runs on the main thread. */\n sort: 0,\n /** Uniform and buffer updates in `beforeRender`, excluding skin and sort. */\n prepare: 0,\n /** Splat instances submitted to the GPU this frame. */\n splatsDrawn: 0,\n /** Splat instances those draws could have covered at full detail. */\n splatsTotal: 0,\n },\n\n /** Restore every knob to its default. Call when tearing the engine down. */\n resetStatics(): void {\n SplatQuality.quadAlphaCutoff = 8 / 255;\n SplatQuality.screenSizeCull = 0;\n SplatQuality.minOpacity = 0.05;\n SplatQuality.pruneRatio = 0;\n SplatQuality.pruneVoxelSize = 0.04;\n SplatQuality.depthOcclusion = true;\n SplatQuality.passTimings = false;\n resetTimings();\n },\n};\n\n/** The effective sub-pixel cull for one splat: its own floor or the global one. */\nexport function effectiveMinPixelSize(splatMinPixelSize: number): number {\n const global = SplatQuality.screenSizeCull;\n return global > splatMinPixelSize ? global : splatMinPixelSize;\n}\n\n// CPU skinning happens during `engine.update()`, before anything renders, so\n// it cannot be accumulated into the same bucket the render-time stages fill:\n// the frame boundary falls between the two. It lands here instead, and the\n// first splat of the next frame moves it across - which is the frame it\n// belongs to, since the pose it skinned is the one about to be drawn.\nlet pendingSkin = 0;\n\n/**\n * Splats that have contributed to the current accumulation. Seeing one twice\n * is what marks the start of a new pass.\n *\n * There is no counter to key this on. `WebGLRenderer` has\n * `info.render.frame`, but `WebGPURenderer` has nothing equivalent: its\n * `info.frame` is declared and never written, and the node frame's id - the\n * only thing that does advance - is driven by the renderer's own\n * `requestAnimationFrame` loop, not by `render()`, so it stands still across\n * however many renders happen inside one display frame and advances on its\n * own in between. Keying a once-per-pass guard on either of those produces\n * something that holds for an entire display frame, or forever.\n *\n * Each splat drawing exactly once per pass is a property of the scene graph\n * rather than of a renderer, so that is what this uses instead.\n */\nconst contributors = new Set<object>();\n\n/**\n * Add a CPU skinning measurement for the frame now being prepared.\n * @internal\n */\nexport function addSkinTime(ms: number): void {\n pendingSkin += ms;\n}\n\nfunction resetTimings(): void {\n const t = SplatQuality.timings;\n t.skin = pendingSkin;\n pendingSkin = 0;\n t.sort = 0;\n t.prepare = 0;\n t.splatsDrawn = 0;\n t.splatsTotal = 0;\n}\n\n/**\n * Open this pass's timing accumulation, clearing it when `source` - the splat\n * reporting - has already contributed, which means a new pass has begun.\n * Called by every backend before it adds to {@link SplatQuality.timings}.\n *\n * @internal\n */\nexport function beginFrameTimings(source: object): void {\n if (contributors.has(source)) {\n contributors.clear();\n resetTimings();\n }\n contributors.add(source);\n}\n", "/**\n * Load-time splat removal: the two passes that make a character cheaper by\n * containing fewer splats, rather than by drawing each one faster.\n *\n * Both run on the decoded attribute columns, before {@link packSplats} turns\n * them into texels, so a removed splat costs nothing anywhere afterwards -\n * no texel, no CPU skinning slot, no sort slot, no quad. That is what\n * separates these from {@link SplatQuality.quadAlphaCutoff}, which shrinks\n * quads and saves rasterisation alone.\n *\n * Ported from the Unity build's `SplatCharacterBinData.CullByOpacity` and\n * `PruneByImportance`, including the two decisions in them that are easy to\n * get wrong: ranking inside spatial cells rather than globally, and selecting\n * rather than sorting within a cell.\n */\n\nimport type { SplatAttributes } from '../loader/character/types';\nimport type { SplatWeights } from '../types';\n\nimport { bucketByCell, cellKeyOf } from './importance';\nimport { SplatQuality } from './quality';\n\n/** Every per-splat column in {@link SplatAttributes}, so a compaction cannot miss one. */\nconst COLUMNS = [\n 'x', 'y', 'z',\n 'scale_0', 'scale_1', 'scale_2',\n 'rot_0', 'rot_1', 'rot_2', 'rot_3',\n 'f_dc_0', 'f_dc_1', 'f_dc_2',\n 'opacity',\n] as const;\n\n/** What {@link pruneSplats} did, for a caller that wants to log or report it. */\nexport interface PruneReport {\n /** Splats the decode handed in. */\n numSplatsIn: number;\n /** Splats left after both passes. This is what every consumer should read. */\n numSplatsOut: number;\n /** Removed by the opacity floor. */\n droppedByOpacity: number;\n /** Removed by the per-voxel importance quota, on top of the opacity floor. */\n droppedByImportance: number;\n /**\n * The skinning influences, re-viewed onto the compacted prefix when anything\n * was removed, or the caller's own object when nothing was. `undefined` for\n * a splat with no skinning.\n *\n * Handed back rather than mutated in place because the arrays' *length* is\n * what says how many influences each splat has: `Splat` divides it by the\n * splat count to recover `K`, and leaving a pruned set at its original\n * length would make that division report a `K` several times too large.\n */\n weights?: SplatWeights;\n}\n\nexport interface PruneOptions {\n /** Defaults to {@link SplatQuality.minOpacity}. */\n minOpacity?: number;\n /** Defaults to {@link SplatQuality.pruneRatio}. */\n pruneRatio?: number;\n /** Defaults to {@link SplatQuality.pruneVoxelSize}. */\n voxelSize?: number;\n}\n\n/**\n * Remove splats the current quality settings say are not worth carrying,\n * compacting every column in place.\n *\n * `attributes` and `weights` are mutated: their arrays keep their allocated\n * length and the returned count is what every consumer should read, which is\n * exactly how {@link packSplats} already uses `numSplats`. Order is preserved,\n * so whatever spatial coherence the file had survives.\n *\n * Returns the input count unchanged, having touched nothing, when both knobs\n * are off - the default - so this sits on the load path for free.\n */\nexport function pruneSplats(\n numSplats: number,\n attributes: SplatAttributes,\n weights?: SplatWeights,\n opts?: PruneOptions,\n): PruneReport {\n const minOpacity = opts?.minOpacity ?? SplatQuality.minOpacity;\n const pruneRatio = opts?.pruneRatio ?? SplatQuality.pruneRatio;\n const voxelSize = opts?.voxelSize ?? SplatQuality.pruneVoxelSize;\n\n const report: PruneReport = {\n numSplatsIn: numSplats,\n numSplatsOut: numSplats,\n droppedByOpacity: 0,\n droppedByImportance: 0,\n weights,\n };\n if (numSplats === 0) return report;\n\n const k = influencesPerSplat(numSplats, weights);\n let count = numSplats;\n if (minOpacity > 0) {\n const kept = cullByOpacity(count, attributes, weights, k, minOpacity);\n report.droppedByOpacity = count - kept;\n count = kept;\n }\n if (pruneRatio > 0 && voxelSize > 0) {\n const kept = pruneByImportance(count, attributes, weights, k, Math.min(pruneRatio, 1), voxelSize);\n report.droppedByImportance = count - kept;\n count = kept;\n }\n report.numSplatsOut = count;\n if (weights && count !== numSplats) {\n report.weights = {\n indices: weights.indices.subarray(0, count * k),\n weights: weights.weights.subarray(0, count * k),\n };\n }\n return report;\n}\n\n/** Number of influences per splat in `weights`, or 0 when there are none. */\nfunction influencesPerSplat(numSplats: number, weights?: SplatWeights): number {\n if (!weights || numSplats === 0) return 0;\n return Math.max(1, Math.floor(weights.indices.length / numSplats));\n}\n\n/**\n * Drop splats whose peak opacity is below `minOpacity`.\n *\n * A splat's alpha at its centre is its opacity - the gaussian only falls off\n * from there - so one below the fragment shader's own 1/255 discard cannot put\n * a single pixel on screen from any camera. Those splats are not a quality\n * trade at that threshold; above it they become one.\n *\n * The comparison runs against the logit rather than the alpha: `opacity` is\n * stored pre-sigmoid and the sigmoid is monotonic, so comparing against\n * `logit(minOpacity)` is the same test without a transcendental per splat.\n */\nfunction cullByOpacity(\n numSplats: number,\n attributes: SplatAttributes,\n weights: SplatWeights | undefined,\n influences: number,\n minOpacity: number,\n): number {\n // Any opacity passes a threshold of 0 or less; nothing passes one of 1 or more.\n if (minOpacity >= 1) return 0;\n const threshold = Math.log(minOpacity / (1 - minOpacity));\n const opacity = attributes.opacity;\n\n const keep = new Uint8Array(numSplats);\n let kept = 0;\n for (let i = 0; i < numSplats; i++) {\n if (opacity[i] >= threshold) {\n keep[i] = 1;\n kept++;\n }\n }\n if (kept === numSplats) return kept;\n compact(numSplats, keep, attributes, weights, influences);\n return kept;\n}\n\n/**\n * Drop the lowest-importance `ratio` fraction of splats *within* each\n * `voxelSize` cell, so every region gives up the same share and the density\n * the character was authored with survives.\n *\n * Importance is opacity times the two largest gaussian axes - the footprint a\n * splat actually paints. Ranking globally instead of per-cell is the obvious\n * version and the wrong one: facial detail is many individually-faint splats\n * where a jacket is few strong ones, so a global sort deletes the whole face\n * first. The Unity build measured both on its reference character at ratio\n * 0.5: per-cell held the face at 43.5 dB, a global rank at 37.6.\n */\nfunction pruneByImportance(\n numSplats: number,\n attributes: SplatAttributes,\n weights: SplatWeights | undefined,\n influences: number,\n ratio: number,\n voxelSize: number,\n): number {\n const { x, y, z, scale_0, scale_1, scale_2, opacity } = attributes;\n\n // Cell origin is the actual minimum of the positions, so the grid does not\n // inherit any margin a bundle's declared bounds might carry.\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n for (let i = 0; i < numSplats; i++) {\n if (x[i] < minX) minX = x[i];\n if (y[i] < minY) minY = y[i];\n if (z[i] < minZ) minZ = z[i];\n }\n\n const invVoxel = 1 / voxelSize;\n const score = new Float32Array(numSplats);\n const cellKey = new Float64Array(numSplats);\n\n for (let i = 0; i < numSplats; i++) {\n // Scales are stored as logs and opacity as a logit; both transforms are\n // monotonic, but the score is a product of the three, so they have to be\n // in linear units before being multiplied.\n const s0 = Math.exp(scale_0[i]);\n const s1 = Math.exp(scale_1[i]);\n const s2 = Math.exp(scale_2[i]);\n const mx = s0 > s1 ? (s0 > s2 ? s0 : s2) : (s1 > s2 ? s1 : s2);\n const mn = s0 < s1 ? (s0 < s2 ? s0 : s2) : (s1 < s2 ? s1 : s2);\n // The middle axis: the sum less the largest and the smallest.\n const md = s0 + s1 + s2 - mx - mn;\n const alpha = 1 / (1 + Math.exp(-opacity[i]));\n score[i] = alpha * mx * md;\n\n cellKey[i] = cellKeyOf(x[i], y[i], z[i], minX, minY, minZ, invVoxel);\n }\n\n const { order, start, cells } = bucketByCell(cellKey, numSplats);\n\n // Per cell, drop the floor(size * ratio) weakest. Only the PARTITION matters,\n // not the order within it, so this selects rather than sorts. Flooring keeps\n // at least one splat in any cell of fewer than 1/ratio members, so a sparse\n // region is never emptied.\n const keep = new Uint8Array(numSplats).fill(1);\n let dropped = 0;\n for (let c = 0; c < cells; c++) {\n const lo = start[c];\n const hi = start[c + 1];\n const size = hi - lo;\n const dropN = Math.floor(size * ratio);\n if (dropN <= 0) continue;\n if (dropN >= size) {\n for (let k = lo; k < hi; k++) keep[order[k]] = 0;\n dropped += size;\n continue;\n }\n selectWeakest(order, score, lo, hi, dropN);\n for (let k = 0; k < dropN; k++) keep[order[lo + k]] = 0;\n dropped += dropN;\n }\n\n if (dropped === 0) return numSplats;\n compact(numSplats, keep, attributes, weights, influences);\n return numSplats - dropped;\n}\n\n/**\n * Partially order `order[lo..hi)` so its first `k` entries are the `k`\n * lowest-scoring, in no particular order among themselves. That is all the\n * quota needs, and it is strictly less work than sorting the cell.\n */\nfunction selectWeakest(order: Uint32Array, score: Float32Array, lo: number, hi: number, k: number): void {\n // Median-of-three pivot: cells are spatially coherent, so their scores arrive\n // already partly ordered, which is the input that makes a first-element pivot\n // degenerate.\n while (hi - lo > 1) {\n const mid = lo + ((hi - lo) >> 1);\n const a = score[order[lo]];\n const b = score[order[mid]];\n const c = score[order[hi - 1]];\n const pivot = a < b ? (b < c ? b : (a < c ? c : a)) : (a < c ? a : (b < c ? c : b));\n\n let i = lo;\n let j = hi - 1;\n while (i <= j) {\n while (score[order[i]] < pivot) i++;\n while (score[order[j]] > pivot) j--;\n if (i <= j) {\n const t = order[i];\n order[i] = order[j];\n order[j] = t;\n i++;\n j--;\n }\n }\n // k counts from lo, so compare against the split point in the same frame.\n if (lo + k <= i && lo + k > j + 1) return; // the boundary landed inside the pivot run\n if (lo + k <= j + 1) hi = j + 1;\n else { k -= i - lo; lo = i; }\n }\n}\n\n/** Compact every per-splat column down to the entries `keep` marks, in place. */\nfunction compact(\n numSplats: number,\n keep: Uint8Array,\n attributes: SplatAttributes,\n weights: SplatWeights | undefined,\n k: number,\n): void {\n const indices = weights?.indices;\n const values = weights?.weights;\n\n let w = 0;\n for (let r = 0; r < numSplats; r++) {\n if (!keep[r]) continue;\n if (w !== r) {\n for (const column of COLUMNS) attributes[column][w] = attributes[column][r];\n // Skinning arrays are optional - a static capture has none - but when\n // they are present they are indexed by splat, so they compact in\n // lockstep or not at all.\n if (indices && values) {\n for (let j = 0; j < k; j++) {\n indices[w * k + j] = indices[r * k + j];\n values[w * k + j] = values[r * k + j];\n }\n }\n }\n w++;\n }\n}\n", "import {\n Box3,\n ClampToEdgeWrapping,\n DataTexture,\n FloatType,\n HalfFloatType,\n NearestFilter,\n RedFormat,\n RGBAFormat,\n RGBAIntegerFormat,\n Sphere,\n UnsignedIntType,\n Vector2,\n Vector3,\n Vector4,\n} from 'three';\nimport type { Frustum, PixelFormat, TextureDataType } from 'three';\n\nimport type { SplatEngine } from '../engine';\nimport type { Mat4 } from '../math';\nimport type { SplatWeights } from '../types';\n\nimport type { SplatColorModifier } from './color-modifier';\nimport { packCutGroups } from './cut-groups';\nimport { buildImportanceOrder } from './importance';\nimport type { PackedSplats } from './packed-splats';\nimport { SplatQuality, addSkinTime } from './quality';\nimport type { SplatRelightBinding } from './relight-binding';\nimport { bakeRevealDistances } from './reveal-bake';\nimport type { RevealSkeleton } from './reveal-bake';\nimport { DEFAULT_REVEAL_LOOK, packRevealLook } from './reveal-look';\nimport type { RevealLook } from './reveal-look';\nimport { SplatMesh } from './splat-mesh';\nimport { TransformPalette } from './transform-palette';\n\nconst WHITE_TINT = { r: 1, g: 1, b: 1 };\n\n/** Bones in the widest rig the skeleton library knows: the palette size for a bundle that does not say. */\nconst MAX_RIG_BONES = 1185;\n\nfunction dataTexture(\n name: string,\n data: ArrayBufferView,\n width: number,\n height: number,\n format: PixelFormat,\n type: TextureDataType,\n): DataTexture {\n const texture = new DataTexture(data as never, width, height, format, type);\n texture.name = name;\n texture.minFilter = NearestFilter;\n texture.magFilter = NearestFilter;\n texture.wrapS = ClampToEdgeWrapping;\n texture.wrapT = ClampToEdgeWrapping;\n texture.generateMipmaps = false;\n texture.needsUpdate = true;\n return texture;\n}\n\n/** What a {@link Splat} is built from: packed gaussians, plus skinning data for characters. */\nexport interface SplatSource {\n packed: PackedSplats;\n /** Present for skinned splats. Any `K` influences per splat; the top four are used. */\n splatWeights?: SplatWeights;\n /** Bone count of the rig the weights index into, when it differs from the armature's. */\n sourceBoneCount?: number;\n}\n\n/** @group Splats */\nexport interface SplatOptions {\n /**\n * Depth-sort in a worker instead of synchronously. Default: `true` for\n * unskinned splats, `false` for skinned ones (whose order must track the pose).\n */\n asyncSort?: boolean;\n}\n\n/**\n * Gaussian splat renderer.\n *\n * Owns the splat data textures, the bone index/weight textures used for\n * skeletal deformation, the transform palette written to by the linked\n * {@link Armature}, and the three.js mesh that draws it all. Skinning runs on\n * the GPU when the splat has weights; unskinned splats (environments) take the\n * same path with the identity transform.\n *\n * {@link Character.load} and {@link Environment.load} construct this\n * internally. Direct construction is only needed for custom loading pipelines.\n *\n * @group Splats\n */\nexport class Splat {\n readonly numSplats: number;\n /** The packed gaussian data backing the textures. */\n readonly packed: PackedSplats;\n /** The three.js object that draws this splat. Parent it; do not replace it. */\n readonly object3D: SplatMesh;\n\n readonly colorTexture: DataTexture;\n readonly transformATexture: DataTexture;\n readonly transformBTexture: DataTexture;\n\n /** Per-splat palette slot indices, four per splat. Rewritten when an armature binds. */\n boneIndicesData?: Float32Array;\n boneWeightsData?: Float32Array;\n boneIndicesTexture?: DataTexture;\n boneWeightsTexture?: DataTexture;\n\n groupIdsTexture?: DataTexture;\n variantMaskTexture?: DataTexture;\n variantMask?: Float32Array;\n groupIds?: Uint8Array;\n /** Bumped whenever the group ids or the variant mask change. */\n variantMaskVersion = 0;\n\n transformPalette: TransformPalette;\n /** rgb tint colour, w tint amount. Shared with the material by reference. */\n readonly tint = new Vector4(1, 1, 1, 0);\n /** x contrast, y saturation. Shared with the material by reference. */\n readonly grade = new Vector2(1, 1);\n /**\n * x opacity, y reveal amount, z reveal inverse (0/1), w cut amount. Shared\n * with the material by reference. `(1, 1, 0, 0)` changes nothing.\n */\n readonly effects = new Vector4(1, 1, 0, 0);\n /** Reveal look: band (width, hold, max stretch), sketch (lead, density, dot scale), tint (rgb, luminance floor). */\n readonly revealBand = new Vector4();\n readonly revealSketch = new Vector4();\n readonly revealTint = new Vector4();\n /** Per-splat feet-to-head distance for the reveal. Skinned splats only, after {@link setReveal} opts in. */\n revealDistanceTexture?: DataTexture;\n /** Per-piece cut data, `numGroups x 1` each: offset + scale, pivot, axis + angle. See {@link setCutGroups}. */\n groupOffsetsTexture?: DataTexture;\n groupPivotsTexture?: DataTexture;\n groupRotsTexture?: DataTexture;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n linkedArmature: any = null;\n\n /** Skinning influences normalised to exactly four slots per splat. */\n splatWeights?: SplatWeights;\n sourceBoneCount?: number;\n\n /**\n * Splat centres in local space: the rest pose until the first skinning\n * update, the skinned pose after.\n *\n * Only kept current when the renderer sorts on the CPU (WebGL). Under WebGPU\n * this lags the pose; call {@link Splat.ensureCenters} before reading it.\n */\n centers: Float32Array;\n /** Bumped whenever {@link Splat.centers} changes. */\n centersVersion = 0;\n /**\n * Local-space bounds used for culling and visibility tests. With CPU\n * centres these track the pose exactly; without, they are the rest bounds\n * padded generously enough to contain any pose.\n */\n readonly localBounds = new Box3();\n\n /** Discard splats smaller than this many pixels on screen. `0` draws everything. */\n minPixelSize = 0;\n\n private _activeSplatCount: number;\n private _importanceOrder: Uint32Array | null = null;\n /** `_importanceOrder` inverted: each splat's place in it. @internal */\n private _importanceRank: Uint32Array | null = null;\n\n private readonly _mesh: SplatMesh;\n private _cpuInfluences: Float32Array | null = null;\n private _pendingBoneTransforms: Mat4[] | null = null;\n private _flatBones: Float32Array | null = null;\n private _variantMaskEnabled = false;\n private _cutEnabled = false;\n private _revealEnabled = false;\n private _revealBaked = false;\n private _colorModifier: SplatColorModifier | null = null;\n private _relight: SplatRelightBinding | null = null;\n // Bone->palette mapping recorded when an armature binds (rememberBoneMapping),\n // so a re-upload of edited weights writes palette slots, not raw rig indices.\n private _boneMapFirstIdx: number | null = null;\n private _boneMapRemap: Int32Array | null = null;\n private _nonRigidCov = false;\n private _antiAlias = false;\n private _destroyed = false;\n private readonly _worldBounds = new Box3();\n private readonly _worldSphere = new Sphere();\n private readonly _groundHist = new Int32Array(256);\n\n constructor(engine: SplatEngine, source: SplatSource, opts?: SplatOptions) {\n const { packed } = source;\n this.packed = packed;\n this.numSplats = packed.numSplats;\n this.sourceBoneCount = source.sourceBoneCount;\n\n const { width, height } = packed;\n this.colorTexture = dataTexture('splatColor', packed.color, width, height, RGBAFormat, HalfFloatType);\n this.transformATexture = dataTexture('transformA', packed.transformA, width, height, RGBAIntegerFormat, UnsignedIntType);\n this.transformATexture.internalFormat = 'RGBA32UI';\n this.transformBTexture = dataTexture('transformB', packed.transformB, width, height, RGBAFormat, HalfFloatType);\n\n this.localBounds.min.fromArray(packed.boundsMin);\n this.localBounds.max.fromArray(packed.boundsMax);\n\n if (source.splatWeights) {\n this.splatWeights = this._normalizeWeights(source.splatWeights);\n this.boneIndicesData = new Float32Array(width * height * 4);\n this.boneWeightsData = new Float32Array(width * height * 4);\n // Raw rig indices for now; an armature rewrites them as palette slots when it binds.\n this.boneIndicesData.set(this.splatWeights.indices);\n this.boneWeightsData.set(this.splatWeights.weights);\n this.boneIndicesTexture = dataTexture('boneIndices', this.boneIndicesData, width, height, RGBAFormat, FloatType);\n this.boneWeightsTexture = dataTexture('boneWeights', this.boneWeightsData, width, height, RGBAFormat, FloatType);\n this._bakeInfluences();\n // Skinning moves centres every frame, so they need their own buffer.\n this.centers = new Float32Array(packed.centers);\n } else {\n this.centers = packed.centers;\n }\n\n // Sized to the bundle's own rig (plus the identity slot) so the per-frame\n // upload is no larger than it has to be. Binding to a bigger armature\n // grows it, which the backends handle.\n this.transformPalette = new TransformPalette(\n this.splatWeights ? (this.sourceBoneCount ?? MAX_RIG_BONES) + 1 : 1,\n );\n\n if (this.splatWeights) {\n // Until CPU-skinned centres exist (and under WebGPU they never do),\n // nothing tracks the pose, so pad the rest bounds by the character's own\n // half-size: room for a raised arm, a kick, or a jump.\n const size = this.localBounds.getSize(_size);\n this.localBounds.expandByScalar(0.5 * Math.max(size.x, size.y, size.z));\n }\n this._uncutBounds.copy(this.localBounds);\n\n this._activeSplatCount = this.numSplats;\n this.minPixelSize = engine.subPixelCull;\n packRevealLook(DEFAULT_REVEAL_LOOK, _band, _sketch, _tint);\n this.revealBand.fromArray(_band);\n this.revealSketch.fromArray(_sketch);\n this.revealTint.fromArray(_tint);\n\n const asyncSort = opts?.asyncSort ?? !this.splatWeights;\n this._mesh = new SplatMesh(this, engine, asyncSort);\n this.object3D = this._mesh;\n\n Splat._liveInstances.add(this);\n }\n\n /**\n * A new, independent splat over the same packed data, carrying this one's\n * render options. For unskinned splats only.\n * @internal\n */\n cloneStatic(engine: SplatEngine, asyncSort: boolean): Splat {\n const copy = new Splat(engine, { packed: this.packed }, { asyncSort });\n copy.tint.copy(this.tint);\n copy.grade.copy(this.grade);\n copy.effects.x = this.effects.x;\n copy.minPixelSize = this.minPixelSize;\n copy.antiAlias = this.antiAlias;\n return copy;\n }\n\n /** Top-4 influences per splat, zero-padded. The shader and the CPU path both assume four. */\n private _normalizeWeights(src: SplatWeights): SplatWeights {\n const n = this.numSplats;\n const k = n > 0 ? Math.max(1, Math.floor(src.indices.length / n)) : 4;\n if (k === 4) return { indices: src.indices, weights: src.weights };\n const indices = new Uint16Array(n * 4);\n const weights = new Float32Array(n * 4);\n const take = Math.min(k, 4);\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < take; j++) {\n indices[i * 4 + j] = src.indices[i * k + j];\n weights[i * 4 + j] = src.weights[i * k + j];\n }\n }\n return { indices, weights };\n }\n\n /**\n * How many splats are skinned, sorted and drawn this frame: the whole set,\n * or the first `n` of {@link Splat.importanceOrder} after\n * {@link Splat.setCountLod}.\n */\n get activeSplatCount(): number {\n return this._activeSplatCount;\n }\n\n /** Whether a count LOD is currently reducing this splat. */\n get countLodActive(): boolean {\n return this._activeSplatCount < this.numSplats;\n }\n\n /**\n * Process only the `n` most important splats this frame, or the whole set\n * with `null`.\n *\n * The dynamic counterpart of {@link SplatQuality.pruneRatio}: the prune\n * decides once, at load, that some splats are not worth carrying at all,\n * while this decides per frame how many of them are worth the work right\n * now - which is the trade a character makes as it walks away from the\n * camera. Nothing is freed, so it reverses the moment `n` goes back up.\n *\n * Which splats the first `n` are is {@link Splat.importanceOrder}'s answer:\n * the strongest splat of every 4 cm cell, then the second of every cell, and\n * so on, so the character thins evenly rather than losing a region.\n *\n * `WebGLRenderer` only, where it is worth the most: that backend skins every\n * splat centre on the CPU each frame to feed its sort, and this cuts that\n * pass, the sort and the draw together. Under `WebGPURenderer` all of that\n * already happens in compute, and the call is accepted and ignored rather\n * than silently changing which splats a GPU sort can see.\n *\n * {@link Character.setSplatCountLod} drives this from camera distance; call\n * it directly for a policy of your own.\n */\n setCountLod(n: number | null): void {\n const next = n === null ? this.numSplats : Math.max(1, Math.min(this.numSplats, Math.floor(n)));\n if (next === this._activeSplatCount) return;\n if (next < this.numSplats) this.prepareCountLod();\n this._activeSplatCount = next;\n // The drawn set changed, so both the skinned centres and the order are\n // stale even if nothing else moved.\n this.centersVersion++;\n this._mesh.requestSort();\n }\n\n /**\n * Build {@link Splat.importanceOrder} now, if it does not exist yet.\n *\n * One pass over the splats plus a small sort inside each 4 cm cell - single\n * digit milliseconds for a character, but milliseconds that would otherwise\n * land on the frame where the LOD first engages, which is a frame where the\n * camera is already moving. {@link Character.setSplatCountLod} calls this\n * when the LOD is configured, so the cost lands there instead.\n */\n prepareCountLod(): void {\n if (this._importanceRank) return;\n const order = this._importanceOrder ??= buildImportanceOrder(this.packed, SplatQuality.pruneVoxelSize);\n // Inverted once, here, because every per-frame user of it asks the\n // question the other way round: not \"which splat is 1000th\" but \"is this\n // splat in the first K\". Walking the splats in order and testing their\n // rank keeps the per-frame passes sequential; walking the ordering itself\n // would chase a scattered list and cost a cache miss per splat.\n const rank = new Uint32Array(order.length);\n for (let i = 0; i < order.length; i++) rank[order[i]] = i;\n this._importanceRank = rank;\n }\n\n /**\n * Each splat's place in {@link Splat.importanceOrder}, which is how the\n * per-frame passes test membership of the active prefix. `null` until\n * {@link Splat.prepareCountLod}.\n * @internal\n */\n get importanceRank(): Uint32Array | null {\n return this._importanceRank;\n }\n\n /**\n * Splat indices ordered by importance for {@link Splat.setCountLod}. `null`\n * until {@link Splat.prepareCountLod} or a count LOD has asked for one.\n */\n get importanceOrder(): Uint32Array | null {\n return this._importanceOrder;\n }\n\n /** Re-upload the bone index/weight textures after editing their data arrays. */\n markBoneTexturesDirty(): void {\n this._mesh.syncBoneData();\n }\n\n /** Keep CPU-skinned centres (sorting and ground probes) on the same bone\n * mapping as the GPU shader. Called once when an armature binds this splat. */\n syncMappedCpuInfluences(firstPaletteIdx: number): void {\n const packed = this._cpuInfluences;\n const indices = this.boneIndicesData;\n const weights = this.boneWeightsData;\n if (!packed || !indices || !weights) return;\n for (let s = 0; s < this.numSplats; s++) {\n const base = s * 11;\n const src = s * 4;\n for (let j = 0; j < 4; j++) {\n packed[base + 3 + j * 2] = weights[src + j];\n packed[base + 4 + j * 2] = indices[src + j] - firstPaletteIdx;\n }\n }\n }\n\n get variantMaskEnabled(): boolean {\n return this._variantMaskEnabled;\n }\n\n get nonRigidCovariance(): boolean {\n return this._nonRigidCov;\n }\n\n /**\n * Toggle the non-rigid covariance shader path. When on, the palette's\n * per-axis scale stretches each gaussian's covariance; the palette must then\n * actually carry that scale (see `SplatSkinning.covStretch`). Off is the\n * rigid path, where palette scale is treated as unit. Switching recompiles\n * the shader, so toggle it rarely.\n */\n setNonRigidCovariance(on: boolean): void {\n if (this._nonRigidCov === on) return;\n this._nonRigidCov = on;\n this._mesh.syncDefines();\n }\n\n /**\n * Compensate each splat's opacity for the screen-space dilation applied to\n * keep sub-pixel splats visible. Off by default; turn on for assets trained\n * with anti-aliasing (e.g. Mip-Splatting).\n */\n get antiAlias(): boolean {\n return this._antiAlias;\n }\n\n set antiAlias(on: boolean) {\n if (this._antiAlias === on) return;\n this._antiAlias = on;\n this._mesh.syncDefines();\n }\n\n /**\n * Blend every splat's colour toward `color` by `intensity` (0..1).\n * `intensity = 0` restores the authored colour.\n */\n setTint(intensity: number, color: { r: number; g: number; b: number } = WHITE_TINT): void {\n this.tint.set(color.r, color.g, color.b, intensity);\n }\n\n /** Per-splat colour grade. `(1, 1)` is a true no-op. */\n setGrade(contrast: number, saturation: number): void {\n this.grade.set(contrast, saturation);\n }\n\n /**\n * Like {@link setTint}, but multiplies: the splat colour times `color`, by\n * `strength` (0..1). Darkens or browns while keeping the splat's own\n * variation (cooking, scorching). `setTint` goes back to the mix.\n */\n setTintMultiply(strength: number, color: { r: number; g: number; b: number } = WHITE_TINT): void {\n // A negative amount is the shader's \"multiply\" flag.\n this.tint.set(color.r, color.g, color.b, -Math.max(0, Math.min(1, strength)));\n }\n\n /** Multiply every splat's alpha by `opacity` (0..1); 1, the default, leaves it. */\n setOpacity(opacity: number): void {\n this.effects.x = Math.min(1, Math.max(0, opacity));\n }\n\n /** The value last given to {@link setOpacity}. */\n get opacity(): number {\n return this.effects.x;\n }\n\n /**\n * Reveal amount in [0, 1]. At 1 (the default) the splat renders unchanged.\n * Below 1 a bright front walks from feet to head, with sparse dots just\n * ahead of it. Zero is invisible. `inverse` keeps the area ahead of the\n * front instead, for outgoing transitions.\n *\n * The first call below 1 (or with `inverse`) opts the splat in: it bakes\n * the per-splat distances through the linked {@link Armature} and rebuilds\n * the shader. Call {@link Armature.prepareReveal} after loading to pay that\n * up front. A splat that is never revealed pays nothing.\n */\n setReveal(amount: number, inverse = false): void {\n if (!this._revealEnabled && (amount < 1 || inverse)) {\n this.linkedArmature?.prepareReveal?.();\n this._enableReveal();\n }\n this.effects.y = Math.min(1, Math.max(0, amount));\n this.effects.z = inverse ? 1 : 0;\n }\n\n /**\n * Change how the reveal looks. Unset fields keep their current value; the\n * starting look is {@link DEFAULT_REVEAL_LOOK}.\n */\n setRevealLook(look: RevealLook): void {\n this.revealBand.toArray(_band);\n this.revealSketch.toArray(_sketch);\n this.revealTint.toArray(_tint);\n packRevealLook(look, _band, _sketch, _tint);\n this.revealBand.fromArray(_band);\n this.revealSketch.fromArray(_sketch);\n this.revealTint.fromArray(_tint);\n }\n\n /** Whether the reveal has been opted into - see {@link setReveal}. */\n get revealEnabled(): boolean {\n return this._revealEnabled;\n }\n\n /** Whether {@link bakeReveal} has run for this splat. */\n get revealBaked(): boolean {\n return this._revealBaked;\n }\n\n private _enableReveal(): void {\n if (this._revealEnabled) return;\n this._revealEnabled = true;\n if (this.splatWeights) {\n const { width, height } = this.packed;\n // A splat the bake never reaches stays hidden until the reveal completes.\n const data = new Float32Array(width * height).fill(1);\n this.revealDistanceTexture = dataTexture('splatRevealDistance', data, width, height, RedFormat, FloatType);\n }\n this._mesh.syncDefines();\n }\n\n /**\n * Bake the per-splat reveal distances against `skeleton`, opting the splat\n * into the reveal. Called by {@link Armature.prepareReveal}.\n *\n * @param boneRemap - Splat bone index to armature bone, `-1` when unmapped,\n * or `null` when the splat's bones are the armature's.\n */\n bakeReveal(skeleton: RevealSkeleton, boneRemap: ArrayLike<number> | null): void {\n this._enableReveal();\n this._revealBaked = true;\n const texture = this.revealDistanceTexture;\n if (!this.splatWeights || !texture) return;\n const n = this.numSplats;\n const rest = this.packed.centers;\n const x = new Float32Array(n), y = new Float32Array(n), z = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n x[i] = rest[i * 3];\n y[i] = rest[i * 3 + 1];\n z[i] = rest[i * 3 + 2];\n }\n const { indices, weights } = this.splatWeights;\n bakeRevealDistances(texture.image.data as Float32Array, { x, y, z, indices, weights, numSplats: n }, skeleton, boneRemap);\n texture.needsUpdate = true;\n }\n\n /** Whether {@link setCutGroups} has opted this splat in. */\n get cutEnabled(): boolean {\n return this._cutEnabled;\n }\n\n /**\n * Opt this splat into a \"cut\": its splats split into pieces that slide,\n * tumble and scale apart. `groupIds` tags each splat with a piece; each\n * piece gets a model-space `offset`, and optionally a `pivot` and a\n * `rotation` (it tumbles rigidly about its pivot) and a uniform `scale`\n * about the pivot. Starts fully cut ({@link setCut} 1); animate with\n * `setCut`. Uses the {@link setSplatGroups} group ids.\n *\n * @param groupIds - per-splat piece, length {@link numSplats}.\n * @param offsets - `numGroups x 3` model-space offsets.\n * @param numGroups - the number of pieces.\n * @param pivots - optional `numGroups x 3` pivots (default the origin).\n * @param rotations - optional `numGroups x 4`: unit axis xyz, angle (rad).\n * @param scales - optional `numGroups` uniform scales (default 1).\n */\n setCutGroups(\n groupIds: Uint8Array,\n offsets: Float32Array,\n numGroups: number,\n pivots?: Float32Array,\n rotations?: Float32Array,\n scales?: Float32Array,\n ): void {\n if (offsets.length < numGroups * 3) {\n throw new Error(`Splat.setCutGroups: offsets length ${offsets.length} < numGroups*3 ${numGroups * 3}`);\n }\n if (!this.groupOffsetsTexture || this.groupOffsetsTexture.image.width !== numGroups) {\n this.groupOffsetsTexture?.dispose();\n this.groupPivotsTexture?.dispose();\n this.groupRotsTexture?.dispose();\n const tex = (name: string) =>\n dataTexture(name, new Float32Array(numGroups * 4), numGroups, 1, RGBAFormat, FloatType);\n this.groupOffsetsTexture = tex('splatGroupOffsets');\n this.groupPivotsTexture = tex('splatGroupPivots');\n this.groupRotsTexture = tex('splatGroupRots');\n }\n this._uploadCutData(offsets, numGroups, pivots, rotations, scales);\n const newlyCut = !this._cutEnabled;\n this._cutEnabled = true;\n const variantWasOn = this._variantMaskEnabled;\n // Uploads the group ids, and rebuilds the shader when it turns the mask on.\n this.setSplatGroups(groupIds, numGroups);\n if (newlyCut && variantWasOn) this._mesh.syncDefines();\n this.setCut(1);\n }\n\n /**\n * Rewrite the pieces' offsets, pivots, rotations and scales without a\n * shader rebuild, e.g. to dice finer on each chop, then show them fully\n * cut. No-op before {@link setCutGroups}, or with more groups than it\n * allocated.\n */\n setCutOffsets(\n offsets: Float32Array,\n numGroups: number,\n pivots?: Float32Array,\n rotations?: Float32Array,\n scales?: Float32Array,\n ): void {\n if (!this.groupOffsetsTexture) return;\n if (this.groupOffsetsTexture.image.width < numGroups || offsets.length < numGroups * 3) return;\n this._uploadCutData(offsets, numGroups, pivots, rotations, scales);\n this.setCut(1);\n }\n\n /** How far apart the pieces are: 0 whole, 1 fully cut. No-op before {@link setCutGroups}. */\n setCut(amount: number): void {\n this.effects.w = Math.max(0, Math.min(1, amount));\n this._mesh.requestSort();\n }\n\n private _uploadCutData(\n offsets: Float32Array,\n numGroups: number,\n pivots?: Float32Array,\n rotations?: Float32Array,\n scales?: Float32Array,\n ): void {\n const packed = packCutGroups(offsets, numGroups, pivots, rotations, scales);\n const write = (texture: DataTexture, data: Float32Array) => {\n (texture.image.data as Float32Array).set(data);\n texture.needsUpdate = true;\n };\n write(this.groupOffsetsTexture!, packed.offsets);\n write(this.groupPivotsTexture!, packed.pivots);\n write(this.groupRotsTexture!, packed.rotations);\n this.variantMaskVersion++;\n\n // Pieces move off the body, so the bounds used for culling and for the\n // depth range of a GPU sort must reach them: pad by the furthest any\n // piece can get at any cut amount - its slide, plus, if it turns or\n // grows, a full sweep about its pivot.\n this._uncutBounds.getBoundingSphere(_sphere);\n let pad = 0;\n for (let g = 0; g < numGroups; g++) {\n const i = g * 4;\n const o = packed.offsets;\n let reach = Math.hypot(o[i], o[i + 1], o[i + 2]);\n const scale = o[i + 3];\n if (packed.rotations[i + 3] !== 0 || scale !== 1) {\n const pv = packed.pivots;\n const toPivot = Math.hypot(pv[i] - _sphere.center.x, pv[i + 1] - _sphere.center.y, pv[i + 2] - _sphere.center.z);\n reach += 2 * (toPivot + _sphere.radius) * Math.max(1, scale);\n }\n if (reach > pad) pad = reach;\n }\n this._cutPad = pad;\n this._padForCut();\n }\n\n /** Set {@link localBounds} to the uncut bounds grown by the cut's reach, once. @internal */\n private _padForCut(): void {\n this.localBounds.copy(this._uncutBounds);\n if (this._cutPad > 0) this.localBounds.expandByScalar(this._cutPad);\n this._mesh.syncBounds();\n }\n\n private _cutPad = 0;\n // localBounds before the cut pad: what the pad is measured from and applied to.\n private readonly _uncutBounds = new Box3();\n\n /** The hook set by {@link setColorModifier}, or `null`. */\n get colorModifier(): SplatColorModifier | null {\n return this._colorModifier;\n }\n\n /**\n * Run a colour hook of the game's own on every splat, after the engine's\n * colour work - see {@link SplatColorModifier}. `null` removes it. Each\n * call rebuilds the shader; change the hook's uniforms to animate it.\n */\n setColorModifier(modifier: SplatColorModifier | null): void {\n this._colorModifier = modifier;\n this._mesh.syncDefines();\n }\n\n /** The relight writing into this splat, or `null`. @internal */\n get relightBinding(): SplatRelightBinding | null {\n return this._relight;\n }\n\n /**\n * Attach the per-splat output of a {@link SplatRelight}, or detach it with\n * `null`. Rebuilds the shader when the relight turns on or off.\n * @internal\n */\n setRelightBinding(binding: SplatRelightBinding | null): void {\n if (this._relight === binding) return;\n const toggled = !this._relight !== !binding;\n this._relight = binding;\n if (toggled) this._mesh.syncDefines();\n else this._mesh.syncRelight();\n }\n\n /**\n * Put the splat on exactly these three.js layers (0..31), for cameras that\n * render a subset of the scene. `[0]` is the default.\n */\n setLayers(layerIds: number[]): void {\n const layers = this.object3D.layers;\n layers.disableAll();\n for (const id of layerIds) layers.enable(id);\n }\n\n /**\n * Record the palette base and source->target remap the armature chose when\n * it bound this splat, so a later {@link reuploadBoneWeights} writes\n * palette slots, not raw rig indices.\n */\n rememberBoneMapping(firstIdx: number, _numBones: number, remap: Int32Array | null): void {\n this._boneMapFirstIdx = firstIdx;\n this._boneMapRemap = remap;\n }\n\n /**\n * `true` once this splat's bone weights are its own to edit. Splats built\n * from shared decoded data (clones, overlays) share\n * {@link Splat.splatWeights} until {@link privatizeBoneWeights}.\n */\n get boneWeightsArePrivate(): boolean {\n return !!this.splatWeights && this._weightsPrivate;\n }\n\n private _weightsPrivate = false;\n\n /**\n * Give this splat its own copy of {@link Splat.splatWeights}, so editing\n * them (a ragdoll detaching a limb, hit-based weight pruning) and calling\n * {@link reuploadBoneWeights} leaves every other splat alone. Idempotent.\n */\n privatizeBoneWeights(): void {\n if (!this.splatWeights || this._weightsPrivate) return;\n this.splatWeights = {\n indices: new Uint16Array(this.splatWeights.indices),\n weights: new Float32Array(this.splatWeights.weights),\n };\n this._weightsPrivate = true;\n }\n\n /**\n * Upload the current {@link Splat.splatWeights} to the GPU after editing\n * them, through the palette mapping the armature chose. Call\n * {@link privatizeBoneWeights} first.\n */\n reuploadBoneWeights(): void {\n if (!this._weightsPrivate) {\n throw new Error(\n '[Splat] reuploadBoneWeights: bone weights are still shared with other instances. ' +\n 'Call privatizeBoneWeights() first or you will corrupt sibling characters.',\n );\n }\n const sw = this.splatWeights;\n const indicesData = this.boneIndicesData;\n const weightsData = this.boneWeightsData;\n if (!sw || !indicesData || !weightsData) return;\n const firstIdx = this._boneMapFirstIdx;\n const remap = this._boneMapRemap;\n const n = this.numSplats;\n for (let i = 0; i < n * 4; i++) {\n const raw = sw.indices[i];\n if (firstIdx === null) {\n indicesData[i] = raw;\n weightsData[i] = sw.weights[i];\n } else {\n const target = remap ? (remap[raw] ?? -1) : raw;\n if (target < 0) {\n indicesData[i] = firstIdx;\n weightsData[i] = 0;\n } else {\n indicesData[i] = firstIdx + target;\n weightsData[i] = sw.weights[i];\n }\n }\n }\n this._bakeInfluences();\n if (firstIdx !== null) this.syncMappedCpuInfluences(firstIdx);\n this._mesh.syncBoneData();\n }\n\n /**\n * Splat centres (splat-local) in the latest pose. Under WebGL they are\n * kept current anyway; under WebGPU this skins them on the CPU on demand,\n * for picking or ground probes.\n */\n posedCenters(): Float32Array {\n this.ensureCenters();\n return this.centers;\n }\n\n /**\n * Assign each splat to a group and enable per-group visibility. All groups\n * start visible; toggle them with {@link Splat.setVariantMask}.\n *\n * `groupIds` is indexed by splat, so it has to be built against\n * {@link Splat.numSplats} as loaded - which {@link SplatQuality.minOpacity}\n * makes smaller than the count in the file. An array authored offline\n * against the file cannot simply be shortened: see the error this throws.\n */\n setSplatGroups(groupIds: Uint8Array, numGroups: number): void {\n if (groupIds.length !== this.numSplats) {\n // Spelled out because the obvious repair is the wrong one. Cutting an\n // array that was authored against the file down to this length hands\n // every surviving splat the id of a different splat, which draws the\n // wrong parts of the character and throws nothing - strictly worse than\n // this. Either build the array from the splats that loaded, or load the\n // character with SplatQuality.minOpacity = 0 so the file's indices and\n // these ones are the same thing.\n throw new Error(\n `Splat.setSplatGroups: groupIds has ${groupIds.length} entries but this splat has ` +\n `${this.numSplats}. One id per loaded splat is required. If the array was authored ` +\n 'against the source file, do not truncate it - its indices no longer line up, because ' +\n 'SplatQuality.minOpacity drops splats during the decode. Build it from the loaded ' +\n 'splats, or set SplatQuality.minOpacity = 0 before loading this character.',\n );\n }\n if (numGroups < 1) throw new Error('Splat.setSplatGroups: numGroups must be \u22651');\n this.groupIds = groupIds;\n\n const { width, height } = this.packed;\n if (!this.groupIdsTexture) {\n this.groupIdsTexture = dataTexture('splatGroupIds', new Float32Array(width * height), width, height, RedFormat, FloatType);\n }\n const gidData = this.groupIdsTexture.image.data as Float32Array;\n for (let i = 0; i < this.numSplats; i++) gidData[i] = groupIds[i];\n this.groupIdsTexture.needsUpdate = true;\n\n if (!this.variantMaskTexture || this.variantMaskTexture.image.width !== numGroups) {\n this.variantMaskTexture?.dispose();\n this.variantMask = new Float32Array(numGroups);\n this.variantMaskTexture = dataTexture('splatVariantMask', this.variantMask, numGroups, 1, RedFormat, FloatType);\n }\n this.variantMask!.fill(1);\n this.variantMaskTexture.needsUpdate = true;\n this.variantMaskVersion++;\n\n if (!this._variantMaskEnabled) {\n this._variantMaskEnabled = true;\n this._mesh.syncDefines();\n } else {\n this._mesh.syncVariantGroups();\n }\n }\n\n /** Per-group visibility, one entry per group: `>= 0.5` shows the group. */\n setVariantMask(mask: ArrayLike<number>): void {\n if (!this.variantMaskTexture || !this.variantMask) return;\n const n = Math.min(this.variantMask.length, mask.length);\n for (let i = 0; i < n; i++) this.variantMask[i] = mask[i];\n this.variantMaskTexture.needsUpdate = true;\n this.variantMaskVersion++;\n }\n\n /** Whether the splat's world-space bounding sphere touches `frustum`. */\n isInFrustum(frustum: Frustum): boolean {\n this.object3D.updateWorldMatrix(true, false);\n this._worldBounds.copy(this.localBounds).applyMatrix4(this.object3D.matrixWorld);\n this._worldBounds.getBoundingSphere(this._worldSphere);\n return frustum.intersectsSphere(this._worldSphere);\n }\n\n /** World-space bounds of the splat in its current pose. */\n getWorldAabb(out: Box3 = new Box3()): Box3 {\n this.object3D.updateWorldMatrix(true, false);\n return out.copy(this.localBounds).applyMatrix4(this.object3D.matrixWorld);\n }\n\n /** World-space Y of the lowest corner of the current bounds. */\n getWorldMinY(): number {\n return this.getWorldAabb(this._worldBounds).min.y;\n }\n\n /**\n * World-space Y of the splat's ground contact: the height below which only\n * `quantile` of the splats lie. More robust than the bounds minimum, which a\n * single stray gaussian can drag down.\n */\n getGroundWorldY(quantile = 0.005): number {\n const n = this.numSplats;\n if (n === 0 || !this.splatWeights) return this.getWorldMinY();\n this.ensureCenters();\n const centers = this.centers;\n\n this.object3D.updateWorldMatrix(true, false);\n const m = this.object3D.matrixWorld.elements;\n const worldY = (i: number) =>\n m[1] * centers[i * 3] + m[5] * centers[i * 3 + 1] +\n m[9] * centers[i * 3 + 2] + m[13];\n\n let lo = Infinity, hi = -Infinity;\n for (let i = 0; i < n; i++) {\n const y = worldY(i);\n if (y < lo) lo = y;\n if (y > hi) hi = y;\n }\n if (!(hi > lo)) return lo;\n\n const BUCKETS = 256;\n const counts = this._groundHist;\n counts.fill(0);\n const scale = BUCKETS / (hi - lo);\n for (let i = 0; i < n; i++) {\n const y = worldY(i);\n let b = ((y - lo) * scale) | 0;\n if (b >= BUCKETS) b = BUCKETS - 1;\n if (b < 0) b = 0;\n counts[b]++;\n }\n const threshold = Math.max(1, Math.floor(n * quantile));\n let cum = 0;\n let boundary = lo;\n for (let b = 0; b < BUCKETS; b++) {\n cum += counts[b];\n if (cum >= threshold) { boundary = lo + (b + 1) / scale; break; }\n }\n return boundary;\n }\n\n /**\n * Flatten rest centres and influences into one interleaved buffer for the\n * per-frame CPU skinning pass: `[x, y, z, w0, b0, w1, b1, w2, b2, w3, b3]`.\n */\n private _bakeInfluences(): void {\n if (!this.splatWeights) return;\n const rest = this.packed.centers;\n const { indices, weights } = this.splatWeights;\n const STRIDE = 11;\n const buf = new Float32Array(this.numSplats * STRIDE);\n for (let i = 0, base = 0; i < this.numSplats; i++, base += STRIDE) {\n buf[base] = rest[i * 3];\n buf[base + 1] = rest[i * 3 + 1];\n buf[base + 2] = rest[i * 3 + 2];\n const src = i * 4;\n for (let j = 0; j < 4; j++) {\n buf[base + 3 + j * 2] = weights[src + j];\n buf[base + 4 + j * 2] = indices[src + j];\n }\n }\n this._cpuInfluences = buf;\n }\n\n /**\n * Tell the splat its bone matrices changed. When the renderer sorts on the\n * CPU the centres are re-skinned immediately; otherwise the work is deferred\n * until something asks for them ({@link Splat.ensureCenters}).\n */\n updatePositions(boneTransforms: Mat4[]): void {\n if (!this.splatWeights || !boneTransforms.length) return;\n this._pendingBoneTransforms = boneTransforms;\n if (this._mesh.needsCpuCenters) this.ensureCenters();\n }\n\n /** Bring {@link Splat.centers} up to date with the latest bone matrices. */\n ensureCenters(): void {\n const boneTransforms = this._pendingBoneTransforms;\n if (!boneTransforms) return;\n this._pendingBoneTransforms = null;\n if (!SplatQuality.passTimings) {\n this._skinCenters(boneTransforms);\n return;\n }\n const t0 = performance.now();\n this._skinCenters(boneTransforms);\n addSkinTime(performance.now() - t0);\n }\n\n /**\n * Skin the splat centres on the CPU with the same matrices the GPU uses.\n * This is the dominant per-character CPU cost, which is why it only runs\n * when something needs the result.\n */\n private _skinCenters(boneTransforms: Mat4[]): void {\n const packed = this._cpuInfluences;\n if (!packed) return;\n\n // Copy the affine 3x4 of every bone into one flat array first. The inner\n // loop then reads plain typed-array slots instead of chasing a Mat4 object\n // per influence, which is worth a large constant factor over ~50k splats.\n const numBones = boneTransforms.length;\n let bones = this._flatBones;\n if (!bones || bones.length !== numBones * 12) {\n bones = this._flatBones = new Float32Array(numBones * 12);\n }\n for (let b = 0, o = 0; b < numBones; b++, o += 12) {\n const m = boneTransforms[b].data;\n bones[o] = m[0]; bones[o + 1] = m[4]; bones[o + 2] = m[8]; bones[o + 3] = m[12];\n bones[o + 4] = m[1]; bones[o + 5] = m[5]; bones[o + 6] = m[9]; bones[o + 7] = m[13];\n bones[o + 8] = m[2]; bones[o + 9] = m[6]; bones[o + 10] = m[10]; bones[o + 11] = m[14];\n }\n\n const centers = this.centers;\n // A count LOD skins only the prefix it will draw; the centres of the rest\n // keep whatever pose they were last skinned in, which nothing reads -\n // neither the sort nor the draw touches a splat outside the prefix. The\n // pass still walks every splat in index order and skips the ones it does\n // not want, rather than walking the prefix: see Splat.prepareCountLod.\n const count = this.numSplats;\n const active = this._activeSplatCount;\n const rank = active < count ? this._importanceRank : null;\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n\n for (let i = 0, base = 0, ci = 0; i < count; i++, base += 11, ci += 3) {\n if (rank !== null && rank[i] >= active) continue;\n const rx = packed[base];\n const ry = packed[base + 1];\n const rz = packed[base + 2];\n\n let outX = 0, outY = 0, outZ = 0, totalWeight = 0;\n for (let k = 0; k < 4; k++) {\n const w = packed[base + 3 + k * 2];\n if (w < 0.001) continue;\n const b = packed[base + 4 + k * 2] | 0;\n if (b >= numBones) continue;\n const o = b * 12;\n outX += (rx * bones[o] + ry * bones[o + 1] + rz * bones[o + 2] + bones[o + 3]) * w;\n outY += (rx * bones[o + 4] + ry * bones[o + 5] + rz * bones[o + 6] + bones[o + 7]) * w;\n outZ += (rx * bones[o + 8] + ry * bones[o + 9] + rz * bones[o + 10] + bones[o + 11]) * w;\n totalWeight += w;\n }\n\n let cx: number, cy: number, cz: number;\n if (totalWeight > 0.001) {\n const inv = 1 / totalWeight;\n cx = outX * inv;\n cy = outY * inv;\n cz = outZ * inv;\n } else {\n cx = rx;\n cy = ry;\n cz = rz;\n }\n\n centers[ci] = cx;\n centers[ci + 1] = cy;\n centers[ci + 2] = cz;\n\n if (cx < minX) minX = cx;\n if (cx > maxX) maxX = cx;\n if (cy < minY) minY = cy;\n if (cy > maxY) maxY = cy;\n if (cz < minZ) minZ = cz;\n if (cz > maxZ) maxZ = cz;\n }\n\n this.centersVersion++;\n // Exact bounds are only authoritative when centres are kept current;\n // otherwise the padded rest bounds stay in force.\n if (this._mesh.needsCpuCenters) {\n this._uncutBounds.min.set(minX, minY, minZ);\n this._uncutBounds.max.set(maxX, maxY, maxZ);\n this._padForCut();\n }\n }\n\n /** Force a re-sort on the next render. */\n requestSort(): void {\n this._mesh.requestSort();\n }\n\n /** True while an asynchronous sort is outstanding, i.e. the drawn order is stale or absent. */\n get sortPending(): boolean {\n return this._mesh.sortPending;\n }\n\n /** Show or hide the splat without disturbing its bindings. */\n setRenderingEnabled(enabled: boolean): void {\n this.object3D.visible = enabled;\n }\n\n get renderingEnabled(): boolean {\n return this.object3D.visible;\n }\n\n get destroyed(): boolean {\n return this._destroyed;\n }\n\n /** Remove from the scene graph and release every GPU resource. */\n destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n Splat._liveInstances.delete(this);\n this.object3D.removeFromParent();\n this._mesh.dispose();\n this.colorTexture.dispose();\n this.transformATexture.dispose();\n this.transformBTexture.dispose();\n this.boneIndicesTexture?.dispose();\n this.boneWeightsTexture?.dispose();\n this.groupIdsTexture?.dispose();\n this.variantMaskTexture?.dispose();\n this.revealDistanceTexture?.dispose();\n this.groupOffsetsTexture?.dispose();\n this.groupPivotsTexture?.dispose();\n this.groupRotsTexture?.dispose();\n this.transformPalette.dispose();\n }\n\n /** @internal */\n static _liveInstances = new Set<Splat>();\n}\n\nconst _size = new Vector3();\nconst _sphere = new Sphere();\nconst _band = new Float32Array(4);\nconst _sketch = new Float32Array(4);\nconst _tint = new Float32Array(4);\n", "/**\n * The CPU side of a splat \"cut\" (`Splat.setCutGroups`): packing the per-piece\n * data into the three `numGroups x 1` RGBA32F textures the work-buffer shader\n * reads, and a reference of the shader's per-splat transform for tests.\n */\n\nexport interface PackedCutGroups {\n /** xyz = model-space offset, w = the piece's uniform scale (default 1). */\n offsets: Float32Array;\n /** xyz = pivot (default the origin), w unused. */\n pivots: Float32Array;\n /** xyz = unit rotation axis (default +Y), w = angle in radians (default 0). */\n rotations: Float32Array;\n}\n\n/**\n * Pack per-piece data for the shader. `offsets` and `pivots` are\n * `numGroups x 3`, `rotations` `numGroups x 4` (axis xyz, angle), `scales`\n * `numGroups`. The scale defaults to 1, never 0, since the shader multiplies\n * by it; the axis defaults to +Y so a stray angle stays well defined.\n */\nexport function packCutGroups(\n offsets: ArrayLike<number>,\n numGroups: number,\n pivots?: ArrayLike<number>,\n rotations?: ArrayLike<number>,\n scales?: ArrayLike<number>,\n): PackedCutGroups {\n const o = new Float32Array(numGroups * 4);\n const p = new Float32Array(numGroups * 4);\n const r = new Float32Array(numGroups * 4);\n for (let g = 0; g < numGroups; g++) {\n const i = g * 4;\n o[i] = offsets[g * 3];\n o[i + 1] = offsets[g * 3 + 1];\n o[i + 2] = offsets[g * 3 + 2];\n o[i + 3] = scales ? scales[g] : 1;\n if (pivots) {\n p[i] = pivots[g * 3];\n p[i + 1] = pivots[g * 3 + 1];\n p[i + 2] = pivots[g * 3 + 2];\n }\n r[i] = rotations ? rotations[g * 4] : 0;\n r[i + 1] = rotations ? rotations[g * 4 + 1] : 1;\n r[i + 2] = rotations ? rotations[g * 4 + 2] : 0;\n r[i + 3] = rotations ? rotations[g * 4 + 3] : 0;\n }\n return { offsets: o, pivots: p, rotations: r };\n}\n\n/**\n * Where the shader's `applyGroupCut` moves a model-space point of piece `g`\n * at cut `amount`: rotate about the pivot (Rodrigues) by `angle * amount`,\n * scale about the pivot by `mix(1, scale, amount)`, then slide by\n * `offset * amount`. Mirrors the GLSL and WGSL; used by tests.\n */\nexport function applyGroupCutCpu(\n point: readonly [number, number, number],\n packed: PackedCutGroups,\n g: number,\n amount: number,\n): [number, number, number] {\n const i = g * 4;\n const px = packed.pivots[i], py = packed.pivots[i + 1], pz = packed.pivots[i + 2];\n const ax = packed.rotations[i], ay = packed.rotations[i + 1], az = packed.rotations[i + 2];\n const angle = packed.rotations[i + 3] * amount;\n const vx = point[0] - px, vy = point[1] - py, vz = point[2] - pz;\n const c = Math.cos(angle), s = Math.sin(angle);\n const dot = ax * vx + ay * vy + az * vz;\n const cx = ay * vz - az * vy, cy = az * vx - ax * vz, cz = ax * vy - ay * vx;\n const k = 1 + (packed.offsets[i + 3] - 1) * amount;\n const rx = (vx * c + cx * s + ax * dot * (1 - c)) * k;\n const ry = (vy * c + cy * s + ay * dot * (1 - c)) * k;\n const rz = (vz * c + cz * s + az * dot * (1 - c)) * k;\n return [\n px + rx + packed.offsets[i] * amount,\n py + ry + packed.offsets[i + 1] * amount,\n pz + rz + packed.offsets[i + 2] * amount,\n ];\n}\n", "/**\n * How a character reveal looks: a bright band that walks the skeleton from\n * feet to head, with sparse sketch dots just ahead of it. Distances are\n * fractions of that feet-to-head path. Every field is optional; unset fields\n * keep their current value. See {@link Character.setReveal}.\n *\n * @group Splats\n */\nexport interface RevealLook {\n /** Width of the bright band behind the front. */\n bandWidth?: number;\n /** Share of the band held at full brightness before it fades, 0-1. */\n bandHold?: number;\n /** Longest a splat may stretch inside the band, in multiples of its shortest axis. */\n bandMaxStretch?: number;\n /** How far ahead of the front the sketch dots start. */\n sketchLead?: number;\n /** Share of splats drawn as sketch dots, 0-1. */\n sketchDensity?: number;\n /** Size of a sketch dot relative to its splat. */\n sketchScale?: number;\n /** Colour the band leans toward, 0-1 per channel. */\n tint?: { r: number; g: number; b: number };\n /** Luminance below which the band is lifted toward {@link tint}. */\n tintFloor?: number;\n}\n\n/** The engine's default reveal look. */\nexport const DEFAULT_REVEAL_LOOK: Readonly<Required<RevealLook>> = Object.freeze({\n bandWidth: 0.07,\n bandHold: 0.6,\n bandMaxStretch: 2.5,\n sketchLead: 0.07,\n sketchDensity: 0.15,\n sketchScale: 0.35,\n tint: Object.freeze({ r: 0.55, g: 0.9, b: 1.0 }),\n tintFloor: 0.5,\n});\n\n/**\n * The default look for an ENVIRONMENT reveal, where the sweep is radial\n * distance from the capture point rather than a path up a body. Distances are\n * fractions of the room's radius either way, so these are the same numbers\n * read against a different subject - and the subject is what moves them.\n *\n * A body's feet-to-head coordinate is a line: a narrow band shows a thin ring\n * of it, and a sweep up it is legible. A room's radius is a SHELL, and a\n * Flow2D capture keeps most of its splats in the one shell that is its walls,\n * so the character's 0.07 band crosses nearly the whole room in a single\n * instant - a flashbulb, not an assembly. The band is wider here and holds\n * less of its width at full brightness, which turns that slab into a front\n * with a falloff behind it; a wide band at the character's 0.6 hold would be\n * a wall of white across the entire frame instead.\n *\n * The dots thin out for the same reason. A character is a few hundred\n * thousand splats in the middle of the frame, where 15% of them reads as a\n * sketch; a scene is millions of them filling it edge to edge, where 15%\n * reads as fog. They also lead by more than the band is wide, so the shape of\n * the room is legible just before it lands.\n *\n * The colour is deliberately the character's, unchanged: the two reveals are\n * one effect seen on two subjects, and a scene that assembled in a different\n * hue would say they were not.\n */\nexport const DEFAULT_ENV_REVEAL_LOOK: Readonly<Required<RevealLook>> = Object.freeze({\n bandWidth: 0.16,\n bandHold: 0.35,\n bandMaxStretch: 2.5,\n sketchLead: 0.18,\n sketchDensity: 0.08,\n sketchScale: 0.3,\n tint: Object.freeze({ r: 0.55, g: 0.9, b: 1.0 }),\n tintFloor: 0.5,\n});\n\n/**\n * Write the set fields of `look` into the shader's three uniforms:\n * `band` = (width, hold, max stretch), `sketch` = (lead, density, dot scale),\n * `tint` = (r, g, b, luminance floor).\n */\nexport function packRevealLook(\n look: RevealLook,\n band: Float32Array,\n sketch: Float32Array,\n tint: Float32Array,\n): void {\n if (look.bandWidth !== undefined) band[0] = look.bandWidth;\n if (look.bandHold !== undefined) band[1] = look.bandHold;\n if (look.bandMaxStretch !== undefined) band[2] = look.bandMaxStretch;\n if (look.sketchLead !== undefined) sketch[0] = look.sketchLead;\n if (look.sketchDensity !== undefined) sketch[1] = look.sketchDensity;\n if (look.sketchScale !== undefined) sketch[2] = look.sketchScale;\n if (look.tint) { tint[0] = look.tint.r; tint[1] = look.tint.g; tint[2] = look.tint.b; }\n if (look.tintFloor !== undefined) tint[3] = look.tintFloor;\n}\n", "import { BufferAttribute, BufferGeometry, Mesh, MeshBasicMaterial } from 'three';\nimport type { Camera } from 'three';\n\nimport type { SplatEngine } from '../engine';\n\nimport type { SplatBackend, SplatRenderImpl } from './backend';\nimport type { Splat } from './splat';\nimport { WebGLSplatBackend } from './webgl/backend';\n\n// What a splat mesh holds until a renderer has drawn it once: one degenerate\n// triangle that writes nothing. Any three.js renderer accepts it, and drawing\n// it is what gets `onBeforeRender` called so the real implementation can attach.\nconst PLACEHOLDER_GEOMETRY = new BufferGeometry();\nPLACEHOLDER_GEOMETRY.setAttribute('position', new BufferAttribute(new Float32Array(9), 3));\nconst PLACEHOLDER_MATERIAL = new MeshBasicMaterial({ colorWrite: false, depthWrite: false, depthTest: false });\n\nconst webglBackend = new WebGLSplatBackend();\nlet webgpuBackend: SplatBackend | null = null;\nconst warned = new Set<string>();\n\nfunction warnOnce(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n console.error(`[splat-engine-three] ${message}`);\n}\n\n/**\n * Make the WebGPU backend available to every {@link SplatMesh}. Called by the\n * `@viggle/splat-engine-three/webgpu` entry point when it is imported; the\n * default entry point leaves it out so WebGL applications never load\n * `three/webgpu`.\n *\n * @internal\n */\nexport function registerWebGPUBackend(backend: SplatBackend): void {\n webgpuBackend = backend;\n}\n\n/** The backend that can draw with `renderer`, or `null` (after saying why) when none can. */\nfunction backendFor(renderer: unknown): SplatBackend | null {\n const r = renderer as { isWebGPURenderer?: boolean; backend?: { isWebGPUBackend?: boolean } };\n if (r.isWebGPURenderer !== true) return webglBackend;\n if (r.backend?.isWebGPUBackend !== true) {\n warnOnce(\n 'WebGPURenderer is running on its WebGL2 fallback, which has no compute shaders, so splats cannot be drawn. ' +\n 'Use THREE.WebGLRenderer on devices without WebGPU.',\n );\n return null;\n }\n if (!webgpuBackend) {\n warnOnce(\n \"Splats are being drawn by a WebGPURenderer, but the WebGPU backend is not loaded. \" +\n \"Import from '@viggle/splat-engine-three/webgpu' instead of '@viggle/splat-engine-three'.\",\n );\n return null;\n }\n return webgpuBackend;\n}\n\n/**\n * The object that draws one {@link Splat}: an ordinary `THREE.Mesh` in your\n * scene graph, so `visible`, `renderOrder`, `layers` and parent transforms all\n * work as they do for any mesh.\n *\n * It works with both `THREE.WebGLRenderer` and `WebGPURenderer`. Which one is\n * not known until something renders it, so the renderer-specific geometry and\n * material are attached the first time it is drawn; the mesh shows from the\n * following frame.\n *\n * @group Splats\n */\nexport class SplatMesh extends Mesh {\n /** Type flag, in the three.js manner. */\n readonly isSplatMesh = true;\n\n /** The splat this mesh draws: its data, tint, grade and render options. */\n readonly splat: Splat;\n\n private readonly _engine: SplatEngine;\n private readonly _asyncSort: boolean;\n private _impl: SplatRenderImpl | null = null;\n\n /**\n * @param asyncSort - See {@link SplatBackend.createImpl}.\n * @internal Construct a {@link Splat} instead; it creates its own mesh.\n */\n constructor(splat: Splat, engine: SplatEngine, asyncSort: boolean) {\n super(PLACEHOLDER_GEOMETRY, PLACEHOLDER_MATERIAL);\n this.name = 'splat';\n this.splat = splat;\n this._engine = engine;\n this._asyncSort = asyncSort;\n // The placeholder has no extent to cull against, and must be drawn for the\n // real implementation to attach.\n this.frustumCulled = false;\n if (engine.backend) this._attach(engine.backend);\n }\n\n private _attach(backend: SplatBackend): void {\n const impl = backend.createImpl(this, this.splat, this._engine, this._asyncSort);\n this._impl = impl;\n this.geometry = impl.geometry;\n this.material = impl.material;\n this.frustumCulled = true;\n }\n\n /** See {@link SplatRenderImpl.needsCpuCenters}. False until a renderer has drawn this mesh. */\n get needsCpuCenters(): boolean {\n return this._impl?.needsCpuCenters ?? false;\n }\n\n /** True while the drawn order is stale or absent, including before the first draw. */\n get sortPending(): boolean {\n return this._impl ? this._impl.sortPending : true;\n }\n\n requestSort(): void {\n this._impl?.requestSort();\n }\n\n syncDefines(): void {\n this._impl?.syncDefines();\n }\n\n syncBounds(): void {\n this._impl?.syncBounds();\n }\n\n syncBoneData(): void {\n this._impl?.syncBoneData();\n }\n\n syncVariantGroups(): void {\n this._impl?.syncVariantGroups();\n }\n\n syncRelight(): void {\n this._impl?.syncRelight();\n }\n\n override onBeforeRender(renderer: unknown, _scene: unknown, camera: Camera): void {\n if (!this._impl) {\n const backend = backendFor(renderer);\n // This draw still uses the placeholder; the real mesh shows next frame.\n if (backend) this._attach(backend);\n return;\n }\n this._impl.beforeRender(renderer, camera);\n }\n\n /**\n * A second mesh drawing the same splat data, at the same transform. The\n * decoded data is shared; the GPU copy of it is not.\n *\n * Only for static splats. A mesh that belongs to a character is driven by\n * that character's rig and cannot stand alone - clone the `SplatCharacter`.\n */\n override clone(): this {\n const source = this.splat;\n if (source.splatWeights) {\n throw new Error('SplatMesh.clone: this mesh is part of a character; clone the SplatCharacter instead');\n }\n const copy = source.cloneStatic(this._engine, this._asyncSort).object3D;\n copy.name = this.name;\n copy.position.copy(this.position);\n copy.quaternion.copy(this.quaternion);\n copy.scale.copy(this.scale);\n copy.visible = this.visible;\n copy.renderOrder = this.renderOrder;\n copy.layers.mask = this.layers.mask;\n copy.userData = { ...this.userData };\n return copy as this;\n }\n\n /**\n * Splats are not pickable. The inherited implementation would test the ray\n * against this mesh's own geometry, which is a single proxy quad at the\n * local origin - every instance is positioned in the shader - and report\n * hits that have nothing to do with where the splats are drawn.\n */\n override raycast(): void {}\n\n /**\n * Release every GPU resource behind this mesh - the splat's data textures as\n * well as the renderer-specific buffers - and remove it from its parent.\n */\n override dispose(): void {\n // The splat owns the teardown order; it calls back here once it has begun.\n if (!this.splat.destroyed) {\n this.splat.destroy();\n return;\n }\n this._impl?.dispose();\n this._impl = null;\n this.geometry = PLACEHOLDER_GEOMETRY;\n this.material = PLACEHOLDER_MATERIAL;\n super.dispose();\n }\n}\n", "import {\n BufferAttribute,\n ColorManagement,\n CustomBlending,\n DoubleSide,\n DynamicDrawUsage,\n GLSL3,\n InstancedBufferAttribute,\n InstancedBufferGeometry,\n LinearTransfer,\n OneFactor,\n OneMinusSrcAlphaFactor,\n Quaternion,\n RawShaderMaterial,\n Sphere,\n Vector2,\n Vector3,\n Vector4,\n} from 'three';\nimport type { Camera, Mesh, WebGLRenderer } from 'three';\n\nimport type { SplatEngine } from '../../engine';\nimport type { SplatRenderImpl } from '../backend';\nimport { AsyncDepthSorter, DepthSorter, projectBoundsOnDirection } from '../depth-sort';\nimport { SplatQuality, beginFrameTimings, effectiveMinPixelSize } from '../quality';\nimport type { Splat } from '../splat';\n\nimport { colorModifierGLSL } from '../color-modifier';\n\nimport { SPLAT_FRAGMENT_GLSL, splatVertexGLSL } from './shaders';\n\nconst _position = new Vector3();\nconst _quaternion = new Quaternion();\nconst _scale = new Vector3();\nconst _viewport = new Vector4();\n\nconst RELIGHT_UNIFORMS = [\n 'uRelightTex', 'uRelightShadowTex', 'uRelightVP', 'uRelightParams', 'uRelightStrength',\n 'uRelightTint', 'uRelightAmbient', 'uRelightShadowStrength', 'uRelightFlipY', 'uRelightDebug',\n];\n\n/**\n * How one {@link Splat} is drawn under `WebGLRenderer`: one instanced quad per\n * gaussian, drawn back-to-front with premultiplied alpha.\n *\n * The instance attribute holds splat indices in draw order, so sorting only\n * ever rewrites that one buffer; all splat data stays put in textures.\n *\n * @internal\n */\nexport class WebGLSplatImpl implements SplatRenderImpl {\n readonly geometry: InstancedBufferGeometry;\n readonly material: RawShaderMaterial;\n /** The depth sort runs on the CPU, so it needs CPU-side centres. */\n readonly needsCpuCenters = true;\n\n private readonly _host: Mesh;\n private readonly _splat: Splat;\n private readonly _engine: SplatEngine;\n private readonly _order: InstancedBufferAttribute;\n private readonly _syncSorter: DepthSorter | null;\n private readonly _asyncSorter: AsyncDepthSorter | null;\n\n private _sortedVersion = -1;\n private _sortRequested = true;\n private _lastDx = NaN;\n private _lastDy = NaN;\n private _lastDz = NaN;\n /** The importance ordering the worker already holds, if any. */\n private _sentSubset: Uint32Array | null = null;\n /** Names of the colour hook's uniforms currently on the material. */\n private _hookUniforms: string[] = [];\n\n /**\n * @param asyncSort - Sort in a worker and keep drawing the previous order\n * meanwhile. Right for large static splats; wrong for skinned ones, whose\n * order would lag the pose.\n */\n constructor(host: Mesh, splat: Splat, engine: SplatEngine, asyncSort: boolean) {\n const geometry = new InstancedBufferGeometry();\n geometry.setAttribute(\n 'position',\n new BufferAttribute(new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]), 3),\n );\n geometry.setIndex([0, 1, 2, 0, 2, 3]);\n\n const order = new InstancedBufferAttribute(new Uint32Array(splat.numSplats), 1);\n order.setUsage(DynamicDrawUsage);\n geometry.setAttribute('splatOrder', order);\n geometry.boundingSphere = new Sphere();\n\n const lighting = engine.lightingUniforms;\n const material = new RawShaderMaterial({\n name: 'SplatMaterial',\n glslVersion: GLSL3,\n vertexShader: splatVertexGLSL(),\n fragmentShader: SPLAT_FRAGMENT_GLSL,\n uniforms: {\n tTransformA: { value: splat.transformATexture },\n tTransformB: { value: splat.transformBTexture },\n tColor: { value: splat.colorTexture },\n uTexWidth: { value: splat.packed.width },\n uViewport: { value: new Vector2(1, 1) },\n uMinPixelSize: { value: 0 },\n uAlphaCutoffScale: { value: 255 },\n uModelRotation: { value: new Vector4(0, 0, 0, 1) },\n uModelScale: { value: new Vector3(1, 1, 1) },\n uTint: { value: splat.tint },\n uGrade: { value: splat.grade },\n uEffects: { value: splat.effects },\n uOutputLinear: { value: 0 },\n transformPalette: { value: splat.transformPalette.texture },\n boneIndices: { value: splat.boneIndicesTexture ?? null },\n boneWeights: { value: splat.boneWeightsTexture ?? null },\n splatGroupIds: { value: null },\n splatVariantMask: { value: null },\n splatRevealDistanceTex: { value: null },\n uRevealBand: { value: splat.revealBand },\n uRevealSketch: { value: splat.revealSketch },\n uRevealTint: { value: splat.revealTint },\n splatGroupOffsets: { value: null },\n splatGroupPivots: { value: null },\n splatGroupRots: { value: null },\n // Shared objects: one write in the engine reaches every splat material.\n uSunColor: lighting.uSunColor,\n uSunIntensity: lighting.uSunIntensity,\n uAmbientColor: lighting.uAmbientColor,\n uPointLightCount: lighting.uPointLightCount,\n uPointLightTex: lighting.uPointLightTex,\n },\n // The ellipse axes can mirror the quad, so its winding is not fixed.\n side: DoubleSide,\n transparent: true,\n depthTest: true,\n depthWrite: false,\n premultipliedAlpha: true,\n blending: CustomBlending,\n blendSrc: OneFactor,\n blendDst: OneMinusSrcAlphaFactor,\n blendSrcAlpha: OneFactor,\n blendDstAlpha: OneMinusSrcAlphaFactor,\n });\n\n this.geometry = geometry;\n this.material = material;\n this._host = host;\n this._splat = splat;\n this._engine = engine;\n this._order = order;\n\n if (asyncSort) {\n this._syncSorter = null;\n // Nothing is drawn until the first order arrives.\n geometry.instanceCount = 0;\n this._asyncSorter = new AsyncDepthSorter(splat.centers, splat.numSplats, (sorted, count) => {\n (order.array as Uint32Array).set(sorted);\n order.needsUpdate = true;\n geometry.instanceCount = count;\n });\n } else {\n this._asyncSorter = null;\n this._syncSorter = new DepthSorter();\n geometry.instanceCount = splat.numSplats;\n }\n\n this.syncDefines();\n this.syncBounds();\n }\n\n /** True while a worker sort is in flight (always false for synchronous sorting). */\n get sortPending(): boolean {\n return this._asyncSorter ? this._asyncSorter.busy || this.geometry.instanceCount === 0 : false;\n }\n\n /** Force a re-sort on the next render even if the view direction is unchanged. */\n requestSort(): void {\n this._sortRequested = true;\n }\n\n /** Rebuild the shader variant after a feature toggle on the splat. */\n syncDefines(): void {\n const splat = this._splat;\n const defines: Record<string, string> = {};\n if (splat.splatWeights) defines.USE_BONE_BLENDING = '';\n if (splat.variantMaskEnabled) defines.USE_VARIANT_MASK = '';\n if (splat.nonRigidCovariance) defines.USE_NONRIGID_COV = '';\n if (splat.antiAlias) defines.USE_ANTIALIAS = '';\n if (splat.revealEnabled) defines.USE_REVEAL = '';\n if (splat.cutEnabled && splat.variantMaskEnabled) defines.USE_GROUP_OFFSET = '';\n if (splat.relightBinding) defines.USE_RELIGHT = '';\n\n // A game colour hook: its uniforms join the material's by reference, and\n // its source is spliced into the vertex stage. Uniforms of a hook that\n // was replaced are dropped so they cannot shadow the next one's.\n const u = this.material.uniforms;\n for (const name of this._hookUniforms) delete u[name];\n this._hookUniforms = [];\n const modifier = splat.colorModifier;\n let hook = '';\n if (modifier?.glsl) {\n defines.USE_COLOR_MODIFIER = '';\n hook = colorModifierGLSL(modifier);\n for (const [name, uniform] of Object.entries(modifier.uniforms ?? {})) {\n u[name] = uniform;\n this._hookUniforms.push(name);\n }\n }\n this.material.vertexShader = splatVertexGLSL(hook);\n this.syncRelight();\n\n this.material.defines = defines;\n this.material.needsUpdate = true;\n }\n\n /** Point the relight uniforms at the splat's current binding. */\n syncRelight(): void {\n const binding = this._splat.relightBinding;\n const u = this.material.uniforms;\n if (!binding) {\n for (const name of RELIGHT_UNIFORMS) delete u[name];\n return;\n }\n u.uRelightTex = { get value() { return binding.texture; } };\n u.uRelightShadowTex = { get value() { return binding.shadowTexture ?? binding.texture; } };\n u.uRelightVP = { value: binding.viewProjection };\n u.uRelightParams = { value: binding.params };\n u.uRelightStrength = { get value() { return binding.strength; } };\n u.uRelightTint = { value: binding.tint };\n u.uRelightAmbient = { get value() { return binding.ambient; } };\n u.uRelightShadowStrength = { get value() { return binding.shadowStrength; } };\n u.uRelightFlipY = { get value() { return binding.flipY; } };\n u.uRelightDebug = { get value() { return binding.debug; } };\n }\n\n /** The bone textures are the splat's own; flagging them is all there is to do. */\n syncBoneData(): void {\n const splat = this._splat;\n if (splat.boneIndicesTexture) splat.boneIndicesTexture.needsUpdate = true;\n if (splat.boneWeightsTexture) splat.boneWeightsTexture.needsUpdate = true;\n }\n\n /** Group ids live in the splat's own texture, which it flags itself. */\n syncVariantGroups(): void {}\n\n /** Refresh the culling sphere from the splat's current local bounds. */\n syncBounds(): void {\n const box = this._splat.localBounds;\n box.getBoundingSphere(this.geometry.boundingSphere!);\n }\n\n beforeRender(renderer: unknown, camera: Camera): void {\n const tEntered = SplatQuality.passTimings ? performance.now() : 0;\n const gl = renderer as WebGLRenderer;\n const splat = this._splat;\n const u = this.material.uniforms;\n\n gl.getCurrentViewport(_viewport);\n u.uViewport.value.set(_viewport.z, _viewport.w);\n\n // Splat colours are display-referred. Decode them only when the target\n // wants linear values (a post-processing chain); drawing straight to an\n // sRGB canvas passes them through untouched.\n const target = gl.getRenderTarget();\n const outputColorSpace = target ? target.texture.colorSpace : gl.outputColorSpace;\n u.uOutputLinear.value = ColorManagement.getTransfer(outputColorSpace) === LinearTransfer ? 1 : 0;\n\n this._host.matrixWorld.decompose(_position, _quaternion, _scale);\n u.uModelRotation.value.set(_quaternion.x, _quaternion.y, _quaternion.z, _quaternion.w);\n u.uModelScale.value.copy(_scale);\n\n u.uMinPixelSize.value = effectiveMinPixelSize(splat.minPixelSize);\n // Clamped off a true zero rather than branched on: at 1/65535 the quad is\n // already the full 2-sigma one for any alpha that can draw, so \"off\" is the\n // bottom of the same curve and the shader keeps one code path.\n u.uAlphaCutoffScale.value = 1 / Math.max(1 / 65535, SplatQuality.quadAlphaCutoff);\n u.transformPalette.value = splat.transformPalette.texture;\n u.splatGroupIds.value = splat.groupIdsTexture ?? null;\n u.splatVariantMask.value = splat.variantMaskTexture ?? null;\n u.splatRevealDistanceTex.value = splat.revealDistanceTexture ?? null;\n u.splatGroupOffsets.value = splat.groupOffsetsTexture ?? null;\n u.splatGroupPivots.value = splat.groupPivotsTexture ?? null;\n u.splatGroupRots.value = splat.groupRotsTexture ?? null;\n if (this.material.depthTest !== SplatQuality.depthOcclusion) {\n this.material.depthTest = SplatQuality.depthOcclusion;\n }\n this._engine.syncLighting();\n\n if (!SplatQuality.passTimings) {\n this._sortFor(camera);\n return;\n }\n\n beginFrameTimings(this);\n const t = SplatQuality.timings;\n const tPrepared = performance.now();\n t.prepare += tPrepared - tEntered;\n this._sortFor(camera);\n t.sort += performance.now() - tPrepared;\n t.splatsDrawn += this.geometry.instanceCount;\n t.splatsTotal += splat.numSplats;\n }\n\n private _sortFor(camera: Camera): void {\n const splat = this._splat;\n const count = splat.activeSplatCount;\n if (count === 0) return;\n // Centres may be waiting on a pose pushed before this implementation existed.\n splat.ensureCenters();\n\n // Camera forward (-Z of its world matrix) carried into splat-local space.\n // Depth along it is dot(M^T f, p) + const, so M^T f orders local centres\n // exactly as view depth orders world ones - for any affine M.\n const ce = camera.matrixWorld.elements;\n const fx = -ce[8], fy = -ce[9], fz = -ce[10];\n const me = this._host.matrixWorld.elements;\n const dx = me[0] * fx + me[1] * fy + me[2] * fz;\n const dy = me[4] * fx + me[5] * fy + me[6] * fz;\n const dz = me[8] * fx + me[9] * fy + me[10] * fz;\n\n const dirChanged = dx !== this._lastDx || dy !== this._lastDy || dz !== this._lastDz;\n const dataChanged = splat.centersVersion !== this._sortedVersion;\n if (!dirChanged && !dataChanged && !this._sortRequested) return;\n\n this._lastDx = dx;\n this._lastDy = dy;\n this._lastDz = dz;\n this._sortedVersion = splat.centersVersion;\n this._sortRequested = false;\n\n const box = splat.localBounds;\n const { depthMin, depthMax } = projectBoundsOnDirection(\n [box.min.x, box.min.y, box.min.z],\n [box.max.x, box.max.y, box.max.z],\n dx, dy, dz,\n );\n\n // A count LOD sorts the first `count` entries of the importance order and\n // draws exactly those, so the instance count follows the sort.\n const subset = splat.countLodActive ? splat.importanceOrder : null;\n if (this._asyncSorter) {\n if (subset && subset !== this._sentSubset) {\n this._sentSubset = subset;\n this._asyncSorter.setSubset(subset);\n }\n this._asyncSorter.request({ dx, dy, dz, depthMin, depthMax, count });\n } else {\n this._syncSorter!.sort(\n splat.centers, count, dx, dy, dz, depthMin, depthMax,\n this._order.array as Uint32Array, subset,\n );\n this._order.needsUpdate = true;\n this.geometry.instanceCount = count;\n }\n }\n\n dispose(): void {\n this._asyncSorter?.dispose();\n this.geometry.dispose();\n this.material.dispose();\n }\n}\n", "/**\n * Back-to-front depth ordering for splats: a counting sort over quantised\n * distance along the view direction.\n *\n * The same routine runs in two places. Skinned characters are small and move\n * every frame, so they sort synchronously on the main thread and never show a\n * stale order. Environments are large and only need a new order when the camera\n * moves, so they sort in a worker ({@link AsyncDepthSorter}) and keep drawing\n * the previous order until the new one lands.\n */\n\ninterface SortScratch {\n keys: Uint32Array | null;\n counts: Uint32Array | null;\n}\n\n/**\n * Write into `order` the indices `[0, count)` sorted far-to-near along\n * `(dx, dy, dz)`, which must be the view direction expressed in the same space\n * as `centers`.\n *\n * `depthMin` / `depthMax` bound `dot(center, dir)` over the splats; a\n * conservative bound (from an AABB) is fine and avoids a pass over the data.\n *\n * Written to be self-contained - no closures over module state - because its\n * source text is also what the worker runs.\n */\nfunction countingSortByDepth(\n centers: Float32Array,\n count: number,\n dx: number,\n dy: number,\n dz: number,\n depthMin: number,\n depthMax: number,\n order: Uint32Array,\n scratch: SortScratch,\n subset?: Uint32Array | null,\n): void {\n if (count === 0) return;\n\n // Bucket resolution tracks the splat count: ~4 splats per bucket, clamped to\n // [2^10, 2^20]. More buckets than that costs cache misses for no visible gain.\n const bits = Math.max(10, Math.min(20, Math.round(Math.log2(count / 4))));\n const bucketCount = 1 << bits;\n\n if (!scratch.keys || scratch.keys.length < count) scratch.keys = new Uint32Array(count);\n if (!scratch.counts || scratch.counts.length !== bucketCount) scratch.counts = new Uint32Array(bucketCount);\n const keys = scratch.keys;\n const counts = scratch.counts;\n counts.fill(0);\n\n const range = depthMax - depthMin;\n const scale = range > 1e-12 ? (bucketCount - 1) / range : 0;\n const last = bucketCount - 1;\n\n // Key 0 is the farthest splat, so ascending key order is back-to-front.\n //\n // `subset` names which splats take part, for a count LOD that processes\n // only the first K of an importance ordering. Walking that list costs a\n // scattered read per splat, where testing every splat's rank in index order\n // would be sequential - but this loop's per-splat work is three multiplies,\n // so the unpredictable branch that test needs costs more than the cache\n // miss it saves. Measured on 32 characters at K = 30%: walking the list\n // 1.8 ms, testing ranks 4.3 ms, against 2.8 ms for the whole set. The CPU\n // skinning pass, whose per-splat work is an order of magnitude larger,\n // comes out the other way round and does test ranks - see Splat._skinCenters.\n if (subset) {\n for (let i = 0; i < count; i++) {\n const c = subset[i] * 3;\n const depth = centers[c] * dx + centers[c + 1] * dy + centers[c + 2] * dz;\n let key = ((depthMax - depth) * scale) | 0;\n if (key < 0) key = 0;\n else if (key > last) key = last;\n keys[i] = key;\n counts[key]++;\n }\n } else {\n for (let i = 0, c = 0; i < count; i++, c += 3) {\n const depth = centers[c] * dx + centers[c + 1] * dy + centers[c + 2] * dz;\n let key = ((depthMax - depth) * scale) | 0;\n if (key < 0) key = 0;\n else if (key > last) key = last;\n keys[i] = key;\n counts[key]++;\n }\n }\n\n for (let i = 1; i < bucketCount; i++) counts[i] += counts[i - 1];\n\n // The value written is the SPLAT index, which is what the draw reads; `i` is\n // only its place in the subset.\n if (subset) {\n for (let i = count - 1; i >= 0; i--) order[--counts[keys[i]]] = subset[i];\n } else {\n for (let i = count - 1; i >= 0; i--) order[--counts[keys[i]]] = i;\n }\n}\n\n/**\n * Range of `dot(p, dir)` over an axis-aligned box - the projection of the box\n * onto the view direction.\n */\nexport function projectBoundsOnDirection(\n min: ArrayLike<number>,\n max: ArrayLike<number>,\n dx: number,\n dy: number,\n dz: number,\n): { depthMin: number; depthMax: number } {\n const depthMin =\n (dx >= 0 ? min[0] : max[0]) * dx + (dy >= 0 ? min[1] : max[1]) * dy + (dz >= 0 ? min[2] : max[2]) * dz;\n const depthMax =\n (dx >= 0 ? max[0] : min[0]) * dx + (dy >= 0 ? max[1] : min[1]) * dy + (dz >= 0 ? max[2] : min[2]) * dz;\n return { depthMin, depthMax };\n}\n\n/** Synchronous sorter with its own scratch buffers. One per splat. */\nexport class DepthSorter {\n private readonly _scratch: SortScratch = { keys: null, counts: null };\n\n /**\n * @param count - How many splats take part. With `subset`, the length of\n * the prefix of it to use; without, the splats are `[0, count)`.\n * @param subset - Splat indices to sort, for a count LOD. See\n * {@link Splat.setCountLod}.\n */\n sort(\n centers: Float32Array,\n count: number,\n dx: number,\n dy: number,\n dz: number,\n depthMin: number,\n depthMax: number,\n order: Uint32Array,\n subset?: Uint32Array | null,\n ): void {\n countingSortByDepth(centers, count, dx, dy, dz, depthMin, depthMax, order, this._scratch, subset);\n }\n}\n\nexport interface SortRequest {\n dx: number;\n dy: number;\n dz: number;\n depthMin: number;\n depthMax: number;\n /**\n * How many splats to order, for a count LOD. Defaults to all of them; with\n * a subset set, the length of the prefix of it to use.\n */\n count?: number;\n}\n\n/**\n * Worker-backed sorter for static splats.\n *\n * At most one sort is in flight. A request made while the worker is busy\n * replaces any earlier pending one, so a fast-moving camera never queues work\n * it no longer wants. A single order buffer is transferred to the worker and\n * back, never copied.\n *\n * The worker is built from a Blob of this module's own sort routine, so there\n * is no second file for a bundler to lose.\n */\nexport class AsyncDepthSorter {\n private _worker: Worker | null;\n private _pending: SortRequest | null = null;\n /** The order buffer, when it is on this side of the worker boundary. */\n private _order: Uint32Array | null;\n\n /**\n * @param centers - Flat `[x,y,z] * count`. Copied into the worker once.\n * @param onSorted - Called with each finished order and how many of its\n * entries are current. The array is only valid for the duration of the call\n * - it goes back to the worker on the next request - so copy out of it\n * before returning.\n */\n constructor(centers: Float32Array, count: number, onSorted: (order: Uint32Array, count: number) => void) {\n this._order = new Uint32Array(count);\n\n // Wrapped as an expression so the text works whether a bundler leaves the\n // routine as a function declaration or rewrites it as an arrow.\n const source = `\n const sortByDepth = (${countingSortByDepth.toString()});\n let centers = null;\n let subset = null;\n const scratch = { keys: null, counts: null };\n self.onmessage = (e) => {\n const m = e.data;\n if (m.centers) { centers = m.centers; return; }\n if (m.subset) { subset = m.subset; return; }\n const order = m.order;\n const count = m.count === undefined ? order.length : m.count;\n sortByDepth(centers, count, m.dx, m.dy, m.dz, m.depthMin, m.depthMax, order, scratch, subset);\n self.postMessage({ order, count }, [order.buffer]);\n };\n `;\n const url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));\n this._worker = new Worker(url, { name: 'splat-depth-sort' });\n URL.revokeObjectURL(url);\n\n this._worker.onmessage = (e: MessageEvent<{ order: Uint32Array; count: number }>) => {\n this._order = e.data.order;\n onSorted(this._order, e.data.count);\n if (this._pending) {\n const next = this._pending;\n this._pending = null;\n this.request(next);\n }\n };\n\n const copy = centers.slice(0, count * 3);\n this._worker.postMessage({ centers: copy }, [copy.buffer]);\n }\n\n /**\n * Give the worker the importance ordering a count LOD selects from. Sent\n * once and kept there, like the centres; after this a request carries only\n * how many of its entries to use.\n */\n setSubset(subset: Uint32Array): void {\n if (!this._worker) return;\n const copy = subset.slice();\n this._worker.postMessage({ subset: copy }, [copy.buffer]);\n }\n\n /** True while a sort is running in the worker. */\n get busy(): boolean {\n return this._order === null;\n }\n\n request(req: SortRequest): void {\n if (!this._worker) return;\n const order = this._order;\n if (!order) {\n this._pending = req;\n return;\n }\n this._order = null;\n this._worker.postMessage({ ...req, order }, [order.buffer]);\n }\n\n dispose(): void {\n this._worker?.terminate();\n this._worker = null;\n this._pending = null;\n }\n}\n", "import type { IUniform } from 'three';\n\n/**\n * Values the colour hook can read, as TSL nodes. See {@link SplatColorModifier.tsl}.\n *\n * @group Splats\n */\nexport interface SplatColorModifierInputs {\n /** World-space centre of the splat, skinned. `vec3`. */\n center: unknown;\n /** Model-space centre, skinned (and cut), before the object's own transform. `vec3`. */\n modelCenter: unknown;\n /** Model-space centre in the rest pose, as stored in the file. `vec3`. */\n restCenter: unknown;\n /** Index of the splat in its cloud. `uint`. */\n splatIndex: unknown;\n /** The colour the engine computed: rgb, and alpha before the gaussian falloff. `vec4`. */\n color: unknown;\n /** One uniform node per {@link SplatColorModifier.uniforms} entry, by the same name. */\n uniforms: Record<string, unknown>;\n}\n\n/**\n * A per-splat colour hook that runs after the engine's own colour work -\n * lighting, tint, relight, grade, reveal, opacity - and can change any of it.\n *\n * The three.js counterpart of the PlayCanvas build's work-buffer modifier\n * (`setWorkBufferModifier` with `WORK_BUFFER_MODIFIER_GLSL/WGSL`): instead of\n * splicing into the engine's shader source, a game supplies one function per\n * backend and the engine calls it.\n *\n * Give `glsl` for `THREE.WebGLRenderer`, and `wgsl` or `tsl` for\n * `WebGPURenderer`. A splat drawn by a renderer whose source is missing\n * renders as if no hook were set.\n *\n * ```ts\n * const fade = { uFade: { value: 1 } };\n * character.setColorModifier({\n * uniforms: fade,\n * glsl: `void modifySplatColor(vec3 center, vec3 modelCenter, vec3 restCenter, uint splatIndex, inout vec4 color) {\n * color.a *= uFade;\n * }`,\n * wgsl: `fn modifySplatColor(center: vec3f, modelCenter: vec3f, restCenter: vec3f, splatIndex: u32,\n * color: vec4f, uFade: f32) -> vec4f {\n * return vec4f(color.rgb, color.a * uFade);\n * }`,\n * });\n * fade.uFade.value = 0.5; // takes effect next frame\n * ```\n *\n * @group Splats\n */\nexport interface SplatColorModifier {\n /**\n * Uniforms the hook reads, by name. Change `.value` at any time; the\n * objects are bound by reference. Values may be numbers or three.js\n * `Vector2/3/4`, `Color`, `Matrix3/4`.\n */\n uniforms?: Record<string, IUniform>;\n /**\n * GLSL ES 3.00 source defining\n * `void modifySplatColor(vec3 center, vec3 modelCenter, vec3 restCenter, uint splatIndex, inout vec4 color)`.\n * May define helpers. Each uniform is declared for you with the GLSL type\n * matching its value; do not redeclare it.\n */\n glsl?: string;\n /**\n * WGSL source defining\n * `fn modifySplatColor(center: vec3f, modelCenter: vec3f, restCenter: vec3f, splatIndex: u32, color: vec4f, ...) -> vec4f`,\n * with one further parameter per uniform, named after it. Used when `tsl`\n * is not given.\n */\n wgsl?: string;\n /** A TSL builder returning the new colour (`vec4`). Takes precedence over `wgsl`. */\n tsl?: (inputs: SplatColorModifierInputs) => unknown;\n}\n\n/** GLSL type of a uniform value, for the declarations generated around a hook. @internal */\nexport function glslTypeOf(value: unknown): string {\n if (typeof value === 'number') return 'float';\n if (typeof value === 'boolean') return 'bool';\n const v = value as Record<string, unknown> | null;\n if (v && v.isVector2) return 'vec2';\n if (v && (v.isVector3 || v.isColor)) return 'vec3';\n if (v && v.isVector4) return 'vec4';\n if (v && v.isMatrix3) return 'mat3';\n if (v && v.isMatrix4) return 'mat4';\n if (v && v.isTexture) return 'sampler2D';\n throw new Error(`SplatColorModifier: unsupported uniform value ${String(value)}`);\n}\n\n/** The GLSL a hook contributes to the vertex stage: declarations, then its source. @internal */\nexport function colorModifierGLSL(modifier: SplatColorModifier): string {\n const decls = Object.entries(modifier.uniforms ?? {})\n .map(([name, u]) => `uniform ${glslTypeOf(u.value)} ${name};`)\n .join('\\n');\n return `${decls}\\n${modifier.glsl ?? ''}\\n`;\n}\n", "import { ClampToEdgeWrapping, DataTexture, FloatType, NearestFilter, RGBAFormat } from 'three';\n\nimport type { Mat4 } from '../math';\n\n// Column-major 4x4 -> three row-major texels (the bottom row is implicit 0,0,0,1).\nconst idx = [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14];\n/** Transforms per texture row. The shader's palette lookup hard-codes this. */\nexport const PALETTE_ROW_SLOTS = 512;\nconst width = PALETTE_ROW_SLOTS * 3;\n\nfunction createPaletteTexture(data: Float32Array, w: number, h: number): DataTexture {\n const texture = new DataTexture(data, w, h, RGBAFormat, FloatType);\n texture.name = 'transformPalette';\n texture.minFilter = NearestFilter;\n texture.magFilter = NearestFilter;\n texture.wrapS = ClampToEdgeWrapping;\n texture.wrapT = ClampToEdgeWrapping;\n texture.generateMipmaps = false;\n texture.needsUpdate = true;\n return texture;\n}\n\n/**\n * The per-splat table of skinning matrices, stored as a float texture: three\n * RGBA texels per transform, {@link PALETTE_ROW_SLOTS} transforms per row.\n *\n * Slot 0 is reserved for identity and is what unmapped influences point at.\n */\nclass TransformPalette {\n private _texture!: DataTexture;\n private _data!: Float32Array;\n private _dirty = false;\n private _nextIdx = 1;\n private readonly _identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];\n\n constructor(initialSize = 4096) {\n this._realloc(Math.ceil(initialSize / PALETTE_ROW_SLOTS));\n this._data.set(this._identity, 0);\n this.upload();\n }\n\n /**\n * The backing texture. Replaced when the palette grows, so read it each\n * frame rather than holding on to it.\n */\n get texture(): DataTexture {\n return this._texture;\n }\n\n /**\n * The backing array: twelve floats per slot, three row-major vec4 rows.\n * Replaced when the palette grows, like {@link TransformPalette.texture}.\n */\n get data(): Float32Array {\n return this._data;\n }\n\n /** Incremented every time {@link TransformPalette.upload} reports a change. */\n version = 0;\n\n /** Slots the palette can hold before it has to grow. */\n get capacity(): number {\n return this._data.length / 12;\n }\n\n private _realloc(height: number): void {\n const data = new Float32Array(width * height * 4);\n if (this._texture) {\n data.set(this._data);\n this._texture.dispose();\n }\n this._data = data;\n this._texture = createPaletteTexture(data, width, height);\n this._dirty = true;\n }\n\n getTransform(index: number, transform: Mat4): void {\n const dst = transform.data;\n const data = this._data;\n for (let i = 0; i < 12; ++i) {\n dst[idx[i]] = data[index * 12 + i];\n }\n }\n\n setTransform(index: number, transform: Mat4): void {\n const src = transform.data;\n const data = this._data;\n const base = index * 12;\n let changed = false;\n for (let i = 0; i < 12; ++i) {\n const v = src[idx[i]];\n if (data[base + i] !== v) {\n data[base + i] = v;\n changed = true;\n }\n }\n if (changed) this._dirty = true;\n }\n\n /** Flag the texture for re-upload if anything changed. Returns whether it did. */\n upload(): boolean {\n if (!this._dirty) return false;\n this._dirty = false;\n this._texture.needsUpdate = true;\n this.version++;\n return true;\n }\n\n /** Reserve `num` consecutive slots and return the index of the first. */\n alloc(num = 1): number {\n const result = this._nextIdx;\n while (this._nextIdx + num > this._data.length / 12) {\n this._realloc(this._texture.image.height * 2);\n }\n this._nextIdx += num;\n return result;\n }\n\n free(num = 1): void {\n this._nextIdx -= num;\n }\n\n dispose(): void {\n this._texture.dispose();\n }\n}\n\nexport { TransformPalette };\n", "import { PALETTE_ROW_SLOTS } from '../transform-palette';\n\n// GLSL ES 3.00 sources for the WebGLRenderer splat material.\n//\n// One vertex stage does what the PlayCanvas build spreads over two passes\n// (skin into a work buffer, then project): fetch the splat, blend its bone\n// transforms, lift it to world space, project its covariance to a screen-space\n// quad. The maths is kept line-for-line comparable with that build so the two\n// can be diffed, and so the A/B suite has a reason to agree.\n//\n// Defines:\n// USE_BONE_BLENDING - splat carries skinning weights (characters).\n// USE_NONRIGID_COV - let the palette's per-axis scale stretch the gaussian\n// (bone-length scaling).\n// USE_VARIANT_MASK - per-splat group id + per-group visibility.\n// USE_ANTIALIAS - compensate opacity for the screen-space dilation.\n// USE_REVEAL - the feet-to-head reveal (Splat.setReveal).\n// USE_GROUP_OFFSET - per-group \"cut\" displacement (Splat.setCutGroups);\n// implies USE_VARIANT_MASK for the group ids.\n// USE_RELIGHT - a SplatRelight writes lighting for this splat.\n// USE_COLOR_MODIFIER - a game colour hook (Splat.setColorModifier).\n//\n// Uniforms that carry a quality setting (see splat/quality.ts) are named in\n// their declarations; they are plain uniforms, so changing one costs a write\n// and never a recompile.\n\nconst lightingChunk = /* glsl */ `\nuniform vec3 uSunColor;\nuniform float uSunIntensity;\nuniform vec3 uAmbientColor;\nuniform int uPointLightCount;\nuniform highp sampler2D uPointLightTex;\n\n// Baked splat colour is multiplied by this. With no lights it is exactly 1.\nvec3 computeLitFactor(vec3 worldCenter) {\n vec3 lit = uAmbientColor + uSunColor * uSunIntensity;\n for (int i = 0; i < uPointLightCount; i++) {\n vec4 posRange = texelFetch(uPointLightTex, ivec2(i, 0), 0);\n vec4 colorInt = texelFetch(uPointLightTex, ivec2(i, 1), 0);\n vec3 toLight = posRange.xyz - worldCenter;\n float dist = length(toLight);\n float range = posRange.w;\n if (dist >= range) continue;\n float t = dist / range;\n float atten = 1.0 - t * t;\n atten = atten * atten;\n lit += colorInt.rgb * colorInt.w * atten;\n }\n return lit;\n}\n`;\n\nconst skinningChunk = /* glsl */ `\nuniform highp sampler2D transformPalette;\n\n#ifdef USE_BONE_BLENDING\nuniform highp sampler2D boneIndices;\nuniform highp sampler2D boneWeights;\n#endif\n\n#ifdef USE_VARIANT_MASK\nuniform highp sampler2D splatGroupIds;\nuniform highp sampler2D splatVariantMask;\n\nbool isSplatHiddenByVariantMask(ivec2 splatUV) {\n float gidF = texelFetch(splatGroupIds, splatUV, 0).r;\n int gid = int(gidF + 0.5);\n float bit = texelFetch(splatVariantMask, ivec2(gid, 0), 0).r;\n return bit < 0.5;\n}\n#endif\n\nbool isReasonablePaletteTransform(mat4 t) {\n mat3 lin = mat3(t);\n vec3 s = vec3(length(lin[0]), length(lin[1]), length(lin[2]));\n // Reject only when EVERY column is near-zero (a truly empty palette slot).\n // Linear-blend skinning of two very different bone rotations produces a\n // candy-wrapper matrix with one short column; that is still a valid\n // mid-rotation transform. Requiring all columns to pass would collapse\n // joint-spanning splats (notably the neck) back to the bind pose.\n return any(greaterThan(s, vec3(1e-4)));\n}\n\nmat4 readTransformFromPalette(uint paletteIndex) {\n if (paletteIndex == 0u) {\n return mat4(1.0);\n }\n\n int u = int(paletteIndex % ${PALETTE_ROW_SLOTS}u) * 3;\n int v = int(paletteIndex / ${PALETTE_ROW_SLOTS}u);\n\n mat4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n t[3] = vec4(0.0, 0.0, 0.0, 1.0);\n\n mat4 result = transpose(t);\n if (!isReasonablePaletteTransform(result)) {\n return mat4(1.0);\n }\n return result;\n}\n\nmat4 getSplatPaletteTransform(ivec2 splatUV) {\n #ifdef USE_BONE_BLENDING\n vec4 boneIdxVec = texelFetch(boneIndices, splatUV, 0);\n vec4 boneWeightVec = texelFetch(boneWeights, splatUV, 0);\n float totalWeight = dot(boneWeightVec, vec4(1.0));\n if (totalWeight > 0.001) {\n mat4 blended = mat4(0.0);\n for (int i = 0; i < 4; i++) {\n float w = boneWeightVec[i];\n if (w > 0.001) {\n uint idx = uint(boneIdxVec[i] + 0.5);\n blended += readTransformFromPalette(idx) * w;\n }\n }\n mat4 result = blended / totalWeight;\n if (isReasonablePaletteTransform(result)) {\n return result;\n }\n }\n #endif\n\n return mat4(1.0);\n}\n\nvec4 mat3ToQuatXYZW(mat3 R) {\n vec4 q;\n float trace = R[0][0] + R[1][1] + R[2][2];\n if (trace > 0.0) {\n float s = sqrt(trace + 1.0) * 2.0;\n q.w = 0.25 * s;\n q.x = (R[1][2] - R[2][1]) / s;\n q.y = (R[2][0] - R[0][2]) / s;\n q.z = (R[0][1] - R[1][0]) / s;\n } else if (R[0][0] > R[1][1] && R[0][0] > R[2][2]) {\n float s = sqrt(1.0 + R[0][0] - R[1][1] - R[2][2]) * 2.0;\n q.w = (R[1][2] - R[2][1]) / s;\n q.x = 0.25 * s;\n q.y = (R[1][0] + R[0][1]) / s;\n q.z = (R[2][0] + R[0][2]) / s;\n } else if (R[1][1] > R[2][2]) {\n float s = sqrt(1.0 + R[1][1] - R[0][0] - R[2][2]) * 2.0;\n q.w = (R[2][0] - R[0][2]) / s;\n q.x = (R[1][0] + R[0][1]) / s;\n q.y = 0.25 * s;\n q.z = (R[2][1] + R[1][2]) / s;\n } else {\n float s = sqrt(1.0 + R[2][2] - R[0][0] - R[1][1]) * 2.0;\n q.w = (R[0][1] - R[1][0]) / s;\n q.x = (R[2][0] + R[0][2]) / s;\n q.y = (R[2][1] + R[1][2]) / s;\n q.z = 0.25 * s;\n }\n return q;\n}\n`;\n\n\n// Relight: the lighting a SplatRelight rendered for this splat's proxy, looked\n// up at the splat centre's projection. The PlayCanvas build's relight chunk,\n// line for line. Runs after the tint and before the grade.\nconst relightChunk = /* glsl */ `\n#ifdef USE_RELIGHT\nuniform mediump sampler2D uRelightTex; // rgb = lighting, a = proxy coverage\nuniform mediump sampler2D uRelightShadowTex; // r = shadow visibility, g = coverage\nuniform mat4 uRelightVP; // the view-projection the texture was rendered with\nuniform vec4 uRelightParams; // xy = 1/size, z = 1/referenceLuminance, w = 1 when valid\nuniform float uRelightStrength;\nuniform vec3 uRelightTint;\nuniform float uRelightAmbient;\nuniform float uRelightShadowStrength;\nuniform float uRelightFlipY;\nuniform float uRelightDebug;\n\nvoid applyRelight(vec3 worldCenter, inout vec4 color) {\n float strength = clamp(uRelightStrength, 0.0, 1.0);\n float shadowStrength = clamp(uRelightShadowStrength, 0.0, 1.0);\n bool debug = uRelightDebug > 0.5;\n bool debugVis = uRelightDebug > 1.5;\n if (!debug && strength <= 0.0 && shadowStrength <= 0.0) return;\n\n if (uRelightParams.w <= 0.0) {\n if (debug) { color.rgb = vec3(1.0, 0.0, 1.0); color.a = 1.0; }\n return;\n }\n\n vec4 clipPos = uRelightVP * vec4(worldCenter, 1.0);\n if (clipPos.w <= 0.0) {\n if (debug) { color.rgb = vec3(1.0, 1.0, 0.0); color.a = 1.0; }\n return;\n }\n\n vec2 uv = clipPos.xy / clipPos.w * 0.5 + 0.5;\n if (uRelightFlipY > 0.5) uv.y = 1.0 - uv.y;\n\n if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {\n if (debug) { color.rgb = vec3(1.0, 0.0, 0.0); color.a = 1.0; }\n return;\n }\n\n if (debugVis) {\n vec2 dv = textureLod(uRelightShadowTex, uv, 0.0).rg;\n color.rgb = dv.g > 0.0 ? vec3(clamp(dv.r, 0.0, 1.0)) : vec3(1.0, 0.0, 1.0);\n color.a = 1.0;\n return;\n }\n\n vec4 s = textureLod(uRelightTex, uv, 0.0);\n\n if (debug) {\n if (s.a > 0.0) {\n color.rgb = s.rgb;\n } else {\n vec2 mirrored = vec2(uv.x, 1.0 - uv.y);\n color.rgb = textureLod(uRelightTex, mirrored, 0.0).a > 0.0\n ? vec3(1.0, 0.5, 0.0)\n : vec3(0.0, 0.0, 1.0);\n }\n color.a = 1.0;\n return;\n }\n\n if (strength > 0.0) {\n float mask = clamp(s.a, 0.0, 1.0);\n vec3 lighting = max(s.rgb * uRelightParams.z, vec3(uRelightAmbient)) * uRelightTint;\n color.rgb = mix(color.rgb, color.rgb * lighting, strength * mask);\n }\n\n if (shadowStrength > 0.0) {\n vec2 v = textureLod(uRelightShadowTex, uv, 0.0).rg;\n color.rgb *= mix(1.0, clamp(v.r, 0.0, 1.0), shadowStrength * clamp(v.g, 0.0, 1.0));\n }\n}\n#endif\n`;\n\n// Reveal and cut, after the PlayCanvas build's work-buffer modifier.\nconst effectsChunk = /* glsl */ `\n#ifdef USE_REVEAL\n#ifdef USE_BONE_BLENDING\nuniform highp sampler2D splatRevealDistanceTex;\n#endif\nuniform vec4 uRevealBand; // x width, y hold, z max stretch\nuniform vec4 uRevealSketch; // x lead, y density, z dot scale\nuniform vec4 uRevealTint; // rgb tint, a luminance floor\n\n// Per-splat distance along the skeleton, feet (0) to head (1).\nfloat splatRevealDistance(ivec2 splatUV) {\n #ifdef USE_BONE_BLENDING\n return texelFetch(splatRevealDistanceTex, splatUV, 0).r;\n #else\n return 1.0;\n #endif\n}\n\n// Signed distance behind the moving front.\nfloat splatRevealX(ivec2 splatUV, float reveal) {\n float front = mix(-uRevealBand.x, 1.0 + uRevealBand.x, reveal);\n return front - splatRevealDistance(splatUV);\n}\n\n// Bright edge colour derived from the splat's own colour.\nvec3 splatRevealHot(vec3 base) {\n const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);\n vec3 tint = uRevealTint.rgb;\n float floorLuma = max(uRevealTint.a, 1e-4);\n float luma = dot(base, LUMA);\n vec3 hot = clamp(mix(vec3(luma), base, 2.2) * 1.9, 0.0, 1.0);\n hot = mix(hot, tint * max(luma, 0.35) * 2.0, 0.3);\n hot = clamp(hot, 0.0, 1.0);\n float lift = clamp((floorLuma - dot(hot, LUMA)) / floorLuma, 0.0, 1.0);\n return mix(hot, tint, lift);\n}\n\n// Stable sparse dots just ahead of the front.\nfloat splatRevealSketch(vec3 rest, float x) {\n float lead = uRevealSketch.x;\n if (x >= 0.0 || x < -lead) return 0.0;\n float h = fract(sin(dot(rest, vec3(12.9898, 78.233, 37.719))) * 43758.5453);\n if (h > uRevealSketch.y) return 0.0;\n return smoothstep(-lead, -lead * 0.7, x);\n}\n\nvoid splatRevealApply(ivec2 splatUV, vec3 rest, float reveal, bool inverse, inout vec4 color) {\n float x = splatRevealX(splatUV, reveal);\n float bandWidth = uRevealBand.x;\n vec3 base = clamp(color.rgb, 0.0, 1.0);\n vec3 hot = splatRevealHot(base);\n if (inverse) {\n if (x < 0.0) return;\n float band = 1.0 - smoothstep(0.0, bandWidth, x);\n color.rgb = mix(base, hot, band);\n color.a = band * 0.95;\n return;\n }\n if (x >= 0.0) {\n float band = 1.0 - smoothstep(bandWidth * uRevealBand.y, bandWidth, x);\n color.rgb = mix(base, hot, band);\n color.a = max(color.a, band * 0.95);\n } else {\n float sketch = splatRevealSketch(rest, x);\n color.rgb = hot;\n color.a = sketch;\n }\n}\n\n// Ahead of the front draws small (only the sketch subset has alpha there);\n// inside the band, elongated splats are squashed so the edge stays a stroke.\nvec3 splatRevealScale(ivec2 splatUV, float reveal, bool inverse, vec3 scale) {\n float x = splatRevealX(splatUV, reveal);\n if (inverse) {\n if (x >= 0.0 && x < uRevealBand.x) {\n float m = min(scale.x, min(scale.y, scale.z));\n scale = min(scale, vec3(m * uRevealBand.z));\n }\n } else if (reveal < 1.0) {\n if (x < 0.0) {\n scale *= uRevealSketch.z;\n } else if (x < uRevealBand.x) {\n float m = min(scale.x, min(scale.y, scale.z));\n scale = min(scale, vec3(m * uRevealBand.z));\n }\n }\n return scale;\n}\n#endif\n\n#ifdef USE_GROUP_OFFSET\nuniform highp sampler2D splatGroupOffsets; // xyz = model-space offset, w = piece scale\nuniform highp sampler2D splatGroupPivots; // xyz = pivot (model space)\nuniform highp sampler2D splatGroupRots; // xyz = unit axis, w = angle (rad) at cut 1\n\nint getGroupId(ivec2 splatUV) { return int(texelFetch(splatGroupIds, splatUV, 0).r + 0.5); }\n\n// Rotate p about pivot by angle around a unit axis (Rodrigues).\nvec3 cutRotate(vec3 p, vec3 pivot, vec3 axis, float angle) {\n vec3 v = p - pivot;\n float c = cos(angle), s = sin(angle);\n return pivot + v * c + cross(axis, v) * s + axis * dot(axis, v) * (1.0 - c);\n}\n\n// Each piece turns and scales about its pivot, then slides by its offset, all\n// eased by the cut amount. Mirrors applyGroupCutCpu (cut-groups.ts).\nvec3 applyGroupCut(ivec2 splatUV, vec3 center, float amount) {\n int gid = getGroupId(splatUV);\n vec4 offS = texelFetch(splatGroupOffsets, ivec2(gid, 0), 0);\n vec3 pivot = texelFetch(splatGroupPivots, ivec2(gid, 0), 0).xyz;\n vec4 rot = texelFetch(splatGroupRots, ivec2(gid, 0), 0);\n vec3 rel = cutRotate(center, pivot, rot.xyz, rot.w * amount) - pivot;\n rel *= mix(1.0, offS.w, amount);\n return pivot + rel + offS.xyz * amount;\n}\n\n// The same turn as a quaternion (xyzw), applied to each gaussian's own\n// orientation so a piece turns rigidly rather than just moving its centres.\nvec4 getGroupRotQuat(ivec2 splatUV, float amount) {\n vec4 rot = texelFetch(splatGroupRots, ivec2(getGroupId(splatUV), 0), 0);\n float a = rot.w * amount * 0.5;\n return vec4(rot.xyz * sin(a), cos(a));\n}\n#endif\n`;\n\n/**\n * The vertex stage, with a game colour hook (`USE_COLOR_MODIFIER`) spliced in\n * where given. See SplatColorModifier.\n */\nexport function splatVertexGLSL(colorModifier = ''): string {\n return SPLAT_VERTEX_HEAD + colorModifier + SPLAT_VERTEX_MAIN;\n}\n\nconst SPLAT_VERTEX_HEAD = /* glsl */ `\nprecision highp float;\nprecision highp int;\nprecision highp usampler2D;\n\n// Quad corner in [-1, 1].\nin vec3 position;\n// Index of the splat this instance draws; instances arrive back-to-front.\nin uint splatOrder;\n\nuniform mat4 modelMatrix;\nuniform mat4 viewMatrix;\nuniform mat4 projectionMatrix;\n\nuniform highp usampler2D tTransformA;\nuniform highp sampler2D tTransformB;\nuniform highp sampler2D tColor;\nuniform int uTexWidth;\n\n// Drawing-buffer size in pixels.\nuniform vec2 uViewport;\nuniform float uMinPixelSize;\n// 1 / the alpha a splat's quad is allowed to end at. Carried as the reciprocal\n// so the historic 1/255 cutoff arrives as exactly 255.0 and the two\n// expressions below reduce, bit for bit, to what they were before the cutoff\n// was a setting at all. See SplatQuality.quadAlphaCutoff.\nuniform float uAlphaCutoffScale;\n// World rotation (xyzw) and scale of the splat object.\nuniform vec4 uModelRotation;\nuniform vec3 uModelScale;\n// rgb tint colour, a tint amount.\nuniform vec4 uTint;\n// x contrast, y saturation.\nuniform vec2 uGrade;\n// x opacity, y reveal amount, z reveal inverse, w cut amount.\nuniform vec4 uEffects;\n// 1 when the render target expects linear colour, 0 when it is display-referred.\nuniform float uOutputLinear;\n\nout mediump vec2 gaussianUV;\nout mediump vec4 gaussianColor;\n\n${lightingChunk}\n${skinningChunk}\n${relightChunk}\n${effectsChunk}\n`;\n\nconst SPLAT_VERTEX_MAIN = /* glsl */ `\n\nconst vec4 discardVec = vec4(0.0, 0.0, 2.0, 1.0);\n\nmat3 quatToMat3(vec4 R) {\n vec4 R2 = R + R;\n float X = R2.x * R.w;\n vec4 Y = R2.y * R;\n vec4 Z = R2.z * R;\n float W = R2.w * R.w;\n return mat3(\n 1.0 - Z.z - W, Y.z + X, Y.w - Z.x,\n Y.z - X, 1.0 - Y.y - W, Z.w + Y.x,\n Y.w + Z.x, Z.w - Y.x, 1.0 - Y.y - Z.z\n );\n}\n\nvec4 quatMul(vec4 a, vec4 b) {\n return vec4(\n a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,\n a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,\n a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,\n a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z\n );\n}\n\nvoid computeCovariance(vec4 rotation, vec3 scale, out vec3 covA, out vec3 covB) {\n mat3 rot = quatToMat3(rotation);\n mat3 M = transpose(mat3(\n scale.x * rot[0],\n scale.y * rot[1],\n scale.z * rot[2]\n ));\n covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));\n covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));\n}\n\nvec3 sRGBToLinear(vec3 c) {\n return mix(\n pow(c * 0.9478672986 + vec3(0.0521327014), vec3(2.4)),\n c * 0.0773993808,\n vec3(lessThanEqual(c, vec3(0.04045)))\n );\n}\n\nvoid main(void) {\n ivec2 splatUV = ivec2(int(splatOrder % uint(uTexWidth)), int(splatOrder / uint(uTexWidth)));\n uvec4 tA = texelFetch(tTransformA, splatUV, 0);\n vec4 tB = texelFetch(tTransformB, splatUV, 0);\n\n vec3 modelCenter = uintBitsToFloat(tA.xyz);\n vec3 packedRot = vec3(unpackHalf2x16(tA.w), tB.w);\n // xyzw, with w recovered: quaternions are stored on the w >= 0 hemisphere.\n vec4 srcRotation = vec4(packedRot, sqrt(max(0.0, 1.0 - dot(packedRot, packedRot))));\n vec3 srcScale = tB.xyz;\n\n // ---- Skin, then lift to world space --------------------------------\n mat4 palette = getSplatPaletteTransform(splatUV);\n vec3 modelDeformed = (palette * vec4(modelCenter, 1.0)).xyz;\n #ifdef USE_GROUP_OFFSET\n modelDeformed = applyGroupCut(splatUV, modelDeformed, uEffects.w);\n srcRotation = quatMul(getGroupRotQuat(splatUV, uEffects.w), srcRotation);\n #endif\n vec3 worldCenter = (modelMatrix * vec4(modelDeformed, 1.0)).xyz;\n\n vec4 worldRotation = quatMul(uModelRotation, srcRotation);\n if (worldRotation.w < 0.0) worldRotation = -worldRotation;\n vec3 worldScale = uModelScale * srcScale;\n\n #ifdef USE_BONE_BLENDING\n {\n // The full world-space skinning rotation comes from modelMatrix * palette;\n // the palette's own scale is deliberately dropped (rigid skinning).\n mat3 lin = mat3(modelMatrix * palette);\n vec3 s = vec3(length(lin[0]), length(lin[1]), length(lin[2]));\n if (s.x > 1e-5 && s.y > 1e-5 && s.z > 1e-5) {\n mat3 rot = mat3(lin[0] / s.x, lin[1] / s.y, lin[2] / s.z);\n vec4 composed = normalize(quatMul(mat3ToQuatXYZW(rot), srcRotation));\n if (composed.w < 0.0) composed = -composed;\n worldRotation = composed;\n }\n #ifdef USE_NONRIGID_COV\n // Bone-length scaling: the palette keeps its per-axis scale and the\n // gaussian stretches with the bone.\n worldScale *= s;\n #endif\n }\n #endif\n\n #ifdef USE_VARIANT_MASK\n if (isSplatHiddenByVariantMask(splatUV)) {\n gl_Position = discardVec;\n return;\n }\n #endif\n\n #ifdef USE_REVEAL\n worldScale = splatRevealScale(splatUV, uEffects.y, uEffects.z > 0.5, worldScale);\n #endif\n\n // ---- Project the centre --------------------------------------------\n bool ortho = projectionMatrix[3][3] == 1.0;\n vec4 centerView = viewMatrix * vec4(worldCenter, 1.0);\n if (!ortho && centerView.z > 0.0) {\n gl_Position = discardVec;\n return;\n }\n vec4 centerProj = projectionMatrix * centerView;\n centerProj.z = clamp(centerProj.z, -abs(centerProj.w), abs(centerProj.w));\n\n // ---- Project the covariance to a screen-space ellipse ----------------\n vec3 covA, covB;\n computeCovariance(worldRotation.wxyz, worldScale, covA, covB);\n mat3 Vrk = mat3(\n covA.x, covA.y, covA.z,\n covA.y, covB.x, covB.y,\n covA.z, covB.y, covB.z\n );\n\n float focal = uViewport.x * projectionMatrix[0][0];\n vec3 v = centerView.xyz;\n vec3 vp = ortho ? vec3(0.0, 0.0, 1.0) : v;\n float J1 = focal / vp.z;\n vec2 J2 = -J1 / vp.z * vp.xy;\n mat3 J = mat3(\n J1, 0.0, J2.x,\n 0.0, J1, J2.y,\n 0.0, 0.0, 0.0\n );\n mat3 W = transpose(mat3(viewMatrix));\n mat3 T = W * J;\n mat3 cov = transpose(T) * Vrk * T;\n\n #ifdef USE_ANTIALIAS\n float detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[0][1];\n float detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[0][1];\n float aaFactor = sqrt(max(detOrig / detBlur, 0.0));\n #endif\n\n float diagonal1 = cov[0][0] + 0.3;\n float offDiagonal = cov[0][1];\n float diagonal2 = cov[1][1] + 0.3;\n float mid = 0.5 * (diagonal1 + diagonal2);\n float radius = length(vec2((diagonal1 - diagonal2) / 2.0, offDiagonal));\n float lambda1 = mid + radius;\n float lambda2 = max(mid - radius, 0.1);\n\n float vmin = min(1024.0, min(uViewport.x, uViewport.y));\n float l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin);\n float l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin);\n if (max(l1, l2) < uMinPixelSize) {\n gl_Position = discardVec;\n return;\n }\n\n // Cull splats whose ellipse lies wholly off-screen.\n vec2 c = centerProj.ww / uViewport;\n if (any(greaterThan(abs(centerProj.xy) - vec2(max(l1, l2)) * c, centerProj.ww))) {\n gl_Position = discardVec;\n return;\n }\n\n vec2 diagonalVector = normalize(vec2(offDiagonal, lambda1 - diagonal1));\n vec2 v1 = l1 * diagonalVector;\n vec2 v2 = l2 * vec2(diagonalVector.y, -diagonalVector.x);\n vec2 cornerUV = position.xy;\n vec2 offset = (cornerUV.x * v1 + cornerUV.y * v2) * c;\n\n // ---- Colour -----------------------------------------------------------\n vec4 clr = texelFetch(tColor, splatUV, 0);\n #ifdef USE_ANTIALIAS\n clr.a *= aaFactor;\n #endif\n\n clr.rgb *= computeLitFactor(worldCenter);\n // Tint amount >= 0 mixes toward the tint colour; < 0 multiplies by it,\n // with strength -a (Splat.setTintMultiply).\n if (uTint.a >= 0.0) {\n clr.rgb = mix(clr.rgb, uTint.rgb, clamp(uTint.a, 0.0, 1.0));\n } else {\n clr.rgb = mix(clr.rgb, clr.rgb * uTint.rgb, min(-uTint.a, 1.0));\n }\n #ifdef USE_RELIGHT\n applyRelight(worldCenter, clr);\n #endif\n // Identity grade is a true no-op: skipping it keeps HDR splat colours unclamped.\n if (uGrade.x != 1.0 || uGrade.y != 1.0) {\n clr.rgb = (clr.rgb - 0.5) * uGrade.x + 0.5;\n float luma = dot(clr.rgb, vec3(0.2126, 0.7152, 0.0722));\n clr.rgb = mix(vec3(luma), clr.rgb, uGrade.y);\n clr.rgb = clamp(clr.rgb, 0.0, 1.0);\n }\n #ifdef USE_REVEAL\n if (uEffects.y < 1.0 || uEffects.z > 0.5) {\n splatRevealApply(splatUV, modelCenter, uEffects.y, uEffects.z > 0.5, clr);\n }\n #endif\n clr.a *= uEffects.x;\n #ifdef USE_COLOR_MODIFIER\n modifySplatColor(worldCenter, modelDeformed, modelCenter, splatOrder, clr);\n #endif\n\n // A splat whose peak alpha is already under the cutoff cannot put a\n // fragment on screen: its own quad would be empty.\n float alphaOverCutoff = clr.a * uAlphaCutoffScale;\n if (alphaOverCutoff <= 1.0) {\n gl_Position = discardVec;\n return;\n }\n\n // Shrink the quad to where the gaussian is still above the cutoff: fewer\n // fragments. At a cutoff of 1/255 the pixels are identical, since below\n // that frag() discards anyway; above it, this is the trade the setting\n // exists to make.\n float clip = min(1.0, sqrt(log(alphaOverCutoff)) * 0.5);\n offset *= clip;\n\n gl_Position = centerProj + vec4(offset, 0.0, 0.0);\n gaussianUV = cornerUV * clip;\n\n vec3 rgb = max(clr.rgb, 0.0);\n if (uOutputLinear > 0.5) rgb = sRGBToLinear(rgb);\n gaussianColor = vec4(rgb, clr.a);\n}\n`;\n\nexport const SPLAT_FRAGMENT_GLSL = /* glsl */ `\nprecision highp float;\n\nin mediump vec2 gaussianUV;\nin mediump vec4 gaussianColor;\n\nlayout(location = 0) out highp vec4 fragColor;\n\nconst float EXP4 = exp(-4.0);\nconst float INV_EXP4 = 1.0 / (1.0 - EXP4);\n\n// exp(-4x) rescaled to hit exactly 0 at the quad edge (x = 1).\nfloat normExp(float x) {\n return (exp(x * -4.0) - EXP4) * INV_EXP4;\n}\n\nvoid main(void) {\n mediump float A = dot(gaussianUV, gaussianUV);\n if (A > 1.0) {\n discard;\n }\n mediump float alpha = normExp(A) * gaussianColor.a;\n if (alpha < 1.0 / 255.0) {\n discard;\n }\n // Premultiplied.\n fragColor = vec4(gaussianColor.rgb * alpha, alpha);\n}\n`;\n", "import type { Mesh } from 'three';\n\nimport type { SplatEngine } from '../../engine';\nimport type { SplatBackend, SplatRenderImpl } from '../backend';\nimport type { Splat } from '../splat';\n\nimport { WebGLSplatImpl } from './splat-mesh';\n\n/**\n * Splat rendering for `THREE.WebGLRenderer`: GLSL ES 3.00, WebGL2.\n *\n * Splats are skinned and projected in the vertex stage. The depth sort runs on\n * the CPU - synchronously for skinned characters, in a worker for static\n * environments - which is what makes this backend's cost scale with the\n * number of animated characters.\n *\n * @group Engine\n */\nexport class WebGLSplatBackend implements SplatBackend {\n createImpl(host: Mesh, splat: Splat, engine: SplatEngine, asyncSort: boolean): SplatRenderImpl {\n return new WebGLSplatImpl(host, splat, engine, asyncSort);\n }\n}\n", "import type { SplatAttributes } from '../character/types';\n\nconst HEADER_END = 'end_header\\n';\n/** Headers are a few hundred bytes; anything past this is not a PLY we read. */\nconst MAX_HEADER_BYTES = 64 * 1024;\n\nconst PLY_TYPES: Record<string, { size: number; read: (v: DataView, o: number) => number }> = {\n char: { size: 1, read: (v, o) => v.getInt8(o) },\n int8: { size: 1, read: (v, o) => v.getInt8(o) },\n uchar: { size: 1, read: (v, o) => v.getUint8(o) },\n uint8: { size: 1, read: (v, o) => v.getUint8(o) },\n short: { size: 2, read: (v, o) => v.getInt16(o, true) },\n int16: { size: 2, read: (v, o) => v.getInt16(o, true) },\n ushort: { size: 2, read: (v, o) => v.getUint16(o, true) },\n uint16: { size: 2, read: (v, o) => v.getUint16(o, true) },\n int: { size: 4, read: (v, o) => v.getInt32(o, true) },\n int32: { size: 4, read: (v, o) => v.getInt32(o, true) },\n uint: { size: 4, read: (v, o) => v.getUint32(o, true) },\n uint32: { size: 4, read: (v, o) => v.getUint32(o, true) },\n float: { size: 4, read: (v, o) => v.getFloat32(o, true) },\n float32: { size: 4, read: (v, o) => v.getFloat32(o, true) },\n double: { size: 8, read: (v, o) => v.getFloat64(o, true) },\n float64: { size: 8, read: (v, o) => v.getFloat64(o, true) },\n};\n\n/** The fourteen properties a gaussian splat needs, in {@link SplatAttributes} order. */\nconst REQUIRED = [\n 'x', 'y', 'z',\n 'scale_0', 'scale_1', 'scale_2',\n 'rot_0', 'rot_1', 'rot_2', 'rot_3',\n 'f_dc_0', 'f_dc_1', 'f_dc_2',\n 'opacity',\n] as const;\n\ninterface PlyProperty {\n name: string;\n type: string;\n offset: number;\n}\n\n/**\n * Parse an uncompressed 3D Gaussian Splatting `.ply` (the layout written by\n * the reference trainer and most tools since): one binary little-endian\n * `vertex` element carrying position, log-scale, a `wxyz` rotation, the\n * spherical-harmonic DC colour and a logit opacity.\n *\n * Higher-order SH (`f_rest_*`) and normals are skipped: splats here are lit\n * flat, by their DC colour.\n *\n * @throws If the file is not a binary little-endian PLY, or lacks a required property.\n */\nexport function parseGaussianPly(file: ArrayBuffer): { numSplats: number; splats: SplatAttributes } {\n const headerBytes = new Uint8Array(file, 0, Math.min(file.byteLength, MAX_HEADER_BYTES));\n const headerText = new TextDecoder('ascii').decode(headerBytes);\n const end = headerText.indexOf(HEADER_END);\n if (!headerText.startsWith('ply') || end < 0) {\n throw new Error('[parseGaussianPly] not a PLY file: missing \"ply\" magic or \"end_header\"');\n }\n const dataStart = end + HEADER_END.length;\n\n let numSplats = 0;\n let stride = 0;\n let inVertex = false;\n let sawVertex = false;\n let skipBefore = 0;\n const props: PlyProperty[] = [];\n\n for (const raw of headerText.slice(0, end).split('\\n')) {\n const tokens = raw.trim().split(/\\s+/);\n switch (tokens[0]) {\n case 'format':\n if (tokens[1] !== 'binary_little_endian') {\n throw new Error(`[parseGaussianPly] unsupported PLY format '${tokens[1]}'; expected binary_little_endian`);\n }\n break;\n case 'element':\n inVertex = tokens[1] === 'vertex';\n if (inVertex) {\n sawVertex = true;\n numSplats = Number.parseInt(tokens[2], 10);\n } else if (!sawVertex) {\n // An element stored ahead of `vertex` would shift where vertex data\n // begins; nothing we read writes one, so reject rather than guess.\n skipBefore++;\n }\n break;\n case 'property': {\n if (!inVertex) break;\n if (tokens[1] === 'list') {\n throw new Error('[parseGaussianPly] list properties on the vertex element are not supported');\n }\n const type = PLY_TYPES[tokens[1]];\n if (!type) throw new Error(`[parseGaussianPly] unknown property type '${tokens[1]}'`);\n props.push({ name: tokens[2], type: tokens[1], offset: stride });\n stride += type.size;\n break;\n }\n default:\n break;\n }\n }\n\n if (!sawVertex) throw new Error('[parseGaussianPly] PLY has no vertex element');\n if (skipBefore > 0) throw new Error('[parseGaussianPly] PLY stores another element before vertex');\n if (!Number.isFinite(numSplats) || numSplats < 0) {\n throw new Error('[parseGaussianPly] PLY vertex count is not a non-negative integer');\n }\n if (dataStart + numSplats * stride > file.byteLength) {\n throw new Error(\n `[parseGaussianPly] truncated: header declares ${numSplats} vertices x ${stride} B, ` +\n `but only ${file.byteLength - dataStart} B follow it`,\n );\n }\n\n const byName = new Map(props.map((p) => [p.name, p]));\n const columns = REQUIRED.map((name) => {\n const p = byName.get(name);\n if (!p) throw new Error(`[parseGaussianPly] PLY is missing the required property '${name}'`);\n return p;\n });\n\n const out = REQUIRED.map(() => new Float32Array(numSplats));\n\n // The overwhelmingly common case is an all-float32 vertex whose stride is a\n // multiple of four: read whole columns through one aligned Float32Array view\n // instead of a DataView call per value.\n const allFloat = columns.every((p) => PLY_TYPES[p.type].size === 4 && p.type.startsWith('float'));\n if (allFloat && stride % 4 === 0 && columns.every((p) => p.offset % 4 === 0)) {\n const aligned =\n dataStart % 4 === 0\n ? new Float32Array(file, dataStart, (numSplats * stride) / 4)\n : new Float32Array(file.slice(dataStart, dataStart + numSplats * stride));\n const step = stride / 4;\n for (let c = 0; c < columns.length; c++) {\n const dst = out[c];\n for (let i = 0, o = columns[c].offset / 4; i < numSplats; i++, o += step) dst[i] = aligned[o];\n }\n } else {\n const view = new DataView(file, dataStart);\n for (let c = 0; c < columns.length; c++) {\n const dst = out[c];\n const { offset, type } = columns[c];\n const read = PLY_TYPES[type].read;\n for (let i = 0; i < numSplats; i++) dst[i] = read(view, i * stride + offset);\n }\n }\n\n const [x, y, z, scale_0, scale_1, scale_2, rot_0, rot_1, rot_2, rot_3, f_dc_0, f_dc_1, f_dc_2, opacity] = out;\n return {\n numSplats,\n splats: { x, y, z, scale_0, scale_1, scale_2, rot_0, rot_1, rot_2, rot_3, f_dc_0, f_dc_1, f_dc_2, opacity },\n };\n}\n", "/**\n * Inflate `data`, refusing to produce more than `maxBytes`. A size the file\n * declares is only an upper bound a hostile one sets itself, so callers cap\n * it by what a valid file could hold; `capFromHead`, when given, tightens the\n * cap once the first `headBytes` of output are in - a format whose header\n * says how long the rest is. Runs in the decode worker too (see\n * `decode-worker.ts`), so it uses nothing from outside itself.\n */\nexport async function inflateCapped(\n data: Uint8Array,\n format: 'gzip' | 'deflate-raw',\n maxBytes: number,\n headBytes = 0,\n capFromHead: ((head: Uint8Array) => number) | null = null,\n): Promise<Uint8Array> {\n const reader = new Blob([data as BlobPart]).stream()\n .pipeThrough(new DecompressionStream(format) as ReadableWritablePair<Uint8Array, Uint8Array>)\n .getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n let cap = maxBytes;\n let headPending = capFromHead !== null;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n chunks.push(value);\n if (headPending && total >= headBytes) {\n headPending = false;\n const head = new Uint8Array(headBytes);\n let at = 0;\n for (const chunk of chunks) {\n if (at >= headBytes) break;\n const part = chunk.subarray(0, headBytes - at);\n head.set(part, at);\n at += part.byteLength;\n }\n cap = Math.min(cap, capFromHead!(head));\n }\n if (total > cap) throw new Error(`inflates past the ${cap} bytes it can hold`);\n }\n } catch (err) {\n await reader.cancel().catch(() => {});\n throw err;\n }\n if (chunks.length === 1) return chunks[0];\n const out = new Uint8Array(total);\n let at = 0;\n for (const chunk of chunks) {\n out.set(chunk, at);\n at += chunk.byteLength;\n }\n return out;\n}\n", "/**\n * The CPU half of an `.spz` decode: header, framing and the per-attribute\n * unpack into the 3DGS PLY conventions every other format here decodes to.\n *\n * Ported from the PlayCanvas build's `spz-format.ts` / `spz-decode.ts`, minus\n * the decompression (injected by `spz.ts`, which has the platform in it).\n *\n * \u2500\u2500 Why every function here stands alone \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * These functions are also the source text of the decode worker\n * (`decode-worker.ts` stringifies them), so they may call each other but\n * must not read anything else at module scope: no imports, no module-level\n * constants. Tables live inside the function that uses them. The one import,\n * `inflateCapped`, is a stand-alone function the worker carries too.\n */\n\nimport type { SplatAttributes } from '../character/types';\nimport { inflateCapped } from '../shared/inflate';\n\n/** The fields of an SPZ header this reader acts on. */\nexport interface SpzHeader {\n version: number;\n numPoints: number;\n shDegree: number;\n fractionalBits: number;\n /** Trained with anti-aliasing. Read, not applied: the PlayCanvas build ignores it too. */\n antialiased: boolean;\n /** Version 4: how many zstd streams the table of contents lists. */\n numStreams: number;\n /** Version 4: where the table of contents starts. */\n tocByteOffset: number;\n}\n\n/**\n * The header of an UNCOMPRESSED file (version 4, or a gunzipped 1-3), or\n * `null` when these bytes do not start with the \"NGSP\" magic - which is how a\n * caller tells the two framings apart without parsing anything twice.\n */\nexport function readSpzHeader(file: Uint8Array): SpzHeader | null {\n if (file.byteLength < 16) return null;\n const view = new DataView(file.buffer, file.byteOffset, file.byteLength);\n // \"NGSP\", little-endian.\n if (view.getUint32(0, true) !== 0x5053474e) return null;\n const version = view.getUint32(4, true);\n return {\n version,\n numPoints: view.getUint32(8, true),\n shDegree: file[12],\n fractionalBits: file[13],\n antialiased: (file[14] & 0x1) !== 0,\n numStreams: file[15],\n tocByteOffset: version >= 4 && file.byteLength >= 32 ? view.getUint32(16, true) : 0,\n };\n}\n\n/**\n * Refuse a header no file of ours could have written. A point count past\n * spz-js's own ceiling is a corrupt header rather than a scene, and allocating\n * from it is how that becomes a crash instead of an error.\n */\nexport function checkSpzHeader(head: SpzHeader): void {\n if (head.version < 1 || head.version > 4) {\n throw new Error(`[spz] this is an SPZ version ${head.version}; this decoder reads 1 to 4`);\n }\n if (head.shDegree > 4) throw new Error(`[spz] spherical-harmonic degree ${head.shDegree} is not a degree`);\n if (!(head.numPoints > 0) || head.numPoints > 10_000_000) {\n throw new Error(`[spz] ${head.numPoints} points is not a plausible cloud`);\n }\n}\n\n/**\n * Byte length of each attribute stream, in the writer's order: positions,\n * alphas, colours, scales, rotations, SH. That order is the writer's and not\n * the format document's, and it matters: colours and scales are both 3 bytes\n * a point, so a reader that guessed from sizes would silently swap a scene's\n * colour for its size. Version 4 skips empty streams, so SH is 0 here when\n * absent and its table of contents lists one stream fewer.\n */\nexport function spzStreamSizes(head: SpzHeader): number[] {\n const n = head.numPoints;\n const shDim = [0, 3, 8, 15, 24][head.shDegree];\n return [\n // Version 1 stores a half float per axis, 2 onwards 24-bit fixed point.\n (head.version >= 2 ? 9 : 6) * n,\n n,\n 3 * n,\n 3 * n,\n // Smallest-three from version 3; three signed bytes with w derived before.\n (head.version >= 3 ? 4 : 3) * n,\n shDim * 3 * n,\n ];\n}\n\n/** Versions 1-3: one gzip stream holding the header, then each attribute in order. */\nexport function splitLegacySpz(raw: Uint8Array, head: SpzHeader): Uint8Array[] {\n const out: Uint8Array[] = [];\n let at = 16;\n for (const size of spzStreamSizes(head)) {\n if (at + size > raw.byteLength) {\n throw new Error(`[spz] this file ends early: ${raw.byteLength} bytes for a cloud of ${head.numPoints}`);\n }\n out.push(raw.subarray(at, at + size));\n at += size;\n }\n return out;\n}\n\n/**\n * Unpack the attribute streams into the 3DGS PLY conventions\n * {@link SplatAttributes} carries, with the PlayCanvas build's arithmetic:\n *\n * - colour: the DC spherical-harmonic term, `(byte / 255 - 0.5) / 0.15`;\n * - opacity: the raw logit `log(a / (1 - a))`, infinite at the ends as there;\n * - scale: the natural log, `byte / 16 - 10`;\n * - rotation: stored `xyzw`, returned with `rot_0 = w`.\n *\n * Higher SH bands are not read: splats here are lit flat, by their DC colour.\n */\nexport function unpackSpz(streams: Uint8Array[], head: SpzHeader): SplatAttributes {\n const n = head.numPoints;\n const [p, alpha, rgb, scale, rot] = streams;\n const x = new Float32Array(n), y = new Float32Array(n), z = new Float32Array(n);\n\n if (head.version >= 2) {\n const fixedScale = 1 / (1 << head.fractionalBits);\n // 24-bit little-endian, sign-extended by shifting the sign into bit 31 and back.\n const fixed = (k: number): number => (((p[k] | (p[k + 1] << 8) | (p[k + 2] << 16)) << 8) >> 8) * fixedScale;\n for (let i = 0, k = 0; i < n; i++, k += 9) {\n x[i] = fixed(k);\n y[i] = fixed(k + 3);\n z[i] = fixed(k + 6);\n }\n } else {\n // IEEE half by hand: the bytes sit at an offset a Float16Array view cannot take.\n const half = (bits: number): number => {\n const sign = bits & 0x8000 ? -1 : 1;\n const exponent = (bits >> 10) & 0x1f;\n const mantissa = bits & 0x3ff;\n if (exponent === 0) return sign * mantissa * 2 ** -24;\n if (exponent === 31) return mantissa !== 0 ? NaN : sign * Infinity;\n return sign * (mantissa + 1024) * 2 ** (exponent - 25);\n };\n for (let i = 0; i < n; i++) {\n x[i] = half(p[i * 6] | (p[i * 6 + 1] << 8));\n y[i] = half(p[i * 6 + 2] | (p[i * 6 + 3] << 8));\n z[i] = half(p[i * 6 + 4] | (p[i * 6 + 5] << 8));\n }\n }\n\n // Every one of these is a function of one byte: tables of 256, computed in\n // doubles and stored as float32, exactly as the per-splat arithmetic would.\n const opacityOf = new Float32Array(256);\n const colorOf = new Float32Array(256);\n const scaleOf = new Float32Array(256);\n for (let c = 0; c < 256; c++) {\n const a = c / 255;\n opacityOf[c] = Math.log(a / (1 - a));\n colorOf[c] = (c / 255 - 0.5) / 0.15;\n scaleOf[c] = c / 16 - 10;\n }\n\n const opacity = new Float32Array(n);\n const f_dc_0 = new Float32Array(n), f_dc_1 = new Float32Array(n), f_dc_2 = new Float32Array(n);\n const scale_0 = new Float32Array(n), scale_1 = new Float32Array(n), scale_2 = new Float32Array(n);\n for (let i = 0, j = 0; i < n; i++, j += 3) {\n opacity[i] = opacityOf[alpha[i]];\n f_dc_0[i] = colorOf[rgb[j]];\n f_dc_1[i] = colorOf[rgb[j + 1]];\n f_dc_2[i] = colorOf[rgb[j + 2]];\n scale_0[i] = scaleOf[scale[j]];\n scale_1[i] = scaleOf[scale[j + 1]];\n scale_2[i] = scaleOf[scale[j + 2]];\n }\n\n const rot_0 = new Float32Array(n), rot_1 = new Float32Array(n), rot_2 = new Float32Array(n), rot_3 = new Float32Array(n);\n const q = [rot_1, rot_2, rot_3, rot_0];\n if (head.version >= 3) {\n // Smallest-three: the 2-bit index of the dropped component, then the other\n // three in index order, each a sign bit and 9 bits of magnitude over\n // sqrt(1/2). The dropped one is the positive root of what they leave.\n const view = new DataView(rot.buffer, rot.byteOffset, rot.byteLength);\n const v = [0, 0, 0, 0];\n for (let i = 0; i < n; i++) {\n const bits = view.getUint32(i * 4, true);\n const largest = bits >>> 30;\n let sum = 0;\n let shift = 20;\n for (let c = 0; c < 4; c++) {\n if (c === largest) continue;\n const field = (bits >>> shift) & 0x3ff;\n const mag = ((field & 0x1ff) / 511) * Math.SQRT1_2;\n v[c] = field & 0x200 ? -mag : mag;\n sum += v[c] * v[c];\n shift -= 10;\n }\n v[largest] = Math.sqrt(Math.max(0, 1 - sum));\n for (let c = 0; c < 4; c++) q[c][i] = v[c];\n }\n } else {\n for (let i = 0; i < n; i++) {\n const qx = rot[i * 3] / 127.5 - 1;\n const qy = rot[i * 3 + 1] / 127.5 - 1;\n const qz = rot[i * 3 + 2] / 127.5 - 1;\n rot_1[i] = qx;\n rot_2[i] = qy;\n rot_3[i] = qz;\n rot_0[i] = Math.sqrt(Math.max(0, 1 - (qx * qx + qy * qy + qz * qz)));\n }\n }\n\n return { x, y, z, scale_0, scale_1, scale_2, rot_0, rot_1, rot_2, rot_3, f_dc_0, f_dc_1, f_dc_2, opacity };\n}\n\n/**\n * The splat order PlayCanvas's `GSplatData.calcMortonOrder` produces (10 bits\n * per axis over the cloud's bounds), by a stable two-pass radix sort. The\n * PlayCanvas build stores every `.spz` in this order: neighbours in space are\n * neighbours in memory, which is what the depth sort and every later pass\n * over the cloud read in.\n */\nexport function mortonOrder(x: Float32Array, y: Float32Array, z: Float32Array): Uint32Array {\n const n = x.length;\n const range = (a: Float32Array): [number, number] => {\n // The same comparisons as PlayCanvas, so a NaN lands where it would there.\n let min = a[0], max = a[0];\n for (let i = 1; i < n; i++) {\n if (a[i] < min) min = a[i];\n if (a[i] > max) max = a[i];\n }\n return [min, max];\n };\n const spread = (v: number): number => {\n v &= 0x3ff;\n v = (v ^ (v << 16)) & 0xff0000ff;\n v = (v ^ (v << 8)) & 0x0300f00f;\n v = (v ^ (v << 4)) & 0x030c30c3;\n return (v ^ (v << 2)) & 0x09249249;\n };\n const [minX, maxX] = range(x), [minY, maxY] = range(y), [minZ, maxZ] = range(z);\n const sx = minX === maxX ? 0 : 1024 / (maxX - minX);\n const sy = minY === maxY ? 0 : 1024 / (maxY - minY);\n const sz = minZ === maxZ ? 0 : 1024 / (maxZ - minZ);\n const codes = new Uint32Array(n);\n for (let i = 0; i < n; i++) {\n const ix = Math.min(1023, Math.floor((x[i] - minX) * sx));\n const iy = Math.min(1023, Math.floor((y[i] - minY) * sy));\n const iz = Math.min(1023, Math.floor((z[i] - minZ) * sz));\n codes[i] = (spread(iz) << 2) + (spread(iy) << 1) + spread(ix);\n }\n\n // Codes are 30 bits: two stable 15-bit passes, low digit first.\n const counts = new Uint32Array(1 << 15);\n const tmp = new Uint32Array(n);\n for (let i = 0; i < n; i++) counts[codes[i] & 0x7fff]++;\n for (let b = 0, sum = 0; b < counts.length; b++) { const c = counts[b]; counts[b] = sum; sum += c; }\n for (let i = 0; i < n; i++) tmp[counts[codes[i] & 0x7fff]++] = i;\n const order = new Uint32Array(n);\n counts.fill(0);\n for (let i = 0; i < n; i++) counts[codes[i] >>> 15]++;\n for (let b = 0, sum = 0; b < counts.length; b++) { const c = counts[b]; counts[b] = sum; sum += c; }\n for (let k = 0; k < n; k++) { const i = tmp[k]; order[counts[codes[i] >>> 15]++] = i; }\n return order;\n}\n\n/** Every attribute of `splats`, permuted by `order`. */\nexport function reorderSplats(splats: SplatAttributes, order: Uint32Array): SplatAttributes {\n const out = {} as Record<keyof SplatAttributes, Float32Array>;\n for (const key of Object.keys(splats) as (keyof SplatAttributes)[]) {\n const src = splats[key];\n const dst = new Float32Array(order.length);\n for (let i = 0; i < order.length; i++) dst[i] = src[order[i]];\n out[key] = dst;\n }\n return out;\n}\n\n/**\n * The worker's whole `.spz` job, given the file already split into streams\n * (version 4, inflated by the caller) or still gzipped (versions 1-3, inflated\n * here - `DecompressionStream` exists in a worker; zstd does not).\n */\nexport async function decodeSpzTask(\n input: { gzip: Uint8Array } | { head: SpzHeader; streams: Uint8Array[] },\n): Promise<{ numSplats: number; splats: SplatAttributes }> {\n let head: SpzHeader;\n let streams: Uint8Array[];\n if ('gzip' in input) {\n let raw: Uint8Array;\n try {\n // A gzip member ends with its inflated size (mod 2^32), which caps the\n // output - at whatever the file says. The SPZ header inside says how\n // long the cloud really is, and its point count is checked, so the\n // output stops there (a little past, for a writer's padding).\n const gz = input.gzip;\n const size = gz.length >= 18 ? new DataView(gz.buffer, gz.byteOffset + gz.length - 4, 4).getUint32(0, true) : 0;\n raw = await inflateCapped(gz, 'gzip', size, 16, (bytes) => {\n const inner = readSpzHeader(bytes);\n if (!inner) throw new Error('[spz] these bytes gunzip to something that is not an SPZ');\n if (inner.version >= 4) throw new Error('[spz] a version 4 file should not be gzipped; its streams carry their own');\n checkSpzHeader(inner);\n return 16 + spzStreamSizes(inner).reduce((sum, n) => sum + n, 0) + 65536;\n });\n } catch (err) {\n const message = (err as Error).message;\n if (message.startsWith('[spz]')) throw err;\n throw new Error(`[spz] this file is gzipped but does not decompress: ${message}`);\n }\n const parsed = readSpzHeader(raw);\n if (!parsed) throw new Error('[spz] these bytes gunzip to something that is not an SPZ');\n if (parsed.version >= 4) throw new Error(\"[spz] a version 4 file should not be gzipped; its streams carry their own\");\n checkSpzHeader(parsed);\n head = parsed;\n streams = splitLegacySpz(raw, head);\n } else {\n head = input.head;\n streams = input.streams;\n }\n const splats = unpackSpz(streams, head);\n return { numSplats: head.numPoints, splats: reorderSplats(splats, mortonOrder(splats.x, splats.y, splats.z)) };\n}\n", "/**\n * `packSplats` for the decode worker.\n *\n * Packing a million splats is ~100 ms of main thread on a desktop (half-float\n * conversions and an `exp` per scale axis), several times that on a phone, so\n * the worker packs what it decodes. `packSplats` itself cannot go there - it\n * converts through three's `DataUtils.toHalfFloat`, and the worker has no\n * three - so this is that function again with three's conversion inlined.\n *\n * IT MUST STAY BIT-IDENTICAL TO `packSplats` (splat/packed-splats.ts): an\n * `.spz` and the same scene as `.ply` have to upload the same texels. Change\n * the two together. Like the other worker functions it reads nothing at\n * module scope.\n */\n\nimport type { PackedSplats } from '../../splat/packed-splats';\nimport type { SplatAttributes } from '../character/types';\n\nexport function packSplatsInWorker(numSplats: number, s: SplatAttributes): PackedSplats {\n // three's `toHalfFloat` (DataUtils.js, \"fast half float conversions\"):\n // clamp to the half range, then a base + shift table on the float's sign and exponent.\n const floatView = new Float32Array(1);\n const bitsView = new Uint32Array(floatView.buffer);\n const baseTable = new Uint32Array(512);\n const shiftTable = new Uint32Array(512);\n for (let i = 0; i < 256; ++i) {\n const e = i - 127;\n if (e < -27) {\n baseTable[i] = 0x0000; baseTable[i | 0x100] = 0x8000;\n shiftTable[i] = shiftTable[i | 0x100] = 24;\n } else if (e < -14) {\n baseTable[i] = 0x0400 >> (-e - 14); baseTable[i | 0x100] = (0x0400 >> (-e - 14)) | 0x8000;\n shiftTable[i] = shiftTable[i | 0x100] = -e - 1;\n } else if (e <= 15) {\n baseTable[i] = (e + 15) << 10; baseTable[i | 0x100] = ((e + 15) << 10) | 0x8000;\n shiftTable[i] = shiftTable[i | 0x100] = 13;\n } else if (e < 128) {\n baseTable[i] = 0x7c00; baseTable[i | 0x100] = 0xfc00;\n shiftTable[i] = shiftTable[i | 0x100] = 24;\n } else {\n baseTable[i] = 0x7c00; baseTable[i | 0x100] = 0xfc00;\n shiftTable[i] = shiftTable[i | 0x100] = 13;\n }\n }\n const toHalf = (v: number): number => {\n floatView[0] = Math.max(-65504, Math.min(65504, v));\n const f = bitsView[0];\n const e = (f >> 23) & 0x1ff;\n return baseTable[e] + ((f & 0x007fffff) >> shiftTable[e]);\n };\n\n const SH_C0 = 0.28209479177387814;\n const width = Math.max(1, Math.ceil(Math.sqrt(numSplats)));\n const height = Math.max(1, Math.ceil(numSplats / width));\n const texels = width * height;\n const color = new Uint16Array(texels * 4);\n const transformA = new Uint32Array(texels * 4);\n const transformAFloat = new Float32Array(transformA.buffer);\n const transformB = new Uint16Array(texels * 4);\n const centers = new Float32Array(numSplats * 3);\n\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n\n for (let i = 0; i < numSplats; i++) {\n const o = i * 4;\n\n color[o] = toHalf(s.f_dc_0[i] * SH_C0 + 0.5);\n color[o + 1] = toHalf(s.f_dc_1[i] * SH_C0 + 0.5);\n color[o + 2] = toHalf(s.f_dc_2[i] * SH_C0 + 0.5);\n color[o + 3] = toHalf(1 / (1 + Math.exp(-s.opacity[i])));\n\n const x = s.x[i], y = s.y[i], z = s.z[i];\n transformAFloat[o] = x;\n transformAFloat[o + 1] = y;\n transformAFloat[o + 2] = z;\n centers[i * 3] = x;\n centers[i * 3 + 1] = y;\n centers[i * 3 + 2] = z;\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n if (z < minZ) minZ = z;\n if (z > maxZ) maxZ = z;\n\n let qw = s.rot_0[i], qx = s.rot_1[i], qy = s.rot_2[i], qz = s.rot_3[i];\n const len = Math.sqrt(qx * qx + qy * qy + qz * qz + qw * qw);\n if (len === 0) {\n qx = qy = qz = 0;\n qw = 1;\n } else {\n const inv = (qw < 0 ? -1 : 1) / len;\n qx *= inv;\n qy *= inv;\n qz *= inv;\n }\n transformA[o + 3] = (toHalf(qx) | (toHalf(qy) << 16)) >>> 0;\n\n transformB[o] = toHalf(Math.exp(s.scale_0[i]));\n transformB[o + 1] = toHalf(Math.exp(s.scale_1[i]));\n transformB[o + 2] = toHalf(Math.exp(s.scale_2[i]));\n transformB[o + 3] = toHalf(qz);\n }\n\n if (numSplats === 0) {\n minX = minY = minZ = maxX = maxY = maxZ = 0;\n }\n\n return {\n numSplats, width, height, color, transformA, transformB, centers,\n boundsMin: [minX, minY, minZ],\n boundsMax: [maxX, maxY, maxZ],\n };\n}\n", "/**\n * The CPU half of a SOG decode (PlayCanvas's \"Spatially Ordered Gaussians\":\n * a `meta.json` and lossless WebP images, unbundled or zipped as `.sog`):\n * image bytes to pixels to the 3DGS PLY conventions of {@link SplatAttributes}.\n * The arithmetic is PlayCanvas's `GSplatSogData.decompress`, as the PlayCanvas\n * build's `sog-decode.ts` reproduces it.\n *\n * Like `spz-decode.ts`, these functions are also the decode worker's source\n * text (`decode-worker.ts`), so they read nothing at module scope.\n */\n\nimport type { SplatAttributes } from '../character/types';\n\n/** A SOG `meta.json`: version 2 (codebooks), or the version 1 layout PlayCanvas still reads. */\nexport interface SogMeta {\n version?: number;\n /** Version 2. Version 1 has `means.shape[0]` instead. */\n count?: number;\n means: { mins: number[]; maxs: number[]; files: string[]; shape?: number[] };\n scales: { codebook?: (number | null)[]; mins?: number[]; maxs?: number[]; files: string[] };\n quats: { files: string[] };\n sh0: { codebook?: (number | null)[]; mins?: number[]; maxs?: number[]; files: string[] };\n}\n\n/** RGBA8 pixels of the five images a DC-only decode reads, in file order (row-major from the top). */\nexport interface SogPixels {\n means_l: Uint8Array;\n means_u: Uint8Array;\n quats: Uint8Array;\n scales: Uint8Array;\n sh0: Uint8Array;\n}\n\n/** Splat count of a SOG, from either version of its meta. */\nexport function sogCount(meta: SogMeta): number {\n return meta.count ?? meta.means.shape?.[0] ?? 0;\n}\n\n/**\n * Decode images to their exact RGBA8 bytes.\n *\n * Not through a 2D canvas: `getImageData` hands back pixels that went through\n * premultiplied storage, and SOG keeps data in alpha (opacity in `sh0.a`, the\n * rotation's mode byte in `quats.a`), so every pixel with alpha below 255\n * would come back with its colour quantised against it. An unpremultiplied\n * `ImageBitmap` uploaded to a WebGL2 texture and read back is exact - and is\n * what PlayCanvas itself does with these images.\n */\nexport async function readImagePixels(files: Uint8Array[]): Promise<Uint8Array[]> {\n const bitmaps = await Promise.all(\n files.map((bytes) => createImageBitmap(new Blob([bytes as BlobPart]), {\n premultiplyAlpha: 'none',\n colorSpaceConversion: 'none',\n })),\n );\n const gl = new OffscreenCanvas(1, 1).getContext('webgl2');\n if (!gl) {\n for (const b of bitmaps) b.close();\n throw new Error('[sog] WebGL2 is not available here to read the SOG images back');\n }\n const texture = gl.createTexture();\n const framebuffer = gl.createFramebuffer();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);\n gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);\n try {\n return bitmaps.map((bitmap) => {\n const { width, height } = bitmap;\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n const pixels = new Uint8Array(width * height * 4);\n gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);\n return pixels;\n });\n } finally {\n for (const b of bitmaps) b.close();\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(texture);\n // Contexts are a scarce per-page resource; do not wait for the collector.\n gl.getExtension('WEBGL_lose_context')?.loseContext();\n }\n}\n\n/**\n * SOG pixels to splat attributes, with PlayCanvas's arithmetic:\n *\n * - centre: 16 bits per axis over `means.mins..maxs`, stored log-encoded\n * (`sign(t) * (exp|t| - 1)`);\n * - rotation: three components over `\u00B1sqrt(1/2)` and a mode byte (252-255)\n * naming which one was dropped. A mode outside that range keeps the\n * previous splat's rotation, as PlayCanvas's iterator does;\n * - scale and colour: a byte each per channel into a codebook (version 2) or\n * onto `mins..maxs` (version 1), colour as the SH DC term;\n * - opacity: `sh0.a` is the alpha (version 2) or a logit byte (version 1),\n * returned as a logit clamped to \u00B140.\n */\nexport function decodeSogPixels(meta: SogMeta, px: SogPixels): SplatAttributes {\n const n = sogCount(meta);\n const v2 = meta.version === 2;\n const lerp = (a: number, b: number, t: number): number => a * (1 - t) + b * t;\n // A codebook written with a null first entry: PlayCanvas extrapolates it.\n const book = (codebook: (number | null)[] | undefined): number[] => {\n const out = (codebook ?? []).slice() as number[];\n if (codebook?.[0] === null) out[0] = out[1] + (out[1] - out[255]) / 255;\n return out;\n };\n const scaleBook = book(meta.scales.codebook);\n const colorBook = book(meta.sh0.codebook);\n const SH_C0 = 0.28209479177387814;\n\n // Each value below is a function of one byte (or, for centres, of 16 bits):\n // tables, computed in doubles and stored as float32 as per splat they would be.\n const positionTable = (axis: number): Float32Array => {\n const out = new Float32Array(65536);\n const min = meta.means.mins[axis], max = meta.means.maxs[axis];\n for (let v = 0; v < 65536; v++) {\n const t = lerp(min, max, v / 65535);\n out[v] = Math.sign(t) * (Math.exp(Math.abs(t)) - 1);\n }\n return out;\n };\n const posX = positionTable(0), posY = positionTable(1), posZ = positionTable(2);\n const scaleOf = new Float32Array(768);\n const colorOf = new Float32Array(768);\n for (let c = 0; c < 3; c++) {\n for (let b = 0; b < 256; b++) {\n scaleOf[c * 256 + b] = v2 ? scaleBook[b] : lerp(meta.scales.mins![c], meta.scales.maxs![c], b / 255);\n const color = 0.5 + (v2 ? colorBook[b] : lerp(meta.sh0.mins![c], meta.sh0.maxs![c], b / 255)) * SH_C0;\n colorOf[c * 256 + b] = (color - 0.5) / SH_C0;\n }\n }\n const opacityOf = new Float32Array(256);\n for (let b = 0; b < 256; b++) {\n const a = v2 ? b / 255 : 1 / (1 + Math.exp(-lerp(meta.sh0.mins![3], meta.sh0.maxs![3], b / 255)));\n opacityOf[b] = a <= 0 ? -40 : a >= 1 ? 40 : -Math.log(1 / a - 1);\n }\n\n const out = {} as Record<keyof SplatAttributes, Float32Array>;\n for (const key of ['x', 'y', 'z', 'scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3', 'f_dc_0', 'f_dc_1', 'f_dc_2', 'opacity'] as const) {\n out[key] = new Float32Array(n);\n }\n const { means_l: ml, means_u: mu, quats: qd, scales: sd, sh0: cd } = px;\n let qx = 0, qy = 0, qz = 0, qw = 1;\n for (let i = 0; i < n; i++) {\n const o = i * 4;\n out.x[i] = posX[(mu[o] << 8) + ml[o]];\n out.y[i] = posY[(mu[o + 1] << 8) + ml[o + 1]];\n out.z[i] = posZ[(mu[o + 2] << 8) + ml[o + 2]];\n\n const a = (qd[o] / 255 - 0.5) * Math.SQRT2;\n const b = (qd[o + 1] / 255 - 0.5) * Math.SQRT2;\n const c = (qd[o + 2] / 255 - 0.5) * Math.SQRT2;\n const d = Math.sqrt(Math.max(0, 1 - (a * a + b * b + c * c)));\n switch (qd[o + 3] - 252) {\n case 0: qx = a; qy = b; qz = c; qw = d; break;\n case 1: qx = d; qy = b; qz = c; qw = a; break;\n case 2: qx = b; qy = d; qz = c; qw = a; break;\n case 3: qx = b; qy = c; qz = d; qw = a; break;\n }\n out.rot_0[i] = qw;\n out.rot_1[i] = qx;\n out.rot_2[i] = qy;\n out.rot_3[i] = qz;\n\n out.scale_0[i] = scaleOf[sd[o]];\n out.scale_1[i] = scaleOf[256 + sd[o + 1]];\n out.scale_2[i] = scaleOf[512 + sd[o + 2]];\n out.f_dc_0[i] = colorOf[cd[o]];\n out.f_dc_1[i] = colorOf[256 + cd[o + 1]];\n out.f_dc_2[i] = colorOf[512 + cd[o + 2]];\n out.opacity[i] = opacityOf[cd[o + 3]];\n }\n return out;\n}\n\n/** The worker's whole SOG job: the five images' bytes, in {@link SogPixels} order, to splat attributes. */\nexport async function decodeSogTask(\n input: { meta: SogMeta; images: Uint8Array[] },\n): Promise<{ numSplats: number; splats: SplatAttributes }> {\n const [means_l, means_u, quats, scales, sh0] = await readImagePixels(input.images);\n const numSplats = sogCount(input.meta);\n for (const p of [means_l, means_u, quats, scales, sh0]) {\n if (p.length < numSplats * 4) throw new Error(`[sog] an image holds ${p.length / 4} pixels for ${numSplats} splats`);\n }\n return { numSplats, splats: decodeSogPixels(input.meta, { means_l, means_u, quats, scales, sh0 }) };\n}\n", "/**\n * One worker, shared by every load, for the CPU-heavy half of an `.spz` or\n * SOG decode, packing included: a million-splat unpack, Morton order and pack\n * is the better part of a second of main thread on a phone otherwise.\n *\n * The worker is built from a Blob of the decode functions' own source text, as\n * `AsyncDepthSorter` builds its sorter, so there is no second file for an\n * application's bundler to lose. Each function is emitted under the name it\n * has in this bundle, which is the name its callers use too - so whatever a\n * bundler or minifier renamed, the functions still find each other.\n */\n\nimport type { PackedSplats } from '../../splat/packed-splats';\nimport {\n checkSpzHeader,\n decodeSpzTask,\n mortonOrder,\n readSpzHeader,\n reorderSplats,\n splitLegacySpz,\n spzStreamSizes,\n unpackSpz,\n} from '../environment/spz-decode';\n\nimport { inflateCapped } from './inflate';\nimport { packSplatsInWorker } from './pack-splats-task';\nimport { decodeSogPixels, decodeSogTask, readImagePixels, sogCount } from './sog-decode';\n\n/** The decode tasks, by name, and what each takes. */\ninterface TaskInputs {\n spz: Parameters<typeof decodeSpzTask>[0];\n sog: Parameters<typeof decodeSogTask>[0];\n}\n\n/** Decode, then pack: the whole of a task, in the worker or - without workers - here. */\nasync function runTask(task: keyof TaskInputs, input: TaskInputs[keyof TaskInputs]): Promise<PackedSplats> {\n const { numSplats, splats } = task === 'spz'\n ? await decodeSpzTask(input as TaskInputs['spz'])\n : await decodeSogTask(input as TaskInputs['sog']);\n return packSplatsInWorker(numSplats, splats);\n}\n\nconst WORKER_FUNCTIONS = [\n inflateCapped,\n readSpzHeader, checkSpzHeader, spzStreamSizes, splitLegacySpz, unpackSpz, mortonOrder, reorderSplats, decodeSpzTask,\n sogCount, readImagePixels, decodeSogPixels, decodeSogTask, packSplatsInWorker, runTask,\n];\n\nfunction workerSource(): string {\n // Wrapped as an expression so the text works whether a bundler leaves a\n // function as a declaration or rewrites it as an arrow.\n const functions = WORKER_FUNCTIONS.map((f) => `const ${f.name} = (${f.toString()});`).join('\\n');\n return `${functions}\n self.postMessage({ ready: true });\n self.onmessage = async (e) => {\n const { id, task, input } = e.data;\n try {\n const out = await ${runTask.name}(task, input);\n self.postMessage({ id, ok: true, out }, [out.color.buffer, out.transformA.buffer, out.transformB.buffer, out.centers.buffer]);\n } catch (err) {\n self.postMessage({ id, ok: false, error: err instanceof Error ? err.message : String(err) });\n }\n };\n `;\n}\n\ntype Pending = { resolve: (v: PackedSplats) => void; reject: (e: unknown) => void };\nlet worker: Worker | null = null;\n/** Resolves true once the worker has started, false if it could not. */\nlet workerReady: Promise<boolean> | null = null;\n/** Set when a worker cannot start here (a CSP without `worker-src blob:`, say): decode on this thread from then on. */\nlet workersUnavailable = false;\nlet nextId = 0;\nconst pending = new Map<number, Pending>();\n\nfunction spawn(): Promise<boolean> {\n let w: Worker;\n try {\n const url = URL.createObjectURL(new Blob([workerSource()], { type: 'text/javascript' }));\n w = new Worker(url, { name: 'splat-decode' });\n URL.revokeObjectURL(url);\n } catch {\n return Promise.resolve(false);\n }\n worker = w;\n let started = false;\n let settle!: (ok: boolean) => void;\n const ready = new Promise<boolean>((resolve) => { settle = resolve; });\n w.onmessage = (e: MessageEvent<{ ready?: true; id: number; ok: boolean; out?: PackedSplats; error?: string }>) => {\n if (e.data.ready) {\n started = true;\n settle(true);\n return;\n }\n const entry = pending.get(e.data.id);\n if (!entry) return;\n pending.delete(e.data.id);\n if (e.data.ok) entry.resolve(e.data.out!);\n else entry.reject(new Error(e.data.error));\n };\n // A worker that died, or a reply that could not be read, names no request:\n // fail every one in flight, and let the next decode start a fresh worker.\n // One that never started cannot here: decode on this thread instead.\n const fail = (detail?: string) => {\n w.terminate();\n if (worker === w) {\n worker = null;\n workerReady = null;\n }\n if (!started) {\n workersUnavailable = true;\n settle(false);\n return;\n }\n const failure = new Error(`[splat-engine-three] the decode worker failed${detail ? `: ${detail}` : ''}`);\n const failed = [...pending.values()];\n pending.clear();\n for (const p of failed) p.reject(failure);\n };\n w.onerror = (e) => fail(e.message);\n w.onmessageerror = () => fail('a reply could not be read');\n return ready;\n}\n\n/**\n * Decode and pack in the shared worker - or on this thread where there are\n * no workers (a test runner, a server render, a page whose CSP blocks them).\n * The buffers in `transfer` are moved, not copied: the caller must not read\n * them afterwards.\n */\nexport async function runDecodeTask<K extends keyof TaskInputs>(\n task: K,\n input: TaskInputs[K],\n transfer: ArrayBuffer[],\n): Promise<PackedSplats> {\n if (typeof Worker === 'undefined' || workersUnavailable) return runTask(task, input);\n // Nothing is posted until the worker has started, so a worker that cannot\n // start has not taken the input's buffers with it.\n if (!(await (workerReady ??= spawn()))) {\n workersUnavailable = true;\n return runTask(task, input);\n }\n // It started, then died before this call: start another.\n if (!worker) return runDecodeTask(task, input, transfer);\n const id = nextId++;\n const result = new Promise<PackedSplats>((resolve, reject) => pending.set(id, { resolve, reject }));\n worker.postMessage({ id, task, input }, transfer);\n return result;\n}\n", "/**\n * `.spz` captures, decoded and packed for a {@link Splat}.\n *\n * Reads every version the PlayCanvas build reads: 1 to 3, which wrap the\n * whole file in gzip, and 4, which has a plaintext header, a table of contents\n * and one zstd stream per attribute.\n *\n * The decompression is split by what the platform offers. Gzip is\n * `DecompressionStream`, which a worker has, so a gzipped file goes to the\n * decode worker whole. Zstd is not in any browser's script API - Chrome takes\n * it as a Content-Encoding, which is a different thing - so version 4 streams\n * are inflated here with `zstddec` (the reference decoder as WASM, carried\n * inside this bundle), and only the unpack and the packing go to the worker.\n */\n\nimport type { ZSTDDecoder } from 'zstddec';\n\nimport type { PackedSplats } from '../../splat/packed-splats';\nimport { runDecodeTask } from '../shared/decode-worker';\n\nimport { checkSpzHeader, readSpzHeader, spzStreamSizes } from './spz-decode';\nimport type { SpzHeader } from './spz-decode';\n\nlet zstd: Promise<ZSTDDecoder> | null = null;\n\nfunction zstdDecoder(): Promise<ZSTDDecoder> {\n if (!zstd) {\n // Imported on first use: the decoder is ~75 KB of inlined WASM that an\n // application reading no version 4 file should not download.\n zstd = import('zstddec').then(async ({ ZSTDDecoder }) => {\n const decoder = new ZSTDDecoder();\n await decoder.init();\n return decoder;\n });\n // A failed init is retried by the next file rather than cached.\n zstd.catch(() => { zstd = null; });\n }\n return zstd;\n}\n\n/** The streams of a version 4 file this reader uses, inflated. Spherical harmonics are skipped: splats here are lit by their DC colour. */\nasync function inflateV4(file: Uint8Array, head: SpzHeader): Promise<Uint8Array[]> {\n const view = new DataView(file.buffer, file.byteOffset, file.byteLength);\n const sizes = spzStreamSizes(head);\n // The writer skips empty streams, so `numStreams` counts what is present.\n const present = sizes.filter((size) => size > 0);\n if (present.length !== head.numStreams) {\n throw new Error(\n `[spz] the header says ${head.numStreams} streams; a cloud of ${head.numPoints} points ` +\n `with SH degree ${head.shDegree} has ${present.length}`,\n );\n }\n const toc = head.tocByteOffset;\n if (toc < 32 || toc + present.length * 16 > file.byteLength) {\n throw new Error(`[spz] the table of contents is not inside the file (at ${toc})`);\n }\n\n const decoder = await zstdDecoder();\n const names = ['positions', 'alphas', 'colors', 'scales', 'rotations'];\n const streams: Uint8Array[] = [];\n let at = toc + present.length * 16;\n for (let i = 0; i < names.length; i++) {\n const compressed = Number(view.getBigUint64(toc + i * 16, true));\n const size = Number(view.getBigUint64(toc + i * 16 + 8, true));\n // Trusted only as far as it checks out: a stream whose length disagrees\n // with the point count is a file we have misread, and misreading a stream\n // swaps one attribute for another rather than failing.\n if (size !== sizes[i]) {\n throw new Error(`[spz] the ${names[i]} stream says ${size} bytes, not the ${sizes[i]} that ${head.numPoints} points need`);\n }\n if (at + compressed > file.byteLength) throw new Error(`[spz] the ${names[i]} stream runs past the end of the file`);\n // zstddec returns an empty array rather than throwing on a bad stream,\n // so the length check is what refuses one - naming the stream, which the\n // decoder's own message would not.\n const out = decoder.decode(file.subarray(at, at + compressed), size);\n if (out.byteLength !== size) throw new Error(`[spz] the ${names[i]} stream does not decompress`);\n streams.push(out);\n at += compressed;\n }\n streams.push(new Uint8Array(0));\n return streams;\n}\n\n/**\n * Decode an `.spz` file into packed splats, in Morton order.\n *\n * The framing is read off the bytes, never off a name: a file that starts\n * with the \"NGSP\" magic is version 4, one that starts with gzip's is 1-3.\n * Anything else is refused here, in those words - handed to a decompressor it\n * would fail as \"incorrect header check\", which names neither the file nor\n * the format.\n *\n * @throws If the bytes are not an SPZ this reader understands.\n * @group Loaders\n */\nexport async function decodeSpz(file: Uint8Array): Promise<PackedSplats> {\n const head = readSpzHeader(file);\n if (!head) {\n if (file.byteLength < 2 || file[0] !== 0x1f || file[1] !== 0x8b) {\n throw new Error(`[spz] these ${file.byteLength} bytes are not an SPZ: no \"NGSP\" header and no gzip wrapper`);\n }\n // Copied to the worker, not transferred: the caller's bytes stay theirs.\n return runDecodeTask('spz', { gzip: file }, []);\n }\n checkSpzHeader(head);\n if (head.version !== 4) {\n throw new Error(`[spz] an uncompressed version ${head.version} file; versions before 4 are read gzipped`);\n }\n const streams = await inflateV4(file, head);\n return runDecodeTask('spz', { head, streams }, streams.map((s) => s.buffer as ArrayBuffer));\n}\n", "/**\n * SOG scenes: a `meta.json` beside its WebP images (what a streaming LOD\n * bundle is made of, one per chunk), or the same files zipped into one `.sog`.\n * Fetching and unzipping happen here; decoding the images and the splats is\n * the decode worker's (`sog-decode.ts`).\n */\n\nimport { cachedFetch } from './bin-cache';\nimport type { PackedSplats } from '../../splat/packed-splats';\n\nimport { runDecodeTask } from './decode-worker';\nimport type { SogMeta } from './sog-decode';\nimport { inflateCapped } from './inflate';\n\n/** `url` resolved against `base`, itself resolved against the page. */\nexport function resolveUrl(url: string, base: string): string {\n return new URL(url, new URL(base, globalThis.location?.href)).href;\n}\n\nasync function fetchBytes(url: string): Promise<Uint8Array> {\n const res = await cachedFetch(url);\n if (!res.ok) throw new Error(`[sog] fetch failed (${res.status}): ${url}`);\n return new Uint8Array(await res.arrayBuffer());\n}\n\nfunction decodeImages(meta: SogMeta, images: Uint8Array[]): Promise<PackedSplats> {\n // The bytes are ours alone (a fetch or an unzip made them), so they move to the worker.\n return runDecodeTask('sog', { meta, images }, images.map((b) => b.buffer as ArrayBuffer));\n}\n\n/** The image files a DC-only decode reads, in `SogPixels` order. */\nfunction imageFiles(meta: SogMeta): string[] {\n const [means_l, means_u] = meta.means.files;\n return [means_l, means_u, meta.quats.files[0], meta.scales.files[0], meta.sh0.files[0]];\n}\n\n/**\n * Fetch and decode an unbundled SOG from its `meta.json`; the images are\n * fetched from beside it. Higher SH bands (`shN`) are not fetched: splats here\n * are lit by their DC colour.\n */\nexport async function loadSogMeta(url: string): Promise<PackedSplats> {\n const res = await cachedFetch(url);\n if (!res.ok) throw new Error(`[sog] fetch failed (${res.status}): ${url}`);\n const meta = (await res.json()) as SogMeta;\n const images = await Promise.all(imageFiles(meta).map((file) => fetchBytes(resolveUrl(file, url))));\n return decodeImages(meta, images);\n}\n\n/**\n * The most one deflated entry of a bundle may inflate to. Its images are\n * WebP, compressed already, so a writer stores them or barely deflates them,\n * and meta.json is text: none of it comes near this.\n */\nconst SOG_ENTRY_MAX_BYTES = 256 * 1024 * 1024;\n/** The most all of a bundle's deflated entries together may inflate to. */\nconst SOG_INFLATE_MAX_BYTES = 1024 * 1024 * 1024;\n\n/**\n * The files of a zip archive, by name. Stored and deflated entries - all a\n * `.sog` writer produces, its images being compressed already. No zip64.\n */\nasync function unzip(file: Uint8Array): Promise<Map<string, Uint8Array>> {\n const view = new DataView(file.buffer, file.byteOffset, file.byteLength);\n // The end-of-central-directory record: 22 bytes plus a comment of up to 64 KB.\n let eocd = -1;\n for (let i = file.byteLength - 22; i >= Math.max(0, file.byteLength - 22 - 0xffff); i--) {\n if (view.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n }\n if (eocd < 0) throw new Error('[sog] not a .sog bundle: no zip directory');\n const entries = view.getUint16(eocd + 10, true);\n let at = view.getUint32(eocd + 16, true);\n const names = new TextDecoder();\n const out = new Map<string, Uint8Array>();\n let inflated = 0;\n for (let e = 0; e < entries; e++) {\n if (view.getUint32(at, true) !== 0x02014b50) throw new Error('[sog] the zip directory is corrupt');\n const method = view.getUint16(at + 10, true);\n const compressed = view.getUint32(at + 20, true);\n const uncompressed = view.getUint32(at + 24, true);\n const nameLength = view.getUint16(at + 28, true);\n const skip = nameLength + view.getUint16(at + 30, true) + view.getUint16(at + 32, true);\n const name = names.decode(file.subarray(at + 46, at + 46 + nameLength));\n const local = view.getUint32(at + 42, true);\n const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);\n const data = file.subarray(start, start + compressed);\n if (method === 0) {\n out.set(name, data.slice());\n } else if (method === 8) {\n try {\n // The declared size is the file's own word: cap it by what deflate\n // can expand to and by what a bundle this engine draws holds.\n const cap = Math.min(uncompressed, data.byteLength * 1032 + 64, SOG_ENTRY_MAX_BYTES, SOG_INFLATE_MAX_BYTES - inflated);\n const bytes = await inflateCapped(data, 'deflate-raw', cap);\n inflated += bytes.byteLength;\n out.set(name, bytes);\n } catch (err) {\n throw new Error(`[sog] '${name}' does not inflate: ${(err as Error).message}`);\n }\n } else {\n throw new Error(`[sog] '${name}' uses zip compression method ${method}; only stored and deflated entries are read`);\n }\n at += 46 + skip;\n }\n return out;\n}\n\n/** Decode a bundled `.sog` (a zip of `meta.json` and its images) held in memory. */\nexport async function decodeSogBundle(file: Uint8Array): Promise<PackedSplats> {\n const files = await unzip(file);\n const metaBytes = files.get('meta.json');\n if (!metaBytes) throw new Error('[sog] the bundle has no meta.json');\n const meta = JSON.parse(new TextDecoder().decode(metaBytes)) as SogMeta;\n const images = imageFiles(meta).map((name) => {\n const bytes = files.get(name);\n if (!bytes) throw new Error(`[sog] the bundle has no '${name}'`);\n return bytes;\n });\n return decodeImages(meta, images);\n}\n", "/**\n * Splat files by URL, whatever their format: fetched, decoded, packed.\n *\n * The three.js counterpart of the PlayCanvas build's `loadSplatAsset`. There\n * it returns a PlayCanvas asset for the caller to mount on a `gsplat` entity;\n * here it returns a {@link Splat} for the caller to add to a scene, and the\n * decoded data behind it is a {@link SplatSource} any number of splats can be\n * built from.\n */\n\nimport type { SplatEngine } from '../../engine';\nimport { EngineDisposedError } from '../../engine';\nimport { packSplats } from '../../splat/packed-splats';\nimport { Splat } from '../../splat/splat';\nimport type { SplatSource } from '../../splat/splat';\nimport { parseGaussianPly } from '../environment/ply';\nimport { decodeSpz } from '../environment/spz';\n\nimport { cacheKeyFor, cachedFetch } from './bin-cache';\nimport { decodeSogBundle, loadSogMeta } from './sog';\n\n/** The splat formats {@link loadSplatSource} reads, as told by the file name. */\ntype SplatFormat = 'ply' | 'spz' | 'sog' | 'sog-meta';\n\n/** File name of `url`, without directory or query string. */\nexport function fileNameOf(url: string): string {\n return url.split(/[?#]/)[0].split('/').pop() || 'splat';\n}\n\n/** The format a file name says, or `null` for one this package does not read. */\nexport function splatFormatOf(filename: string): SplatFormat | null {\n const lower = filename.toLowerCase();\n // PlayCanvas's own quantised PLY: a different layout behind the same extension.\n if (lower.endsWith('.compressed.ply')) return null;\n if (lower.endsWith('.ply')) return 'ply';\n if (lower.endsWith('.spz')) return 'spz';\n if (lower.endsWith('.sog')) return 'sog';\n if (lower.endsWith('meta.json')) return 'sog-meta';\n return null;\n}\n\n// \u2500\u2500 Shared decodes (opt-in) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// With sharing on, every load of one file - by path, so a re-signed URL still\n// matches - reuses one decode: the fetch, the decode and the packed CPU data\n// happen once, however many splats are built from it. A game spawning many of\n// one model (a crowd, a pile of props) pays for one.\n//\n// What it does not share is the GPU copy: each `Splat` uploads its own\n// textures from the shared arrays.\nlet _shareResources = false;\nconst _shared = new Map<string, Promise<unknown>>();\n\n/**\n * Share one decode among every load of the same file, for a game that spawns\n * many of one model. Off by default: each load decodes its own copy. Affects\n * loads after the call; turning it off releases what it holds.\n *\n * Decoded data is held until sharing is turned off: it is not reference\n * counted, so a game that cycles through many distinct files should leave\n * this off.\n *\n * @group Loaders\n */\nexport function setShareSplatResources(enabled: boolean): void {\n _shareResources = enabled;\n if (!enabled) _shared.clear();\n}\n\n/**\n * `decode()`, or - with {@link setShareSplatResources} on - the result of an\n * earlier `decode()` for the same `kind` of load of the same file. The result\n * must be treated as read-only by everything that receives it.\n * @internal\n */\nexport function sharedDecode<T>(kind: string, url: string, decode: () => Promise<T>): Promise<T> {\n if (!_shareResources) return decode();\n const key = `${kind}:${cacheKeyFor(url)}`;\n let entry = _shared.get(key) as Promise<T> | undefined;\n if (!entry) {\n entry = decode();\n _shared.set(key, entry);\n // A failed decode is retried by the next load rather than cached.\n entry.catch(() => { if (_shared.get(key) === entry) _shared.delete(key); });\n }\n return entry;\n}\n\nfunction unsupportedFormat(filename: string): Error {\n return new Error(\n `[splat-engine-three] unsupported splat format '${filename}'; expected .ply, .spz, .sog or a SOG meta.json`,\n );\n}\n\n/**\n * Decode a splat file already in memory. `filename` names the format; an\n * unbundled SOG (`meta.json`) cannot be read this way, since its images are\n * separate files.\n *\n * @throws If the format is not one this package reads, or the bytes are not that format.\n * @group Loaders\n */\nexport async function decodeSplatFile(data: ArrayBuffer, filename: string): Promise<SplatSource> {\n switch (splatFormatOf(filename)) {\n case 'ply': {\n const { numSplats, splats } = parseGaussianPly(data);\n return { packed: packSplats(numSplats, splats) };\n }\n case 'spz': return { packed: await decodeSpz(new Uint8Array(data)) };\n case 'sog': return { packed: await decodeSogBundle(new Uint8Array(data)) };\n default: throw unsupportedFormat(filename);\n }\n}\n\n/**\n * Fetch and decode a splat file: `.ply` (uncompressed 3D Gaussian Splatting),\n * `.spz` (versions 1-4), `.sog`, or an unbundled SOG's `meta.json`.\n *\n * The bytes go through the asset cache (`cachedFetch`). With\n * {@link setShareSplatResources} on, repeated loads of one file share one decode.\n *\n * @param filename - Names the format when the URL does not (a signed CDN URL). Default: the URL's file name.\n * @group Loaders\n */\nexport function loadSplatSource(url: string, filename = fileNameOf(url)): Promise<SplatSource> {\n return sharedDecode('splat', url, () => fetchSplatSource(url, filename));\n}\n\n/**\n * {@link loadSplatSource} without the sharing: always a fresh fetch and\n * decode, for a caller that manages the lifetime of what it loads.\n * @internal\n */\nexport async function fetchSplatSource(url: string, filename = fileNameOf(url)): Promise<SplatSource> {\n const format = splatFormatOf(filename);\n // Refused before the download, not after it.\n if (!format) throw unsupportedFormat(filename);\n if (format === 'sog-meta') return { packed: await loadSogMeta(url) };\n const res = await cachedFetch(url);\n if (!res.ok) throw new Error(`[splat-engine-three] fetch failed (${res.status}): ${url}`);\n return decodeSplatFile(await res.arrayBuffer(), filename);\n}\n\n/**\n * Load a Gaussian-splat file as an unparented {@link Splat}: add its\n * `object3D` to a scene, or to a character's bone, yourself.\n *\n * The PlayCanvas build's `loadSplatAsset`, which returns an asset to mount on\n * a `gsplat` entity; the splat is that mounted thing. See\n * {@link loadSplatSource} for the formats and {@link setShareSplatResources}\n * for loading one model many times.\n *\n * @param filename - Names the format when the URL does not (a signed CDN URL). Default: the URL's file name.\n * @throws {EngineDisposedError} If `engine` is disposed before or while the file loads.\n *\n * @example\n * ```ts\n * const prop = await loadSplatAsset(engine, '/assets/crate.spz');\n * prop.object3D.position.set(1, 0, 0);\n * scene.add(prop.object3D);\n * ```\n *\n * @group Loaders\n */\nexport async function loadSplatAsset(engine: SplatEngine, url: string, filename?: string): Promise<Splat> {\n if (engine.destroyed) throw new EngineDisposedError('loadSplatAsset');\n const source = await loadSplatSource(url, filename);\n // The fetch can outlive the engine, and everything below allocates GPU resources.\n if (engine.destroyed) throw new EngineDisposedError('loadSplatAsset');\n const splat = new Splat(engine, source);\n splat.object3D.name = (filename ?? fileNameOf(url)).replace(/\\.\\w+$/, '');\n return splat;\n}\n", "/**\n * The one interface every character-bundle version handler satisfies, and the\n * one error type they all fail with.\n *\n * This module is version-agnostic on purpose and holds no knowledge of any\n * particular version: it is the boundary that lets `index.ts` treat `v1/` and\n * `legacy/` as interchangeable, and the reason adding version N+1 costs exactly\n * one module and one registry entry\n * (character-bundle format spec, R2/R3).\n */\n\n/**\n * Error categories, from the spec's `Errors` table.\n *\n * A caller distinguishes \"not our file\" (`WrongMagic`) from \"our file, broken\"\n * (everything else) without parsing a message string.\n */\ntype BundleErrorCategory =\n | 'WrongMagic'\n | 'UnknownVersion'\n | 'Truncated'\n | 'MalformedHeader'\n | 'UnalignedPayload'\n | 'MissingField'\n | 'UnexpectedField'\n | 'BadFieldValue'\n | 'BlockSizeMismatch'\n | 'InconsistentHeader';\n\n/**\n * A rejection carrying its category.\n *\n * The category travels over the worker boundary alongside the message, so the\n * main thread can tell a foreign file from a corrupt one without re-reading the\n * bytes. The message names the offending block or field and reports the value\n * found next to the value expected.\n */\nclass CharacterBundleError extends Error {\n readonly category: BundleErrorCategory;\n\n constructor(category: BundleErrorCategory, message: string) {\n super(`[${category}] ${message}`);\n this.name = 'CharacterBundleError';\n this.category = category;\n }\n}\n\n/** The 14 Float32 attribute arrays the GPU pipeline consumes, one per column. */\ninterface SplatAttributes {\n x: Float32Array;\n y: Float32Array;\n z: Float32Array;\n scale_0: Float32Array;\n scale_1: Float32Array;\n scale_2: Float32Array;\n /** Quaternion `w`. The engine wants `wxyz`, whatever order the file stores. */\n rot_0: Float32Array;\n rot_1: Float32Array;\n rot_2: Float32Array;\n rot_3: Float32Array;\n f_dc_0: Float32Array;\n f_dc_1: Float32Array;\n f_dc_2: Float32Array;\n /** The LOGIT, not the alpha. */\n opacity: Float32Array;\n}\n\n/**\n * The version-independent decode output. Every handler returns this shape and a\n * caller cannot tell from it which handler ran.\n *\n * Three of these fields exist because the answer differs per version and the\n * QUESTION does not, so asking it downstream would put a per-version branch\n * outside the handlers - the one thing R2 forbids:\n *\n * - `rigBoneCount` - the legacy containers spell the rig's size three\n * different ways across two magics; version 1 has no header key for it at all\n * and derives it from `blocks.joints.count`.\n * - `corrected` - the legacy containers carry a correction receipt, in either\n * of two spellings, and files exist both with and without it. Version 1 needs\n * no receipt: the version itself means corrected, and the spec forbids a\n * reader from looking for a signal.\n * - `bundledRestIsPerCharacter` - whether `jointsArray` is this character's own\n * vetted rest pose, i.e. whether a consumer may pose the splats against it\n * instead of against the shared canonical tables.\n */\ninterface DecodedBundle {\n /** The version's own header, verbatim. Diagnostics; nothing dispatches on it. */\n header: unknown;\n numSplats: number;\n splats: SplatAttributes;\n /** `numSplats * K` global rig indices, or `null` when unskinned. */\n boneIndices: Uint16Array | null;\n /** `numSplats * K` weights, matching `boneIndices`, or `null`. */\n boneWeights: Float32Array | null;\n animationArray: Float32Array | null;\n animNumFrames: number;\n animNumBones: number;\n /** Flat `[x,y,z] * rigBoneCount` rest translations, or `null` when no rig. */\n jointsArray: Float32Array | null;\n /** Bones in the rig this bundle poses. `0` when it carries no rig. */\n rigBoneCount: number;\n /** Whether the geometric corrections are baked into the splats and joints. */\n corrected: boolean;\n /**\n * Whether `jointsArray` is this character's OWN rest pose, vetted against the\n * gaussians it ships with - i.e. whether posing the splats from it (rather\n * than from the shared canonical rest tables) is correct.\n *\n * A separate question from `corrected`, and deliberately not derived from it.\n * `corrected` answers \"did the correction pipeline run\", which some legacy\n * files answer yes to and others no, from the same generation of writer;\n * this one answers \"is the joints block authoritative\", which is a property\n * of the CONTAINER:\n *\n * - version 1 - yes, by definition. The joint canonicalisation, the ankle\n * pitch bake and the ground shift are all baked into the gaussians AND\n * into this block, so the two agree and nothing else does.\n * - legacy - no. Those joints were written for diagnostics, were never\n * vetted as a posing rest, and the shipped characters render today against\n * the canonical tables.\n *\n * Read by `Character`'s ground-convention shim, which must be able to tell\n * a v1 bundle from a legacy one WITHOUT keying on `corrected` - some legacy\n * bundles carry a receipt, and moving those would move already-shipped\n * characters. See `Character.bakedGroundShiftY`.\n */\n bundledRestIsPerCharacter: boolean;\n}\n\n/**\n * What a handler hands back: the bundle, plus the buffers the worker may\n * transfer instead of copying.\n */\ninterface DecodeResult {\n result: DecodedBundle;\n transferables: ArrayBuffer[];\n}\n\n/**\n * One payload version's reader.\n *\n * Given the whole file, the offset its payload begins at, and how long that\n * payload is. A handler is total over its own version, never learns that\n * another version exists, and never re-checks the magic or the version - the\n * dispatcher owns both.\n */\ntype VersionHandler = (\n file: ArrayBuffer,\n payloadOffset: number,\n payloadLength: number,\n) => Promise<DecodeResult>;\n\nexport { CharacterBundleError };\nexport type {\n BundleErrorCategory,\n DecodeResult,\n DecodedBundle,\n SplatAttributes,\n VersionHandler,\n};\n", "/**\n * Interleaved character-splat decoder - the payload half of `VFCHARB1`.\n *\n * MOVED, NOT REWRITTEN. This is `binary-gsplat-worker.ts`'s `parseBinaryGsplat`\n * verbatim, lifted out of the worker glue so the legacy readers sit behind one\n * door (`../index.ts`). It decodes files that are already in storage and will\n * stay there - there is no backfill - so any behaviour change here is a\n * regression, and it keeps its own vocabulary: this container talks about\n * CHUNKS, where the planar one talks about PLANES and `VIGGCHAR` talks about\n * BLOCKS.\n *\n * `version` here numbers one global bundle lineage across both legacy magics\n * (1 = fp32 interleaved, 2 = fp16 interleaved, 3 = planar), which is exactly the\n * accretion `VIGGCHAR` was shaped to end.\n */\n\n/** The interleaved container: per-splat records, v1 (fp32) and v2 (fp16). */\nconst CHARACTER_BUNDLE_MAGIC = 'VFCHARB1';\n\n/**\n * First `version` of the PLANAR container, which the interleaved reader below\n * must never attempt. `version` numbers one global bundle lineage across both\n * magics (1 = fp32 interleaved, 2 = fp16 interleaved, 3 = planar), so\n * `version >= 3` under the interleaved magic is a mislabelled file, not a\n * newer interleaved one - and `encoding.precision === 'fp16'` would happily\n * accept it and decode planes as records.\n */\nconst FIRST_PLANAR_VERSION = 3;\n\nconst SH_C0 = 0.28209479177387814;\n\ninterface BundleChunk {\n offset: number;\n length: number;\n stride?: number;\n}\n\ninterface AssetHeader {\n format: string;\n version: number;\n numSplats: number;\n numBones: number;\n bounds: { min: number[]; max: number[] };\n encoding?: {\n /**\n * Bundle-wide field precision. `'fp16'` means pos/scale/rot/opacity and\n * the weights chunk's per-splat weights are stored as IEEE 754 half-floats\n * (read 2 bytes / value, expanded to Float32 on parse). `'fp32'` or\n * missing = legacy raw float32 (the v1 layout). RGB stays uint8 and bone\n * indices stay uint16 either way. Bumps the file size by ~42%; expanding\n * to Float32 here means GPU memory is unchanged.\n */\n precision?: 'fp16' | 'fp32';\n weights?: { topK: number; indexType: string; weightType: string; stride: number };\n color?: { format: string; levels: number };\n };\n chunks: {\n splats: BundleChunk;\n weights?: BundleChunk;\n joints?: BundleChunk;\n animation?: BundleChunk;\n };\n animation?: {\n format: string;\n numFrames: number;\n numBones: number;\n shape: number[];\n stride: number;\n };\n joints?: {\n count: number;\n format: string;\n stride: number;\n };\n}\n\n// IEEE 754 half-float \u2192 single-float, branch-light. Used to expand the v2\n// quantized fields back into the Float32Arrays the GPU pipeline expects.\n// Subnormals are handled correctly (rare in our data - opacity 0 / unused\n// channels). Speed matters: this runs numSplats \u00D7 ~12 times per asset load.\nconst _f16Buf = new ArrayBuffer(4);\nconst _f16U32 = new Uint32Array(_f16Buf);\nconst _f16F32 = new Float32Array(_f16Buf);\nfunction f16ToF32(h: number): number {\n const sign = (h & 0x8000) << 16;\n const exp = (h & 0x7c00) >> 10;\n const frac = h & 0x03ff;\n let bits: number;\n if (exp === 0) {\n if (frac === 0) {\n bits = sign;\n } else {\n // Subnormal - normalize the mantissa into f32 representation.\n let e = -14;\n let m = frac;\n while ((m & 0x400) === 0) {\n m <<= 1;\n e--;\n }\n m &= 0x3ff;\n bits = sign | ((e + 127) << 23) | (m << 13);\n }\n } else if (exp === 31) {\n bits = sign | 0x7f800000 | (frac << 13);\n } else {\n bits = sign | ((exp - 15 + 127) << 23) | (frac << 13);\n }\n _f16U32[0] = bits;\n return _f16F32[0];\n}\n\nfunction parseBinaryGsplat(bundleBuffer: ArrayBuffer) {\n if (bundleBuffer.byteLength < 12) {\n throw new Error('Character bundle too small');\n }\n\n const bundleView = new DataView(bundleBuffer);\n const magic = new TextDecoder().decode(new Uint8Array(bundleBuffer, 0, CHARACTER_BUNDLE_MAGIC.length));\n if (magic !== CHARACTER_BUNDLE_MAGIC) {\n throw new Error(`Invalid character bundle magic: ${magic}`);\n }\n\n const headerLength = bundleView.getUint32(CHARACTER_BUNDLE_MAGIC.length, true);\n const headerStart = CHARACTER_BUNDLE_MAGIC.length + 4;\n const headerEnd = headerStart + headerLength;\n if (headerEnd > bundleBuffer.byteLength) {\n throw new Error('Character bundle header length out of range');\n }\n\n const headerText = new TextDecoder().decode(new Uint8Array(bundleBuffer, headerStart, headerLength));\n const header: AssetHeader = JSON.parse(headerText);\n if (header.format !== 'vfa3d-charbin') {\n throw new Error(`Unsupported character bundle format: ${header.format}`);\n }\n // Both `format` and `version` are checked, not just one: this reader used to\n // decide layout from `encoding.precision` alone, which cannot tell a planar\n // payload from an interleaved fp16 one. A file that gets this far is claiming\n // to be interleaved under two independent fields.\n if (header.version >= FIRST_PLANAR_VERSION) {\n throw new Error(\n `Character bundle declares version ${header.version} under the ${CHARACTER_BUNDLE_MAGIC} ` +\n 'magic; planar payloads must be published as VFCHARB2',\n );\n }\n\n const payloadStart = headerEnd;\n const chunkBuffer = (chunk: BundleChunk | undefined): ArrayBuffer | null => {\n if (!chunk) return null;\n const start = payloadStart + chunk.offset;\n const end = start + chunk.length;\n if (start < payloadStart || end > bundleBuffer.byteLength || start > end) {\n throw new Error('Character bundle chunk range out of bounds');\n }\n return bundleBuffer.slice(start, end);\n };\n\n const numSplats = header.numSplats;\n\n // Parse splats\n const splatsBuffer = chunkBuffer(header.chunks.splats);\n if (!splatsBuffer) throw new Error('Missing splats chunk');\n const splatData = new DataView(splatsBuffer);\n\n const storage_x = new Float32Array(numSplats);\n const storage_y = new Float32Array(numSplats);\n const storage_z = new Float32Array(numSplats);\n const storage_scale_0 = new Float32Array(numSplats);\n const storage_scale_1 = new Float32Array(numSplats);\n const storage_scale_2 = new Float32Array(numSplats);\n const storage_rot_0 = new Float32Array(numSplats);\n const storage_rot_1 = new Float32Array(numSplats);\n const storage_rot_2 = new Float32Array(numSplats);\n const storage_rot_3 = new Float32Array(numSplats);\n const storage_f_dc_0 = new Float32Array(numSplats);\n const storage_f_dc_1 = new Float32Array(numSplats);\n const storage_f_dc_2 = new Float32Array(numSplats);\n const storage_opacity = new Float32Array(numSplats);\n\n const isFp16 = header.encoding?.precision === 'fp16';\n let offset = 0;\n if (isFp16) {\n // v2 layout: pos/scale/rot/opacity stored as fp16. RGB+pad still 4B, no\n // padding after opacity. Per-splat stride = 6 + 6 + 8 + 4 + 2 = 26 B.\n for (let i = 0; i < numSplats; i++) {\n storage_x[i] = f16ToF32(splatData.getUint16(offset + 0, true));\n storage_y[i] = f16ToF32(splatData.getUint16(offset + 2, true));\n storage_z[i] = f16ToF32(splatData.getUint16(offset + 4, true));\n offset += 6;\n\n const scaleX = f16ToF32(splatData.getUint16(offset + 0, true));\n const scaleY = f16ToF32(splatData.getUint16(offset + 2, true));\n const scaleZ = f16ToF32(splatData.getUint16(offset + 4, true));\n storage_scale_0[i] = Math.log(Math.max(scaleX, 1e-8));\n storage_scale_1[i] = Math.log(Math.max(scaleY, 1e-8));\n storage_scale_2[i] = Math.log(Math.max(scaleZ, 1e-8));\n offset += 6;\n\n const qx = f16ToF32(splatData.getUint16(offset + 0, true));\n const qy = f16ToF32(splatData.getUint16(offset + 2, true));\n const qz = f16ToF32(splatData.getUint16(offset + 4, true));\n const qw = f16ToF32(splatData.getUint16(offset + 6, true));\n storage_rot_0[i] = qw;\n storage_rot_1[i] = qx;\n storage_rot_2[i] = qy;\n storage_rot_3[i] = qz;\n offset += 8;\n\n const r = splatData.getUint8(offset + 0);\n const g = splatData.getUint8(offset + 1);\n const b = splatData.getUint8(offset + 2);\n storage_f_dc_0[i] = (r / 255 - 0.5) / SH_C0;\n storage_f_dc_1[i] = (g / 255 - 0.5) / SH_C0;\n storage_f_dc_2[i] = (b / 255 - 0.5) / SH_C0;\n offset += 4;\n\n const opacity = f16ToF32(splatData.getUint16(offset + 0, true));\n const clampedOpacity = Math.max(0.0001, Math.min(0.9999, opacity));\n storage_opacity[i] = -Math.log(1 / clampedOpacity - 1);\n offset += 2;\n }\n } else {\n // v1 layout: all float32. Per-splat stride 48 B.\n for (let i = 0; i < numSplats; i++) {\n storage_x[i] = splatData.getFloat32(offset + 0, true);\n storage_y[i] = splatData.getFloat32(offset + 4, true);\n storage_z[i] = splatData.getFloat32(offset + 8, true);\n offset += 12;\n\n const scaleX = splatData.getFloat32(offset + 0, true);\n const scaleY = splatData.getFloat32(offset + 4, true);\n const scaleZ = splatData.getFloat32(offset + 8, true);\n storage_scale_0[i] = Math.log(Math.max(scaleX, 1e-8));\n storage_scale_1[i] = Math.log(Math.max(scaleY, 1e-8));\n storage_scale_2[i] = Math.log(Math.max(scaleZ, 1e-8));\n offset += 12;\n\n const qx = splatData.getFloat32(offset + 0, true);\n const qy = splatData.getFloat32(offset + 4, true);\n const qz = splatData.getFloat32(offset + 8, true);\n const qw = splatData.getFloat32(offset + 12, true);\n storage_rot_0[i] = qw;\n storage_rot_1[i] = qx;\n storage_rot_2[i] = qy;\n storage_rot_3[i] = qz;\n offset += 16;\n\n const r = splatData.getUint8(offset + 0);\n const g = splatData.getUint8(offset + 1);\n const b = splatData.getUint8(offset + 2);\n storage_f_dc_0[i] = (r / 255 - 0.5) / SH_C0;\n storage_f_dc_1[i] = (g / 255 - 0.5) / SH_C0;\n storage_f_dc_2[i] = (b / 255 - 0.5) / SH_C0;\n offset += 4;\n\n const opacity = splatData.getFloat32(offset + 0, true);\n const clampedOpacity = Math.max(0.0001, Math.min(0.9999, opacity));\n storage_opacity[i] = -Math.log(1 / clampedOpacity - 1);\n offset += 4;\n }\n }\n\n // Parse weights\n let boneIndices: Uint16Array | undefined;\n let boneWeights: Float32Array | undefined;\n const weightsBuffer = chunkBuffer(header.chunks.weights);\n if (weightsBuffer) {\n const topK = Math.max(1, header.encoding?.weights?.topK ?? 4);\n const indexBytes = 2;\n // v1 stores per-splat weights as float32; v2 stores them as fp16. Indices\n // stay uint16 either way (capacity for the 441-bone full rig).\n const weightBytes = isFp16 ? 2 : 4;\n const weightsData = new DataView(weightsBuffer);\n boneIndices = new Uint16Array(numSplats * topK);\n boneWeights = new Float32Array(numSplats * topK);\n let wOffset = 0;\n for (let i = 0; i < numSplats; i++) {\n for (let j = 0; j < topK; j++) {\n boneIndices[i * topK + j] = weightsData.getUint16(wOffset + j * 2, true);\n }\n wOffset += topK * indexBytes;\n if (isFp16) {\n for (let j = 0; j < topK; j++) {\n boneWeights[i * topK + j] = f16ToF32(weightsData.getUint16(wOffset + j * 2, true));\n }\n } else {\n for (let j = 0; j < topK; j++) {\n boneWeights[i * topK + j] = weightsData.getFloat32(wOffset + j * 4, true);\n }\n }\n wOffset += topK * weightBytes;\n }\n }\n\n // Parse animation\n let animationArray: Float32Array | undefined;\n let animNumFrames = 0;\n let animNumBones = 0;\n if (header.animation && header.animation.numFrames > 0 && header.animation.numBones > 0) {\n const animationBuffer = chunkBuffer(header.chunks.animation);\n if (animationBuffer) {\n const FLOATS_PER_BONE = 16;\n animNumBones = header.animation.numBones;\n animNumFrames = header.animation.numFrames;\n const expectedSize = animNumFrames * animNumBones * FLOATS_PER_BONE * 4;\n if (animationBuffer.byteLength !== expectedSize) {\n const actualBoneCount = animationBuffer.byteLength / 4 / (animNumFrames * FLOATS_PER_BONE);\n if (Number.isInteger(actualBoneCount) && actualBoneCount > 0) {\n animNumBones = actualBoneCount;\n }\n }\n animationArray = new Float32Array(animationBuffer);\n }\n }\n\n // Parse joints\n let jointsArray: Float32Array | undefined;\n if (header.joints) {\n const jointsBuffer = chunkBuffer(header.chunks.joints);\n if (jointsBuffer) {\n const FLOATS_PER_JOINT = 3;\n const expectedJointsSize = header.joints.count * FLOATS_PER_JOINT * 4;\n if (jointsBuffer.byteLength === expectedJointsSize) {\n jointsArray = new Float32Array(jointsBuffer);\n }\n }\n }\n\n // Collect all transferable buffers\n const transferables: ArrayBuffer[] = [\n storage_x.buffer as ArrayBuffer, storage_y.buffer as ArrayBuffer, storage_z.buffer as ArrayBuffer,\n storage_scale_0.buffer as ArrayBuffer, storage_scale_1.buffer as ArrayBuffer, storage_scale_2.buffer as ArrayBuffer,\n storage_rot_0.buffer as ArrayBuffer, storage_rot_1.buffer as ArrayBuffer, storage_rot_2.buffer as ArrayBuffer, storage_rot_3.buffer as ArrayBuffer,\n storage_f_dc_0.buffer as ArrayBuffer, storage_f_dc_1.buffer as ArrayBuffer, storage_f_dc_2.buffer as ArrayBuffer,\n storage_opacity.buffer as ArrayBuffer,\n ];\n if (boneIndices) transferables.push(boneIndices.buffer as ArrayBuffer);\n if (boneWeights) transferables.push(boneWeights.buffer as ArrayBuffer);\n if (animationArray) transferables.push(animationArray.buffer as ArrayBuffer);\n if (jointsArray) transferables.push(jointsArray.buffer as ArrayBuffer);\n\n const result = {\n header,\n numSplats,\n splats: {\n x: storage_x, y: storage_y, z: storage_z,\n scale_0: storage_scale_0, scale_1: storage_scale_1, scale_2: storage_scale_2,\n rot_0: storage_rot_0, rot_1: storage_rot_1, rot_2: storage_rot_2, rot_3: storage_rot_3,\n f_dc_0: storage_f_dc_0, f_dc_1: storage_f_dc_1, f_dc_2: storage_f_dc_2,\n opacity: storage_opacity,\n },\n boneIndices: boneIndices ?? null,\n boneWeights: boneWeights ?? null,\n animationArray: animationArray ?? null,\n animNumFrames,\n animNumBones,\n jointsArray: jointsArray ?? null,\n };\n\n return { result, transferables };\n}\n\nexport { parseBinaryGsplat, CHARACTER_BUNDLE_MAGIC };\n", "/**\n * Planar character-splat decoder - the payload half of `VFCHARB2`.\n *\n * A planar container stores one contiguous, component-major byte plane per\n * attribute (all x, then all y, then all z) instead of the per-splat records\n * `VFCHARB1` uses. Two precision modes share the one layout:\n *\n * `fp16` - the same half-float values the shipping v2 `VFCHARB1` bundle\n * carries, only re-laid-out. It decodes bit-identically to the v2\n * path, which is what makes it the control when judging q23.\n * `q23` - ~23 B/gaussian: u16 position against per-file bounds, u8 rotation\n * (w derived), u8 log-scale, u8 logit-opacity, u8 weights (the last\n * one derived), bone indices through a per-file palette.\n *\n * This module is deliberately free of Worker glue so it can be driven directly\n * (from `binary-gsplat-worker.ts`, and from a plain Node process when the\n * decode is being compared against the Python reference implementation).\n */\n\nconst SH_C0 = 0.28209479177387814;\n\n// Mirrors the decoder clamp in the interleaved path in binary-gsplat-worker.ts.\n// q23 opacity is already quantized inside this band by the encoder, so the\n// clamp costs nothing there.\nconst OPACITY_CLAMP_LO = 0.0001;\nconst OPACITY_CLAMP_HI = 0.9999;\nconst MIN_SCALE = 1e-8;\n\n/**\n * Magic -> the `format` string a file under that magic must declare.\n *\n * The MAGIC is the container generation and the one field this decoder refuses\n * to guess at: a planar payload published under `VFCHARB1` would sail past\n * every version check in the interleaved reader and decode to silent garbage.\n * `format` is then checked as well - dispatching on `version` alone is exactly\n * how a file can be misparsed without anything throwing.\n *\n * `VSPLAT01` is the pre-release prototype of the same layout. It is kept\n * readable so the `.vsplat` LOD/quantisation A/B rig keeps working, and because\n * routing it through this same decoder means the prototype exercises the\n * production code path rather than a copy of it.\n */\nconst PLANAR_CONTAINERS: Record<string, string> = {\n VFCHARB2: 'vfa3d-charb2',\n VSPLAT01: 'vsplat-planar',\n};\n\n/** First planar `version`. `1` = fp32 interleaved, `2` = fp16 interleaved. */\nconst FIRST_PLANAR_VERSION = 3;\n\ntype PlaneDtype = 'f32' | 'f16' | 'u16' | 'u8';\n\n/**\n * Per-plane compression codec, as written in the header.\n *\n * WHY DEFLATE AND NOT BROTLI OR ZSTD, which both compress ~10% better: these\n * three are the only formats `DecompressionStream` accepts, and the equivalents\n * (`GZipStream` / `DeflateStream`) are in the .NET base library, so a file with\n * compressed planes decodes on both targets with ZERO shipped decoder. Browsers\n * expose brotli and zstd only to the HTTP layer, never to script, so choosing\n * either would put a WASM decoder on the critical path of every character load.\n *\n * In-file compression is for platforms with no HTTP layer (Unity\n * StreamingAssets, AssetBundles, local files). On the web the file is served\n * flat with `Content-Encoding: br` instead, which is free and compresses\n * better. This decoder honours whichever the file declares.\n */\ntype PlaneCodec = 'gzip' | 'deflate' | 'deflate-raw';\n\nconst PLANE_CODECS: ReadonlySet<string> = new Set(['gzip', 'deflate', 'deflate-raw']);\n\ninterface PlaneInfo {\n offset: number;\n /** Bytes IN THE FILE - the compressed size when `compression` is set. */\n length: number;\n dtype: PlaneDtype;\n /** Values per splat. Stored COMPONENT-major: all c0, then all c1, ... */\n components: number;\n count: number;\n compression?: PlaneCodec;\n /** Bytes after inflation. Normative when `compression` is set. */\n uncompressedLength?: number;\n}\n\n/** A plane's bytes, wherever they ended up: in the file, or in an inflated copy. */\ninterface ResolvedPlane extends PlaneInfo {\n buf: ArrayBuffer;\n /** Byte offset of component 0 within `buf`. */\n base: number;\n}\n\ninterface PlanarHeader {\n format: string;\n version: number;\n precision: 'fp16' | 'q23';\n numSplats: number;\n numBones: number;\n topK: number;\n bounds: { min: number[]; max: number[] };\n /** q23 only - normative, positions cannot be reconstructed without them. */\n logScale?: { min: number[]; max: number[] };\n logitOpacity?: { min: number; max: number };\n bonePalette?: number[];\n joints?: { count: number };\n /** Free-form; informational. The plane table is what the decoder obeys. */\n encoding?: { planeCompression?: PlaneCodec | null };\n planes: Record<string, PlaneInfo>;\n}\n\nconst BYTES_PER_ELEMENT: Record<PlaneDtype, number> = { f32: 4, f16: 2, u16: 2, u8: 1 };\n\n// Float16Array landed in browsers only recently (Chrome 135+/Safari 26+), so\n// the manual expansion below stays as the fallback. Where it exists it is the\n// whole point of the planar layout: a component plane converts into its\n// Float32Array destination in one `set()` instead of a per-splat DataView walk.\nconst NativeFloat16Array = (globalThis as unknown as {\n Float16Array?: new (buffer: ArrayBuffer, byteOffset?: number, length?: number) => ArrayLike<number>;\n}).Float16Array;\n\n// IEEE 754 half-float -> single-float. Identical to the one in\n// binary-gsplat-worker.ts; the two decoders stay independent files so the\n// interleaved path has no import edge into the planar one.\nconst _f16Buf = new ArrayBuffer(4);\nconst _f16U32 = new Uint32Array(_f16Buf);\nconst _f16F32 = new Float32Array(_f16Buf);\nfunction f16ToF32(h: number): number {\n const sign = (h & 0x8000) << 16;\n const exp = (h & 0x7c00) >> 10;\n const frac = h & 0x03ff;\n let bits: number;\n if (exp === 0) {\n if (frac === 0) {\n bits = sign;\n } else {\n let e = -14;\n let m = frac;\n while ((m & 0x400) === 0) {\n m <<= 1;\n e--;\n }\n m &= 0x3ff;\n bits = sign | ((e + 127) << 23) | (m << 13);\n }\n } else if (exp === 31) {\n bits = sign | 0x7f800000 | (frac << 13);\n } else {\n bits = sign | ((exp - 15 + 127) << 23) | (frac << 13);\n }\n _f16U32[0] = bits;\n return _f16F32[0];\n}\n\n/** The 8-byte ASCII magic, or `''` when the buffer is too short to have one. */\nfunction readMagic(buffer: ArrayBuffer): string {\n if (buffer.byteLength < 12) return '';\n return new TextDecoder().decode(new Uint8Array(buffer, 0, 8));\n}\n\n/** True when `magic` names a planar container this module can decode. */\nfunction isPlanarMagic(magic: string): boolean {\n return Object.prototype.hasOwnProperty.call(PLANAR_CONTAINERS, magic);\n}\n\n/** Inflate one plane into its own exactly-sized ArrayBuffer. */\nasync function inflate(src: Uint8Array, codec: PlaneCodec): Promise<ArrayBuffer> {\n const stream = new Blob([src as unknown as BlobPart])\n .stream()\n .pipeThrough(new DecompressionStream(codec));\n return await new Response(stream).arrayBuffer();\n}\n\n/**\n * Resolve every plane to a buffer + offset, inflating the compressed ones.\n *\n * This is the whole cost of supporting compressed planes: a decompressed plane\n * lands at offset 0 of a fresh buffer (so every typed-array view below stays\n * aligned), an uncompressed one is still a view straight into the file with no\n * copy at all. Everything downstream reads `p.buf` / `p.base` and no longer\n * cares which mode the file was written in.\n */\nasync function resolvePlanes(\n buffer: ArrayBuffer,\n header: PlanarHeader,\n planeStart: number,\n): Promise<Record<string, ResolvedPlane>> {\n const out: Record<string, ResolvedPlane> = {};\n for (const [name, p] of Object.entries(header.planes)) {\n const start = planeStart + p.offset;\n if (start + p.length > buffer.byteLength) {\n throw new Error(`Planar plane out of bounds: ${name}`);\n }\n const expected = p.components * p.count * BYTES_PER_ELEMENT[p.dtype];\n if (p.compression) {\n if (!PLANE_CODECS.has(p.compression)) {\n throw new Error(`Planar plane ${name}: unsupported compression ${p.compression}`);\n }\n const buf = await inflate(new Uint8Array(buffer, start, p.length), p.compression);\n // The header's uncompressedLength is what a native decoder would have\n // used to size its destination, so a disagreement means the file lies\n // about itself - fail rather than render half a character.\n if (buf.byteLength !== (p.uncompressedLength ?? expected)) {\n throw new Error(\n `Planar plane ${name}: inflated to ${buf.byteLength} B, header says ` +\n `${p.uncompressedLength ?? expected} B`,\n );\n }\n if (buf.byteLength !== expected) {\n throw new Error(`Planar plane ${name}: ${buf.byteLength} B, expected ${expected} B`);\n }\n out[name] = { ...p, buf, base: 0 };\n } else {\n if (p.length !== expected) {\n throw new Error(`Planar plane ${name}: ${p.length} B, expected ${expected} B`);\n }\n out[name] = { ...p, buf: buffer, base: start };\n }\n }\n return out;\n}\n\n/**\n * Decode a planar character bundle into the Float32 arrays the GPU pipeline\n * expects, plus the skinning and joint data.\n *\n * Returns the same shape `parseBinaryGsplat` returns for the interleaved\n * container (minus the animation chunk, which planar files do not carry - clips\n * are registered separately), so both feed one `loadBinaryGsplat`.\n */\nasync function parsePlanarSplats(buffer: ArrayBuffer) {\n const magic = readMagic(buffer);\n const expectedFormat = PLANAR_CONTAINERS[magic];\n if (!expectedFormat) {\n throw new Error(`Invalid planar character bundle magic: ${magic}`);\n }\n\n const view = new DataView(buffer);\n const headerLength = view.getUint32(8, true);\n const headerStart = 12;\n const planeStart = headerStart + headerLength;\n if (planeStart > buffer.byteLength) throw new Error('Planar header length out of range');\n\n const header: PlanarHeader = JSON.parse(\n new TextDecoder().decode(new Uint8Array(buffer, headerStart, headerLength)),\n );\n if (header.format !== expectedFormat) {\n throw new Error(\n `Planar bundle ${magic} declares format '${header.format}', expected '${expectedFormat}'`,\n );\n }\n // The magic is the container generation, so a version below the planar line\n // under a planar magic means the file mislabels itself - the one thing this\n // reader must never shrug off. A LATER version is accepted: the format's own\n // rule is that a breaking layout change bumps the magic, not the version.\n if (!(header.version >= FIRST_PLANAR_VERSION)) {\n throw new Error(\n `Planar bundle ${magic} declares version ${header.version}, expected >= ${FIRST_PLANAR_VERSION}`,\n );\n }\n if (header.precision !== 'fp16' && header.precision !== 'q23') {\n throw new Error(`Unsupported planar precision: ${String(header.precision)}`);\n }\n if (!header.planes) throw new Error('Planar bundle has no plane table');\n // The encoder pads the header so the plane block is 4-byte aligned; without\n // that every typed-array view below would be a coin flip. (Inflated planes\n // start at offset 0 of their own buffer and are aligned for free.)\n if (planeStart % 4 !== 0) throw new Error('Planar plane block is not 4-byte aligned');\n\n const numSplats = header.numSplats;\n const topK = header.topK ?? 4;\n const isQ23 = header.precision === 'q23';\n\n const resolved = await resolvePlanes(buffer, header, planeStart);\n\n const plane = (name: string): ResolvedPlane => {\n const p = resolved[name];\n if (!p) throw new Error(`Planar bundle missing plane: ${name}`);\n return p;\n };\n\n const componentOffset = (p: ResolvedPlane, c: number): number =>\n p.base + c * p.count * BYTES_PER_ELEMENT[p.dtype];\n\n /** Expand one f16 component plane into `out`, natively where possible. */\n const readF16 = (p: ResolvedPlane, c: number, out: Float32Array): Float32Array => {\n const off = componentOffset(p, c);\n if (NativeFloat16Array) {\n out.set(new NativeFloat16Array(p.buf, off, p.count) as unknown as ArrayLike<number>);\n return out;\n }\n const dv = new DataView(p.buf, off, p.count * 2);\n for (let i = 0; i < p.count; i++) out[i] = f16ToF32(dv.getUint16(i * 2, true));\n return out;\n };\n\n const readU8 = (p: ResolvedPlane, c: number) => new Uint8Array(p.buf, componentOffset(p, c), p.count);\n const readU16 = (p: ResolvedPlane, c: number) => new Uint16Array(p.buf, componentOffset(p, c), p.count);\n const readUint = (p: ResolvedPlane, c: number): Uint8Array | Uint16Array =>\n p.dtype === 'u8' ? readU8(p, c) : readU16(p, c);\n\n const storage_x = new Float32Array(numSplats);\n const storage_y = new Float32Array(numSplats);\n const storage_z = new Float32Array(numSplats);\n const storage_scale_0 = new Float32Array(numSplats);\n const storage_scale_1 = new Float32Array(numSplats);\n const storage_scale_2 = new Float32Array(numSplats);\n const storage_rot_0 = new Float32Array(numSplats);\n const storage_rot_1 = new Float32Array(numSplats);\n const storage_rot_2 = new Float32Array(numSplats);\n const storage_rot_3 = new Float32Array(numSplats);\n const storage_f_dc_0 = new Float32Array(numSplats);\n const storage_f_dc_1 = new Float32Array(numSplats);\n const storage_f_dc_2 = new Float32Array(numSplats);\n const storage_opacity = new Float32Array(numSplats);\n\n const posPlane = plane('position');\n const scalePlane = plane('scale');\n const rotPlane = plane('rotation');\n const colorPlane = plane('color');\n const opacityPlane = plane('opacity');\n\n // \u2500\u2500 position \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const posOut = [storage_x, storage_y, storage_z];\n if (isQ23) {\n const bmin = header.bounds.min;\n const bmax = header.bounds.max;\n for (let c = 0; c < 3; c++) {\n const q = readU16(posPlane, c);\n const lo = bmin[c];\n const step = (bmax[c] - lo) / 65535;\n const out = posOut[c];\n for (let i = 0; i < numSplats; i++) out[i] = lo + q[i] * step;\n }\n } else {\n for (let c = 0; c < 3; c++) readF16(posPlane, c, posOut[c]);\n }\n\n // \u2500\u2500 scale \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // The engine consumes LOG scale. q23 already stores log scale, so its decode\n // is a multiply-add; fp16 stores the linear value the v2 .bin stores and pays\n // the same log() the v2 path pays.\n const scaleOut = [storage_scale_0, storage_scale_1, storage_scale_2];\n if (isQ23) {\n const lsMin = header.logScale!.min;\n const lsMax = header.logScale!.max;\n for (let c = 0; c < 3; c++) {\n const q = readU8(scalePlane, c);\n const lo = lsMin[c];\n const step = (lsMax[c] - lo) / 255;\n const out = scaleOut[c];\n for (let i = 0; i < numSplats; i++) out[i] = lo + q[i] * step;\n }\n } else {\n for (let c = 0; c < 3; c++) {\n const out = readF16(scalePlane, c, scaleOut[c]);\n for (let i = 0; i < numSplats; i++) out[i] = Math.log(Math.max(out[i], MIN_SCALE));\n }\n }\n\n // \u2500\u2500 rotation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Stored xyzw; the engine wants wxyz (rot_0 = w).\n if (isQ23) {\n const qx = readU8(rotPlane, 0);\n const qy = readU8(rotPlane, 1);\n const qz = readU8(rotPlane, 2);\n for (let i = 0; i < numSplats; i++) {\n const x = (qx[i] / 255) * 2 - 1;\n const y = (qy[i] / 255) * 2 - 1;\n const z = (qz[i] / 255) * 2 - 1;\n // The encoder forced w >= 0, which is what makes this branch valid.\n storage_rot_0[i] = Math.sqrt(Math.max(0, 1 - x * x - y * y - z * z));\n storage_rot_1[i] = x;\n storage_rot_2[i] = y;\n storage_rot_3[i] = z;\n }\n } else {\n readF16(rotPlane, 0, storage_rot_1);\n readF16(rotPlane, 1, storage_rot_2);\n readF16(rotPlane, 2, storage_rot_3);\n readF16(rotPlane, 3, storage_rot_0);\n }\n\n // \u2500\u2500 colour \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const dcOut = [storage_f_dc_0, storage_f_dc_1, storage_f_dc_2];\n for (let c = 0; c < 3; c++) {\n const src = readU8(colorPlane, c);\n const out = dcOut[c];\n for (let i = 0; i < numSplats; i++) out[i] = (src[i] / 255 - 0.5) / SH_C0;\n }\n\n // \u2500\u2500 opacity \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // The engine consumes the LOGIT. Same trade as scale: q23 stores it already\n // in logit space, fp16 stores the post-sigmoid value the v2 .bin stores.\n if (isQ23) {\n const lo = header.logitOpacity!.min;\n const step = (header.logitOpacity!.max - lo) / 255;\n const q = readU8(opacityPlane, 0);\n for (let i = 0; i < numSplats; i++) storage_opacity[i] = lo + q[i] * step;\n } else {\n readF16(opacityPlane, 0, storage_opacity);\n for (let i = 0; i < numSplats; i++) {\n const a = Math.max(OPACITY_CLAMP_LO, Math.min(OPACITY_CLAMP_HI, storage_opacity[i]));\n storage_opacity[i] = -Math.log(1 / a - 1);\n }\n }\n\n // \u2500\u2500 skinning \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let boneIndices: Uint16Array | undefined;\n let boneWeights: Float32Array | undefined;\n if (header.planes.boneIndex && header.planes.boneWeight) {\n const idxPlane = plane('boneIndex');\n const wPlane = plane('boneWeight');\n boneIndices = new Uint16Array(numSplats * topK);\n boneWeights = new Float32Array(numSplats * topK);\n\n // q23 indexes a per-file palette so the plane can be a byte wide; the\n // encoder widens it to u16 when a character touches more than 256 bones,\n // which the plane dtype records.\n const palette = header.bonePalette;\n for (let j = 0; j < topK; j++) {\n const src = readUint(idxPlane, j);\n if (palette) {\n for (let i = 0; i < numSplats; i++) boneIndices[i * topK + j] = palette[src[i]];\n } else {\n for (let i = 0; i < numSplats; i++) boneIndices[i * topK + j] = src[i];\n }\n }\n\n if (isQ23) {\n // Slots 0..2 are stored; the last one is whatever is left, which is what\n // makes the decoded quartet sum to exactly 1.\n const scratch = new Float32Array(numSplats);\n for (let j = 0; j < wPlane.components; j++) {\n const src = readU8(wPlane, j);\n for (let i = 0; i < numSplats; i++) {\n const w = src[i] / 255;\n boneWeights[i * topK + j] = w;\n scratch[i] += w;\n }\n }\n for (let i = 0; i < numSplats; i++) {\n boneWeights[i * topK + (topK - 1)] = Math.max(0, 1 - scratch[i]);\n }\n } else {\n const col = new Float32Array(numSplats);\n for (let j = 0; j < topK; j++) {\n readF16(wPlane, j, col);\n for (let i = 0; i < numSplats; i++) boneWeights[i * topK + j] = col[i];\n }\n }\n }\n\n // \u2500\u2500 joints \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Component-major like every other plane, unlike the interleaved container's\n // joints chunk, which is float3 records.\n let jointsArray: Float32Array | undefined;\n if (header.planes.joints) {\n const jp = plane('joints');\n jointsArray = new Float32Array(jp.count * 3);\n for (let c = 0; c < 3; c++) {\n const src = new Float32Array(jp.buf, componentOffset(jp, c), jp.count);\n for (let i = 0; i < jp.count; i++) jointsArray[i * 3 + c] = src[i];\n }\n }\n\n const transferables: ArrayBuffer[] = [\n storage_x.buffer as ArrayBuffer, storage_y.buffer as ArrayBuffer, storage_z.buffer as ArrayBuffer,\n storage_scale_0.buffer as ArrayBuffer, storage_scale_1.buffer as ArrayBuffer, storage_scale_2.buffer as ArrayBuffer,\n storage_rot_0.buffer as ArrayBuffer, storage_rot_1.buffer as ArrayBuffer, storage_rot_2.buffer as ArrayBuffer, storage_rot_3.buffer as ArrayBuffer,\n storage_f_dc_0.buffer as ArrayBuffer, storage_f_dc_1.buffer as ArrayBuffer, storage_f_dc_2.buffer as ArrayBuffer,\n storage_opacity.buffer as ArrayBuffer,\n ];\n if (boneIndices) transferables.push(boneIndices.buffer as ArrayBuffer);\n if (boneWeights) transferables.push(boneWeights.buffer as ArrayBuffer);\n if (jointsArray) transferables.push(jointsArray.buffer as ArrayBuffer);\n\n const result = {\n header,\n numSplats,\n splats: {\n x: storage_x, y: storage_y, z: storage_z,\n scale_0: storage_scale_0, scale_1: storage_scale_1, scale_2: storage_scale_2,\n rot_0: storage_rot_0, rot_1: storage_rot_1, rot_2: storage_rot_2, rot_3: storage_rot_3,\n f_dc_0: storage_f_dc_0, f_dc_1: storage_f_dc_1, f_dc_2: storage_f_dc_2,\n opacity: storage_opacity,\n },\n boneIndices: boneIndices ?? null,\n boneWeights: boneWeights ?? null,\n // Planar files carry no animation chunk; the fields exist so both\n // containers hand `loadBinaryGsplat` the same shape.\n animationArray: null as Float32Array | null,\n animNumFrames: 0,\n animNumBones: 0,\n jointsArray: jointsArray ?? null,\n nativeFloat16: !!NativeFloat16Array,\n planeCompression: header.encoding?.planeCompression ?? null,\n };\n\n return { result, transferables };\n}\n\nexport { parsePlanarSplats, readMagic, isPlanarMagic, PLANAR_CONTAINERS, FIRST_PLANAR_VERSION };\nexport type { PlanarHeader, PlaneInfo, PlaneCodec, PlaneDtype };\n", "/**\n * The legacy door.\n *\n * Everything whose first 8 bytes are not `VIGGCHAR` arrives here, and nothing\n * else does. Behind it are the two container generations that shipped before\n * the format was respecified:\n *\n * `VFCHARB1` -> interleaved per-splat records (v1 fp32, v2 fp16)\n * `VFCHARB2` -> planar byte planes (v3; fp16 or q23 precision)\n * `VSPLAT01` -> the pre-release prototype of the planar layout\n *\n * These readers are PERMANENT, not migration scaffolding. Files already in\n * storage keep their old magic forever - there is no backfill - so this module\n * is kept indefinitely and its decoders are moved, never improved. What it is\n * NOT is entangled: it is one branch of one top-level `if`, it imports nothing\n * from `../v1/`, and `../v1/` imports nothing from it.\n *\n * These containers spell `version` as one global lineage across two magics,\n * which is precisely the accretion `VIGGCHAR` exists to end. Nothing about that\n * lineage leaks past this file: the dispatcher upstream never reads it, and the\n * bundle handed back is the same version-independent shape `v1/` returns.\n */\n\nimport { CharacterBundleError } from '../types';\nimport type { DecodeResult, DecodedBundle } from '../types';\nimport { CHARACTER_BUNDLE_MAGIC, parseBinaryGsplat } from './interleaved-splat';\nimport { isPlanarMagic, parsePlanarSplats, readMagic } from './planar-splat';\n\n/** The header keys the legacy rules below read; the rest is diagnostics. */\ntype LegacyHeader = {\n corrections?: unknown;\n ankleCorrection?: unknown;\n joints?: { count: number };\n skeleton?: { count: number };\n} | null | undefined;\n\n/**\n * Did this bundle go through the character-correction pipeline?\n *\n * A LEGACY question with a legacy answer. The old writers agree on the meaning\n * and disagree on the spelling, so both are accepted:\n *\n * - `corrections` - the production encoder, which stamps this header ONLY\n * when the corrections ran. That makes presence an exact test: with the\n * corrections switched off the encoder is byte-identical to its\n * pre-correction self, receipt included.\n * - `ankleCorrection` - the offline authoring writer, which writes the ankle\n * block at the top level and no `corrections` key at all.\n *\n * `groundOffset` and `visibleBounds` are deliberately NOT accepted: the writer\n * emits them unconditionally, so they say \"written recently\", not \"corrected\".\n *\n * Two spellings for one fact is exactly how a gate like this rots, and it is\n * why `VIGGCHAR` version 1 carries no receipt at all - the version means\n * corrected, so there is no question left to ask. Nothing here is shared with\n * that path; a receipt is a property of these containers only.\n */\nfunction hasCorrectionReceipt(header: unknown): boolean {\n const h = header as LegacyHeader;\n return h?.corrections != null || h?.ankleCorrection != null;\n}\n\n/**\n * How many bones the rig this bundle poses has, by the legacy rules.\n *\n * Three header keys can answer, in a fixed order of trust, and `0` means the\n * bundle carries no rig. This is lifted verbatim out of `binary-gsplat.ts`,\n * where it used to run downstream of the worker on a header only these\n * containers produce; it belongs to them, so it moved in with them.\n */\nfunction legacyRigBoneCount(header: unknown, animNumFrames: number, animNumBones: number): number {\n const h = header as LegacyHeader;\n if (!h?.joints && !h?.skeleton) return 0;\n let numBones = animNumFrames > 0 && animNumBones > 0 ? animNumBones : 0;\n if (numBones === 0 && h.skeleton) numBones = h.skeleton.count;\n if (numBones === 0 && h.joints) numBones = h.joints.count;\n return numBones > 0 ? numBones : 0;\n}\n\n/**\n * Decode a bundle in one of the pre-`VIGGCHAR` containers.\n *\n * The container is identified by SNIFFING THE 8-BYTE MAGIC and never by the\n * filename or a header key - both generations arrive through the same URLs,\n * with no out-of-band type information, so the bytes are the only honest\n * answer. Anything this door does not recognise throws with the magic it\n * actually found.\n */\nasync function decodeLegacyBundle(file: ArrayBuffer): Promise<DecodeResult> {\n if (file.byteLength < 12) {\n throw new CharacterBundleError(\n 'WrongMagic',\n `character bundle is ${file.byteLength} B, too small to carry a magic`,\n );\n }\n const magic = readMagic(file);\n\n let decoded: Awaited<ReturnType<typeof parsePlanarSplats>> | ReturnType<typeof parseBinaryGsplat>;\n if (isPlanarMagic(magic)) {\n decoded = await parsePlanarSplats(file);\n } else if (magic === CHARACTER_BUNDLE_MAGIC) {\n decoded = parseBinaryGsplat(file);\n } else {\n throw new CharacterBundleError(\n 'WrongMagic',\n `unrecognised character bundle magic '${magic}'`,\n );\n }\n\n const { result, transferables } = decoded;\n // The decoders above are untouched, so the two version-independent answers\n // are computed here from what they returned. Cast because the legacy planar\n // reader also carries `nativeFloat16` / `planeCompression` diagnostics on the\n // worker message, which predate this interface and are kept for the A/B rig.\n const bundle: DecodedBundle = {\n ...result,\n rigBoneCount: legacyRigBoneCount(result.header, result.animNumFrames, result.animNumBones),\n corrected: hasCorrectionReceipt(result.header),\n // Never. A legacy joints block is diagnostics: it was not vetted as a\n // posing rest, and every shipped legacy character renders against the\n // canonical tables. Independent of the receipt above on purpose.\n bundledRestIsPerCharacter: false,\n } as DecodedBundle;\n\n return { result: bundle, transferables };\n}\n\nexport { decodeLegacyBundle };\n", "/**\n * `VIGGCHAR` version 1 - the quantised block payload.\n *\n * Written from the character-bundle format spec and from nothing else.\n * A JSON header with exactly two keys, `numSplats` and `blocks`, followed by\n * the blocks it lists. Each block holds one attribute for every gaussian,\n * stored component-major, and each block's entry carries everything needed to\n * decode THAT block - its dequantisation bounds, its palette. There is no\n * top-level decoding parameter and no file-wide precision mode.\n *\n * This handler is total over version 1 and knows that no other version exists.\n * It never re-checks the magic or the version: the dispatcher owns both.\n *\n * Vocabulary note: this format says BLOCKS. The legacy containers next door say\n * planes and chunks. The difference is deliberate - a block is self-describing\n * in a way a plane was not, and keeping the words apart keeps the two readers\n * from being read as one.\n */\n\nimport { CharacterBundleError } from '../types';\nimport type { DecodeResult, DecodedBundle } from '../types';\n\n/** Spherical-harmonic DC coefficient. A constant of version 1. */\nconst SH_C0 = 0.28209479177387814;\n\n/** Position quantisation levels: stored values run `0..65535`. */\nconst POSITION_LEVELS = 65536;\n\n/** Scale and opacity quantisation levels: stored values run `0..255`. */\nconst BYTE_LEVELS = 256;\n\ntype BlockDtype = 'f32' | 'u16' | 'u8';\n\nconst BYTES_PER_ELEMENT: Record<BlockDtype, number> = { f32: 4, u16: 2, u8: 1 };\n\n/** The five keys required on every block entry. */\nconst COMMON_KEYS = ['offset', 'length', 'dtype', 'components', 'count'] as const;\n\n/**\n * Every block this version defines, with the shape its entry must declare.\n *\n * `components: null` means \"whatever the entry says\" - `boneIndex` carries `K`\n * and `boneWeight` carries `K - 1`, and `K` is per-file. A block name that is\n * not in here is ignored: the manifest is what the file contains, and a name\n * this version does not define contributes nothing to the decode.\n */\nconst BLOCK_SHAPES: Record<string, { dtypes: BlockDtype[]; components: number | null }> = {\n position: { dtypes: ['u16'], components: 3 },\n scale: { dtypes: ['u8'], components: 3 },\n rotation: { dtypes: ['u8'], components: 3 },\n color: { dtypes: ['u8'], components: 3 },\n opacity: { dtypes: ['u8'], components: 1 },\n boneIndex: { dtypes: ['u8', 'u16'], components: null },\n boneWeight: { dtypes: ['u8'], components: null },\n joints: { dtypes: ['f32'], components: 3 },\n};\n\n/** The five blocks every conforming file carries. A missing one is rejected by name. */\nconst UNCONDITIONAL_BLOCKS = ['position', 'scale', 'rotation', 'color', 'opacity'] as const;\n\n/**\n * The blocks quantised against a range measured from this file's data.\n *\n * These and only these carry `min` / `max`. `rotation`, `boneWeight` and\n * `color` do not, because their range is a property of their type rather than\n * of this character, and there is nothing per-file to record.\n */\nconst BOUNDED_BLOCKS = ['position', 'scale', 'opacity'] as const;\n\ninterface BlockEntry {\n offset: number;\n /** Bytes in the file, and the only length a block has. */\n length: number;\n dtype: BlockDtype;\n /** Values per row, stored component-major: all c0, then all c1, ... */\n components: number;\n count: number;\n /** Per-component dequantisation bounds. Present on `BOUNDED_BLOCKS` only. */\n min?: number[];\n max?: number[];\n /** Stored index -> global rig bone index. Present on `boneIndex` only. */\n palette?: number[];\n}\n\ninterface V1Header {\n numSplats: number;\n blocks: Record<string, BlockEntry>;\n}\n\n/** A block entry with its bytes located: `base` is where component 0 begins. */\ninterface ResolvedBlock extends BlockEntry {\n /** Absolute byte offset of component 0 in the file: `blockStart + offset`. */\n base: number;\n}\n\n// A `function` declaration rather than a `const` arrow, deliberately: TypeScript\n// only narrows control flow through a never-returning call when the callee is a\n// function declaration or an explicitly-annotated variable. As a `const` arrow\n// this returned `never` and still left every `if (x === undefined) fail(...)`\n// guard invisible to the compiler, so the code after it saw `x` as possibly\n// undefined even though the guard had already thrown.\nfunction fail(\n category: ConstructorParameters<typeof CharacterBundleError>[0],\n message: string,\n): never {\n throw new CharacterBundleError(category, message);\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\nconst isUint = (v: unknown): v is number =>\n typeof v === 'number' && Number.isInteger(v) && v >= 0;\n\n/**\n * Check the five common keys and the arithmetic that ties them together.\n *\n * Everything here is a property of ONE block entry, which is the point: no\n * check reaches into a sibling key, so a block decodes from its own entry plus\n * the constants of this version.\n */\nfunction validateCommonKeys(name: string, entry: unknown, blockStart: number, totalLength: number) {\n if (!isPlainObject(entry)) {\n fail('BadFieldValue', `block '${name}': entry is ${JSON.stringify(entry)}, expected an object`);\n }\n const e = entry as Record<string, unknown>;\n for (const key of COMMON_KEYS) {\n if (e[key] === undefined || e[key] === null) {\n fail('MissingField', `block '${name}': missing required key '${key}'`);\n }\n }\n for (const key of ['offset', 'length', 'components', 'count'] as const) {\n if (!isUint(e[key])) {\n fail('BadFieldValue', `block '${name}': '${key}' is ${JSON.stringify(e[key])}, expected a non-negative integer`);\n }\n }\n if (!Object.prototype.hasOwnProperty.call(BYTES_PER_ELEMENT, e.dtype as string)) {\n fail(\n 'BadFieldValue',\n `block '${name}': dtype ${JSON.stringify(e.dtype)}, expected one of ${Object.keys(BYTES_PER_ELEMENT).join(', ')}`,\n );\n }\n\n const p = e as unknown as BlockEntry;\n // A u16 or f32 block at an odd offset otherwise fails deep inside the decode,\n // where the cause is no longer visible.\n if (p.offset % 4 !== 0) {\n fail('UnalignedPayload', `block '${name}': offset ${p.offset} is not a multiple of 4`);\n }\n const end = blockStart + p.offset + p.length;\n if (end > totalLength) {\n fail(\n 'Truncated',\n `block '${name}': bytes [${blockStart + p.offset}, ${end}) run past the file's ${totalLength} B`,\n );\n }\n // The block's bytes are the decoded bytes, so its stored length is the size\n // its own shape asks for. A disagreement is the file describing itself wrong,\n // and it is caught here rather than as a short read deep inside the decode.\n const decoded = p.components * p.count * BYTES_PER_ELEMENT[p.dtype];\n if (p.length !== decoded) {\n fail(\n 'BlockSizeMismatch',\n `block '${name}': length ${p.length} B, but ` +\n `${p.components} components x ${p.count} rows x ${BYTES_PER_ELEMENT[p.dtype]} B (${p.dtype}) = ${decoded} B`,\n );\n }\n}\n\n/**\n * Check the manifest as a whole: which blocks are present, and what their\n * entries must then say about each other.\n *\n * The block table is the ONE place this reader learns what the file contains.\n * Nothing below probes the payload, guesses from a size, or reads meaning into\n * a block's absence beyond the presence rules the spec states outright.\n */\nfunction validateManifest(header: V1Header, blocks: Record<string, BlockEntry>) {\n for (const name of UNCONDITIONAL_BLOCKS) {\n if (!blocks[name]) fail('MissingField', `manifest is missing the required block '${name}'`);\n }\n\n for (const [name, p] of Object.entries(blocks)) {\n const shape = BLOCK_SHAPES[name];\n if (!shape) continue;\n if (!shape.dtypes.includes(p.dtype)) {\n fail(\n 'InconsistentHeader',\n `block '${name}': dtype '${p.dtype}', expected ${shape.dtypes.map((d) => `'${d}'`).join(' or ')}`,\n );\n }\n if (shape.components !== null && p.components !== shape.components) {\n fail(\n 'InconsistentHeader',\n `block '${name}': ${p.components} components, expected exactly ${shape.components}`,\n );\n }\n if (name !== 'joints' && p.count !== header.numSplats) {\n fail(\n 'InconsistentHeader',\n `block '${name}': count ${p.count}, expected numSplats ${header.numSplats}`,\n );\n }\n }\n\n // Checked before anything reads the rig's size: an empty rig is not a rig,\n // and a `joints.count` of 0 would otherwise surface as every palette entry\n // being out of range.\n if (blocks.joints && blocks.joints.count === 0) {\n fail('UnexpectedField', `block 'joints': count 0, and an empty rig is not a rig`);\n }\n\n // Bounds live in the entry of the block they decode, and nowhere else. A\n // block that carries them where it should not is as wrong as one that omits\n // them: both mean a decoder cannot tell from an entry how to read it.\n for (const [name, p] of Object.entries(blocks)) {\n if (!BLOCK_SHAPES[name]) continue;\n const bounded = (BOUNDED_BLOCKS as readonly string[]).includes(name);\n for (const key of ['min', 'max'] as const) {\n const v = p[key];\n if (!bounded) {\n if (v !== undefined) {\n fail('UnexpectedField', `block '${name}': carries '${key}', but its range is fixed by its type`);\n }\n continue;\n }\n if (v === undefined) {\n fail('MissingField', `block '${name}': missing dequantisation bound '${key}'`);\n }\n if (!Array.isArray(v) || v.length !== p.components || !v.every((n) => typeof n === 'number' && Number.isFinite(n))) {\n fail(\n 'BadFieldValue',\n `block '${name}': '${key}' is ${JSON.stringify(v)}, expected an array of ${p.components} finite numbers`,\n );\n }\n }\n if (bounded) {\n for (let c = 0; c < p.components; c++) {\n if (p.max![c] < p.min![c]) {\n fail(\n 'BadFieldValue',\n `block '${name}': component ${c} has max ${p.max![c]} below min ${p.min![c]}, an inverted span`,\n );\n }\n }\n }\n if (name !== 'boneIndex' && p.palette !== undefined) {\n fail('UnexpectedField', `block '${name}': carries a 'palette', which only 'boneIndex' takes`);\n }\n }\n\n // Skinning is one fact in two blocks. A bundle with one of them has no\n // defined meaning, so neither half is guessed at from the other's absence.\n const hasIndex = !!blocks.boneIndex;\n const hasWeight = !!blocks.boneWeight;\n if (hasIndex && !hasWeight) {\n fail('MissingField', `manifest has 'boneIndex' but not 'boneWeight'; skinning needs both`);\n }\n if (hasWeight && !hasIndex) {\n fail('UnexpectedField', `manifest has 'boneWeight' but not 'boneIndex'; skinning needs both`);\n }\n if (hasIndex) {\n const idx = blocks.boneIndex;\n const w = blocks.boneWeight;\n if (w.components !== idx.components - 1) {\n fail(\n 'InconsistentHeader',\n `block 'boneWeight': ${w.components} components, expected boneIndex.components - 1 = ${idx.components - 1}`,\n );\n }\n if (idx.palette === undefined) {\n fail('MissingField', `block 'boneIndex': missing 'palette'`);\n }\n if (!Array.isArray(idx.palette) || !idx.palette.every(isUint)) {\n fail(\n 'BadFieldValue',\n `block 'boneIndex': 'palette' is ${JSON.stringify(idx.palette)?.slice(0, 80)}, expected an array of rig indices`,\n );\n }\n // A palette entry is a global rig index, so the rig - when the file carries\n // one - is what says which indices exist.\n const rigBones = blocks.joints?.count;\n if (rigBones !== undefined) {\n for (let i = 0; i < idx.palette.length; i++) {\n if (idx.palette[i] >= rigBones) {\n fail(\n 'InconsistentHeader',\n `block 'boneIndex': palette[${i}] is ${idx.palette[i]}, outside the ${rigBones}-bone rig`,\n );\n }\n }\n }\n }\n\n}\n\n/**\n * Locate every block: `base` is where its component 0 begins in the file.\n *\n * A block is read in place - no copy at all. `blockStart` and every `offset`\n * are multiples of 4, so every typed-array view below is aligned by the\n * layout's own rules and nothing has to be moved to make it so.\n */\nfunction resolveBlocks(\n blocks: Record<string, BlockEntry>,\n blockStart: number,\n): Record<string, ResolvedBlock> {\n const out: Record<string, ResolvedBlock> = {};\n for (const [name, p] of Object.entries(blocks)) {\n if (!BLOCK_SHAPES[name]) continue;\n out[name] = { ...p, base: blockStart + p.offset };\n }\n return out;\n}\n\n/**\n * Decode a `VIGGCHAR` version 1 payload.\n *\n * Version 1 means CORRECTED: the ankle pitch bake and then the ground shift are\n * already in the gaussians and in the `joints` block, and the character stands\n * on `y = 0` by construction. There is no in-file signal about that and nothing\n * below looks for one - the version answered it.\n *\n * The decode is straight-line and never yields; it is declared `async` only\n * because `VersionHandler` is promise-shaped for the handlers that must be.\n */\nasync function decodeV1(\n file: ArrayBuffer,\n payloadOffset: number,\n payloadLength: number,\n): Promise<DecodeResult> {\n const totalLength = payloadOffset + payloadLength;\n\n if (payloadLength < 4) {\n fail('Truncated', `payload is ${payloadLength} B, too small to carry a header length`);\n }\n const headerLength = new DataView(file).getUint32(payloadOffset, true);\n const headerStart = payloadOffset + 4;\n const blockStart = headerStart + headerLength;\n if (blockStart > totalLength) {\n fail(\n 'Truncated',\n `header claims ${headerLength} B, which ends at ${blockStart}, past the file's ${totalLength} B`,\n );\n }\n // The writer pads the JSON with spaces until this holds. Block offsets are\n // relative to `blockStart`, so a misaligned base makes every typed-array view\n // in the payload invalid - and a `u16` block would fail far from the cause.\n if (headerLength % 4 !== 0) {\n fail('UnalignedPayload', `headerLength ${headerLength} is not a multiple of 4`);\n }\n\n let header: V1Header;\n try {\n const text = new TextDecoder('utf-8', { fatal: true }).decode(\n new Uint8Array(file, headerStart, headerLength),\n );\n header = JSON.parse(text);\n } catch (err) {\n return fail('MalformedHeader', `header is not valid UTF-8 JSON (${(err as Error)?.message ?? String(err)})`);\n }\n if (!isPlainObject(header)) {\n return fail('MalformedHeader', `header is ${JSON.stringify(header)}, expected a JSON object`);\n }\n\n if (header.numSplats === undefined || header.numSplats === null) {\n fail('MissingField', `header is missing 'numSplats'`);\n }\n if (!isUint(header.numSplats)) {\n fail('BadFieldValue', `header 'numSplats' is ${JSON.stringify(header.numSplats)}, expected a non-negative integer`);\n }\n if (header.blocks === undefined || header.blocks === null) {\n fail('MissingField', `header is missing 'blocks', the block table`);\n }\n if (!isPlainObject(header.blocks)) {\n fail('BadFieldValue', `header 'blocks' is ${JSON.stringify(header.blocks)}, expected an object`);\n }\n\n const numSplats = header.numSplats;\n // A name this version does not define contributes nothing to the decode, so\n // it is ignored whole rather than validated against rules written for other\n // blocks. Everything past this point works from `blocks`.\n const blocks: Record<string, BlockEntry> = {};\n for (const [name, entry] of Object.entries(header.blocks)) {\n if (!BLOCK_SHAPES[name]) continue;\n validateCommonKeys(name, entry, blockStart, totalLength);\n blocks[name] = entry as BlockEntry;\n }\n validateManifest(header, blocks);\n\n const resolved = resolveBlocks(blocks, blockStart);\n const block = (name: string): ResolvedBlock => resolved[name];\n\n const componentOffset = (p: ResolvedBlock, c: number): number =>\n p.base + c * p.count * BYTES_PER_ELEMENT[p.dtype];\n\n const readU8 = (p: ResolvedBlock, c: number) => new Uint8Array(file, componentOffset(p, c), p.count);\n const readU16 = (p: ResolvedBlock, c: number) => new Uint16Array(file, componentOffset(p, c), p.count);\n const readUint = (p: ResolvedBlock, c: number): Uint8Array | Uint16Array =>\n p.dtype === 'u8' ? readU8(p, c) : readU16(p, c);\n\n const storage_x = new Float32Array(numSplats);\n const storage_y = new Float32Array(numSplats);\n const storage_z = new Float32Array(numSplats);\n const storage_scale_0 = new Float32Array(numSplats);\n const storage_scale_1 = new Float32Array(numSplats);\n const storage_scale_2 = new Float32Array(numSplats);\n const storage_rot_0 = new Float32Array(numSplats);\n const storage_rot_1 = new Float32Array(numSplats);\n const storage_rot_2 = new Float32Array(numSplats);\n const storage_rot_3 = new Float32Array(numSplats);\n const storage_f_dc_0 = new Float32Array(numSplats);\n const storage_f_dc_1 = new Float32Array(numSplats);\n const storage_f_dc_2 = new Float32Array(numSplats);\n const storage_opacity = new Float32Array(numSplats);\n\n // \u2500\u2500 position, scale, opacity \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // One decode, `min[c] + q * (max[c] - min[c]) / (levels - 1)`, over the\n // component index of whichever block is being read. Nothing distinguishes\n // the single-component block from the three-component ones, which is why\n // opacity's bounds are one-element arrays like everybody else's.\n const dequantise = (p: ResolvedBlock, levels: number, out: Float32Array[]) => {\n for (let c = 0; c < out.length; c++) {\n const q = levels === POSITION_LEVELS ? readU16(p, c) : readU8(p, c);\n const lo = p.min![c];\n const step = (p.max![c] - lo) / (levels - 1);\n const dst = out[c];\n for (let i = 0; i < numSplats; i++) dst[i] = lo + q[i] * step;\n }\n };\n\n dequantise(block('position'), POSITION_LEVELS, [storage_x, storage_y, storage_z]);\n // Log-space per-axis standard deviations, which is the space the engine\n // consumes, so the decode is a multiply-add and nothing pays a `log` per\n // gaussian.\n dequantise(block('scale'), BYTE_LEVELS, [storage_scale_0, storage_scale_1, storage_scale_2]);\n // The LOGIT, not an alpha. Same trade as scale.\n dequantise(block('opacity'), BYTE_LEVELS, [storage_opacity]);\n\n // \u2500\u2500 rotation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Three components, not four: the writer negated any quaternion with w < 0\n // before quantising, which is what makes w recoverable from xyz. Stored\n // xyzw; the engine wants wxyz, so rot_0 is w.\n {\n const p = block('rotation');\n const qx = readU8(p, 0);\n const qy = readU8(p, 1);\n const qz = readU8(p, 2);\n for (let i = 0; i < numSplats; i++) {\n const x = (qx[i] / 255) * 2 - 1;\n const y = (qy[i] / 255) * 2 - 1;\n const z = (qz[i] / 255) * 2 - 1;\n storage_rot_0[i] = Math.sqrt(Math.max(0, 1 - x * x - y * y - z * z));\n storage_rot_1[i] = x;\n storage_rot_2[i] = y;\n storage_rot_3[i] = z;\n }\n }\n\n // \u2500\u2500 colour \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // The spherical-harmonic DC term. There is no higher band; characters are\n // lit flat.\n {\n const p = block('color');\n const dcOut = [storage_f_dc_0, storage_f_dc_1, storage_f_dc_2];\n for (let c = 0; c < 3; c++) {\n const src = readU8(p, c);\n const dst = dcOut[c];\n for (let i = 0; i < numSplats; i++) dst[i] = (src[i] / 255 - 0.5) / SH_C0;\n }\n }\n\n // \u2500\u2500 skinning \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let boneIndices: Uint16Array | undefined;\n let boneWeights: Float32Array | undefined;\n if (resolved.boneIndex) {\n const idxBlock = block('boneIndex');\n const wBlock = block('boneWeight');\n const palette = idxBlock.palette!;\n const K = idxBlock.components;\n boneIndices = new Uint16Array(numSplats * K);\n boneWeights = new Float32Array(numSplats * K);\n\n // The palette is what lets a narrow character on a 441-bone rig store its\n // indices in a byte. It is required even when it is the identity mapping,\n // so there is only ever one index space to read.\n for (let j = 0; j < K; j++) {\n const src = readUint(idxBlock, j);\n for (let i = 0; i < numSplats; i++) {\n const q = src[i];\n if (q >= palette.length) {\n fail(\n 'InconsistentHeader',\n `block 'boneIndex': gaussian ${i} slot ${j} stores index ${q}, ` +\n `outside its ${palette.length}-entry palette`,\n );\n }\n boneIndices[i * K + j] = palette[q];\n }\n }\n\n // K - 1 slots are stored; the last is whatever is left, which is what makes\n // the decoded influences sum to exactly 1. The writer allocated the K byte\n // weights by largest remainder so they total 255, so summing the BYTES and\n // dividing once evaluates `1 - sum(q / 255)` with no rounding drift.\n const stored = new Uint32Array(numSplats);\n for (let j = 0; j < wBlock.components; j++) {\n const src = readU8(wBlock, j);\n for (let i = 0; i < numSplats; i++) {\n boneWeights[i * K + j] = src[i] / 255;\n stored[i] += src[i];\n }\n }\n for (let i = 0; i < numSplats; i++) {\n boneWeights[i * K + (K - 1)] = Math.max(0, 255 - stored[i]) / 255;\n }\n }\n\n // \u2500\u2500 joints \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Rest positions only - no rotations, no names, no hierarchy. Row i is the\n // rest position of global rig bone i, the same index space a decoded\n // `boneIndex` lands in. Component-major like every other block.\n let jointsArray: Float32Array | undefined;\n let rigBoneCount = 0;\n if (resolved.joints) {\n const p = block('joints');\n rigBoneCount = p.count;\n jointsArray = new Float32Array(p.count * 3);\n for (let c = 0; c < 3; c++) {\n const src = new Float32Array(file, componentOffset(p, c), p.count);\n for (let i = 0; i < p.count; i++) jointsArray[i * 3 + c] = src[i];\n }\n }\n\n const transferables: ArrayBuffer[] = [\n storage_x.buffer as ArrayBuffer, storage_y.buffer as ArrayBuffer, storage_z.buffer as ArrayBuffer,\n storage_scale_0.buffer as ArrayBuffer, storage_scale_1.buffer as ArrayBuffer, storage_scale_2.buffer as ArrayBuffer,\n storage_rot_0.buffer as ArrayBuffer, storage_rot_1.buffer as ArrayBuffer, storage_rot_2.buffer as ArrayBuffer, storage_rot_3.buffer as ArrayBuffer,\n storage_f_dc_0.buffer as ArrayBuffer, storage_f_dc_1.buffer as ArrayBuffer, storage_f_dc_2.buffer as ArrayBuffer,\n storage_opacity.buffer as ArrayBuffer,\n ];\n if (boneIndices) transferables.push(boneIndices.buffer as ArrayBuffer);\n if (boneWeights) transferables.push(boneWeights.buffer as ArrayBuffer);\n if (jointsArray) transferables.push(jointsArray.buffer as ArrayBuffer);\n\n const result: DecodedBundle = {\n header,\n numSplats,\n splats: {\n x: storage_x, y: storage_y, z: storage_z,\n scale_0: storage_scale_0, scale_1: storage_scale_1, scale_2: storage_scale_2,\n rot_0: storage_rot_0, rot_1: storage_rot_1, rot_2: storage_rot_2, rot_3: storage_rot_3,\n f_dc_0: storage_f_dc_0, f_dc_1: storage_f_dc_1, f_dc_2: storage_f_dc_2,\n opacity: storage_opacity,\n },\n boneIndices: boneIndices ?? null,\n boneWeights: boneWeights ?? null,\n // This format carries no animation. Clips are separate files, registered\n // separately; the fields exist so every version hands back one shape.\n animationArray: null,\n animNumFrames: 0,\n animNumBones: 0,\n jointsArray: jointsArray ?? null,\n rigBoneCount,\n // Version 1 means corrected. There is no field to read and no receipt to\n // find, and a reader is forbidden from looking for one.\n corrected: true,\n // Always. The corrections are baked into the gaussians AND into the joints\n // block, so this rest is the character's own and the two agree.\n bundledRestIsPerCharacter: true,\n };\n\n return { result, transferables };\n}\n\nexport { decodeV1 };\n", "/**\n * Character-bundle reader: the dispatch table and the public entry point.\n *\n * ONE top-level branch, and legacy behind one door:\n *\n * magic == VIGGCHAR -> look `version` up in VERSION_HANDLERS\n * otherwise -> legacy/\n *\n * That is the whole structure, and it is the point of it: adding version N+1\n * costs one module under `vN/` and one line in the table below, and removing a\n * version costs deleting exactly those two things. If a change to support a new\n * version has to touch an existing handler, the decomposition is not real.\n * (Character-bundle format spec, \"Reader architecture\", R1-R5.)\n *\n * The only bytes read before dispatch are the 16 container bytes. Nothing here\n * sniffs the payload, peeks at the header, tries a parse, or consults the\n * filename, the extension, the URL or the MIME type - the `.vsplat` extension\n * is advisory and says nothing this reader may act on.\n */\n\nimport { CharacterBundleError } from './types';\nimport type { DecodeResult, VersionHandler } from './types';\nimport { decodeLegacyBundle } from './legacy';\nimport { decodeV1 } from './v1/decode';\n\n/**\n * The format tag, compared as 8 bytes and never decoded as an integer.\n *\n * Loading it as one or two integers would make the comparison depend on byte\n * order, and a magic whose numeric spelling differs per platform is a magic\n * that fails on one of them.\n */\nconst VIGGCHAR_MAGIC = new Uint8Array([0x56, 0x49, 0x47, 0x47, 0x43, 0x48, 0x41, 0x52]); // 'VIGGCHAR'\n\n/** Bytes of container: `magic` (8) + `version` (4) + `totalLength` (4). */\nconst CONTAINER_BYTES = 16;\n\n/**\n * The dispatch table: payload version -> the one handler that decodes it.\n *\n * A SET of versions, not a range. There is no ordering relation here - a\n * higher version is not \"newer and probably compatible\", it is unknown, and\n * unknown is a hard failure.\n */\nconst VERSION_HANDLERS: ReadonlyMap<number, VersionHandler> = new Map([\n [1, decodeV1],\n]);\n\n/** True when the first 8 bytes are exactly `VIGGCHAR`. */\nfunction hasViggcharMagic(file: ArrayBuffer): boolean {\n if (file.byteLength < VIGGCHAR_MAGIC.length) return false;\n const bytes = new Uint8Array(file, 0, VIGGCHAR_MAGIC.length);\n for (let i = 0; i < VIGGCHAR_MAGIC.length; i++) {\n if (bytes[i] !== VIGGCHAR_MAGIC[i]) return false;\n }\n return true;\n}\n\n/**\n * Read a character bundle of any container this reader implements.\n *\n * @param file - the whole file as a read-only byte buffer.\n * @returns the decoded bundle in the version-independent output type, plus the\n * buffers a worker may transfer rather than copy. A caller cannot tell from the\n * result which handler ran.\n * @throws {CharacterBundleError} carrying the spec's error category.\n */\nasync function parseCharacterBundle(file: ArrayBuffer): Promise<DecodeResult> {\n // Not our file. A caller may reasonably try another format - which is why\n // this is the one branch that leaves, rather than rejecting outright.\n if (!hasViggcharMagic(file)) {\n return await decodeLegacyBundle(file);\n }\n\n if (file.byteLength < CONTAINER_BYTES) {\n throw new CharacterBundleError(\n 'Truncated',\n `file is ${file.byteLength} B, shorter than the ${CONTAINER_BYTES} B container`,\n );\n }\n\n const view = new DataView(file);\n const version = view.getUint32(8, true);\n const handler = VERSION_HANDLERS.get(version);\n if (!handler) {\n // No fallback, no \"probably compatible\", no speculative parse, no partial\n // decode. The supported set is reported so the caller knows what to do.\n throw new CharacterBundleError(\n 'UnknownVersion',\n `file declares version ${version}; this reader implements ` +\n `${[...VERSION_HANDLERS.keys()].sort((a, b) => a - b).join(', ')}`,\n );\n }\n\n // Carried rather than taken from the transport: a truncated download or a\n // clipped upload otherwise arrives with an intact header and a short last\n // block, and surfaces as a broken character instead of an error. Trailing\n // bytes beyond it are ignored, so the container can be embedded in a larger\n // stream.\n const totalLength = view.getUint32(12, true);\n if (totalLength < CONTAINER_BYTES) {\n throw new CharacterBundleError(\n 'Truncated',\n `header declares totalLength ${totalLength} B, below the ${CONTAINER_BYTES} B container`,\n );\n }\n if (file.byteLength < totalLength) {\n throw new CharacterBundleError(\n 'Truncated',\n `header declares totalLength ${totalLength} B, but the file is ${file.byteLength} B`,\n );\n }\n\n return await handler(file, CONTAINER_BYTES, totalLength - CONTAINER_BYTES);\n}\n\nexport { parseCharacterBundle, CharacterBundleError };\nexport type { DecodeResult };\n", "import { packSplats } from '../../splat/packed-splats';\nimport { pruneSplats } from '../../splat/prune';\nimport type { SplatSource } from '../../splat/splat';\nimport type { ArmatureData, SplatWeights } from '../../types';\nimport { sharedDecode } from '../shared/asset-loader';\nimport { cachedFetch } from '../shared/bin-cache';\n\nimport { parseCharacterBundle } from './index';\n\n/** A clip embedded in a legacy character bundle: per-frame, per-bone 4x4 matrices. */\nexport interface RawAnimationData {\n data: Float32Array;\n numFrames: number;\n numBones: number;\n keyframeFrames?: number[];\n}\n\n/** A decoded character bundle, ready to become a {@link Splat} and an {@link Armature}. */\nexport interface CharacterBundle {\n source: SplatSource;\n armatureData?: ArmatureData;\n animationData?: RawAnimationData;\n}\n\n// Raw bytes by URL (query string dropped, so a re-signed URL still hits). Lets\n// a second character from the same file skip the network; each load still\n// decodes its own copy because splats own and mutate their buffers. Capped at\n// 96 MB, least recently used out first, as in the PlayCanvas build, so\n// browsing many characters doesn't pin every bundle for the session; an\n// evicted bundle comes back from the persistent Cache API tier.\nconst MAX_BUFFER_CACHE_BYTES = 96 * 1024 * 1024;\nconst _bufferCache = new Map<string, ArrayBuffer>();\nconst _bufferLoading = new Map<string, Promise<ArrayBuffer>>();\nlet _bufferCacheBytes = 0;\n\nfunction setCachedBuffer(key: string, buf: ArrayBuffer): void {\n const existing = _bufferCache.get(key);\n if (existing) _bufferCacheBytes -= existing.byteLength;\n _bufferCache.delete(key);\n _bufferCache.set(key, buf);\n _bufferCacheBytes += buf.byteLength;\n // Map iteration is insertion order: the first entries are the least\n // recently used. The newest entry stays even if it alone is over budget.\n for (const [k, b] of _bufferCache) {\n if (_bufferCacheBytes <= MAX_BUFFER_CACHE_BYTES || k === key) break;\n _bufferCache.delete(k);\n _bufferCacheBytes -= b.byteLength;\n }\n}\n\nfunction cacheKeyFor(url: string): string {\n const q = url.indexOf('?');\n return q === -1 ? url : url.slice(0, q);\n}\n\nasync function fetchBundleBuffer(url: string): Promise<ArrayBuffer> {\n const key = cacheKeyFor(url);\n const cached = _bufferCache.get(key);\n if (cached) {\n // Refresh its place so the budget evicts the least recently used.\n _bufferCache.delete(key);\n _bufferCache.set(key, cached);\n return cached;\n }\n const inflight = _bufferLoading.get(key);\n if (inflight) return inflight;\n const promise = cachedFetch(url)\n .then(async (res) => {\n if (!res.ok) throw new Error(`[loadCharacterBundle] fetch failed (${res.status}): ${url}`);\n const buf = await res.arrayBuffer();\n setCachedBuffer(key, buf);\n return buf;\n })\n .finally(() => {\n _bufferLoading.delete(key);\n });\n _bufferLoading.set(key, promise);\n return promise;\n}\n\n/**\n * Decode a character bundle held in memory.\n *\n * Accepts every container the reader implements - `VIGGCHAR` (`.vsplat`) and\n * the legacy `.bin` layouts - and dispatches on the file's own magic, never on\n * a filename.\n *\n * Decoding runs on the calling thread. A bundle is a few megabytes and decodes\n * in single-digit milliseconds, which does not earn the packaging cost of a\n * separate worker file.\n *\n * @throws {CharacterBundleError} carrying the format spec's error category.\n */\nexport async function decodeCharacterBundle(file: ArrayBuffer): Promise<CharacterBundle> {\n const { result } = await parseCharacterBundle(file);\n\n let armatureData: ArmatureData | undefined;\n if (result.rigBoneCount > 0) {\n armatureData = { numBones: result.rigBoneCount };\n if (result.jointsArray) {\n armatureData.joints = result.jointsArray;\n armatureData.corrected = result.corrected;\n armatureData.restIsPerCharacter = result.bundledRestIsPerCharacter;\n }\n }\n\n let animationData: RawAnimationData | undefined;\n if (result.animationArray && result.animNumFrames > 0 && result.animNumBones > 0) {\n animationData = {\n data: result.animationArray,\n numFrames: result.animNumFrames,\n numBones: result.animNumBones,\n };\n }\n\n const header = result.header as { numBones?: number } | null | undefined;\n\n // Quality-driven splat removal, before anything is packed into texels: a\n // dropped splat then costs nothing anywhere downstream. Off by default, in\n // which case this returns the decode's own count having touched nothing.\n const decodedWeights: SplatWeights | undefined =\n result.boneIndices && result.boneWeights\n ? { indices: result.boneIndices, weights: result.boneWeights }\n : undefined;\n const { numSplatsOut, weights: splatWeights } = pruneSplats(\n result.numSplats,\n result.splats,\n decodedWeights,\n );\n\n return {\n source: {\n packed: packSplats(numSplatsOut, result.splats),\n splatWeights,\n sourceBoneCount: header?.numBones ?? armatureData?.numBones,\n },\n armatureData,\n animationData,\n };\n}\n\n/**\n * Fetch and decode a character bundle. With `setShareSplatResources(true)`,\n * characters loaded from one URL share the decode.\n */\nexport async function loadCharacterBundle(url: string): Promise<CharacterBundle> {\n return sharedDecode('character', url, async () => decodeCharacterBundle(await fetchBundleBuffer(url)));\n}\n\n/** Start downloading a character bundle; a later {@link loadCharacterBundle} reuses the bytes. */\nexport function prefetchCharacterBundle(url: string): void {\n fetchBundleBuffer(url).catch(() => {});\n}\n\n/** Decode a character bundle from bytes already in memory. */\nexport async function loadCharacterBundleFromBytes(bytes: Uint8Array): Promise<CharacterBundle> {\n // The decoders build aligned typed-array views straight onto the buffer, so\n // a view that starts mid-buffer has to be copied out first.\n const aligned =\n bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength\n ? (bytes.buffer as ArrayBuffer)\n : (bytes.slice().buffer as ArrayBuffer);\n return decodeCharacterBundle(aligned);\n}\n", "/**\n * Bone-mask utilities for layered animation. A {@link BoneMask} selects a\n * subset of an armature's bones by index; the {@link Armature} layer system\n * uses it to gate an overlay animation to (e.g.) just the upper body while a\n * base full-body clip drives the rest.\n *\n * Built-in regions ({@link UPPER_BODY_BONE_NAMES} / {@link LOWER_BODY_BONE_NAMES})\n * follow the canonical 86-bone rig naming. The split bone is the pelvis:\n * - UPPER covers everything from `spine_01` up (spine 01-05, neck, head,\n * clavicles, arms, hands, all fingers) so the overlay fully replaces\n * the torso without leak from the base's spine rotation.\n * - LOWER covers `pelvis` plus the leg chain (thighs, calves, calf\n * twists, feet, ball, all toes). Including pelvis means an overlay's\n * pelvis Y motion drives the rig and routes through `rootMotionMode`,\n * so the lower-body overlay owns root motion when active.\n *\n * @group Characters & Animation\n */\n\nexport const UPPER_BODY_BONE_NAMES = [\n 'spine_01', 'spine_02', 'spine_03', 'spine_04', 'spine_05',\n 'neck_01', 'neck_02',\n 'head',\n 'clavicle_l', 'clavicle_r',\n 'upperarm_l', 'upperarm_r',\n 'lowerarm_l', 'lowerarm_r',\n 'hand_l', 'hand_r',\n // Fingers - so the overlay fully owns hand pose.\n 'thumb_01_l', 'thumb_02_l', 'thumb_03_l',\n 'index_metacarpal_l', 'index_01_l', 'index_02_l', 'index_03_l',\n 'middle_metacarpal_l', 'middle_01_l', 'middle_02_l', 'middle_03_l',\n 'ring_metacarpal_l', 'ring_01_l', 'ring_02_l', 'ring_03_l',\n 'pinky_metacarpal_l', 'pinky_01_l', 'pinky_02_l', 'pinky_03_l',\n 'thumb_01_r', 'thumb_02_r', 'thumb_03_r',\n 'index_metacarpal_r', 'index_01_r', 'index_02_r', 'index_03_r',\n 'middle_metacarpal_r', 'middle_01_r', 'middle_02_r', 'middle_03_r',\n 'ring_metacarpal_r', 'ring_01_r', 'ring_02_r', 'ring_03_r',\n 'pinky_metacarpal_r', 'pinky_01_r', 'pinky_02_r', 'pinky_03_r',\n] as const;\n\nexport const LOWER_BODY_BONE_NAMES = [\n 'pelvis',\n 'thigh_l', 'thigh_r',\n 'calf_l', 'calf_r',\n 'calf_twist_01_l', 'calf_twist_01_r',\n 'foot_l', 'foot_r',\n 'ball_l', 'ball_r',\n 'bigtoe_01_l', 'bigtoe_02_l',\n 'indextoe_01_l', 'indextoe_02_l',\n 'middletoe_01_l', 'middletoe_02_l',\n 'ringtoe_01_l', 'ringtoe_02_l',\n 'littletoe_01_l', 'littletoe_02_l',\n 'bigtoe_01_r', 'bigtoe_02_r',\n 'indextoe_01_r', 'indextoe_02_r',\n 'middletoe_01_r', 'middletoe_02_r',\n 'ringtoe_01_r', 'ringtoe_02_r',\n 'littletoe_01_r', 'littletoe_02_r',\n] as const;\n\nexport interface BoneMask {\n name: string;\n boneIndices: Int32Array;\n}\n\nexport function resolveBoneIndices(\n allBoneNames: readonly string[],\n maskNames: readonly string[],\n): Int32Array {\n const out: number[] = [];\n for (const n of maskNames) {\n const i = allBoneNames.indexOf(n);\n if (i >= 0) out.push(i);\n }\n return Int32Array.from(out);\n}\n\nexport type BodyRegion = 'upperBody' | 'lowerBody';\n\nexport function makeRegionMask(\n region: BodyRegion,\n allBoneNames: readonly string[],\n): BoneMask {\n const names = region === 'upperBody' ? UPPER_BODY_BONE_NAMES : LOWER_BODY_BONE_NAMES;\n return { name: region, boneIndices: resolveBoneIndices(allBoneNames, names) };\n}\n", "import { FileLoader, Loader } from 'three';\nimport type { LoadingManager } from 'three';\n\nimport { Animation } from '../animation';\nimport { SplatEngine } from '../engine';\nimport { decodeCharacterBundle } from '../loader/character/load';\nimport { parseGaussianPly } from '../loader/environment/ply';\nimport { packSplats } from '../splat/packed-splats';\nimport { Splat } from '../splat/splat';\nimport type { SplatMesh } from '../splat/splat-mesh';\n\nimport { SplatCharacter } from './splat-character';\n\nconst GLB_MAGIC = 0x46546c67; // 'glTF'\n\n/** File name without directory, query string or extension. */\nfunction baseName(url: string): string {\n const file = url.split(/[?#]/)[0].split('/').pop() ?? '';\n return file.replace(/\\.\\w+$/, '');\n}\n\n/**\n * Shared plumbing: fetch bytes the three.js way - through a `FileLoader`, so\n * the `LoadingManager`, base path, request headers and credentials mode all\n * apply - then hand them to an asynchronous `parseAsync`.\n */\nabstract class SplatLoaderBase<T> extends Loader<T> {\n /**\n * The engine loaded objects belong to: the skeleton library, clip registry\n * and lights they share. Leave unset to use {@link SplatEngine.shared}.\n */\n engine: SplatEngine | null = null;\n\n constructor(manager?: LoadingManager) {\n super(manager);\n }\n\n setEngine(engine: SplatEngine | null): this {\n this.engine = engine;\n return this;\n }\n\n /** Decode bytes already in memory. `name` labels the result; for a loaded file it is the file's base name. */\n abstract parseAsync(data: ArrayBuffer, name?: string): Promise<T>;\n\n override load(\n url: string,\n onLoad: (result: T) => void,\n onProgress?: (event: ProgressEvent) => void,\n onError?: (error: unknown) => void,\n ): void {\n const loader = new FileLoader(this.manager);\n loader.setPath(this.path);\n loader.setResponseType('arraybuffer');\n loader.setRequestHeader(this.requestHeader);\n loader.setWithCredentials(this.withCredentials);\n loader.load(\n url,\n (data) => {\n this.parseAsync(data as ArrayBuffer, baseName(url)).then(onLoad, (error) => {\n if (onError) onError(error);\n else console.error(error);\n this.manager.itemError(url);\n });\n },\n onProgress,\n onError,\n );\n }\n\n protected get resolvedEngine(): SplatEngine {\n return this.engine ?? SplatEngine.shared;\n }\n}\n\n/**\n * Loads a `.vsplat` character bundle (or a legacy `.bin` one - the container\n * is recognised from the file's own bytes) as a {@link SplatCharacter}.\n *\n * ```ts\n * const character = await new VSplatLoader().loadAsync('/assets/hero.vsplat');\n * scene.add(character);\n * ```\n *\n * @group Loaders\n */\nexport class VSplatLoader extends SplatLoaderBase<SplatCharacter> {\n override async parseAsync(data: ArrayBuffer, name = 'character'): Promise<SplatCharacter> {\n const bundle = await decodeCharacterBundle(data);\n return new SplatCharacter(this.resolvedEngine, [bundle], name);\n }\n}\n\n/**\n * Loads an animation clip for {@link SplatCharacter.play}: a MetaHuman-rig\n * `.glb`, or an `.anim` file.\n *\n * ```ts\n * const run = await new SplatClipLoader().loadAsync('/assets/run.glb');\n * character.play(run);\n * ```\n *\n * A clip is not tied to one character; play the same one on as many as you like.\n *\n * @group Loaders\n */\nexport class SplatClipLoader extends SplatLoaderBase<Animation> {\n /** For a `.glb` holding several animations, the one to take. Default: the first. */\n animationName: string | undefined;\n\n override async parseAsync(data: ArrayBuffer, name = ''): Promise<Animation> {\n const isGlb = data.byteLength >= 4 && new DataView(data).getUint32(0, true) === GLB_MAGIC;\n const clip = isGlb ? Animation.parseGlb(data, this.animationName) : Animation.parse(data);\n if (!clip.name) clip.name = name;\n return clip;\n }\n}\n\n/**\n * Loads an uncompressed 3D Gaussian Splatting `.ply` as a static\n * {@link SplatMesh} - an environment, a prop, a scanned object.\n *\n * ```ts\n * const room = await new SplatPLYLoader().loadAsync('/assets/room.ply');\n * room.rotation.x = Math.PI; // many captures are authored Y-down\n * scene.add(room);\n * ```\n *\n * The mesh is given `renderOrder = -1` so it draws before characters, which\n * then always composite on top of it. Splats do not write depth, so without\n * that a large environment whose origin happens to be nearer the camera would\n * be drawn over a character standing in it.\n *\n * @group Loaders\n */\nexport class SplatPLYLoader extends SplatLoaderBase<SplatMesh> {\n override async parseAsync(data: ArrayBuffer, name = 'splat'): Promise<SplatMesh> {\n const { numSplats, splats } = parseGaussianPly(data);\n // No quality prune here, deliberately. The two load-time knobs\n // (SplatQuality.minOpacity, pruneRatio) are character settings in the\n // Unity build this port takes them from - it applies them in the skinned\n // renderer and nowhere else - and a splat scene is a different\n // distribution: measured on the test capture, minOpacity 0.05 removes 8.7%\n // of a character and 41.8% of a 1M-splat room, because a scene trained\n // without constraints is full of faint splats that are nonetheless what\n // the soft parts of it are made of. `pruneSplats` is exported for an\n // application that wants to make that trade on a scene of its own.\n const splat = new Splat(this.resolvedEngine, { packed: packSplats(numSplats, splats) });\n const mesh = splat.object3D;\n mesh.name = name;\n mesh.renderOrder = -1;\n return mesh;\n }\n}\n", "import { AmbientLight, Color, PerspectiveCamera, SRGBColorSpace, Scene as ThreeScene, Vector3, WebGLRenderer } from 'three';\n\nimport { CameraFrame } from './effects/postfx/camera-frame';\nimport { PostFX } from './effects/postfx/postfx';\nimport { EngineDisposedError, SplatEngine } from './engine';\nimport { PhysicsWorld } from './physics/physics-world';\n\n/**\n * Graphics backend preference for {@link CreateSceneOptions.backend}.\n *\n * @group Scene\n */\nexport type RenderBackend = 'webgl' | 'webgpu';\n\n/**\n * Options for {@link Scene.create}. Named and defaulted as in the PlayCanvas\n * build's `Scene.create`, so a game's options carry over.\n *\n * @group Scene\n */\nexport interface CreateSceneOptions {\n /** Clear colour as normalized floats (0\u20131). Default `{r: 0.08, g: 0.08, b: 0.12, a: 1}`. An `a` below 1 makes the canvas see-through. */\n bgColor?: { r: number; g: number; b: number; a: number };\n /** Keep the drawing buffer after compositing, so the canvas can be read back. Default `false`. */\n preserveDrawingBuffer?: boolean;\n /** MSAA on the canvas. Default `false`. */\n antialias?: boolean;\n /**\n * `'webgpu'` uses `WebGPURenderer`, and needs the\n * `@viggle/splat-engine-three/webgpu` entry point to have been imported; a\n * device without WebGPU falls back to WebGL. Default `'webgl'`.\n */\n backend?: RenderBackend;\n /** Initial camera world position. Default `{x: 0, y: 1, z: 5}`. */\n cameraPosition?: { x: number; y: number; z: number };\n /** Initial camera look-at target. Default `{x: 0, y: 0.5, z: 0}`. */\n cameraTarget?: { x: number; y: number; z: number };\n /** Vertical field of view in degrees. Default `60`. */\n fov?: number;\n /** Near clip plane. Default `0.1`. */\n near?: number;\n /** Far clip plane. Default `100`. */\n far?: number;\n /** Ambient light for meshes (splats ignore it), 0\u20131. Default `0.55`. */\n ambientLight?: number;\n /** Tone-mapping exposure. Default `1`. */\n exposure?: number;\n /**\n * Ammo-backed physics: rigid bodies on {@link Scene.physics}, and the\n * engine's `Ragdoll`. The engine does not ship Ammo. Pass `true` when\n * `globalThis.Ammo` is already set, or `{ loadAmmo }` to have the engine\n * await your loader first. Default `false`.\n */\n physics?: boolean | { loadAmmo: () => Promise<void> };\n /**\n * Cap on frames per second: frames that arrive sooner are skipped whole,\n * update and render alike. Default: the display's own rate.\n */\n maxFps?: number;\n /** Cap on the device pixel ratio of the drawing buffer. Default `1`. */\n maxPixelRatio?: number;\n /** GPU power preference. Default `'high-performance'`. */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /**\n * Discard splats smaller than this many pixels on screen, on every splat\n * loaded into the scene. `true` is 2 px. Default off.\n */\n subPixelCull?: boolean | number;\n /**\n * {@link SplatEngine.legacyRootRotation} for this scene. Default `false`:\n * GLB clips keep their root rotation, as in the PlayCanvas build 0.3.2.\n */\n legacyRootRotation?: boolean;\n /** Kept for PlayCanvas parity; three.js always has a depth buffer. */\n depth?: boolean;\n /** Kept for PlayCanvas parity; the skeleton library always loads. */\n loadSkeleton?: boolean;\n}\n\n/** Longest step one frame may take, so a tab coming back does not fling bodies. */\nconst MAX_DELTA_TIME = 0.1;\n\n/** Events {@link Scene.on} accepts. */\nexport type SceneEvent = 'update' | 'postUpdate' | 'preRender' | 'postRender';\n\ntype WebGPURendererFactory = (canvas: HTMLCanvasElement, opts: CreateSceneOptions) => Promise<unknown | null>;\nlet webgpuRendererFactory: WebGPURendererFactory | null = null;\n\n/**\n * Make `backend: 'webgpu'` available to {@link Scene.create}. Called by the\n * `@viggle/splat-engine-three/webgpu` entry point.\n * @internal\n */\nexport function registerWebGPURendererFactory(factory: WebGPURendererFactory): void {\n webgpuRendererFactory = factory;\n}\n\n/**\n * Everything a game needs to draw splats, in one object: a renderer on your\n * canvas, a three.js scene and camera, the render loop, resizing, and the\n * engine state ({@link SplatEngine}) characters and clips load into.\n *\n * The three.js counterpart of the PlayCanvas build's `Scene`. It IS a\n * `SplatEngine`, so `Character.load(scene, \u2026)` and\n * `Animation.loadGlb(scene, \u2026)` work as they do there. Where that build\n * exposes PlayCanvas objects, this one exposes three.js ones:\n *\n * | PlayCanvas build | here |\n * |-------------------------------|-------------------------------|\n * | `scene.app` | {@link renderer}, {@link threeScene} |\n * | `scene.cameraEntity` | {@link camera} |\n * | `scene.graphicsDevice.setResolution(w, h)` | {@link setResolution} |\n * | `scene.app.on('update', fn)` | {@link on}`('update', fn)` |\n * | `entity.addComponent('rigidbody' / 'collision', \u2026)` | {@link physics}`.addBody(object, { shape, \u2026 })` |\n * | `entity.rigidbody` | {@link physics}`.getBody(object)` |\n * | `app.systems.rigidbody.raycastFirst / gravity / dynamicsWorld` | {@link physics}`.raycastFirst / gravity / dynamicsWorld` |\n *\n * Applications that already own a renderer and a loop keep using\n * {@link SplatEngine} directly; nothing here is required.\n *\n * ```ts\n * const scene = await Scene.create(canvas, { fov: 70, bgColor: { r: 0.05, g: 0.06, b: 0.08, a: 1 } });\n * const hero = await Character.load(scene, '/assets/hero.vsplat');\n * await Animation.loadGlb(scene, '/assets/idle.glb', 'idle');\n * hero.playAnimation('idle', { loop: true });\n * scene.on('update', (dt) => { \u2026 });\n * scene.start();\n * ```\n *\n * @group Scene\n */\nexport class Scene extends SplatEngine {\n /** The canvas the renderer draws into. */\n readonly canvas: HTMLCanvasElement;\n /**\n * The three.js renderer: a `THREE.WebGLRenderer`, or a `WebGPURenderer`\n * when {@link backendName} is `'webgpu'`.\n */\n readonly renderer: WebGLRenderer;\n /** Which backend {@link renderer} runs on. */\n readonly backendName: RenderBackend;\n /** The three.js scene everything is drawn from. {@link contentRoot} is in it. */\n readonly threeScene: ThreeScene;\n /** The scene camera. */\n declare camera: PerspectiveCamera;\n /** Ambient light for meshes added to {@link threeScene}. Splats are not lit by it. */\n readonly ambientLight: AmbientLight;\n /** The post-processing chain. Empty until an effect is added. */\n readonly postfx: PostFX;\n /** Rigid-body physics, when the scene was created with {@link CreateSceneOptions.physics}. */\n readonly physics: PhysicsWorld | null;\n /** True when the scene was created with a see-through background (`bgColor.a < 1`). */\n readonly transparent: boolean;\n /** Frames per second cap; `0` for none. Read every frame. */\n maxFps: number;\n\n private readonly _listeners: Record<SceneEvent, Set<(dt: number) => void>> = {\n update: new Set(), postUpdate: new Set(), preRender: new Set(), postRender: new Set(),\n };\n private _running = false;\n private _suspended = false;\n private _lastTime = -1;\n private _lastFrameTime = -1;\n private _maxPixelRatio: number;\n private _explicitSize: { width: number; height: number } | null = null;\n private readonly _resizeObserver: ResizeObserver | null;\n private readonly _clearDisplay: Color;\n private readonly _clearLinear: Color;\n private readonly _clearAlpha: number;\n\n /** @internal Use {@link Scene.create}. */\n constructor(\n canvas: HTMLCanvasElement,\n renderer: WebGLRenderer,\n backendName: RenderBackend,\n physics: PhysicsWorld | null,\n opts: CreateSceneOptions,\n ) {\n const threeScene = new ThreeScene();\n const fov = opts.fov ?? 60;\n const camera = new PerspectiveCamera(fov, 1, opts.near ?? 0.1, opts.far ?? 100);\n camera.name = 'camera';\n super({ scene: threeScene, camera, legacyRootRotation: opts.legacyRootRotation ?? false });\n this.canvas = canvas;\n this.renderer = renderer;\n this.backendName = backendName;\n this.threeScene = threeScene;\n this.physics = physics;\n this.maxFps = opts.maxFps ?? 0;\n this._maxPixelRatio = opts.maxPixelRatio ?? 1;\n\n const bg = opts.bgColor ?? { r: 0.08, g: 0.08, b: 0.12, a: 1 };\n this.transparent = bg.a < 1;\n // Drawn straight to the canvas, PlayCanvas writes the clear colour as\n // is: display colour. Into a CameraFrame's target it is linear.\n this._clearDisplay = new Color().setRGB(bg.r, bg.g, bg.b, SRGBColorSpace);\n this._clearLinear = new Color(bg.r, bg.g, bg.b);\n this._clearAlpha = bg.a;\n renderer.setClearColor(this._clearDisplay, bg.a);\n renderer.toneMappingExposure = opts.exposure ?? 1;\n\n const amb = opts.ambientLight ?? 0.55;\n this.ambientLight = new AmbientLight(0xffffff, amb);\n this.ambientLight.name = 'ambientLight';\n threeScene.add(this.ambientLight);\n\n const p = opts.cameraPosition ?? { x: 0, y: 1, z: 5 };\n const t = opts.cameraTarget ?? { x: 0, y: 0.5, z: 0 };\n camera.position.set(p.x, p.y, p.z);\n camera.lookAt(new Vector3(t.x, t.y, t.z));\n threeScene.add(camera);\n\n if (opts.subPixelCull) this.subPixelCull = opts.subPixelCull === true ? 2 : opts.subPixelCull;\n\n this.postfx = new PostFX(this);\n\n this._resizeObserver = typeof ResizeObserver !== 'undefined'\n ? new ResizeObserver(() => this._fitToCanvas())\n : null;\n this._resizeObserver?.observe(canvas);\n this._fitToCanvas();\n }\n\n /**\n * Create a renderer on `canvas` and return a ready scene. Call\n * {@link start} to begin rendering.\n */\n static async create(canvas: HTMLCanvasElement, opts: CreateSceneOptions = {}): Promise<Scene> {\n const physics = opts.physics ? await PhysicsWorld.create(opts.physics) : null;\n try {\n return await Scene._createWithPhysics(canvas, opts, physics);\n } catch (e) {\n // Nothing else holds the world yet; free it rather than leak it.\n physics?.destroy();\n throw e;\n }\n }\n\n private static async _createWithPhysics(\n canvas: HTMLCanvasElement, opts: CreateSceneOptions, physics: PhysicsWorld | null,\n ): Promise<Scene> {\n let renderer: unknown = null;\n let backendName: RenderBackend = 'webgl';\n if (opts.backend === 'webgpu') {\n if (!webgpuRendererFactory) {\n console.warn(\n \"[splat-engine-three] Scene.create: backend 'webgpu' needs the '@viggle/splat-engine-three/webgpu' \" +\n 'entry point; using WebGL.',\n );\n } else {\n renderer = await webgpuRendererFactory(canvas, opts);\n if (renderer) backendName = 'webgpu';\n }\n }\n if (!renderer) {\n renderer = new WebGLRenderer({\n canvas,\n antialias: opts.antialias ?? false,\n alpha: (opts.bgColor?.a ?? 1) < 1 || !!opts.preserveDrawingBuffer,\n preserveDrawingBuffer: opts.preserveDrawingBuffer ?? false,\n powerPreference: opts.powerPreference ?? 'high-performance',\n });\n }\n return new Scene(canvas, renderer as WebGLRenderer, backendName, physics, opts);\n }\n\n /** Cap on the drawing buffer's device pixel ratio. */\n get maxPixelRatio(): number {\n return this._maxPixelRatio;\n }\n\n set maxPixelRatio(ratio: number) {\n this._maxPixelRatio = ratio;\n this._explicitSize = null;\n this._fitToCanvas();\n }\n\n /** Drawing-buffer width in pixels. */\n get width(): number {\n return this.canvas.width;\n }\n\n /** Drawing-buffer height in pixels. */\n get height(): number {\n return this.canvas.height;\n }\n\n /**\n * Set the drawing buffer to exactly `width` x `height` pixels, whatever the\n * canvas's CSS size and the pixel ratio. Holds until {@link maxPixelRatio}\n * is set again.\n */\n setResolution(width: number, height: number): void {\n this._explicitSize = { width: Math.max(1, Math.round(width)), height: Math.max(1, Math.round(height)) };\n this._applySize(this._explicitSize.width, this._explicitSize.height);\n }\n\n private _fitToCanvas(): void {\n if (this.destroyed) return;\n if (this._explicitSize) {\n this._applySize(this._explicitSize.width, this._explicitSize.height);\n return;\n }\n const dpr = Math.min(typeof devicePixelRatio === 'number' ? devicePixelRatio : 1, this._maxPixelRatio);\n const w = Math.max(1, Math.round((this.canvas.clientWidth || this.canvas.width) * dpr));\n const h = Math.max(1, Math.round((this.canvas.clientHeight || this.canvas.height) * dpr));\n this._applySize(w, h);\n }\n\n private _applySize(width: number, height: number): void {\n const r = this.renderer;\n if (this.canvas.width !== width || this.canvas.height !== height || r.getPixelRatio() !== 1) {\n r.setPixelRatio(1);\n // CSS size is the page's to set; only the drawing buffer is ours.\n r.setSize(width, height, false);\n }\n this.camera.aspect = width / height;\n this.camera.updateProjectionMatrix();\n this.postfx.resize(width, height);\n }\n\n /**\n * Run `fn` every frame. `'update'` runs after physics and the characters\n * have advanced, `'postUpdate'` after every `'update'` listener,\n * `'preRender'` / `'postRender'` around the draw. `dt` is in seconds.\n * @returns A function that removes the listener.\n */\n on(event: SceneEvent, fn: (dt: number) => void): () => void {\n this._listeners[event].add(fn);\n return () => this.off(event, fn);\n }\n\n /** Remove a listener added with {@link on}. */\n off(event: SceneEvent, fn: (dt: number) => void): void {\n this._listeners[event].delete(fn);\n }\n\n /** Start the render loop. */\n start(): void {\n if (this._running || this.destroyed) return;\n this._running = true;\n this._lastTime = -1;\n this.renderer.setAnimationLoop((time: number) => this._loop(time));\n }\n\n /** Stop the render loop. {@link start} resumes it. */\n stop(): void {\n if (!this._running) return;\n this._running = false;\n this.renderer.setAnimationLoop(null);\n }\n\n /** Pause rendering while updates keep ticking; resuming draws again. */\n setSuspended(suspended: boolean): void {\n this._suspended = suspended;\n }\n\n private _loop(time: number): void {\n if (this.destroyed) return;\n if (this.maxFps > 0 && this._lastFrameTime >= 0) {\n // A little slack, so a 60 Hz display asked for 30 does not drop to 20\n // when a frame lands a hair early.\n if (time - this._lastFrameTime < 1000 / this.maxFps - 2) return;\n }\n this._lastFrameTime = time;\n const dt = this._lastTime < 0 ? 0 : Math.min(MAX_DELTA_TIME, (time - this._lastTime) / 1000);\n this._lastTime = time;\n this.tick(dt);\n }\n\n /**\n * Advance and draw one frame by hand: physics, characters, the `'update'`\n * listeners, then the render. The loop {@link start} runs calls this.\n */\n tick(dt: number): void {\n if (this.destroyed) return;\n this.physics?.step(dt);\n this.update(dt, this.camera);\n for (const fn of this._listeners.update) fn(dt);\n for (const fn of this._listeners.postUpdate) fn(dt);\n if (this._suspended) return;\n this.render(dt);\n }\n\n /** Draw one frame with the current state, through the post-processing chain. */\n render(dt = 0): void {\n if (this.destroyed) return;\n for (const fn of this._listeners.preRender) fn(dt);\n this.postfx.render();\n for (const fn of this._listeners.postRender) fn(dt);\n }\n\n /**\n * Switch the renderer's clear colour between the background as display\n * colour (drawing to the canvas) and as a linear value (drawing into a\n * {@link CameraFrame}'s target). @internal\n */\n useLinearClearColor(linear: boolean): void {\n this.renderer.setClearColor(linear ? this._clearLinear : this._clearDisplay, this._clearAlpha);\n }\n\n /** The camera's built-in tone mapping, bloom, grading and vignette, created on first call. */\n getOrCreateCameraFrame(): CameraFrame {\n return this.postfx.getOrCreateCameraFrame();\n }\n\n /** The {@link CameraFrame}, or `null` before {@link getOrCreateCameraFrame}. */\n get cameraFrame(): CameraFrame | null {\n return this.postfx.cameraFrame;\n }\n\n /** Drop the {@link CameraFrame} and its effects. */\n destroyCameraFrame(): void {\n this.postfx.destroyCameraFrame();\n }\n\n /**\n * Stop the loop, release the renderer and its context, and stop observing\n * the canvas. Characters and environments are not destroyed for you.\n */\n destroy(): void {\n if (this.destroyed) return;\n this.stop();\n this._resizeObserver?.disconnect();\n this.skeletalAnimationLibrary.clear();\n for (const set of Object.values(this._listeners)) set.clear();\n try { this.postfx.destroyAll(); } catch { /* keep tearing down */ }\n try { this.physics?.destroy(); } catch { /* keep tearing down */ }\n this.dispose();\n const r = this.renderer as WebGLRenderer & { forceContextLoss?: () => void };\n try { r.dispose(); } catch { /* keep tearing down */ }\n // Free the context now rather than at GC: browsers cap live contexts.\n try { r.forceContextLoss?.(); } catch { /* keep tearing down */ }\n }\n}\n\n/**\n * Thrown when an asset finishes loading onto a scene that has already been\n * destroyed. The same class as {@link EngineDisposedError}, under the\n * PlayCanvas build's name.\n *\n * @group Scene\n */\nexport const SceneDestroyedError = EngineDisposedError;\n", "import { Color } from 'three';\n\n/**\n * Tone-mapping curves for {@link CameraFrame.rendering}. The values match\n * PlayCanvas's `TONEMAP_*` constants, so a number carried over from a\n * PlayCanvas game means the same curve here.\n *\n * @group PostFX\n */\nexport const TONEMAP_LINEAR = 0;\nexport const TONEMAP_FILMIC = 1;\nexport const TONEMAP_HEJL = 2;\nexport const TONEMAP_ACES = 3;\nexport const TONEMAP_ACES2 = 4;\nexport const TONEMAP_NEUTRAL = 5;\nexport const TONEMAP_NONE = 6;\n\n/**\n * An RGB colour as the frame reads it: a three.js `Color`, or any object with\n * `r`, `g`, `b` (a PlayCanvas `Color` carried over from a game works).\n *\n * @group PostFX\n */\nexport interface FrameColor {\n r: number;\n g: number;\n b: number;\n}\n\n/**\n * A colour with optional alpha, as the effects take it: a three.js `Color`\n * (alpha 1), a PlayCanvas `Color`, or a plain `{ r, g, b, a }`.\n *\n * @group PostFX\n */\nexport type EffectColor = FrameColor & { a?: number };\n\n/**\n * The scene camera's built-in post-processing: tone mapping, bloom, colour\n * grading and vignette, in the shape of PlayCanvas's `CameraFrame` so a game's\n * settings carry over field for field. Get it with\n * `scene.getOrCreateCameraFrame()` and change fields.\n *\n * With a frame, the scene renders into a linear half-float target and a\n * compose pass applies, in PlayCanvas's order: bloom, grading, tone mapping\n * (scaled by the renderer's `toneMappingExposure`), vignette, then the encode\n * to display colour. Splats blend in linear light there, as they do under\n * PlayCanvas's frame. Without one the scene draws straight to the canvas.\n *\n * @group PostFX\n */\nexport class CameraFrame {\n readonly rendering = {\n /** One of the `TONEMAP_*` constants. */\n toneMapping: TONEMAP_LINEAR,\n /** MSAA samples for the scene target. 1 = none. */\n samples: 1,\n /** Resolution of the scene target relative to the canvas. */\n renderTargetScale: 1,\n /** Kept for PlayCanvas parity: three.js always composes meshes and splats by depth. */\n sceneDepthMap: false,\n /** Contrast-adaptive sharpening of the scene before tone mapping, 0..1. */\n sharpness: 0,\n };\n\n /**\n * Kept for PlayCanvas parity, so a game that tunes ambient occlusion runs:\n * nothing here renders it.\n */\n readonly ssao = {\n type: 'none' as string,\n blurEnabled: true,\n randomize: false,\n intensity: 0.5,\n radius: 30,\n samples: 12,\n power: 6,\n minAngle: 10,\n scale: 1,\n };\n\n readonly bloom = {\n /** Amount of bloom mixed in. 0 turns it off. */\n intensity: 0,\n /** How wide the bloom spreads: the number of blur levels, 1..16. */\n blurLevel: 16,\n };\n\n readonly grading = {\n enabled: false,\n brightness: 1,\n contrast: 1,\n saturation: 1,\n tint: new Color(1, 1, 1) as FrameColor,\n };\n\n readonly vignette = {\n /** 0 turns it off. */\n intensity: 0,\n inner: 0.5,\n outer: 1,\n curvature: 0.5,\n color: new Color(0, 0, 0) as FrameColor,\n };\n\n /**\n * Kept for PlayCanvas parity, where changes wait for this call: here the\n * settings are read every frame, so they apply with or without it.\n */\n update(): void {}\n}\n", "// The CameraFrame's shaders: PlayCanvas's compose pass (render-pass-compose,\n// compose*.js chunks) and its bloom passes (frame-pass-bloom, downsample.js,\n// upsample.js), ported term for term so a game's settings give the same\n// picture. Sources are generated per variant instead of preprocessed: three.js\n// has no preprocessor for WGSL.\n//\n// One deliberate difference: the final encode is the piecewise sRGB curve,\n// not PlayCanvas's pow(1 / 2.2). Each engine encodes with the inverse of its\n// own splat decode, so a frame at default settings returns the colours a\n// plain render would.\n\nimport {\n TONEMAP_ACES,\n TONEMAP_ACES2,\n TONEMAP_FILMIC,\n TONEMAP_HEJL,\n TONEMAP_LINEAR,\n TONEMAP_NEUTRAL,\n} from './camera-frame';\nimport type { PostFXShaderSource } from './program';\n\n/** The parts of the compose shader a frame's settings switch on. @internal */\nexport interface ComposeVariant {\n toneMapping: number;\n bloom: boolean;\n grading: boolean;\n vignette: boolean;\n sharpen: boolean;\n}\n\n/** A stable key for a {@link ComposeVariant}, for caching its program. @internal */\nexport function composeVariantKey(v: ComposeVariant): string {\n return `${v.toneMapping}${v.bloom ? 'b' : ''}${v.grading ? 'g' : ''}${v.vignette ? 'v' : ''}${v.sharpen ? 's' : ''}`;\n}\n\n// \u2500\u2500 tone mapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst TONEMAP_GLSL: Record<number, string> = {\n [TONEMAP_LINEAR]: 'vec3 toneMap(vec3 color, float exposure) { return color * exposure; }',\n [TONEMAP_FILMIC]: `\nconst float A = 0.15; const float B = 0.50; const float C = 0.10;\nconst float D = 0.20; const float E = 0.02; const float F = 0.30; const float W = 11.2;\nvec3 uncharted2Tonemap(vec3 x) { return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F; }\nvec3 toneMap(vec3 color, float exposure) {\n color = uncharted2Tonemap(color * exposure);\n return color / uncharted2Tonemap(vec3(W));\n}`,\n [TONEMAP_HEJL]: `\nvec3 toneMap(vec3 color, float exposure) {\n color *= exposure;\n const float A = 0.22, B = 0.3, C = 0.1, D = 0.2, E = 0.01, F = 0.3;\n const float Scl = 1.25;\n vec3 h = max(vec3(0.0), color - vec3(0.004));\n return (h * ((Scl * A) * h + Scl * vec3(C * B)) + Scl * vec3(D * E)) / (h * (A * h + vec3(B)) + vec3(D * F)) - Scl * vec3(E / F);\n}`,\n [TONEMAP_ACES]: `\nvec3 toneMap(vec3 color, float exposure) {\n vec3 x = color * exposure;\n return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14);\n}`,\n [TONEMAP_ACES2]: `\nconst mat3 ACESInputMat = mat3(0.59719, 0.35458, 0.04823, 0.07600, 0.90834, 0.01566, 0.02840, 0.13383, 0.83777);\nconst mat3 ACESOutputMat = mat3(1.60475, -0.53108, -0.07367, -0.10208, 1.10813, -0.00605, -0.00327, -0.07276, 1.07602);\nvec3 RRTAndODTFit(vec3 v) {\n vec3 a = v * (v + 0.0245786) - 0.000090537;\n vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n return a / b;\n}\nvec3 toneMap(vec3 color, float exposure) {\n color *= exposure / 0.6;\n color = color * ACESInputMat;\n color = RRTAndODTFit(color);\n color = color * ACESOutputMat;\n return clamp(color, 0.0, 1.0);\n}`,\n [TONEMAP_NEUTRAL]: `\nvec3 toneMap(vec3 color, float exposure) {\n color *= exposure;\n float startCompression = 0.8 - 0.04;\n float desaturation = 0.15;\n float x = min(color.r, min(color.g, color.b));\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n color -= offset;\n float peak = max(color.r, max(color.g, color.b));\n if (peak < startCompression) return color;\n float d = 1.0 - startCompression;\n float newPeak = 1.0 - d * d / (peak + d - startCompression);\n color *= newPeak / peak;\n float g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);\n return mix(color, vec3(newPeak), g);\n}`,\n};\nconst TONEMAP_NONE_GLSL = 'vec3 toneMap(vec3 color, float exposure) { return color; }';\n\nconst TONEMAP_WGSL: Record<number, string> = {\n [TONEMAP_LINEAR]: 'fn toneMap(color: vec3f, exposure: f32) -> vec3f { return color * exposure; }',\n [TONEMAP_FILMIC]: `\nfn uncharted2Tonemap(x: vec3f) -> vec3f {\n let A = 0.15; let B = 0.50; let C = 0.10; let D = 0.20; let E = 0.02; let F = 0.30;\n return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\n}\nfn toneMap(color: vec3f, exposure: f32) -> vec3f {\n return uncharted2Tonemap(color * exposure) / uncharted2Tonemap(vec3f(11.2));\n}`,\n [TONEMAP_HEJL]: `\nfn toneMap(colorIn: vec3f, exposure: f32) -> vec3f {\n let color = colorIn * exposure;\n let A = 0.22; let B = 0.3; let C = 0.1; let D = 0.2; let E = 0.01; let F = 0.3;\n let Scl = 1.25;\n let h = max(vec3f(0.0), color - vec3f(0.004));\n return (h * ((Scl * A) * h + Scl * vec3f(C * B)) + Scl * vec3f(D * E)) / (h * (A * h + vec3f(B)) + vec3f(D * F)) - Scl * vec3f(E / F);\n}`,\n [TONEMAP_ACES]: `\nfn toneMap(color: vec3f, exposure: f32) -> vec3f {\n let x = color * exposure;\n return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14);\n}`,\n [TONEMAP_ACES2]: `\nconst ACESInputMat = mat3x3f(0.59719, 0.35458, 0.04823, 0.07600, 0.90834, 0.01566, 0.02840, 0.13383, 0.83777);\nconst ACESOutputMat = mat3x3f(1.60475, -0.53108, -0.07367, -0.10208, 1.10813, -0.00605, -0.00327, -0.07276, 1.07602);\nfn RRTAndODTFit(v: vec3f) -> vec3f {\n let a = v * (v + 0.0245786) - 0.000090537;\n let b = v * (0.983729 * v + 0.4329510) + 0.238081;\n return a / b;\n}\nfn toneMap(colorIn: vec3f, exposure: f32) -> vec3f {\n var color = colorIn * (exposure / 0.6);\n color = color * ACESInputMat;\n color = RRTAndODTFit(color);\n color = color * ACESOutputMat;\n return clamp(color, vec3f(0.0), vec3f(1.0));\n}`,\n [TONEMAP_NEUTRAL]: `\nfn toneMap(colorIn: vec3f, exposure: f32) -> vec3f {\n var color = colorIn * exposure;\n let startCompression = 0.8 - 0.04;\n let desaturation = 0.15;\n let x = min(color.r, min(color.g, color.b));\n let offset = select(0.04, x - 6.25 * x * x, x < 0.08);\n color -= offset;\n let peak = max(color.r, max(color.g, color.b));\n if (peak < startCompression) { return color; }\n let d = 1.0 - startCompression;\n let newPeak = 1.0 - d * d / (peak + d - startCompression);\n color *= newPeak / peak;\n let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);\n return mix(color, vec3f(newPeak), g);\n}`,\n};\nconst TONEMAP_NONE_WGSL = 'fn toneMap(color: vec3f, exposure: f32) -> vec3f { return color; }';\n\n// \u2500\u2500 compose \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The compose pass for `v`: scene (+ bloom) \u2192 grading \u2192 tone map \u2192 vignette \u2192 sRGB. @internal */\nexport function composeSource(v: ComposeVariant): PostFXShaderSource {\n return {\n name: `postfx-compose-${composeVariantKey(v)}`,\n glsl: composeGLSL(v),\n wgsl: composeWGSL(v),\n };\n}\n\nfunction composeGLSL(v: ComposeVariant): string {\n return /* glsl */ `\nprecision highp float;\nvarying vec2 vUv0;\nuniform sampler2D sceneTexture;\nuniform vec2 sceneTextureInvRes;\nuniform float exposure;\n${v.bloom ? 'uniform sampler2D bloomTexture;\\nuniform float bloomIntensity;' : ''}\n${v.grading ? 'uniform vec3 brightnessContrastSaturation;\\nuniform vec3 tint;' : ''}\n${v.vignette ? 'uniform vec4 vignetterParams;\\nuniform vec3 vignetteColor;' : ''}\n${v.sharpen ? 'uniform float sharpness;' : ''}\n\n${TONEMAP_GLSL[v.toneMapping] ?? TONEMAP_NONE_GLSL}\n\nfloat maxComponent(vec3 c) { return max(c.r, max(c.g, c.b)); }\nvec3 toSDR(vec3 c) { return c / (1.0 + maxComponent(c)); }\nvec3 toHDR(vec3 c) { return c / max(1.0 - maxComponent(c), 1e-4); }\n\nvec3 linearToSrgb(vec3 c) {\n c = max(c, 0.0);\n return mix(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, vec3(lessThanEqual(c, vec3(0.0031308))));\n}\n\nvoid main() {\n vec2 uv = vUv0;\n vec4 scene = texture2D(sceneTexture, uv);\n vec3 result = scene.rgb;\n${v.sharpen ? `\n // Contrast-adaptive sharpening, HDR variant.\n float x = sceneTextureInvRes.x;\n float y = sceneTextureInvRes.y;\n vec3 a = toSDR(texture2D(sceneTexture, uv + vec2(0.0, -y)).rgb);\n vec3 b = toSDR(texture2D(sceneTexture, uv + vec2(-x, 0.0)).rgb);\n vec3 c = toSDR(result);\n vec3 d = toSDR(texture2D(sceneTexture, uv + vec2(x, 0.0)).rgb);\n vec3 e = toSDR(texture2D(sceneTexture, uv + vec2(0.0, y)).rgb);\n float minG = min(a.g, min(b.g, min(c.g, min(d.g, e.g))));\n float maxG = max(a.g, max(b.g, max(c.g, max(d.g, e.g))));\n float w = sqrt(min(1.0 - maxG, minG) / max(maxG, 1e-4)) * sharpness;\n result = toHDR(max((w * (a + b + d + e) + c) / (4.0 * w + 1.0), 0.0));` : ''}\n${v.bloom ? `\n result += texture2D(bloomTexture, uv).rgb * bloomIntensity;` : ''}\n${v.grading ? `\n result *= tint;\n result *= brightnessContrastSaturation.x;\n float grey = dot(result, vec3(0.3, 0.59, 0.11));\n grey = grey / max(1.0, maxComponent(result));\n result = mix(vec3(grey), result, brightnessContrastSaturation.z);\n result = mix(vec3(0.5), result, brightnessContrastSaturation.y);` : ''}\n result = toneMap(max(vec3(0.0), result), exposure);\n${v.vignette ? `\n vec2 curve = pow(abs(uv * 2.0 - 1.0), vec2(1.0 / vignetterParams.z));\n float edge = pow(length(curve), vignetterParams.z);\n float vig = 1.0 - vignetterParams.w * smoothstep(vignetterParams.x, vignetterParams.y, edge);\n result = mix(vignetteColor, result, vig);` : ''}\n gl_FragColor = vec4(linearToSrgb(result), scene.a);\n}\n`;\n}\n\nfunction composeWGSL(v: ComposeVariant): string {\n return /* wgsl */ `\nvar sceneTexture: texture_2d<f32>;\nvar sceneTextureSampler: sampler;\nuniform sceneTextureInvRes: vec2f;\nuniform exposure: f32;\n${v.bloom ? 'var bloomTexture: texture_2d<f32>;\\nvar bloomTextureSampler: sampler;\\nuniform bloomIntensity: f32;' : ''}\n${v.grading ? 'uniform brightnessContrastSaturation: vec3f;\\nuniform tint: vec3f;' : ''}\n${v.vignette ? 'uniform vignetterParams: vec4f;\\nuniform vignetteColor: vec3f;' : ''}\n${v.sharpen ? 'uniform sharpness: f32;' : ''}\n\n${TONEMAP_WGSL[v.toneMapping] ?? TONEMAP_NONE_WGSL}\n\nfn maxComponent(c: vec3f) -> f32 { return max(c.r, max(c.g, c.b)); }\nfn toSDR(c: vec3f) -> vec3f { return c / (1.0 + maxComponent(c)); }\nfn toHDR(c: vec3f) -> vec3f { return c / max(1.0 - maxComponent(c), 1e-4); }\n\nfn linearToSrgb(cIn: vec3f) -> vec3f {\n let c = max(cIn, vec3f(0.0));\n return select(1.055 * pow(c, vec3f(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3f(0.0031308));\n}\n\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let uv = input.texUv;\n let scene = textureSampleLevel(sceneTexture, sceneTextureSampler, uv, 0.0);\n var result = scene.rgb;\n${v.sharpen ? `\n let x = uniform.sceneTextureInvRes.x;\n let y = uniform.sceneTextureInvRes.y;\n let a = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(0.0, -y), 0.0).rgb);\n let b = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(-x, 0.0), 0.0).rgb);\n let c = toSDR(result);\n let d = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(x, 0.0), 0.0).rgb);\n let e = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(0.0, y), 0.0).rgb);\n let minG = min(a.g, min(b.g, min(c.g, min(d.g, e.g))));\n let maxG = max(a.g, max(b.g, max(c.g, max(d.g, e.g))));\n let w = sqrt(min(1.0 - maxG, minG) / max(maxG, 1e-4)) * uniform.sharpness;\n result = toHDR(max((w * (a + b + d + e) + c) / (4.0 * w + 1.0), vec3f(0.0)));` : ''}\n${v.bloom ? `\n result += textureSampleLevel(bloomTexture, bloomTextureSampler, uv, 0.0).rgb * uniform.bloomIntensity;` : ''}\n${v.grading ? `\n let bcs = uniform.brightnessContrastSaturation;\n result *= uniform.tint;\n result *= bcs.x;\n let grey = dot(result, vec3f(0.3, 0.59, 0.11)) / max(1.0, maxComponent(result));\n result = mix(vec3f(grey), result, bcs.z);\n result = mix(vec3f(0.5), result, bcs.y);` : ''}\n result = toneMap(max(vec3f(0.0), result), uniform.exposure);\n${v.vignette ? `\n let vp = uniform.vignetterParams;\n let curve = pow(abs(uv * 2.0 - 1.0), vec2f(1.0 / vp.z));\n let edge = pow(length(curve), vp.z);\n let vig = 1.0 - vp.w * smoothstep(vp.x, vp.y, edge);\n result = mix(uniform.vignetteColor, result, vig);` : ''}\n output.color = vec4f(linearToSrgb(result), scene.a);\n return output;\n}\n`;\n}\n\n// \u2500\u2500 bloom \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Half-resolution copy of the scene that feeds the bloom chain, negatives removed. @internal */\nexport const BLOOM_PREFILTER: PostFXShaderSource = {\n name: 'postfx-bloom-half',\n glsl: /* glsl */ `\nprecision highp float;\nvarying vec2 vUv0;\nuniform sampler2D sourceTexture;\nvoid main() {\n gl_FragColor = vec4(max(texture2D(sourceTexture, vUv0).rgb, 0.0), 1.0);\n}\n`,\n wgsl: /* wgsl */ `\nvar sourceTexture: texture_2d<f32>;\nvar sourceTextureSampler: sampler;\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n output.color = vec4f(max(textureSampleLevel(sourceTexture, sourceTextureSampler, input.texUv, 0.0).rgb, vec3f(0.0)), 1.0);\n return output;\n}\n`,\n};\n\n/** One 13-tap downsample of the bloom chain. @internal */\nexport const BLOOM_DOWNSAMPLE: PostFXShaderSource = {\n name: 'postfx-bloom-down',\n glsl: /* glsl */ `\nprecision highp float;\nvarying vec2 vUv0;\nuniform sampler2D sourceTexture;\nuniform vec2 sourceInvResolution;\nvec3 tap(vec2 o) { return texture2D(sourceTexture, vUv0 + o * sourceInvResolution).rgb; }\nvoid main() {\n vec3 value = tap(vec2(0.0)) * 0.125;\n value += (tap(vec2(-2.0, 2.0)) + tap(vec2(2.0, 2.0)) + tap(vec2(-2.0, -2.0)) + tap(vec2(2.0, -2.0))) * 0.03125;\n value += (tap(vec2(0.0, 2.0)) + tap(vec2(-2.0, 0.0)) + tap(vec2(2.0, 0.0)) + tap(vec2(0.0, -2.0))) * 0.0625;\n value += (tap(vec2(-1.0, 1.0)) + tap(vec2(1.0, 1.0)) + tap(vec2(-1.0, -1.0)) + tap(vec2(1.0, -1.0))) * 0.125;\n gl_FragColor = vec4(value, 1.0);\n}\n`,\n wgsl: /* wgsl */ `\nvar sourceTexture: texture_2d<f32>;\nvar sourceTextureSampler: sampler;\nuniform sourceInvResolution: vec2f;\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let uv = input.texUv;\n let s = uniform.sourceInvResolution;\n var value = textureSampleLevel(sourceTexture, sourceTextureSampler, uv, 0.0).rgb * 0.125;\n value += (textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(-2.0, 2.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(2.0, 2.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(-2.0, -2.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(2.0, -2.0) * s, 0.0).rgb) * 0.03125;\n value += (textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(0.0, 2.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(-2.0, 0.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(2.0, 0.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(0.0, -2.0) * s, 0.0).rgb) * 0.0625;\n value += (textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(-1.0, 1.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(1.0, 1.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(-1.0, -1.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(1.0, -1.0) * s, 0.0).rgb) * 0.125;\n output.color = vec4f(value, 1.0);\n return output;\n}\n`,\n};\n\n/** One 9-tap tent upsample, added onto the level below it. @internal */\nexport const BLOOM_UPSAMPLE: PostFXShaderSource = {\n name: 'postfx-bloom-up',\n blend: 'add',\n glsl: /* glsl */ `\nprecision highp float;\nvarying vec2 vUv0;\nuniform sampler2D sourceTexture;\nuniform vec2 sourceInvResolution;\nvec3 tap(vec2 o) { return texture2D(sourceTexture, vUv0 + o * sourceInvResolution).rgb; }\nvoid main() {\n vec3 value = tap(vec2(0.0)) * 0.25;\n value += (tap(vec2(0.0, 1.0)) + tap(vec2(-1.0, 0.0)) + tap(vec2(1.0, 0.0)) + tap(vec2(0.0, -1.0))) * 0.125;\n value += (tap(vec2(-1.0, 1.0)) + tap(vec2(1.0, 1.0)) + tap(vec2(-1.0, -1.0)) + tap(vec2(1.0, -1.0))) * 0.0625;\n gl_FragColor = vec4(value, 1.0);\n}\n`,\n wgsl: /* wgsl */ `\nvar sourceTexture: texture_2d<f32>;\nvar sourceTextureSampler: sampler;\nuniform sourceInvResolution: vec2f;\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let uv = input.texUv;\n let s = uniform.sourceInvResolution;\n var value = textureSampleLevel(sourceTexture, sourceTextureSampler, uv, 0.0).rgb * 0.25;\n value += (textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(0.0, 1.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(-1.0, 0.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(1.0, 0.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(0.0, -1.0) * s, 0.0).rgb) * 0.125;\n value += (textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(-1.0, 1.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(1.0, 1.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(-1.0, -1.0) * s, 0.0).rgb\n + textureSampleLevel(sourceTexture, sourceTextureSampler, uv + vec2f(1.0, -1.0) * s, 0.0).rgb) * 0.0625;\n output.color = vec4f(value, 1.0);\n return output;\n}\n`,\n};\n", "import {\n ClampToEdgeWrapping,\n HalfFloatType,\n LinearFilter,\n LinearSRGBColorSpace,\n NoColorSpace,\n RGBAFormat,\n RenderTarget,\n UnsignedByteType,\n WebGLRenderTarget,\n} from 'three';\nimport type { WebGLRenderer } from 'three';\n\nimport type { PostFXUniformValue } from './uniforms';\nimport { webglPostFXBackend } from './webgl-program';\n\n/**\n * How a fullscreen shader's output lands on its target.\n * @internal\n */\nexport type PostFXBlend = 'none' | 'alpha' | 'add';\n\n/**\n * A fullscreen fragment shader, written once per shading language in the\n * dialect PlayCanvas's `QuadRender` takes, so a pass ported from the\n * PlayCanvas build keeps its source:\n *\n * - GLSL: `uniform` declarations, `gl_FragCoord`, `gl_FragColor`,\n * `texelFetch` / `texture2D`, and `varying vec2 vUv0` (0..1, y up).\n * - WGSL: `var name: texture_2d<f32>;` and `var nameSampler: sampler;` for\n * textures, `uniform name: type;` read as `uniform.name`, and\n * `fn fragmentMain(input: FragmentInput) -> FragmentOutput` with\n * `input.position` (pixel coordinates, y down) and `output.color`. On top\n * of PlayCanvas's: `input.vUv0` (0..1, y up) and `input.texUv`, the\n * coordinate that samples a full-target texture the right way up.\n *\n * @internal\n */\nexport interface PostFXShaderSource {\n /** Cache and debug name. */\n name: string;\n glsl: string;\n wgsl: string;\n blend?: PostFXBlend;\n}\n\n/**\n * A compiled {@link PostFXShaderSource}, drawn as one fullscreen triangle.\n * @internal\n */\nexport interface PostFXProgram {\n /** Set a uniform the source declares. Unknown names are ignored, as PlayCanvas's scope does. */\n set(name: string, value: PostFXUniformValue): void;\n /** Draw into `target` (`null`: the canvas), over what it holds. */\n draw(target: RenderTarget | null): void;\n dispose(): void;\n}\n\n/**\n * Compiles {@link PostFXShaderSource}s for one kind of renderer.\n * @internal\n */\nexport interface PostFXBackend {\n createProgram(renderer: WebGLRenderer, source: PostFXShaderSource): PostFXProgram;\n}\n\nlet webgpuBackend: PostFXBackend | null = null;\n\n/**\n * Make post-processing available under `WebGPURenderer`. Called by the\n * `@viggle/splat-engine-three/webgpu` entry point.\n * @internal\n */\nexport function registerPostFXWebGPUBackend(backend: PostFXBackend): void {\n webgpuBackend = backend;\n}\n\n/** Whether `renderer` is a `WebGPURenderer` rather than a `THREE.WebGLRenderer`. */\nfunction isWebGPURenderer(renderer: unknown): boolean {\n return (renderer as { isWebGPURenderer?: boolean }).isWebGPURenderer === true;\n}\n\n/** @internal */\nexport function postFXBackendFor(renderer: WebGLRenderer): PostFXBackend {\n if (!isWebGPURenderer(renderer)) return webglPostFXBackend;\n if (!webgpuBackend) {\n throw new Error(\n \"[PostFX] post-processing under WebGPURenderer needs the '@viggle/splat-engine-three/webgpu' entry point\",\n );\n }\n return webgpuBackend;\n}\n\n/**\n * What a post-process target stores. `'hdr'` is linear half-float, what the\n * scene renders into; `'ldr'` is 8-bit display-referred colour, what the\n * passes after the frame's compose hand each other.\n * @internal\n */\nexport interface PostFXTargetOptions {\n format: 'hdr' | 'ldr';\n depth?: boolean;\n samples?: number;\n}\n\n/**\n * A render target the given renderer can draw into. Its texture is never\n * tagged sRGB: both backends would then pick an `-srgb` format and encode on\n * write and decode on read, behind the shaders' backs.\n */\nfunction createPostFXTarget(\n renderer: WebGLRenderer,\n width: number,\n height: number,\n opts: PostFXTargetOptions,\n): RenderTarget {\n const options = {\n type: opts.format === 'hdr' ? HalfFloatType : UnsignedByteType,\n format: RGBAFormat,\n // Splats decode their display-referred colour for a linear target; the\n // 8-bit chain is only ever written by post-process shaders.\n colorSpace: opts.format === 'hdr' ? LinearSRGBColorSpace : NoColorSpace,\n depthBuffer: opts.depth ?? false,\n stencilBuffer: false,\n samples: opts.samples && opts.samples > 1 ? opts.samples : 0,\n generateMipmaps: false,\n minFilter: LinearFilter,\n magFilter: LinearFilter,\n wrapS: ClampToEdgeWrapping,\n wrapT: ClampToEdgeWrapping,\n };\n const w = Math.max(1, Math.floor(width));\n const h = Math.max(1, Math.floor(height));\n return isWebGPURenderer(renderer) ? new RenderTarget(w, h, options) : new WebGLRenderTarget(w, h, options);\n}\n\n/**\n * Keep `current` at `width` x `height` with `samples`, replacing it when the\n * sample count changed (three.js cannot change that in place).\n * @internal\n */\nexport function ensurePostFXTarget(\n renderer: WebGLRenderer,\n current: RenderTarget | null,\n width: number,\n height: number,\n opts: PostFXTargetOptions,\n): RenderTarget {\n const w = Math.max(1, Math.floor(width));\n const h = Math.max(1, Math.floor(height));\n const samples = opts.samples && opts.samples > 1 ? opts.samples : 0;\n if (current && current.samples === samples) {\n if (current.width !== w || current.height !== h) current.setSize(w, h);\n return current;\n }\n current?.dispose();\n return createPostFXTarget(renderer, w, h, opts);\n}\n", "import {\n AddEquation,\n BufferAttribute,\n BufferGeometry,\n CustomBlending,\n Mesh,\n NoBlending,\n NormalBlending,\n OneFactor,\n OrthographicCamera,\n ShaderMaterial,\n} from 'three';\nimport type { RenderTarget, WebGLRenderer, WebGLRenderTarget } from 'three';\n\nimport type { PostFXBackend, PostFXProgram, PostFXShaderSource } from './program';\nimport { assignUniform, initialUniformValue, type DeclaredUniform, type PostFXUniformValue } from './uniforms';\n\n// One triangle past the viewport's corners: no diagonal seam, a third fewer\n// vertices than a quad.\nconst TRIANGLE = new BufferGeometry();\nTRIANGLE.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]), 3));\nconst CAMERA = new OrthographicCamera(-1, 1, 1, -1, 0, 1);\n\nconst VERTEX = /* glsl */ `\nvarying vec2 vUv0;\nvoid main() {\n vUv0 = position.xy * 0.5 + 0.5;\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n`;\n\nconst GLSL_UNIFORM = /^\\s*uniform\\s+(?:(?:lowp|mediump|highp)\\s+)?(\\w+)\\s+(\\w+)\\s*;/gm;\nconst GLSL_TYPES: Record<string, DeclaredUniform['type']> = {\n float: 'float', int: 'int', vec2: 'vec2', vec3: 'vec3', vec4: 'vec4', sampler2D: 'texture',\n};\n\n/** The uniforms a PlayCanvas-dialect GLSL fragment declares. @internal */\nexport function glslUniforms(source: string): DeclaredUniform[] {\n const out: DeclaredUniform[] = [];\n for (const m of source.matchAll(GLSL_UNIFORM)) {\n const type = GLSL_TYPES[m[1]];\n if (!type) throw new Error(`[PostFX] unsupported GLSL uniform type '${m[1]}' for '${m[2]}'`);\n out.push({ name: m[2], type });\n }\n return out;\n}\n\n/**\n * A {@link PostFXShaderSource}'s GLSL as a `ShaderMaterial` on a fullscreen\n * triangle. three.js compiles it as GLSL 3, aliasing `gl_FragColor` and\n * `texture2D`, so PlayCanvas-dialect sources run as written.\n */\nclass WebGLPostFXProgram implements PostFXProgram {\n private readonly _renderer: WebGLRenderer;\n private readonly _material: ShaderMaterial;\n private readonly _mesh: Mesh;\n\n constructor(renderer: WebGLRenderer, source: PostFXShaderSource) {\n this._renderer = renderer;\n const uniforms: Record<string, { value: unknown }> = {};\n for (const u of glslUniforms(source.glsl)) uniforms[u.name] = { value: initialUniformValue(u.type) };\n const blend = source.blend ?? 'none';\n this._material = new ShaderMaterial({\n name: source.name,\n vertexShader: VERTEX,\n fragmentShader: source.glsl,\n uniforms,\n depthTest: false,\n depthWrite: false,\n transparent: blend !== 'none',\n blending: blend === 'add' ? CustomBlending : blend === 'alpha' ? NormalBlending : NoBlending,\n blendEquation: AddEquation,\n blendSrc: OneFactor,\n blendDst: OneFactor,\n blendSrcAlpha: OneFactor,\n blendDstAlpha: OneFactor,\n toneMapped: false,\n });\n this._mesh = new Mesh(TRIANGLE, this._material);\n this._mesh.frustumCulled = false;\n }\n\n set(name: string, value: PostFXUniformValue): void {\n const holder = this._material.uniforms[name];\n if (holder) assignUniform(holder, value);\n }\n\n draw(target: RenderTarget | null): void {\n const r = this._renderer;\n const autoClear = r.autoClear;\n r.autoClear = false;\n r.setRenderTarget(target as WebGLRenderTarget | null);\n r.render(this._mesh, CAMERA);\n r.autoClear = autoClear;\n }\n\n dispose(): void {\n this._material.dispose();\n }\n}\n\n/** Post-process programs for `THREE.WebGLRenderer`. @internal */\nexport const webglPostFXBackend: PostFXBackend = {\n createProgram: (renderer, source) => new WebGLPostFXProgram(renderer, source),\n};\n", "import { Vector2, Vector3, Vector4 } from 'three';\nimport type { Texture } from 'three';\n\n/**\n * A value a post-process shader uniform takes: a number, a 2-4 component\n * vector (as a three.js vector or an array), or a texture.\n *\n * @group PostFX\n */\nexport type PostFXUniformValue = number | ArrayLike<number> | Vector2 | Vector3 | Vector4 | Texture | null;\n\n/**\n * Store `value` in a uniform holder, keeping the holder's vector instance:\n * a WebGPU uniform node is bound to it.\n * @internal\n */\nexport function assignUniform(holder: { value: unknown }, value: PostFXUniformValue): void {\n const current = holder.value as { fromArray?: (a: ArrayLike<number>) => unknown; copy?: (v: unknown) => unknown };\n if (value === null || typeof value === 'number' || (value as Texture).isTexture) {\n holder.value = value;\n } else if (current && typeof current.fromArray === 'function') {\n if ((value as Vector4).isVector4 || (value as Vector3).isVector3 || (value as Vector2).isVector2) current.copy!(value);\n else current.fromArray(value as ArrayLike<number>);\n } else {\n holder.value = value;\n }\n}\n\n/** The uniforms a shader source declares, by name, with their declared type. @internal */\nexport interface DeclaredUniform {\n name: string;\n type: 'float' | 'int' | 'vec2' | 'vec3' | 'vec4' | 'texture' | 'sampler';\n}\n\n/** A zeroed holder value for a uniform of `type`. @internal */\nexport function initialUniformValue(type: DeclaredUniform['type']): unknown {\n switch (type) {\n case 'vec2': return new Vector2();\n case 'vec3': return new Vector3();\n case 'vec4': return new Vector4();\n case 'texture':\n case 'sampler': return null;\n default: return 0;\n }\n}\n", "import type { Camera, RenderTarget, Scene as ThreeScene, WebGLRenderer, WebGLRenderTarget } from 'three';\n\nimport type { CameraFrame } from './camera-frame';\nimport { BLOOM_DOWNSAMPLE, BLOOM_PREFILTER, BLOOM_UPSAMPLE, composeSource, composeVariantKey, type ComposeVariant } from './frame-shaders';\nimport { ensurePostFXTarget, postFXBackendFor, type PostFXProgram } from './program';\n\n/**\n * The GPU half of a {@link CameraFrame}: the linear scene target, the bloom\n * chain and the compose pass, laid out as PlayCanvas's frame lays them out.\n * @internal\n */\nexport class FrameRenderer {\n private readonly _renderer: WebGLRenderer;\n private _scene: RenderTarget | null = null;\n private _half: RenderTarget | null = null;\n private readonly _levels: RenderTarget[] = [];\n private readonly _compose = new Map<string, PostFXProgram>();\n private _prefilter: PostFXProgram | null = null;\n private _down: PostFXProgram | null = null;\n private _up: PostFXProgram | null = null;\n\n constructor(renderer: WebGLRenderer) {\n this._renderer = renderer;\n }\n\n /** Draw the scene into the linear scene target and return it. */\n renderScene(scene: ThreeScene, camera: Camera, width: number, height: number, samples: number): RenderTarget {\n const r = this._renderer;\n this._scene = ensurePostFXTarget(r, this._scene, width, height, { format: 'hdr', depth: true, samples });\n r.setRenderTarget(this._scene as WebGLRenderTarget);\n r.render(scene, camera);\n return this._scene;\n }\n\n /** Bloom, grade, tone map, vignette and encode the scene target into `target` (`null`: the canvas). */\n compose(frame: CameraFrame, exposure: number, target: RenderTarget | null): void {\n const scene = this._scene;\n if (!scene) return;\n const variant: ComposeVariant = {\n toneMapping: frame.rendering.toneMapping,\n bloom: frame.bloom.intensity > 0,\n grading: frame.grading.enabled,\n vignette: frame.vignette.intensity > 0,\n sharpen: frame.rendering.sharpness > 0,\n };\n const key = composeVariantKey(variant);\n let program = this._compose.get(key);\n if (!program) {\n program = postFXBackendFor(this._renderer).createProgram(this._renderer, composeSource(variant));\n this._compose.set(key, program);\n }\n\n program.set('sceneTexture', scene.texture);\n program.set('sceneTextureInvRes', [1 / scene.width, 1 / scene.height]);\n program.set('exposure', exposure);\n if (variant.bloom) {\n program.set('bloomTexture', this._bloom(scene, frame.bloom.blurLevel));\n program.set('bloomIntensity', frame.bloom.intensity);\n } else {\n this._releaseBloom();\n }\n if (variant.grading) {\n const g = frame.grading;\n program.set('brightnessContrastSaturation', [g.brightness, g.contrast, g.saturation]);\n program.set('tint', [g.tint.r, g.tint.g, g.tint.b]);\n }\n if (variant.vignette) {\n const v = frame.vignette;\n program.set('vignetterParams', [v.inner, v.outer, v.curvature, v.intensity]);\n program.set('vignetteColor', [v.color.r, v.color.g, v.color.b]);\n }\n if (variant.sharpen) {\n // PlayCanvas maps 0..1 onto its CAS weight range.\n program.set('sharpness', -0.125 + (-0.2 + 0.125) * Math.min(1, frame.rendering.sharpness));\n }\n program.draw(target);\n }\n\n /**\n * PlayCanvas's bloom: a half-size copy of the scene, `levels` 13-tap\n * downsamples each half the last, then 9-tap upsamples added back up the\n * chain. Returns the top level, a quarter of the scene's size.\n */\n private _bloom(scene: RenderTarget, blurLevel: number): RenderTarget['texture'] {\n const r = this._renderer;\n const backend = postFXBackendFor(r);\n this._prefilter ??= backend.createProgram(r, BLOOM_PREFILTER);\n this._down ??= backend.createProgram(r, BLOOM_DOWNSAMPLE);\n this._up ??= backend.createProgram(r, BLOOM_UPSAMPLE);\n\n let w = Math.max(1, Math.floor(scene.width / 2));\n let h = Math.max(1, Math.floor(scene.height / 2));\n this._half = ensurePostFXTarget(r, this._half, w, h, { format: 'hdr' });\n const count = Math.min(Math.max(Math.floor(Math.log2(Math.min(w, h))), 1), Math.max(1, Math.floor(blurLevel)));\n for (let i = 0; i < count; i++) {\n w = Math.max(1, Math.floor(w / 2));\n h = Math.max(1, Math.floor(h / 2));\n this._levels[i] = ensurePostFXTarget(r, this._levels[i] ?? null, w, h, { format: 'hdr' });\n }\n for (const rt of this._levels.splice(count)) rt.dispose();\n\n this._prefilter.set('sourceTexture', scene.texture);\n this._prefilter.draw(this._half);\n let source = this._half;\n for (const level of this._levels) {\n this._down.set('sourceTexture', source.texture);\n this._down.set('sourceInvResolution', [1 / source.width, 1 / source.height]);\n this._down.draw(level);\n source = level;\n }\n for (let i = count - 2; i >= 0; i--) {\n const from = this._levels[i + 1];\n this._up.set('sourceTexture', from.texture);\n this._up.set('sourceInvResolution', [1 / from.width, 1 / from.height]);\n this._up.draw(this._levels[i]);\n }\n return this._levels[0].texture;\n }\n\n /** Free the render targets, keeping the compiled programs for when the frame is back. */\n releaseTargets(): void {\n this._scene?.dispose();\n this._scene = null;\n this._releaseBloom();\n }\n\n dispose(): void {\n this.releaseTargets();\n for (const p of this._compose.values()) p.dispose();\n this._prefilter?.dispose();\n this._down?.dispose();\n this._up?.dispose();\n this._compose.clear();\n this._prefilter = this._down = this._up = null;\n }\n\n private _releaseBloom(): void {\n this._half?.dispose();\n this._half = null;\n for (const rt of this._levels) rt.dispose();\n this._levels.length = 0;\n }\n}\n", "import type { RenderTarget, WebGLRenderer } from 'three';\n\nimport type { Scene } from '../../scene';\n\nimport { CameraFrame } from './camera-frame';\nimport { FrameRenderer } from './frame-renderer';\nimport { ensurePostFXTarget } from './program';\n\n/**\n * A post-process effect {@link PostFX} runs. The three.js counterpart of the\n * PlayCanvas build's `PostFXPass`, with the same lifecycle names so a pass\n * ported from there keeps its overrides.\n *\n * A *capturing* pass reads the full picture the stage before it produced and\n * writes a new one: the first capturing pass reads the scene as the\n * {@link CameraFrame} composed it, each later one the output of the one\n * before, and the last writes the canvas. A non-capturing pass draws nothing;\n * it changes the frame's settings in {@link install} and puts them back in\n * {@link uninstall}.\n *\n * Lifecycle: {@link configureFrame} once when added, then {@link install};\n * {@link render} every frame (capturing passes); {@link uninstall} when\n * removed. Render targets are PostFX's, handed over per frame in a\n * {@link PostFXRenderContext}, so a pass has nothing to reallocate on resize.\n *\n * @group PostFX\n */\nexport interface PostFXPass {\n /** True for a pass that reads the picture so far and writes a new one. */\n readonly capturesScene?: boolean;\n\n /** Request frame features before {@link install}. Runs once, when the pass is added. */\n configureFrame?(scene: Scene, config: PostFXFrameConfig): void;\n\n /**\n * First capturing pass only: the size of the target the frame composes the\n * scene into, given the canvas size. The scene itself renders at that size\n * times `rendering.renderTargetScale`. Default: the canvas size.\n */\n getSceneCaptureSize?(width: number, height: number): { width: number; height: number };\n\n /** Set the pass up. `ctx.frame` is live here for passes that tune it. */\n install(scene: Scene, ctx: PostFXInstallContext): void;\n\n /** Undo {@link install}. The pass may be installed again afterwards. */\n uninstall(scene: Scene): void;\n\n /** Capturing passes: draw `ctx.inputTarget` into `ctx.outputTarget`. */\n render?(ctx: PostFXRenderContext): void;\n}\n\n/**\n * What {@link PostFXPass.install} receives.\n *\n * @group PostFX\n */\nexport interface PostFXInstallContext {\n /** The scene's frame; null unless the app or a pass ({@link PostFXFrameConfig}) asked for one. */\n frame: CameraFrame | null;\n}\n\n/**\n * What a capturing pass's {@link PostFXPass.render} receives each frame.\n *\n * @group PostFX\n */\nexport interface PostFXRenderContext {\n /** The scene's renderer, a `THREE.WebGLRenderer` or a `WebGPURenderer`. */\n readonly renderer: WebGLRenderer;\n /** The scene's frame, or null. */\n readonly frame: CameraFrame | null;\n /** The picture so far: 8-bit display colour. Its size is the capture size for the first pass, the canvas's after. */\n readonly inputTarget: RenderTarget;\n /** Where to write: another 8-bit target, or `null` for the canvas. */\n readonly outputTarget: RenderTarget | null;\n /** Size of the output in pixels. */\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Frame features a pass asks for in {@link PostFXPass.configureFrame}. Either\n * one realizes the scene's {@link CameraFrame}, as in the PlayCanvas build;\n * both stay set once set.\n *\n * @group PostFX\n */\nexport interface PostFXFrameConfig {\n /** Kept for PlayCanvas parity, where it asks for a scene depth prepass: here it realizes the frame. */\n sceneDepthMap?: boolean;\n /** Realize the frame, for a pass that relies on its tone mapping, bloom, grading or vignette. */\n requireFrame?: boolean;\n}\n\n/**\n * Something drawn over the scene before the frame composes it, such as an\n * outline. Unlike a pass, an overlay alone keeps the scene on the direct path.\n * @internal\n */\nexport interface PostFXOverlay {\n /** Draw over the scene in `target` (`null`: the canvas), `width` x `height` pixels. */\n renderOverlay(target: RenderTarget | null, width: number, height: number): void;\n}\n\n/** Frame settings for a chain no one asked a frame for: tone mapping off, nothing else. */\nconst DEFAULT_FRAME = new CameraFrame();\n\n/**\n * Post-processing for a {@link Scene}: the scene's {@link CameraFrame} and a\n * chain of {@link PostFXPass}es between the scene render and the canvas.\n * Always present as `scene.postfx`. Empty, it costs nothing: the scene\n * renders straight to the canvas.\n *\n * ```ts\n * const pixelart = scene.postfx.add(new PixelartEffect({ scale: 3 }));\n * const film = scene.postfx.add(new FilmPass()); // chains after pixelart\n * ```\n *\n * @group PostFX\n */\nexport class PostFX {\n private readonly _scene: Scene;\n private readonly _passes: PostFXPass[] = [];\n private readonly _config: PostFXFrameConfig = {};\n private readonly _overlays = new Set<PostFXOverlay>();\n private _frameRenderer: FrameRenderer | null = null;\n private _capture: RenderTarget | null = null;\n private readonly _chain: RenderTarget[] = [];\n private _width = 1;\n private _height = 1;\n\n constructor(scene: Scene) {\n this._scene = scene;\n }\n\n /** The camera's built-in effects, once {@link getOrCreateCameraFrame} has created them. */\n cameraFrame: CameraFrame | null = null;\n\n /** Whether anything sits between the scene render and the canvas. */\n get active(): boolean {\n return this.cameraFrame !== null || this._passes.length > 0;\n }\n\n /** The passes, in the order they run. */\n get passes(): readonly PostFXPass[] {\n return this._passes;\n }\n\n /** The scene camera's {@link CameraFrame}, created on first call. */\n getOrCreateCameraFrame(): CameraFrame {\n return (this.cameraFrame ??= new CameraFrame());\n }\n\n /** Drop the {@link CameraFrame}, and every effect it applied. */\n destroyCameraFrame(): void {\n this.cameraFrame = null;\n this._releaseIfIdle();\n }\n\n /** Add a pass at the end of the chain. Returns it, for keeping a handle. */\n add<T extends PostFXPass>(pass: T): T {\n if (this._passes.includes(pass)) return pass;\n pass.configureFrame?.(this._scene, this._config);\n if (this._config.requireFrame || this._config.sceneDepthMap) this.getOrCreateCameraFrame();\n this._passes.push(pass);\n pass.install(this._scene, { frame: this.cameraFrame });\n return pass;\n }\n\n /** Take a pass out of the chain. No-op when it is not in it. */\n remove(pass: PostFXPass): void {\n const i = this._passes.indexOf(pass);\n if (i < 0) return;\n this._passes.splice(i, 1);\n pass.uninstall(this._scene);\n this._releaseIfIdle();\n }\n\n /** Whether `pass` is in the chain. */\n has(pass: PostFXPass): boolean {\n return this._passes.includes(pass);\n }\n\n /** @internal */\n addOverlay(overlay: PostFXOverlay): void {\n this._overlays.add(overlay);\n }\n\n /** @internal */\n removeOverlay(overlay: PostFXOverlay): void {\n this._overlays.delete(overlay);\n }\n\n /** Draw one frame: the scene, then every pass. Called by the scene's loop. @internal */\n render(): void {\n const scene = this._scene;\n const renderer = scene.renderer;\n if (!this.active) {\n renderer.render(scene.threeScene, scene.camera);\n for (const overlay of this._overlays) overlay.renderOverlay(null, this._width, this._height);\n return;\n }\n\n const frame = this.cameraFrame;\n const capturing = this._passes.filter((p) => p.capturesScene && p.render);\n const width = this._width;\n const height = this._height;\n const capture = capturing[0]?.getSceneCaptureSize?.(width, height) ?? { width, height };\n const scale = frame?.rendering.renderTargetScale ?? 1;\n const fr = (this._frameRenderer ??= new FrameRenderer(renderer));\n\n // The background is a linear value in the frame's target, as it is in\n // PlayCanvas's frame; straight to the canvas it is display colour.\n scene.useLinearClearColor(true);\n const sceneTarget = fr.renderScene(\n scene.threeScene, scene.camera,\n Math.max(1, Math.floor(capture.width * scale)), Math.max(1, Math.floor(capture.height * scale)),\n frame?.rendering.samples ?? 1,\n );\n scene.useLinearClearColor(false);\n for (const overlay of this._overlays) overlay.renderOverlay(sceneTarget, sceneTarget.width, sceneTarget.height);\n\n let input: RenderTarget | null = null;\n if (capturing.length > 0) {\n this._capture = ensurePostFXTarget(renderer, this._capture, capture.width, capture.height, { format: 'ldr' });\n input = this._capture;\n }\n fr.compose(frame ?? DEFAULT_FRAME, renderer.toneMappingExposure, input);\n\n for (let i = 0; i < capturing.length; i++) {\n let output: RenderTarget | null = null;\n if (i < capturing.length - 1) {\n this._chain[i] = ensurePostFXTarget(renderer, this._chain[i] ?? null, width, height, { format: 'ldr' });\n output = this._chain[i];\n }\n capturing[i].render!({\n renderer, frame, inputTarget: input!, outputTarget: output,\n width: output?.width ?? width, height: output?.height ?? height,\n });\n input = output;\n }\n for (const rt of this._chain.splice(Math.max(0, capturing.length - 1))) rt.dispose();\n renderer.setRenderTarget(null);\n }\n\n /** The drawing buffer changed size. Called by the scene. @internal */\n resize(width: number, height: number): void {\n this._width = Math.max(1, width);\n this._height = Math.max(1, height);\n }\n\n /** Tear everything down. Called by {@link Scene.destroy}. @internal */\n destroyAll(): void {\n for (let i = this._passes.length - 1; i >= 0; i--) {\n try { this._passes[i].uninstall(this._scene); } catch { /* keep tearing down */ }\n }\n this._passes.length = 0;\n this._overlays.clear();\n this.cameraFrame = null;\n this._releaseIfIdle();\n this._frameRenderer?.dispose();\n this._frameRenderer = null;\n }\n\n // Back on the direct path, the targets in between would only hold memory.\n private _releaseIfIdle(): void {\n if (this.active) return;\n this._frameRenderer?.releaseTargets();\n this._capture?.dispose();\n this._capture = null;\n for (const rt of this._chain) rt.dispose();\n this._chain.length = 0;\n }\n}\n", "import { Object3D, Vector3 } from 'three';\n\nimport { ammo } from './ammo';\nimport type {\n AmmoDispatcher,\n AmmoDynamicsWorld,\n AmmoManifold,\n AmmoNS,\n AmmoQuat,\n AmmoRayCallback,\n AmmoTransform,\n AmmoVec3,\n} from './ammo';\nimport { RigidBody } from './rigid-body';\nimport type { BodyHost, BodyPairEvent, ContactPoint, ContactResult, RigidBodyOptions, XYZ } from './rigid-body';\n\n/**\n * Options for {@link PhysicsWorld.raycastFirst} / {@link PhysicsWorld.raycastAll}.\n * PlayCanvas's raycast options, with `filterTags` dropped (three.js objects\n * have no tags; use `filterCallback`).\n *\n * @group Physics\n */\nexport interface RaycastOptions {\n /** The ray's own collision group. Bodies whose mask excludes it are not hit. */\n filterCollisionGroup?: number;\n /** Groups the ray can hit. */\n filterCollisionMask?: number;\n /** Return `false` to skip a body. */\n filterCallback?: (body: RigidBody) => boolean;\n /** `raycastAll` only: sort hits nearest first. Default `false`. */\n sort?: boolean;\n}\n\n/**\n * One ray hit. PlayCanvas's `RaycastResult`, with `entity` \u2192 `object`.\n *\n * @group Physics\n */\nexport interface RaycastResult {\n /** The hit body's object. */\n object: Object3D;\n body: RigidBody;\n /** World-space hit point. */\n point: Vector3;\n /** World-space surface normal at the hit. */\n normal: Vector3;\n /** Where along the ray the hit is, 0 at `start` to 1 at `end`. */\n hitFraction: number;\n}\n\n/** Something tied to two bodies that must go before either does (a joint). @internal */\nexport interface BodyAttachment {\n readonly bodyA: RigidBody;\n readonly bodyB: RigidBody;\n remove(): void;\n /** One of the bodies is about to free its native object. */\n suspend(): void;\n /** That body has its new native object. */\n resume(): void;\n}\n\ninterface QueuedEvent { target: RigidBody; event: { type: string } & (ContactResult | BodyPairEvent) }\n\n/**\n * Ammo (Bullet) rigid-body physics for a {@link Scene}, which steps it every\n * frame before characters update. Create the scene with\n * `Scene.create(canvas, { physics: { loadAmmo } })` and use `scene.physics`.\n * The engine does not ship Ammo: the game loads it, and this class reads\n * `globalThis.Ammo`.\n *\n * Bodies attach to `THREE.Object3D`s ({@link addBody}); a dynamic body moves\n * its object, a kinematic one follows it. Stepping, interpolation, collision\n * groups, events and raycasts behave as PlayCanvas's `rigidbody` system, so\n * game code maps across almost name for name:\n *\n * | PlayCanvas | here |\n * |---------------------------------------------------------|---------------------------------------------------|\n * | `e.addComponent('collision', shape)` + `e.addComponent('rigidbody', opts)` | `physics.addBody(object, { shape, ...opts })` |\n * | `e.addComponent('collision', shape)` alone (a trigger) | `physics.addBody(object, { shape, trigger: true })` |\n * | `collision.linearOffset` / `angularOffset` | `linearOffset` / `angularOffset` options |\n * | `{ type: 'mesh', model }` | `{ type: 'mesh', geometry: object3DOrGeometry }` |\n * | `e.rigidbody` | `physics.getBody(object)` |\n * | `e.rigidbody.body` (btRigidBody) | `body.ammoBody` |\n * | `e.removeComponent('rigidbody')` / `e.destroy()` | `physics.removeBody(body)` |\n * | `rb.applyForce(x, y, z)` / `applyImpulse(v, p)` | `body.applyForce(vec)` / `applyImpulse(vec, p)` - vectors only |\n * | `rb.applyTorque` / `applyTorqueImpulse` | same |\n * | `rb.linearVelocity` / `angularVelocity` (get / set) | same, `THREE.Vector3` |\n * | `rb.teleport(pos, rot)` | `body.teleport(pos, quatOrEuler)` - Euler in radians |\n * | `rb.type` / `mass` / `friction` / `restitution` / `linearDamping` / `angularDamping` / `linearFactor` / `angularFactor` / `gravityScale` / `group` / `mask` / `enabled` | same |\n * | `rb.activate()` / `isActive()` | same |\n * | `rb.on('collisionstart', (r: ContactResult) => \u2026)` | `body.addEventListener('collisionstart', (r) => \u2026)`; `r.other` is the Object3D |\n * | `collisionend` / `contact` / `triggerenter` / `triggerleave` | same names |\n * | `app.systems.rigidbody.raycastFirst(a, b, opts)` | `physics.raycastFirst(a, b, opts)`; `hit.entity` \u2192 `hit.object` |\n * | `app.systems.rigidbody.raycastAll(a, b, opts)` | `physics.raycastAll(a, b, opts)` |\n * | `app.systems.rigidbody.gravity` | `physics.gravity` (mutable `THREE.Vector3`) |\n * | `app.systems.rigidbody.fixedTimeStep` / `maxSubSteps` | same |\n * | `app.systems.rigidbody.dynamicsWorld` | `physics.dynamicsWorld` |\n * | `BODYTYPE_STATIC` / `DYNAMIC` / `KINEMATIC` | `'static'` / `'dynamic'` / `'kinematic'` |\n * | `BODYGROUP_*` / `BODYMASK_*` | same names and values, exported from this package |\n *\n * @group Physics\n */\nexport class PhysicsWorld {\n /** World gravity, m/s\u00B2. Mutate it freely; it is applied at the next step. */\n readonly gravity = new Vector3(0, -9.81, 0);\n /** Simulation step, seconds. Frames are cut into steps of this size. Default `1/60`. */\n fixedTimeStep = 1 / 60;\n /** Most fixed steps one frame may take before time is dropped. Default `10`. */\n maxSubSteps = 10;\n /** Multiplier on frame time; `0` pauses the simulation. Default `1`. */\n timeScale = 1;\n /** The Bullet `btDiscreteDynamicsWorld`, for raw constraints. */\n readonly dynamicsWorld: AmmoDynamicsWorld;\n\n private readonly _A: AmmoNS;\n private readonly _collisionConfiguration: unknown;\n private readonly _dispatcher: AmmoDispatcher;\n private readonly _broadphase: unknown;\n private readonly _solver: unknown;\n private readonly _host: BodyHost;\n private readonly _appliedGravity = new Vector3();\n private readonly _btVec1: AmmoVec3;\n private readonly _btVec2: AmmoVec3;\n private readonly _btQuat: AmmoQuat;\n private readonly _btTransform: AmmoTransform;\n\n private _nextId = 1;\n private readonly _bodies = new Map<number, RigidBody>();\n private readonly _byObject = new WeakMap<Object3D, RigidBody>();\n private readonly _dynamic = new Set<RigidBody>();\n private readonly _kinematic = new Set<RigidBody>();\n private readonly _triggers = new Set<RigidBody>();\n private readonly _attachments = new Set<BodyAttachment>();\n\n /** body \u2192 the bodies it is touching (or overlapping, for a trigger) as of the last sub-step. */\n private readonly _collisions = new Map<RigidBody, Set<RigidBody>>();\n private readonly _frameCollisions = new Map<RigidBody, Set<RigidBody>>();\n private readonly _queue: QueuedEvent[] = [];\n private readonly _worldPointer: number = 0;\n private readonly _tickDispatcher: TickDispatcher | null = null;\n private _destroyed = false;\n\n /**\n * Await the game's Ammo loader (when given) and build a world. Throws when\n * `globalThis.Ammo` is still not set.\n */\n static async create(opts: true | { loadAmmo: () => Promise<void> }): Promise<PhysicsWorld> {\n if (typeof opts === 'object' && opts.loadAmmo) await opts.loadAmmo();\n return new PhysicsWorld();\n }\n\n /** Build a world on the already-loaded `globalThis.Ammo`. {@link Scene.create} does this for you. */\n constructor() {\n const A = ammo();\n this._A = A;\n this._collisionConfiguration = new A.btDefaultCollisionConfiguration();\n this._dispatcher = new A.btCollisionDispatcher(this._collisionConfiguration);\n this._broadphase = new A.btDbvtBroadphase();\n this._solver = new A.btSequentialImpulseConstraintSolver();\n this.dynamicsWorld = new A.btDiscreteDynamicsWorld(\n this._dispatcher, this._broadphase, this._solver, this._collisionConfiguration,\n );\n this._btVec1 = new A.btVector3();\n this._btVec2 = new A.btVector3();\n this._btQuat = new A.btQuaternion(0, 0, 0, 1);\n this._btTransform = new A.btTransform();\n\n this._appliedGravity.copy(this.gravity);\n this._btVec1.setValue(this.gravity.x, this.gravity.y, this.gravity.z);\n this.dynamicsWorld.setGravity(this._btVec1);\n\n // Walk contacts after every fixed sub-step, as PlayCanvas does, so a brief\n // touch inside a long frame still starts and ends a collision. Builds\n // without the tick callback fall back to one walk per frame.\n const tick = getTickDispatcher(A);\n if (tick && this.dynamicsWorld.setInternalTickCallback) {\n this._worldPointer = A.getPointer(this.dynamicsWorld);\n tick.worlds.set(this._worldPointer, this);\n this._tickDispatcher = tick;\n this.dynamicsWorld.setInternalTickCallback(tick.pointer);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const world = this;\n this._host = {\n world,\n gravity: this.gravity,\n native: this.dynamicsWorld,\n btVec1: this._btVec1,\n btVec2: this._btVec2,\n btQuat: this._btQuat,\n btTransform: this._btTransform,\n simulationChanged: (body, inWorld) => world._simulationChanged(body, inWorld),\n nativeReplacing: (body, done) => world._nativeReplacing(body, done),\n };\n }\n\n // \u2500\u2500 Bodies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Give `object` a rigid body, placed at the object's current world pose.\n * One body per object; throws if it already has one. Put the object in the\n * scene graph first if it has a parent, so its world pose is known.\n */\n addBody(object: Object3D, opts: RigidBodyOptions): RigidBody {\n this._assertAlive();\n if (this._byObject.has(object)) {\n throw new Error(`[PhysicsWorld] '${object.name}' already has a rigid body; removeBody it first.`);\n }\n const id = this._nextId++;\n const body = new RigidBody(this._host, id, object, opts);\n this._bodies.set(id, body);\n this._byObject.set(object, body);\n return body;\n }\n\n /** The body {@link addBody} gave `object`, or `null`. */\n getBody(object: Object3D): RigidBody | null {\n return this._byObject.get(object) ?? null;\n }\n\n /** Every live body, in creation order. */\n get bodies(): IterableIterator<RigidBody> {\n return this._bodies.values();\n }\n\n /**\n * Take a body (or the body on an object) out of the world and free it.\n * Joints made with this module's joint helpers that use it go first. The\n * object itself is left where it is. Idempotent.\n */\n removeBody(target: RigidBody | Object3D): void {\n const body = target instanceof RigidBody ? target : this._byObject.get(target);\n if (!body || this._bodies.get(body._id) !== body) return;\n for (const a of Array.from(this._attachments)) {\n if (a.bodyA === body || a.bodyB === body) a.remove();\n }\n this._forgetCollisions(body);\n body._destroy();\n this._bodies.delete(body._id);\n this._byObject.delete(body.object);\n }\n\n /** @internal Joints register so they are removed before the bodies they hold. */\n _attach(a: BodyAttachment): void {\n this._attachments.add(a);\n }\n\n /** @internal */\n _detach(a: BodyAttachment): void {\n this._attachments.delete(a);\n }\n\n // \u2500\u2500 Queries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** The nearest body the segment `start` \u2192 `end` hits, or `null`. */\n raycastFirst(start: XYZ, end: XYZ, options: RaycastOptions = {}): RaycastResult | null {\n if (options.filterCallback) {\n let closest: RaycastResult | null = null;\n for (const r of this.raycastAll(start, end, options)) {\n if (!closest || r.hitFraction < closest.hitFraction) closest = r;\n }\n return closest;\n }\n const A = this._A;\n const from = new A.btVector3(start.x, start.y, start.z);\n const to = new A.btVector3(end.x, end.y, end.z);\n const cb = new A.ClosestRayResultCallback(from, to);\n applyRayOptions(cb, options);\n this.dynamicsWorld.rayTest(from, to, cb);\n let result: RaycastResult | null = null;\n if (cb.hasHit()) {\n const body = this._bodyFromNative(cb.get_m_collisionObject());\n if (body) {\n const p = cb.get_m_hitPointWorld();\n const n = cb.get_m_hitNormalWorld();\n result = {\n object: body.object,\n body,\n point: new Vector3(p.x(), p.y(), p.z()),\n normal: new Vector3(n.x(), n.y(), n.z()),\n hitFraction: cb.get_m_closestHitFraction(),\n };\n }\n }\n A.destroy(cb);\n A.destroy(from);\n A.destroy(to);\n return result;\n }\n\n /** Every body the segment `start` \u2192 `end` hits. Unordered unless `options.sort`. */\n raycastAll(start: XYZ, end: XYZ, options: RaycastOptions = {}): RaycastResult[] {\n const A = this._A;\n const from = new A.btVector3(start.x, start.y, start.z);\n const to = new A.btVector3(end.x, end.y, end.z);\n const cb = new A.AllHitsRayResultCallback(from, to);\n applyRayOptions(cb, options);\n this.dynamicsWorld.rayTest(from, to, cb);\n const results: RaycastResult[] = [];\n if (cb.hasHit()) {\n const objs = cb.get_m_collisionObjects();\n const points = cb.get_m_hitPointWorld();\n const normals = cb.get_m_hitNormalWorld();\n const fractions = cb.get_m_hitFractions();\n for (let i = 0, n = objs.size(); i < n; i++) {\n const body = this._bodyFromNative(objs.at(i));\n if (!body) continue;\n if (options.filterCallback && !options.filterCallback(body)) continue;\n const p = points.at(i);\n const nn = normals.at(i);\n results.push({\n object: body.object,\n body,\n point: new Vector3(p.x(), p.y(), p.z()),\n normal: new Vector3(nn.x(), nn.y(), nn.z()),\n hitFraction: fractions.at(i),\n });\n }\n }\n A.destroy(cb);\n A.destroy(from);\n A.destroy(to);\n if (options.sort) results.sort((a, b) => a.hitFraction - b.hitFraction);\n return results;\n }\n\n // \u2500\u2500 Stepping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Advance the simulation by `dt` seconds, in {@link fixedTimeStep} steps,\n * then move dynamic objects to their (interpolated) bodies and dispatch\n * collision events. {@link Scene} calls this every frame before characters\n * update; call it yourself only on a world you drive by hand.\n */\n step(dt: number): void {\n if (this._destroyed || !(this.timeScale > 0)) return;\n if (!this._appliedGravity.equals(this.gravity)) {\n this._appliedGravity.copy(this.gravity);\n this._btVec1.setValue(this.gravity.x, this.gravity.y, this.gravity.z);\n this.dynamicsWorld.setGravity(this._btVec1);\n for (const b of this._dynamic) b._onGravityChanged();\n }\n for (const b of this._triggers) b._updateTrigger();\n for (const b of this._kinematic) b._updateKinematic();\n this.dynamicsWorld.stepSimulation(dt * this.timeScale, this.maxSubSteps, this.fixedTimeStep);\n for (const b of this._dynamic) b._updateDynamic();\n if (!this._tickDispatcher) this._walkContacts();\n this._flushEvents();\n }\n\n /** Free every body, joint and the world. {@link Scene.destroy} calls it. */\n destroy(): void {\n if (this._destroyed) return;\n for (const a of Array.from(this._attachments)) a.remove();\n for (const body of Array.from(this._bodies.values())) this.removeBody(body);\n this._destroyed = true;\n if (this._tickDispatcher) this._tickDispatcher.worlds.delete(this._worldPointer);\n const A = this._A;\n A.destroy(this.dynamicsWorld);\n A.destroy(this._solver);\n A.destroy(this._broadphase);\n A.destroy(this._dispatcher);\n A.destroy(this._collisionConfiguration);\n A.destroy(this._btVec1);\n A.destroy(this._btVec2);\n A.destroy(this._btQuat);\n A.destroy(this._btTransform);\n this._queue.length = 0;\n this._collisions.clear();\n }\n\n // \u2500\u2500 Internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _assertAlive(): void {\n if (this._destroyed) throw new Error('[PhysicsWorld] the world has been destroyed.');\n }\n\n private _simulationChanged(body: RigidBody, inWorld: boolean): void {\n const list = body.isTrigger ? this._triggers : body.type === 'dynamic' ? this._dynamic\n : body.type === 'kinematic' ? this._kinematic : null;\n // A type change re-adds the body, so clear it from every list first.\n this._dynamic.delete(body);\n this._kinematic.delete(body);\n this._triggers.delete(body);\n // Contacts are kept, as PlayCanvas keeps them: a body leaving the world\n // ends its pairs on the next step (collisionend / triggerleave), and one\n // re-added while still touching does not start them again.\n if (inWorld) list?.add(body);\n }\n\n /**\n * `body` frees and re-creates its btRigidBody inside `replace`: the joints\n * that hold it let go first and are re-made against the new one after.\n */\n private _nativeReplacing(body: RigidBody, replace: () => void): void {\n const held = Array.from(this._attachments).filter((a) => a.bodyA === body || a.bodyB === body);\n for (const a of held) a.suspend();\n replace();\n for (const a of held) if (this._attachments.has(a)) a.resume();\n }\n\n private _bodyFromNative(obj: unknown): RigidBody | null {\n const A = this._A;\n const rb = A.castObject(obj, A.btRigidBody);\n return this._bodies.get(rb.getUserIndex()) ?? null;\n }\n\n /**\n * Drop a body's own contact bookkeeping. Bodies it was touching keep it in\n * theirs, so the next sub-step ends those collisions and they get their\n * `collisionend` / `triggerleave`, as in PlayCanvas.\n */\n private _forgetCollisions(body: RigidBody): void {\n this._collisions.delete(body);\n }\n\n /**\n * Read this sub-step's contact manifolds into events. PlayCanvas's\n * `onContactPair` logic: contact points are gathered only for bodies with\n * listeners, a pair is new if it was not touching last sub-step, and a pair\n * that stopped touching ends. Events are queued, not fired, because this\n * may run inside Bullet's step, where a listener removing a body would\n * free memory the solver is still using.\n * @internal\n */\n _walkContacts(): void {\n const frame = this._frameCollisions;\n frame.clear();\n const d = this._dispatcher;\n const n = d.getNumManifolds();\n for (let i = 0; i < n; i++) {\n const m = d.getManifoldByIndexInternal(i);\n const count = m.getNumContacts();\n if (count <= 0) continue;\n const b0 = this._bodyFromNative(m.getBody0());\n const b1 = this._bodyFromNative(m.getBody1());\n if (!b0 || !b1) continue;\n if (b0.isTrigger || b1.isTrigger) {\n if (b0.isTrigger && b1.isTrigger) continue;\n const trigger = b0.isTrigger ? b0 : b1;\n const other = trigger === b0 ? b1 : b0;\n if (this._store(trigger, other)) {\n this._enqueue(trigger, 'triggerenter', { other: other.object, otherBody: other });\n this._enqueue(other, 'triggerenter', { other: trigger.object, otherBody: trigger });\n }\n continue;\n }\n const w0 = b0._wantsContacts();\n const w1 = b1._wantsContacts();\n if (!w0 && !w1) continue;\n const forward: ContactPoint[] = [];\n const reverse: ContactPoint[] = [];\n for (let j = 0; j < count; j++) readContact(m, j, forward, reverse);\n if (w0) {\n const r: ContactResult = { other: b1.object, otherBody: b1, contacts: forward };\n const isNew = this._store(b0, b1);\n this._enqueue(b0, 'contact', r);\n if (isNew) this._enqueue(b0, 'collisionstart', r);\n }\n if (w1) {\n const r: ContactResult = { other: b0.object, otherBody: b0, contacts: reverse };\n const isNew = this._store(b1, b0);\n this._enqueue(b1, 'contact', r);\n if (isNew) this._enqueue(b1, 'collisionstart', r);\n }\n }\n\n for (const [body, others] of this._collisions) {\n const seen = frame.get(body);\n for (const other of others) {\n if (seen?.has(other)) continue;\n others.delete(other);\n if (body.isTrigger) {\n this._enqueue(body, 'triggerleave', { other: other.object, otherBody: other });\n this._enqueue(other, 'triggerleave', { other: body.object, otherBody: body });\n } else {\n this._enqueue(body, 'collisionend', { other: other.object, otherBody: other });\n }\n }\n if (others.size === 0) this._collisions.delete(body);\n }\n }\n\n /** Record `body` touching `other` this sub-step; true if it was not touching last time. */\n private _store(body: RigidBody, other: RigidBody): boolean {\n let set = this._frameCollisions.get(body);\n if (!set) this._frameCollisions.set(body, set = new Set());\n set.add(other);\n let prev = this._collisions.get(body);\n if (!prev) this._collisions.set(body, prev = new Set());\n if (prev.has(other)) return false;\n prev.add(other);\n return true;\n }\n\n private _enqueue(target: RigidBody, type: string, payload: ContactResult | BodyPairEvent): void {\n this._queue.push({ target, event: { type, ...payload } });\n }\n\n private _flushEvents(): void {\n const q = this._queue;\n if (q.length === 0) return;\n const events = q.splice(0, q.length);\n for (const { target, event } of events) {\n // A listener earlier in the batch may have removed either body. An end\n // event still reaches the survivor: the other body going away is what\n // ended it.\n if (!target.ammoBody) continue;\n const ending = event.type === 'collisionend' || event.type === 'triggerleave';\n if (!ending && !(event as unknown as BodyPairEvent).otherBody.ammoBody) continue;\n (target as unknown as { dispatchEvent(e: { type: string }): void }).dispatchEvent(event);\n }\n }\n}\n\nfunction applyRayOptions(cb: AmmoRayCallback, options: RaycastOptions): void {\n if (typeof options.filterCollisionGroup === 'number') cb.set_m_collisionFilterGroup(options.filterCollisionGroup);\n if (typeof options.filterCollisionMask === 'number') cb.set_m_collisionFilterMask(options.filterCollisionMask);\n}\n\nfunction readContact(m: AmmoManifold, j: number, forward: ContactPoint[], reverse: ContactPoint[]): void {\n const cp = m.getContactPoint(j);\n const la = cp.get_m_localPointA();\n const lb = cp.get_m_localPointB();\n const pa = cp.getPositionWorldOnA();\n const pb = cp.getPositionWorldOnB();\n const nb = cp.get_m_normalWorldOnB();\n const impulse = cp.getAppliedImpulse();\n const localA = new Vector3(la.x(), la.y(), la.z());\n const localB = new Vector3(lb.x(), lb.y(), lb.z());\n const pointA = new Vector3(pa.x(), pa.y(), pa.z());\n const pointB = new Vector3(pb.x(), pb.y(), pb.z());\n const normal = new Vector3(nb.x(), nb.y(), nb.z());\n forward.push({ localPoint: localA, localPointOther: localB, point: pointA, pointOther: pointB, normal, impulse });\n reverse.push({\n localPoint: localB.clone(), localPointOther: localA.clone(),\n point: pointB.clone(), pointOther: pointA.clone(),\n normal: normal.clone().negate(), impulse,\n });\n}\n\n// \u2500\u2500 Internal tick callback \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface TickDispatcher { pointer: number; worlds: Map<number, PhysicsWorld> }\n\nconst tickDispatchers = new WeakMap<AmmoNS, TickDispatcher | null>();\n\n/**\n * One Emscripten function pointer per Ammo instance, routing Bullet's\n * internal tick callback to the world it came from. Function-table slots are\n * a scarce resource in an Emscripten build, so worlds share it. `null` when\n * the build cannot add functions.\n */\nfunction getTickDispatcher(A: AmmoNS): TickDispatcher | null {\n if (tickDispatchers.has(A)) return tickDispatchers.get(A)!;\n let dispatcher: TickDispatcher | null = null;\n if (A.addFunction) {\n try {\n const worlds = new Map<number, PhysicsWorld>();\n const pointer = A.addFunction((worldPointer: number) => worlds.get(worldPointer)?._walkContacts(), 'vif');\n dispatcher = { pointer, worlds };\n } catch {\n dispatcher = null;\n }\n }\n tickDispatchers.set(A, dispatcher);\n return dispatcher;\n}\n", "// Minimal ambient typing for the Ammo (Bullet) surface the physics module\n// calls. The full Emscripten typings (kripken/ammo.js) are a large dependency\n// for a handful of methods, and the games ship their own Ammo build, so type\n// only what is used here; everything else stays `unknown`.\n//\n// Methods some Ammo builds lack are marked optional and feature-tested at the\n// call site. The build the games ship (test-assets/ammo) has no\n// `btTypedConstraint.getAppliedImpulse`, no `btScaledBvhTriangleMeshShape`\n// and no `btRigidBody.setInterpolationWorldTransform`.\n\n/** @internal */\nexport interface AmmoVec3 {\n x(): number; y(): number; z(): number;\n setValue(x: number, y: number, z: number): void;\n op_mul(s: number): AmmoVec3;\n}\n\n/** @internal */\nexport interface AmmoQuat {\n x(): number; y(): number; z(): number; w(): number;\n setValue(x: number, y: number, z: number, w: number): void;\n}\n\n/** @internal */\nexport interface AmmoTransform {\n setIdentity(): void;\n setOrigin(v: AmmoVec3): void;\n setRotation(q: AmmoQuat): void;\n getOrigin(): AmmoVec3;\n getRotation(): AmmoQuat;\n}\n\n/** @internal */\nexport interface AmmoMotionState {\n getWorldTransform(out: AmmoTransform): void;\n setWorldTransform(t: AmmoTransform): void;\n}\n\n/** @internal */\nexport interface AmmoShape {\n calculateLocalInertia(mass: number, out: AmmoVec3): void;\n setMargin(m: number): void;\n}\n\n/** @internal */\nexport interface AmmoConvexHull extends AmmoShape {\n addPoint(p: AmmoVec3, recalcAabb?: boolean): void;\n recalcLocalAabb(): void;\n}\n\n/** @internal */\nexport interface AmmoTriangleMesh {\n addTriangle(a: AmmoVec3, b: AmmoVec3, c: AmmoVec3, removeDuplicateVertices?: boolean): void;\n}\n\n/** A `btRigidBody`. Games reach it through {@link RigidBody.ammoBody} for CCD and raw constraints. @group Physics */\nexport interface AmmoRigidBody {\n setUserIndex(i: number): void;\n getUserIndex(): number;\n setFriction(v: number): void;\n setRollingFriction(v: number): void;\n setRestitution(v: number): void;\n setDamping(linear: number, angular: number): void;\n setLinearFactor(v: AmmoVec3): void;\n setAngularFactor(v: AmmoVec3): void;\n setGravity(v: AmmoVec3): void;\n getFlags?(): number;\n setFlags?(f: number): void;\n setLinearVelocity(v: AmmoVec3): void;\n getLinearVelocity(): AmmoVec3;\n setAngularVelocity(v: AmmoVec3): void;\n getAngularVelocity(): AmmoVec3;\n getCollisionShape(): AmmoShape;\n setMassProps(mass: number, inertia: AmmoVec3): void;\n updateInertiaTensor(): void;\n isActive(): boolean;\n activate(force?: boolean): void;\n setWorldTransform(t: AmmoTransform): void;\n getWorldTransform(): AmmoTransform;\n getMotionState(): AmmoMotionState | null;\n getCollisionFlags(): number;\n setCollisionFlags(f: number): void;\n setActivationState(s: number): void;\n forceActivationState(s: number): void;\n applyForce(force: AmmoVec3, relPos: AmmoVec3): void;\n applyImpulse(impulse: AmmoVec3, relPos: AmmoVec3): void;\n applyTorque(torque: AmmoVec3): void;\n applyTorqueImpulse(torque: AmmoVec3): void;\n setCcdMotionThreshold(v: number): void;\n setCcdSweptSphereRadius(v: number): void;\n /** Sets the world transform and restarts interpolation from it. */\n setCenterOfMassTransform(t: AmmoTransform): void;\n}\n\n/** @internal */\nexport interface AmmoConstraint {\n setBreakingImpulseThreshold(v: number): void;\n /** Absent from the games' Ammo build; see `Joint.isBroken`. */\n getAppliedImpulse?(): number;\n}\n\n/** @internal */\nexport interface AmmoConeTwist extends AmmoConstraint {\n /** Swing about local Y, swing about local Z, twist about local X. Radians. */\n setLimit(swingY: number, swingZ: number, twist: number): void;\n}\n\n/** @internal */\nexport interface AmmoHinge extends AmmoConstraint {\n setLimit(low: number, high: number, softness?: number, bias?: number, relax?: number): void;\n}\n\n/** @internal */\nexport interface AmmoGeneric6Dof extends AmmoConstraint {\n setLinearLowerLimit(v: AmmoVec3): void;\n setLinearUpperLimit(v: AmmoVec3): void;\n setAngularLowerLimit(v: AmmoVec3): void;\n setAngularUpperLimit(v: AmmoVec3): void;\n}\n\n/** @internal */\nexport interface AmmoManifoldPoint {\n get_m_localPointA(): AmmoVec3;\n get_m_localPointB(): AmmoVec3;\n getPositionWorldOnA(): AmmoVec3;\n getPositionWorldOnB(): AmmoVec3;\n get_m_normalWorldOnB(): AmmoVec3;\n getAppliedImpulse(): number;\n}\n\n/** @internal */\nexport interface AmmoManifold {\n getBody0(): unknown;\n getBody1(): unknown;\n getNumContacts(): number;\n getContactPoint(i: number): AmmoManifoldPoint;\n}\n\n/** @internal */\nexport interface AmmoDispatcher {\n getNumManifolds(): number;\n getManifoldByIndexInternal(i: number): AmmoManifold;\n}\n\n/** @internal */\nexport interface AmmoRayCallback {\n set_m_collisionFilterGroup(g: number): void;\n set_m_collisionFilterMask(m: number): void;\n set_m_flags?(f: number): void;\n hasHit(): boolean;\n}\n\n/** @internal */\nexport interface AmmoClosestRayCallback extends AmmoRayCallback {\n get_m_collisionObject(): unknown;\n get_m_hitPointWorld(): AmmoVec3;\n get_m_hitNormalWorld(): AmmoVec3;\n get_m_closestHitFraction(): number;\n}\n\n/** @internal */\nexport interface AmmoArray<T> { size(): number; at(i: number): T }\n\n/** @internal */\nexport interface AmmoAllHitsRayCallback extends AmmoRayCallback {\n get_m_collisionObjects(): AmmoArray<unknown>;\n get_m_hitPointWorld(): AmmoArray<AmmoVec3>;\n get_m_hitNormalWorld(): AmmoArray<AmmoVec3>;\n get_m_hitFractions(): AmmoArray<number>;\n}\n\n/** A `btDiscreteDynamicsWorld`, exposed as {@link PhysicsWorld.dynamicsWorld} for raw constraints. @group Physics */\nexport interface AmmoDynamicsWorld {\n setGravity(v: AmmoVec3): void;\n stepSimulation(dt: number, maxSubSteps: number, fixedTimeStep: number): number;\n addRigidBody(body: AmmoRigidBody, group?: number, mask?: number): void;\n removeRigidBody(body: AmmoRigidBody): void;\n addConstraint(c: AmmoConstraint, disableCollisionBetweenLinkedBodies?: boolean): void;\n removeConstraint(c: AmmoConstraint): void;\n rayTest(from: AmmoVec3, to: AmmoVec3, cb: AmmoRayCallback): void;\n setInternalTickCallback?(fnPtr: number): void;\n updateSingleAabb?(body: AmmoRigidBody): void;\n}\n\ntype Ctor<T, A extends unknown[] = []> = new (...args: A) => T;\n\n/** @internal */\nexport interface AmmoNS {\n btVector3: Ctor<AmmoVec3, [number?, number?, number?]>;\n btQuaternion: Ctor<AmmoQuat, [number, number, number, number]>;\n btTransform: Ctor<AmmoTransform>;\n btDefaultMotionState: Ctor<AmmoMotionState, [AmmoTransform]>;\n btRigidBodyConstructionInfo: Ctor<unknown, [number, AmmoMotionState, AmmoShape, AmmoVec3]>;\n btRigidBody: Ctor<AmmoRigidBody, [unknown]>;\n btDefaultCollisionConfiguration: Ctor<unknown>;\n btCollisionDispatcher: Ctor<AmmoDispatcher, [unknown]>;\n btDbvtBroadphase: Ctor<unknown>;\n btSequentialImpulseConstraintSolver: Ctor<unknown>;\n btDiscreteDynamicsWorld: Ctor<AmmoDynamicsWorld, [AmmoDispatcher, unknown, unknown, unknown]>;\n btBoxShape: Ctor<AmmoShape, [AmmoVec3]>;\n btSphereShape: Ctor<AmmoShape, [number]>;\n btCapsuleShape: Ctor<AmmoShape, [number, number]>;\n btCapsuleShapeX: Ctor<AmmoShape, [number, number]>;\n btCapsuleShapeZ: Ctor<AmmoShape, [number, number]>;\n btCylinderShape: Ctor<AmmoShape, [AmmoVec3]>;\n btCylinderShapeX: Ctor<AmmoShape, [AmmoVec3]>;\n btCylinderShapeZ: Ctor<AmmoShape, [AmmoVec3]>;\n btConeShape: Ctor<AmmoShape, [number, number]>;\n btConeShapeX: Ctor<AmmoShape, [number, number]>;\n btConeShapeZ: Ctor<AmmoShape, [number, number]>;\n btConvexHullShape: Ctor<AmmoConvexHull>;\n btTriangleMesh: Ctor<AmmoTriangleMesh>;\n btBvhTriangleMeshShape: Ctor<AmmoShape, [AmmoTriangleMesh, boolean]>;\n btConeTwistConstraint: Ctor<AmmoConeTwist, [AmmoRigidBody, AmmoRigidBody, AmmoTransform, AmmoTransform]>;\n btHingeConstraint: Ctor<AmmoHinge, [AmmoRigidBody, AmmoRigidBody, AmmoVec3, AmmoVec3, AmmoVec3, AmmoVec3]>;\n btGeneric6DofConstraint: Ctor<AmmoGeneric6Dof, [AmmoRigidBody, AmmoRigidBody, AmmoTransform, AmmoTransform, boolean]>;\n ClosestRayResultCallback: Ctor<AmmoClosestRayCallback, [AmmoVec3, AmmoVec3]>;\n AllHitsRayResultCallback: Ctor<AmmoAllHitsRayCallback, [AmmoVec3, AmmoVec3]>;\n castObject<T>(obj: unknown, cls: Ctor<T, never[]>): T;\n getPointer(obj: unknown): number;\n addFunction?(fn: (...args: number[]) => void, signature: string): number;\n destroy(obj: unknown): void;\n}\n\n/** `globalThis.Ammo`, or a clear error when physics was never set up. @internal */\nexport function ammo(): AmmoNS {\n const a = (globalThis as { Ammo?: AmmoNS }).Ammo;\n if (!a?.btVector3) {\n throw new Error(\n '[physics] globalThis.Ammo is not set. Pass physics: true (with Ammo loaded) or ' +\n 'physics: { loadAmmo } to Scene.create first.',\n );\n }\n return a;\n}\n\n// Bullet collision flags and activation states, as PlayCanvas names them.\n/** @internal */ export const CF_KINEMATIC_OBJECT = 2;\n/** @internal */ export const CF_NO_CONTACT_RESPONSE = 4;\n/** @internal */ export const ACTIVE_TAG = 1;\n/** @internal */ export const DISABLE_DEACTIVATION = 4;\n/** @internal */ export const DISABLE_SIMULATION = 5;\n/** `btRigidBody` flag that stops the world's gravity overwriting a per-body gravity. @internal */\nexport const BT_DISABLE_WORLD_GRAVITY = 1;\n", "import { BufferGeometry, EventDispatcher, Euler, Matrix4, Mesh, Object3D, Quaternion, Vector3 } from 'three';\n\nimport {\n ACTIVE_TAG,\n ammo,\n BT_DISABLE_WORLD_GRAVITY,\n CF_KINEMATIC_OBJECT,\n CF_NO_CONTACT_RESPONSE,\n DISABLE_DEACTIVATION,\n DISABLE_SIMULATION,\n} from './ammo';\nimport type {\n AmmoConvexHull,\n AmmoDynamicsWorld,\n AmmoNS,\n AmmoQuat,\n AmmoRigidBody,\n AmmoShape,\n AmmoTransform,\n AmmoVec3,\n} from './ammo';\nimport type { PhysicsWorld } from './physics-world';\n\n/** Anything with `x`, `y`, `z`: a `THREE.Vector3`, or a plain object. @group Physics */\nexport interface XYZ { x: number; y: number; z: number }\n\n/** Anything with `x`, `y`, `z`, `w`: a `THREE.Quaternion`, or a plain object. @group Physics */\nexport interface XYZW { x: number; y: number; z: number; w: number }\n\n/**\n * How a body moves. As in PlayCanvas: `'static'` never moves, `'dynamic'` is\n * simulated and writes its pose to the object, `'kinematic'` follows the\n * object and pushes dynamic bodies out of the way.\n *\n * @group Physics\n */\nexport type RigidBodyType = 'static' | 'dynamic' | 'kinematic';\n\n/**\n * Collision shape, in the same terms as PlayCanvas's `collision` component.\n * `axis` is 0 = X, 1 = Y (default), 2 = Z. A capsule's `height` includes its\n * two caps. Primitive shapes ignore the object's scale, as in PlayCanvas.\n *\n * `'mesh'` builds a static triangle mesh from every `Mesh` under `geometry`\n * (or from the geometry itself), in the body object's frame with its world\n * scale baked in. Bullet cannot simulate a triangle mesh as a dynamic body:\n * pass `convexHull: true` for a moving one.\n *\n * @group Physics\n */\nexport type CollisionShape =\n | { type: 'box'; halfExtents: XYZ }\n | { type: 'sphere'; radius: number }\n | { type: 'capsule'; radius: number; height: number; axis?: 0 | 1 | 2 }\n | { type: 'cylinder'; radius: number; height: number; axis?: 0 | 1 | 2 }\n | { type: 'cone'; radius: number; height: number; axis?: 0 | 1 | 2 }\n | { type: 'mesh'; geometry: BufferGeometry | Object3D; convexHull?: boolean };\n\n/**\n * Options for {@link PhysicsWorld.addBody}. Every default matches\n * PlayCanvas's `rigidbody` component.\n *\n * @group Physics\n */\nexport interface RigidBodyOptions {\n shape: CollisionShape;\n /** Default `'static'`. */\n type?: RigidBodyType;\n /** Kilograms; only dynamic bodies have mass. Default `1`. */\n mass?: number;\n /** Default `0.5`. */\n friction?: number;\n /** Default `0`. */\n rollingFriction?: number;\n /** Default `0`. */\n restitution?: number;\n /** Default `0`. */\n linearDamping?: number;\n /** Default `0`. */\n angularDamping?: number;\n /** Per-axis multiplier on linear motion; `(1, 1, 0)` keeps a body in the XY plane. Default `(1, 1, 1)`. */\n linearFactor?: XYZ;\n /** Per-axis multiplier on rotation. Default `(1, 1, 1)`. */\n angularFactor?: XYZ;\n /** Multiplier on the world's gravity. Default `1`. */\n gravityScale?: number;\n /** Collision group bits. Default from {@link type}: dynamic 1, static 2, kinematic 4. */\n group?: number;\n /** Groups this body collides with. Default: static `BODYMASK_NOT_STATIC`, others `BODYMASK_ALL`. */\n mask?: number;\n /** Shape position in the object's frame (PlayCanvas `collision.linearOffset`). */\n linearOffset?: XYZ;\n /** Shape rotation in the object's frame (PlayCanvas `collision.angularOffset`). */\n angularOffset?: XYZW;\n /**\n * A sensor: no collision response, follows the object every step and fires\n * `triggerenter` / `triggerleave`. PlayCanvas's `collision` component\n * without a `rigidbody`. `type`, `mass` and the material options are\n * ignored. Default `false`.\n */\n trigger?: boolean;\n /** Whether the body starts in the simulation. Default `true`. */\n enabled?: boolean;\n}\n\n/**\n * One point of contact between two bodies, seen from the body the event is\n * dispatched on. PlayCanvas's `ContactPoint`.\n *\n * @group Physics\n */\nexport interface ContactPoint {\n /** On this body, in its local frame. */\n localPoint: Vector3;\n /** On the other body, in its local frame. */\n localPointOther: Vector3;\n /** On this body, world space. */\n point: Vector3;\n /** On the other body, world space. */\n pointOther: Vector3;\n /** World-space contact normal, pointing from the other body toward this one. */\n normal: Vector3;\n /** Impulse the solver applied at this point, N\u00B7s. */\n impulse: number;\n}\n\n/**\n * Payload of `contact` and `collisionstart`. PlayCanvas's `ContactResult`,\n * with `other` the other body's object.\n *\n * @group Physics\n */\nexport interface ContactResult {\n other: Object3D;\n otherBody: RigidBody;\n contacts: ContactPoint[];\n}\n\n/** Payload of `collisionend`, `triggerenter` and `triggerleave`. @group Physics */\nexport interface BodyPairEvent {\n other: Object3D;\n otherBody: RigidBody;\n}\n\n/**\n * Events a {@link RigidBody} dispatches, with PlayCanvas's names. They fire\n * after the step that produced them, once every dynamic object is in place.\n *\n * - `contact`: every physics sub-step the bodies touch.\n * - `collisionstart` / `collisionend`: the first and the first-not-touching sub-step.\n * - `triggerenter` / `triggerleave`: on both a trigger and the body entering it.\n *\n * @group Physics\n */\nexport interface RigidBodyEventMap {\n contact: ContactResult;\n collisionstart: ContactResult;\n collisionend: BodyPairEvent;\n triggerenter: BodyPairEvent;\n triggerleave: BodyPairEvent;\n}\n\n// PlayCanvas's collision groups and masks, with the same values, so group /\n// mask numbers in game code mean the same thing on either engine.\n/** @group Physics */ export const BODYGROUP_NONE = 0;\n/** @group Physics */ export const BODYGROUP_DEFAULT = 1;\n/** @group Physics */ export const BODYGROUP_DYNAMIC = 1;\n/** @group Physics */ export const BODYGROUP_STATIC = 2;\n/** @group Physics */ export const BODYGROUP_KINEMATIC = 4;\n/** @group Physics */ export const BODYGROUP_ENGINE_1 = 8;\n/** @group Physics */ export const BODYGROUP_TRIGGER = 16;\n/** @group Physics */ export const BODYGROUP_ENGINE_2 = 32;\n/** @group Physics */ export const BODYGROUP_ENGINE_3 = 64;\n/** @group Physics */ export const BODYGROUP_USER_1 = 128;\n/** @group Physics */ export const BODYGROUP_USER_2 = 256;\n/** @group Physics */ export const BODYGROUP_USER_3 = 512;\n/** @group Physics */ export const BODYGROUP_USER_4 = 1024;\n/** @group Physics */ export const BODYGROUP_USER_5 = 2048;\n/** @group Physics */ export const BODYGROUP_USER_6 = 4096;\n/** @group Physics */ export const BODYGROUP_USER_7 = 8192;\n/** @group Physics */ export const BODYGROUP_USER_8 = 16384;\n/** @group Physics */ export const BODYMASK_NONE = 0;\n/** @group Physics */ export const BODYMASK_ALL = 65535;\n/** @group Physics */ export const BODYMASK_STATIC = 2;\n/** @group Physics */ export const BODYMASK_NOT_STATIC = 65535 ^ 2;\n/** @group Physics */ export const BODYMASK_NOT_STATIC_KINEMATIC = 65535 ^ (2 | 4);\n\nfunction defaultGroup(type: RigidBodyType): number {\n return type === 'dynamic' ? BODYGROUP_DYNAMIC : type === 'kinematic' ? BODYGROUP_KINEMATIC : BODYGROUP_STATIC;\n}\n\nfunction defaultMask(type: RigidBodyType): number {\n return type === 'static' ? BODYMASK_NOT_STATIC : BODYMASK_ALL;\n}\n\n/**\n * The parts of {@link PhysicsWorld} a body calls into. Kept narrow so the two\n * classes don't reach into each other's state.\n * @internal\n */\nexport interface BodyHost {\n readonly world: PhysicsWorld;\n readonly gravity: Vector3;\n readonly native: AmmoDynamicsWorld;\n readonly btVec1: AmmoVec3;\n readonly btVec2: AmmoVec3;\n readonly btTransform: AmmoTransform;\n readonly btQuat: AmmoQuat;\n simulationChanged(body: RigidBody, inWorld: boolean): void;\n /** Run `replace`, which frees and re-creates `body`'s btRigidBody, with its joints let go meanwhile. */\n nativeReplacing(body: RigidBody, replace: () => void): void;\n}\n\n/**\n * A rigid body attached to a `THREE.Object3D`: PlayCanvas's `rigidbody` and\n * `collision` components in one object. Create one with\n * {@link PhysicsWorld.addBody}; {@link PhysicsWorld.getBody} finds it again\n * from the object.\n *\n * A dynamic body writes its pose into the object's `position` and\n * `quaternion` after each step (converted into the parent's frame, so the\n * object may sit anywhere in the graph; its own scale is left alone). A\n * kinematic body or a trigger reads the object's world pose before each step.\n * A static body reads it when created, enabled or {@link teleport}ed.\n *\n * Events use three.js's `addEventListener`; see {@link RigidBodyEventMap}.\n *\n * @group Physics\n */\nexport class RigidBody extends EventDispatcher<RigidBodyEventMap> {\n /** The object this body moves (dynamic) or follows (kinematic, trigger). */\n readonly object: Object3D;\n /** The shape description the body was built from. */\n readonly shape: CollisionShape;\n /** True for a sensor body; see {@link RigidBodyOptions.trigger}. */\n readonly isTrigger: boolean;\n /** @internal Key for looking the body up from a Bullet pointer (`btRigidBody` user index). */\n readonly _id: number;\n\n private readonly _host: BodyHost;\n private _ammoShape: AmmoShape | null;\n /** Native objects the shape keeps alive (triangle meshes), freed with it. */\n private readonly _shapeParts: unknown[];\n private _body: AmmoRigidBody | null = null;\n private _type: RigidBodyType;\n private _mass: number;\n private _friction: number;\n private _rollingFriction: number;\n private _restitution: number;\n private _linearDamping: number;\n private _angularDamping: number;\n private readonly _linearFactor = new Vector3(1, 1, 1);\n private readonly _angularFactor = new Vector3(1, 1, 1);\n private _gravityScale: number;\n private _group: number;\n private _mask: number;\n private _enabled: boolean;\n private _inWorld = false;\n private readonly _linearOffset: Vector3 | null;\n private readonly _angularOffset: Quaternion | null;\n private readonly _linearVelocity = new Vector3();\n private readonly _angularVelocity = new Vector3();\n\n /** @internal Use {@link PhysicsWorld.addBody}. */\n constructor(host: BodyHost, id: number, object: Object3D, opts: RigidBodyOptions) {\n super();\n this._host = host;\n this._id = id;\n this.object = object;\n this.shape = opts.shape;\n this.isTrigger = !!opts.trigger;\n this._type = this.isTrigger ? 'dynamic' : (opts.type ?? 'static');\n this._mass = opts.mass ?? 1;\n this._friction = opts.friction ?? 0.5;\n this._rollingFriction = opts.rollingFriction ?? 0;\n this._restitution = opts.restitution ?? 0;\n this._linearDamping = opts.linearDamping ?? 0;\n this._angularDamping = opts.angularDamping ?? 0;\n if (opts.linearFactor) this._linearFactor.copy(opts.linearFactor);\n if (opts.angularFactor) this._angularFactor.copy(opts.angularFactor);\n this._gravityScale = opts.gravityScale ?? 1;\n this._group = opts.group ?? (this.isTrigger ? BODYGROUP_TRIGGER : defaultGroup(this._type));\n this._mask = opts.mask ?? (this.isTrigger ? BODYMASK_NOT_STATIC ^ BODYGROUP_TRIGGER : defaultMask(this._type));\n this._enabled = opts.enabled ?? true;\n const lo = opts.linearOffset;\n const ao = opts.angularOffset;\n const hasLo = !!lo && (lo.x !== 0 || lo.y !== 0 || lo.z !== 0);\n const hasAo = !!ao && (ao.x !== 0 || ao.y !== 0 || ao.z !== 0 || ao.w !== 1);\n this._linearOffset = hasLo || hasAo ? new Vector3(lo?.x ?? 0, lo?.y ?? 0, lo?.z ?? 0) : null;\n this._angularOffset = hasLo || hasAo ? new Quaternion(ao?.x ?? 0, ao?.y ?? 0, ao?.z ?? 0, ao?.w ?? 1) : null;\n\n this._shapeParts = [];\n this._ammoShape = createShape(ammo(), opts.shape, object, this._shapeParts);\n this._createBody();\n }\n\n // \u2500\u2500 Native access \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * The Bullet `btRigidBody`, for what this wrapper does not cover: CCD\n * (`setCcdMotionThreshold`), raw constraints on\n * {@link PhysicsWorld.dynamicsWorld}. PlayCanvas's `rigidbody.body`.\n * `null` once the body is removed.\n */\n get ammoBody(): AmmoRigidBody | null {\n return this._body;\n }\n\n /** The world this body belongs to. */\n get world(): PhysicsWorld {\n return this._host.world;\n }\n\n // \u2500\u2500 Simulation membership \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Whether the body is in the simulation. Disabling takes it out without destroying it. */\n get enabled(): boolean {\n return this._enabled;\n }\n\n set enabled(v: boolean) {\n if (this._enabled === v) return;\n this._enabled = v;\n if (v) this._enableSimulation();\n else this._disableSimulation();\n }\n\n /**\n * Body type. Changing it rebuilds the body and resets {@link group} and\n * {@link mask} to the new type's defaults, as in PlayCanvas.\n */\n get type(): RigidBodyType {\n return this._type;\n }\n\n set type(t: RigidBodyType) {\n if (this._type === t || this.isTrigger) return;\n this._type = t;\n this._group = defaultGroup(t);\n this._mask = defaultMask(t);\n this._host.nativeReplacing(this, () => this._createBody());\n }\n\n /** Collision group bits. Setting it re-adds the body to the world. */\n get group(): number {\n return this._group;\n }\n\n set group(g: number) {\n if (this._group === g) return;\n this._group = g;\n this._readd();\n }\n\n /** Groups this body collides with. Setting it re-adds the body to the world. */\n get mask(): number {\n return this._mask;\n }\n\n set mask(m: number) {\n if (this._mask === m) return;\n this._mask = m;\n this._readd();\n }\n\n // \u2500\u2500 Material and mass \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Kilograms. Only dynamic bodies use it. */\n get mass(): number {\n return this._mass;\n }\n\n set mass(m: number) {\n if (this._mass === m) return;\n this._mass = m;\n const body = this._body;\n if (!body || this._type !== 'dynamic') return;\n const inWorld = this._inWorld;\n if (inWorld) this._disableSimulation();\n const v = this._host.btVec1;\n body.getCollisionShape().calculateLocalInertia(m, v);\n body.setMassProps(m, v);\n body.updateInertiaTensor();\n if (inWorld) this._enableSimulation();\n }\n\n get friction(): number { return this._friction; }\n set friction(v: number) { this._friction = v; this._body?.setFriction(v); }\n\n get rollingFriction(): number { return this._rollingFriction; }\n set rollingFriction(v: number) { this._rollingFriction = v; this._body?.setRollingFriction(v); }\n\n get restitution(): number { return this._restitution; }\n set restitution(v: number) { this._restitution = v; this._body?.setRestitution(v); }\n\n get linearDamping(): number { return this._linearDamping; }\n set linearDamping(v: number) { this._linearDamping = v; this._body?.setDamping(v, this._angularDamping); }\n\n get angularDamping(): number { return this._angularDamping; }\n set angularDamping(v: number) { this._angularDamping = v; this._body?.setDamping(this._linearDamping, v); }\n\n /** Per-axis multiplier on linear motion. Assign a vector; mutating the returned one does nothing. */\n get linearFactor(): Vector3 { return this._linearFactor; }\n set linearFactor(f: XYZ) {\n this._linearFactor.copy(f);\n if (this._body && this._type === 'dynamic') this._body.setLinearFactor(this._bt(f));\n }\n\n /** Per-axis multiplier on rotation. Assign a vector; mutating the returned one does nothing. */\n get angularFactor(): Vector3 { return this._angularFactor; }\n set angularFactor(f: XYZ) {\n this._angularFactor.copy(f);\n if (this._body && this._type === 'dynamic') this._body.setAngularFactor(this._bt(f));\n }\n\n /** Multiplier on the world's gravity for this body. */\n get gravityScale(): number { return this._gravityScale; }\n set gravityScale(s: number) {\n if (this._gravityScale === s) return;\n this._gravityScale = s;\n if (this._body && this._type === 'dynamic') this._applyGravityScale();\n }\n\n // \u2500\u2500 Velocity \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * World-space linear velocity, m/s. Dynamic bodies only. The getter returns\n * one reused vector; clone it to keep it. Setting it wakes the body.\n */\n get linearVelocity(): Vector3 {\n const body = this._body;\n if (body && this._type === 'dynamic') readVec(body.getLinearVelocity(), this._linearVelocity);\n return this._linearVelocity;\n }\n\n set linearVelocity(v: XYZ) {\n const body = this._body;\n if (!body || this._type !== 'dynamic') return;\n body.activate();\n body.setLinearVelocity(this._bt(v));\n this._linearVelocity.copy(v);\n }\n\n /** World-space angular velocity, rad/s. Same rules as {@link linearVelocity}. */\n get angularVelocity(): Vector3 {\n const body = this._body;\n if (body && this._type === 'dynamic') readVec(body.getAngularVelocity(), this._angularVelocity);\n return this._angularVelocity;\n }\n\n set angularVelocity(v: XYZ) {\n const body = this._body;\n if (!body || this._type !== 'dynamic') return;\n body.activate();\n body.setAngularVelocity(this._bt(v));\n this._angularVelocity.copy(v);\n }\n\n // \u2500\u2500 Forces \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Apply a world-space force (N) for the next step, at `relativePoint`\n * (world-space offset from the centre of mass; default the centre).\n */\n applyForce(force: XYZ, relativePoint?: XYZ): void {\n const body = this._body;\n if (!body) return;\n body.activate();\n body.applyForce(this._bt(force), this._bt2(relativePoint));\n }\n\n /** Apply a world-space impulse (N\u00B7s) at `relativePoint` (as {@link applyForce}). */\n applyImpulse(impulse: XYZ, relativePoint?: XYZ): void {\n const body = this._body;\n if (!body) return;\n body.activate();\n body.applyImpulse(this._bt(impulse), this._bt2(relativePoint));\n }\n\n /** Apply a world-space torque (N\u00B7m) for the next step. */\n applyTorque(torque: XYZ): void {\n const body = this._body;\n if (!body) return;\n body.activate();\n body.applyTorque(this._bt(torque));\n }\n\n /** Apply a world-space angular impulse (N\u00B7m\u00B7s). */\n applyTorqueImpulse(torque: XYZ): void {\n const body = this._body;\n if (!body) return;\n body.activate();\n body.applyTorqueImpulse(this._bt(torque));\n }\n\n /** Whether Bullet is simulating the body this step (it sleeps once it comes to rest). */\n isActive(): boolean {\n return this._body?.isActive() ?? false;\n }\n\n /** Wake the body. */\n activate(): void {\n this._body?.activate();\n }\n\n /**\n * Move the object and the body to a world-space position, and optionally a\n * world-space rotation (a quaternion, or an Euler in radians). Velocities\n * are kept. PlayCanvas's `rigidbody.teleport`.\n */\n teleport(position: XYZ, rotation?: XYZW | Euler): void {\n const o = this.object;\n o.updateWorldMatrix(true, false);\n o.matrixWorld.decompose(_pos, _quat, _scale);\n _pos.copy(position);\n if (rotation instanceof Euler) _quat.setFromEuler(rotation);\n else if (rotation) _quat.copy(rotation);\n setObjectWorldPose(o, _pos, _quat);\n this._syncObjectToBody();\n }\n\n // \u2500\u2500 Internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** @internal Kinematic bodies: the object's pose becomes the motion-state target. */\n _updateKinematic(): void {\n const body = this._body;\n if (!body) return;\n this._readObjectPose(_pos, _quat);\n body.getMotionState()?.setWorldTransform(this._btXform(_pos, _quat));\n }\n\n /** @internal Triggers follow the object as if teleported every step. */\n _updateTrigger(): void {\n this._syncObjectToBody();\n }\n\n /**\n * @internal Dynamic bodies: write the motion state's pose, which Bullet\n * interpolates between fixed steps, into the object. Sleeping bodies are\n * skipped, so an object moved by hand stays put until the body wakes.\n */\n _updateDynamic(): void {\n const body = this._body;\n if (!body || !body.isActive()) return;\n const ms = body.getMotionState();\n if (!ms) return;\n const t = this._host.btTransform;\n ms.getWorldTransform(t);\n const p = t.getOrigin();\n const q = t.getRotation();\n _pos.set(p.x(), p.y(), p.z());\n _quat.set(q.x(), q.y(), q.z(), q.w());\n if (this._linearOffset && this._angularOffset) {\n _quat.multiply(_quat2.copy(this._angularOffset).invert());\n _pos.sub(_vec.copy(this._linearOffset).applyQuaternion(_quat));\n }\n setObjectWorldPose(this.object, _pos, _quat);\n }\n\n /** @internal Re-apply gravity to a body with its own gravity scale after the world gravity changed. */\n _onGravityChanged(): void {\n if (this._body && this._type === 'dynamic' && this._gravityScale !== 1) this._applyGravityScale();\n }\n\n /** @internal Whether contacts must be gathered for this body's listeners. */\n _wantsContacts(): boolean {\n return hasListeners(this, 'contact') || hasListeners(this, 'collisionstart') || hasListeners(this, 'collisionend');\n }\n\n /** @internal Free every native object. Called by {@link PhysicsWorld.removeBody}. */\n _destroy(): void {\n this._destroyBody();\n const A = ammo();\n if (this._ammoShape) A.destroy(this._ammoShape);\n this._ammoShape = null;\n for (const part of this._shapeParts) A.destroy(part);\n this._shapeParts.length = 0;\n }\n\n /** The object's world pose, moved to where the shape sits (collision offsets). */\n private _readObjectPose(pos: Vector3, quat: Quaternion): void {\n const o = this.object;\n o.updateWorldMatrix(true, false);\n o.matrixWorld.decompose(pos, quat, _scale);\n if (this._linearOffset && this._angularOffset) {\n pos.add(_vec.copy(this._linearOffset).applyQuaternion(quat));\n quat.multiply(this._angularOffset);\n }\n }\n\n /** Place the body where the object is: PlayCanvas's `syncEntityToBody`. */\n private _syncObjectToBody(): void {\n const body = this._body;\n if (!body) return;\n this._readObjectPose(_pos, _quat);\n const t = this._btXform(_pos, _quat);\n body.setWorldTransform(t);\n const ms = body.getMotionState();\n if (this._type === 'kinematic') {\n ms?.setWorldTransform(t);\n } else if (this._type === 'dynamic' && !this.isTrigger) {\n // Restart interpolation at the new pose, or the next frame lerps from\n // the old one. PlayCanvas uses setInterpolationWorldTransform, which the\n // games' Ammo build lacks; setCenterOfMassTransform resets the same state.\n body.setCenterOfMassTransform(t);\n ms?.setWorldTransform(t);\n }\n if (this._inWorld) this._host.native.updateSingleAabb?.(body);\n body.activate();\n }\n\n private _createBody(): void {\n const A = ammo();\n const shape = this._ammoShape;\n if (!shape) return;\n this._destroyBody();\n\n const mass = this._type === 'dynamic' ? this._mass : 0;\n this._readObjectPose(_pos, _quat);\n const inertia = new A.btVector3(0, 0, 0);\n if (mass !== 0) shape.calculateLocalInertia(mass, inertia);\n const motionState = new A.btDefaultMotionState(this._btXform(_pos, _quat));\n const info = new A.btRigidBodyConstructionInfo(mass, motionState, shape, inertia);\n const body = new A.btRigidBody(info);\n A.destroy(info);\n A.destroy(inertia);\n body.setUserIndex(this._id);\n if (this._type === 'kinematic') {\n body.setCollisionFlags(body.getCollisionFlags() | CF_KINEMATIC_OBJECT);\n body.setActivationState(DISABLE_DEACTIVATION);\n }\n if (this.isTrigger) {\n body.setCollisionFlags(body.getCollisionFlags() | CF_NO_CONTACT_RESPONSE);\n // Mass 1 so Bullet treats it as dynamic and reports overlaps with\n // static-free masks; zero factors so nothing ever moves it.\n body.setRestitution(0);\n body.setFriction(0);\n body.setDamping(0, 0);\n body.setLinearFactor(this._bt(_zero));\n body.setAngularFactor(this._bt(_zero));\n } else {\n body.setRestitution(this._restitution);\n body.setFriction(this._friction);\n body.setRollingFriction(this._rollingFriction);\n body.setDamping(this._linearDamping, this._angularDamping);\n if (this._type === 'dynamic') {\n body.setLinearFactor(this._bt(this._linearFactor));\n body.setAngularFactor(this._bt(this._angularFactor));\n }\n }\n this._body = body;\n if (this._enabled) this._enableSimulation();\n }\n\n private _destroyBody(): void {\n const body = this._body;\n if (!body) return;\n this._disableSimulation();\n const A = ammo();\n const ms = body.getMotionState();\n if (ms) A.destroy(ms);\n A.destroy(body);\n this._body = null;\n }\n\n private _enableSimulation(): void {\n const body = this._body;\n if (!body || this._inWorld) return;\n this._host.native.addRigidBody(body, this._group, this._mask);\n body.forceActivationState(this._type === 'kinematic' ? DISABLE_DEACTIVATION : ACTIVE_TAG);\n this._inWorld = true;\n if (this._type === 'dynamic' && this._gravityScale !== 1 && !this.isTrigger) this._applyGravityScale();\n this._syncObjectToBody();\n this._host.simulationChanged(this, true);\n }\n\n private _disableSimulation(): void {\n const body = this._body;\n if (!body || !this._inWorld) return;\n this._host.native.removeRigidBody(body);\n body.forceActivationState(DISABLE_SIMULATION);\n this._inWorld = false;\n this._host.simulationChanged(this, false);\n }\n\n private _readd(): void {\n if (!this._inWorld) return;\n this._disableSimulation();\n this._enableSimulation();\n }\n\n private _applyGravityScale(): void {\n const body = this._body!;\n // Bullet resets every body's gravity to the world's on addRigidBody and\n // setGravity unless this flag is set.\n if (body.getFlags && body.setFlags) {\n const flags = body.getFlags();\n body.setFlags(this._gravityScale === 1 ? flags & ~BT_DISABLE_WORLD_GRAVITY : flags | BT_DISABLE_WORLD_GRAVITY);\n }\n const g = this._host.gravity;\n body.setGravity(this._bt(_vec.copy(g).multiplyScalar(this._gravityScale)));\n }\n\n private _bt(v: XYZ): AmmoVec3 {\n const out = this._host.btVec1;\n out.setValue(v.x, v.y, v.z);\n return out;\n }\n\n private _bt2(v: XYZ | undefined): AmmoVec3 {\n const out = this._host.btVec2;\n if (v) out.setValue(v.x, v.y, v.z);\n else out.setValue(0, 0, 0);\n return out;\n }\n\n private _btXform(pos: XYZ, quat: XYZW): AmmoTransform {\n const t = this._host.btTransform;\n const v = this._host.btVec1;\n const q = this._host.btQuat;\n v.setValue(pos.x, pos.y, pos.z);\n q.setValue(quat.x, quat.y, quat.z, quat.w);\n t.setIdentity();\n t.setOrigin(v);\n t.setRotation(q);\n return t;\n }\n}\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Whether `target` has listeners for `type`. three.js's EventDispatcher only\n * answers that per listener; its `_listeners` table has been the storage\n * since r1, and gathering contacts nobody listens for costs a vector\n * allocation per contact point per sub-step.\n */\nfunction hasListeners(target: object, type: string): boolean {\n const table = (target as { _listeners?: Record<string, unknown[] | undefined> })._listeners;\n return !!table?.[type]?.length;\n}\n\nfunction readVec(v: AmmoVec3, out: Vector3): Vector3 {\n return out.set(v.x(), v.y(), v.z());\n}\n\n/**\n * Give `object` this world-space position and rotation by solving for its\n * local transform under its parent. The object's own scale is kept.\n */\nexport function setObjectWorldPose(object: Object3D, pos: Vector3, quat: Quaternion): void {\n const parent = object.parent;\n if (parent) {\n parent.updateWorldMatrix(true, false);\n _mat.compose(pos, quat, _one);\n _mat.premultiply(_mat2.copy(parent.matrixWorld).invert());\n _mat.decompose(object.position, object.quaternion, _scale);\n } else {\n object.position.copy(pos);\n object.quaternion.copy(quat);\n }\n object.updateWorldMatrix(false, true);\n}\n\nfunction createShape(A: AmmoNS, desc: CollisionShape, owner: Object3D, parts: unknown[]): AmmoShape {\n switch (desc.type) {\n case 'box': {\n const he = new A.btVector3(desc.halfExtents.x, desc.halfExtents.y, desc.halfExtents.z);\n const s = new A.btBoxShape(he);\n A.destroy(he);\n return s;\n }\n case 'sphere':\n return new A.btSphereShape(desc.radius);\n case 'capsule': {\n // PlayCanvas's height spans the caps; Bullet's is the cylinder between them.\n const h = Math.max(desc.height - 2 * desc.radius, 0);\n if (desc.axis === 0) return new A.btCapsuleShapeX(desc.radius, h);\n if (desc.axis === 2) return new A.btCapsuleShapeZ(desc.radius, h);\n return new A.btCapsuleShape(desc.radius, h);\n }\n case 'cylinder': {\n const r = desc.radius;\n const hh = desc.height * 0.5;\n let s: AmmoShape;\n if (desc.axis === 0) {\n const he = new A.btVector3(hh, r, r);\n s = new A.btCylinderShapeX(he);\n A.destroy(he);\n } else if (desc.axis === 2) {\n const he = new A.btVector3(r, r, hh);\n s = new A.btCylinderShapeZ(he);\n A.destroy(he);\n } else {\n const he = new A.btVector3(r, hh, r);\n s = new A.btCylinderShape(he);\n A.destroy(he);\n }\n return s;\n }\n case 'cone':\n if (desc.axis === 0) return new A.btConeShapeX(desc.radius, desc.height);\n if (desc.axis === 2) return new A.btConeShapeZ(desc.radius, desc.height);\n return new A.btConeShape(desc.radius, desc.height);\n case 'mesh':\n return createMeshShape(A, desc.geometry, !!desc.convexHull, owner, parts);\n }\n}\n\n/**\n * Triangles of every mesh under `source`, in `source`'s frame, scaled by the\n * body object's world scale - Bullet bodies carry no scale, and this Ammo\n * build has no btScaledBvhTriangleMeshShape, so the scale is baked in the\n * way PlayCanvas does without it.\n */\nfunction createMeshShape(\n A: AmmoNS,\n source: BufferGeometry | Object3D,\n convexHull: boolean,\n owner: Object3D,\n parts: unknown[],\n): AmmoShape {\n owner.updateWorldMatrix(true, false);\n owner.matrixWorld.decompose(_pos, _quat, _scale);\n const ownerScale = _scale.clone();\n\n const pieces: Array<{ geometry: BufferGeometry; matrix: Matrix4 }> = [];\n if (source instanceof BufferGeometry) {\n pieces.push({ geometry: source, matrix: new Matrix4() });\n } else {\n source.updateWorldMatrix(true, true);\n const inv = new Matrix4().copy(source.matrixWorld).invert();\n source.traverse((o) => {\n const mesh = o as Mesh;\n if (!mesh.isMesh || !mesh.geometry) return;\n pieces.push({ geometry: mesh.geometry, matrix: new Matrix4().multiplyMatrices(inv, mesh.matrixWorld) });\n });\n }\n\n const v0 = new A.btVector3();\n const v1 = new A.btVector3();\n const v2 = new A.btVector3();\n const p = new Vector3();\n const setV = (bt: AmmoVec3, g: BufferGeometry, i: number, m: Matrix4) => {\n const pos = g.getAttribute('position');\n p.fromBufferAttribute(pos, i).applyMatrix4(m).multiply(ownerScale);\n bt.setValue(p.x, p.y, p.z);\n };\n\n let shape: AmmoShape;\n if (convexHull) {\n const hull: AmmoConvexHull = new A.btConvexHullShape();\n for (const { geometry, matrix } of pieces) {\n const n = geometry.getAttribute('position')?.count ?? 0;\n for (let i = 0; i < n; i++) {\n setV(v0, geometry, i, matrix);\n hull.addPoint(v0, false);\n }\n }\n hull.recalcLocalAabb();\n hull.setMargin(0.01);\n shape = hull;\n } else {\n const tri = new A.btTriangleMesh();\n for (const { geometry, matrix } of pieces) {\n const pos = geometry.getAttribute('position');\n if (!pos) continue;\n const index = geometry.getIndex();\n const count = index ? index.count : pos.count;\n for (let i = 0; i + 2 < count; i += 3) {\n const a = index ? index.getX(i) : i;\n const b = index ? index.getX(i + 1) : i + 1;\n const c = index ? index.getX(i + 2) : i + 2;\n setV(v0, geometry, a, matrix);\n setV(v1, geometry, b, matrix);\n setV(v2, geometry, c, matrix);\n tri.addTriangle(v0, v1, v2, false);\n }\n }\n parts.push(tri);\n shape = new A.btBvhTriangleMeshShape(tri, true);\n }\n A.destroy(v0);\n A.destroy(v1);\n A.destroy(v2);\n return shape;\n}\n\n// Scratch, only used within one synchronous call.\nconst _pos = new Vector3();\nconst _vec = new Vector3();\nconst _scale = new Vector3();\nconst _one = new Vector3(1, 1, 1);\nconst _zero = new Vector3(0, 0, 0);\nconst _quat = new Quaternion();\nconst _quat2 = new Quaternion();\nconst _mat = new Matrix4();\nconst _mat2 = new Matrix4();\n", "import type { Scene } from '../../scene';\n\nimport type { PostFXFrameConfig, PostFXInstallContext, PostFXPass, PostFXRenderContext } from './postfx';\nimport { postFXBackendFor, type PostFXProgram } from './program';\nimport type { PostFXUniformValue } from './uniforms';\n\n/**\n * Construction options for a {@link BaseCapturingPass}.\n *\n * @group PostFX\n */\nexport interface BaseCapturingPassOptions {\n /** Debug and cache name, e.g. `'film-v1'`. */\n readonly shaderName: string;\n /**\n * GLSL fragment for `THREE.WebGLRenderer`, in PlayCanvas's dialect:\n * `uniform sampler2D uSourceTex;`, `gl_FragCoord`, `gl_FragColor`. Read the\n * source with `texelFetch(uSourceTex, ivec2(gl_FragCoord.xy), 0)`.\n */\n readonly fragmentGLSL: string;\n /**\n * WGSL fragment for `WebGPURenderer`, in PlayCanvas's dialect:\n * `var uSourceTex: texture_2d<f32>;`, `uniform name: type;` read as\n * `uniform.name`, `fn fragmentMain(input: FragmentInput) -> FragmentOutput`\n * writing `output.color`. Read the source with\n * `textureLoad(uSourceTex, vec2i(input.position.xy), 0)`. Helper functions\n * may sit above `fragmentMain`, but take uniforms as arguments.\n */\n readonly fragmentWGSL: string;\n /** Kept for PlayCanvas parity: asks for the frame through `sceneDepthMap` instead of `requireFrame`. */\n readonly needsSceneDepth?: boolean;\n}\n\n/**\n * Sets a pass's shader uniforms by name, the way PlayCanvas's `ScopeSpace`\n * does: `scope.resolve('uTint').setValue([1, 0.5, 0.5])`.\n *\n * @group PostFX\n */\nexport interface PostFXUniformScope {\n resolve(name: string): { setValue(value: PostFXUniformValue): void };\n}\n\n/**\n * Base for a capturing {@link PostFXPass} that is one fullscreen shader: it\n * reads the picture so far as `uSourceTex` and writes the next one. Give it\n * the shader in GLSL and WGSL; the GLSL runs under `THREE.WebGLRenderer`, the\n * WGSL under `WebGPURenderer`. Fragment coordinates and the source texture\n * share an origin on each backend, so sample by pixel coordinate as below and\n * the image comes out the right way up on both.\n *\n * ```ts\n * class TintPass extends BaseCapturingPass {\n * constructor(private tint = [1, 0.5, 0.5]) {\n * super({\n * shaderName: 'tint-v1',\n * fragmentGLSL: `\n * uniform sampler2D uSourceTex;\n * uniform vec3 uTint;\n * void main() {\n * vec3 c = texelFetch(uSourceTex, ivec2(gl_FragCoord.xy), 0).rgb;\n * gl_FragColor = vec4(c * uTint, 1.0);\n * }`,\n * fragmentWGSL: `\n * var uSourceTex: texture_2d<f32>;\n * uniform uTint: vec3f;\n * @fragment\n * fn fragmentMain(input: FragmentInput) -> FragmentOutput {\n * var output: FragmentOutput;\n * let c = textureLoad(uSourceTex, vec2i(input.position.xy), 0).rgb;\n * output.color = vec4f(c * uniform.uTint, 1.0);\n * return output;\n * }`,\n * });\n * }\n * protected bindUniforms(scope: PostFXUniformScope): void {\n * scope.resolve('uTint').setValue(this.tint);\n * }\n * }\n * scene.postfx.add(new TintPass());\n * ```\n *\n * @group PostFX\n */\nexport abstract class BaseCapturingPass implements PostFXPass {\n readonly capturesScene = true;\n\n /** The options given at construction. */\n protected readonly options: BaseCapturingPassOptions;\n\n /** Set from {@link configureFrame} on; kept across uninstall and install. */\n protected _scene: Scene | null = null;\n\n private _program: PostFXProgram | null = null;\n private readonly _scope: PostFXUniformScope;\n\n constructor(options: BaseCapturingPassOptions) {\n this.options = options;\n const setters = new Map<string, { setValue(value: PostFXUniformValue): void }>();\n this._scope = {\n resolve: (name) => {\n let setter = setters.get(name);\n if (!setter) {\n setter = { setValue: (value) => this._program?.set(name, value) };\n setters.set(name, setter);\n }\n return setter;\n },\n };\n }\n\n /**\n * Set the shader's own uniforms; `uSourceTex` is already bound. `target` is\n * the output's size in pixels (the canvas's, for the last pass), the way\n * PlayCanvas passes read `device.width` / `device.height`.\n */\n protected bindUniforms(\n _scope: PostFXUniformScope,\n _target: { width: number; height: number },\n _ctx: PostFXRenderContext,\n ): void {}\n\n /** Size to compose the scene at when this pass is first in the chain. Default: the canvas size. */\n getSceneCaptureSize(width: number, height: number): { width: number; height: number } {\n return { width, height };\n }\n\n configureFrame(scene: Scene, config: PostFXFrameConfig): void {\n this._scene = scene;\n if (this.options.needsSceneDepth) config.sceneDepthMap = true;\n else config.requireFrame = true;\n }\n\n install(scene: Scene, _ctx: PostFXInstallContext): void {\n this._scene = scene;\n }\n\n uninstall(_scene: Scene): void {\n this._program?.dispose();\n this._program = null;\n }\n\n render(ctx: PostFXRenderContext): void {\n this._program ??= postFXBackendFor(ctx.renderer).createProgram(ctx.renderer, {\n name: this.options.shaderName,\n glsl: this.options.fragmentGLSL,\n wgsl: this.options.fragmentWGSL,\n });\n this._program.set('uSourceTex', ctx.inputTarget.texture);\n this.bindUniforms(this._scope, { width: ctx.width, height: ctx.height }, ctx);\n this._program.draw(ctx.outputTarget);\n }\n}\n", "import { Color } from 'three';\nimport type { Camera, Material, Object3D, RenderTarget, WebGLRenderTarget } from 'three';\n\nimport type { Scene } from '../../scene';\n\n/**\n * three.js layers the effects' silhouette masks render on. Tagged objects are\n * on them only while their mask draws, so a game's own use of layers, or a\n * character re-layering its splats, never meets them; nothing else may use\n * these two.\n * @internal\n */\n// 28 and 29 belong to the relight's proxies (relight/relight-pass.ts).\nexport const PIXELART_MASK_LAYER = 31;\n/** @internal */\nexport const OUTLINE_MASK_LAYER = 30;\n\n/**\n * A tagged object: anything with an `Object3D`, or a character (an object with\n * `splats`, each with an `object3D`), whose every level of detail is tagged so\n * the mask follows whichever level is drawing.\n *\n * @group PostFX\n */\nexport type MaskTarget = Object3D | { splats: ReadonlyArray<{ object3D: Object3D }> };\n\n/** The objects a {@link MaskTarget} stands for. @internal */\nexport function maskRoots(target: MaskTarget): Object3D[] {\n const splats = (target as { splats?: ReadonlyArray<{ object3D?: Object3D }> }).splats;\n if (Array.isArray(splats)) return splats.flatMap((s) => (s?.object3D ? [s.object3D] : []));\n return [target as Object3D];\n}\n\nconst _clearColor = new Color();\nconst _tagged: Object3D[] = [];\nconst _hidden: Object3D[] = [];\nconst _colorMuted: Material[] = [];\n\n/**\n * Render the silhouettes of `roots` (their subtrees too where `recursive`)\n * into `target`, cleared to transparent black: alpha is the coverage, which is\n * all the effects read. Everything draws with its own material, so a splat's\n * mask follows its pose and opacity with no shader of its own; it does not\n * re-sort either, as the camera is the scene's own. Lights are not on the\n * layer, so meshes draw unlit, which leaves their alpha as it is.\n *\n * With `occlude`, the rest of the scene's depth is laid down first, so the\n * silhouettes are hidden where something stands in front of them - the\n * PlayCanvas build's pixel-art mask, which shares the scene's depth. Its\n * outline mask does not: an outline shows through walls.\n * @internal\n */\nexport function renderMask(\n scene: Scene,\n camera: Camera,\n roots: Iterable<{ root: Object3D; recursive: boolean }>,\n layer: number,\n target: RenderTarget,\n occlude = false,\n): void {\n const tag = (o: Object3D) => {\n if (o.layers.isEnabled(layer)) return;\n o.layers.enable(layer);\n _tagged.push(o);\n };\n for (const { root, recursive } of roots) {\n if (recursive) root.traverse(tag);\n else tag(root);\n }\n\n const r = scene.renderer;\n const three = scene.threeScene;\n const cameraMask = camera.layers.mask;\n const background = three.background;\n r.getClearColor(_clearColor);\n const clearAlpha = r.getClearAlpha();\n const autoClear = r.autoClear;\n\n three.background = null;\n r.setClearColor(0x000000, 0);\n r.autoClear = true;\n r.setRenderTarget(target as WebGLRenderTarget);\n if (occlude) {\n renderDepthOnly(scene, camera, layer);\n r.autoClear = false;\n }\n camera.layers.set(layer);\n r.render(three, camera);\n\n r.autoClear = autoClear;\n r.setClearColor(_clearColor, clearAlpha);\n three.background = background;\n camera.layers.mask = cameraMask;\n for (const o of _tagged) o.layers.disable(layer);\n _tagged.length = 0;\n}\n\n/**\n * Draw the depth of what the camera sees, minus the masked objects, with no\n * colour. Objects that write no depth (splats, transparent meshes) are hidden\n * meanwhile, so their vertex work is not paid for nothing - unless something\n * under them might write depth, in which case they only lose their colour.\n */\nfunction renderDepthOnly(scene: Scene, camera: Camera, maskLayer: number): void {\n const three = scene.threeScene;\n three.traverseVisible((o) => {\n const material = (o as { material?: Material | Material[] }).material;\n if (!material) return;\n const materials = Array.isArray(material) ? material : [material];\n const writesDepth = materials.some((m) => m.depthWrite);\n if (o.layers.isEnabled(maskLayer) || (!writesDepth && o.children.length === 0)) {\n o.visible = false;\n _hidden.push(o);\n return;\n }\n for (const m of materials) {\n if (!m.colorWrite) continue;\n m.colorWrite = false;\n _colorMuted.push(m);\n }\n });\n scene.renderer.render(three, camera);\n for (const o of _hidden) o.visible = true;\n for (const m of _colorMuted) m.colorWrite = true;\n _hidden.length = 0;\n _colorMuted.length = 0;\n}\n", "/**\n * Pixel-art upscale shader, GLSL and WGSL. Ported from the PlayCanvas build\n * unchanged: it was already written to PostFX's dialect.\n *\n * Samples the low-resolution scene with integer pixel coordinates, one output\n * pixel per canvas pixel. Fragment coordinates and the source share an origin\n * on each backend, so texelFetch / textureLoad by `gl_FragCoord` /\n * `input.position` reads the right way up on both, where UV sampling would\n * have to know which way each backend stores a render target.\n *\n * A mask the size of the low-res scene says which pixels belong to a tagged\n * character (alpha > 0.5). Character pixels sample at the fine scale;\n * environment pixels snap to a grid `uEnvSnap` source pixels wide, which is\n * what gives two pixel sizes from one scene render.\n *\n * Uniforms:\n * uSourceTex low-res scene, display colour.\n * uMaskTex character silhouettes, coverage in alpha.\n * uScale (srcW / dstW, srcH / dstH): output pixel to source texel.\n * uEnvSnap environment snap factor, >= 1.\n * uQuantLevels 0 = off, else steps per channel.\n * uDitherStrength Bayer 4x4 amplitude in quant steps (with quantize only),\n * indexed by the perceptual pixel so dither cells match the\n * pixel blocks of each region.\n * uOutlineColor / uOutlineThicknessPx / uOutlineMode / uOutlineSmoothness\n * an 8-tap ring on the mask: 0 outer, 1 inner, 2 both.\n * uEnvDarken 0..1 multiplies environment pixels by (1 - v).\n * uGradeLift / uGradeGain c * gain + lift, last.\n */\n\nexport const upscaleFragmentGLSL = /* glsl */ `\nprecision highp float;\nuniform highp sampler2D uSourceTex;\nuniform highp sampler2D uMaskTex;\nuniform vec2 uScale;\nuniform float uEnvSnap;\nuniform float uQuantLevels;\nuniform float uDitherStrength; // 0 disables. 1 = \u00B10.5 step amplitude (paired with uQuantLevels).\nuniform vec4 uOutlineColor;\nuniform float uOutlineThicknessPx;\nuniform float uOutlineMode; // 0 outer, 1 inner, 2 both\nuniform float uOutlineSmoothness; // 0 = hard step. Larger = wider smoothstep window on ring alpha.\nuniform vec3 uGradeLift; // Added to final colour. Default (0,0,0).\nuniform vec3 uGradeGain; // Multiplied with final colour. Default (1,1,1).\nuniform float uEnvDarken; // 0 = no-op, 1 = env pixels fully black. Char pixels untouched.\n\nvoid main() {\n ivec2 srcFine = ivec2(gl_FragCoord.xy * uScale);\n float maskAlpha = texelFetch(uMaskTex, srcFine, 0).a;\n bool isChar = maskAlpha > 0.5;\n\n // Perceptual pixel index - equals srcFine for char, srcFine/snap for\n // env. Used both as the source-sample coord (\u00D7snap) and as the Bayer\n // index for dither, so dither cells match the apparent pixel size\n // of whichever region we're in.\n int snap = 1;\n if (!isChar && uEnvSnap > 1.0) snap = int(uEnvSnap + 0.5);\n ivec2 perceptCoord = srcFine / snap;\n ivec2 src = perceptCoord * snap;\n\n // Scene color first - outline blends on top of it (smoothstep needs\n // both colors to mix). Tiny perf cost vs the old hard-early-return\n // path but the unified path keeps the smooth path clean.\n vec3 c = texelFetch(uSourceTex, src, 0).rgb;\n if (uQuantLevels > 0.5) {\n float lv = uQuantLevels - 1.0;\n if (uDitherStrength > 0.0) {\n // Bayer 4\u00D74 - classic ordered dither. Threshold in [-0.5, +0.5)\n // is added to the colour before snapping to the quant grid, so\n // neighbouring perceptual pixels land on different rungs.\n const float bayer[16] = float[16](\n 0.0, 8.0, 2.0, 10.0,\n 12.0, 4.0, 14.0, 6.0,\n 3.0, 11.0, 1.0, 9.0,\n 15.0, 7.0, 13.0, 5.0\n );\n int bx = perceptCoord.x & 3;\n int by = perceptCoord.y & 3;\n float threshold = (bayer[by * 4 + bx] / 16.0) - 0.5;\n c += vec3(threshold / lv * uDitherStrength);\n c = clamp(c, 0.0, 1.0);\n }\n c = floor(c * lv + 0.5) / lv;\n }\n\n // Outline. Ring max \u2192 \"ring touches char\", ring min \u2192 \"ring touches\n // env\". For OUTER on env pixels: amt rises as ringMax approaches 1.\n // For INNER on char pixels: amt rises as (1-ringMin) approaches 1\n // (i.e. ring leaks out of silhouette). smoothstep window width is\n // uOutlineSmoothness - when 0 it collapses to a hard step.\n if (uOutlineThicknessPx > 0.5) {\n bool wantOuter = (uOutlineMode < 0.5 || uOutlineMode > 1.5) && !isChar;\n bool wantInner = (uOutlineMode > 0.5) && isChar;\n if (wantOuter || wantInner) {\n ivec2 off = ivec2(uOutlineThicknessPx * uScale + 0.5);\n off = ivec2(max(off.x, 1), max(off.y, 1));\n float ringMax = 0.0;\n float ringMin = 1.0;\n float s;\n s = texelFetch(uMaskTex, srcFine + ivec2( off.x, 0), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = texelFetch(uMaskTex, srcFine + ivec2(-off.x, 0), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = texelFetch(uMaskTex, srcFine + ivec2( 0, off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = texelFetch(uMaskTex, srcFine + ivec2( 0, -off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = texelFetch(uMaskTex, srcFine + ivec2( off.x, off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = texelFetch(uMaskTex, srcFine + ivec2(-off.x, off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = texelFetch(uMaskTex, srcFine + ivec2( off.x, -off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = texelFetch(uMaskTex, srcFine + ivec2(-off.x, -off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n float t = max(uOutlineSmoothness, 0.001);\n float amt = 0.0;\n if (wantOuter) amt = max(amt, smoothstep(0.5 - t, 0.5 + t, ringMax));\n if (wantInner) amt = max(amt, smoothstep(0.5 - t, 0.5 + t, 1.0 - ringMin));\n c = mix(c, uOutlineColor.rgb, amt * uOutlineColor.a);\n }\n }\n\n // Env-only darken - multiplies env pixels by (1 - uEnvDarken). Used\n // by the death cutscene to fade the map (and untagged enemies) to\n // black while the player (still char-tagged) stays at full intensity.\n // Applied AFTER outline so outline colour fades with env, BEFORE\n // colour grade so the warm ambient still tints the dying frame.\n if (!isChar && uEnvDarken > 0.0) c *= (1.0 - uEnvDarken);\n\n // Colour grade - gain \u25E6 c + lift, clamped. Applied last so it acts\n // as a whole-frame LUT on top of scene + outline. Identity by default\n // (gain=(1,1,1), lift=(0,0,0)).\n c = clamp(c * uGradeGain + uGradeLift, 0.0, 1.0);\n\n gl_FragColor = vec4(c, 1.0);\n}\n`;\n\nexport const upscaleFragmentWGSL = /* wgsl */ `\nvar uSourceTex: texture_2d<f32>;\nvar uMaskTex: texture_2d<f32>;\nuniform uScale: vec2f;\nuniform uEnvSnap: f32;\nuniform uQuantLevels: f32;\nuniform uDitherStrength: f32;\nuniform uOutlineColor: vec4f;\nuniform uOutlineThicknessPx: f32;\nuniform uOutlineMode: f32;\nuniform uOutlineSmoothness: f32;\nuniform uGradeLift: vec3f;\nuniform uGradeGain: vec3f;\nuniform uEnvDarken: f32;\n\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let srcFine = vec2i(input.position.xy * uniform.uScale);\n let maskAlpha = textureLoad(uMaskTex, srcFine, 0).a;\n let isChar = maskAlpha > 0.5;\n\n // Perceptual pixel index - see GLSL twin for details.\n var snap: i32 = 1;\n if (!isChar && uniform.uEnvSnap > 1.0) { snap = i32(uniform.uEnvSnap + 0.5); }\n let perceptCoord = srcFine / snap;\n let src = perceptCoord * snap;\n\n // Scene first - outline blends on top so smooth and hard share the path.\n var c = textureLoad(uSourceTex, src, 0).rgb;\n if (uniform.uQuantLevels > 0.5) {\n let lv = uniform.uQuantLevels - 1.0;\n if (uniform.uDitherStrength > 0.0) {\n var bayer = array<f32, 16>(\n 0.0, 8.0, 2.0, 10.0,\n 12.0, 4.0, 14.0, 6.0,\n 3.0, 11.0, 1.0, 9.0,\n 15.0, 7.0, 13.0, 5.0\n );\n let bx = perceptCoord.x & 3;\n let by = perceptCoord.y & 3;\n let threshold = (bayer[by * 4 + bx] / 16.0) - 0.5;\n c = c + vec3f(threshold / lv * uniform.uDitherStrength);\n c = clamp(c, vec3f(0.0), vec3f(1.0));\n }\n c = floor(c * lv + 0.5) / lv;\n }\n\n if (uniform.uOutlineThicknessPx > 0.5) {\n let wantOuter = (uniform.uOutlineMode < 0.5 || uniform.uOutlineMode > 1.5) && !isChar;\n let wantInner = (uniform.uOutlineMode > 0.5) && isChar;\n if (wantOuter || wantInner) {\n var off = vec2i(uniform.uOutlineThicknessPx * uniform.uScale + 0.5);\n off = vec2i(max(off.x, 1), max(off.y, 1));\n var ringMax: f32 = 0.0;\n var ringMin: f32 = 1.0;\n var s: f32;\n s = textureLoad(uMaskTex, srcFine + vec2i( off.x, 0), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = textureLoad(uMaskTex, srcFine + vec2i(-off.x, 0), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = textureLoad(uMaskTex, srcFine + vec2i( 0, off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = textureLoad(uMaskTex, srcFine + vec2i( 0, -off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = textureLoad(uMaskTex, srcFine + vec2i( off.x, off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = textureLoad(uMaskTex, srcFine + vec2i(-off.x, off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = textureLoad(uMaskTex, srcFine + vec2i( off.x, -off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n s = textureLoad(uMaskTex, srcFine + vec2i(-off.x, -off.y), 0).a; ringMax = max(ringMax, s); ringMin = min(ringMin, s);\n let t = max(uniform.uOutlineSmoothness, 0.001);\n var amt: f32 = 0.0;\n if (wantOuter) { amt = max(amt, smoothstep(0.5 - t, 0.5 + t, ringMax)); }\n if (wantInner) { amt = max(amt, smoothstep(0.5 - t, 0.5 + t, 1.0 - ringMin)); }\n c = mix(c, uniform.uOutlineColor.rgb, amt * uniform.uOutlineColor.a);\n }\n }\n\n // Env-only darken - see GLSL twin.\n if (!isChar && uniform.uEnvDarken > 0.0) { c = c * (1.0 - uniform.uEnvDarken); }\n\n // Colour grade - see GLSL twin. Identity by default.\n c = clamp(c * uniform.uGradeGain + uniform.uGradeLift, vec3f(0.0), vec3f(1.0));\n\n output.color = vec4f(c, 1.0);\n return output;\n}\n`;\n", "import type { Object3D, RenderTarget } from 'three';\n\nimport type { Scene } from '../../scene';\nimport type { EffectColor, FrameColor } from '../postfx/camera-frame';\nimport { maskRoots, PIXELART_MASK_LAYER, renderMask, type MaskTarget } from '../postfx/mask';\nimport type { PostFXFrameConfig, PostFXInstallContext, PostFXPass, PostFXRenderContext } from '../postfx/postfx';\nimport { ensurePostFXTarget, postFXBackendFor, type PostFXProgram } from '../postfx/program';\n\nimport { upscaleFragmentGLSL, upscaleFragmentWGSL } from './pixelart-shaders';\n\n/**\n * Options for {@link PixelartEffect}. The same as the PlayCanvas build's.\n *\n * @group Pixelart\n */\nexport interface PixelartEffectOptions {\n /** Integer downscale factor for tagged characters, and for everything when `environmentScale` is unset. Default 4. */\n scale?: number;\n /**\n * Integer downscale factor for everything but tagged characters, a multiple\n * of `scale`. Larger gives the world chunkier pixels than the characters.\n * Default: `scale`.\n */\n environmentScale?: number;\n /** Per-channel colour quantisation into `levels` steps. Default off. */\n quantize?: { levels: number } | null;\n /**\n * Bayer 4x4 ordered dither before quantisation, `strength` in quant steps\n * (1 breaks banding into the classic dot pattern). Needs `quantize`. Default off.\n */\n dither?: { strength: number } | null;\n /**\n * A line around tagged characters, from the same mask: `thicknessPx` in\n * canvas pixels (at least about `scale`), `mode` where it sits relative to\n * the silhouette, `smoothness` 0 (hard) to ~0.5 (soft). Default off.\n */\n outline?: {\n color: EffectColor;\n thicknessPx?: number;\n mode?: 'outer' | 'inner' | 'both';\n smoothness?: number;\n } | null;\n /** Whole-frame grade, last: `clamp(c * gain + lift)`. Default identity. */\n colorGrade?: { lift?: FrameColor; gain?: FrameColor } | null;\n /**\n * Whether adding the effect realizes the scene's {@link CameraFrame}, as the\n * PlayCanvas build's scene-depth prepass did. Default `true`.\n */\n requireSceneDepth?: boolean;\n}\n\nconst OUTLINE_MODES = ['outer', 'inner', 'both'] as const;\n\n/**\n * Pixel-art post-process: the scene renders at a fraction of the canvas size\n * and is scaled back up with nearest-neighbour sampling, so splat edges become\n * clean pixel blocks. Optionally quantises and dithers colour, grades the\n * frame, and gives tagged characters a finer pixel than the world plus a\n * crisp outline.\n *\n * ```ts\n * const pixelart = scene.postfx.add(new PixelartEffect({ scale: 2, environmentScale: 4 }));\n * pixelart.addCharacter(hero); // finer pixels, outlined\n * pixelart.pixelScale = 3; // live\n * pixelart.destroy();\n * ```\n *\n * Characters are told apart from the world by a silhouette mask: tagged\n * objects render a second time, alone, into a small target at the scene's\n * resolution. That costs one more draw of each tagged character a frame.\n *\n * @group Pixelart\n */\nexport class PixelartEffect implements PostFXPass {\n readonly capturesScene = true;\n\n private _scale: number;\n private _envSnap: number;\n private _quantLevels: number;\n private _ditherStrength: number;\n private _outlineColor: EffectColor;\n private _outlineThickness: number;\n private _outlineMode: number;\n private _outlineSmoothness: number;\n private _gradeLift: FrameColor;\n private _gradeGain: FrameColor;\n private _envDarken = 0;\n private readonly _requireFrame: boolean;\n\n private _scene: Scene | null = null;\n private _program: PostFXProgram | null = null;\n private _mask: RenderTarget | null = null;\n /** Tagged targets and whether each covers its subtree. */\n private readonly _tags = new Map<MaskTarget, boolean>();\n private _destroyed = false;\n\n /** Shorthand for `scene.postfx.add(new PixelartEffect(opts))`. */\n static create(scene: Scene, opts: PixelartEffectOptions = {}): PixelartEffect {\n return scene.postfx.add(new PixelartEffect(opts));\n }\n\n /** A detached effect; add it with `scene.postfx.add`. */\n constructor(opts: PixelartEffectOptions = {}) {\n this._scale = Math.max(1, Math.floor(opts.scale ?? 4));\n const envScale = Math.max(this._scale, Math.floor(opts.environmentScale ?? this._scale));\n this._envSnap = Math.max(1, Math.round(envScale / this._scale));\n this._quantLevels = opts.quantize ? Math.max(2, Math.floor(opts.quantize.levels)) : 0;\n this._ditherStrength = opts.dither ? Math.max(0, opts.dither.strength) : 0;\n this._outlineColor = opts.outline?.color ?? { r: 0, g: 0, b: 0, a: 1 };\n this._outlineThickness = opts.outline ? Math.max(1, Math.floor(opts.outline.thicknessPx ?? 2)) : 0;\n this._outlineMode = OUTLINE_MODES.indexOf(opts.outline?.mode ?? 'outer');\n this._outlineSmoothness = Math.max(0, opts.outline?.smoothness ?? 0);\n this._gradeLift = opts.colorGrade?.lift ?? { r: 0, g: 0, b: 0 };\n this._gradeGain = opts.colorGrade?.gain ?? { r: 1, g: 1, b: 1 };\n this._requireFrame = opts.requireSceneDepth ?? true;\n }\n\n // \u2500\u2500 PostFXPass \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n configureFrame(scene: Scene, config: PostFXFrameConfig): void {\n this._scene = scene;\n if (this._requireFrame) config.sceneDepthMap = true;\n }\n\n getSceneCaptureSize(width: number, height: number): { width: number; height: number } {\n return { width: Math.max(1, Math.floor(width / this._scale)), height: Math.max(1, Math.floor(height / this._scale)) };\n }\n\n install(scene: Scene, _ctx: PostFXInstallContext): void {\n this._scene = scene;\n }\n\n uninstall(_scene: Scene): void {\n this._program?.dispose();\n this._program = null;\n this._mask?.dispose();\n this._mask = null;\n }\n\n render(ctx: PostFXRenderContext): void {\n const scene = this._scene;\n if (!scene) return;\n const source = ctx.inputTarget;\n const r = ctx.renderer;\n this._mask = ensurePostFXTarget(r, this._mask, source.width, source.height, { format: 'ldr', depth: true });\n // Depth-tested against the scene, as in the PlayCanvas build: no pixel-art\n // edge on a character behind a wall.\n renderMask(scene, scene.camera, this._maskRoots(), PIXELART_MASK_LAYER, this._mask, true);\n\n this._program ??= postFXBackendFor(r).createProgram(r, {\n name: 'pixelart-upscale',\n glsl: upscaleFragmentGLSL,\n wgsl: upscaleFragmentWGSL,\n });\n const p = this._program;\n const oc = this._outlineColor;\n p.set('uSourceTex', source.texture);\n p.set('uMaskTex', this._mask.texture);\n p.set('uScale', [source.width / ctx.width, source.height / ctx.height]);\n p.set('uEnvSnap', this._envSnap);\n p.set('uQuantLevels', this._quantLevels);\n p.set('uDitherStrength', this._ditherStrength);\n p.set('uOutlineColor', [oc.r, oc.g, oc.b, oc.a ?? 1]);\n p.set('uOutlineThicknessPx', this._outlineThickness);\n p.set('uOutlineMode', this._outlineMode);\n p.set('uOutlineSmoothness', this._outlineSmoothness);\n p.set('uGradeLift', [this._gradeLift.r, this._gradeLift.g, this._gradeLift.b]);\n p.set('uGradeGain', [this._gradeGain.r, this._gradeGain.g, this._gradeGain.b]);\n p.set('uEnvDarken', this._envDarken);\n p.draw(ctx.outputTarget);\n }\n\n // \u2500\u2500 live settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** The fine (character) downscale factor. Takes effect next frame. */\n get pixelScale(): number { return this._scale; }\n set pixelScale(s: number) { this._scale = Math.max(1, Math.floor(s)); }\n\n /** Environment snap factor, >= 1: environment pixels are this many character pixels wide. */\n get environmentSnap(): number { return this._envSnap; }\n set environmentSnap(s: number) { this._envSnap = Math.max(1, Math.round(s)); }\n\n /** Levels per channel, or 0 for no quantisation. */\n get quantizationLevels(): number { return this._quantLevels; }\n set quantizationLevels(levels: number) { this._quantLevels = levels > 0 ? Math.max(2, Math.floor(levels)) : 0; }\n\n /** Dither amplitude in quant steps; 0 turns it off. */\n get ditherStrength(): number { return this._ditherStrength; }\n set ditherStrength(v: number) { this._ditherStrength = Math.max(0, v); }\n\n /** Outline thickness in canvas pixels; 0 turns it off. */\n get outlineThickness(): number { return this._outlineThickness; }\n set outlineThickness(px: number) { this._outlineThickness = px > 0 ? Math.max(1, Math.floor(px)) : 0; }\n\n getOutlineColor(): EffectColor { return this._outlineColor; }\n setOutlineColor(c: EffectColor): void { this._outlineColor = c; }\n\n get outlineMode(): 'outer' | 'inner' | 'both' { return OUTLINE_MODES[this._outlineMode] ?? 'outer'; }\n set outlineMode(m: 'outer' | 'inner' | 'both') { this._outlineMode = Math.max(0, OUTLINE_MODES.indexOf(m)); }\n\n /** Outline softness, 0 (hard) to about 0.5. */\n get outlineSmoothness(): number { return this._outlineSmoothness; }\n set outlineSmoothness(v: number) { this._outlineSmoothness = Math.max(0, v); }\n\n getColorGradeLift(): FrameColor { return this._gradeLift; }\n setColorGradeLift(c: FrameColor): void { this._gradeLift = c; }\n\n getColorGradeGain(): FrameColor { return this._gradeGain; }\n setColorGradeGain(c: FrameColor): void { this._gradeGain = c; }\n\n /** Darken everything but tagged characters, 0 (off) to 1 (black): a death-cutscene fade. */\n getEnvDarken(): number { return this._envDarken; }\n setEnvDarken(v: number): void { this._envDarken = Math.max(0, Math.min(1, v)); }\n\n // \u2500\u2500 characters \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Whether `target` is tagged by {@link addCharacter}. */\n hasCharacter(target: MaskTarget): boolean {\n return this._tags.has(target);\n }\n\n /**\n * Tag a character: it samples at the fine scale, takes the outline, and is\n * spared {@link setEnvDarken}. Pass a `Character` (every level of detail is\n * tagged) or any `Object3D` (its subtree too, unless `recursive: false`);\n * a mesh paints its silhouette the same way a splat does. Re-tagging\n * replaces the tag.\n */\n addCharacter(target: MaskTarget, opts: { recursive?: boolean } = {}): void {\n if (this._destroyed) return;\n this._tags.set(target, opts.recursive ?? true);\n }\n\n /** Untag a character. No-op when it is not tagged. */\n removeCharacter(target: MaskTarget): void {\n this._tags.delete(target);\n }\n\n /** Untag every character. */\n clearCharacters(): void {\n this._tags.clear();\n }\n\n /** Remove the effect for good: out of the chain, every tag dropped. */\n destroy(): void {\n if (this._destroyed) return;\n this._scene?.postfx.remove(this);\n this.clearCharacters();\n this._destroyed = true;\n }\n\n // Resolved every frame, so a character's level of detail added after tagging is covered.\n private *_maskRoots(): Iterable<{ root: Object3D; recursive: boolean }> {\n for (const [target, recursive] of this._tags) {\n for (const root of maskRoots(target)) yield { root, recursive };\n }\n }\n}\n", "/**\n * Outline expand shader, GLSL and WGSL, ported from the PlayCanvas build.\n *\n * A fullscreen fragment over the scene: it samples the silhouette mask in an\n * 8-tap ring `uThicknessPx` pixels wide, discards pixels inside the\n * silhouette (the line is the ring, not the fill) and pixels whose ring never\n * reaches it, and writes the outline colour on the rest, alpha-blended.\n *\n * Uniforms: uMask (coverage in alpha), uTexelSize, uOutlineColor (alpha is the\n * blend), uThicknessPx, uStrength (multiplies alpha), uShimmer (how much a\n * band travelling up the screen modulates the line), uTime (seconds).\n */\n\nexport const expandFragmentGLSL = /* glsl */ `\nprecision mediump float;\nvarying vec2 vUv0;\nuniform sampler2D uMask;\nuniform vec2 uTexelSize; // (1/w, 1/h) of the mask RT\nuniform vec4 uOutlineColor; // rgba - a = blend strength\nuniform float uThicknessPx;\nuniform float uStrength; // 0..1, multiplies the alpha\nuniform float uShimmer; // 0..1, how much the travelling band modulates\nuniform float uTime; // seconds\n\nvoid main() {\n // Use integer pixel coordinates instead of vUv0 so mask and present\n // stay in the same screen-space orientation on both WebGL and WebGPU.\n // Sampling the mask RT with vUv0 was visually Y-flipped under WebGPU\n // (render-target origin convention differs), which made the outline\n // render upside-down relative to the character.\n ivec2 texel = ivec2(gl_FragCoord.xy);\n float center = texelFetch(uMask, texel, 0).a;\n // Inside the silhouette \u2192 the outline belongs on the boundary, not\n // the fill. Discard so the scene underneath shows through.\n if (center > 0.5) discard;\n\n int off = int(uThicknessPx + 0.5);\n\n // 8-tap ring. Hard step - any ring sample inside the silhouette\n // means this pixel is within thicknessPx of the silhouette\n // boundary, so we emit the outline colour.\n float s = 0.0;\n s = max(s, texelFetch(uMask, texel + ivec2( off, 0), 0).a);\n s = max(s, texelFetch(uMask, texel + ivec2(-off, 0), 0).a);\n s = max(s, texelFetch(uMask, texel + ivec2( 0, off), 0).a);\n s = max(s, texelFetch(uMask, texel + ivec2( 0, -off), 0).a);\n s = max(s, texelFetch(uMask, texel + ivec2( off, off), 0).a);\n s = max(s, texelFetch(uMask, texel + ivec2(-off, off), 0).a);\n s = max(s, texelFetch(uMask, texel + ivec2( off, -off), 0).a);\n s = max(s, texelFetch(uMask, texel + ivec2(-off, -off), 0).a);\n\n if (s < 0.5) discard;\n\n // A soft band travelling up the screen while selected: the line breathes\n // along the body instead of sitting dead on it.\n float band = 0.5 + 0.5 * sin(vUv0.y * 18.0 - uTime * 1.6);\n float shimmer = mix(1.0, 0.55 + 0.45 * band, uShimmer);\n gl_FragColor = vec4(uOutlineColor.rgb, uOutlineColor.a * uStrength * shimmer);\n}\n`;\n\nexport const expandFragmentWGSL = /* wgsl */ `\nvar uMask: texture_2d<f32>;\nuniform uTexelSize: vec2f;\nuniform uOutlineColor: vec4f;\nuniform uThicknessPx: f32;\nuniform uStrength: f32;\nuniform uShimmer: f32;\nuniform uTime: f32;\n\n\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n // Use integer pixel coordinates (from @builtin(position)) so mask and\n // present stay in the same screen-space orientation. Sampling the mask\n // RT via UV was visually Y-flipped under WebGPU (render-target origin\n // convention differs), producing an upside-down outline.\n let texel = vec2i(input.position.xy);\n let center = textureLoad(uMask, texel, 0).a;\n if (center > 0.5) { discard; }\n\n let off = i32(uniform.uThicknessPx + 0.5);\n\n var s: f32 = 0.0;\n s = max(s, textureLoad(uMask, texel + vec2i( off, 0), 0).a);\n s = max(s, textureLoad(uMask, texel + vec2i(-off, 0), 0).a);\n s = max(s, textureLoad(uMask, texel + vec2i( 0, off), 0).a);\n s = max(s, textureLoad(uMask, texel + vec2i( 0, -off), 0).a);\n s = max(s, textureLoad(uMask, texel + vec2i( off, off), 0).a);\n s = max(s, textureLoad(uMask, texel + vec2i(-off, off), 0).a);\n s = max(s, textureLoad(uMask, texel + vec2i( off, -off), 0).a);\n s = max(s, textureLoad(uMask, texel + vec2i(-off, -off), 0).a);\n\n if (s < 0.5) { discard; }\n\n let band = 0.5 + 0.5 * sin(input.vUv0.y * 18.0 - uniform.uTime * 1.6);\n let shimmer = mix(1.0, 0.55 + 0.45 * band, uniform.uShimmer);\n output.color = vec4f(uniform.uOutlineColor.rgb, uniform.uOutlineColor.a * uniform.uStrength * shimmer);\n return output;\n}\n`;\n", "import type { Camera, Object3D, RenderTarget, Texture } from 'three';\n\nimport type { Scene } from '../../scene';\nimport type { EffectColor } from '../postfx/camera-frame';\nimport { maskRoots, OUTLINE_MASK_LAYER, renderMask, type MaskTarget } from '../postfx/mask';\nimport type { PostFXOverlay } from '../postfx/postfx';\nimport { ensurePostFXTarget, postFXBackendFor, type PostFXProgram } from '../postfx/program';\n\nimport { expandFragmentGLSL, expandFragmentWGSL } from './outline-shaders';\n\n/**\n * Options for {@link OutlineEffect}.\n *\n * @group Outlines\n */\nexport interface OutlineEffectOptions {\n /** Line colour; alpha is how strongly it covers the scene. Default purple (0.6, 0.2, 1, 1). */\n color?: EffectColor;\n /** Line thickness in pixels, constant across zoom. Default 3. */\n thicknessPx?: number;\n /** The camera the silhouettes are drawn from. Default: the scene's camera. */\n mainCamera?: Camera;\n}\n\n/**\n * Options for {@link OutlineEffect.add}.\n *\n * @group Outlines\n */\nexport interface OutlineAddOptions {\n /** Outline the object's descendants too, such as a held weapon. Default `true`. */\n recursive?: boolean;\n}\n\n/**\n * Per-object outlines: a line of one colour around everything tagged, drawn\n * over the scene and through anything in front of it.\n *\n * ```ts\n * const outlines = new OutlineEffect(scene, { color: { r: 1, g: 1, b: 1, a: 1 }, thicknessPx: 3 });\n * outlines.add(hero); // a Character, or any Object3D\n * outlines.remove(hero);\n * outlines.destroy();\n * ```\n *\n * Each frame something is tagged, the tagged objects render alone into a\n * silhouette mask, then a fullscreen pass draws the ring around it onto the\n * scene, before the {@link CameraFrame} (if any) composes it. That is a\n * second draw of every tagged object; untag rather than set the strength to\n * 0 to save it.\n *\n * @group Outlines\n */\nexport class OutlineEffect implements PostFXOverlay {\n private readonly _scene: Scene;\n private readonly _camera: Camera;\n private _color: EffectColor;\n private _thickness: number;\n private _strength = 1;\n private _shimmer = 0;\n private _time = 0;\n private _mask: RenderTarget | null = null;\n private _program: PostFXProgram | null = null;\n private readonly _tags = new Map<MaskTarget, boolean>();\n private _destroyed = false;\n\n constructor(scene: Scene, opts: OutlineEffectOptions = {}) {\n this._scene = scene;\n this._camera = opts.mainCamera ?? scene.camera;\n this._color = opts.color ?? { r: 0.6, g: 0.2, b: 1, a: 1 };\n this._thickness = Math.max(1, opts.thicknessPx ?? 3);\n scene.postfx.addOverlay(this);\n }\n\n /** Line colour; alpha is the blend. Takes effect next frame. */\n get outlineColor(): EffectColor { return this._color; }\n set outlineColor(c: EffectColor) { this._color = c; }\n\n /** Line thickness in pixels. */\n get outlineThickness(): number { return this._thickness; }\n set outlineThickness(px: number) { this._thickness = Math.max(1, px); }\n\n /** The silhouette mask of everything tagged, coverage in alpha; null before the first frame. */\n get maskTexture(): Texture | null {\n return this._mask?.texture ?? null;\n }\n\n /**\n * Outline `target`: a `Character` (every level of detail), or any\n * `Object3D` and, unless `recursive: false`, its subtree. Re-tagging\n * replaces the tag.\n */\n add(target: MaskTarget, opts: OutlineAddOptions = {}): void {\n if (this._destroyed) return;\n this._tags.set(target, opts.recursive ?? true);\n }\n\n /** Whether `target` is outlined. */\n has(target: MaskTarget): boolean {\n return this._tags.has(target);\n }\n\n /** Stop outlining `target`. No-op when it is not outlined. */\n remove(target: MaskTarget): void {\n this._tags.delete(target);\n }\n\n /** Stop outlining everything. */\n clear(): void {\n this._tags.clear();\n }\n\n /**\n * Change the line's look, per frame if wanted: `color` (alpha the base\n * blend), `thicknessPx`, `strength` 0..1 multiplying the alpha (0 draws\n * nothing, so a hover can fade the line in), and `shimmer` 0..1, a soft\n * band travelling up the screen at `time` seconds.\n */\n setLook(look: {\n color?: EffectColor;\n thicknessPx?: number;\n strength?: number;\n shimmer?: number;\n time?: number;\n }): void {\n if (look.color) this._color = { r: look.color.r, g: look.color.g, b: look.color.b, a: look.color.a ?? this._color.a };\n if (look.thicknessPx !== undefined) this._thickness = Math.max(1, look.thicknessPx);\n if (look.strength !== undefined) this._strength = Math.max(0, Math.min(1, look.strength));\n if (look.shimmer !== undefined) this._shimmer = Math.max(0, Math.min(1, look.shimmer));\n if (look.time !== undefined) this._time = look.time;\n }\n\n /** Tear everything down. Safe to call more than once. */\n destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n this._scene.postfx.removeOverlay(this);\n this.clear();\n this._mask?.dispose();\n this._program?.dispose();\n this._mask = null;\n this._program = null;\n }\n\n /** @internal */\n renderOverlay(target: RenderTarget | null, width: number, height: number): void {\n if (this._tags.size === 0 || this._strength <= 0) return;\n const r = this._scene.renderer;\n this._mask = ensurePostFXTarget(r, this._mask, width, height, { format: 'ldr', depth: true });\n renderMask(this._scene, this._camera, this._maskRoots(), OUTLINE_MASK_LAYER, this._mask);\n\n this._program ??= postFXBackendFor(r).createProgram(r, {\n name: 'outline-expand',\n glsl: expandFragmentGLSL,\n wgsl: expandFragmentWGSL,\n blend: 'alpha',\n });\n const p = this._program;\n const c = this._color;\n p.set('uMask', this._mask.texture);\n p.set('uTexelSize', [1 / width, 1 / height]);\n p.set('uThicknessPx', this._thickness);\n p.set('uOutlineColor', [c.r, c.g, c.b, c.a ?? 1]);\n p.set('uStrength', this._strength);\n p.set('uShimmer', this._shimmer);\n p.set('uTime', this._time);\n p.draw(target);\n }\n\n private *_maskRoots(): Iterable<{ root: Object3D; recursive: boolean }> {\n for (const [target, recursive] of this._tags) {\n for (const root of maskRoots(target)) yield { root, recursive };\n }\n }\n}\n", "/**\n * Thin wrapper around the Ammo constraint API that {@link PhysicsWorld}\n * doesn't wrap itself. Construct via the helpers below; each returns a\n * {@link JointHandle} whose `remove()` detaches the constraint from the\n * dynamics world and frees the native object.\n *\n * Why this exists: ragdolls, hinged doors, swinging ropes and chains of\n * bodies all need raw Bullet constraints. Joints made here are tied to their\n * bodies: {@link PhysicsWorld.removeBody} removes them first, and a body that\n * rebuilds its native object (a `type` change) has them re-made against the\n * new one, so Bullet never steps a constraint on a freed body.\n *\n * Ported from the PlayCanvas build, where the bodies are entities with a\n * `rigidbody` component. Here they are {@link RigidBody}s, and the options\n * drop `app` (the world is the bodies').\n *\n * @module\n * @group Physics\n */\n\nimport { Quaternion, Vector3 } from 'three';\n\nimport { ammo } from './ammo';\nimport type { AmmoConstraint, AmmoDynamicsWorld, AmmoTransform } from './ammo';\nimport type { BodyAttachment, PhysicsWorld } from './physics-world';\nimport type { RigidBody, XYZ, XYZW } from './rigid-body';\n\nfunction bodyOf(body: RigidBody) {\n const b = body.ammoBody;\n if (!b) {\n throw new Error(\n `[joints] '${body.object.name}' has no live rigid body. ` +\n 'Create joints between bodies that are still in the world.',\n );\n }\n return b;\n}\n\nfunction worldOf(a: RigidBody, b: RigidBody): PhysicsWorld {\n if (a.world !== b.world) throw new Error('[joints] the two bodies belong to different physics worlds.');\n return a.world;\n}\n\n/** A copy of a vector option, so a rebuilt joint never sees the caller's later edits. */\nfunction copyXYZ(v: XYZ): XYZ {\n return { x: v.x, y: v.y, z: v.z };\n}\n\n/** A copy of a frame option; see {@link copyXYZ}. */\nfunction copyFrame(f: { position: XYZ; rotation: XYZW }): { position: XYZ; rotation: XYZW } {\n return { position: copyXYZ(f.position), rotation: { x: f.rotation.x, y: f.rotation.y, z: f.rotation.z, w: f.rotation.w } };\n}\n\n/** Build an Ammo btTransform from a pose. Caller owns destroy(). */\nfunction makeXform(pos: XYZ, rot: XYZW): AmmoTransform {\n const A = ammo();\n const t = new A.btTransform();\n t.setIdentity();\n // Bullet copies setOrigin / setRotation inputs by value, so we can free\n // the temporaries immediately.\n const p = new A.btVector3(pos.x, pos.y, pos.z);\n t.setOrigin(p);\n A.destroy(p);\n const q = new A.btQuaternion(rot.x, rot.y, rot.z, rot.w);\n t.setRotation(q);\n A.destroy(q);\n return t;\n}\n\n/**\n * Reference to a live joint. `remove()` detaches the constraint and frees\n * the underlying Ammo object. Idempotent.\n *\n * @group Physics\n */\nexport interface JointHandle {\n /** Detach from the dynamics world and free the underlying Ammo\n * object. Idempotent. */\n remove(): void;\n /** True if the constraint has been broken by Bullet's solver (its\n * applied impulse exceeded the configured `breakImpulse`). Always\n * `true` after `remove()`. */\n isBroken(): boolean;\n}\n\n/**\n * How far apart (m) a breakable joint's two anchors may drift before it\n * counts as broken, on Ammo builds without `getAppliedImpulse`. A held\n * joint keeps its locked anchors within millimetres; one Bullet has\n * disabled lets them fly apart.\n */\nconst BROKEN_SEPARATION = 0.08;\n\n/** Makes the native constraint between two live Ammo bodies. */\ntype ConstraintFactory = (bA: ReturnType<typeof bodyOf>, bB: ReturnType<typeof bodyOf>) => AmmoConstraint;\n\nclass Joint implements JointHandle, BodyAttachment {\n readonly bodyA: RigidBody;\n readonly bodyB: RigidBody;\n private _c: AmmoConstraint | null;\n private readonly _world: PhysicsWorld;\n private readonly _native: AmmoDynamicsWorld;\n private readonly _make: ConstraintFactory;\n private readonly _disableCollision: boolean;\n /** Set while a body is rebuilding: the constraint is gone, the joint is not. */\n private _suspended = false;\n /** Breaking threshold (N\u00B7s) stored on the wrapper for our own poll;\n * `0` means \"unbreakable\". */\n private readonly _breakThreshold: number;\n /** Joint anchor in each body's local frame, for the separation test. */\n private readonly _anchorA: Vector3 | null;\n private readonly _anchorB: Vector3 | null;\n private _broken = false;\n\n constructor(\n world: PhysicsWorld, bodyA: RigidBody, bodyB: RigidBody, make: ConstraintFactory,\n disableCollision: boolean, breakThreshold: number, anchorA?: XYZ, anchorB?: XYZ,\n ) {\n this._world = world;\n this._native = world.dynamicsWorld;\n this.bodyA = bodyA;\n this.bodyB = bodyB;\n this._make = make;\n this._disableCollision = disableCollision;\n this._c = make(bodyOf(bodyA), bodyOf(bodyB));\n this._native.addConstraint(this._c, disableCollision);\n this._breakThreshold = breakThreshold;\n this._anchorA = anchorA ? new Vector3(anchorA.x, anchorA.y, anchorA.z) : null;\n this._anchorB = anchorB ? new Vector3(anchorB.x, anchorB.y, anchorB.z) : null;\n world._attach(this);\n }\n\n remove(): void {\n if (this._suspended) {\n this._suspended = false;\n this._world._detach(this);\n return;\n }\n if (!this._c) return;\n this._native.removeConstraint(this._c);\n ammo().destroy(this._c);\n this._c = null;\n this._world._detach(this);\n }\n\n /** @internal A body is about to free its native object: drop the constraint, keep the joint. */\n suspend(): void {\n if (!this._c) return;\n // A joint that has already broken stays broken rather than being re-made.\n if (this.isBroken()) {\n this.remove();\n return;\n }\n this._native.removeConstraint(this._c);\n ammo().destroy(this._c);\n this._c = null;\n this._suspended = true;\n }\n\n /** @internal Both bodies have native objects again: re-make the constraint. */\n resume(): void {\n if (!this._suspended) return;\n this._suspended = false;\n this._c = this._make(bodyOf(this.bodyA), bodyOf(this.bodyB));\n this._native.addConstraint(this._c, this._disableCollision);\n }\n\n isBroken(): boolean {\n if (this._suspended) return false;\n if (!this._c) return true;\n if (this._broken) return true;\n if (this._breakThreshold > 0) {\n // Bullet disables the constraint once its applied impulse passes the\n // threshold. Read that impulse where the build exposes it; the games'\n // Ammo build exposes neither it nor isEnabled(), so there the joint\n // counts as broken once its anchors come apart.\n const c = this._c;\n const broken = c.getAppliedImpulse\n ? Math.abs(c.getAppliedImpulse()) > this._breakThreshold\n : this._anchorSeparation() > BROKEN_SEPARATION;\n if (broken) {\n this._broken = true;\n return true;\n }\n }\n return false;\n }\n\n private _anchorSeparation(): number {\n if (!this._anchorA || !this._anchorB) return 0;\n anchorWorld(this.bodyA, this._anchorA, _sepA);\n anchorWorld(this.bodyB, this._anchorB, _sepB);\n return _sepA.distanceTo(_sepB);\n }\n}\n\n/** Where a body-local point is now, from the body's (uninterpolated) transform. */\nfunction anchorWorld(body: RigidBody, local: Vector3, out: Vector3): Vector3 {\n const t = body.ammoBody!.getWorldTransform();\n const o = t.getOrigin();\n const q = t.getRotation();\n _sepQ.set(q.x(), q.y(), q.z(), q.w());\n return out.copy(local).applyQuaternion(_sepQ).add(_sepO.set(o.x(), o.y(), o.z()));\n}\n\nconst _sepA = new Vector3();\nconst _sepB = new Vector3();\nconst _sepO = new Vector3();\nconst _sepQ = new Quaternion();\n\n/**\n * Options for {@link createConeTwistJoint}.\n *\n * @group Physics\n */\nexport interface ConeTwistJointOptions {\n bodyA: RigidBody;\n bodyB: RigidBody;\n /** Joint anchor in `bodyA`'s local space. */\n frameInA: { position: XYZ; rotation: XYZW };\n /** Joint anchor in `bodyB`'s local space. */\n frameInB: { position: XYZ; rotation: XYZW };\n /** Cone half-angle about the joint's local Y axis (radians). Default \u03C0/4. */\n swingY?: number;\n /** Cone half-angle about the joint's local Z axis (radians). Default \u03C0/4. */\n swingZ?: number;\n /** Twist half-angle about the joint's local X axis (radians). Default \u03C0/6. */\n twist?: number;\n /**\n * When true, the two bodies stop colliding with each other - required\n * for limb pairs whose colliders overlap at the joint. Default `true`.\n */\n disableCollisionBetweenLinkedBodies?: boolean;\n}\n\n/**\n * Create a cone-twist constraint between two bodies. Models ball-and-\n * socket joints (shoulder, hip, neck) - bodyB can swing within an\n * elliptical cone of bodyA and twist around the cone's axis.\n *\n * @group Physics\n */\nexport function createConeTwistJoint(opts: ConeTwistJointOptions): JointHandle {\n const world = worldOf(opts.bodyA, opts.bodyB);\n // Taken now: `make` runs again whenever a body rebuilds.\n const frameInA = copyFrame(opts.frameInA);\n const frameInB = copyFrame(opts.frameInB);\n const swingY = opts.swingY ?? Math.PI / 4;\n const swingZ = opts.swingZ ?? Math.PI / 4;\n const twist = opts.twist ?? Math.PI / 6;\n const make: ConstraintFactory = (bA, bB) => {\n const A = ammo();\n const fA = makeXform(frameInA.position, frameInA.rotation);\n const fB = makeXform(frameInB.position, frameInB.rotation);\n const c = new A.btConeTwistConstraint(bA, bB, fA, fB);\n c.setLimit(swingY, swingZ, twist);\n A.destroy(fA);\n A.destroy(fB);\n return c;\n };\n return new Joint(world, opts.bodyA, opts.bodyB, make, opts.disableCollisionBetweenLinkedBodies ?? true, 0);\n}\n\n/**\n * Options for {@link createHingeJoint}.\n *\n * @group Physics\n */\nexport interface HingeJointOptions {\n bodyA: RigidBody;\n bodyB: RigidBody;\n /** Hinge pivot in `bodyA`'s local space. */\n pivotInA: XYZ;\n /** Hinge pivot in `bodyB`'s local space. */\n pivotInB: XYZ;\n /** Hinge axis in `bodyA`'s local space. Need not be unit-length. */\n axisInA: XYZ;\n /** Hinge axis in `bodyB`'s local space. */\n axisInB: XYZ;\n /** Lower hinge angle (radians). Default \u2212\u03C0 (no lower stop). */\n lowLimit?: number;\n /** Upper hinge angle (radians). Default \u03C0 (no upper stop). */\n highLimit?: number;\n /** See {@link ConeTwistJointOptions.disableCollisionBetweenLinkedBodies}. */\n disableCollisionBetweenLinkedBodies?: boolean;\n}\n\n/**\n * Options for {@link createGeneric6DofJoint}.\n *\n * @group Physics\n */\nexport interface Generic6DofJointOptions {\n bodyA: RigidBody;\n bodyB: RigidBody;\n /** Joint frame in `bodyA`'s local space. */\n frameInA: { position: XYZ; rotation: XYZW };\n /** Joint frame in `bodyB`'s local space. */\n frameInB: { position: XYZ; rotation: XYZW };\n /** Translation limits per axis (in the joint frame). Default `(0,0,0)` /\n * `(0,0,0)` - fully locked, the typical ball-and-socket case. */\n linearLowerLimit?: XYZ;\n linearUpperLimit?: XYZ;\n /** Rotation limits per axis (radians). Conventions in `btGeneric6DofConstraint`:\n * - `lower < upper`: axis is limited to that range\n * - `lower == upper`: axis is fully locked\n * - `lower > upper`: axis is free (no limit)\n *\n * For a cone-twist-style joint where frame X is the twist/cone axis:\n * `lower = (-twist, -swingY, -swingZ)`, `upper = (twist, swingY, swingZ)`. */\n angularLowerLimit: XYZ;\n angularUpperLimit: XYZ;\n /**\n * Breaking impulse threshold (N\u00B7s). When the constraint's applied\n * impulse exceeds this value in a single physics step, Bullet\n * auto-disables the constraint and the two bodies become free of each\n * other. Poll {@link JointHandle.isBroken} each frame to react. Omit for\n * an unbreakable joint.\n */\n breakImpulse?: number;\n /** See {@link ConeTwistJointOptions.disableCollisionBetweenLinkedBodies}. */\n disableCollisionBetweenLinkedBodies?: boolean;\n}\n\n/**\n * Create a generic 6-DOF constraint between two bodies. The workhorse\n * for ragdoll joints - independently constrain translation and rotation\n * on each axis of a joint frame. More numerically robust than\n * {@link createConeTwistJoint} for the asymmetric body orientations\n * typical of ragdoll shoulders / hips.\n *\n * @group Physics\n */\nexport function createGeneric6DofJoint(opts: Generic6DofJointOptions): JointHandle {\n const world = worldOf(opts.bodyA, opts.bodyB);\n // Taken now: `make` runs again whenever a body rebuilds.\n const frameInA = copyFrame(opts.frameInA);\n const frameInB = copyFrame(opts.frameInB);\n const linLow = copyXYZ(opts.linearLowerLimit ?? _zero3);\n const linHigh = copyXYZ(opts.linearUpperLimit ?? _zero3);\n const aLow = copyXYZ(opts.angularLowerLimit);\n const aHigh = copyXYZ(opts.angularUpperLimit);\n const breakImpulse = opts.breakImpulse;\n const make: ConstraintFactory = (bA, bB) => {\n const A = ammo();\n const fA = makeXform(frameInA.position, frameInA.rotation);\n const fB = makeXform(frameInB.position, frameInB.rotation);\n // useLinearReferenceFrameA = true: linear constraints measured in\n // body A's frame (the common choice for joints).\n const c = new A.btGeneric6DofConstraint(bA, bB, fA, fB, true);\n\n const vLL = new A.btVector3(linLow.x, linLow.y, linLow.z);\n c.setLinearLowerLimit(vLL); A.destroy(vLL);\n const vLU = new A.btVector3(linHigh.x, linHigh.y, linHigh.z);\n c.setLinearUpperLimit(vLU); A.destroy(vLU);\n\n const vAL = new A.btVector3(aLow.x, aLow.y, aLow.z);\n c.setAngularLowerLimit(vAL); A.destroy(vAL);\n const vAU = new A.btVector3(aHigh.x, aHigh.y, aHigh.z);\n c.setAngularUpperLimit(vAU); A.destroy(vAU);\n\n if (breakImpulse !== undefined) {\n // Bullet's own break-on-threshold path: the solver disables the\n // constraint mid-solve, which is what actually frees the bodies.\n c.setBreakingImpulseThreshold(breakImpulse);\n }\n A.destroy(fA);\n A.destroy(fB);\n return c;\n };\n // Anchors are only compared when the translation is locked; with linear\n // slack the frames legitimately drift apart.\n const locked = linLow.x === 0 && linLow.y === 0 && linLow.z === 0 &&\n linHigh.x === 0 && linHigh.y === 0 && linHigh.z === 0;\n return new Joint(\n world, opts.bodyA, opts.bodyB, make, opts.disableCollisionBetweenLinkedBodies ?? true, breakImpulse ?? 0,\n locked ? frameInA.position : undefined,\n locked ? frameInB.position : undefined,\n );\n}\n\nconst _zero3: XYZ = { x: 0, y: 0, z: 0 };\n\n/**\n * Create a hinge constraint between two bodies. Models single-axis joints\n * like elbows, knees, and doors. Set `lowLimit`/`highLimit` to author\n * realistic limb ranges (e.g. an elbow swings 0 \u2192 +2.4 rad, not the full\n * \u00B1\u03C0 default).\n *\n * @group Physics\n */\nexport function createHingeJoint(opts: HingeJointOptions): JointHandle {\n const world = worldOf(opts.bodyA, opts.bodyB);\n // Taken now: `make` runs again whenever a body rebuilds.\n const pivotInA = copyXYZ(opts.pivotInA);\n const pivotInB = copyXYZ(opts.pivotInB);\n const axisInA = copyXYZ(opts.axisInA);\n const axisInB = copyXYZ(opts.axisInB);\n const lowLimit = opts.lowLimit ?? -Math.PI;\n const highLimit = opts.highLimit ?? Math.PI;\n const make: ConstraintFactory = (bA, bB) => {\n const A = ammo();\n const pA = new A.btVector3(pivotInA.x, pivotInA.y, pivotInA.z);\n const pB = new A.btVector3(pivotInB.x, pivotInB.y, pivotInB.z);\n const aA = new A.btVector3(axisInA.x, axisInA.y, axisInA.z);\n const aB = new A.btVector3(axisInB.x, axisInB.y, axisInB.z);\n const c = new A.btHingeConstraint(bA, bB, pA, pB, aA, aB);\n c.setLimit(lowLimit, highLimit);\n A.destroy(pA);\n A.destroy(pB);\n A.destroy(aA);\n A.destroy(aB);\n return c;\n };\n return new Joint(world, opts.bodyA, opts.bodyB, make, opts.disableCollisionBetweenLinkedBodies ?? true, 0);\n}\n", "/**\n * Ragdoll: physics-driven {@link PoseProvider} for a character.\n *\n * ## Mode is strictly binary\n *\n * When the ragdoll is enabled, animation evaluation is fully replaced\n * by physics. No per-bone blend, no transition window. This is a\n * deliberate design choice - it keeps the pose write-back path simple\n * and makes it unambiguous which subsystem owns the pose at any\n * moment. If you need \"the right arm goes ragdoll while the rest\n * keeps animating,\" this module isn't it; you'd build a partial-mask\n * pose provider on the same {@link PoseProvider} hook instead.\n *\n * ## Rig conventions\n *\n * Bodies are placed assuming each bone's bind-pose **direction** is\n * captured by `endBoneName` in the config (e.g. pelvis's direction is\n * the vector to spine_03). For terminal bones without a useful end\n * bone (head, hand, foot), the body axis defaults to the bone's\n * bind-pose **local +Y** in model space - true for UE-style rigs that\n * follow the standard humanoid bone naming (`pelvis`, `spine_NN`,\n * `upperarm_l/r`, etc.). Other rig conventions can be supported by\n * authoring a {@link RagdollConfig} that specifies `endBoneName`\n * everywhere instead of relying on the fallback.\n *\n * Ported from the PlayCanvas build. The bone math is unchanged (it runs on\n * the same `Mat4` / `Quat` kernel); the body entities become `Object3D`s\n * carrying a {@link RigidBody} in the scene's {@link PhysicsWorld}.\n *\n * @module\n * @group Ragdoll\n */\n\nimport { BufferAttribute, BufferGeometry, Group, LineBasicMaterial, LineSegments, Matrix4, Object3D, Quaternion, Vector3 } from 'three';\n\nimport { computeBindPoseTransforms } from '../anim/bind-pose';\nimport type { Armature, PoseProvider } from '../armature';\nimport type { SplatEngine } from '../engine';\nimport { Mat4, Quat, Vec3 } from '../math';\nimport { createGeneric6DofJoint } from '../physics/joints';\nimport type { JointHandle } from '../physics/joints';\nimport type { PhysicsWorld } from '../physics/physics-world';\nimport { setObjectWorldPose } from '../physics/rigid-body';\nimport type { RigidBody, XYZ } from '../physics/rigid-body';\n\nimport type { Pose } from './pose';\nimport { DEFAULT_HUMANOID_RAGDOLL } from './ragdoll-config';\nimport type {\n RagdollBoneDesc,\n RagdollConfig,\n RagdollJointDesc,\n} from './ragdoll-config';\nimport type { Skeleton } from './skeleton';\n\n/**\n * Information passed to {@link Ragdoll.onLimbDetached} listeners.\n *\n * @group Ragdoll\n */\nexport interface LimbDetachedInfo {\n /** Bone name (as authored in the config) whose joint just severed. */\n boneName: string;\n /** World-space position of the joint anchor at the moment of\n * severance. A natural spawn point for blood/spark VFX. */\n worldPos: Vector3;\n}\n\n/**\n * Physics-driven ragdoll for a character. Owns one capsule rigid body\n * per configured bone plus the joints between them. Implements\n * {@link PoseProvider}; the Armature itself has no ragdoll knowledge.\n *\n * Lifecycle:\n * - Construct: cheap, no bodies yet, just resolves bone names.\n * - `enable()`: build bodies + joints at the armature's current\n * pose, install as the armature's `poseProvider`.\n * - `applyImpulse(boneName, impulse)`: kick a specific body.\n * - `disable()`: tear down, animation resumes.\n *\n * Bodies parent to the engine's `contentRoot` (not the armature's\n * object); once active they have their own world transforms driven by\n * Ammo. The armature object stays put - the pose write-back absorbs\n * the world position into bone-local TRS, so the splat deforms to the\n * physics-driven world either way. Trade-off: distance-LOD / frustum\n * culling bands are computed against the spawn origin, not the\n * ragdoll's drift. Fine for short-distance ragdolls.\n *\n * Requires a physics world: the armature's {@link Scene} created with\n * {@link CreateSceneOptions.physics}, or one passed to the constructor;\n * {@link enable} throws otherwise.\n *\n * @group Ragdoll\n */\nexport class Ragdoll implements PoseProvider {\n private readonly _armature: Armature;\n private readonly _engine: SplatEngine;\n private readonly _armatureObject: Object3D;\n private readonly _skeleton: Skeleton;\n private readonly _bindWorld: Mat4[];\n /** Live reference to the armature's per-bone world matrices. */\n private readonly _worldTransforms: readonly Mat4[];\n\n /** Ragdoll bone records, ordered to match the config. */\n private readonly _bones: RagdollBone[] = [];\n /** boneIdx \u2192 ragdoll-bone record (lookup for parent-chain walks). */\n private readonly _byBoneIdx = new Map<number, RagdollBone>();\n\n private _active = false;\n private _physics: PhysicsWorld | null = null;\n private _container: Group | null = null;\n private _joints: JointHandle[] = [];\n\n // Workspace mat4s reused per-frame in writePose.\n private readonly _tmpMat = new Mat4();\n private readonly _tmpMat2 = new Mat4();\n private readonly _entityWorld = new Mat4();\n\n // Per-bone world-transform cache for writePose, allocated lazily on\n // first use and reused across frames. `_writePoseHas[i]` is the\n // \"populated this frame\" flag - cheaper to reset than to refill the\n // matrix array with nulls.\n private _writePoseBoneWorld: Mat4[] = [];\n private _writePoseHas: boolean[] = [];\n\n /**\n * Build a Ragdoll bound to `armature`. The armature must already be\n * attached to an engine (a character loaded into a scene).\n *\n * @param args.armature - Target armature. Must already be attached to a scene.\n * @param args.config - Bone/joint descriptor. Defaults to\n * {@link DEFAULT_HUMANOID_RAGDOLL} (works for any rig that follows\n * the standard UE-style bone naming).\n * @param args.physics - The world to simulate in. Defaults to the\n * armature's scene's {@link Scene.physics}; pass one for an engine\n * driven by your own loop rather than a {@link Scene}.\n */\n constructor(args: {\n armature: Armature;\n config?: RagdollConfig;\n physics?: PhysicsWorld;\n }) {\n const engine = args.armature.engine;\n if (!engine) {\n throw new Error('[Ragdoll] armature is not attached to a scene yet.');\n }\n\n this._armature = args.armature;\n this._engine = engine;\n this._physics = args.physics ?? null;\n this._armatureObject = args.armature.object3D;\n this._skeleton = args.armature.skeleton;\n this._worldTransforms = args.armature.boneWorldMatrices;\n\n this._bindWorld = computeBindPoseTransforms(\n this._skeleton.numBones,\n this._skeleton.bindT,\n this._skeleton.bindR,\n this._skeleton.parents,\n );\n\n // Build a name\u2192idx lookup, then resolve every config entry. Skip any\n // entry whose bone (or end bone, or parent) is missing - config is\n // designed for the standard humanoid rig but should degrade\n // gracefully on smaller rigs (e.g. props with only a torso).\n const boneNames = args.armature.boneNames;\n const nameToIdx = new Map<string, number>();\n for (let i = 0; i < boneNames.length; i++) {\n const n = boneNames[i];\n if (n) nameToIdx.set(n, i);\n }\n\n const config = args.config ?? DEFAULT_HUMANOID_RAGDOLL;\n\n // First pass: build bone records. Skip if the bone itself is missing.\n for (const desc of config.bones) {\n const idx = nameToIdx.get(desc.boneName);\n if (idx === undefined) continue;\n const record = buildBoneRecord(desc, idx, nameToIdx, this._bindWorld);\n if (!record) continue;\n this._bones.push(record);\n this._byBoneIdx.set(idx, record);\n }\n\n // Second pass: resolve parents.\n for (const b of this._bones) {\n if (!b.parentName) continue;\n const parentIdx = nameToIdx.get(b.parentName);\n if (parentIdx === undefined) continue;\n const parent = this._byBoneIdx.get(parentIdx);\n if (!parent) continue;\n b.parent = parent;\n }\n\n // Third pass: precompute the skeleton subtree for each ragdoll\n // bone. When the bone detaches, splats weighted to anything in\n // its subtree go with it. The subtree is over the actual skeleton\n // hierarchy (`Skeleton.parents`), NOT the ragdoll graph - a single\n // ragdoll-bone like upperarm_l owns its full skeletal descent\n // (upperarm_l, lowerarm_l, hand_l, plus any intermediate twist\n // bones the rig has but ragdoll doesn't represent).\n this._computeSubtrees();\n }\n\n /** Build each `RagdollBone.subtreeBones` set by walking\n * `Skeleton.parents`. O(numBones \u00D7 numRagdollBones) - runs once. */\n private _computeSubtrees(): void {\n const parents = this._skeleton.parents;\n const n = this._skeleton.numBones;\n for (const b of this._bones) {\n const set = b.subtreeBones;\n set.clear();\n set.add(b.boneIdx);\n // Walk every bone; if its parent-chain passes through b.boneIdx,\n // include it. Cheap enough at humanoid scale (~86 bones).\n for (let i = 0; i < n; i++) {\n let cur = parents[i];\n while (cur >= 0 && cur < n) {\n if (cur === b.boneIdx) { set.add(i); break; }\n cur = parents[cur];\n }\n }\n }\n }\n\n /** Whether the ragdoll is currently active (bodies are in the physics world). */\n get isActive(): boolean {\n return this._active;\n }\n\n /**\n * Live `Object3D` carrying the rigid body for `boneName`, or `null`\n * if the ragdoll isn't active or no body is configured for that bone.\n * Its `position` / `quaternion` are world-space (the ragdoll container\n * sits at the content root's origin). Use with {@link getBody} to apply\n * continued forces, read velocities, attach extra constraints, or wire\n * bone-tracked effects to a specific limb. Reference is invalidated by\n * {@link disable}.\n */\n getBodyEntity(boneName: string): Object3D | null {\n if (!this._active) return null;\n const b = this._bones.find((x) => x.descBoneName === boneName);\n return b?.bodyEntity ?? null;\n }\n\n /**\n * The {@link RigidBody} for `boneName` - what `getBodyEntity(name).rigidbody`\n * was in the PlayCanvas build. `null` under the same conditions as\n * {@link getBodyEntity}.\n */\n getBody(boneName: string): RigidBody | null {\n if (!this._active) return null;\n const b = this._bones.find((x) => x.descBoneName === boneName);\n return b?.body ?? null;\n }\n\n // \u2500\u2500 Limb detachment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _detachListeners: Array<(info: LimbDetachedInfo) => void> = [];\n\n /**\n * Names of bones whose joint-to-parent has been severed during this\n * enable() session (manually via {@link detach} or by Bullet's\n * break threshold). Cleared on `disable()`.\n */\n get detachedBones(): readonly string[] {\n const out: string[] = [];\n for (const b of this._bones) if (b.detached) out.push(b.descBoneName);\n return out;\n }\n\n /**\n * Sever the joint connecting `boneName`'s body to its parent body.\n * The body and the skeletal subtree it represents continue to exist\n * as free physics bodies - they just stop being constrained to the\n * rest of the ragdoll. Fires {@link onLimbDetached}.\n *\n * No-op if the ragdoll is not active, the bone has no parent joint\n * (root bone), or the bone has already been detached.\n */\n detach(boneName: string): void {\n if (!this._active) return;\n const b = this._bones.find((x) => x.descBoneName === boneName);\n if (!b || !b.parentJoint || b.detached) return;\n this._severJoint(b);\n }\n\n /**\n * Subscribe to limb-detach events. Listener fires once per\n * detachment (manual or break-threshold) while the ragdoll is\n * active. Returns an unsubscribe function. All listeners are\n * automatically cleared on {@link disable}.\n *\n * The reported `worldPos` is the joint anchor's world position at\n * the moment of severance - a sensible spawn point for blood/spark\n * VFX.\n */\n onLimbDetached(cb: (info: LimbDetachedInfo) => void): () => void {\n this._detachListeners.push(cb);\n return () => {\n const i = this._detachListeners.indexOf(cb);\n if (i >= 0) this._detachListeners.splice(i, 1);\n };\n }\n\n /** Tear down a single bone's parent joint and fire listeners.\n * Internal - used by manual {@link detach} and by the per-frame\n * break-threshold poll in {@link writePose}. */\n private _severJoint(b: RagdollBone): void {\n const joint = b.parentJoint;\n if (!joint) return;\n // Capture the joint anchor world before we tear anything down.\n const worldPos = new Vector3();\n if (b.bodyEntity) {\n // Anchor in body local is (0, -length/2, 0) per the authoring\n // convention; transform to world via the current body pose.\n const local = _detachLocal.set(0, -b.length * 0.5, 0);\n transformPoint(objectWorld(b.bodyEntity, this._tmpMat), local, _vec1);\n worldPos.set(_vec1.x, _vec1.y, _vec1.z);\n }\n joint.remove();\n const idx = this._joints.indexOf(joint);\n if (idx >= 0) this._joints.splice(idx, 1);\n b.parentJoint = null;\n b.detached = true;\n\n // Snap every splat's bone weights to one side of the broken\n // joint so gaussians weighted across the cut don't stretch\n // between the now-separated bodies. Privatizes the splat's bone\n // textures on first detach.\n this._rewriteSplatWeightsForSubtree(b.subtreeBones);\n\n const info: LimbDetachedInfo = { boneName: b.descBoneName, worldPos };\n // Copy listener list before dispatch so a listener that\n // unsubscribes itself doesn't perturb iteration.\n const listeners = this._detachListeners.slice();\n for (const fn of listeners) {\n try { fn(info); } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[Ragdoll] onLimbDetached listener threw:', err);\n }\n }\n }\n\n /** Per-frame poll: any joint with a break threshold whose\n * `isBroken()` flipped this step gets severed via the normal\n * detach path. Called from {@link writePose}. */\n private _pollBrokenJoints(): void {\n for (const b of this._bones) {\n if (b.detached || !b.parentJoint) continue;\n if (b.parentJoint.isBroken()) this._severJoint(b);\n }\n }\n\n /**\n * Snap every linked splat's bone weights so each gaussian sits\n * entirely on one side of the cut - either fully weighted to bones\n * in `subtreeBones` (= goes with the detached limb) or fully\n * weighted to bones outside (= stays with the rest of the body).\n *\n * Implementation: per splat, sum its weights on each side. The\n * heavier side keeps its weights (zero out the other side's\n * influences), then renormalize the remaining weights to sum to\n * 1. Privatizes the splat's bone-weight buffers on first call so\n * other character instances of the same asset are unaffected.\n */\n private _rewriteSplatWeightsForSubtree(subtreeBones: Set<number>): void {\n for (const splat of this._armature.linkedSplats) {\n if (!splat.splatWeights) continue;\n splat.privatizeBoneWeights();\n\n const { indices, weights } = splat.splatWeights;\n const numSplats = splat.numSplats;\n const K = indices.length / numSplats; // top-K influences, typically 4\n for (let i = 0; i < numSplats; i++) {\n const base = i * K;\n let wIn = 0;\n let wOut = 0;\n for (let k = 0; k < K; k++) {\n const w = weights[base + k];\n if (w === 0) continue;\n if (subtreeBones.has(indices[base + k])) wIn += w;\n else wOut += w;\n }\n if (wIn === 0 || wOut === 0) continue; // splat is already pure\n const keepInside = wIn >= wOut;\n let kept = 0;\n for (let k = 0; k < K; k++) {\n const inside = subtreeBones.has(indices[base + k]);\n if (inside !== keepInside) {\n weights[base + k] = 0;\n } else {\n kept += weights[base + k];\n }\n }\n if (kept > 0 && kept !== 1) {\n // Renormalise the kept side so total weight stays 1.\n const inv = 1 / kept;\n for (let k = 0; k < K; k++) {\n if (weights[base + k] !== 0) weights[base + k] *= inv;\n }\n }\n }\n splat.reuploadBoneWeights();\n }\n }\n\n /**\n * Take over from animation: build physics bodies at the current\n * (animated) pose's world positions, wire up joints, and install\n * this Ragdoll as the armature's pose provider. Apply impulses\n * (e.g. for a death-kick) AFTER enable returns via\n * {@link applyImpulse}.\n *\n * Caller's contract: the armature must have run update() at least\n * once before enable(), so the bone world matrices used to place\n * the bodies reflect the current animated pose.\n *\n * No-op if the ragdoll is already active. Throws if the engine has\n * no physics world.\n */\n enable(opts?: {\n /** Whether bodies collide with each other across joints. Default `false`. */\n selfCollide?: boolean;\n }): void {\n if (this._active) return;\n this._physics ??= (this._engine as SplatEngine & { physics?: PhysicsWorld | null }).physics ?? null;\n if (!this._physics) {\n throw new Error(\n '[Ragdoll] the scene has no physics world. Create it with Scene.create(canvas, { physics: { loadAmmo } }), ' +\n 'or pass { physics } to the Ragdoll.',\n );\n }\n this._buildContainer();\n this._buildBodies(opts?.selfCollide ?? false);\n this._buildJoints();\n this._active = true;\n // Install ourselves as the armature's pose provider. The setter\n // detaches any previous provider for us (firing its onDetach).\n this._armature.poseProvider = this;\n }\n\n /**\n * Apply a world-space impulse (N\u00B7s) to the body for `boneName`. Pass\n * `'*'` to apply the same impulse to every body - useful for an\n * explosion-style push. Silently no-ops if the ragdoll isn't active\n * or if the bone has no body.\n *\n * Typical use: kick the ragdoll on activation.\n * ```ts\n * ragdoll.enable();\n * ragdoll.applyImpulse('pelvis', new THREE.Vector3(0, 8, -10));\n * ```\n */\n applyImpulse(boneName: string, impulse: XYZ): void {\n if (!this._active) return;\n if (boneName === '*') {\n for (const b of this._bones) {\n b.body?.applyImpulse(impulse);\n }\n return;\n }\n const entry = this._bones.find((b) => b.descBoneName === boneName);\n entry?.body?.applyImpulse(impulse);\n }\n\n // \u2500\u2500 enable() helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _buildContainer(): void {\n const container = new Group();\n container.name = 'ragdoll';\n this._engine.contentRoot.add(container);\n this._container = container;\n }\n\n /** Create one capsule body per ragdoll bone at its current animated\n * world transform. Parent under the ragdoll container. */\n private _buildBodies(selfCollide: boolean): void {\n const container = this._container!;\n const physics = this._physics!;\n const tmpPos = new Vec3();\n const tmpRot = new Quat();\n\n for (const b of this._bones) {\n const boneWorld = this._currentBoneWorld(b.boneIdx, this._tmpMat);\n const bodyWorld = this._tmpMat2.mul2(boneWorld, b.boneToBody);\n bodyWorld.getTranslation(tmpPos);\n tmpRot.setFromMat4(bodyWorld);\n\n const e = new Object3D();\n e.name = `ragdoll-${b.descBoneName}`;\n container.add(e);\n setObjectWorldPose(e, _tPos.set(tmpPos.x, tmpPos.y, tmpPos.z), _tQuat.set(tmpRot.x, tmpRot.y, tmpRot.z, tmpRot.w));\n b.body = physics.addBody(e, {\n shape: {\n type: 'capsule',\n radius: b.radius,\n // `height` is total length including both hemispherical caps\n // (PC convention). We deliberately extend `radius` past each\n // bone endpoint so the capsule wraps the joint regions, not\n // just the bone segment - feet, hands, and head read as solid\n // rather than as a thin shaft with a cap floating off.\n height: b.length + b.radius * 2,\n // Capsule axis: 0=X, 1=Y, 2=Z. Y matches our\n // bone-direction-along-local-Y authoring convention.\n axis: 1,\n },\n type: 'dynamic',\n mass: b.mass,\n friction: 0.6,\n restitution: 0.1,\n // Damping keeps the ragdoll from looking jittery and helps it\n // settle after a few seconds.\n linearDamping: 0.05,\n angularDamping: 0.1,\n // Collision groups (bit-flags, PlayCanvas's values): 1 = DYNAMIC,\n // 2 = STATIC, 4 = KINEMATIC, 8+ user. Default mode puts ragdoll\n // bodies on user bit 8 and excludes only that bit from the mask\n // so bodies don't collide with each other but still hit the\n // static world (group 2) and other dynamics (group 1). Group\n // 2 is the tempting \"non-default\" pick but conflicts with\n // the static-body group - ragdoll then falls through the\n // floor.\n group: selfCollide ? 1 : 8,\n mask: selfCollide ? 0xffff : 0xfff7,\n });\n b.bodyEntity = e;\n }\n }\n\n /** Wire up the joints linking each body to its parent body. Skips\n * bones with no parent (root) or no joint descriptor. */\n private _buildJoints(): void {\n for (const b of this._bones) {\n b.parentJoint = null;\n b.detached = false;\n if (!b.parent || !b.jointDesc || !b.body || !b.parent.body) continue;\n const joint = makeJoint(b, b.parent, b.jointDesc);\n if (!joint) continue;\n this._joints.push(joint);\n b.parentJoint = joint;\n }\n }\n\n /**\n * Tear down the physics bodies and joints, and detach from the\n * armature's pose-provider slot so animation resumes next frame.\n * No-op if already disabled. Safe to call repeatedly.\n */\n disable(): void {\n if (!this._active) return;\n this._teardownBodies();\n // Setter is the user-facing teardown signal. When the setter calls\n // back into onDetach below, _teardownBodies short-circuits (already\n // inactive), so no recursion problem.\n if (this._armature.poseProvider === this) {\n this._armature.poseProvider = null;\n }\n }\n\n /**\n * {@link PoseProvider.onDetach} - called by the Armature when it's\n * destroyed or when another provider replaces us. Tears down bodies\n * but does NOT touch `armature.poseProvider` (the setter is mid-\n * transition; mutating it from here would either overwrite the new\n * provider or recurse).\n */\n onDetach(): void {\n this._teardownBodies();\n }\n\n /** Release physics bodies, joints, and the container object. Sets\n * `_active = false`. Idempotent. */\n private _teardownBodies(): void {\n if (!this._active) return;\n this._active = false;\n // Joints before bodies: Bullet must never hold a constraint on a\n // freed body.\n for (const j of this._joints) j.remove();\n this._joints.length = 0;\n for (const b of this._bones) {\n if (b.body) this._physics?.removeBody(b.body);\n b.body = null;\n b.bodyEntity = null;\n b.parentJoint = null;\n b.detached = false;\n }\n this._container?.removeFromParent();\n this._container = null;\n this._detachListeners.length = 0;\n }\n\n /**\n * Full cleanup: tear down bodies (if active) plus any debug\n * visualization. Call when discarding a Ragdoll instance (e.g. on\n * character respawn) - `disable()` alone leaves the debug viz\n * running.\n */\n destroy(): void {\n this.disable();\n this.setDebugVisible(false);\n }\n\n // \u2500\u2500 Debug visualization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _debugLines: LineSegments | null = null;\n private _debugUnhook: (() => void) | null = null;\n\n /** Whether the debug box visualization is currently visible. */\n get debugVisible(): boolean { return this._debugLines !== null; }\n\n /**\n * Show or hide debug wireframe boxes mirroring each configured\n * ragdoll body. Drawn without depth test so they always render on\n * top of splats / standard meshes / each other. Boxes follow bones\n * via the same `boneToBody` offset the physics bodies use, so they\n * sit in the right place both during animation (no physics) and\n * during ragdoll (physics-driven). Use for tuning capsule radii /\n * lengths in the config.\n */\n setDebugVisible(visible: boolean): void {\n if (visible === this.debugVisible) return;\n if (visible) {\n // 24 positions per body: 12 edges \u00D7 2 endpoints.\n const positions = new Float32Array(this._bones.length * _BOX_EDGES.length * 3);\n const geometry = new BufferGeometry();\n geometry.setAttribute('position', new BufferAttribute(positions, 3));\n const material = new LineBasicMaterial({ color: 0xff8c1a, depthTest: false, depthWrite: false, transparent: true });\n const lines = new LineSegments(geometry, material);\n lines.name = 'ragdoll-debug';\n lines.frustumCulled = false;\n lines.renderOrder = 1e6;\n this._engine.contentRoot.add(lines);\n this._debugLines = lines;\n // Refresh every engine update, after the characters registered before\n // it have posed (the PlayCanvas build listens to the app's 'update').\n this._debugUnhook = this._engine.addUpdater(() => this._drawDebug(lines));\n } else if (this._debugLines) {\n const lines = this._debugLines;\n this._debugUnhook?.();\n this._debugUnhook = null;\n lines.removeFromParent();\n lines.geometry.dispose();\n (lines.material as LineBasicMaterial).dispose();\n this._debugLines = null;\n }\n }\n\n /** Per-frame: refresh the corners of each body's box, written straight\n * into the line buffer in the lines' parent frame. */\n private _drawDebug(lines: LineSegments): void {\n const attr = lines.geometry.getAttribute('position') as BufferAttribute;\n const out = attr.array as Float32Array;\n lines.parent?.updateWorldMatrix(true, false);\n _dbgInv.copy(lines.parent ? lines.parent.matrixWorld : _dbgIdentity).invert();\n let o = 0;\n for (let i = 0; i < this._bones.length; i++) {\n const b = this._bones[i];\n const boneWorld = this._worldTransforms[b.boneIdx];\n if (!boneWorld) { o += _BOX_EDGES.length * 3; continue; }\n const bodyWorld = _dbgMat.mul2(boneWorld, b.boneToBody);\n\n // 8 box corners in body-local space (Y = bone direction).\n const r = b.radius;\n const h = b.length * 0.5;\n _dbgLocal[0].set(-r, -h, -r); _dbgLocal[1].set( r, -h, -r);\n _dbgLocal[2].set( r, -h, r); _dbgLocal[3].set(-r, -h, r);\n _dbgLocal[4].set(-r, h, -r); _dbgLocal[5].set( r, h, -r);\n _dbgLocal[6].set( r, h, r); _dbgLocal[7].set(-r, h, r);\n for (let c = 0; c < 8; c++) {\n transformPoint(bodyWorld, _dbgLocal[c], _dbgWorld[c]);\n _dbgCorner[c].set(_dbgWorld[c].x, _dbgWorld[c].y, _dbgWorld[c].z).applyMatrix4(_dbgInv);\n }\n for (const e of _BOX_EDGES) {\n const p = _dbgCorner[e];\n out[o++] = p.x; out[o++] = p.y; out[o++] = p.z;\n }\n }\n attr.needsUpdate = true;\n }\n\n /**\n * {@link PoseProvider} implementation. Replaces the entire pose with\n * values derived from the bodies' world transforms.\n *\n * Strategy: reset every bone to bind first, then overwrite the\n * ragdoll-driven bones. Intermediate skeleton bones (e.g. spine_01\n * sitting between pelvis and spine_03) stay at bind - they don't\n * articulate. This is the simplification the \"pure physics\" mode\n * buys us.\n *\n * The armature object is NOT moved to follow the pelvis. The\n * bone-local TRS we write absorbs the world position; the splat\n * deforms to the physics-driven world either way.\n */\n writePose(pose: Pose, _armature: Armature, _dt: number): void {\n if (!this._active) return;\n\n // Check for joints that broke during the most recent physics\n // step before reading bodies. Listeners fire here; detaching a\n // limb doesn't change the per-bone body-read loop below - the\n // body is still in the world, just no longer joint-constrained.\n this._pollBrokenJoints();\n\n // Reset every bone to bind. Cheap; avoids stale animation values\n // bleeding into intermediate non-ragdoll bones.\n pose.setToBind(this._skeleton.bindT, this._skeleton.bindR);\n\n // For each ragdoll-driven bone, derive its desired world from the\n // body, then convert to local TRS relative to its skeleton-parent\n // bone's world transform (which uses bind values for intermediate\n // non-ragdoll bones, by construction).\n const parents = this._skeleton.parents;\n const numBones = this._skeleton.numBones;\n const entityWorld = objectWorld(this._armatureObject, this._entityWorld);\n\n // Anchor the rig's root bone (parent of pelvis in the skeleton) to\n // the pelvis body's current world transform. Without this, root\n // stays at its bind position relative to the armature object, and\n // any splat weighted to \"root\" renders at the spawn point instead\n // of following the ragdoll - visible as gaussians floating in\n // mid-air at (0,0,0) when a limb detaches. The pelvis bone itself\n // then resolves to identity in the main loop below\n // (parentInv * desired = desired^-1 * desired = identity), which\n // is correct.\n const pelvisBone = this._bones[0];\n if (pelvisBone?.bodyEntity) {\n const skelRootIdx = parents[pelvisBone.boneIdx];\n if (skelRootIdx >= 0 && skelRootIdx < numBones) {\n const bodyW = objectWorld(pelvisBone.bodyEntity, _bodyWorld);\n const desiredPelvisW = this._tmpMat.mul2(bodyW, pelvisBone.bodyToBone);\n const entInv = this._tmpMat2.copy(entityWorld); entInv.invert();\n const rootLocal = _localMat.mul2(entInv, desiredPelvisW);\n rootLocal.getTranslation(pose.positions[skelRootIdx]);\n rootLocal.getScale(pose.scales[skelRootIdx]);\n pose.rotations[skelRootIdx].setFromMat4(rootLocal);\n }\n }\n\n // Per-bone world-transform cache. Grow the Mat4 array once (covers\n // all future frames since rigs don't change size at runtime) and\n // clear only the populated-flag array each frame.\n const boneWorld = this._writePoseBoneWorld;\n const has = this._writePoseHas;\n while (boneWorld.length < numBones) boneWorld.push(new Mat4());\n if (has.length < numBones) has.length = numBones;\n for (let i = 0; i < numBones; i++) has[i] = false;\n\n const getBoneWorld = (i: number): Mat4 => {\n if (has[i]) return boneWorld[i];\n const out = boneWorld[i];\n const pi = parents[i];\n // Resolve the parent BEFORE filling the shared `_localMat`: the\n // recursion fills it too. Filled first, any ragdoll bone two or more\n // non-ragdoll bones below its ragdoll parent - spine_03, neck_01, the\n // arms - is placed against a wrong parent world and drawn up to ~18 cm\n // off its body, as in the PlayCanvas build up to 0.3.2.\n const parentW = pi < 0 || pi >= numBones ? entityWorld : getBoneWorld(pi);\n const local = _localMat;\n local.setTRS(pose.positions[i], pose.rotations[i], pose.scales[i]);\n out.mul2(parentW, local);\n has[i] = true;\n return out;\n };\n\n // Compute desired world for each ragdoll bone, then back out its\n // local TRS using its parent's world.\n for (const b of this._bones) {\n if (!b.bodyEntity) continue;\n // desired bone world = body world * boneToBody^-1 = body world * bodyToBone\n const bodyW = objectWorld(b.bodyEntity, _bodyWorld);\n const desired = this._tmpMat;\n desired.mul2(bodyW, b.bodyToBone);\n\n const parentIdx = parents[b.boneIdx];\n let parentW: Mat4;\n if (parentIdx < 0 || parentIdx >= numBones) {\n parentW = entityWorld;\n } else {\n parentW = getBoneWorld(parentIdx);\n }\n\n // localTRS = parentW^-1 * desired\n const parentInv = this._tmpMat2;\n parentInv.copy(parentW);\n parentInv.invert();\n const local = _localMat;\n local.mul2(parentInv, desired);\n\n // Decompose into TRS. Bodies are unit-scale and the math doesn't\n // introduce scale, so the rotation read from the 3\u00D73 is safe.\n local.getTranslation(pose.positions[b.boneIdx]);\n local.getScale(pose.scales[b.boneIdx]);\n pose.rotations[b.boneIdx].setFromMat4(local);\n\n // Cache so descendant ragdoll bones can read this world directly\n // instead of walking the chain. boneWorld[i] is always present\n // (pre-allocated above); we just stamp the value and flag it.\n boneWorld[b.boneIdx].copy(desired);\n has[b.boneIdx] = true;\n }\n }\n\n /** Read the bone's current world matrix from the armature's array.\n * Falls back to armatureWorld * bindWorld if the array hasn't been\n * populated yet (e.g. enable() called before the first update()). */\n private _currentBoneWorld(boneIdx: number, out: Mat4): Mat4 {\n const m = this._worldTransforms[boneIdx];\n if (m) {\n out.copy(m);\n return out;\n }\n out.mul2(objectWorld(this._armatureObject, this._entityWorld), this._bindWorld[boneIdx]);\n return out;\n }\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Internal: per-bone record built once at construction.\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface RagdollBone {\n /** As authored in the config (for debug + impulse target lookup). */\n descBoneName: string;\n /** Skeleton bone index. */\n boneIdx: number;\n /** Parent body's bone name, or null if root. */\n parentName: string | null;\n /** Resolved parent record, set in the constructor's second pass. */\n parent: RagdollBone | null;\n /** Joint to the parent body. Null if root. */\n jointDesc: RagdollJointDesc | null;\n /** Capsule length (m). */\n length: number;\n /** Capsule radius (m). */\n radius: number;\n /** Body mass (kg). */\n mass: number;\n /** Constant offset from bone frame to body frame (in bone-local space). */\n boneToBody: Mat4;\n /** Inverse of `boneToBody`. */\n bodyToBone: Mat4;\n /**\n * Set of skeleton bone indices for the descendant subtree rooted at\n * `boneIdx` (inclusive). Used when this bone is detached to decide\n * which splats belong to the severed limb. Precomputed at Ragdoll\n * construction from {@link Skeleton.parents}.\n */\n subtreeBones: Set<number>;\n /** Live body object while ragdoll is active; null otherwise. */\n bodyEntity: Object3D | null;\n /** The rigid body on {@link bodyEntity}. */\n body: RigidBody | null;\n /** Joint connecting this body to its parent body. Null for the root\n * bone or for bones whose joint has been severed via {@link detach}\n * or by Bullet's break threshold. */\n parentJoint: JointHandle | null;\n /** True once this bone's parent joint has been severed. Stays true\n * until the Ragdoll is disabled. */\n detached: boolean;\n}\n\nfunction buildBoneRecord(\n desc: RagdollBoneDesc,\n boneIdx: number,\n nameToIdx: Map<string, number>,\n bindWorld: Mat4[],\n): RagdollBone | null {\n // Resolve capsule length + direction. Prefer endBoneName when present.\n const bonePos = _vec1;\n bindWorld[boneIdx].getTranslation(bonePos);\n\n const dir = _vec2;\n let length = desc.length ?? 0;\n if (desc.endBoneName) {\n const endIdx = nameToIdx.get(desc.endBoneName);\n if (endIdx !== undefined) {\n const endPos = _vec3;\n bindWorld[endIdx].getTranslation(endPos);\n dir.sub2(endPos, bonePos);\n length = dir.length();\n if (length > 1e-5) dir.mulScalar(1 / length);\n }\n }\n if (length < 1e-4) {\n // No usable end bone and no explicit length \u2192 can't build. Skip.\n return null;\n }\n if (!desc.endBoneName) {\n // length-only fallback: capsule points along bone's local +Y in\n // world. Compute that direction.\n const localY = _vec3.set(0, 1, 0);\n transformVector(bindWorld[boneIdx], localY, dir);\n if (dir.dot(dir) < 1e-10) dir.set(0, 1, 0);\n dir.normalize();\n }\n\n // body bind world transform: position = bone + dir * length/2,\n // rotation = rotates local Y to dir\n const bodyWorldPos = new Vec3().add2(bonePos, _vec4.copy(dir).mulScalar(length * 0.5));\n const bodyWorldRot = new Quat();\n quatFromYTo(dir, bodyWorldRot);\n\n const bodyWorld = new Mat4().setTRS(bodyWorldPos, bodyWorldRot, _UNIT_SCALE);\n\n // boneToBody = bindWorld(bone)^-1 * bodyWorld\n const boneInv = new Mat4();\n boneInv.copy(bindWorld[boneIdx]);\n boneInv.invert();\n const boneToBody = new Mat4().mul2(boneInv, bodyWorld);\n\n const bodyToBone = new Mat4();\n bodyToBone.copy(boneToBody);\n bodyToBone.invert();\n\n return {\n descBoneName: desc.boneName,\n boneIdx,\n parentName: desc.parent,\n parent: null,\n jointDesc: desc.joint ?? null,\n length,\n radius: desc.radius,\n mass: desc.mass,\n boneToBody,\n bodyToBone,\n subtreeBones: new Set([boneIdx]), // filled in by Ragdoll ctor\n bodyEntity: null,\n body: null,\n parentJoint: null,\n detached: false,\n };\n}\n\nfunction makeJoint(\n child: RagdollBone,\n parent: RagdollBone,\n desc: RagdollJointDesc,\n): JointHandle | null {\n if (!child.bodyEntity || !parent.bodyEntity || !child.body || !parent.body) return null;\n\n // Use the bodies' CURRENT world transforms (we just placed them at\n // the current animated pose during enable()).\n const childBodyWorld = objectWorld(child.bodyEntity, _jmChildBody);\n const parentBodyWorld = objectWorld(parent.bodyEntity, _jmParentBody);\n\n // Anchor at the proximal end of the child capsule, which by our\n // authoring convention is at (0, \u2212length/2, 0) in the child body's\n // local frame. Compute its world position from there.\n const pivotInChild = new Vec3(0, -child.length * 0.5, 0);\n const anchorWorld = _vec1;\n transformPoint(childBodyWorld, pivotInChild, anchorWorld);\n\n // Express the same anchor in parent body local.\n const parentBodyInv = _jmParentBodyInv.copy(parentBodyWorld); parentBodyInv.invert();\n const pivotInParent = new Vec3();\n transformPoint(parentBodyInv, anchorWorld, pivotInParent);\n\n if (desc.type === 'hinge') {\n // Validate: btGeneric6DofConstraint treats `low > high` as\n // \"axis is free\" - almost certainly not what the author meant if\n // they typed inverted values. Catch early.\n if (desc.low > desc.high) {\n throw new Error(\n `[Ragdoll] hinge ${parent.descBoneName}->${child.descBoneName}: ` +\n `low (${desc.low}) > high (${desc.high}); did you mean to swap them?`,\n );\n }\n // Hinge as 6DOF: anchor a joint frame whose X axis IS the hinge\n // axis (in child body local), lock translation + Y/Z rotation,\n // allow X rotation within [low, high].\n let axisAlignRot: Quat;\n if (desc.axis === 'x') {\n // Frame X = child body X. No rotation.\n axisAlignRot = new Quat();\n } else if (desc.axis === 'y') {\n // Frame X = child body Y \u2192 rotate frame's X to Y axis: Rz(90\u00B0).\n axisAlignRot = quatFromAxisAngle(_vec3.set(0, 0, 1), Math.PI / 2, new Quat());\n } else {\n // Frame X = child body Z \u2192 rotate frame's X to Z axis: Ry(-90\u00B0).\n axisAlignRot = quatFromAxisAngle(_vec3.set(0, 1, 0), -Math.PI / 2, new Quat());\n }\n const axisAlignMat = _jmAlign.setTRS(_zeroVec, axisAlignRot, _UNIT_SCALE);\n\n const jointWorldMat = _jmJointWorld.mul2(childBodyWorld, axisAlignMat);\n const frameInChildRot = axisAlignRot.clone();\n const frameInParentMat = _jmFrameInParent.mul2(parentBodyInv, jointWorldMat);\n const frameInParentRot = new Quat().setFromMat4(frameInParentMat);\n\n return createGeneric6DofJoint({\n bodyA: parent.body,\n bodyB: child.body,\n frameInA: { position: pivotInParent, rotation: frameInParentRot },\n frameInB: { position: pivotInChild, rotation: frameInChildRot },\n angularLowerLimit: new Vec3(desc.low, 0, 0),\n angularUpperLimit: new Vec3(desc.high, 0, 0),\n breakImpulse: desc.breakImpulse,\n });\n }\n\n // Cone-twist: the joint frame's X axis is the cone axis. We anchor\n // it along the CHILD's bone direction (= child body's local +Y).\n // Crucially, both bodies' joint frames must COINCIDE in world space\n // at the moment of construction - same origin, same orientation -\n // or Bullet sees an initial constraint violation that the solver\n // either explodes from (NaN) or fights forever (frozen bodies).\n //\n // jointWorld_rot = childBodyWorld_rot \u00B7 Rz(90\u00B0)\n // \u2192 joint frame's X axis in world = child body's local Y in world = bone dir\n // frameInChild_rot = childBodyWorld_rot\u207B\u00B9 \u00B7 jointWorld_rot = Rz(90\u00B0)\n // frameInParent_rot = parentBodyWorld_rot\u207B\u00B9 \u00B7 jointWorld_rot\n // = parentBodyWorld_rot\u207B\u00B9 \u00B7 childBodyWorld_rot \u00B7 Rz(90\u00B0)\n const zRot90 = quatFromAxisAngle(_vec3.set(0, 0, 1), Math.PI / 2, new Quat());\n const zRot90Mat = _jmAlign.setTRS(_zeroVec, zRot90, _UNIT_SCALE);\n\n // jointWorldMat = childBodyWorld \u00B7 Rz(90\u00B0)\n const jointWorldMat = _jmJointWorld.mul2(childBodyWorld, zRot90Mat);\n\n // frameInChild_rot - Rz(90\u00B0) directly.\n const frameInChildRot = zRot90.clone();\n\n // frameInParent_rot = parentBodyWorld\u207B\u00B9 \u00B7 jointWorldMat\n const frameInParentMat = _jmFrameInParent.mul2(parentBodyInv, jointWorldMat);\n const frameInParentRot = new Quat().setFromMat4(frameInParentMat);\n\n // Build the cone-twist with a btGeneric6DofConstraint - the same\n // frame setup as btConeTwistConstraint but a more robust solver.\n // Frame convention: X = twist axis, Y/Z = swing axes. Locked\n // translation makes the joint a pure ball-and-socket; angular\n // limits express the cone.\n const swingY = desc.swingY ?? Math.PI / 4;\n const swingZ = desc.swingZ ?? Math.PI / 4;\n const twist = desc.twist ?? Math.PI / 6;\n return createGeneric6DofJoint({\n bodyA: parent.body,\n bodyB: child.body,\n frameInA: { position: pivotInParent, rotation: frameInParentRot },\n frameInB: { position: pivotInChild, rotation: frameInChildRot },\n angularLowerLimit: new Vec3(-twist, -swingY, -swingZ),\n angularUpperLimit: new Vec3(twist, swingY, swingZ),\n breakImpulse: desc.breakImpulse,\n });\n}\n\n// \u2500\u2500 Math helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// The PlayCanvas Mat4 / Quat methods the original calls that the shared\n// math kernel (../math) does not carry. Same formulas, except that angles\n// are radians here, where PlayCanvas's setFromAxisAngle takes degrees.\n\n/** `out = m \u00B7 (p, 1)`. */\nfunction transformPoint(m: Mat4, p: Vec3, out: Vec3): Vec3 {\n const d = m.data;\n const x = p.x, y = p.y, z = p.z;\n return out.set(\n x * d[0] + y * d[4] + z * d[8] + d[12],\n x * d[1] + y * d[5] + z * d[9] + d[13],\n x * d[2] + y * d[6] + z * d[10] + d[14],\n );\n}\n\n/** `out = m \u00B7 (v, 0)`. */\nfunction transformVector(m: Mat4, v: Vec3, out: Vec3): Vec3 {\n const d = m.data;\n const x = v.x, y = v.y, z = v.z;\n return out.set(\n x * d[0] + y * d[4] + z * d[8],\n x * d[1] + y * d[5] + z * d[9],\n x * d[2] + y * d[6] + z * d[10],\n );\n}\n\n/** Rotation of `radians` about `axis` (unit length). */\nfunction quatFromAxisAngle(axis: Vec3, radians: number, out: Quat): Quat {\n const half = radians * 0.5;\n const s = Math.sin(half);\n return out.set(axis.x * s, axis.y * s, axis.z * s, Math.cos(half));\n}\n\n/** An object's world matrix in the kernel's `Mat4`, refreshed from its ancestors. */\nfunction objectWorld(object: Object3D, out: Mat4): Mat4 {\n object.updateWorldMatrix(true, false);\n return out.setFromArray(object.matrixWorld.elements);\n}\n\n// Quat that rotates local +Y to `dir`. Falls back to identity / 180\u00B0 about\n// X for the degenerate aligned / antiparallel cases.\nfunction quatFromYTo(dir: Vec3, out: Quat): Quat {\n const dx = dir.x;\n const dy = dir.y;\n const dz = dir.z;\n const lsq = dx * dx + dy * dy + dz * dz;\n if (lsq < 1e-10) { out.set(0, 0, 0, 1); return out; }\n const inv = 1 / Math.sqrt(lsq);\n const nx = dx * inv, ny = dy * inv, nz = dz * inv;\n const dot = ny; // (0,1,0) \u00B7 n = ny\n if (dot > 0.9999) { out.set(0, 0, 0, 1); return out; }\n if (dot < -0.9999) { out.set(1, 0, 0, 0); return out; } // 180\u00B0 about X\n // axis = (0,1,0) \u00D7 n = (nz, 0, -nx)\n const ax = nz, ay = 0, az = -nx;\n const aLen = Math.sqrt(ax * ax + az * az);\n const axn = ax / aLen, ayn = ay, azn = az / aLen;\n const ang = Math.acos(dot);\n return quatFromAxisAngle(_vec4.set(axn, ayn, azn), ang, out);\n}\n\n// Scratch - module-scoped so we don't allocate per-call. These are NOT\n// safe to hold across yields; each function uses them within a single\n// synchronous call.\nconst _vec1 = new Vec3();\nconst _vec2 = new Vec3();\nconst _vec3 = new Vec3();\nconst _vec4 = new Vec3();\n// Detach math scratch (joint-anchor local point).\nconst _detachLocal = new Vec3();\nconst _UNIT_SCALE = new Vec3(1, 1, 1);\n// Used only by the recursive `getBoneWorld` closure inside writePose\n// (single synchronous call).\nconst _localMat = new Mat4();\n// A body object's world matrix, read once per bone inside writePose.\nconst _bodyWorld = new Mat4();\n// three.js scratch for placing body objects.\nconst _tPos = new Vector3();\nconst _tQuat = new Quaternion();\n// Debug viz scratch. Safe to share - only touched inside _drawDebug,\n// which runs synchronously per frame.\nconst _dbgMat = new Mat4();\nconst _dbgInv = new Matrix4();\nconst _dbgIdentity = new Matrix4();\nconst _dbgLocal: Vec3[] = Array.from({ length: 8 }, () => new Vec3());\nconst _dbgWorld: Vec3[] = Array.from({ length: 8 }, () => new Vec3());\nconst _dbgCorner: Vector3[] = Array.from({ length: 8 }, () => new Vector3());\n/** Indices into an 8-corner box giving the 12 edges (24 endpoint\n * indices). Bottom rect, top rect, then 4 vertical struts. */\nconst _BOX_EDGES: readonly number[] = [\n 0, 1, 1, 2, 2, 3, 3, 0, // bottom\n 4, 5, 5, 6, 6, 7, 7, 4, // top\n 0, 4, 1, 5, 2, 6, 3, 7, // verticals\n];\n\n// Joint-frame computation scratch - `_jm*` prefix marks \"used inside\n// makeJoint, distinct from the instance scratch on the Ragdoll class\".\nconst _zeroVec = new Vec3();\nconst _jmChildBody = new Mat4();\nconst _jmParentBody = new Mat4();\nconst _jmParentBodyInv = new Mat4();\nconst _jmAlign = new Mat4();\nconst _jmJointWorld = new Mat4();\nconst _jmFrameInParent = new Mat4();\n", "/**\n * Describes how a humanoid (or other) rig becomes a set of physics\n * bodies for ragdoll. Keyed by bone name.\n *\n * ## Assumed conventions\n *\n * The Ragdoll places each capsule body so that the body's local +Y\n * axis points along the bone's bind-pose direction (i.e. toward\n * `endBoneName`'s bind position). Authoring the config correctly\n * therefore requires that the rig's bone hierarchy and bind pose be\n * known - name lookup is done by string match against\n * `Armature.boneNames`, which is supplied by `Scene.skeletonLibrary`.\n *\n * For UE-style humanoids (`pelvis`, `spine_NN`, `neck_NN`, `head`,\n * `clavicle_l/r`, `upperarm_l/r`, `lowerarm_l/r`, `hand_l/r`,\n * `thigh_l/r`, `calf_l/r`, `foot_l/r`) the bundled\n * {@link DEFAULT_HUMANOID_RAGDOLL} works without modification. Other\n * rigs (Maya joint orientation, custom skeletons, props) can supply a\n * custom config; only the bone names need to differ.\n *\n * @group Ragdoll\n */\nexport interface RagdollConfig {\n bones: RagdollBoneDesc[];\n}\n\n/**\n * One physics body in the ragdoll graph. Each body is a capsule attached to\n * a bone; its axis points from the bone's bind-pose origin toward the\n * bind-pose position of `endBoneName` (so its length is implicit in the\n * rig). Terminal bodies (head, hand, foot) without a useful end bone in\n * the config specify `length` directly.\n *\n * @group Ragdoll\n */\nexport interface RagdollBoneDesc {\n /** Bone the body is attached to. */\n boneName: string;\n /**\n * Bone whose bind-pose position defines the capsule's distal end.\n * Capsule length = \u2016bindPos(endBoneName) \u2212 bindPos(boneName)\u2016.\n * Omit and set {@link length} for terminal bodies (head, hand, foot)\n * whose child bones don't represent the body's tip.\n */\n endBoneName?: string;\n /** Capsule length override when {@link endBoneName} is absent. Meters. */\n length?: number;\n /** Capsule radius. Meters. */\n radius: number;\n /** Body mass. */\n mass: number;\n /** Parent body's `boneName`. `null` for the root body (pelvis). */\n parent: string | null;\n /**\n * Joint to the parent body. `null` for the root body. The joint anchors\n * sit at the proximal end of the child capsule (where the bone starts)\n * and at the corresponding point on the parent body.\n */\n joint?: RagdollJointDesc | null;\n}\n\n/**\n * Joint between a body and its parent. `coneTwist` is the right choice for\n * shoulders, hips, neck, and the spine; `hinge` is for elbows and knees.\n *\n * @group Ragdoll\n */\n/**\n * Shared fields across joint variants.\n *\n * @group Ragdoll\n */\ninterface RagdollJointCommon {\n /**\n * When set, the joint detaches if its applied impulse in a single\n * physics step exceeds this value (N\u00B7s). Triggers\n * {@link Ragdoll.onLimbDetached} for the child bone and severs the\n * skeletal subtree. Omit for an unbreakable joint.\n *\n * Tuning is rig-specific - start around 8\u201315 N\u00B7s for shoulders /\n * hips on a humanoid; lower values detach more easily.\n */\n breakImpulse?: number;\n}\n\nexport type RagdollJointDesc =\n | (RagdollJointCommon & {\n type: 'coneTwist';\n /** Cone half-angle, radians. Default \u03C0/4. */\n swingY?: number;\n /** Cone half-angle, radians. Default \u03C0/4. */\n swingZ?: number;\n /** Twist half-angle, radians. Default \u03C0/6. */\n twist?: number;\n })\n | (RagdollJointCommon & {\n type: 'hinge';\n /** Hinge axis in the child body's local space. `'x' | 'y' | 'z'`. */\n axis: 'x' | 'y' | 'z';\n /** Lower limit, radians. */\n low: number;\n /** Upper limit, radians. */\n high: number;\n });\n\n/**\n * A sensible default humanoid ragdoll for rigs that use the standard\n * UE-style bone naming (`pelvis`, `spine_NN`, `neck_NN`, `head`,\n * `clavicle_l/r`, `upperarm_l/r`, `lowerarm_l/r`, `hand_l/r`,\n * `thigh_l/r`, `calf_l/r`, `foot_l/r`). Collapses the spine to a single\n * torso body, ignores fingers, toes, and twist bones - 14 bodies total,\n * enough for recognizable ragdoll motion without the cost of a per-bone\n * body.\n *\n * Override per-character by passing a custom {@link RagdollConfig} to\n * the {@link Ragdoll} constructor.\n *\n * @group Ragdoll\n */\nexport const DEFAULT_HUMANOID_RAGDOLL: RagdollConfig = {\n bones: [\n // \u2500\u2500 Torso \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Pelvis is the root - no joint, no parent.\n {\n boneName: 'pelvis',\n endBoneName: 'spine_03',\n radius: 0.13,\n mass: 8,\n parent: null,\n },\n // Single chest body covers spine_01..spine_05. Parent is pelvis.\n {\n boneName: 'spine_03',\n endBoneName: 'neck_01',\n radius: 0.12,\n mass: 10,\n parent: 'pelvis',\n joint: { type: 'coneTwist', swingY: Math.PI / 6, swingZ: Math.PI / 6, twist: Math.PI / 8 },\n },\n // Head - terminal, length authored.\n {\n boneName: 'neck_01',\n endBoneName: 'head',\n radius: 0.08,\n mass: 4,\n parent: 'spine_03',\n joint: { type: 'coneTwist', swingY: Math.PI / 4, swingZ: Math.PI / 4, twist: Math.PI / 6 },\n },\n\n // \u2500\u2500 Left arm \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n boneName: 'upperarm_l',\n endBoneName: 'lowerarm_l',\n radius: 0.05,\n mass: 2,\n parent: 'spine_03',\n // Shoulders are very free - wide cone.\n joint: { type: 'coneTwist', swingY: Math.PI / 2, swingZ: Math.PI / 2, twist: Math.PI / 3 },\n },\n {\n boneName: 'lowerarm_l',\n endBoneName: 'hand_l',\n radius: 0.045,\n mass: 1.2,\n parent: 'upperarm_l',\n // Elbow: hinge, ~0..140\u00B0.\n joint: { type: 'hinge', axis: 'x', low: 0, high: Math.PI * 0.75 },\n },\n\n // \u2500\u2500 Right arm \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n boneName: 'upperarm_r',\n endBoneName: 'lowerarm_r',\n radius: 0.05,\n mass: 2,\n parent: 'spine_03',\n joint: { type: 'coneTwist', swingY: Math.PI / 2, swingZ: Math.PI / 2, twist: Math.PI / 3 },\n },\n {\n boneName: 'lowerarm_r',\n endBoneName: 'hand_r',\n radius: 0.045,\n mass: 1.2,\n parent: 'upperarm_r',\n joint: { type: 'hinge', axis: 'x', low: 0, high: Math.PI * 0.75 },\n },\n\n // \u2500\u2500 Left leg \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n boneName: 'thigh_l',\n endBoneName: 'calf_l',\n radius: 0.07,\n mass: 5,\n parent: 'pelvis',\n // Hips: large cone, low twist.\n joint: { type: 'coneTwist', swingY: Math.PI / 3, swingZ: Math.PI / 3, twist: Math.PI / 8 },\n },\n {\n boneName: 'calf_l',\n endBoneName: 'foot_l',\n radius: 0.05,\n mass: 3,\n parent: 'thigh_l',\n // Knee: hinge, opposite direction from elbow.\n joint: { type: 'hinge', axis: 'x', low: -Math.PI * 0.75, high: 0 },\n },\n\n // \u2500\u2500 Right leg \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n boneName: 'thigh_r',\n endBoneName: 'calf_r',\n radius: 0.07,\n mass: 5,\n parent: 'pelvis',\n joint: { type: 'coneTwist', swingY: Math.PI / 3, swingZ: Math.PI / 3, twist: Math.PI / 8 },\n },\n {\n boneName: 'calf_r',\n endBoneName: 'foot_r',\n radius: 0.05,\n mass: 3,\n parent: 'thigh_r',\n joint: { type: 'hinge', axis: 'x', low: -Math.PI * 0.75, high: 0 },\n },\n ],\n};\n", "import { Euler, MathUtils } from 'three';\nimport type { Object3D } from 'three';\n\nimport type { SplatEngine } from './engine';\nimport { EngineDisposedError } from './engine';\nimport { LodBundle } from './loader/environment/lod-bundle';\nimport type { LodManifest } from './loader/environment/lod-bundle';\nimport { fetchSplatSource, fileNameOf, splatFormatOf } from './loader/shared/asset-loader';\nimport { cachedFetch } from './loader/shared/bin-cache';\nimport { Splat } from './splat/splat';\n\n/** @group Environment */\nexport interface LoadEnvironmentOptions {\n /** Object name. Default: basename of the URL. */\n name?: string;\n /** World position. Default: origin. */\n position?: { x: number; y: number; z: number };\n /** Euler angles in degrees. Default: no rotation. */\n rotation?: { x: number; y: number; z: number };\n /** Uniform scale. Default: 1. */\n scale?: number;\n /** Explicit filename for extension detection on URLs without one. */\n filename?: string;\n}\n\n/** @group Environment */\nexport interface LoadLodBundleOptions {\n /** Object name. Default: `'lod_environment'`. */\n name?: string;\n /** World position. Default: origin. */\n position?: { x: number; y: number; z: number };\n /**\n * Authored euler angles in degrees. The loader stacks the bundle's\n * RDF-to-Y-up correction (+180 degrees about X) on top: pass the same\n * rotation you would give {@link Environment.load} for the monolithic splat.\n */\n rotation?: { x: number; y: number; z: number };\n /** Uniform scale. Default: 1. */\n scale?: number;\n /**\n * Camera distance (world units) of the first LOD transition. Level `i`\n * takes over from `lodBaseDistance * lodMultiplier^(i-1)`. Default: 8.\n */\n lodBaseDistance?: number;\n /** Geometric ratio between successive LOD distance thresholds. Default: 3. */\n lodMultiplier?: number;\n /**\n * Longest the bundle stays pinned to its coarsest level waiting for it to\n * stream in (a stalled chunk), in ms. Counted from the first\n * {@link SplatEngine.update}, not from load, and pushed back while chunks\n * are still arriving. Default: 8000.\n */\n coarseTimeoutMs?: number;\n /**\n * Pin the whole bundle to one LOD level instead of switching by distance,\n * for editor and debug previews. 0 is the finest; values outside the\n * bundle's range are clamped.\n */\n fixedLodLevel?: number;\n}\n\n/**\n * Environments draw before characters so characters always composite on top,\n * matching the PlayCanvas build's dedicated environment layer.\n */\nconst ENVIRONMENT_RENDER_ORDER = -1;\n\nconst _euler = new Euler();\n\nfunction applyTransform(\n object: Object3D,\n opts: { position?: { x: number; y: number; z: number }; rotation?: { x: number; y: number; z: number }; scale?: number } | undefined,\n extraXDegrees = 0,\n): void {\n if (opts?.position) object.position.set(opts.position.x, opts.position.y, opts.position.z);\n const rotation = opts?.rotation ?? { x: 0, y: 0, z: 0 };\n if (opts?.rotation || extraXDegrees) {\n // 'ZYX' is the order that reproduces the PlayCanvas build's euler convention.\n object.quaternion.setFromEuler(_euler.set(\n (rotation.x + extraXDegrees) * MathUtils.DEG2RAD,\n rotation.y * MathUtils.DEG2RAD,\n rotation.z * MathUtils.DEG2RAD,\n 'ZYX',\n ));\n }\n if (opts?.scale !== undefined) object.scale.setScalar(opts.scale);\n}\n\n/**\n * Gaussian-splat environment loaded into an engine: one splat file, or a\n * streaming LOD bundle.\n *\n * A static, unskinned splat that responds to the engine's lighting registry\n * (sun + sky + point lights). Its depth sort runs in a worker and only when\n * the view direction changes, so a large scene costs nothing while the camera\n * is still.\n *\n * Construct via {@link Environment.load} or {@link Environment.loadLodBundle} -\n * the constructor is internal.\n *\n * @group Environment\n */\nexport class Environment {\n /**\n * The three.js object for the environment. Transform it like any other.\n * For a single file it is the {@link SplatMesh} itself; for a LOD bundle, a\n * group whose child is whichever splat holds the levels drawn now.\n */\n readonly object3D: Object3D;\n\n /**\n * Resolves once the coarsest LOD level has streamed in and the full LOD\n * range is open (or the stall guard gave up waiting), one frame after that\n * frame was drawn. Already resolved for an environment without LOD levels.\n * For a gate that needs the map visible first (\"put the player in\").\n *\n * Frames here are {@link SplatEngine.update} calls: a bundle streams only\n * while the engine is being updated.\n */\n readonly coarseReady: Promise<void>;\n\n private readonly _splat: Splat | null;\n private readonly _lod: LodBundle | null;\n\n private constructor(object3D: Object3D, splat: Splat | null, lod: LodBundle | null) {\n this.object3D = object3D;\n this._splat = splat;\n this._lod = lod;\n this.coarseReady = lod ? lod.coarseReady : Promise.resolve();\n }\n\n /**\n * The splat that draws the environment - for render options, tint and\n * grade. For a LOD bundle, the one drawing it now: replaced as levels\n * change, with the options set on it carried over to its successor, and\n * empty until the first chunks have arrived.\n */\n get splat(): Splat {\n return this._lod ? this._lod.splat : this._splat!;\n }\n\n /** {@link object3D} under the PlayCanvas build's name. Hide it with `visible`, not `enabled`. */\n get entity(): Object3D {\n return this.object3D;\n }\n\n /**\n * Fetch, decode and add an environment splat.\n *\n * Reads uncompressed 3D Gaussian Splatting `.ply`, `.spz` (versions 1 to\n * 4), and SOG (a `.sog` bundle or an unbundled `meta.json`). The format is\n * told by the file name: pass `filename` when the URL does not end in one.\n * `.spz` and SOG decode in a worker.\n *\n * @param url - Location of the splat file.\n * @throws {EngineDisposedError} If `engine` is disposed before or while the file loads.\n */\n static async load(engine: SplatEngine, url: string, opts?: LoadEnvironmentOptions): Promise<Environment> {\n if (engine.destroyed) throw new EngineDisposedError('Environment.load');\n const fname = opts?.filename ?? fileNameOf(url);\n if (!splatFormatOf(fname)) {\n throw new Error(\n `[Environment.load] unsupported environment format '${fname}'; expected .ply, .spz, .sog or a SOG meta.json`,\n );\n }\n\n const source = await fetchSplatSource(url, fname);\n if (engine.destroyed) throw new EngineDisposedError('Environment.load');\n\n // No quality prune here, deliberately. The two load-time knobs\n // (SplatQuality.minOpacity, pruneRatio) are character settings in the\n // Unity build this port takes them from - it applies them in the skinned\n // renderer and nowhere else - and a splat scene is a different\n // distribution: measured on the test capture, minOpacity 0.05 removes 8.7%\n // of a character and 41.8% of a 1M-splat room, because a scene trained\n // without constraints is full of faint splats that are nonetheless what\n // the soft parts of it are made of. `pruneSplats` is exported for an\n // application that wants to make that trade on a scene of its own.\n const splat = new Splat(engine, source);\n const object = splat.object3D;\n object.name = opts?.name ?? fname.replace(/\\.\\w+$/, '');\n object.renderOrder = ENVIRONMENT_RENDER_ORDER;\n applyTransform(object, opts);\n\n engine.contentRoot.add(object);\n return new Environment(object, splat, null);\n }\n\n /**\n * Load a streaming LOD bundle - a `lod-meta.json` octree manifest over SOG\n * chunks, as splat-transform writes it - and add it to the engine.\n *\n * Unlike {@link load}, the splats are not one file: each octree leaf picks\n * a detail level by its distance from {@link SplatEngine.camera} every\n * {@link SplatEngine.update}, and the chunks those levels live in are\n * fetched as they are needed. The promise resolves once the manifest is in;\n * streaming then proceeds in the background, coarsest level first, the full\n * range opening once it is drawn (see {@link coarseReady}). Without a\n * camera the bundle stays at its coarsest level.\n *\n * @param url - Location of the `lod-meta.json`. Chunk paths in it are relative to it.\n * @throws {EngineDisposedError} If `engine` is disposed before or while the manifest loads.\n */\n static async loadLodBundle(engine: SplatEngine, url: string, opts?: LoadLodBundleOptions): Promise<Environment> {\n if (engine.destroyed) throw new EngineDisposedError('Environment.loadLodBundle');\n const res = await cachedFetch(url);\n if (!res.ok) throw new Error(`[Environment.loadLodBundle] fetch failed (${res.status}): ${url}`);\n const manifest = (await res.json()) as LodManifest;\n if (engine.destroyed) throw new EngineDisposedError('Environment.loadLodBundle');\n if (!(manifest.lodLevels > 0) || !Array.isArray(manifest.filenames) || !manifest.tree) {\n throw new Error(`[Environment.loadLodBundle] not a LOD bundle manifest: ${url}`);\n }\n\n const lod = new LodBundle(engine, url, manifest, {\n // PlayCanvas's own floors for the two, which its gsplat component applies.\n lodBaseDistance: Math.max(0.1, opts?.lodBaseDistance ?? 8),\n lodMultiplier: Math.max(1.2, opts?.lodMultiplier ?? 3),\n coarseTimeoutMs: opts?.coarseTimeoutMs ?? 8000,\n fixedLodLevel: opts?.fixedLodLevel,\n });\n lod.root.name = opts?.name ?? 'lod_environment';\n // splat-transform writes a bundle's SOG in RDF (Y down): 180 degrees about\n // X brings it upright, stacked on the authored rotation.\n applyTransform(lod.root, opts, 180);\n\n engine.contentRoot.add(lod.root);\n return new Environment(lod.root, null, lod);\n }\n\n /** Remove the environment and release its GPU resources. A LOD bundle stops streaming. */\n destroy(): void {\n this._lod?.destroy();\n this._splat?.destroy();\n }\n}\n", "/**\n * Streaming LOD bundles: a `lod-meta.json` octree manifest over chunk files\n * (SOG `meta.json`s as splat-transform writes them), each chunk holding one\n * detail level of a run of octree leaves.\n *\n * PlayCanvas streams these itself; this is the same policy over this\n * package's renderer. Every frame each leaf picks a level by its distance from\n * the camera, the chunk files those levels live in are fetched (coarser and\n * nearer first), and once a leaf's level has arrived the splats drawn are\n * rebuilt as ONE splat holding every leaf at its current level.\n *\n * One splat and not one per leaf or per chunk, because splats from separate\n * meshes are layered by draw order rather than depth (see the README): a\n * scene drawn as many meshes composites far leaves over near ones. A single\n * splat is sorted as a whole, which is what PlayCanvas's unified gsplat\n * rendering does. The price is that a level change re-uploads the scene; the\n * old splat keeps drawing until the new one has its first depth order, so the\n * switch never shows a gap.\n *\n * There is always a splat, so that render options set on it before anything\n * has streamed in carry over: until the first chunks arrive it is an empty one\n * kept out of the scene.\n */\n\nimport { Group, Matrix4, Vector3 } from 'three';\nimport type { Camera, PerspectiveCamera } from 'three';\n\nimport type { SplatEngine } from '../../engine';\nimport type { PackedSplats } from '../../splat/packed-splats';\nimport { textureSizeFor } from '../../splat/packed-splats';\nimport { Splat } from '../../splat/splat';\nimport { fetchSplatSource } from '../shared/asset-loader';\nimport { resolveUrl } from '../shared/sog';\n\n/** A `lod-meta.json`, as splat-transform writes it and PlayCanvas's `GSplatOctree` reads it. */\nexport interface LodManifest {\n lodLevels: number;\n /** Chunk files, relative to the manifest. */\n filenames: string[];\n /** An optional splat drawn whole at every distance (a skybox), relative to the manifest. */\n environment?: string | null;\n tree: LodTreeNode;\n}\n\ninterface LodTreeNode {\n bound: { min: number[]; max: number[] };\n children?: LodTreeNode[];\n /** Leaves only: where each level of this leaf's splats is, keyed by level. */\n lods?: Record<string, { file: number; offset?: number; count?: number }>;\n}\n\n/** Tuning for {@link LodBundle}, as `LoadLodBundleOptions` carries it. */\nexport interface LodBundleSettings {\n lodBaseDistance: number;\n lodMultiplier: number;\n coarseTimeoutMs: number;\n fixedLodLevel?: number;\n}\n\ninterface Leaf {\n /** Per level: file index (-1 for none), first splat in that file, splat count. */\n file: Int32Array;\n offset: Int32Array;\n count: Int32Array;\n min: Vector3;\n max: Vector3;\n /** How far the box overhangs a typical leaf's, per axis; see `evaluateDistances`. */\n excess: Vector3;\n}\n\ninterface ChunkFile {\n url: string;\n packed: PackedSplats | null;\n loading: boolean;\n failed: boolean;\n /** Frames since anything last wanted this file; it is dropped at {@link UNLOAD_AFTER_FRAMES}. */\n idleFrames: number;\n}\n\n// PlayCanvas's defaults for the knobs PlayCanvas has and this API does not\n// surface (GSplatParams): splats behind the camera count as up to 1.5x as far,\n// leaf boxes are shrunk by 75% of their overhang over a typical leaf before\n// measuring, and an unused chunk is kept for 100 frames.\nconst BEHIND_PENALTY = 0.5;\nconst DISTANCE_SHRINK = 0.75;\nconst UNLOAD_AFTER_FRAMES = 100;\n/** Distances are scaled to a 45 degree vertical field of view, PlayCanvas's reference. */\nconst REF_TAN_HALF_FOV = Math.tan((22.5 * Math.PI) / 180);\n/** Chunk downloads in flight at once. */\nconst MAX_LOADS = 4;\nconst ENVIRONMENT_RENDER_ORDER = -1;\n\nconst _inverse = new Matrix4();\nconst _cameraPos = new Vector3();\nconst _cameraFwd = new Vector3();\nconst _tmp = new Vector3();\n\n/** @internal Drives one bundle; owned by its `Environment`. */\nexport class LodBundle {\n /** Carries the bundle's transform; the splat drawing it is its child. */\n readonly root = new Group();\n readonly coarseReady: Promise<void>;\n\n private readonly _engine: SplatEngine;\n private readonly _settings: LodBundleSettings;\n private readonly _leaves: Leaf[];\n private readonly _files: ChunkFile[];\n private readonly _environmentFile: ChunkFile | null;\n /** Per leaf: the level it should show now, and the level the drawn splat holds (-1: none). */\n private readonly _desired: Int32Array;\n private readonly _drawn: Int32Array;\n private readonly _distance: Float32Array;\n private _rangeMin: number;\n private _rangeMax: number;\n private _drawnEnvironment = false;\n private _splat: Splat;\n /** The splat being swapped in, drawing alongside {@link _splat} until its first sort lands. */\n private _incoming: Splat | null = null;\n private _loadsInFlight = 0;\n private _coarsePinned: boolean;\n private _coarseTimer: ReturnType<typeof setTimeout> | null = null;\n private _resolveCoarse: (() => void) | null = null;\n private _coarseOpenedFrame = false;\n private readonly _removeUpdater: () => void;\n private _destroyed = false;\n\n constructor(engine: SplatEngine, manifestUrl: string, manifest: LodManifest, settings: LodBundleSettings) {\n this._engine = engine;\n this._settings = settings;\n this._files = manifest.filenames.map((name) => chunkFile(resolveUrl(name, manifestUrl)));\n this._environmentFile = manifest.environment ? chunkFile(resolveUrl(manifest.environment, manifestUrl)) : null;\n // Checked here, once: a bad index would otherwise throw every frame from\n // inside the engine's update.\n this._leaves = extractLeaves(manifest.tree, manifest.lodLevels, this._files.length, manifestUrl);\n const n = this._leaves.length;\n this._desired = new Int32Array(n).fill(-1);\n this._drawn = new Int32Array(n).fill(-1);\n this._distance = new Float32Array(n);\n this._splat = new Splat(engine, { packed: emptyPacked() });\n\n const coarsest = Math.max(0, manifest.lodLevels - 1);\n if (settings.fixedLodLevel !== undefined) {\n // Pinned for good, so there is no coarse pass to wait out.\n const level = Math.min(coarsest, Math.max(0, Math.round(settings.fixedLodLevel)));\n this._rangeMin = this._rangeMax = level;\n this._coarsePinned = false;\n this.coarseReady = Promise.resolve();\n } else {\n // Coarse first: the whole bundle at its coarsest level, so something is\n // on screen as soon as possible, then the full range once that is in.\n this._rangeMin = this._rangeMax = coarsest;\n this._coarsePinned = true;\n this.coarseReady = new Promise((resolve) => { this._resolveCoarse = resolve; });\n }\n\n this._removeUpdater = engine.addUpdater(() => this._update());\n }\n\n /** The splat drawing the bundle now: empty, and not in the scene, until its first chunks have arrived. */\n get splat(): Splat {\n return this._incoming ?? this._splat;\n }\n\n destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n this._removeUpdater();\n if (this._coarseTimer !== null) clearTimeout(this._coarseTimer);\n this._incoming?.destroy();\n this._incoming = null;\n this._splat.destroy();\n for (const f of this._files) f.packed = null;\n this.root.removeFromParent();\n }\n\n private _update(): void {\n if (this._destroyed) return;\n if (this._coarseOpenedFrame) {\n // A frame after the range opened, so the frame showing the coarse\n // level has been drawn before a loading screen waiting on this clears.\n this._coarseOpenedFrame = false;\n this._resolveCoarse?.();\n this._resolveCoarse = null;\n }\n\n this._finishSwap();\n this._chooseLevels();\n this._requestFiles();\n this._rebuildIfChanged();\n this._unloadIdleFiles();\n if (this._coarsePinned) this._watchCoarse();\n }\n\n /** Each leaf's level for this frame, from its distance to the camera. */\n private _chooseLevels(): void {\n const camera = this._engine.camera;\n const { lodBaseDistance: base, lodMultiplier: mult } = this._settings;\n const span = this._rangeMax - this._rangeMin + 1;\n if (camera) this._evaluateDistances(camera);\n for (let i = 0; i < this._leaves.length; i++) {\n // Band b covers distances from base * mult^(rangeMin + b - 1); take the\n // farthest band this leaf has reached. With no camera, the coarsest.\n let band = span - 1;\n if (camera) {\n const d = this._distance[i];\n while (band > 0 && d < base * mult ** (this._rangeMin + band - 1)) band--;\n }\n this._desired[i] = levelForBand(this._leaves[i], this._rangeMin + band, this._rangeMin, this._rangeMax);\n }\n }\n\n /**\n * Distance from the camera to each leaf's box, in the bundle's local space,\n * scaled as PlayCanvas scales it: by the bundle's world scale, by the field\n * of view relative to 45 degrees (a narrower view sees farther, so detail\n * holds out longer), and up to 1.5x for a box behind the camera.\n */\n private _evaluateDistances(camera: Camera): void {\n this.root.updateWorldMatrix(true, false);\n _inverse.copy(this.root.matrixWorld).invert();\n _cameraPos.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_inverse);\n camera.getWorldDirection(_cameraFwd).transformDirection(_inverse);\n let fovScale = 1;\n const perspective = camera as PerspectiveCamera;\n if (perspective.isPerspectiveCamera) {\n const tanHalfV = Math.tan((perspective.fov * Math.PI) / 360) / perspective.zoom;\n const aspect = perspective.aspect > 0 && Number.isFinite(perspective.aspect) ? perspective.aspect : 1;\n fovScale = Math.min(tanHalfV, tanHalfV * aspect) / REF_TAN_HALF_FOV;\n }\n const scale = fovScale * this.root.getWorldScale(_tmp).x;\n\n for (let i = 0; i < this._leaves.length; i++) {\n const { min, max, excess } = this._leaves[i];\n const shrinkX = excess.x * DISTANCE_SHRINK, shrinkY = excess.y * DISTANCE_SHRINK, shrinkZ = excess.z * DISTANCE_SHRINK;\n const dx = clamp(_cameraPos.x, min.x + shrinkX, max.x - shrinkX) - _cameraPos.x;\n const dy = clamp(_cameraPos.y, min.y + shrinkY, max.y - shrinkY) - _cameraPos.y;\n const dz = clamp(_cameraPos.z, min.z + shrinkZ, max.z - shrinkZ) - _cameraPos.z;\n const d = Math.sqrt(dx * dx + dy * dy + dz * dz);\n let penalty = 1;\n if (d > 1e-2) {\n const along = (_cameraFwd.x * dx + _cameraFwd.y * dy + _cameraFwd.z * dz) / d;\n if (along < 0) penalty = 1 - along * BEHIND_PENALTY;\n }\n this._distance[i] = d * penalty * scale;\n }\n }\n\n /** Start downloads for the chunks the chosen levels need: coarser levels first, then nearer leaves. */\n private _requestFiles(): void {\n if (this._environmentFile) this._load(this._environmentFile, false);\n const wanted: { file: number; level: number; distance: number }[] = [];\n for (let i = 0; i < this._leaves.length; i++) {\n const level = this._desired[i];\n if (level < 0) continue;\n const f = this._leaves[i].file[level];\n const file = this._files[f];\n // Wanted, so not idle - even while it waits for a free download slot.\n file.idleFrames = 0;\n if (!file.packed && !file.loading && !file.failed) wanted.push({ file: f, level, distance: this._distance[i] });\n }\n wanted.sort((a, b) => b.level - a.level || a.distance - b.distance);\n for (const w of wanted) {\n if (this._loadsInFlight >= MAX_LOADS) break;\n this._load(this._files[w.file], true);\n }\n }\n\n private _load(file: ChunkFile, counted: boolean): void {\n if (file.packed || file.loading || file.failed) return;\n file.loading = true;\n if (counted) this._loadsInFlight++;\n fetchSplatSource(file.url)\n .then(({ packed }) => {\n if (!this._destroyed) file.packed = packed;\n })\n .catch((err: unknown) => {\n // A chunk that will not load leaves its leaves at the level they have;\n // retrying every frame would only repeat the failure.\n file.failed = true;\n console.error(`[Environment.loadLodBundle] chunk failed: ${file.url}`, err);\n })\n .finally(() => {\n file.loading = false;\n if (counted) this._loadsInFlight--;\n });\n }\n\n /**\n * What each leaf can draw this frame: its chosen level once that chunk is\n * in, else whatever it draws already, so a level change never opens a hole.\n * When that differs from what is drawn, build the splat that draws it.\n * One swap at a time: the next waits for the last one's first sort.\n */\n private _rebuildIfChanged(): void {\n if (this._incoming) return;\n const n = this._leaves.length;\n const next = new Int32Array(n);\n let changed = false;\n for (let i = 0; i < n; i++) {\n const want = this._desired[i];\n const drawn = this._drawn[i];\n const leaf = this._leaves[i];\n next[i] = want >= 0 && this._files[leaf.file[want]].packed ? want\n : want < 0 ? -1\n : drawn >= 0 && this._files[leaf.file[drawn]].packed ? drawn\n : -1;\n if (next[i] !== drawn) changed = true;\n }\n const environment = this._environmentFile?.packed != null;\n if (!changed && environment === this._drawnEnvironment) return;\n this._drawn.set(next);\n this._drawnEnvironment = environment;\n this._swapIn(this._composite(next, environment));\n }\n\n /** One splat set holding every leaf at its level in `levels`, plus the environment splat. */\n private _composite(levels: Int32Array, environment: boolean): PackedSplats {\n const pieces: { packed: PackedSplats; offset: number; count: number }[] = [];\n let total = 0;\n const lo = new Vector3(Infinity, Infinity, Infinity);\n const hi = new Vector3(-Infinity, -Infinity, -Infinity);\n for (let i = 0; i < levels.length; i++) {\n const level = levels[i];\n if (level < 0) continue;\n const leaf = this._leaves[i];\n const packed = this._files[leaf.file[level]].packed!;\n // A run that overhangs its chunk is cut to what the chunk holds.\n const offset = leaf.offset[level];\n const count = Math.max(0, Math.min(leaf.count[level], packed.numSplats - offset));\n if (count === 0) continue;\n pieces.push({ packed, offset, count });\n total += count;\n lo.min(leaf.min);\n hi.max(leaf.max);\n }\n const env = environment ? this._environmentFile!.packed! : null;\n if (env) {\n pieces.push({ packed: env, offset: 0, count: env.numSplats });\n total += env.numSplats;\n lo.min(_tmp.fromArray(env.boundsMin));\n hi.max(_tmp.fromArray(env.boundsMax));\n }\n if (total === 0) return emptyPacked();\n\n const { width, height } = textureSizeFor(total);\n const texels = width * height;\n const out: PackedSplats = {\n numSplats: total,\n width,\n height,\n color: new Uint16Array(texels * 4),\n transformA: new Uint32Array(texels * 4),\n transformB: new Uint16Array(texels * 4),\n centers: new Float32Array(total * 3),\n boundsMin: [lo.x, lo.y, lo.z],\n boundsMax: [hi.x, hi.y, hi.z],\n };\n // Every stream is one record per splat in splat order, so a leaf's run is\n // one contiguous copy per stream.\n let at = 0;\n for (const { packed, offset, count } of pieces) {\n const end = offset + count;\n out.color.set(packed.color.subarray(offset * 4, end * 4), at * 4);\n out.transformA.set(packed.transformA.subarray(offset * 4, end * 4), at * 4);\n out.transformB.set(packed.transformB.subarray(offset * 4, end * 4), at * 4);\n out.centers.set(packed.centers.subarray(offset * 3, end * 3), at * 3);\n at += count;\n }\n return out;\n }\n\n private _swapIn(packed: PackedSplats): void {\n const splat = new Splat(this._engine, { packed });\n // Render options set on the splat being replaced carry over to its successor.\n const previous = this._splat;\n splat.tint.copy(previous.tint);\n splat.grade.copy(previous.grade);\n splat.effects.x = previous.effects.x;\n splat.minPixelSize = previous.minPixelSize;\n splat.antiAlias = previous.antiAlias;\n if (packed.numSplats === 0) {\n // Nothing to draw, so nothing to wait for: kept out of the scene.\n previous.destroy();\n this._splat = splat;\n return;\n }\n splat.object3D.name = this.root.name;\n splat.object3D.renderOrder = ENVIRONMENT_RENDER_ORDER;\n this.root.add(splat.object3D);\n this._incoming = splat;\n }\n\n /** Retire the old splat once the incoming one draws a sorted frame. */\n private _finishSwap(): void {\n const incoming = this._incoming;\n if (!incoming || incoming.object3D.sortPending) return;\n this._splat.destroy();\n this._splat = incoming;\n this._incoming = null;\n }\n\n private _unloadIdleFiles(): void {\n const inUse = new Set<number>();\n for (let i = 0; i < this._leaves.length; i++) {\n if (this._drawn[i] >= 0) inUse.add(this._leaves[i].file[this._drawn[i]]);\n }\n for (let f = 0; f < this._files.length; f++) {\n const file = this._files[f];\n if (!file.packed || inUse.has(f)) continue;\n // `_requestFiles` resets the count for every file a leaf still wants.\n if (++file.idleFrames > UNLOAD_AFTER_FRAMES) file.packed = null;\n }\n }\n\n /**\n * While pinned to the coarsest level: open the full range once every leaf\n * draws it, or once the stall guard fires. The guard is armed by the first\n * frame, not at load - nothing streams until frames run, and a game may\n * show a menu for a while first - and pushed back while chunks are still\n * arriving, so a slow connection streaming steadily is not a stall.\n */\n private _watchCoarse(): void {\n if (this._loadsInFlight > 0 || this._coarseTimer === null) {\n if (this._coarseTimer !== null) clearTimeout(this._coarseTimer);\n this._coarseTimer = setTimeout(() => this._openRange(), this._settings.coarseTimeoutMs);\n }\n const env = this._environmentFile;\n const complete = !this._incoming && this._splat.numSplats > 0 &&\n (!env || env.failed || this._drawnEnvironment) &&\n this._leaves.every((_leaf, i) => this._desired[i] < 0 || this._drawn[i] === this._desired[i]);\n if (complete && !this._splat.object3D.sortPending) this._openRange();\n }\n\n private _openRange(): void {\n if (!this._coarsePinned || this._destroyed) return;\n this._coarsePinned = false;\n if (this._coarseTimer !== null) clearTimeout(this._coarseTimer);\n this._coarseTimer = null;\n this._rangeMin = 0;\n this._coarseOpenedFrame = true;\n }\n}\n\nfunction emptyPacked(): PackedSplats {\n return {\n numSplats: 0, width: 1, height: 1,\n color: new Uint16Array(4), transformA: new Uint32Array(4), transformB: new Uint16Array(4),\n centers: new Float32Array(0), boundsMin: [0, 0, 0], boundsMax: [0, 0, 0],\n };\n}\n\nfunction chunkFile(url: string): ChunkFile {\n return { url, packed: null, loading: false, failed: false, idleFrames: 0 };\n}\n\nfunction clamp(v: number, lo: number, hi: number): number {\n return v < lo ? lo : v > hi ? hi : v;\n}\n\n/**\n * The level a leaf shows for `band`, as PlayCanvas's `GSplatLodTable` maps it.\n * A band past the coarsest level the leaf has data for (within the range)\n * shows nothing - a leaf whose coarsest level is still too fine for its\n * distance drops out. A band the leaf has no data for borrows the nearest\n * finer level, else the nearest coarser one.\n */\nfunction levelForBand(leaf: Leaf, band: number, rangeMin: number, rangeMax: number): number {\n let coarsest = -1;\n for (let l = rangeMax; l >= rangeMin; l--) {\n if (leaf.count[l] > 0) { coarsest = l; break; }\n }\n if (coarsest < 0 || band > coarsest) return -1;\n if (leaf.count[band] > 0) return band;\n for (let l = band - 1; l >= rangeMin; l--) if (leaf.count[l] > 0) return l;\n for (let l = band + 1; l <= coarsest; l++) if (leaf.count[l] > 0) return l;\n return -1;\n}\n\n/** The octree's leaves, with each box's overhang over the median leaf box per axis. */\nfunction extractLeaves(tree: LodTreeNode, lodLevels: number, numFiles: number, url: string): Leaf[] {\n const leaves: Leaf[] = [];\n const index = (v: unknown, what: string, below = Infinity): number => {\n if (Number.isInteger(v) && (v as number) >= 0 && (v as number) < below) return v as number;\n throw new Error(`[Environment.loadLodBundle] bad ${what} ${String(v)} in ${url}`);\n };\n const walk = (node: LodTreeNode): void => {\n if (node.lods) {\n const file = new Int32Array(lodLevels).fill(-1);\n const offset = new Int32Array(lodLevels);\n const count = new Int32Array(lodLevels);\n for (let l = 0; l < lodLevels; l++) {\n const lod = node.lods[String(l)];\n // A level listed with no splats has nothing to load, like one omitted.\n if (!lod || !(lod.count! > 0)) continue;\n file[l] = index(lod.file, 'file index', numFiles);\n offset[l] = index(lod.offset ?? 0, 'offset', 2 ** 31);\n count[l] = index(lod.count, 'count', 2 ** 31);\n }\n leaves.push({\n file, offset, count,\n min: new Vector3().fromArray(node.bound.min),\n max: new Vector3().fromArray(node.bound.max),\n excess: new Vector3(),\n });\n } else {\n for (const child of node.children ?? []) walk(child);\n }\n };\n walk(tree);\n\n for (const axis of ['x', 'y', 'z'] as const) {\n const half = leaves.map((leaf) => (leaf.max[axis] - leaf.min[axis]) * 0.5);\n const typical = Float32Array.from(half).sort()[half.length >> 1] ?? 0;\n leaves.forEach((leaf, i) => { leaf.excess[axis] = Math.max(0, half[i] - typical); });\n }\n return leaves;\n}\n", "import { FileLoader, Loader } from 'three';\nimport type { LoadingManager } from 'three';\n\nimport { SplatEngine } from '../engine';\nimport { decodeSpz } from '../loader/environment/spz';\nimport { Splat } from '../splat/splat';\nimport type { SplatMesh } from '../splat/splat-mesh';\n\n/**\n * Loads an `.spz` Gaussian-splat capture (versions 1 to 4) as a static\n * {@link SplatMesh}, the way {@link SplatPLYLoader} loads a `.ply`.\n *\n * ```ts\n * const field = await new SplatSPZLoader().loadAsync('/assets/field.spz');\n * scene.add(field);\n * ```\n *\n * The file decodes and packs in a worker; version 4's zstd streams are\n * inflated on the calling thread first, since no browser offers zstd to\n * script. The mesh is given `renderOrder = -1` so it draws before characters,\n * as {@link SplatPLYLoader}'s is.\n *\n * SPZ stores no coordinate convention of its own and none is applied here:\n * the splats come out in the file's axes, as the PlayCanvas build reads them.\n *\n * @group Loaders\n */\nexport class SplatSPZLoader extends Loader<SplatMesh> {\n /**\n * The engine loaded meshes belong to: the lights they respond to. Leave\n * unset to use {@link SplatEngine.shared}.\n */\n engine: SplatEngine | null = null;\n\n constructor(manager?: LoadingManager) {\n super(manager);\n }\n\n setEngine(engine: SplatEngine | null): this {\n this.engine = engine;\n return this;\n }\n\n /** Decode bytes already in memory. `name` labels the mesh; for a loaded file it is the file's base name. */\n async parseAsync(data: ArrayBuffer, name = 'splat'): Promise<SplatMesh> {\n const packed = await decodeSpz(new Uint8Array(data));\n // No quality prune, as for SplatPLYLoader: see the note there.\n const splat = new Splat(this.engine ?? SplatEngine.shared, { packed });\n const mesh = splat.object3D;\n mesh.name = name;\n mesh.renderOrder = -1;\n return mesh;\n }\n\n override load(\n url: string,\n onLoad: (result: SplatMesh) => void,\n onProgress?: (event: ProgressEvent) => void,\n onError?: (error: unknown) => void,\n ): void {\n // Through a FileLoader, so the LoadingManager, base path, request headers\n // and credentials mode all apply.\n const loader = new FileLoader(this.manager);\n loader.setPath(this.path);\n loader.setResponseType('arraybuffer');\n loader.setRequestHeader(this.requestHeader);\n loader.setWithCredentials(this.withCredentials);\n loader.load(\n url,\n (data) => {\n const name = (url.split(/[?#]/)[0].split('/').pop() ?? '').replace(/\\.\\w+$/, '');\n this.parseAsync(data as ArrayBuffer, name).then(onLoad, (error) => {\n if (onError) onError(error);\n else console.error(error);\n this.manager.itemError(url);\n });\n },\n onProgress,\n onError,\n );\n }\n}\n", "import { Color, Vector3 } from 'three';\n\nimport type { SplatEngine } from '../engine';\n\nimport { applyHexTo, rawColor } from './color';\n\n/** @group Lighting */\nexport interface CreateSunLightOptions {\n /** Azimuth in degrees. 0 = +Z, 90 = +X. */\n azimuth?: number;\n /** Elevation in degrees. 0 = horizon, 90 = directly overhead. */\n elevation?: number;\n /** Sun colour as CSS hex string, e.g. '#fff4e0'. */\n color?: string;\n /** Brightness multiplier applied to `color` in the shader. */\n intensity?: number;\n /** Start disabled. Lights default to enabled. */\n enabled?: boolean;\n}\n\n/**\n * Directional light for splats. Splats have no normals, so the sun is a flat\n * brightness term: every splat receives `color * intensity`, regardless of\n * which way it faces.\n *\n * @group Lighting\n */\nexport class SunLight {\n azimuth = 30;\n elevation = 60;\n /** Raw component values; not colour-managed. */\n color = rawColor(new Color(), 1, 0.95, 0.85);\n intensity = 1.0;\n enabled = true;\n\n /** Unit vector pointing from the scene toward the sun. */\n lightDir(out: Vector3 = new Vector3()): Vector3 {\n const azRad = (this.azimuth * Math.PI) / 180;\n const elRad = (this.elevation * Math.PI) / 180;\n const ce = Math.cos(elRad);\n return out.set(ce * Math.sin(azRad), Math.sin(elRad), ce * Math.cos(azRad));\n }\n\n /** Create a sun and make it the engine's sun. */\n static create(engine: SplatEngine, opts?: CreateSunLightOptions): SunLight {\n const sun = new SunLight();\n if (opts?.azimuth !== undefined) sun.azimuth = opts.azimuth;\n if (opts?.elevation !== undefined) sun.elevation = opts.elevation;\n if (opts?.color !== undefined) applyHexTo(sun.color, opts.color);\n if (opts?.intensity !== undefined) sun.intensity = opts.intensity;\n if (opts?.enabled !== undefined) sun.enabled = opts.enabled;\n engine.lighting.sun = sun;\n return sun;\n }\n}\n", "import type { Color } from 'three';\n\n/** Parse `#rrggbb` into raw 0..1 components. */\nexport function parseHex(css: string): [number, number, number] {\n const hex = css.replace('#', '');\n const r = parseInt(hex.substring(0, 2), 16) / 255;\n const g = parseInt(hex.substring(2, 4), 16) / 255;\n const b = parseInt(hex.substring(4, 6), 16) / 255;\n return [r, g, b];\n}\n\n/**\n * Write a CSS hex colour into `color` as raw component values.\n *\n * Deliberately not `Color.set(hex)`: light colours here multiply baked,\n * display-referred splat colour, so they are used as written. three.js colour\n * management would convert the hex to linear and darken every light.\n */\nexport function applyHexTo(color: Color, css: string): void {\n const [r, g, b] = parseHex(css);\n color.r = r;\n color.g = g;\n color.b = b;\n}\n\n/** A `Color` holding exactly the given component values, with no colour-space conversion. */\nexport function rawColor(color: Color, r: number, g: number, b: number): Color {\n color.r = r;\n color.g = g;\n color.b = b;\n return color;\n}\n", "import { Color } from 'three';\n\nimport type { SplatEngine } from '../engine';\n\nimport { applyHexTo, rawColor } from './color';\n\n/** @group Lighting */\nexport interface CreateSkyLightOptions {\n /** Sky colour as CSS hex string. */\n color?: string;\n intensity?: number;\n enabled?: boolean;\n}\n\n/**\n * Ambient light for splats: a constant `color * intensity` added to every splat.\n *\n * @group Lighting\n */\nexport class SkyLight {\n /** Raw component values; not colour-managed. */\n color = rawColor(new Color(), 0.55, 0.62, 0.78);\n intensity = 0.35;\n enabled = true;\n\n /** Create a sky light and make it the engine's sky. */\n static create(engine: SplatEngine, opts?: CreateSkyLightOptions): SkyLight {\n const sky = new SkyLight();\n if (opts?.color !== undefined) applyHexTo(sky.color, opts.color);\n if (opts?.intensity !== undefined) sky.intensity = opts.intensity;\n if (opts?.enabled !== undefined) sky.enabled = opts.enabled;\n engine.lighting.sky = sky;\n return sky;\n }\n}\n", "import { Color, Vector3 } from 'three';\n\nimport type { SplatEngine } from '../engine';\n\nimport { applyHexTo, rawColor } from './color';\n\n/** @group Lighting */\nexport interface CreatePointLightOptions {\n position?: { x: number; y: number; z: number };\n /** Light colour as CSS hex string. */\n color?: string;\n intensity?: number;\n /** Hard cutoff distance in world units. Contribution is 0 at and beyond this. */\n range?: number;\n enabled?: boolean;\n}\n\n/** @group Lighting */\nexport class PointLight {\n /** World-space position. */\n position = new Vector3();\n /** Raw component values; not colour-managed. */\n color = rawColor(new Color(), 1, 1, 1);\n intensity = 1.0;\n range = 5.0;\n enabled = true;\n\n private _engine: SplatEngine | null = null;\n\n /** @internal */\n _attach(engine: SplatEngine): void {\n this._engine = engine;\n }\n\n /** Remove this light from its engine. After calling, the light stops contributing. */\n destroy(): void {\n const engine = this._engine;\n if (!engine) return;\n const i = engine.lighting.points.indexOf(this);\n if (i >= 0) engine.lighting.points.splice(i, 1);\n this._engine = null;\n }\n\n /** Create a point light and register it on the engine's lighting registry. */\n static create(engine: SplatEngine, opts?: CreatePointLightOptions): PointLight {\n const light = new PointLight();\n if (opts?.position) light.position.set(opts.position.x, opts.position.y, opts.position.z);\n if (opts?.color !== undefined) applyHexTo(light.color, opts.color);\n if (opts?.intensity !== undefined) light.intensity = opts.intensity;\n if (opts?.range !== undefined) light.range = opts.range;\n if (opts?.enabled !== undefined) light.enabled = opts.enabled;\n light._attach(engine);\n engine.lighting.points.push(light);\n return light;\n }\n}\n", "import type { Object3D } from 'three';\n\nimport type { Vec3Like } from '../../presets/camera/camera-preset';\nimport type { Scene } from '../../scene';\nimport type { IVfxInstance, IVfxPrefab } from './prefab';\n\ninterface PoolEntry {\n instance: IVfxInstance;\n active: boolean;\n}\n\n/**\n * Per-spawn knobs forwarded to the underlying {@link IVfxInstance}.\n *\n * @group Effects\n */\nexport interface VfxSpawnOptions {\n /** Uniform scale multiplier applied via {@link IVfxInstance.setScale}. */\n scale?: number;\n /** RGB tint (0..1). Ignored if the prefab doesn't implement `setColor`. */\n color?: [number, number, number];\n /** Position offset added to the spawn position. */\n offset?: { x?: number; y?: number; z?: number };\n /** Euler rotation (degrees) for the effect root. Ignored if the prefab\n * doesn't implement `setRotation`. Use to aim directional effects (slash\n * arcs, cones) at a target. */\n rotation?: { x?: number; y?: number; z?: number };\n}\n\n/**\n * Generic ring-buffer pool for VFX. Contains zero VFX-specific code - the\n * pool only knows how to call the {@link IVfxInstance} lifecycle. Prefab\n * choice (particles, mesh flashes, etc.) is supplied at construction.\n *\n * @group Effects\n */\nexport class VfxPool {\n private readonly _entries: PoolEntry[];\n private readonly _prefab: IVfxPrefab;\n private readonly _scratchPos = { x: 0, y: 0, z: 0 };\n\n constructor(prefab: IVfxPrefab, scene: Scene, root: Object3D, size: number) {\n this._prefab = prefab;\n this._entries = Array.from({ length: size }, () => ({\n instance: prefab.create(scene, root),\n active: false,\n }));\n }\n\n /**\n * Activate an effect at `pos`. If no free slot exists, the oldest slot\n * (index 0) is force-recycled.\n */\n spawn(pos: Vec3Like, opts?: VfxSpawnOptions): void {\n const entry = this._entries.find((e) => !e.active) ?? this._entries[0];\n if (entry.active) entry.instance.reset();\n entry.active = true;\n if (opts?.scale !== undefined) entry.instance.setScale(opts.scale);\n if (opts?.color && entry.instance.setColor) entry.instance.setColor(opts.color);\n if (opts?.rotation && entry.instance.setRotation) {\n entry.instance.setRotation(opts.rotation.x ?? 0, opts.rotation.y ?? 0, opts.rotation.z ?? 0);\n }\n const o = opts?.offset;\n let sp = pos;\n if (o) {\n const s = this._scratchPos;\n s.x = pos.x + (o.x ?? 0);\n s.y = pos.y + (o.y ?? 0);\n s.z = pos.z + (o.z ?? 0);\n sp = s;\n }\n entry.instance.spawn(sp);\n }\n\n /** Advance all active effects. Call once per frame. */\n update(dt: number): void {\n for (const entry of this._entries) {\n if (!entry.active) continue;\n const finished = entry.instance.update(dt);\n if (finished) {\n entry.active = false;\n entry.instance.reset();\n }\n }\n }\n\n /** Dispose all instances and the prefab's shared GPU resources. */\n destroy(): void {\n for (const entry of this._entries) entry.instance.dispose();\n this._prefab.dispose?.();\n }\n}\n", "/**\n * JsonVfxPrefab - generic JSON-walker that turns a `VfxEffectData` into a\n * runnable VFX. Knows nothing about specific layer types: looks each layer's\n * `type` up in a `VfxLayerRegistry` and delegates construction + per-frame\n * tick to the matched `VfxLayerRenderer`.\n *\n * Owns:\n * - The root object and its rotation animation (`rootRotationSpeed`).\n * - Shared time math: `elapsed`, `loop`, per-layer `startDelay` + duration\n * resolution. Renderers receive a clean `VfxLayerUpdateContext`.\n * - Optional position trail (puffs sampled from the root's path).\n *\n * Implements the `IVfxPrefab` / `IVfxInstance` contracts so it plugs into\n * `VfxPool` (gameplay path) and `VfxStage.spawn` (editor path) unchanged.\n */\n\nimport { Group, Vector3 } from 'three';\nimport type { Mesh, MeshBasicMaterial, Object3D } from 'three';\n\nimport type { Vec3Like } from '../../presets/camera/camera-preset';\nimport type { Scene } from '../../scene';\nimport type { IVfxInstance, IVfxPrefab } from './prefab';\nimport type { VfxEffectData, VfxLayer, VfxTrailConfig } from './data-types';\nimport type {\n VfxLayerBuildContext,\n VfxLayerInstance,\n VfxLayerRegistry,\n VfxLayerUpdateContext,\n} from './layer-renderer';\nimport { buildVfxTrailMesh } from './layers/mesh';\nimport { isParticleLayerInstance } from './layers/particle';\nimport { quatFromEulerDeg } from './layers/shared';\n\n// \u2500\u2500 Per-layer cached snapshot \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface LayerSlot {\n layer: VfxLayer;\n instance: VfxLayerInstance;\n /** Resolved layer duration: `layer.duration > 0 ? layer.duration : effectDuration`. */\n duration: number;\n}\n\n// \u2500\u2500 JsonVfxInstance \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * One live effect built by {@link JsonVfxPrefab}.\n *\n * @group Effects\n */\nexport class JsonVfxInstance implements IVfxInstance {\n private readonly _root: Group;\n private readonly _slots: LayerSlot[];\n private readonly _duration: number;\n private readonly _loop: boolean;\n private readonly _rootRotSpeed: [number, number, number] | undefined;\n\n private readonly _trailMeshes: Mesh[];\n private readonly _trailMaterials: MeshBasicMaterial[];\n private readonly _trailBuf: Vector3[];\n private readonly _trailConfig: VfxTrailConfig | undefined;\n private _trailHead = 0;\n private _trailTimer = 0;\n\n private _elapsed = 0;\n private _alive = false;\n private _scale = 1;\n /** Base Euler (degrees) from the last `setRotation`, used to aim\n * directional effects (e.g. a slash arc at its target). The root's\n * rotation each frame is this base plus any `rootRotSpeed` spin, so a\n * spinning effect still respects its spawn-time aim. */\n private readonly _baseEuler: [number, number, number] = [0, 0, 0];\n\n /** @internal Built by {@link JsonVfxPrefab.create}. */\n constructor(\n root: Group,\n slots: LayerSlot[],\n duration: number,\n loop: boolean,\n rootRotSpeed?: [number, number, number],\n trailMeshes?: Mesh[],\n trailMaterials?: MeshBasicMaterial[],\n trailConfig?: VfxTrailConfig,\n ) {\n this._root = root;\n this._slots = slots;\n this._duration = duration;\n this._loop = loop;\n this._rootRotSpeed = rootRotSpeed;\n this._trailMeshes = trailMeshes ?? [];\n this._trailMaterials = trailMaterials ?? [];\n this._trailConfig = trailConfig;\n this._trailBuf = Array.from({ length: this._trailMeshes.length }, () => new Vector3());\n this.reset();\n }\n\n /** The effect's root object: move, parent or inspect it like any other. */\n get object3D(): Object3D {\n return this._root;\n }\n\n spawn(pos: Vec3Like): void {\n this._alive = true;\n this._elapsed = 0;\n this._root.position.set(pos.x, pos.y, pos.z);\n // Start from the aim set via setRotation (spin, if any, is added on top\n // each frame in update()). At t=0 there's no spin yet, so this is the\n // base aim alone.\n this._applyRootRotation(0);\n this._root.visible = true;\n\n for (const slot of this._slots) slot.instance.spawn(pos);\n\n this._trailHead = 0;\n this._trailTimer = 0;\n for (const b of this._trailBuf) b.set(pos.x, pos.y, pos.z);\n for (let i = 0; i < this._trailMeshes.length; i++) {\n this._trailMaterials[i].opacity = 0;\n this._trailMeshes[i].position.set(pos.x, -999, pos.z);\n }\n\n // Run one tick at t=0 so every layer is in a defined state on the next\n // render frame.\n this._tickAllLayers(0, 0);\n }\n\n update(dt: number): boolean {\n if (!this._alive) return true;\n this._elapsed += dt;\n\n if (this._loop && this._elapsed >= this._duration && this._duration > 0) {\n this._elapsed %= this._duration;\n }\n\n const capped = (!this._loop && this._duration > 0)\n ? Math.min(this._elapsed, this._duration)\n : this._elapsed;\n\n if (this._rootRotSpeed) this._applyRootRotation(capped);\n\n this._updateTrail(dt);\n this._tickAllLayers(capped, dt);\n\n if (!this._loop && this._elapsed >= this._duration && this._duration > 0) {\n this._alive = false;\n return true;\n }\n return false;\n }\n\n reset(): void {\n this._alive = false;\n this._root.visible = false;\n // Clear the aim so a recycled pool slot doesn't inherit the previous\n // spawn's rotation when the next spawn omits `opts.rotation`.\n this._baseEuler[0] = this._baseEuler[1] = this._baseEuler[2] = 0;\n for (const slot of this._slots) slot.instance.reset();\n for (let i = 0; i < this._trailMeshes.length; i++) {\n this._trailMaterials[i].opacity = 0;\n this._trailMeshes[i].position.set(0, -999, 0);\n }\n }\n\n moveTo(pos: Vec3Like): void {\n this._root.position.set(pos.x, pos.y, pos.z);\n }\n\n setScale(s: number): void {\n this._scale = s;\n this._root.scale.set(s, s, s);\n }\n\n /** Aim the effect root: Euler in degrees. Stored as the base orientation;\n * `rootRotSpeed` spin (if any) is layered on top each frame. Call\n * before/at spawn - the next `_applyRootRotation` picks it up. */\n setRotation(xDeg: number, yDeg: number, zDeg: number): void {\n this._baseEuler[0] = xDeg;\n this._baseEuler[1] = yDeg;\n this._baseEuler[2] = zDeg;\n }\n\n /** Write the root's rotation as base aim + spin at `time` seconds. */\n private _applyRootRotation(time: number): void {\n const spin = this._rootRotSpeed;\n quatFromEulerDeg(\n this._baseEuler[0] + (spin ? spin[0] * time : 0),\n this._baseEuler[1] + (spin ? spin[1] * time : 0),\n this._baseEuler[2] + (spin ? spin[2] * time : 0),\n this._root.quaternion,\n );\n }\n\n /** Jump to an absolute time and evaluate all layers (for editor scrubbing). */\n seekTo(time: number): void {\n const dt = time - this._elapsed;\n this._elapsed = time;\n this._alive = true;\n this._root.visible = true;\n\n if (this._rootRotSpeed) this._applyRootRotation(time);\n\n this._tickAllLayers(time, Math.max(0, dt));\n if (dt > 0) this._updateTrail(dt);\n }\n\n get elapsed(): number { return this._elapsed; }\n get alive(): boolean { return this._alive; }\n\n /** Stop or resume particle layers (for editor pause). */\n setParticlesPaused(paused: boolean): void {\n for (const slot of this._slots) {\n if (isParticleLayerInstance(slot.instance)) {\n slot.instance.setPaused(paused);\n }\n }\n }\n\n dispose(): void {\n for (const slot of this._slots) slot.instance.dispose();\n this._root.removeFromParent();\n for (const mesh of this._trailMeshes) mesh.removeFromParent();\n for (const mat of this._trailMaterials) mat.dispose();\n }\n\n // \u2500\u2500 internal \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _tickAllLayers(elapsed: number, dt: number): void {\n for (const slot of this._slots) {\n const { layer, duration, instance } = slot;\n const localT = elapsed - layer.startDelay;\n const alive = layer.enabled\n && localT >= 0\n && (this._loop || duration <= 0 || localT <= duration);\n const ctx: VfxLayerUpdateContext = {\n t: localT,\n dt,\n elapsed,\n alive,\n layerDuration: duration,\n loop: this._loop,\n };\n instance.update(ctx);\n }\n }\n\n private _updateTrail(dt: number): void {\n const cfg = this._trailConfig;\n if (!cfg || this._trailMeshes.length === 0) return;\n\n this._trailTimer += dt;\n if (this._trailTimer >= cfg.sampleInterval) {\n this._trailTimer -= cfg.sampleInterval;\n this._trailBuf[this._trailHead].copy(this._root.position);\n this._trailHead = (this._trailHead + 1) % this._trailMeshes.length;\n }\n\n const count = this._trailMeshes.length;\n for (let i = 0; i < count; i++) {\n const bufIdx = (this._trailHead - 1 - i + count * 2) % count;\n const tp = this._trailBuf[bufIdx];\n const frac = (i + 1) / (count + 1);\n const alpha = Math.max(0, (1 - frac) * cfg.maxOpacity);\n const scale = Math.max(0.02, (1 - frac * cfg.shrinkFactor) * cfg.radius * this._scale);\n this._trailMeshes[i].position.copy(tp);\n this._trailMeshes[i].scale.set(scale, scale, scale);\n this._trailMaterials[i].opacity = alpha;\n }\n }\n}\n\n// \u2500\u2500 JsonVfxPrefab \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Compiles one {@link VfxEffectData} into instances, through a\n * {@link VfxLayerRegistry}. Usually built with {@link VfxStage.buildPrefab}.\n *\n * @group Effects\n */\nexport class JsonVfxPrefab implements IVfxPrefab {\n private readonly _data: VfxEffectData;\n private readonly _registry: VfxLayerRegistry;\n private readonly _resolveUrl: (path: string) => string;\n private readonly _renderOrder: number | undefined;\n private _count = 0;\n\n constructor(\n data: VfxEffectData,\n registry: VfxLayerRegistry,\n resolveUrl?: (path: string) => string,\n renderOrder?: number,\n ) {\n this._data = data;\n this._registry = registry;\n this._resolveUrl = resolveUrl ?? (p => p);\n this._renderOrder = renderOrder;\n }\n\n create(scene: Scene, parent: Object3D): JsonVfxInstance {\n const idx = this._count++;\n const root = new Group();\n root.name = `vfx_${this._data.name}_${idx}`;\n parent.add(root);\n\n const slots: LayerSlot[] = [];\n const buildCtx: VfxLayerBuildContext = {\n scene,\n parent: root,\n renderOrder: this._renderOrder,\n resolveUrl: this._resolveUrl,\n };\n\n for (const layer of this._data.layers) {\n const renderer = this._registry.get(layer.type);\n if (!renderer) {\n console.warn(`[VFX] no renderer registered for layer type '${layer.type}' in effect '${this._data.name}'`);\n continue;\n }\n // Disabled layers are still constructed so the editor can toggle them\n // without rebuilding the prefab; the renderer's `update` skips work\n // while `layer.enabled` is false.\n const instance = renderer.build(layer, buildCtx);\n const duration = layer.duration > 0 ? layer.duration : this._data.duration;\n slots.push({ layer, instance, duration });\n }\n\n // Optional position trail (puffs tracking the root, beside it under `parent`).\n let trailMeshes: Mesh[] | undefined;\n let trailMaterials: MeshBasicMaterial[] | undefined;\n const trailCfg = this._data.trail;\n if (trailCfg && trailCfg.count > 0) {\n trailMeshes = [];\n trailMaterials = [];\n for (let i = 0; i < trailCfg.count; i++) {\n const { mesh, mat } = buildVfxTrailMesh(\n parent,\n trailCfg.shape,\n trailCfg.color,\n trailCfg.emissiveIntensity ?? 1,\n trailCfg.blendMode,\n trailCfg.radius,\n `vfx_trail_${idx}_${i}`,\n );\n trailMeshes.push(mesh);\n trailMaterials.push(mat);\n }\n }\n\n if (this._renderOrder !== undefined) {\n const order = this._renderOrder;\n root.traverse((o) => { o.renderOrder = order; });\n for (const m of trailMeshes ?? []) m.renderOrder = order;\n }\n\n return new JsonVfxInstance(\n root,\n slots,\n this._data.duration,\n this._data.loop ?? false,\n this._data.rootRotationSpeed,\n trailMeshes,\n trailMaterials,\n trailCfg,\n );\n }\n}\n", "/**\n * Mesh layer - procedural primitives (sphere / ring / spike / quad) with\n * animated material params, optional fan-out instancing, and an animated\n * scale/opacity/color stack driven by keyframes + sin pulses.\n *\n * Unlit `MeshBasicMaterial`s, so the same objects draw under WebGLRenderer\n * and WebGPURenderer. The PlayCanvas build drew these with a\n * StandardMaterial whose only contribution was its emissive colour; that is\n * the basic material's colour here.\n */\n\nimport {\n BufferGeometry,\n Color,\n Float32BufferAttribute,\n Mesh,\n MeshBasicMaterial,\n Quaternion,\n Vector3,\n} from 'three';\nimport type { Object3D } from 'three';\n\nimport type { Vec3Like } from '../../../presets/camera/camera-preset';\nimport type {\n CurvePoint,\n ColorCurvePoint,\n VfxLayerBase,\n} from '../data-types';\nimport type {\n VfxLayerBuildContext,\n VfxLayerInstance,\n VfxLayerRenderer,\n VfxLayerUpdateContext,\n} from '../layer-renderer';\nimport {\n applyBlend,\n applyCull,\n lerpColorCurve,\n lerpCurve,\n quatFromEulerDeg,\n quatFromForward,\n setEmissive,\n} from './shared';\n\n// \u2500\u2500 Public data type \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** @group Effects */\nexport type MeshShape = 'sphere' | 'ring' | 'spike' | 'quad';\n\n/** @group Effects */\nexport type InstancePattern =\n | 'single'\n | 'uniform-sphere'\n | 'uniform-circle'\n | 'custom';\n\n/**\n * Fan one mesh layer out into several copies, each pointed along a direction.\n *\n * @group Effects\n */\nexport interface VfxMeshInstancing {\n pattern: InstancePattern;\n count: number;\n customDirections?: [number, number, number][];\n}\n\n/**\n * `1 + amplitude * sin(elapsed * frequency * 2\u03C0 + offset)`, multiplied in.\n *\n * @group Effects\n */\nexport interface VfxSinPulse {\n amplitude: number;\n frequency: number;\n offset?: number;\n}\n\n/**\n * A procedural mesh primitive with keyframed scale, opacity and colour.\n *\n * @group Effects\n */\nexport interface VfxMeshLayer extends VfxLayerBase {\n type: 'mesh';\n\n shape: MeshShape;\n\n radius?: number;\n innerRatio?: number;\n segments?: number;\n width?: number;\n length?: number;\n\n color: [number, number, number];\n emissiveIntensity: number;\n opacity: number;\n blendMode: 'additive' | 'alpha';\n depthTest: boolean;\n depthWrite: boolean;\n cullFace: boolean;\n\n positionOffset: [number, number, number];\n rotation: [number, number, number];\n scale: number;\n\n scaleKeys?: CurvePoint[];\n opacityKeys?: CurvePoint[];\n rotationSpeed?: [number, number, number];\n colorKeys?: ColorCurvePoint[];\n extensionKeys?: CurvePoint[];\n\n scalePulse?: VfxSinPulse;\n opacityPulse?: VfxSinPulse;\n\n instancing?: VfxMeshInstancing;\n}\n\n// \u2500\u2500 Mesh primitive builders \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction makeGeometry(positions: number[], normals: number[], indices: number[], uvs?: number[]): BufferGeometry {\n const geometry = new BufferGeometry();\n geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));\n geometry.setAttribute('normal', new Float32BufferAttribute(normals, 3));\n if (uvs) geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2));\n geometry.setIndex(indices);\n geometry.computeBoundingSphere();\n return geometry;\n}\n\n/**\n * Unit UV-sphere (radius 1).\n *\n * @group Effects\n */\nexport function buildVfxSphereMesh(lat = 10, lon = 14): BufferGeometry {\n const positions: number[] = [];\n const normals: number[] = [];\n const indices: number[] = [];\n\n for (let i = 0; i <= lat; i++) {\n const theta = (i / lat) * Math.PI;\n for (let j = 0; j <= lon; j++) {\n const phi = (j / lon) * Math.PI * 2;\n const nx = Math.sin(theta) * Math.cos(phi);\n const ny = Math.cos(theta);\n const nz = Math.sin(theta) * Math.sin(phi);\n positions.push(nx, ny, nz);\n normals.push(nx, ny, nz);\n }\n }\n for (let i = 0; i < lat; i++) {\n for (let j = 0; j < lon; j++) {\n const a = i * (lon + 1) + j;\n const b = a + lon + 1;\n indices.push(a, b, a + 1, b, b + 1, a + 1);\n }\n }\n return makeGeometry(positions, normals, indices);\n}\n\n/**\n * Flat annular ring in the XZ plane. Outer radius 1, inner = innerRatio.\n *\n * @group Effects\n */\nexport function buildVfxRingMesh(innerRatio = 0.62, segments = 20): BufferGeometry {\n const positions: number[] = [];\n const normals: number[] = [];\n const indices: number[] = [];\n\n for (let i = 0; i <= segments; i++) {\n const a = (i / segments) * Math.PI * 2;\n const cos = Math.cos(a);\n const sin = Math.sin(a);\n positions.push(cos, 0, sin);\n normals.push(0, 1, 0);\n positions.push(innerRatio * cos, 0, innerRatio * sin);\n normals.push(0, 1, 0);\n }\n\n for (let i = 0; i < segments; i++) {\n const o0 = i * 2;\n const o1 = o0 + 2;\n const i0 = o0 + 1;\n const i1 = o1 + 1;\n indices.push(o0, o1, i0);\n indices.push(o1, i1, i0);\n }\n return makeGeometry(positions, normals, indices);\n}\n\n/**\n * Diamond spike pointing along +Z in [0, 1].\n *\n * @group Effects\n */\nexport function buildVfxSpikeMesh(): BufferGeometry {\n const BZ = 0.18;\n const BR = 0.5;\n\n const positions = [\n 0, 0, 0,\n BR, 0, BZ,\n 0, BR, BZ,\n -BR, 0, BZ,\n 0, -BR, BZ,\n 0, 0, 1,\n ];\n\n const normals = [\n 0, 0, -1,\n 1, 0, 0,\n 0, 1, 0,\n -1, 0, 0,\n 0, -1, 0,\n 0, 0, 1,\n ];\n\n const indices = [\n 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 1, 4,\n 5, 1, 2, 5, 2, 3, 5, 3, 4, 5, 4, 1,\n ];\n return makeGeometry(positions, normals, indices);\n}\n\n/**\n * Unit billboard quad in the XY plane, centred at the origin, size 1x1, with UVs.\n *\n * @group Effects\n */\nexport function buildVfxQuadMesh(): BufferGeometry {\n const h = 0.5;\n const positions = [\n -h, -h, 0,\n h, -h, 0,\n h, h, 0,\n -h, h, 0,\n ];\n const normals = [\n 0, 0, 1,\n 0, 0, 1,\n 0, 0, 1,\n 0, 0, 1,\n ];\n const uvs = [0, 0, 1, 0, 1, 1, 0, 1];\n const indices = [0, 1, 2, 0, 2, 3];\n return makeGeometry(positions, normals, indices, uvs);\n}\n\n// \u2500\u2500 Shared geometry cache \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst _meshCache = new Map<string, BufferGeometry>();\n\n/**\n * One geometry per `shape + innerRatio + segments`, shared by every effect\n * that asks for it. Exported so consumers adding their own mesh-backed\n * renderers can share the same buffers. The cache owns these: do not\n * dispose them.\n *\n * @group Effects\n */\nexport function getVfxMesh(\n shape: MeshShape,\n opts: { innerRatio?: number; segments?: number } = {},\n): BufferGeometry {\n const key = `${shape}_${opts.innerRatio ?? 0.62}_${opts.segments ?? 12}`;\n let mesh = _meshCache.get(key);\n if (!mesh) {\n switch (shape) {\n case 'sphere': mesh = buildVfxSphereMesh(opts.segments ?? 10, opts.segments ?? 14); break;\n case 'ring': mesh = buildVfxRingMesh(opts.innerRatio ?? 0.62, opts.segments ?? 20); break;\n case 'spike': mesh = buildVfxSpikeMesh(); break;\n case 'quad': mesh = buildVfxQuadMesh(); break;\n default: mesh = buildVfxSphereMesh(); break;\n }\n _meshCache.set(key, mesh);\n }\n return mesh;\n}\n\n// \u2500\u2500 Direction generator for instancing fan-out \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction generateDirections(inst: VfxMeshInstancing | undefined): Vector3[] {\n if (!inst || inst.pattern === 'single') return [new Vector3(0, 0, 1)];\n\n const dirs: Vector3[] = [];\n const n = Math.max(1, inst.count);\n\n if (inst.pattern === 'uniform-circle') {\n for (let i = 0; i < n; i++) {\n const a = (i / n) * Math.PI * 2;\n dirs.push(new Vector3(Math.cos(a), Math.sin(a), 0));\n }\n return dirs;\n }\n\n if (inst.pattern === 'uniform-sphere') {\n const phi = Math.PI * (3 - Math.sqrt(5));\n for (let i = 0; i < n; i++) {\n const y = 1 - (i / Math.max(1, n - 1)) * 2;\n const r = Math.sqrt(1 - y * y);\n const th = phi * i;\n dirs.push(new Vector3(Math.cos(th) * r, y, Math.sin(th) * r));\n }\n return dirs;\n }\n\n if (inst.pattern === 'custom' && inst.customDirections) {\n for (const [x, y, z] of inst.customDirections) {\n dirs.push(new Vector3(x, y, z).normalize());\n }\n return dirs;\n }\n\n return [new Vector3(0, 0, 1)];\n}\n\n// \u2500\u2500 Instance + Renderer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst _spin = new Quaternion();\n// The PlayCanvas build spins by `rotationSpeed / 60` per update, whatever the\n// frame time; its effects were tuned to that.\nconst SPIN_STEP = 1 / 60;\n\nclass MeshLayerInstance implements VfxLayerInstance {\n private readonly _layer: VfxMeshLayer;\n private readonly _meshes: Mesh[];\n private readonly _materials: MeshBasicMaterial[];\n private readonly _baseColor: { r: number; g: number; b: number };\n private readonly _rgb: number[] = [0, 0, 0];\n\n constructor(layer: VfxMeshLayer, meshes: Mesh[], materials: MeshBasicMaterial[]) {\n this._layer = layer;\n this._meshes = meshes;\n this._materials = materials;\n this._baseColor = { r: layer.color[0], g: layer.color[1], b: layer.color[2] };\n }\n\n spawn(_pos: Vec3Like): void {\n // Visibility is driven by `update`; the prefab calls update(t=0) on spawn.\n }\n\n update(ctx: VfxLayerUpdateContext): void {\n const layer = this._layer;\n if (!layer.enabled || !ctx.alive) {\n for (const m of this._meshes) m.visible = false;\n return;\n }\n\n const nt = ctx.layerDuration > 0 ? (ctx.t / ctx.layerDuration) : 0;\n\n let s = (layer.scale ?? 1) * lerpCurve(layer.scaleKeys ?? [[0, 1]], nt);\n let o = lerpCurve(layer.opacityKeys ?? [[0, layer.opacity]], nt);\n const ext = lerpCurve(layer.extensionKeys ?? [[0, 1]], nt);\n\n if (layer.scalePulse) {\n const p = layer.scalePulse;\n s *= 1 + p.amplitude * Math.sin(ctx.elapsed * p.frequency * Math.PI * 2 + (p.offset ?? 0));\n }\n if (layer.opacityPulse) {\n const p = layer.opacityPulse;\n o *= 1 + p.amplitude * Math.sin(ctx.elapsed * p.frequency * Math.PI * 2 + (p.offset ?? 0));\n }\n\n const rotSpeed = layer.rotationSpeed;\n const spinning = !!rotSpeed && (rotSpeed[0] !== 0 || rotSpeed[1] !== 0 || rotSpeed[2] !== 0);\n if (spinning) quatFromEulerDeg(rotSpeed[0] * SPIN_STEP, rotSpeed[1] * SPIN_STEP, rotSpeed[2] * SPIN_STEP, _spin);\n\n if (layer.colorKeys && layer.colorKeys.length > 0) {\n lerpColorCurve(layer.colorKeys, nt, this._baseColor);\n this._rgb[0] = this._baseColor.r;\n this._rgb[1] = this._baseColor.g;\n this._rgb[2] = this._baseColor.b;\n }\n\n for (let i = 0; i < this._meshes.length; i++) {\n const mesh = this._meshes[i];\n const mat = this._materials[i];\n mesh.visible = true;\n\n if (layer.shape === 'spike') {\n const len = (layer.length ?? 0.55) * ext;\n const w = (layer.width ?? 0.038) * s;\n mesh.scale.set(w, w, len);\n } else if (layer.shape === 'ring') {\n const r = (layer.radius ?? 0.3) * s;\n mesh.scale.set(r, r, r);\n } else {\n const r = (layer.radius ?? 0.2) * s;\n mesh.scale.set(r, r, r);\n }\n\n if (spinning) mesh.quaternion.multiply(_spin);\n\n if (layer.colorKeys && layer.colorKeys.length > 0) {\n setEmissive(mat.color, this._rgb, layer.emissiveIntensity ?? 1);\n }\n\n mat.opacity = o;\n }\n }\n\n reset(): void {\n for (const m of this._meshes) m.visible = false;\n for (const m of this._materials) m.opacity = 0;\n }\n\n dispose(): void {\n // The meshes leave with the prefab's root; the geometry is the cache's.\n for (const m of this._materials) m.dispose();\n }\n}\n\n/**\n * Renders `mesh` layers.\n *\n * @group Effects\n */\nexport class MeshLayerRenderer implements VfxLayerRenderer<VfxMeshLayer> {\n readonly type = 'mesh';\n\n build(layer: VfxMeshLayer, ctx: VfxLayerBuildContext): VfxLayerInstance {\n const geometry = getVfxMesh(layer.shape, {\n innerRatio: layer.innerRatio,\n segments: layer.segments,\n });\n const dirs = generateDirections(layer.instancing);\n const meshes: Mesh[] = [];\n const materials: MeshBasicMaterial[] = [];\n\n for (let d = 0; d < dirs.length; d++) {\n const mat = makeMeshMaterial(layer);\n const mesh = new Mesh(geometry, mat);\n mesh.name = `vfx_mesh_${layer.id}_${d}`;\n\n if (layer.instancing && layer.instancing.pattern !== 'single') {\n quatFromForward(dirs[d], mesh.quaternion);\n } else {\n const [rx, ry, rz] = layer.rotation ?? [0, 0, 0];\n quatFromEulerDeg(rx, ry, rz, mesh.quaternion);\n }\n\n const [px, py, pz] = layer.positionOffset ?? [0, 0, 0];\n mesh.position.set(px, py, pz);\n\n ctx.parent.add(mesh);\n meshes.push(mesh);\n materials.push(mat);\n }\n\n return new MeshLayerInstance(layer, meshes, materials);\n }\n}\n\nfunction makeMeshMaterial(layer: VfxMeshLayer): MeshBasicMaterial {\n const mat = new MeshBasicMaterial({\n color: setEmissive(new Color(), layer.color, layer.emissiveIntensity ?? 1),\n depthTest: layer.depthTest ?? false,\n depthWrite: layer.depthWrite ?? false,\n opacity: layer.opacity ?? 0.8,\n });\n applyBlend(mat, layer.blendMode === 'additive');\n applyCull(mat, !!layer.cullFace);\n return mat;\n}\n\n// \u2500\u2500 Internal: trail support exposed to JsonVfxInstance \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Build a single trail \"puff\" (one mesh primitive + material). The trail is\n * owned by `JsonVfxInstance`, not a layer renderer, but uses the same mesh\n * cache + material construction as the mesh layer renderer.\n */\nexport function buildVfxTrailMesh(\n parent: Object3D,\n shape: MeshShape,\n color: [number, number, number],\n emissiveIntensity: number,\n blendMode: 'additive' | 'alpha',\n radius: number,\n name: string,\n): { mesh: Mesh; mat: MeshBasicMaterial } {\n const geometry = getVfxMesh(shape, { innerRatio: 0.62, segments: 10 });\n const mat = new MeshBasicMaterial({\n color: setEmissive(new Color(), color, emissiveIntensity),\n depthTest: false,\n depthWrite: false,\n opacity: 0,\n });\n applyBlend(mat, blendMode === 'additive');\n applyCull(mat, false);\n\n const mesh = new Mesh(geometry, mat);\n mesh.name = name;\n mesh.scale.setScalar(radius);\n parent.add(mesh);\n return { mesh, mat };\n}\n", "/**\n * Shared helpers used by layer renderers - curve evaluation, Euler and\n * blending conventions. Both the engine's own renderers and consumer\n * renderers (via the public `VfxLayerRenderer` surface) can use these.\n */\n\nimport {\n AddEquation,\n Color,\n CustomBlending,\n DoubleSide,\n Euler,\n FrontSide,\n Matrix4,\n NormalBlending,\n OneFactor,\n Quaternion,\n SRGBColorSpace,\n Vector3,\n} from 'three';\nimport type { Material } from 'three';\n\nimport type { CurvePoint, ColorCurvePoint } from '../data-types';\n\nexport function lerpCurve(keys: CurvePoint[] | undefined, t: number): number {\n if (!keys || keys.length === 0) return 1;\n if (keys.length === 1) return keys[0][1];\n if (t <= keys[0][0]) return keys[0][1];\n if (t >= keys[keys.length - 1][0]) return keys[keys.length - 1][1];\n\n for (let i = 0; i < keys.length - 1; i++) {\n const [t0, v0] = keys[i];\n const [t1, v1] = keys[i + 1];\n if (t >= t0 && t <= t1) {\n const f = (t - t0) / (t1 - t0);\n return v0 + (v1 - v0) * f;\n }\n }\n return keys[keys.length - 1][1];\n}\n\n/** Writes the curve's RGB at `t` into `out`; leaves it untouched for an empty curve. */\nexport function lerpColorCurve(\n keys: ColorCurvePoint[] | undefined,\n t: number,\n out: { r: number; g: number; b: number },\n): void {\n if (!keys || keys.length === 0) return;\n const set = (r: number, g: number, b: number) => { out.r = r; out.g = g; out.b = b; };\n if (keys.length === 1) { set(keys[0][1], keys[0][2], keys[0][3]); return; }\n if (t <= keys[0][0]) { set(keys[0][1], keys[0][2], keys[0][3]); return; }\n const last = keys[keys.length - 1];\n if (t >= last[0]) { set(last[1], last[2], last[3]); return; }\n\n for (let i = 0; i < keys.length - 1; i++) {\n const a = keys[i];\n const b = keys[i + 1];\n if (t >= a[0] && t <= b[0]) {\n const f = (t - a[0]) / (b[0] - a[0]);\n set(\n a[1] + (b[1] - a[1]) * f,\n a[2] + (b[2] - a[2]) * f,\n a[3] + (b[3] - a[3]) * f,\n );\n return;\n }\n }\n}\n\nconst _euler = new Euler();\nconst DEG = Math.PI / 180;\n\n/**\n * Euler angles in degrees, in the PlayCanvas build's convention (the one its\n * effect data was authored against): three.js order 'ZYX' reproduces it.\n */\nexport function quatFromEulerDeg(xDeg: number, yDeg: number, zDeg: number, out: Quaternion): Quaternion {\n return out.setFromEuler(_euler.set(xDeg * DEG, yDeg * DEG, zDeg * DEG, 'ZYX'));\n}\n\nconst _right = new Vector3();\nconst _up = new Vector3();\nconst _dir = new Vector3();\nconst _basis = new Matrix4();\n\n/** Rotation whose +Z axis points along `dir`, its up as close to world +Y as it can be. */\nexport function quatFromForward(dir: Vector3, out: Quaternion = new Quaternion()): Quaternion {\n const d = _dir.copy(dir).normalize();\n if (Math.abs(d.y) < 0.99) _up.set(0, 1, 0);\n else _up.set(1, 0, 0);\n _right.crossVectors(_up, d).normalize();\n _up.crossVectors(d, _right).normalize();\n return out.setFromRotationMatrix(_basis.makeBasis(_right, _up, d));\n}\n\n/**\n * Emissive colour as the PlayCanvas build's StandardMaterial treats it:\n * authored in sRGB and scaled by the intensity, so `[1, 0.5, 0] x 2` draws\n * as the clamped sRGB value `[1, 1, 0]`.\n */\nexport function setEmissive(out: Color, rgb: readonly number[], intensity: number): Color {\n return out.setRGB(rgb[0] * intensity, rgb[1] * intensity, rgb[2] * intensity, SRGBColorSpace);\n}\n\n/**\n * The PlayCanvas build's blend modes. Its additive is `ONE, ONE`: alpha\n * (and so `opacity`) does not dim an additive layer, only its colour does.\n * That is how the effect data was tuned, so it is kept.\n */\nexport function applyBlend(material: Material, additive: boolean): void {\n material.transparent = true;\n if (additive) {\n material.blending = CustomBlending;\n material.blendEquation = AddEquation;\n material.blendSrc = OneFactor;\n material.blendDst = OneFactor;\n } else {\n material.blending = NormalBlending;\n }\n}\n\n/**\n * Face culling as the layer data states it. Double-sided transparent\n * materials draw in one pass, as PlayCanvas does, rather than three.js's\n * back-then-front two.\n */\nexport function applyCull(material: Material, cullBack: boolean): void {\n material.side = cullBack ? FrontSide : DoubleSide;\n material.forceSinglePass = true;\n}", "/**\n * Particle layer - billboard particles with the PlayCanvas build's JSON\n * schema and its particle system's behaviour.\n *\n * The PlayCanvas build handed these layers to PlayCanvas's own\n * `ParticleSystemComponent`, so the effect data was tuned against that\n * emitter: its spawn timing (`rate` is seconds between spawns), its\n * smoothstep-interpolated graphs sampled at 32 points, its default soft-dot\n * texture and its blending. This file reproduces that emitter on the CPU -\n * the numbers below follow its GPU path, which is the one that ran on WebGL2\n * and WebGPU - and draws the result as one unlit mesh of camera-facing quads,\n * so the same code renders under both three.js renderers.\n *\n * Not reproduced: `depthSoftening` (needs a scene depth texture), and\n * `gravity`, which the PlayCanvas emitter never read either.\n */\n\nimport {\n AddEquation,\n BufferAttribute,\n BufferGeometry,\n ClampToEdgeWrapping,\n CustomBlending,\n DataTexture,\n DoubleSide,\n DynamicDrawUsage,\n LinearFilter,\n Matrix3,\n Matrix4,\n Mesh,\n MeshBasicMaterial,\n NormalBlending,\n Object3D,\n OneFactor,\n Quaternion,\n SrcAlphaFactor,\n SRGBColorSpace,\n Color,\n Vector3,\n} from 'three';\n\nimport type { Vec3Like } from '../../../presets/camera/camera-preset';\nimport type { Scene } from '../../../scene';\nimport type {\n CurvePoint,\n ColorCurvePoint,\n VfxLayerBase,\n} from '../data-types';\nimport type {\n VfxLayerBuildContext,\n VfxLayerInstance,\n VfxLayerRenderer,\n VfxLayerUpdateContext,\n} from '../layer-renderer';\n\n/**\n * Particle emitter settings, named as PlayCanvas's particle system names them.\n *\n * @group Effects\n */\nexport interface VfxParticleLayer extends VfxLayerBase {\n type: 'particle';\n\n numParticles: number;\n lifetime: number;\n /** Seconds between spawns (a random pick between `rate` and `rate2` per particle). */\n rate: number;\n rate2?: number;\n\n emitterShape: 'box' | 'sphere';\n emitterRadius?: number;\n emitterExtents?: [number, number, number];\n\n localVelocity?: [number, number, number];\n localVelocity2?: [number, number, number];\n velocity?: [number, number, number];\n velocity2?: [number, number, number];\n\n initialVelocity?: number;\n /** Not applied: PlayCanvas's particle system has no gravity, so effect data never relied on it. */\n gravity?: [number, number, number];\n\n startAngle?: number;\n startAngle2?: number;\n\n scaleGraph?: CurvePoint[];\n colorGraph?: ColorCurvePoint[];\n alphaGraph?: CurvePoint[];\n rotationSpeedGraph?: CurvePoint[];\n radialSpeedGraph?: CurvePoint[];\n radialSpeedGraph2?: CurvePoint[];\n\n blendType: 'additive' | 'alpha';\n depthWrite: boolean;\n /** Not applied: soft particles need a scene depth texture. */\n depthSoftening?: number;\n\n loop: boolean;\n preWarm: boolean;\n\n stretch?: number;\n alignToMotion?: boolean;\n localSpace?: boolean;\n positionOffset?: [number, number, number];\n}\n\n// \u2500\u2500 PlayCanvas curve semantics \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ntype Keys = ReadonlyArray<readonly [number, number]>;\n\n/** Graph resolution PlayCanvas bakes every particle curve to. */\nconst PRECISION = 32;\nconst FIXED_STEP = 1 / 60;\nconst MAX_SUB_STEPS = 10;\n\n/** A PlayCanvas `Curve` (default type: smoothstep between keys) at `time`. */\nfunction evalCurve(keys: Keys, time: number): number {\n const n = keys.length;\n if (n === 0) return 0;\n if (time < keys[0][0]) return keys[0][1];\n if (time >= keys[n - 1][0]) return keys[n - 1][1];\n let i = 0;\n while (time >= keys[i + 1][0]) i++;\n const span = keys[i + 1][0] - keys[i][0];\n const t = span > 0 ? (time - keys[i][0]) / span : 0;\n return keys[i][1] + (keys[i + 1][1] - keys[i][1]) * (t * t * (3 - 2 * t));\n}\n\nfunction quantize(keys: Keys): Float32Array {\n const out = new Float32Array(PRECISION);\n for (let i = 0; i < PRECISION; i++) out[i] = evalCurve(keys, i / (PRECISION - 1));\n return out;\n}\n\n/** Sorted keys, as `Curve.add` keeps them. */\nfunction sortedKeys(points: readonly CurvePoint[]): Keys {\n return [...points].sort((a, b) => a[0] - b[0]).map(([t, v]) => [t, v] as const);\n}\n\nconst constant = (v: number): Keys => [[0, v]];\n\n/**\n * Index and weight for the graph textures, which PlayCanvas samples with\n * nearest filtering at `life` and `life + 1/32` and blends by the fraction.\n */\nfunction nearestPair(nlife: number): [number, number, number] {\n const x = nlife * PRECISION;\n const i0 = Math.min(Math.floor(x), PRECISION - 1);\n return [i0, Math.min(i0 + 1, PRECISION - 1), x - Math.floor(x)];\n}\n\n// \u2500\u2500 Default particle texture \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst _dotTextures = new Map<number, DataTexture>();\n\n/**\n * PlayCanvas's built-in particle texture: a 16x16 white dot whose alpha falls\n * off from ~0.46, raised to `alphaPower` (see `ParticleLayerInstance`).\n */\nfunction dotTexture(alphaPower: number): DataTexture {\n const cached = _dotTextures.get(alphaPower);\n if (cached) return cached;\n const res = 16;\n const center = res * 0.5 + 0.5;\n const data = new Uint8Array(res * res * 4);\n const sat = (x: number) => Math.max(0, Math.min(1, x));\n for (let y = 0; y < res; y++) {\n for (let x = 0; x < res; x++) {\n const gx = x + 1 - center;\n const gy = y + 1 - center;\n const c = sat(1 - sat(Math.sqrt(gx * gx + gy * gy) / res) - 0.5);\n const p = (y * res + x) * 4;\n data[p] = data[p + 1] = data[p + 2] = 255;\n data[p + 3] = Math.round(Math.pow(Math.floor(c * 255) / 255, alphaPower) * 255);\n }\n }\n const tex = new DataTexture(data, res, res);\n tex.minFilter = LinearFilter;\n tex.magFilter = LinearFilter;\n tex.wrapS = ClampToEdgeWrapping;\n tex.wrapT = ClampToEdgeWrapping;\n tex.needsUpdate = true;\n _dotTextures.set(alphaPower, tex);\n return tex;\n}\n\n// \u2500\u2500 Emitter \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface Graphs {\n scale: Float32Array;\n rotSpeed: Float32Array;\n rotSpeed2: Float32Array;\n localVel: Float32Array[];\n localVel2: Float32Array[];\n vel: Float32Array[];\n vel2: Float32Array[];\n radial: Float32Array;\n radial2: Float32Array;\n /** Colour ramp, linear RGB: PlayCanvas stores it in an 8-bit sRGB texture that decodes on sampling. */\n color: Float32Array;\n /** Alpha ramp, 8-bit. */\n alpha: Float32Array;\n}\n\nconst _col = new Color();\n\nfunction buildGraphs(layer: VfxParticleLayer): Graphs {\n const vec = (v: [number, number, number] | undefined): Float32Array[] =>\n [0, 1, 2].map((c) => quantize(constant(v ? v[c] : 0)));\n const radial = layer.radialSpeedGraph?.length ? sortedKeys(layer.radialSpeedGraph) : constant(0);\n const radial2 = layer.radialSpeedGraph2?.length ? sortedKeys(layer.radialSpeedGraph2) : radial;\n const rot = layer.rotationSpeedGraph?.length ? quantize(sortedKeys(layer.rotationSpeedGraph)) : quantize(constant(0));\n for (let i = 0; i < PRECISION; i++) rot[i] *= Math.PI / 180;\n\n const colorKeys = layer.colorGraph?.length\n ? [1, 2, 3].map((c) => sortedKeys(layer.colorGraph!.map((p) => [p[0], p[c]] as CurvePoint)))\n : [constant(1), constant(1), constant(1)];\n const rgb = colorKeys.map(quantize);\n const alpha = quantize(layer.alphaGraph?.length ? sortedKeys(layer.alphaGraph) : constant(1));\n const to8 = (v: number) => Math.floor(Math.max(0, Math.min(1, v)) * 255) / 255;\n const color = new Float32Array(PRECISION * 3);\n for (let i = 0; i < PRECISION; i++) {\n _col.setRGB(to8(rgb[0][i]), to8(rgb[1][i]), to8(rgb[2][i]), SRGBColorSpace);\n color[i * 3] = _col.r;\n color[i * 3 + 1] = _col.g;\n color[i * 3 + 2] = _col.b;\n alpha[i] = to8(alpha[i]);\n }\n\n return {\n scale: quantize(layer.scaleGraph?.length ? sortedKeys(layer.scaleGraph) : [[0, 0.1], [1, 0.1]]),\n rotSpeed: rot,\n rotSpeed2: rot,\n localVel: vec(layer.localVelocity),\n localVel2: vec(layer.localVelocity2 ?? layer.localVelocity),\n vel: vec(layer.velocity),\n vel2: vec(layer.velocity2 ?? layer.velocity),\n radial: quantize(radial),\n radial2: quantize(radial2),\n color,\n alpha,\n };\n}\n\nconst _m3 = new Matrix3();\nconst _m3Inv = new Matrix3();\nconst _v = new Vector3();\nconst _w = new Vector3();\nconst _emitterPos = new Vector3();\nconst _emitterRot = new Quaternion();\nconst _nodeScale = new Vector3();\nconst _right = new Vector3();\nconst _up = new Vector3();\nconst _view = new Matrix4();\n\n/**\n * One PlayCanvas `ParticleEmitter`, simulated on the CPU. Per particle it\n * keeps what PlayCanvas keeps in its particle state texture: position,\n * velocity, angle, life and a visible flag, plus the four random factors its\n * shader hashes from the particle index and a per-reset seed.\n */\nclass ParticleEmitter {\n readonly numParticles: number;\n private readonly _layer: VfxParticleLayer;\n private readonly _g: Graphs;\n private readonly _lifetime: number;\n private readonly _rate: number;\n private readonly _rate2: number;\n private readonly _box: boolean;\n private readonly _radius: number;\n private readonly _extents: [number, number, number];\n private readonly _initialVelocity: number;\n private readonly _startAngle: number;\n private readonly _startAngle2: number;\n private readonly _localSpace: boolean;\n\n readonly pos: Float32Array;\n readonly vel: Float32Array;\n readonly angle: Float32Array;\n readonly life: Float32Array;\n readonly show: Uint8Array;\n private readonly _rnd: Float32Array;\n /** Each particle's first spawn time (negative), fixed when the emitter is built. */\n private readonly _startLife: Float32Array;\n\n /** False once a non-looping emitter has run its course. */\n visible = true;\n private _loop = false;\n private _simTime = 0;\n private _simTimeTotal = 0;\n private _endTime = 0;\n\n constructor(layer: VfxParticleLayer) {\n this._layer = layer;\n this._g = buildGraphs(layer);\n const n = this.numParticles = Math.max(1, layer.numParticles ?? 30);\n this._lifetime = layer.lifetime ?? 1;\n this._rate = layer.rate ?? 10;\n this._rate2 = layer.rate2 ?? layer.rate ?? 10;\n this._box = layer.emitterShape === 'box';\n this._radius = layer.emitterRadius ?? 0.1;\n this._extents = layer.emitterExtents ?? [0.1, 0.1, 0.1];\n this._initialVelocity = layer.initialVelocity ?? 0;\n this._startAngle = (layer.startAngle ?? 0) * Math.PI / 180;\n this._startAngle2 = (layer.startAngle2 ?? 0) * Math.PI / 180;\n this._localSpace = layer.localSpace ?? false;\n\n this.pos = new Float32Array(n * 3);\n this.vel = new Float32Array(n * 3);\n this.angle = new Float32Array(n);\n this.life = new Float32Array(n);\n this.show = new Uint8Array(n);\n this._rnd = new Float32Array(n * 4);\n this._startLife = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n this._startLife[i] = -(this._rate + (this._rate2 - this._rate) * Math.random()) * i;\n }\n }\n\n get lifetime(): number { return this._lifetime; }\n get localSpace(): boolean { return this._localSpace; }\n\n /** `ParticleSystemComponent.reset`: back to the first spawn, with fresh random factors. */\n reset(node: Object3D): void {\n for (let i = 0; i < this._rnd.length; i++) this._rnd[i] = Math.random();\n this.life.set(this._startLife);\n this.show.fill(1);\n this._simTimeTotal = 0;\n this._simTime = 0;\n this._resetTime();\n const loop = this._loop;\n this._loop = true;\n this._addTime(node, 0, false);\n this._loop = loop;\n if (this._layer.preWarm) {\n const iterations = PRECISION;\n for (let i = 0; i < iterations; i++) this._addTime(node, this._lifetime / iterations, false);\n }\n }\n\n /** `ParticleSystemComponent.play`. */\n play(): void {\n this.visible = true;\n this._loop = this._layer.loop ?? false;\n this._resetTime();\n }\n\n /** `ParticleSystemComponent.stop`: no more spawns; live particles run out. */\n stop(node: Object3D): void {\n this._loop = false;\n this._endTime = this._simTimeTotal + this._lifetime;\n this._addTime(node, 0, true);\n }\n\n /** The component system's per-frame step: fixed 1/60 s substeps, at most ten. */\n step(node: Object3D, dt: number): void {\n this._simTime += dt;\n if (this._simTime < FIXED_STEP) return;\n let steps = Math.floor(this._simTime / FIXED_STEP);\n this._simTime -= steps * FIXED_STEP;\n steps = Math.min(steps, MAX_SUB_STEPS);\n for (let i = 0; i < steps; i++) this._addTime(node, FIXED_STEP, false);\n }\n\n private _resetTime(duration = Math.max(this._rate, this._rate2) * this.numParticles + this._lifetime): void {\n this._endTime = this._simTimeTotal + duration;\n }\n\n private _addTime(node: Object3D, delta: number, onStop: boolean): void {\n this._simTimeTotal += delta;\n node.updateWorldMatrix(true, false);\n const m = node.matrixWorld;\n const e = m.elements;\n if (this._localSpace) _emitterPos.set(0, 0, 0);\n else _emitterPos.set(e[12], e[13], e[14]);\n _m3.setFromMatrix4(m);\n if (this._localSpace) _m3Inv.copy(_m3).invert();\n if (this._box) m.decompose(_w, _emitterRot, _v);\n const es = node.scale;\n _nodeScale.copy(es);\n\n const g = this._g;\n const lifetime = this._lifetime;\n const n = this.numParticles;\n const iv = this._initialVelocity;\n const rate = this._rate;\n const rateDiv = this._rate2 - this._rate;\n\n for (let i = 0; i < n; i++) {\n const rx = this._rnd[i * 4];\n const ry = this._rnd[i * 4 + 1];\n const rz = this._rnd[i * 4 + 2];\n const particleRate = rate + rateDiv * rx;\n const inLife = this.life[i];\n let outLife = inLife + delta;\n const nlife = Math.min(1, Math.max(0, outLife / lifetime));\n const [a, b, c] = nearestPair(nlife);\n const lerp = (q: Float32Array) => q[a] + (q[b] - q[a]) * c;\n\n // Respawn: unborn particles follow the emitter until their turn comes.\n const p = i * 3;\n if (inLife <= 0 || outLife >= lifetime) {\n this._spawnPosition(rx, ry, rz, _v);\n this.pos[p] = _v.x; this.pos[p + 1] = _v.y; this.pos[p + 2] = _v.z;\n this.angle[i] = this._startAngle + (this._startAngle2 - this._startAngle) * rx;\n }\n const px = this.pos[p], py = this.pos[p + 1], pz = this.pos[p + 2];\n\n // Radial speed, and PlayCanvas's spread between its two radial graphs,\n // which it adds per axis rather than along the radius.\n const radial = lerp(g.radial);\n const radialDiv = lerp(g.radial2) - radial;\n let rvx = px - _emitterPos.x, rvy = py - _emitterPos.y, rvz = pz - _emitterPos.z;\n const rl = rvx * rvx + rvy * rvy + rvz * rvz;\n if (rl > 1e-8) {\n const k = radial / Math.sqrt(rl);\n rvx *= k; rvy *= k; rvz *= k;\n } else {\n rvx = rvy = rvz = 0;\n }\n rvx += radialDiv * rx; rvy += radialDiv * ry; rvz += radialDiv * rz;\n\n let lvx = lerp(g.localVel[0]), lvy = lerp(g.localVel[1]), lvz = lerp(g.localVel[2]);\n lvx += (lerp(g.localVel2[0]) - lvx) * rx;\n lvy += (lerp(g.localVel2[1]) - lvy) * ry;\n lvz += (lerp(g.localVel2[2]) - lvz) * rz;\n let vx = lerp(g.vel[0]), vy = lerp(g.vel[1]), vz = lerp(g.vel[2]);\n vx += (lerp(g.vel2[0]) - vx) * rx;\n vy += (lerp(g.vel2[1]) - vy) * ry;\n vz += (lerp(g.vel2[2]) - vz) * rz;\n const rot = lerp(g.rotSpeed);\n const rotSpeed = rot + (lerp(g.rotSpeed2) - rot) * ry;\n\n if (this._box) {\n lvz -= iv;\n } else if (iv !== 0) {\n _w.set(rx - 0.5, ry - 0.5, rz - 0.5).normalize();\n lvx += _w.x * iv; lvy += _w.y * iv; lvz += _w.z * iv;\n }\n\n if (!this._localSpace) {\n _v.set(lvx, lvy, lvz).applyMatrix3(_m3);\n _v.x += (rvx + vx) * es.x;\n _v.y += (rvy + vy) * es.y;\n _v.z += (rvz + vz) * es.z;\n } else {\n _w.set(vx, vy, vz).applyMatrix3(_m3Inv);\n _v.set((lvx + rvx) / es.x + _w.x, (lvy + rvy) / es.y + _w.y, (lvz + rvz) / es.z + _w.z);\n }\n this.vel[p] = _v.x; this.vel[p + 1] = _v.y; this.vel[p + 2] = _v.z;\n this.pos[p] = px + _v.x * delta;\n this.pos[p + 1] = py + _v.y * delta;\n this.pos[p + 2] = pz + _v.z * delta;\n this.angle[i] += rotSpeed * delta;\n\n let show = this.show[i] === 1;\n if (onStop) {\n if (outLife < 0) show = false;\n } else if (outLife >= lifetime) {\n outLife -= Math.max(lifetime, n * particleRate);\n show = this._loop;\n } else if (this._loop && outLife < 0) {\n show = true;\n }\n this.show[i] = show ? 1 : 0;\n this.life[i] = outLife;\n }\n\n if (!this._loop && this._simTimeTotal > this._endTime) this.visible = false;\n }\n\n private _spawnPosition(rx: number, ry: number, rz: number, out: Vector3): void {\n if (this._box) {\n // PlayCanvas's box spawn: the largest component keeps its value, the\n // others are doubled and scaled by it.\n out.set(rx - 0.5, ry - 0.5, rz - 0.5);\n const ax = Math.abs(out.x), ay = Math.abs(out.y), az = Math.abs(out.z);\n const max = Math.max(ax, ay, az);\n out.set(\n max * (max === ax ? Math.sign(out.x) : 2 * out.x),\n max * (max === ay ? Math.sign(out.y) : 2 * out.y),\n max * (max === az ? Math.sign(out.z) : 2 * out.z),\n );\n // Box extents follow the emitter's world rotation and its own scale.\n out.set(\n out.x * this._extents[0] * _nodeScale.x,\n out.y * this._extents[1] * _nodeScale.y,\n out.z * this._extents[2] * _nodeScale.z,\n ).applyQuaternion(_emitterRot);\n } else {\n // Radius from a different digit of the same random factor, as PlayCanvas hashes it.\n const r = (rx * 1000) % 1;\n out.set(rx - 0.5, ry - 0.5, rz - 0.5).normalize().multiplyScalar(r * this._radius);\n }\n if (!this._localSpace) out.add(_emitterPos);\n }\n\n /**\n * Write four camera-facing corners per particle into the mesh buffers, as\n * PlayCanvas's particle vertex shader places them.\n */\n writeVertices(\n node: Object3D,\n camera: { matrixWorld: Matrix4 },\n position: Float32Array,\n color: Float32Array,\n alphaPower: number,\n ): void {\n const g = this._g;\n const lifetime = this._lifetime;\n const ce = camera.matrixWorld.elements;\n _right.set(ce[0], ce[1], ce[2]).normalize();\n _up.set(ce[4], ce[5], ce[6]).normalize();\n _view.copy(camera.matrixWorld).invert();\n const ve = _view.elements;\n const stretch = this._layer.stretch ?? 0;\n const align = this._layer.alignToMotion ?? false;\n const me = node.matrixWorld.elements;\n const es = node.scale;\n\n for (let i = 0; i < this.numParticles; i++) {\n const life = this.life[i];\n const p = i * 3;\n let px = this.pos[p], py = this.pos[p + 1], pz = this.pos[p + 2];\n let vx = this.vel[p], vy = this.vel[p + 1], vz = this.vel[p + 2];\n if (this._localSpace) {\n const wx = me[0] * px + me[4] * py + me[8] * pz + me[12];\n const wy = me[1] * px + me[5] * py + me[9] * pz + me[13];\n const wz = me[2] * px + me[6] * py + me[10] * pz + me[14];\n px = wx; py = wy; pz = wz;\n const ux = me[0] * vx + me[4] * vy + me[8] * vz;\n const uy = me[1] * vx + me[5] * vy + me[9] * vz;\n const uz = me[2] * vx + me[6] * vy + me[10] * vz;\n vx = ux; vy = uy; vz = uz;\n }\n const visible = life > 0 && life <= lifetime && this.show[i] === 1;\n const nlife = Math.min(1, Math.max(0, life / lifetime));\n const [a, b, c] = nearestPair(nlife);\n const scale = visible ? g.scale[a] + (g.scale[b] - g.scale[a]) * c : 0;\n\n // The colour ramp is linearly filtered (texel centres at (i + 0.5) / 32).\n const x = Math.min(PRECISION - 1, Math.max(0, nlife * PRECISION - 0.5));\n const i0 = Math.floor(x);\n const i1 = Math.min(i0 + 1, PRECISION - 1);\n const f = x - i0;\n const cr = g.color[i0 * 3] + (g.color[i1 * 3] - g.color[i0 * 3]) * f;\n const cg = g.color[i0 * 3 + 1] + (g.color[i1 * 3 + 1] - g.color[i0 * 3 + 1]) * f;\n const cb = g.color[i0 * 3 + 2] + (g.color[i1 * 3 + 2] - g.color[i0 * 3 + 2]) * f;\n const ca = g.alpha[i0] + (g.alpha[i1] - g.alpha[i0]) * f;\n\n // Velocity direction on screen, for stretch and align-to-motion.\n let svx = ve[0] * vx + ve[4] * vy + ve[8] * vz;\n let svy = ve[1] * vx + ve[5] * vy + ve[9] * vz;\n const sl = Math.hypot(svx, svy);\n if (sl > 1e-6) { svx /= sl; svy /= sl; }\n\n const angle = align ? Math.atan2(svx, svy) : this.angle[i];\n const cs = Math.cos(angle);\n const sn = Math.sin(angle);\n\n for (let k = 0; k < 4; k++) {\n const qx = QUAD[k * 2];\n const qy = QUAD[k * 2 + 1];\n const rqx = cs * qx + sn * qy;\n const rqy = -sn * qx + cs * qy;\n // Billboard: PlayCanvas builds the corner from the negated camera axes.\n const lx = -_right.x * rqx - _up.x * rqy;\n const ly = -_right.y * rqx - _up.y * rqy;\n const lz = -_right.z * rqx - _up.z * rqy;\n let cx = px, cy = py, cz = pz;\n if (stretch !== 0) {\n // Trail the vertices that face away from the motion back along it.\n const tl = Math.hypot(rqx, rqy) || 1;\n const interp = (-svx * (-rqx / tl) + -svy * (-rqy / tl)) * 0.5 + 0.5;\n cx -= vx * stretch * interp;\n cy -= vy * stretch * interp;\n cz -= vz * stretch * interp;\n }\n const o = (i * 4 + k) * 3;\n position[o] = cx + lx * scale * es.x;\n position[o + 1] = cy + ly * scale * es.y;\n position[o + 2] = cz + lz * scale * es.z;\n const q = (i * 4 + k) * 4;\n color[q] = cr;\n color[q + 1] = cg;\n color[q + 2] = cb;\n color[q + 3] = visible ? Math.pow(ca, alphaPower) : 0;\n }\n }\n }\n}\n\n/** Corners of PlayCanvas's particle quad. */\nconst QUAD = [-1, -1, 1, -1, 1, 1, -1, 1];\n\nfunction buildParticleMesh(emitter: ParticleEmitter, layer: VfxParticleLayer): Mesh {\n const n = emitter.numParticles;\n const geometry = new BufferGeometry();\n const position = new BufferAttribute(new Float32Array(n * 4 * 3), 3).setUsage(DynamicDrawUsage);\n const color = new BufferAttribute(new Float32Array(n * 4 * 4), 4).setUsage(DynamicDrawUsage);\n const uv = new Float32Array(n * 4 * 2);\n const index: number[] = [];\n for (let i = 0; i < n; i++) {\n for (let k = 0; k < 4; k++) {\n // PlayCanvas samples the dot at (q * -0.5 + 0.5) with v flipped.\n uv[(i * 4 + k) * 2] = 0.5 - 0.5 * QUAD[k * 2];\n uv[(i * 4 + k) * 2 + 1] = 0.5 + 0.5 * QUAD[k * 2 + 1];\n }\n const v = i * 4;\n index.push(v, v + 1, v + 2, v, v + 2, v + 3);\n }\n geometry.setAttribute('position', position);\n geometry.setAttribute('color', color);\n geometry.setAttribute('uv', new BufferAttribute(uv, 2));\n geometry.setIndex(index);\n geometry.computeBoundingSphere();\n\n const additive = layer.blendType === 'additive';\n const material = new MeshBasicMaterial({\n map: dotTexture(1),\n vertexColors: true,\n transparent: true,\n depthWrite: layer.depthWrite ?? false,\n side: DoubleSide,\n // PlayCanvas discards alpha-blended particle fragments below 0.01.\n alphaTest: additive ? 0 : 0.01,\n });\n material.forceSinglePass = true;\n if (additive) {\n // PlayCanvas scales additive particles by their alpha, then adds.\n material.blending = CustomBlending;\n material.blendEquation = AddEquation;\n material.blendSrc = SrcAlphaFactor;\n material.blendDst = OneFactor;\n } else {\n material.blending = NormalBlending;\n }\n\n const mesh = new Mesh(geometry, material);\n mesh.name = `vfx_particle_${layer.id}`;\n // Vertices are written in world space.\n mesh.matrixAutoUpdate = false;\n mesh.matrixWorldAutoUpdate = false;\n mesh.frustumCulled = false;\n return mesh;\n}\n\nclass ParticleLayerInstance implements VfxLayerInstance {\n private readonly _scene: Scene;\n private readonly _node: Object3D;\n private readonly _mesh: Mesh;\n private readonly _layer: VfxParticleLayer;\n private readonly _emitter: ParticleEmitter;\n private readonly _offPreRender: () => void;\n\n constructor(scene: Scene, node: Object3D, layer: VfxParticleLayer) {\n this._scene = scene;\n this._node = node;\n this._layer = layer;\n this._emitter = new ParticleEmitter(layer);\n this._mesh = buildParticleMesh(this._emitter, layer);\n node.add(this._mesh);\n // Corners are placed just before the frame draws, against the camera as\n // it is then, and before the renderer uploads the buffers.\n this._offPreRender = scene.on('preRender', () => this._writeVertices());\n }\n\n spawn(_pos: Vec3Like): void {\n if (!this._layer.enabled) return;\n this._node.visible = true;\n this._emitter.reset(this._node);\n this._emitter.play();\n }\n\n update(ctx: VfxLayerUpdateContext): void {\n // The emitter steps first, as PlayCanvas's particle system runs before\n // the app's update handlers, while it is shown.\n if (this._node.visible && this._emitter.visible) this._emitter.step(this._node, ctx.dt);\n\n const layer = this._layer;\n if (!layer.enabled || ctx.t < 0) { this._node.visible = false; return; }\n\n this._node.visible = true;\n if (!layer.loop && ctx.t > ctx.layerDuration) this._emitter.stop(this._node);\n }\n\n reset(): void {\n this._emitter.stop(this._node);\n this._emitter.reset(this._node);\n this._node.visible = false;\n }\n\n dispose(): void {\n this._offPreRender();\n this._mesh.geometry.dispose();\n (this._mesh.material as MeshBasicMaterial).dispose();\n }\n\n /** Editor pause/resume escape hatch. Surfaced through JsonVfxInstance. */\n setPaused(paused: boolean): void {\n if (paused) {\n this._emitter.stop(this._node);\n } else if (this._layer.enabled) {\n this._emitter.reset(this._node);\n this._emitter.play();\n }\n }\n\n private _writeVertices(): void {\n const mesh = this._mesh;\n mesh.visible = this._emitter.visible;\n if (!this._emitter.visible || !isShown(this._node)) return;\n const camera = this._scene.camera;\n camera.updateMatrixWorld();\n // PlayCanvas adds an additive particle at `colour * alpha` in sRGB, the\n // space its framebuffer blends in. WebGPURenderer blends in linear space\n // (its output pass encodes afterwards), where the same sum is\n // `linear colour * alpha^2.2`. Alpha is a product of the dot texture and\n // the ramp, so the power is taken on each. A lone particle then matches;\n // overlaps still add in linear space.\n const r = this._scene.renderer as unknown as { isWebGPURenderer?: boolean; needsFrameBufferTarget?: boolean };\n const alphaPower = this._layer.blendType === 'additive' && r.isWebGPURenderer && r.needsFrameBufferTarget ? 2.2 : 1;\n const material = mesh.material as MeshBasicMaterial;\n material.map = dotTexture(alphaPower);\n const geometry = mesh.geometry;\n const position = geometry.getAttribute('position') as BufferAttribute;\n const color = geometry.getAttribute('color') as BufferAttribute;\n this._emitter.writeVertices(this._node, camera, position.array as Float32Array, color.array as Float32Array, alphaPower);\n position.needsUpdate = true;\n color.needsUpdate = true;\n // Sort against other transparent objects from the emitter, not the origin.\n const sphere = geometry.boundingSphere!;\n this._node.getWorldPosition(sphere.center);\n }\n}\n\nfunction isShown(obj: Object3D): boolean {\n for (let o: Object3D | null = obj; o; o = o.parent) if (!o.visible) return false;\n return true;\n}\n\n/**\n * Renders `particle` layers.\n *\n * @group Effects\n */\nexport class ParticleLayerRenderer implements VfxLayerRenderer<VfxParticleLayer> {\n readonly type = 'particle';\n\n build(layer: VfxParticleLayer, ctx: VfxLayerBuildContext): VfxLayerInstance {\n const node = new Object3D();\n node.name = `vfx_particle_${layer.id}`;\n const [px, py, pz] = layer.positionOffset ?? [0, 0, 0];\n node.position.set(px, py, pz);\n ctx.parent.add(node);\n return new ParticleLayerInstance(ctx.scene, node, layer);\n }\n}\n\n/** Type guard for the prefab's editor escape hatch `setParticlesPaused`. */\nexport function isParticleLayerInstance(inst: VfxLayerInstance): inst is ParticleLayerInstance {\n return inst instanceof ParticleLayerInstance;\n}\n", "/**\n * Sprite layer - animated spritesheet on a quad. Frames advance based on\n * progress through the layer's duration; can either billboard to the camera\n * or stay in world rotation.\n */\n\nimport {\n Color,\n DataTexture,\n LinearFilter,\n Mesh,\n NoColorSpace,\n MeshBasicMaterial,\n Quaternion,\n SRGBColorSpace,\n Texture,\n} from 'three';\nimport type { Camera, Float32BufferAttribute } from 'three';\n\nimport { cachedFetch } from '../../../loader/shared/bin-cache';\nimport type { Vec3Like } from '../../../presets/camera/camera-preset';\nimport type {\n CurvePoint,\n VfxLayerBase,\n} from '../data-types';\nimport type {\n VfxLayerBuildContext,\n VfxLayerInstance,\n VfxLayerRenderer,\n VfxLayerUpdateContext,\n} from '../layer-renderer';\nimport { getVfxMesh } from './mesh';\nimport { applyBlend, applyCull, lerpCurve, quatFromEulerDeg, setEmissive } from './shared';\n\n// \u2500\u2500 Public data type \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * An animated spritesheet on a quad.\n *\n * @group Effects\n */\nexport interface VfxSpriteLayer extends VfxLayerBase {\n type: 'sprite';\n\n /** Path to the spritesheet image, passed through the stage's `resolveUrl`. */\n spriteSheet: string;\n cols: number;\n rows: number;\n /** Total frame count (defaults to cols * rows). */\n frameCount?: number;\n fps: number;\n loop?: boolean;\n\n orientation: 'billboard' | 'world';\n\n color: [number, number, number];\n emissiveIntensity: number;\n opacity: number;\n blendMode: 'additive' | 'alpha';\n depthTest: boolean;\n depthWrite: boolean;\n cullFace: boolean;\n\n positionOffset: [number, number, number];\n rotation: [number, number, number];\n scale: number;\n\n opacityKeys?: CurvePoint[];\n scaleKeys?: CurvePoint[];\n}\n\n// \u2500\u2500 Texture cache \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// A 1x1 white placeholder, assigned at build time so the material compiles its\n// textured program then (at pool creation or prewarm) rather than mid-game,\n// when the real sheet arrives. The program depends on whether a map is set,\n// not on its contents, so the swap to the real texture compiles nothing.\nlet _placeholder: DataTexture | null = null;\n\nfunction placeholderTexture(): DataTexture {\n if (!_placeholder) {\n _placeholder = new DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1);\n _placeholder.needsUpdate = true;\n }\n return _placeholder;\n}\n\nconst _sheets = new Map<string, Promise<Texture>>();\n\n// Sheets are sRGB images, flipped so v = 0 is the bottom of the image: as the\n// PlayCanvas build loads them, which is what the effect data's colours and\n// frame order were authored against.\n//\n// PlayCanvas decodes the sRGB in the shader, after filtering. three.js's\n// WebGL path would decode before filtering (an sRGB texture format), which\n// lightens the soft edges of a sheet, so there the texture stays undecoded\n// and the material decodes it the PlayCanvas way (`decodeInShader`).\n// WebGPURenderer decodes after filtering already.\nfunction loadSpriteTexture(url: string, decodeInShader: boolean): Promise<Texture> {\n const key = `${decodeInShader ? 'shader' : 'srgb'}|${url}`;\n let pending = _sheets.get(key);\n if (!pending) {\n pending = cachedFetch(url)\n .then((r) => { if (!r.ok) throw new Error(`Sprite load failed: ${r.status}`); return r.blob(); })\n .then((blob) => createImageBitmap(blob, { imageOrientation: 'flipY' }))\n .then((bitmap) => {\n // Uploaded from a canvas, as PlayCanvas does: the canvas stores\n // premultiplied colour, and that round trip is part of how a sheet's\n // semi-transparent edges look there.\n const canvas = document.createElement('canvas');\n canvas.width = bitmap.width;\n canvas.height = bitmap.height;\n canvas.getContext('2d')!.drawImage(bitmap, 0, 0);\n bitmap.close();\n const tex = new Texture(canvas);\n tex.flipY = false;\n tex.generateMipmaps = false;\n tex.minFilter = LinearFilter;\n tex.colorSpace = decodeInShader ? NoColorSpace : SRGBColorSpace;\n tex.needsUpdate = true;\n return tex;\n });\n pending.catch((err) => {\n _sheets.delete(key);\n console.warn('[VFX] sprite texture load error:', err);\n });\n _sheets.set(key, pending);\n }\n return pending;\n}\n\n// \u2500\u2500 Instance + Renderer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst _parentQuat = new Quaternion();\nconst _camQuat = new Quaternion();\n\nclass SpriteLayerInstance implements VfxLayerInstance {\n private readonly _layer: VfxSpriteLayer;\n private readonly _mesh: Mesh;\n private readonly _material: MeshBasicMaterial;\n private readonly _uv: Float32BufferAttribute;\n private readonly _cols: number;\n private readonly _rows: number;\n private readonly _frameCount: number;\n private _frame = -1;\n private _textureReady = false;\n\n constructor(layer: VfxSpriteLayer, mesh: Mesh, material: MeshBasicMaterial) {\n this._layer = layer;\n this._mesh = mesh;\n this._material = material;\n this._uv = mesh.geometry.getAttribute('uv') as Float32BufferAttribute;\n this._cols = layer.cols || 1;\n this._rows = layer.rows || 1;\n this._frameCount = layer.frameCount || (this._cols * this._rows);\n if (layer.orientation === 'billboard') {\n // Face the camera that is drawing, at draw time: this is the rotation\n // the PlayCanvas build copied from its camera each update.\n mesh.onBeforeRender = (_r, _s, camera: Camera) => {\n const parent = mesh.parent;\n camera.getWorldQuaternion(_camQuat);\n if (parent) mesh.quaternion.copy(parent.getWorldQuaternion(_parentQuat).invert().multiply(_camQuat));\n else mesh.quaternion.copy(_camQuat);\n mesh.updateMatrixWorld();\n };\n }\n }\n\n setTextureReady(): void {\n this._textureReady = true;\n }\n\n spawn(_pos: Vec3Like): void {\n // Visibility is driven by `update`; the prefab calls update(t=0) on spawn.\n }\n\n update(ctx: VfxLayerUpdateContext): void {\n const layer = this._layer;\n if (!layer.enabled || !this._textureReady) { this._mesh.visible = false; return; }\n\n // Sprite has its own per-layer loop flag - it stays alive past the\n // effect's duration when looping, even if the wider effect isn't.\n const localT = ctx.t;\n if (localT < 0 || (!ctx.loop && !layer.loop && localT > ctx.layerDuration)) {\n this._mesh.visible = false;\n return;\n }\n\n this._mesh.visible = true;\n const nt = ctx.layerDuration > 0 ? Math.min(localT / ctx.layerDuration, 1) : 0;\n\n let progress = ctx.layerDuration > 0 ? localT / ctx.layerDuration : 0;\n if (layer.loop && ctx.layerDuration > 0) progress = progress % 1;\n progress = Math.min(Math.max(progress, 0), 1);\n const frameIdx = Math.min(Math.floor(progress * this._frameCount), this._frameCount - 1);\n if (frameIdx !== this._frame) this._setFrame(frameIdx);\n\n this._material.opacity = (layer.opacity ?? 1) * lerpCurve(layer.opacityKeys ?? [[0, 1]], nt);\n\n const s = (layer.scale ?? 1) * lerpCurve(layer.scaleKeys ?? [[0, 1]], nt);\n this._mesh.scale.set(s, s, s);\n }\n\n /**\n * Point the quad's UVs at one cell of the sheet. Row 0 is the top of the\n * image: PlayCanvas's map transform places a cell at `1 - tiling - offset`\n * in v, and the sheet's v = 1 is its top.\n */\n private _setFrame(frameIdx: number): void {\n this._frame = frameIdx;\n const uTile = 1 / this._cols;\n const vTile = 1 / this._rows;\n const u0 = (frameIdx % this._cols) * uTile;\n const v0 = 1 - (Math.floor(frameIdx / this._cols) + 1) * vTile;\n const uv = this._uv;\n uv.setXY(0, u0, v0);\n uv.setXY(1, u0 + uTile, v0);\n uv.setXY(2, u0 + uTile, v0 + vTile);\n uv.setXY(3, u0, v0 + vTile);\n uv.needsUpdate = true;\n }\n\n reset(): void {\n this._mesh.visible = false;\n this._material.opacity = 0;\n }\n\n dispose(): void {\n this._material.dispose();\n this._mesh.geometry.dispose();\n }\n}\n\n/**\n * Renders `sprite` layers.\n *\n * @group Effects\n */\nexport class SpriteLayerRenderer implements VfxLayerRenderer<VfxSpriteLayer> {\n readonly type = 'sprite';\n\n build(layer: VfxSpriteLayer, ctx: VfxLayerBuildContext): VfxLayerInstance {\n // Each sprite owns its whole quad, not just the UVs its frame lives in:\n // disposing a geometry frees the GPU buffers of every attribute on it, so\n // an attribute shared with the cached quad would die with the first sprite.\n const geometry = getVfxMesh('quad').clone();\n\n const decodeInShader = (ctx.scene.renderer as unknown as { isWebGPURenderer?: boolean }).isWebGPURenderer !== true;\n const mat = new MeshBasicMaterial({\n color: setEmissive(new Color(), layer.color, layer.emissiveIntensity ?? 1),\n depthTest: layer.depthTest ?? true,\n depthWrite: layer.depthWrite ?? false,\n opacity: 0,\n map: layer.spriteSheet ? placeholderTexture() : null,\n });\n // three.js's own switch for decoding an sRGB map after sampling (it uses\n // it for video); see loadSpriteTexture.\n if (decodeInShader) mat.defines = { DECODE_VIDEO_TEXTURE: '' };\n applyBlend(mat, layer.blendMode === 'additive');\n applyCull(mat, !!layer.cullFace);\n\n const mesh = new Mesh(geometry, mat);\n mesh.name = `vfx_sprite_${layer.id}`;\n const [px, py, pz] = layer.positionOffset ?? [0, 0, 0];\n mesh.position.set(px, py, pz);\n if (layer.orientation !== 'billboard') {\n const [rx, ry, rz] = layer.rotation ?? [0, 0, 0];\n quatFromEulerDeg(rx, ry, rz, mesh.quaternion);\n }\n ctx.parent.add(mesh);\n\n const instance = new SpriteLayerInstance(layer, mesh, mat);\n\n if (layer.spriteSheet) {\n loadSpriteTexture(ctx.resolveUrl(layer.spriteSheet), decodeInShader).then((tex) => {\n mat.map = tex;\n instance.setTextureReady();\n }).catch(() => { /* texture load failed - layer stays invisible */ });\n }\n\n return instance;\n }\n}\n", "/**\n * Generic data-driven shader layer.\n *\n * Unlike the other layer types, this one carries its shader code *in the\n * layer JSON*. That makes it the substrate for fully data-driven VFX: a tool\n * authors a fragment shader per effect and it renders without any new\n * TypeScript - the program is just serialized data.\n *\n * The renderer supplies:\n * - one of three meshes (`billboard` camera-facing quad, flat `quad`, `sphere`)\n * - a default vertex stage per geometry, so most effects only need a\n * fragment shader\n * - standard uniforms every frame: uProgress (0..1 lifecycle), uTime\n * (seconds), uDuration, uOpacity, plus any custom uniforms declared in\n * `layer.uniforms`\n *\n * Under WebGLRenderer the layer runs `fragmentGLSL` (and `vertexGLSL`):\n * GLSL ES 1.00 as the PlayCanvas build takes it (attribute / varying /\n * gl_FragColor, PlayCanvas's `vertex_*` attribute and `matrix_*` uniform\n * names), so shaders authored for that build run unchanged. Under\n * WebGPURenderer it runs `fragmentWGSL`, a WGSL function whose parameters\n * are picked by name from the same inputs; that needs the\n * `@viggle/splat-engine-three/webgpu` entry point. A layer without the code\n * for the renderer drawing it is skipped with a warning.\n *\n * The fragment output is written as-is, with no colour-space conversion -\n * the PlayCanvas build's ShaderMaterial behaviour.\n */\n\nimport {\n GLSL3,\n Matrix3,\n Matrix4,\n Mesh,\n RawShaderMaterial,\n} from 'three';\nimport type { BufferGeometry, Camera, IUniform, Material } from 'three';\n\nimport type { Vec3Like } from '../../../presets/camera/camera-preset';\nimport type { CurvePoint, VfxLayerBase } from '../data-types';\nimport type {\n VfxLayerBuildContext,\n VfxLayerInstance,\n VfxLayerRenderer,\n VfxLayerUpdateContext,\n} from '../layer-renderer';\nimport { getVfxMesh } from './mesh';\nimport { applyBlend, applyCull, lerpCurve, quatFromEulerDeg } from './shared';\n\n// \u2500\u2500 Public data type \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** @group Effects */\nexport type VfxShaderGeometry = 'billboard' | 'quad' | 'sphere';\n\n/**\n * A custom uniform: float | vec2 | vec3 | vec4.\n *\n * @group Effects\n */\nexport interface VfxShaderUniform {\n value: number | number[];\n}\n\n/**\n * A mesh drawn with shader code carried in the layer data.\n *\n * @group Effects\n */\nexport interface VfxShaderLayer extends VfxLayerBase {\n type: 'shader';\n\n /** Mesh the shader draws on. billboard = camera-facing quad. */\n geometry: VfxShaderGeometry;\n\n /** GLSL ES 1.00 fragment shader, used under WebGLRenderer. */\n fragmentGLSL?: string;\n /** Optional GLSL ES 1.00 vertex shader. Defaults to the per-geometry one. */\n vertexGLSL?: string;\n /**\n * WGSL fragment function, used under WebGPURenderer. Its parameters are\n * filled by name from `vUv: vec2f`, `vLocalPos`, `vWorldPos`,\n * `vNormal: vec3f`, `uTime`, `uProgress`, `uDuration`, `uOpacity: f32` and\n * the custom uniforms; it returns the `vec4f` colour. See\n * {@link DEFAULT_SHADER_FRAGMENT_WGSL}.\n */\n fragmentWGSL?: string;\n\n /** Custom uniforms, keyed by shader name (must be declared in the shader). */\n uniforms?: Record<string, VfxShaderUniform>;\n\n /** Global opacity multiplier exposed to the shader as `uOpacity`. */\n opacity: number;\n opacityKeys?: CurvePoint[];\n scaleKeys?: CurvePoint[];\n\n blendMode: 'additive' | 'alpha';\n depthTest: boolean;\n depthWrite: boolean;\n /** false \u2192 double-sided, recommended for transparent FX. */\n cullFace: boolean;\n\n scale: number;\n positionOffset: [number, number, number];\n rotation: [number, number, number];\n}\n\n/**\n * Starter fragment shader (soft additive radial glow on a billboard that fades\n * out over the layer lifetime). Exported so editors/generators can seed a new\n * shader layer and use it as a canonical example.\n *\n * @group Effects\n */\nexport const DEFAULT_SHADER_FRAGMENT = /* glsl */ `precision highp float;\nvarying vec2 vUv;\nuniform float uProgress; // 0..1 over the layer's lifetime\nuniform float uOpacity; // multiply final alpha by this\nuniform vec3 uColor; // custom uniform (see \"uniforms\" below)\nvoid main() {\n vec2 p = vUv * 2.0 - 1.0; // -1..1\n float d = length(p);\n float glow = pow(smoothstep(1.0, 0.0, d), 2.0);\n float fade = 1.0 - uProgress; // fade out as the effect ends\n float alpha = glow * fade * uOpacity;\n gl_FragColor = vec4(uColor * glow * 3.0, alpha);\n}`;\n\n/**\n * {@link DEFAULT_SHADER_FRAGMENT} as the WGSL function `fragmentWGSL` takes.\n *\n * @group Effects\n */\nexport const DEFAULT_SHADER_FRAGMENT_WGSL = /* wgsl */ `fn main(vUv: vec2f, uProgress: f32, uOpacity: f32, uColor: vec3f) -> vec4f {\n let p = vUv * 2.0 - 1.0;\n let d = length(p);\n let glow = pow(1.0 - smoothstep(0.0, 1.0, d), 2.0);\n let fade = 1.0 - uProgress;\n let alpha = glow * fade * uOpacity;\n return vec4f(uColor * glow * 3.0, alpha);\n}`;\n\n// \u2500\u2500 default vertex shaders, one per geometry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// The PlayCanvas build's, unchanged. Each exposes the same varying contract\n// to the fragment shader:\n// vUv (vec2 0..1), vLocalPos (vec3), vWorldPos (vec3), vNormal (vec3 world).\n\nconst BILLBOARD_VS = /* glsl */ `\nattribute vec3 vertex_position;\nattribute vec2 vertex_texCoord0;\nuniform mat4 matrix_model;\nuniform mat4 matrix_view;\nuniform mat4 matrix_viewProjection;\nvarying vec2 vUv;\nvarying vec3 vLocalPos;\nvarying vec3 vWorldPos;\nvarying vec3 vNormal;\nvoid main() {\n vec3 center = matrix_model[3].xyz;\n float sx = length(matrix_model[0].xyz);\n float sy = length(matrix_model[1].xyz);\n vec3 camRight = vec3(matrix_view[0][0], matrix_view[1][0], matrix_view[2][0]);\n vec3 camUp = vec3(matrix_view[0][1], matrix_view[1][1], matrix_view[2][1]);\n vec3 worldPos = center + (vertex_position.x * sx) * camRight + (vertex_position.y * sy) * camUp;\n vUv = vertex_texCoord0;\n vLocalPos = vertex_position;\n vWorldPos = worldPos;\n vNormal = normalize(cross(camRight, camUp));\n gl_Position = matrix_viewProjection * vec4(worldPos, 1.0);\n}\n`;\n\nconst QUAD_VS = /* glsl */ `\nattribute vec3 vertex_position;\nattribute vec3 vertex_normal;\nattribute vec2 vertex_texCoord0;\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\nvarying vec2 vUv;\nvarying vec3 vLocalPos;\nvarying vec3 vWorldPos;\nvarying vec3 vNormal;\nvoid main() {\n vec4 wp = matrix_model * vec4(vertex_position, 1.0);\n vUv = vertex_texCoord0;\n vLocalPos = vertex_position;\n vWorldPos = wp.xyz;\n vNormal = normalize((matrix_model * vec4(vertex_normal, 0.0)).xyz);\n gl_Position = matrix_viewProjection * wp;\n}\n`;\n\nconst SPHERE_VS = /* glsl */ `\nattribute vec3 vertex_position;\nattribute vec3 vertex_normal;\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\nvarying vec2 vUv;\nvarying vec3 vLocalPos;\nvarying vec3 vWorldPos;\nvarying vec3 vNormal;\nvoid main() {\n vec4 wp = matrix_model * vec4(vertex_position, 1.0);\n vLocalPos = vertex_position;\n vWorldPos = wp.xyz;\n vNormal = normalize((matrix_model * vec4(vertex_normal, 0.0)).xyz);\n vec3 d = normalize(vertex_position);\n vUv = vec2(atan(d.z, d.x) / 6.28318530718 + 0.5, asin(clamp(d.y, -1.0, 1.0)) / 3.14159265359 + 0.5);\n gl_Position = matrix_viewProjection * wp;\n}\n`;\n\nfunction defaultVS(geometry: VfxShaderGeometry): string {\n switch (geometry) {\n case 'sphere': return SPHERE_VS;\n case 'quad': return QUAD_VS;\n case 'billboard':\n default: return BILLBOARD_VS;\n }\n}\n\n/** The mesh a shader layer draws on, from the shared cache. */\nexport function shaderLayerGeometry(geometry: VfxShaderGeometry): BufferGeometry {\n return geometry === 'sphere' ? getVfxMesh('sphere', { segments: 32 }) : getVfxMesh('quad');\n}\n\n// \u2500\u2500 GLSL ES 1.00 \u2192 three.js \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// three.js compiles this as GLSL ES 3.00 with no prefix of its own beyond the\n// version line, so the compatibility layer is spelled out here: ES 1.00\n// keywords, and PlayCanvas's attribute / uniform names mapped onto the ones\n// three.js binds. `matrix_viewProjection`, `matrix_viewInverse` and\n// `matrix_normal` have no three.js counterpart and are set per draw.\n\nconst VS_PREFIX = `#define attribute in\n#define varying out\n#define texture2D texture\nprecision highp float;\nprecision highp int;\n#define vertex_position position\n#define vertex_normal normal\n#define vertex_texCoord0 uv\n#define matrix_model modelMatrix\n#define matrix_view viewMatrix\n#define matrix_projection projectionMatrix\n#define view_position cameraPosition\n`;\n\nconst FS_PREFIX = `#define varying in\n#define texture2D texture\n#define gl_FragColor pc_fragColor\nlayout(location = 0) out highp vec4 pc_fragColor;\n#define matrix_view viewMatrix\n#define view_position cameraPosition\n`;\n\nfunction glslSources(vs: string, fs: string): { vertex: string; fragment: string } {\n const precision = /precision\\s+(low|medium|high)p\\s+float/.test(fs) ? '' : 'precision highp float;\\n';\n return { vertex: VS_PREFIX + vs, fragment: FS_PREFIX + precision + fs };\n}\n\n// \u2500\u2500 GLSL pre-compile validation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Compile the source as the layer will run it against the renderer's WebGL\n// context, so the driver's own error log reaches the caller instead of the\n// layer silently rendering nothing.\n\nfunction compileLog(gl: WebGL2RenderingContext, type: number, src: string): string | null {\n const sh = gl.createShader(type);\n if (!sh) return null;\n gl.shaderSource(sh, src);\n gl.compileShader(sh);\n const ok = gl.getShaderParameter(sh, gl.COMPILE_STATUS);\n const log = ok ? null : (gl.getShaderInfoLog(sh) || 'unknown compile error');\n gl.deleteShader(sh);\n return log;\n}\n\n/**\n * Compile a shader layer's GLSL on `renderer`'s WebGL context. Returns a\n * human-readable error, or null when both stages compile - and null on any\n * renderer that is not a `WebGLRenderer`, where nothing is checked.\n *\n * @group Effects\n */\nexport function validateShaderGLSL(renderer: unknown, vs: string, fs: string): string | null {\n const r = renderer as { isWebGPURenderer?: boolean; getContext?: () => unknown };\n if (r.isWebGPURenderer || typeof r.getContext !== 'function') return null;\n const gl = r.getContext() as WebGL2RenderingContext;\n if (typeof gl?.createShader !== 'function') return null;\n const { vertex, fragment } = glslSources(vs, fs);\n const vlog = compileLog(gl, gl.VERTEX_SHADER, `#version 300 es\\n${vertex}`);\n if (vlog) return `Vertex shader compile error:\\n${vlog}`;\n const flog = compileLog(gl, gl.FRAGMENT_SHADER, `#version 300 es\\n${fragment}`);\n if (flog) return `Fragment shader compile error:\\n${flog}`;\n return null;\n}\n\n// \u2500\u2500 Materials per renderer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * A shader layer's material and how to feed it uniforms.\n * @internal\n */\nexport interface ShaderLayerMaterial {\n readonly material: Material;\n /** Set a standard (`uTime`, \u2026) or custom uniform. */\n set(name: string, value: number | readonly number[]): void;\n /** Per-draw camera state. */\n beforeRender(renderer: unknown, mesh: Mesh, camera: Camera): void;\n}\n\n/** @internal */\nexport type ShaderLayerMaterialFactory = (layer: VfxShaderLayer, geometry: VfxShaderGeometry) => ShaderLayerMaterial;\n\nlet webgpuFactory: ShaderLayerMaterialFactory | null = null;\n\n/**\n * Make the WGSL path available. Called by the\n * `@viggle/splat-engine-three/webgpu` entry point.\n * @internal\n */\nexport function registerShaderLayerWebGPU(factory: ShaderLayerMaterialFactory): void {\n webgpuFactory = factory;\n}\n\nconst warned = new Set<string>();\nfunction warnOnce(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n console.warn(`[VFX] ${message}`);\n}\n\nfunction glslMaterial(layer: VfxShaderLayer, geometry: VfxShaderGeometry, vs: string, fs: string): ShaderLayerMaterial {\n const { vertex, fragment } = glslSources(vs, fs);\n const viewProjection = new Matrix4();\n const viewInverse = new Matrix4();\n const normal = new Matrix3();\n const uniforms: Record<string, IUniform> = {\n uTime: { value: 0 },\n uProgress: { value: 0 },\n uDuration: { value: layer.duration ?? 0 },\n uOpacity: { value: layer.opacity ?? 1 },\n matrix_viewProjection: { value: viewProjection },\n matrix_viewInverse: { value: viewInverse },\n matrix_normal: { value: normal },\n };\n for (const [name, spec] of Object.entries(layer.uniforms ?? {})) {\n if (spec && spec.value != null) uniforms[name] = { value: spec.value };\n }\n const material = new RawShaderMaterial({\n name: `VfxShader_${layer.id}_${geometry}`,\n glslVersion: GLSL3,\n vertexShader: vertex,\n fragmentShader: fragment,\n uniforms,\n });\n return {\n material,\n set(name, value) {\n const u = uniforms[name];\n if (u) u.value = value;\n },\n beforeRender(_renderer, mesh, camera) {\n viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);\n viewInverse.copy(camera.matrixWorld);\n normal.getNormalMatrix(mesh.matrixWorld);\n },\n };\n}\n\n// \u2500\u2500 instance \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass ShaderLayerInstance implements VfxLayerInstance {\n private readonly _layer: VfxShaderLayer;\n private readonly _mesh: Mesh;\n private readonly _material: ShaderLayerMaterial;\n\n // Explicit fields, not parameter properties: consumers compiling this source\n // with `erasableSyntaxOnly` reject the parameter-property form.\n constructor(layer: VfxShaderLayer, mesh: Mesh, material: ShaderLayerMaterial) {\n this._layer = layer;\n this._mesh = mesh;\n this._material = material;\n }\n\n spawn(_pos: Vec3Like): void {}\n\n update(ctx: VfxLayerUpdateContext): void {\n const layer = this._layer;\n if (!layer.enabled || !ctx.alive) { this._mesh.visible = false; return; }\n this._mesh.visible = true;\n\n const nt = ctx.layerDuration > 0 ? Math.min(1, Math.max(0, ctx.t / ctx.layerDuration)) : 0;\n const scale = lerpCurve(layer.scaleKeys ?? [], nt);\n const opacity = lerpCurve(layer.opacityKeys ?? [], nt);\n\n const s = layer.scale * scale;\n this._mesh.scale.set(s, s, s);\n\n const m = this._material;\n m.set('uTime', ctx.t);\n m.set('uProgress', nt);\n m.set('uDuration', ctx.layerDuration);\n m.set('uOpacity', layer.opacity * opacity);\n }\n\n reset(): void {\n this._mesh.visible = false;\n this._material.set('uOpacity', 0);\n }\n\n dispose(): void {\n this._material.material.dispose();\n }\n}\n\n/** Stands in for a layer that has no code for the renderer drawing it. */\nclass SkippedLayerInstance implements VfxLayerInstance {\n spawn(): void {}\n update(): void {}\n reset(): void {}\n dispose(): void {}\n}\n\n/**\n * Renders `shader` layers.\n *\n * @group Effects\n */\nexport class ShaderLayerRenderer implements VfxLayerRenderer<VfxShaderLayer> {\n readonly type = 'shader';\n\n build(layer: VfxShaderLayer, ctx: VfxLayerBuildContext): VfxLayerInstance {\n const renderer = ctx.scene.renderer as unknown as { isWebGPURenderer?: boolean };\n const geometry = layer.geometry ?? 'billboard';\n\n let material: ShaderLayerMaterial;\n if (renderer.isWebGPURenderer) {\n if (!layer.fragmentWGSL?.trim()) {\n warnOnce(`shader layer \"${layer.name}\" has no fragmentWGSL, which WebGPURenderer needs; skipping it`);\n return new SkippedLayerInstance();\n }\n if (!webgpuFactory) {\n warnOnce(\"shader layers under WebGPURenderer need the '@viggle/splat-engine-three/webgpu' entry point; skipping\");\n return new SkippedLayerInstance();\n }\n if (layer.vertexGLSL?.trim()) warnOnce(`shader layer \"${layer.name}\": vertexGLSL is WebGL-only; using the default vertex stage`);\n material = webgpuFactory(layer, geometry);\n } else {\n const fs = layer.fragmentGLSL;\n if (!fs || !fs.trim()) throw new Error(`shader layer \"${layer.name}\" has no fragmentGLSL`);\n const vs = layer.vertexGLSL && layer.vertexGLSL.trim() ? layer.vertexGLSL : defaultVS(geometry);\n const err = validateShaderGLSL(ctx.scene.renderer, vs, fs);\n if (err) throw new Error(`Shader layer \"${layer.name}\": ${err}`);\n material = glslMaterial(layer, geometry, vs, fs);\n }\n\n const mat = material.material;\n applyBlend(mat, layer.blendMode !== 'alpha');\n mat.depthTest = layer.depthTest ?? false;\n mat.depthWrite = layer.depthWrite ?? false;\n applyCull(mat, !!layer.cullFace);\n\n const mesh = new Mesh(shaderLayerGeometry(geometry), mat);\n mesh.name = `vfx_shader_${layer.id}`;\n mesh.onBeforeRender = (r, _s, camera) => material.beforeRender(r, mesh, camera);\n\n const [px, py, pz] = layer.positionOffset ?? [0, 0, 0];\n mesh.position.set(px, py, pz);\n const [rx, ry, rz] = layer.rotation ?? [0, 0, 0];\n quatFromEulerDeg(rx, ry, rz, mesh.quaternion);\n mesh.scale.setScalar(layer.scale ?? 1);\n\n ctx.parent.add(mesh);\n return new ShaderLayerInstance(layer, mesh, material);\n }\n}\n", "/**\n * Plug-in surface for VFX layer renderers.\n *\n * `JsonVfxPrefab` ships only mechanism - it walks `VfxEffectData.layers`,\n * resolves each layer's `type` against a `VfxLayerRegistry`, and asks the\n * matched renderer to build a `VfxLayerInstance`. The prefab owns the shared\n * time accounting (startDelay, duration, loop, alive flag) and per-frame\n * dispatch; the renderer owns everything specific to its layer type\n * (geometry, materials, per-frame uniform updates).\n *\n * The engine ships four renderers: `ParticleLayerRenderer`,\n * `MeshLayerRenderer`, `SpriteLayerRenderer` and `ShaderLayerRenderer`.\n * Consumers register their own (stylized fire ribbons, clouds, shields, ...)\n * and extend `VfxLayerTypeMap` via declaration merging so the union narrows\n * correctly in user code.\n */\n\nimport type { Object3D } from 'three';\n\nimport type { Vec3Like } from '../../presets/camera/camera-preset';\nimport type { Scene } from '../../scene';\nimport type { VfxLayerBase } from './data-types';\n\n/**\n * Context passed when building a layer instance.\n *\n * @group Effects\n */\nexport interface VfxLayerBuildContext {\n /** The scene the effect draws in: its renderer picks the material flavour, its camera faces billboards. */\n scene: Scene;\n /** Parent object all per-layer objects attach under (the effect root). */\n parent: Object3D;\n /**\n * `renderOrder` for the effect's meshes; `undefined` leaves three.js's\n * default. The prefab applies it to every mesh under the effect root after\n * the renderer returns, so most renderers can ignore it.\n */\n renderOrder?: number;\n /** Resolves asset paths (texture URLs etc.) found inside layer data. */\n resolveUrl: (path: string) => string;\n}\n\n/**\n * Per-frame update context for a single layer instance.\n *\n * @group Effects\n */\nexport interface VfxLayerUpdateContext {\n /**\n * Layer-local time in seconds since spawn, already shifted by\n * `layer.startDelay`. Negative when the layer hasn't started yet - most\n * renderers should just hide themselves while `alive` is false.\n */\n t: number;\n /** Frame delta in seconds. */\n dt: number;\n /** Wall-clock elapsed since spawn, ignoring `startDelay`. Useful for\n * shader `uTime` uniforms that should run during the startDelay window. */\n elapsed: number;\n /**\n * True while the layer is active - i.e. `t >= 0` AND (the effect loops OR\n * `t <= layerDuration`). Renderers should hide their objects and skip\n * uniform updates when this is false.\n */\n alive: boolean;\n /** Resolved layer duration: `layer.duration > 0 ? layer.duration : effectDuration`. */\n layerDuration: number;\n /** Whether the parent effect loops. */\n loop: boolean;\n}\n\n/**\n * One runtime instance of a single layer. The prefab owns N of these.\n *\n * @group Effects\n */\nexport interface VfxLayerInstance {\n /** Show + activate at a position. Called on `JsonVfxInstance.spawn`. */\n spawn(pos: Vec3Like): void;\n /** Hide + return to dormant. Called by `JsonVfxInstance.reset` / before recycle. */\n reset(): void;\n /** Per-frame tick. See `VfxLayerUpdateContext` for time semantics. */\n update(ctx: VfxLayerUpdateContext): void;\n /** Free what the instance owns. Called on `JsonVfxInstance.dispose`. */\n dispose(): void;\n /** Optional: move the active instance to a new position. */\n moveTo?(pos: Vec3Like): void;\n /** Optional: set per-instance uniform scale. */\n setScale?(s: number): void;\n /** Optional: set per-instance color tint. */\n setColor?(rgb: [number, number, number]): void;\n}\n\n/**\n * Factory for one layer type, registered with the registry by name.\n *\n * @group Effects\n */\nexport interface VfxLayerRenderer<L extends VfxLayerBase = VfxLayerBase> {\n /** The discriminator string this renderer handles ('particle', 'cloud', ...). */\n readonly type: string;\n /** Build a runtime instance from one layer definition. */\n build(layer: L, ctx: VfxLayerBuildContext): VfxLayerInstance;\n}\n\n/**\n * Layer-type \u2192 renderer registry. Passed to `VfxStage` / `JsonVfxPrefab`.\n *\n * @group Effects\n */\nexport class VfxLayerRegistry {\n private readonly _renderers = new Map<string, VfxLayerRenderer>();\n\n register<L extends VfxLayerBase>(renderer: VfxLayerRenderer<L>): this {\n this._renderers.set(renderer.type, renderer as unknown as VfxLayerRenderer);\n return this;\n }\n\n get(type: string): VfxLayerRenderer | undefined {\n return this._renderers.get(type);\n }\n\n has(type: string): boolean {\n return this._renderers.has(type);\n }\n}\n\n// Engine-default renderers live in `./layers/`. Imports are at module-top to\n// keep the dependency graph static (layer modules only import _types_ back\n// from this file, so there's no value-level cycle).\nimport { ParticleLayerRenderer } from './layers/particle';\nimport { MeshLayerRenderer } from './layers/mesh';\nimport { SpriteLayerRenderer } from './layers/sprite';\nimport { ShaderLayerRenderer } from './layers/shader';\n\n/**\n * Returns a registry pre-populated with the engine-default layer renderers\n * (`particle`, `mesh`, `sprite`, `shader`). Consumers extend it with their\n * own stylized renderers and pass the result to `VfxStage`.\n *\n * @group Effects\n */\nexport function defaultLayerRegistry(): VfxLayerRegistry {\n return new VfxLayerRegistry()\n .register(new ParticleLayerRenderer())\n .register(new MeshLayerRenderer())\n .register(new SpriteLayerRenderer())\n .register(new ShaderLayerRenderer());\n}\n", "import type { Object3D, WebGLRenderer } from 'three';\n\nimport type { Vec3Like } from '../../presets/camera/camera-preset';\nimport type { Scene } from '../../scene';\nimport { VfxPool } from './pool';\nimport type { VfxSpawnOptions } from './pool';\nimport type { IVfxPrefab, IVfxInstance } from './prefab';\nimport { JsonVfxPrefab } from './json-vfx-prefab';\nimport type { VfxEffectData } from './data-types';\nimport { defaultLayerRegistry } from './layer-renderer';\nimport type { VfxLayerRegistry } from './layer-renderer';\n\n/**\n * Optional construction extras the editor + cutscene flows need.\n *\n * @group Effects\n */\nexport interface VfxStageOptions {\n /**\n * `renderOrder` for every effect mesh. three.js draws transparent objects\n * by `renderOrder` first, then by distance, so a value above the\n * characters' (0) keeps effects over them - what the PlayCanvas build got\n * by drawing effects on a later layer. Omitted = three.js's default (0).\n */\n renderOrder?: number;\n /**\n * The PlayCanvas build's name for {@link renderOrder}: a layer drawn\n * later. Used as the `renderOrder` when that is not set.\n */\n layerId?: number;\n /** URL resolver for asset paths inside VfxEffectData (e.g. sprite textures).\n * Identity when omitted - editor previews pass already-resolved URLs through. */\n resolveUrl?: (path: string) => string;\n /**\n * Layer-type \u2192 renderer registry. Defaults to `defaultLayerRegistry()`\n * (particle + mesh + sprite + shader). Consumers extend it with their own\n * stylized renderers (cloud, shield, lightning, \u2026) by registering them on\n * a fresh registry and passing it here.\n */\n registry?: VfxLayerRegistry;\n}\n\n/**\n * VFX render host for one scene. Effects are added under the scene's\n * `contentRoot` and draw with its renderer, WebGL or WebGPU alike.\n *\n * Two paths for spawning effects - pick by use case:\n *\n * - Gameplay (fire-and-forget, pool-backed):\n * stage.register('punch_hit', prefab, 8);\n * stage.play('punch_hit', pos); // recycled instance, you don't keep a handle\n *\n * - Editor / cutscene (long-lived handle you control):\n * const prefab = stage.buildPrefab(jsonData);\n * const instance = stage.spawn(prefab);\n * instance.spawn(pos); instance.update(dt); instance.dispose();\n *\n * The two paths share the IVfxPrefab/IVfxInstance contracts; only the\n * lifecycle differs. Don't retain handles from `play` - the pool reserves\n * the right to recycle.\n *\n * Particle layers face the camera in the scene's `'preRender'` step, so draw\n * through the scene's own loop ({@link Scene.start}, `tick` or `render`).\n *\n * @example\n * ```ts\n * const vfx = new VfxStage(scene, { renderOrder: 1 });\n * vfx.register('boom', vfx.buildPrefab(explosionJson), 8);\n * scene.on('update', (dt) => vfx.update(dt));\n * vfx.play('boom', { x: 0, y: 1, z: 0 }, { scale: 1.5 });\n * ```\n *\n * @group Effects\n */\nexport class VfxStage {\n private readonly _scene: Scene;\n private readonly _pools = new Map<string, VfxPool>();\n private readonly _resolveUrl?: (path: string) => string;\n private readonly _renderOrder?: number;\n private readonly _registry: VfxLayerRegistry;\n\n constructor(scene: Scene, opts: VfxStageOptions = {}) {\n this._scene = scene;\n this._resolveUrl = opts.resolveUrl;\n this._renderOrder = opts.renderOrder ?? opts.layerId;\n this._registry = opts.registry ?? defaultLayerRegistry();\n }\n\n /** The scene effects draw in. */\n get scene(): Scene { return this._scene; }\n /** The renderer effects draw with. */\n get renderer(): WebGLRenderer { return this._scene.renderer; }\n /** Parent of every effect this stage creates. */\n get contentRoot(): Object3D { return this._scene.contentRoot; }\n get renderOrder(): number | undefined { return this._renderOrder; }\n get registry(): VfxLayerRegistry { return this._registry; }\n\n // \u2500\u2500 Gameplay path: register once, play many times \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Register a prefab under `name`. Allocates a pool of `poolSize` instances\n * eagerly so first-spawn doesn't pay the allocation cost. Re-registering\n * the same name disposes the previous pool. */\n register(name: string, prefab: IVfxPrefab, poolSize = 8): void {\n const existing = this._pools.get(name);\n if (existing) existing.destroy();\n const pool = new VfxPool(prefab, this._scene, this._scene.contentRoot, poolSize);\n this._pools.set(name, pool);\n }\n\n /** Fire one shot of a registered prefab at `pos`. Returns false if no\n * prefab is registered under that name. Caller doesn't keep a handle -\n * the pool reuses the slot when the effect finishes. */\n play(name: string, pos: Vec3Like, opts?: VfxSpawnOptions): boolean {\n const pool = this._pools.get(name);\n if (!pool) return false;\n pool.spawn(pos, opts);\n return true;\n }\n\n // \u2500\u2500 Editor / cutscene path: handle-controlled live instance \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Compile JSON layer data into a runnable prefab. Uses the stage's\n * registry + resolveUrl + renderOrder defaults. The returned prefab can be\n * passed to `spawn` (handle path) or `register` (pool path) interchangeably. */\n buildPrefab(data: VfxEffectData): JsonVfxPrefab {\n return new JsonVfxPrefab(data, this._registry, this._resolveUrl, this._renderOrder);\n }\n\n /** Create one instance you own. Returns the live handle - drive it with\n * spawn(pos) / update(dt) / dispose() yourself. Bypasses the pool. */\n spawn(prefab: IVfxPrefab): IVfxInstance {\n return prefab.create(this._scene, this._scene.contentRoot);\n }\n\n // \u2500\u2500 Shared \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Tick every registered pool. Drive this from your scene's update loop.\n * Handle-instances (from `spawn`) are NOT ticked here - caller owns the\n * update loop for those. */\n update(dt: number): void {\n for (const pool of this._pools.values()) pool.update(dt);\n }\n\n /** Dispose every registered pool, and what {@link prewarmJsonVfxPrefabs}\n * kept warm. Does NOT dispose handle-instances - caller is responsible\n * for those. */\n destroy(): void {\n for (const pool of this._pools.values()) pool.destroy();\n this._pools.clear();\n for (const instance of this._warm) instance.dispose();\n this._warm.length = 0;\n }\n\n /**\n * Hold hidden instances until {@link destroy}, so the shader programs they\n * compiled stay cached: three.js frees a program once no material uses it.\n * @internal\n */\n keepWarm(instances: IVfxInstance[]): void {\n this._warm.push(...instances);\n }\n\n private readonly _warm: IVfxInstance[] = [];\n}\n", "import { Group } from 'three';\n\nimport { JsonVfxPrefab } from './json-vfx-prefab';\nimport type { VfxDataFile } from './data-types';\nimport type { IVfxInstance } from './prefab';\nimport type { VfxStage } from './stage';\n\n/**\n * Compile the shaders of every effect in `dataFile` before the player can\n * see one, so the first spawn during gameplay does not stall a frame while\n * the renderer builds its program.\n *\n * Each effect is spawned once at the origin, the renderer compiles the\n * scene (`compileAsync`, on WebGL and WebGPU alike), and the instances are\n * taken out of the scene and kept by the stage until {@link VfxStage.destroy}: three.js frees\n * a program as soon as no material uses it, so disposing them here would\n * throw the compiled programs away again. Prefabs the game builds later hit\n * that cache. Run it behind a loading screen.\n *\n * @group Effects\n */\nexport async function prewarmJsonVfxPrefabs(\n stage: VfxStage,\n dataFile: VfxDataFile,\n resolveUrl?: (path: string) => string,\n): Promise<void> {\n const tmp: IVfxInstance[] = [];\n const origin = { x: 0, y: 0, z: 0 };\n // The warm instances live under one group, taken out of the scene once\n // compiled: off the graph they draw nothing, and their materials - so the\n // programs - stay alive.\n const holder = new Group();\n holder.name = 'vfx_prewarm';\n stage.contentRoot.add(holder);\n\n for (const [, data] of Object.entries(dataFile)) {\n try {\n const prefab = resolveUrl\n ? new JsonVfxPrefab(data, stage.registry, resolveUrl, stage.renderOrder)\n : stage.buildPrefab(data);\n const instance = prefab.create(stage.scene, holder);\n instance.spawn(origin);\n tmp.push(instance);\n } catch (err) {\n console.warn('[VFX prewarm] failed to build prefab; skipping:', err);\n }\n }\n\n const { scene } = stage;\n try {\n await scene.renderer.compileAsync(scene.threeScene, scene.camera);\n } finally {\n for (const instance of tmp) instance.reset();\n holder.removeFromParent();\n stage.keepWarm(tmp);\n }\n}\n", "import { Matrix4, Quaternion, Vector3 } from 'three';\n\nimport type { CameraHost, CameraPreset, TargetSupplier } from './camera-preset';\n\n/**\n * Options for {@link ThirdPersonCamera}.\n *\n * @group Presets\n */\nexport interface ThirdPersonCameraOptions {\n /** Position the camera orbits around, read each frame. */\n target: TargetSupplier;\n /** Default 4. */\n distance?: number;\n /** LookAt vertical offset above target. Default 1.2. */\n height?: number;\n /** Initial pitch (degrees, downward positive). Default 15. */\n pitch?: number;\n /** Mouse-look sensitivity in degrees per pixel. Default 0.2. */\n mouseSensitivity?: number;\n}\n\nconst _up = new Vector3(0, 1, 0);\nconst _look = new Matrix4();\nconst _parentQuat = new Quaternion();\n\n/**\n * Third-person follow camera.\n *\n * Orbits behind a target position at `distance` with adjustable `yaw`/`pitch`\n * (degrees), looking at `target + (0, height, 0)`. Yaw 0 puts the camera on\n * the target's +Z side. Mouse handling via pointer lock (click the canvas to\n * capture, Escape to release). No smoothing.\n *\n * @example\n * ```ts\n * const cam = new ThirdPersonCamera({ target: () => hero.getPosition(), distance: 5, pitch: 25 });\n * cam.attach({ canvas: scene.canvas, camera: scene.camera });\n * scene.on('update', (dt) => cam.update(dt));\n * ```\n *\n * @group Presets\n */\nexport class ThirdPersonCamera implements CameraPreset {\n yaw = 0;\n pitch: number;\n distance: number;\n height: number;\n mouseSensitivity: number;\n /** When false, mouse-look stops mutating yaw/pitch and the canvas no\n * longer grabs pointer lock. The follow `update()` still runs, so a\n * scripted camera move (e.g. a death cutscene) can drive yaw/pitch/\n * distance/height itself without the player fighting it. Setting this\n * false also releases an active pointer lock. */\n get inputEnabled(): boolean { return this._inputEnabled; }\n set inputEnabled(v: boolean) {\n this._inputEnabled = v;\n if (!v && this._host && document.pointerLockElement === this._host.canvas) {\n document.exitPointerLock();\n }\n }\n\n private _target: TargetSupplier;\n private _host: CameraHost | null = null;\n private _pointerLocked = false;\n private _inputEnabled = true;\n\n private _scratchPos = new Vector3();\n private _scratchLook = new Vector3();\n\n constructor(config: ThirdPersonCameraOptions) {\n this._target = config.target;\n this.distance = config.distance ?? 4;\n this.height = config.height ?? 1.2;\n this.pitch = config.pitch ?? 15;\n this.mouseSensitivity = config.mouseSensitivity ?? 0.2;\n }\n\n attach(host: CameraHost): void {\n if (this._host) throw new Error('[ThirdPersonCamera] already attached');\n this._host = host;\n host.canvas.addEventListener('click', this._onClickToLock);\n document.addEventListener('pointerlockchange', this._onLockChange);\n document.addEventListener('mousemove', this._onMouseMove);\n }\n\n detach(): void {\n if (!this._host) return;\n const { canvas } = this._host;\n canvas.removeEventListener('click', this._onClickToLock);\n document.removeEventListener('pointerlockchange', this._onLockChange);\n document.removeEventListener('mousemove', this._onMouseMove);\n if (document.pointerLockElement === canvas) document.exitPointerLock();\n this._host = null;\n }\n\n /** Place the camera for this frame. Call after the target has moved. */\n update(_dt: number): void {\n if (!this._host) return;\n const t = this._target();\n const yawRad = this.yaw * Math.PI / 180;\n const pitchRad = this.pitch * Math.PI / 180;\n const horiz = this.distance * Math.cos(pitchRad);\n const vert = this.distance * Math.sin(pitchRad);\n const pos = this._scratchPos.set(\n t.x + Math.sin(yawRad) * horiz,\n t.y + this.height + vert,\n t.z + Math.cos(yawRad) * horiz,\n );\n const look = this._scratchLook.set(t.x, t.y + this.height, t.z);\n\n // World pose with -Z towards the look point (the camera convention, for\n // any object), written in the camera's parent space.\n const cam = this._host.camera;\n cam.quaternion.setFromRotationMatrix(_look.lookAt(pos, look, _up));\n const parent = cam.parent;\n if (parent) {\n parent.updateWorldMatrix(true, false);\n cam.quaternion.premultiply(parent.getWorldQuaternion(_parentQuat).invert());\n parent.worldToLocal(pos);\n }\n cam.position.copy(pos);\n cam.updateMatrixWorld();\n }\n\n private _onClickToLock = () => {\n if (!this._inputEnabled || this._pointerLocked || !this._host) return;\n // requestPointerLock returns a Promise in modern browsers. The browser\n // enforces a ~1.25 s cooldown after the user presses Esc to release the\n // lock - re-acquiring inside that window rejects with `SecurityError`.\n // Swallow the rejection: the next click outside the cooldown succeeds.\n // Old browsers return `undefined`, so guard the `.catch`.\n const p = this._host.canvas.requestPointerLock() as Promise<void> | undefined;\n p?.catch(() => { /* post-Esc cooldown - ignore, next click will re-lock */ });\n };\n private _onLockChange = () => {\n this._pointerLocked = !!this._host && document.pointerLockElement === this._host.canvas;\n };\n private _onMouseMove = (e: MouseEvent) => {\n if (!this._inputEnabled || !this._pointerLocked) return;\n this.yaw -= e.movementX * this.mouseSensitivity;\n this.pitch = Math.max(-30, Math.min(70, this.pitch + e.movementY * this.mouseSensitivity));\n };\n}\n", "import type { Character } from '../../character';\nimport type { RevealLook } from '../../splat/reveal-look';\n\n/**\n * What {@link playReveal} drives: a splat {@link Character} or a mesh\n * character, on either side of a handoff.\n *\n * @group Characters & Animation\n */\nexport type RevealTarget = Pick<Character, 'armature' | 'destroyed' | 'setReveal' | 'setRevealLook'>;\n\n/**\n * How {@link playReveal} animates. Times are milliseconds of wall clock, so a\n * reveal keeps its length through dropped frames.\n *\n * @group Characters & Animation\n */\nexport interface RevealPreset {\n /** Length of a full 0 \u2192 1 sweep. */\n duration: number;\n /** Maps linear progress in [0, 1] to reveal amount in [0, 1]. */\n ease: (t: number) => number;\n /**\n * While any frame takes longer than this, the sweep holds at its start - a\n * character's first frames after loading drop several in a row, and\n * advancing through them would spend the sweep in a few jumps.\n */\n settleFrameMs: number;\n /** Longest the sweep waits for frames to settle. 0 starts at once. */\n settleTimeoutMs: number;\n /** Length {@link RevealRun.speedUp} shortens a full sweep to. */\n interruptedDuration: number;\n /** Applied to both characters when the run starts. Unset keeps their own. */\n look?: RevealLook;\n}\n\n/** Quadratic ease-out. */\nconst easeOut = (t: number): number => 1 - (1 - t) * (1 - t);\n\n/**\n * The engine's default reveal timing.\n *\n * @group Characters & Animation\n */\nexport const DEFAULT_REVEAL_PRESET: Readonly<RevealPreset> = Object.freeze({\n duration: 500,\n ease: easeOut,\n settleFrameMs: 24,\n settleTimeoutMs: 400,\n interruptedDuration: 180,\n});\n\n/**\n * Options for {@link playReveal}.\n *\n * @group Characters & Animation\n */\nexport interface PlayRevealOptions {\n /** Dissolves on the same clock as the incoming character appears. */\n outgoing?: RevealTarget | null;\n /** Reveal amount to start from, so an interrupted sweep continues. Default 0. */\n from?: number;\n /** Overrides on {@link DEFAULT_REVEAL_PRESET}. */\n preset?: Partial<RevealPreset>;\n /** Called every frame with the incoming character's reveal amount. */\n onProgress?: (amount: number) => void;\n}\n\n/**\n * A running {@link playReveal}.\n *\n * @group Characters & Animation\n */\nexport interface RevealRun {\n /** Resolves true once the sweep completes, false if cancelled first. */\n readonly finished: Promise<boolean>;\n /** The incoming character's current reveal amount. */\n readonly amount: number;\n /** Finish the rest of the sweep at the pace of a `ms` full sweep. */\n speedUp(ms?: number): void;\n /** Stop where it is. Both characters keep their current reveal amount. */\n cancel(): void;\n}\n\n/**\n * Reveal `incoming` - a bright front walking its skeleton from feet to head -\n * and, given an `outgoing` character, dissolve that one on the same clock so\n * one character hands off to the next. Runs on the engine's update loop\n * ({@link SplatEngine.update}, which `Scene` calls every frame).\n *\n * The caller keeps ownership: nothing is destroyed or hidden when the run\n * ends. Call {@link Character.prepareReveal} after loading so the first frame\n * of the sweep does not pay the one-time setup.\n *\n * @example\n * ```ts\n * const next = await Character.load(scene, url);\n * next.setReveal(0);\n * const run = playReveal(next, { outgoing: current });\n * if (await run.finished) current.destroy();\n * ```\n *\n * @group Characters & Animation\n */\nexport function playReveal(incoming: RevealTarget, options: PlayRevealOptions = {}): RevealRun {\n const preset: RevealPreset = { ...DEFAULT_REVEAL_PRESET, ...options.preset };\n const outgoing = options.outgoing ?? null;\n const from = Math.min(1, Math.max(0, options.from ?? 0));\n const engine = incoming.armature.engine;\n\n if (preset.look) {\n incoming.setRevealLook(preset.look);\n outgoing?.setRevealLook(preset.look);\n }\n\n let amount = from;\n // A sweep that starts part-way is shorter by the part already shown.\n let duration = preset.duration * (1 - from);\n let progress = 0;\n let previous = performance.now();\n const started = previous;\n let done = false;\n let resolve!: (completed: boolean) => void;\n const finished = new Promise<boolean>((r) => { resolve = r; });\n\n const apply = (value: number) => {\n amount = value;\n incoming.setReveal(value);\n outgoing?.setReveal(value, true);\n options.onProgress?.(value);\n };\n const end = (completed: boolean) => {\n if (done) return;\n done = true;\n removeTick?.();\n resolve(completed);\n };\n function tick() {\n if (done) return;\n // A destroyed character's textures are gone; writing its reveal would throw.\n if (incoming.destroyed || outgoing?.destroyed) {\n end(false);\n return;\n }\n const now = performance.now();\n const gap = now - previous;\n previous = now;\n if (progress === 0 && gap > preset.settleFrameMs\n && now - started < preset.settleTimeoutMs) {\n return;\n }\n progress = duration > 0 ? Math.min(1, progress + Math.max(0, gap) / duration) : 1;\n apply(from + (1 - from) * preset.ease(progress));\n if (progress >= 1) end(true);\n }\n\n let removeTick: (() => void) | null = null;\n if (!engine || duration <= 0) {\n // Straight to the end: setting `from` first would opt both characters in.\n apply(1);\n end(true);\n } else {\n apply(from);\n removeTick = engine.addUpdater(tick);\n }\n\n return {\n finished,\n get amount() { return amount; },\n speedUp(ms = preset.interruptedDuration) {\n duration = Math.min(duration, ms * (1 - from));\n },\n cancel() { end(false); },\n };\n}\n", "/**\n * Coarse body-part segmentation used by the damage / variant system.\n *\n * Each bone in the skeleton is classified into one of {@link BodyPart}.\n * A {@link Splat} stores the dominant-bone group per gaussian; at runtime\n * the variant-mask uniform decides per-group whether to render the splat\n * from the \"normal\" cloud or the \"damaged\" cloud. The `DamageVariant`\n * preset (`presets/character/damage-variant.ts`) is the system built on\n * this: `DamageVariant.create` / `setBodyPartDamaged`.\n *\n * The enum values are stable group IDs used directly as texture coords on\n * the variant-mask texture - do not renumber without updating shaders.\n *\n * @group Characters & Animation\n */\n// A const object rather than a TS `enum`: this source is consumed directly\n// (not prebuilt) by apps compiling with `erasableSyntaxOnly`, which rejects\n// `enum` because it emits runtime code. The const-object + union-type pair\n// keeps both the `BodyPart.Head` value form and the `BodyPart` type form\n// working at call sites, and preserves the numeric group IDs exactly.\nexport const BodyPart = {\n Torso: 0,\n Head: 1,\n LeftUpperArm: 2,\n LeftLowerArm: 3,\n LeftHand: 4,\n RightUpperArm: 5,\n RightLowerArm: 6,\n RightHand: 7,\n LeftUpperLeg: 8,\n LeftLowerLeg: 9,\n LeftFoot: 10,\n RightUpperLeg: 11,\n RightLowerLeg: 12,\n RightFoot: 13,\n} as const;\n\n/** One of the {@link BodyPart} group IDs. */\nexport type BodyPart = (typeof BodyPart)[keyof typeof BodyPart];\n\n/** Width of the per-character variant-mask texture (= max group ID + 1). */\nexport const NUM_BODY_PARTS = 14;\n\nconst SUFFIX_LEFT = /(_l|_left|\\.l|\\.left)$/i;\nconst SUFFIX_RIGHT = /(_r|_right|\\.r|\\.right)$/i;\n\nfunction sideOf(name: string): 'l' | 'r' | null {\n if (SUFFIX_LEFT.test(name)) return 'l';\n if (SUFFIX_RIGHT.test(name)) return 'r';\n return null;\n}\n\n/**\n * Classify a single bone name into a {@link BodyPart}. Pattern-based so it\n * tolerates both the 86-bone std-male rig (clavicle_l, upperarm_l, ...) and\n * the 441-bone rig (FACIAL_* in addition).\n *\n * Returns {@link BodyPart.Torso} for anything we can't confidently bucket\n * (root, unknown auxiliary bones) - Torso is the safest fallback because the\n * spine controls the largest contiguous splat region.\n */\nexport function classifyBone(boneName: string): BodyPart {\n const n = boneName.toLowerCase();\n const side = sideOf(n);\n\n // Head & neck. Facial bones in the 441-rig start with FACIAL_ \u2192 all head.\n if (n.startsWith('facial_') || n === 'head' || n.startsWith('neck')) {\n return BodyPart.Head;\n }\n\n // Torso (pelvis included so hip splats move with the body, not the legs).\n if (n.startsWith('spine') || n === 'pelvis' || n === 'root') {\n return BodyPart.Torso;\n }\n\n // \u2500\u2500 Arms \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (side) {\n // Hands & fingers - any hand_*, *_metacarpal_*, finger names.\n if (\n n.startsWith('hand') ||\n n.includes('metacarpal') ||\n n.startsWith('thumb') ||\n n.startsWith('index_0') ||\n n.startsWith('middle_0') ||\n n.startsWith('ring_0') ||\n n.startsWith('pinky_0')\n ) {\n return side === 'l' ? BodyPart.LeftHand : BodyPart.RightHand;\n }\n if (n.startsWith('lowerarm') || n.includes('forearm')) {\n return side === 'l' ? BodyPart.LeftLowerArm : BodyPart.RightLowerArm;\n }\n if (n.startsWith('upperarm') || n.startsWith('clavicle') || n.startsWith('shoulder')) {\n return side === 'l' ? BodyPart.LeftUpperArm : BodyPart.RightUpperArm;\n }\n\n // \u2500\u2500 Legs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (\n n.startsWith('foot') ||\n n.startsWith('ball') ||\n n.includes('toe')\n ) {\n return side === 'l' ? BodyPart.LeftFoot : BodyPart.RightFoot;\n }\n if (n.startsWith('calf') || n.startsWith('shin') || n.startsWith('lowerleg')) {\n return side === 'l' ? BodyPart.LeftLowerLeg : BodyPart.RightLowerLeg;\n }\n if (n.startsWith('thigh') || n.startsWith('upperleg')) {\n return side === 'l' ? BodyPart.LeftUpperLeg : BodyPart.RightUpperLeg;\n }\n }\n\n return BodyPart.Torso;\n}\n\n/**\n * Build a Uint8Array of length `boneNames.length` where entry `i` is the\n * group ID for bone `i`. Cheap (single pass, regex-based) - call once per\n * armature/splat-asset combination.\n */\nexport function buildBoneToGroup(boneNames: readonly string[]): Uint8Array {\n const out = new Uint8Array(boneNames.length);\n for (let i = 0; i < boneNames.length; i++) {\n out[i] = classifyBone(boneNames[i] ?? '');\n }\n return out;\n}\n\n/** Human-readable label for a body part (debug overlays, UI). */\nexport function bodyPartLabel(p: BodyPart): string {\n switch (p) {\n case BodyPart.Torso: return 'Torso';\n case BodyPart.Head: return 'Head';\n case BodyPart.LeftUpperArm: return 'L Upper Arm';\n case BodyPart.LeftLowerArm: return 'L Lower Arm';\n case BodyPart.LeftHand: return 'L Hand';\n case BodyPart.RightUpperArm: return 'R Upper Arm';\n case BodyPart.RightLowerArm: return 'R Lower Arm';\n case BodyPart.RightHand: return 'R Hand';\n case BodyPart.LeftUpperLeg: return 'L Upper Leg';\n case BodyPart.LeftLowerLeg: return 'L Lower Leg';\n case BodyPart.LeftFoot: return 'L Foot';\n case BodyPart.RightUpperLeg: return 'R Upper Leg';\n case BodyPart.RightLowerLeg: return 'R Lower Leg';\n case BodyPart.RightFoot: return 'R Foot';\n }\n}\n\n/** Iteration helper - all defined body parts in stable order. */\nexport const ALL_BODY_PARTS: readonly BodyPart[] = [\n BodyPart.Torso,\n BodyPart.Head,\n BodyPart.LeftUpperArm,\n BodyPart.LeftLowerArm,\n BodyPart.LeftHand,\n BodyPart.RightUpperArm,\n BodyPart.RightLowerArm,\n BodyPart.RightHand,\n BodyPart.LeftUpperLeg,\n BodyPart.LeftLowerLeg,\n BodyPart.LeftFoot,\n BodyPart.RightUpperLeg,\n BodyPart.RightLowerLeg,\n BodyPart.RightFoot,\n];\n", "import type { Character } from '../../character';\nimport type { BoneScaleInput } from '../../skeletal/bone-stretch';\nimport {\n ALL_BODY_PARTS,\n BodyPart,\n NUM_BODY_PARTS,\n buildBoneToGroup,\n} from '../../skeletal/body-parts';\n\n// \u2500\u2500 ProportionSpec: the compact body-proportion vocabulary \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Ported from the proportion-preset tables our earlier character products\n// shipped, so the numbers here are the ones already tuned against this rig. A\n// spec is what a body-shape preset stores; buildStretch() expands it into the\n// per-bone factors Armature.setBoneStretch consumes.\n\nconst SPINE_BONES = ['spine_01', 'spine_02', 'spine_03', 'spine_04', 'spine_05'] as const;\nconst NECK_BONES = ['neck_01', 'neck_02'] as const;\nconst ARM_BONES = ['upperarm_l', 'upperarm_r', 'lowerarm_l', 'lowerarm_r'] as const;\nconst LEG_BONES = ['thigh_l', 'thigh_r', 'calf_l', 'calf_r'] as const;\nconst HAND_BONES = ['hand_l', 'hand_r'] as const;\nconst FOOT_BONES = ['foot_l', 'foot_r', 'ball_l', 'ball_r'] as const;\n\n/**\n * A body-proportion preset, parameterized over the rig's humanoid bones.\n * `along` lengthens a segment; girth (width + thickness) fattens it.\n * Spine girth tapers linearly from `torsoGirthBase` (hips, spine_01) to\n * `torsoGirthTop` (chest, spine_05) so the silhouette can be pyramid-shaped.\n * Every value is a multiplier (1 = unchanged).\n *\n * @group Characters & Animation\n */\nexport interface ProportionSpec {\n /** Uniform scale for the head bone + every FACIAL_* bone. */\n head: number;\n /** Lengthen the spine segments. */\n torsoAlong: number;\n /** Spine cross-section at the hips (spine_01). Default 1. */\n torsoGirthBase?: number;\n /** Spine cross-section at the chest (spine_05). Default = torsoGirthBase. */\n torsoGirthTop?: number;\n /** Lengthen the neck. Default = torsoAlong. */\n neckAlong?: number;\n /** Base length for arms + legs. */\n limbAlong: number;\n /** Base cross-section for arms + legs. Default 1. */\n limbGirth?: number;\n /** Override arm length / cross-section. Default = limb*. */\n armAlong?: number;\n armGirth?: number;\n /** Override leg length / cross-section. Default = limb*. */\n legAlong?: number;\n legGirth?: number;\n /** Uniform scale on hand_l/r. Default 1 (unchanged). */\n hands?: number;\n /** Uniform scale on foot_l/r + ball_l/r. Default 1 (unchanged). */\n feet?: number;\n /**\n * Degrees to swing the upper arms out from the torso each frame. Fattening\n * the belly doesn't move the shoulders, so heavy builds need this to keep\n * the arms from sinking into the gut. NOT applied by buildStretch (it's an\n * animation-layer concern, not a bone scale); stored on the spec so presets\n * round-trip it. Default 0.\n */\n armOutDeg?: number;\n}\n\n/**\n * Expand a {@link ProportionSpec} into the `{ boneName: scale }` map\n * {@link Armature.setBoneStretch} consumes. Encodes the spine-girth taper and\n * all the per-limb defaults, so the compact spec is meaningless without it.\n * `boneNames` = the loaded rig's actual bones (use `armature.rigBoneNames` so\n * the 441-bone facial rig resolves correctly); optional extremities\n * (hands/feet/FACIAL_*) are only written when present.\n *\n * @group Characters & Animation\n */\nexport function buildStretch(\n boneNames: readonly string[],\n spec: ProportionSpec,\n): Record<string, BoneScaleInput> {\n const girthBase = spec.torsoGirthBase ?? 1;\n const girthTop = spec.torsoGirthTop ?? girthBase;\n const armAlong = spec.armAlong ?? spec.limbAlong;\n const armGirth = spec.armGirth ?? spec.limbGirth ?? 1;\n const legAlong = spec.legAlong ?? spec.limbAlong;\n const legGirth = spec.legGirth ?? spec.limbGirth ?? 1;\n\n const has = new Set(boneNames);\n const factors: Record<string, BoneScaleInput> = { head: spec.head };\n\n // Spine girth lerps from hips (spine_01) to chest (spine_05).\n SPINE_BONES.forEach((name, i) => {\n const t = i / (SPINE_BONES.length - 1); // 0 at hips \u2192 1 at chest\n const g = girthBase + (girthTop - girthBase) * t;\n factors[name] = { along: spec.torsoAlong, width: g, thickness: g };\n });\n for (const name of NECK_BONES) factors[name] = { along: spec.neckAlong ?? spec.torsoAlong };\n for (const name of ARM_BONES) factors[name] = { along: armAlong, width: armGirth, thickness: armGirth };\n for (const name of LEG_BONES) factors[name] = { along: legAlong, width: legGirth, thickness: legGirth };\n // Extremities are guarded - not every rig has hand/foot/ball bones.\n if (spec.hands !== undefined) for (const name of HAND_BONES) if (has.has(name)) factors[name] = spec.hands;\n if (spec.feet !== undefined) for (const name of FOOT_BONES) if (has.has(name)) factors[name] = spec.feet;\n // Face scales with the head.\n for (const name of boneNames) if (name.startsWith('FACIAL_')) factors[name] = spec.head;\n\n return factors;\n}\n\n// \u2500\u2500 Legacy uniform per-body-part vocabulary (kept for wire compat) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Stable string keys for {@link BodyPart} - the wire vocabulary of the legacy\n * flat `{part \u2192 multiplier}` shape. Prefer {@link ProportionSpec} presets.\n *\n * @group Characters & Animation\n */\nexport const BODY_PART_SLUGS: readonly (readonly [string, BodyPart])[] = [\n ['torso', BodyPart.Torso],\n ['head', BodyPart.Head],\n ['left_upper_arm', BodyPart.LeftUpperArm],\n ['left_lower_arm', BodyPart.LeftLowerArm],\n ['left_hand', BodyPart.LeftHand],\n ['right_upper_arm', BodyPart.RightUpperArm],\n ['right_lower_arm', BodyPart.RightLowerArm],\n ['right_hand', BodyPart.RightHand],\n ['left_upper_leg', BodyPart.LeftUpperLeg],\n ['left_lower_leg', BodyPart.LeftLowerLeg],\n ['left_foot', BodyPart.LeftFoot],\n ['right_upper_leg', BodyPart.RightUpperLeg],\n ['right_lower_leg', BodyPart.RightLowerLeg],\n ['right_foot', BodyPart.RightFoot],\n];\n\nconst SLUG_TO_PART: ReadonlyMap<string, BodyPart> = new Map(BODY_PART_SLUGS);\n\n/**\n * Body-shape preview driver for one {@link Character}: expands a\n * {@link ProportionSpec} (or a legacy flat per-part map) and applies it via\n * {@link Armature.setBoneStretch}. Cheap enough for live slider dragging.\n *\n * @example\n * ```ts\n * const shape = BodyShapeVariant.create(character);\n * shape.setSpec({ head: 1.6, torsoAlong: 0.7, limbAlong: 0.5, torsoGirthBase: 1.35 });\n * shape.reset();\n * shape.destroy();\n * ```\n *\n * @group Characters & Animation\n */\nexport class BodyShapeVariant {\n private readonly _character: Character;\n private readonly _boneNames: readonly string[];\n /** Bone names per body part (legacy flat-map path), `[BodyPart] \u2192 names`. */\n private readonly _partBoneNames: string[][];\n\n private constructor(character: Character, boneNames: readonly string[]) {\n this._character = character;\n this._boneNames = boneNames;\n const boneToGroup = buildBoneToGroup(boneNames);\n this._partBoneNames = Array.from({ length: NUM_BODY_PARTS }, () => []);\n const n = Math.min(character.armature.numBones, boneToGroup.length);\n for (let i = 0; i < n; i++) this._partBoneNames[boneToGroup[i]].push(boneNames[i]);\n }\n\n /**\n * Bind to the host character's rig. Synchronous - the armature must already\n * be attached to an engine, whose skeleton library names its bones\n * (441-bone facial rigs resolve through `armature.rigBoneNames`).\n */\n static create(character: Character): BodyShapeVariant {\n const names = character.armature.rigBoneNames;\n if (names.length === 0) {\n throw new Error(\n 'BodyShapeVariant.create: no bone names for this rig - the character is not attached to an engine',\n );\n }\n return new BodyShapeVariant(character, names);\n }\n\n /**\n * Apply a {@link ProportionSpec}. Takes effect on the next armature update.\n * `armOutDeg` is carried on the spec but not previewed (animation-layer\n * concern).\n */\n setSpec(spec: ProportionSpec): void {\n this._character.armature.setBoneStretch(buildStretch(this._boneNames, spec));\n this._character.requestSort();\n }\n\n /**\n * Legacy flat shape: uniform multiplier per body part, keyed by\n * {@link BODY_PART_SLUGS} (`'torso'`, `'left_upper_arm'`, \u2026). Unknown keys\n * and non-finite values are ignored. Prefer {@link setSpec}.\n */\n setScalesByName(scales: Record<string, number>): void {\n const factors: Record<string, BoneScaleInput> = {};\n for (const [slug, v] of Object.entries(scales)) {\n const part = SLUG_TO_PART.get(slug);\n if (part === undefined || !Number.isFinite(v) || v === 1) continue;\n for (const name of this._partBoneNames[part]) factors[name] = v;\n }\n this._character.armature.setBoneStretch(Object.keys(factors).length ? factors : null);\n this._character.requestSort();\n }\n\n /** Return the character to its unstretched proportions. */\n reset(): void {\n this._character.armature.setBoneStretch(null);\n this._character.requestSort();\n }\n\n /** Alias of {@link reset} - detach the stretch entirely. */\n destroy(): void {\n this.reset();\n }\n}\n\n// Re-export so preset consumers can iterate parts without a deep import.\nexport { ALL_BODY_PARTS };\n", "// \u2500\u2500 Socket loadout merge (pure - the cross-game base\u2295override layering) \u2500\u2500\u2500\u2500\u2500\n//\n// A character carries a GLOBAL socket loadout (\"wear a hat in every game\")\n// stored on the character record as a socket-name \u2192 item-name map. Each\n// animation clip may then carry its own per-clip socket overrides\n// (`socketItems[]`): an entry can REPLACE the item on a socket for that clip,\n// or REMOVE it. The effective set a game renders while a clip plays is:\n//\n// RESULT[socket] = override wins if present, else the base loadout item;\n// a removal entry drops the socket entirely.\n//\n// This module is the single, dependency-free source of truth for that merge, so\n// every app that renders these characters layers sockets identically instead\n// of re-deriving it. It does NO bone attachment or asset loading - a game feeds\n// the merged result into its own attach driver (bone world matrix \u00D7 the item's\n// socket fit transform, which the host's item manifest supplies).\n//\n// Removal has two accepted wire forms, normalized here:\n// \u2022 `{ socket, hide: true }` - the canonical form.\n// \u2022 `{ socket, item: null }` - the legacy \"reserved/empty slot\" form.\n// Both mean \"remove this socket for the clip\". New authoring should emit\n// `hide: true`; `item: null` stays supported so existing authored data keeps\n// working.\n\n/**\n * A character's global socket loadout: socket name \u2192 item name. This is the\n * BASE layer, applied across every game, and is whatever map the host serves\n * alongside the character record.\n *\n * @group Characters & Animation\n */\nexport type SocketLoadout = Record<string, string>;\n\n/**\n * One per-clip socket override, as authored on an animation's `socketItems[]`.\n * Accepts every in-the-wild shape:\n * \u2022 `{ socket, item }` - replace the socket's item for this clip.\n * \u2022 `{ socket, hide: true }` - remove the socket's item (canonical form).\n * \u2022 `{ socket, item: null }` - remove (legacy form).\n *\n * @group Characters & Animation\n */\nexport interface SocketOverride {\n socket: string;\n /** Item name to place on the socket; `null`/absent (with no explicit item) reads as a removal. */\n item?: string | null;\n /** When true, remove this socket's item for the clip regardless of `item`. */\n hide?: boolean;\n}\n\n/**\n * The resolved item to attach to a socket for the current clip - always a\n * concrete item name (removals are already dropped).\n *\n * @group Characters & Animation\n */\nexport interface ResolvedSocketItem {\n socket: string;\n item: string;\n}\n\n/**\n * True when an override entry means \"remove this socket\" rather than replace it.\n *\n * @group Characters & Animation\n */\nexport function isSocketRemoval(o: SocketOverride): boolean {\n // `item == null` catches both null and undefined; a real replace always\n // carries a non-empty item string.\n return o.hide === true || o.item == null;\n}\n\n/**\n * Merge a character's global base loadout with a clip's per-clip socket\n * overrides, returning the effective set of items to attach while that clip\n * plays. Override wins per socket (replace, or remove via `hide:true`/`item:null`);\n * sockets untouched by the clip keep their base item.\n *\n * Order-independent by socket (one item per socket). Passing `base = null`\n * yields the clip's own items minus any removals - a safe drop-in for a game\n * that has no base loadout yet.\n *\n * @example\n * // base: hat on head; clip swaps in a crown and removes the hat's socket via a helmet\n * mergeSocketLoadout(\n * { head: 'wizard_hat', back: 'cape' },\n * [{ socket: 'head', item: 'gold_crown' }, { socket: 'hand_r', item: 'sword' }],\n * )\n * // => [{socket:'head',item:'gold_crown'}, {socket:'back',item:'cape'}, {socket:'hand_r',item:'sword'}]\n *\n * @group Characters & Animation\n */\nexport function mergeSocketLoadout(\n base: SocketLoadout | null | undefined,\n overrides: readonly SocketOverride[] | null | undefined,\n): ResolvedSocketItem[] {\n const bySocket = new Map<string, string>(); // socket \u2192 item name\n\n if (base) {\n for (const socket of Object.keys(base)) {\n const item = base[socket];\n if (item) bySocket.set(socket, item);\n }\n }\n\n if (overrides) {\n for (const o of overrides) {\n if (!o || !o.socket) continue;\n if (isSocketRemoval(o)) {\n bySocket.delete(o.socket);\n } else {\n // `item` is a non-null string here (isSocketRemoval ruled out null/undefined).\n bySocket.set(o.socket, o.item as string);\n }\n }\n }\n\n const out: ResolvedSocketItem[] = [];\n for (const [socket, item] of bySocket) out.push({ socket, item });\n return out;\n}\n", "import { BufferAttribute, BufferGeometry, DynamicDrawUsage, LineBasicMaterial, LineSegments } from 'three';\n\nimport type { Armature } from '../../armature';\nimport type { Scene } from '../../scene';\n\n/**\n * Configuration for {@link BoneOverlay.create}.\n *\n * @group Presets\n */\nexport interface BoneOverlayOptions {\n /** Line color as CSS hex (e.g. `#40ffa0`). Default `#40ffa0`. */\n color?: string;\n /** Include `FACIAL_*` bones from the full 441-bone rig. Default `false` -\n * the ~356 facial bones collapse into an unreadable blob at body scale. */\n includeFacial?: boolean;\n /** Start enabled. Default `false`. */\n enabled?: boolean;\n}\n\nconst FACIAL_PREFIX = 'FACIAL_';\n\n/** Drawn after everything else, so the skeleton reads on top of the splats. */\nconst OVERLAY_RENDER_ORDER = 1e6;\n\n/**\n * Debug skeleton visualization: draws one line per parent\u2192child bone pair of\n * an {@link Armature}, on top of everything (no depth test), refreshed every\n * frame from the armature's bone matrices.\n *\n * Attach/detach armatures freely - the overlay survives character swaps:\n *\n * ```ts\n * const bones = BoneOverlay.create(scene, { color: '#40ffa0' });\n * bones.armature = character.armature;\n * bones.enabled = true;\n * ```\n *\n * @group Presets\n */\nexport class BoneOverlay {\n /** Draw the overlay this frame? Cheap to toggle - no scene graph churn. */\n enabled: boolean;\n\n private _armature: Armature | null = null;\n private readonly _material: LineBasicMaterial;\n private readonly _lines: LineSegments;\n private readonly _includeFacial: boolean;\n /** Per-bone draw filter, rebuilt when the armature (rig) changes. */\n private _boneVisible: boolean[] = [];\n private readonly _offUpdate: () => void;\n\n /** Create a bone overlay bound to `scene`. Assign {@link armature} to pick\n * which rig it draws. */\n static create(scene: Scene, opts?: BoneOverlayOptions): BoneOverlay {\n return new BoneOverlay(scene, opts);\n }\n\n private constructor(scene: Scene, opts?: BoneOverlayOptions) {\n this._includeFacial = opts?.includeFacial ?? false;\n this.enabled = opts?.enabled ?? false;\n // depthTest off - the skeleton reads as an overlay on top of the splat,\n // which does not write depth anyway.\n this._material = new LineBasicMaterial({\n color: opts?.color ?? '#40ffa0',\n depthTest: false,\n depthWrite: false,\n transparent: true,\n });\n const geometry = new BufferGeometry().setAttribute('position', new BufferAttribute(new Float32Array(0), 3));\n this._lines = new LineSegments(geometry, this._material);\n this._lines.name = 'boneOverlay';\n this._lines.frustumCulled = false;\n this._lines.renderOrder = OVERLAY_RENDER_ORDER;\n this._lines.visible = false;\n scene.threeScene.add(this._lines);\n this._offUpdate = scene.on('update', () => this._draw());\n }\n\n /** The rig being visualized. Set `null` to blank the overlay (e.g. between\n * character swaps) without destroying it. */\n get armature(): Armature | null {\n return this._armature;\n }\n\n set armature(a: Armature | null) {\n this._armature = a;\n this._boneVisible = [];\n }\n\n /** Change the line color at runtime. */\n setColor(hex: string): void {\n this._material.color.set(hex);\n }\n\n /** Unhook from the scene's update loop and remove the lines. The overlay is unusable afterwards. */\n destroy(): void {\n this._offUpdate();\n this._armature = null;\n this._lines.removeFromParent();\n this._lines.geometry.dispose();\n this._material.dispose();\n }\n\n /** Which bones to draw: all, or all but the facial ones. */\n private _resolveFilter(arm: Armature): boolean[] {\n const numBones = arm.numBones;\n const visible: boolean[] = Array.from({ length: numBones }, () => true);\n if (this._includeFacial) return visible;\n const names = arm.rigBoneNames;\n const n = Math.min(numBones, names.length);\n for (let i = 0; i < n; i++) {\n if (names[i].startsWith(FACIAL_PREFIX)) visible[i] = false;\n }\n return visible;\n }\n\n private _draw(): void {\n const lines = this._lines;\n lines.visible = false;\n if (!this.enabled) return;\n const arm = this._armature;\n const parents = arm?.armatureData.stdMaleParents;\n if (!arm || !parents) return;\n\n const numBones = arm.numBones;\n if (this._boneVisible.length !== numBones) this._boneVisible = this._resolveFilter(arm);\n\n // Grow the vertex buffer to the worst case once, then reuse it. A new\n // geometry rather than a new attribute, which renderers cache per geometry.\n let attr = lines.geometry.getAttribute('position') as BufferAttribute;\n if (attr.count < numBones * 2) {\n attr = new BufferAttribute(new Float32Array(numBones * 2 * 3), 3).setUsage(DynamicDrawUsage);\n lines.geometry.dispose();\n lines.geometry = new BufferGeometry().setAttribute('position', attr);\n }\n const out = attr.array as Float32Array;\n\n let n = 0;\n for (let i = 0; i < numBones; i++) {\n const pi = parents[i];\n if (pi < 0 || !this._boneVisible[i] || !this._boneVisible[pi]) continue;\n const childM = arm.getBoneWorldMatrix(i);\n const parentM = arm.getBoneWorldMatrix(pi);\n if (!childM || !parentM) continue;\n out.set(parentM.data.subarray(12, 15), n * 3);\n out.set(childM.data.subarray(12, 15), n * 3 + 3);\n n += 2;\n }\n if (n === 0) return;\n\n attr.needsUpdate = true;\n lines.geometry.setDrawRange(0, n);\n lines.visible = true;\n }\n}\n", "import { Color, Mesh, MeshBasicMaterial, SphereGeometry } from 'three';\nimport type { Object3D } from 'three';\n\nimport type { IVfxInstance, IVfxPrefab } from '../../effects/vfx/prefab';\nimport { applyBlend, setEmissive } from '../../effects/vfx/layers/shared';\nimport type { Scene } from '../../scene';\nimport type { Vec3Like } from '../camera/camera-preset';\n\n/**\n * Options for {@link MeshFlash}.\n *\n * @group Effects\n */\nexport interface MeshFlashOptions {\n /** Total lifetime in seconds. Default 0.4. */\n duration?: number;\n /** Base RGB emissive color (0..1). Default `[1.0, 0.8, 0.4]` (warm spark). */\n color?: [number, number, number];\n /** Peak radius the sphere grows to. Default 0.5 (world units). */\n peakRadius?: number;\n}\n\n/**\n * Generic VFX builtin: an additively-blended sphere that grows from a tiny\n * point to {@link MeshFlashOptions.peakRadius peakRadius}, then vanishes.\n * Useful for hit-sparks, pickup glows, small impact highlights.\n *\n * Its opacity ramps down over the lifetime, as in the PlayCanvas build,\n * where additive blending ignores opacity: the flash draws at full colour\n * until it ends. Kept, since that is the look effects were tuned against.\n *\n * Single shared material per pool - `setColor` mutates it, so all currently\n * active flashes in one pool render the same tint. That keeps the cost flat\n * and is the right trade-off for one-shot effects.\n *\n * ```ts\n * import { VfxStage, MeshFlash } from '@viggle/splat-engine-three';\n *\n * const stage = new VfxStage(scene);\n * stage.register('flash', new MeshFlash({ color: [1, 0.6, 0.2] }));\n * stage.play('flash', somePosition);\n * ```\n *\n * @group Effects\n */\nexport class MeshFlash implements IVfxPrefab {\n private readonly _duration: number;\n private readonly _peakRadius: number;\n private readonly _material: MeshBasicMaterial;\n /** PlayCanvas's sphere primitive: radius 0.5, 16 x 16 bands. */\n private readonly _geometry = new SphereGeometry(0.5, 16, 16);\n\n constructor(opts: MeshFlashOptions = {}) {\n this._duration = opts.duration ?? 0.4;\n this._peakRadius = opts.peakRadius ?? 0.5;\n this._material = new MeshBasicMaterial({\n color: setEmissive(new Color(), opts.color ?? [1.0, 0.8, 0.4], 1),\n depthWrite: false,\n opacity: 1,\n });\n applyBlend(this._material, true);\n }\n\n create(_scene: Scene, parent: Object3D): IVfxInstance {\n return new MeshFlashInstance(parent, this._geometry, this._material, this._duration, this._peakRadius);\n }\n\n /** Update the shared emissive color in-place. Affects all active instances. */\n setColor(rgb: [number, number, number]): void {\n setEmissive(this._material.color, rgb, 1);\n }\n\n dispose(): void {\n this._material.dispose();\n this._geometry.dispose();\n }\n}\n\nclass MeshFlashInstance implements IVfxInstance {\n private readonly _mesh: Mesh;\n private readonly _material: MeshBasicMaterial;\n private readonly _duration: number;\n private readonly _peakRadius: number;\n private _baseScale = 1;\n private _age = 0;\n\n constructor(parent: Object3D, geometry: SphereGeometry, material: MeshBasicMaterial, duration: number, peakRadius: number) {\n this._material = material;\n this._duration = duration;\n this._peakRadius = peakRadius;\n this._mesh = new Mesh(geometry, material);\n this._mesh.name = 'vfx-flash';\n this._mesh.visible = false;\n parent.add(this._mesh);\n }\n\n spawn(pos: Vec3Like): void {\n this._mesh.position.set(pos.x, pos.y, pos.z);\n this._age = 0;\n // Sphere primitive has unit diameter (radius 0.5). Start near-zero.\n this._mesh.scale.setScalar(0.05 * this._baseScale);\n this._mesh.visible = true;\n }\n\n update(dt: number): boolean {\n this._age += dt;\n const t = this._age / this._duration;\n if (t >= 1) return true;\n // Ease-out scale 0.05 \u2192 peak.\n const k = 1 - (1 - t) * (1 - t);\n this._mesh.scale.setScalar((0.05 + (this._peakRadius * 2 - 0.05) * k) * this._baseScale);\n this._material.opacity = 1 - t;\n return false;\n }\n\n reset(): void {\n this._mesh.visible = false;\n }\n\n dispose(): void {\n this._mesh.removeFromParent();\n }\n\n setScale(s: number): void {\n this._baseScale = s;\n }\n}\n", "import type { GLTF, GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';\n\nimport { cachedFetch } from './bin-cache';\n\nlet glbLoader: GLTFLoader | null = null;\n\n/**\n * Use `loader` for {@link loadGlbFromUrl} - one configured with a\n * `DRACOLoader`, `KTX2Loader` or `MeshoptDecoder` for GLBs that need them.\n *\n * @group Loaders\n */\nexport function setGlbLoader(loader: GLTFLoader): void {\n glbLoader = loader;\n}\n\n/** Callback form of {@link loadGlbFromUrl}: `(error message, null)` or `(null, gltf)`. */\nexport type GlbCallback = (err: string | null, gltf: GLTF | null) => void;\n\n/**\n * Load a `.glb` through the engine's asset cache (so it is served from the\n * persistent cache like characters and clips) and parse it with three.js's\n * `GLTFLoader`. Add `gltf.scene` to your scene, or clone it per use.\n *\n * The PlayCanvas build's `loadGlbFromUrl(app, url, callback)` handed back a\n * container asset; this resolves the parsed `GLTF`. That call shape still\n * works - the leading argument is accepted and not needed - and so does the\n * callback, alongside the returned promise.\n *\n * @example\n * ```ts\n * const gltf = await loadGlbFromUrl('/assets/sword.glb');\n * character.object3D.add(gltf.scene);\n * ```\n *\n * @group Loaders\n */\nexport function loadGlbFromUrl(url: string, callback?: GlbCallback): Promise<GLTF>;\nexport function loadGlbFromUrl(host: unknown, url: string, callback?: GlbCallback): Promise<GLTF>;\nexport function loadGlbFromUrl(a: unknown, b?: string | GlbCallback, c?: GlbCallback): Promise<GLTF> {\n const url = typeof b === 'string' ? b : a as string;\n const callback = typeof b === 'string' ? c : b;\n const loading = cachedFetch(url).then(async (res) => {\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n const buffer = await res.arrayBuffer();\n // Resources a GLB references outside itself resolve next to it.\n const base = url.slice(0, url.lastIndexOf('/') + 1);\n // Imported on first use, so the package itself needs no `three/addons`\n // mapping: an app that never loads a GLB never fetches the loader.\n glbLoader ??= new (await import('three/addons/loaders/GLTFLoader.js')).GLTFLoader();\n return glbLoader.parseAsync(buffer, base);\n });\n if (callback) {\n loading.then((gltf) => callback(null, gltf), (err: unknown) => callback(String(err), null));\n }\n return loading;\n}\n", "import {\n BasicShadowMap,\n Bone,\n Box3,\n BufferAttribute,\n BufferGeometry,\n Color,\n DataTexture,\n DirectionalLight,\n LinearSRGBColorSpace,\n Matrix4,\n Mesh,\n MeshMatcapMaterial,\n PCFShadowMap,\n PointLight,\n SRGBColorSpace,\n Skeleton,\n SkinnedMesh,\n Uint16BufferAttribute,\n VSMShadowMap,\n Vector3,\n} from 'three';\nimport type { Camera, InstancedMesh, Light, Object3D, PerspectiveCamera } from 'three';\n\nimport type { Character } from '../character';\nimport { Environment } from '../environment';\nimport { cropInputToWorldBox } from '../proxy/environment-input';\nimport { maxAxisScale, proxyInputFromEnvironment } from '../proxy/environment-source';\nimport type { EnvironmentProxySource } from '../proxy/environment-source';\nimport { ProxyMeshDebug } from '../proxy/proxy-debug';\nimport { proxyInputFromSplat } from '../proxy/splat-source';\nimport { buildProxyMesh, defaultProxySettings } from '../proxy/voxelizer';\nimport type { ProxyMeshInput, ProxyMeshResult, ProxySurfaceStyle } from '../proxy/voxelizer';\nimport type { Scene } from '../scene';\nimport { Splat } from '../splat/splat';\nimport { RELIGHT_PROXY_LAYER, RELIGHT_VISIBILITY_LAYER, RelightPass, relightBackendFor } from './relight-pass';\nimport { createProxyShadowBias } from './shadow-bias';\nimport type { EnvironmentRefreshMode, RelightConsumer } from './relight-pass';\n\n/**\n * What {@link SplatRelight.preview} shows.\n *\n * - `off` - nothing.\n * - `voxels` - the exact voxel cell boundary as lines, blocky and unsmoothed\n * whatever surface the proxy uses. This is what `voxelSize` is judged\n * against.\n * - `mesh` - the proxy surface the lighting is rendered from, solid, with its\n * own headlight shading, drawn over the splats and skinned by the same\n * skeleton as the real proxy.\n *\n * @group Lighting\n */\nexport type RelightPreviewMode = 'off' | 'voxels' | 'mesh';\n\n/**\n * Something {@link SplatRelight.add} can light: a {@link Character}, whose\n * proxy is skinned by its armature; a lone {@link Splat}, whose proxy is a\n * static mesh under the splat's object; or an {@link Environment}, whose proxy\n * is a static mesh under the environment's object, voxelized coarser and with\n * a solid floor - see {@link ENVIRONMENT_PROXY_DEFAULTS}.\n *\n * @group Lighting\n */\nexport type RelightTarget = Character | Splat | Environment;\n\n/** {@link RelightLightOptions.shadowType} values. */\ntype RelightShadowType = 'pcf1' | 'pcf3' | 'pcf5' | 'vsm16' | 'vsm32';\n\n/**\n * The voxelizer settings an {@link Environment} target takes in place of the\n * component-wide ones, unless {@link RelightTargetOptions.proxy} overrides\n * them. Every other knob follows the component.\n *\n * - `voxelSize: 0.1` m. The character default of 0.025 m resolves a finger; a\n * receiver for a character's shadow needs the floor and the walls, not their\n * texture. Measured on the bundled `chamber.spz` (1.2M splats) cropped to its\n * room: 0.03 m is ~500k triangles and ~100 ms to build; 0.1 m is 91k\n * triangles in ~33 ms, and the shadow edge on the floor is set by the\n * character's proxy and the capture's splat size, not by this.\n * - `castShadows: false` - see {@link RelightTargetOptions.castShadows}.\n * - `floorFill: true`. A raw voxelization of a capture is a shell: the ground\n * is one voxel thick, with pinholes wherever the capture was sparse, and a\n * shadow falls straight through them.\n *\n * Voxel sizes are in WORLD metres for every static target: an environment\n * loaded at scale 2 is voxelized at half the size in its own units.\n *\n * @group Lighting\n */\nexport const ENVIRONMENT_PROXY_DEFAULTS: Readonly<Pick<RelightProxySettings, 'voxelSize' | 'floorFill'>> =\n Object.freeze({ voxelSize: 0.1, floorFill: true });\n\n/**\n * The LOD level an environment bundle's proxy is voxelized from when\n * {@link RelightTargetOptions.lod} is omitted: `auto`, the coarsest level that\n * is dense enough for the voxel size.\n *\n * Kept for the PlayCanvas build's API: this port's environment proxy reads\n * whatever the environment's splat holds (see {@link RelightTargetOptions.lod}),\n * so the value is recorded and not yet acted on.\n *\n * @group Lighting\n */\nexport const ENVIRONMENT_DEFAULT_LOD: number | 'coarsest' | 'auto' = 'auto';\n\n/**\n * Per-target options for {@link SplatRelight.add}.\n *\n * @group Lighting\n */\nexport interface RelightTargetOptions {\n /**\n * Voxelizer settings for this target only, over the component's (and, for\n * an environment, over {@link ENVIRONMENT_PROXY_DEFAULTS}). Rebuilds only\n * this target. See {@link SplatRelight.setTargetProxySettings}.\n */\n proxy?: Partial<RelightProxySettings>;\n /**\n * Environment only: the world-space box the proxy is built from. Splats\n * outside it are ignored.\n *\n * The voxelizer builds one dense grid over everything it is given, and a\n * capture's extent is set by its floaters: `chamber.spz`'s room is 6 m wide\n * but its splats span 21 m, which coarsens a 0.03 m request to 0.15 m. On a\n * whole game map (`survivor_map.spz` spans 560 x 350 x 830 m) no voxel size\n * is both buildable and useful - crop it to where characters walk.\n */\n bounds?: { min: { x: number; y: number; z: number }; max: { x: number; y: number; z: number } } | null;\n /**\n * Environment LOD bundles only, in the PlayCanvas build: the level to\n * voxelize. This port's streaming bundles voxelize what they have streamed\n * in when the proxy is first built, so the option is accepted and not yet\n * acted on. Default {@link ENVIRONMENT_DEFAULT_LOD}.\n */\n lod?: number | 'coarsest' | 'auto';\n /**\n * Whether this target's proxy casts into the lights' shadow maps. Default\n * `true` for a character or a splat, `false` for an environment.\n *\n * A capture's own occlusion is already in its baked colours - a wall's\n * shadow on the floor is IN the floor's colour - so an environment that also\n * cast would darken it twice. Worse, a closed room's walls and ceiling put\n * its whole interior, and every character in it, in the key light's shadow.\n * What a capture is missing is the shadow of what moves through it, which is\n * what the default keeps. Turn it on to have a character walk into a\n * capture's shade.\n */\n castShadows?: boolean;\n /**\n * Draw this proxy into the screen-space lighting/visibility receiver maps.\n * Default true. Set false for a shadow-only caster whose splats keep their\n * baked appearance: its coarse silhouette must not overwrite lighting on\n * environment splats behind it. It still casts into the shadow maps.\n */\n lightingReceiver?: boolean;\n}\n\n/**\n * Where a target's proxy geometry came from. See {@link SplatRelight.proxySource}.\n *\n * @group Lighting\n */\nexport interface RelightProxySource {\n /** Splats handed to the voxelizer, after any crop. */\n splats: number;\n /** Splats read from the target, before the crop. */\n sourceSplats: number;\n /** LOD level read, `null` unless the target is an LOD bundle. */\n lodLevel: number | null;\n /** Levels available; `1` unless the target is an LOD bundle. */\n lodLevels: number;\n /** Milliseconds reading the source took. */\n loadMs: number;\n}\n\n/**\n * The voxelizer knobs {@link SplatRelight} exposes. Every one of them rebuilds\n * the proxy mesh. See {@link ProxySettings} for what each does.\n *\n * @group Lighting\n */\nexport interface RelightProxySettings {\n /** `blocky` keeps voxel faces; `smooth` runs surface nets. Default `smooth`. */\n surface: ProxySurfaceStyle;\n /** Voxel edge, metres. Default `0.025`. */\n voxelSize: number;\n /** Splats below this alpha do not occupy a voxel. Default `0.04`. */\n opacityThreshold: number;\n /** Voxel rings grown around the occupied set. Default `0`. */\n dilate: number;\n /** Relaxation passes over the surface. Default `3`. */\n smoothIterations: number;\n /** Close the underside of the lowest occupied layer. Default `false`. */\n floorFill: boolean;\n}\n\n/**\n * The key light {@link SplatRelight} owns: a real three.js\n * `DirectionalLight` that both the app's meshes (on its {@link layers}) and\n * the proxies see.\n *\n * Colours and intensities are read the PlayCanvas way, so a scene authored for\n * the PlayCanvas build lights the same: a CSS colour is gamma-space, and the\n * light delivers `linear(colour) * intensity` (`linear(colour * intensity)`\n * below 1) with no 1/pi.\n *\n * @group Lighting\n */\nexport interface RelightLightOptions {\n /** Azimuth in degrees. 0 = +Z, 90 = +X. Default `30`. */\n azimuth?: number;\n /** Elevation in degrees. 0 = horizon, 90 = overhead. Default `60`. */\n elevation?: number;\n /** CSS hex or a `Color` holding gamma-space values. Default `#fff2d9`. */\n color?: string | Color;\n /** Default `1`. */\n intensity?: number;\n /** Shadow map for meshes AND the proxy's cast shadows. Default `true`. */\n castShadows?: boolean;\n /**\n * Metres the shadow map covers from the camera. Default `40`, the\n * PlayCanvas default: the map is fitted every frame around the view frustum\n * out to this distance.\n */\n shadowDistance?: number;\n /** Shadow map texels a side. Default `1024`. */\n shadowResolution?: number;\n /**\n * Depth bias against shadow acne, as PlayCanvas's light component takes it:\n * 0 to 1, default `0.05`, the PlayCanvas default. It is applied as\n * PlayCanvas applies it - a slope-scaled offset of `shadowBias x 10` shadow\n * texels, on a shadow map whose depth range is fitted to its casters - so a\n * number tuned in a PlayCanvas game means the same here. Under\n * {@link shadowBiasMode} `'three'` it is three.js's `shadow.bias` instead.\n */\n shadowBias?: number;\n /**\n * Metres the shadow lookup moves along the surface normal, 0 to 1, as\n * PlayCanvas's `normalOffsetBias`. Default `0`, the PlayCanvas default.\n * Under {@link shadowBiasMode} `'three'` it is three.js's `shadow.normalBias`.\n */\n normalOffsetBias?: number;\n /**\n * `'playcanvas'` (the default): {@link shadowBias} and\n * {@link normalOffsetBias} mean what they mean in PlayCanvas, and the result\n * matches it. `'three'`: they are three.js's `shadow.bias` (default\n * `-0.0005`) and `shadow.normalBias` (default `0`), used as given, on a\n * shadow camera that spans four radii of the shadowed area.\n */\n shadowBiasMode?: 'playcanvas' | 'three';\n /**\n * How the shadow map is filtered, which is where a soft shadow EDGE comes\n * from. Default `pcf3`.\n *\n * This is the lever to reach for before the compose blur. The softness\n * happens in the shadow test, so it widens the penumbra and leaves the\n * terminator across the subject exactly as sharp as it was;\n * {@link SplatRelight.blurRadius} cannot separate the two, because by the\n * time it runs they are the same channel.\n *\n * three.js filters shadows renderer-wide (`renderer.shadowMap.type`), so\n * `pcf1` (basic) and the `vsm` types set that for every light in the app;\n * `pcf3` and `pcf5` are PCF at radius 1 and 2 and change only this light.\n */\n shadowType?: RelightShadowType;\n /** Blur kernel for the `vsm` shadow types, in texels. Default `11`. */\n vsmBlurSize?: number;\n /**\n * How dark the shadow map is allowed to make a surface, `0..1`. Default `1`.\n *\n * The other half of \"the shadow is too black\": this lifts it at the light,\n * so it applies to the proxy render and therefore to everything read out of\n * the lighting channel - meshes in the scene included.\n */\n shadowIntensity?: number;\n /**\n * three.js layers (0..29) this light also lights the app's meshes on,\n * beside the relight layers the component adds itself. Default `[0]`. `[]`\n * keeps the light to the splats alone.\n */\n layers?: number[];\n}\n\n/**\n * A point light. See {@link SplatRelight.addPointLight}.\n *\n * @group Lighting\n */\nexport interface RelightPointLightOptions {\n position?: { x: number; y: number; z: number };\n /** CSS hex or a `Color` holding gamma-space values. Default white. */\n color?: string | Color;\n /** Default `1`. */\n intensity?: number;\n /**\n * Hard cutoff distance, metres. Default `5`. On the proxies the light falls\n * off linearly to it, as in the PlayCanvas build.\n */\n range?: number;\n /** Default `false`: omni shadows are six renders a frame. */\n castShadows?: boolean;\n /** three.js layers it also lights. Default `[0]`. */\n layers?: number[];\n}\n\n/**\n * Per-target overrides of the scene-wide relight knobs. See\n * {@link SplatRelight.setParams}.\n *\n * @group Lighting\n */\nexport interface RelightTargetParams {\n strength?: number;\n shadowStrength?: number;\n ambient?: number;\n /** CSS hex or a `Color`, applied as given - no colour-space conversion. */\n tint?: string | Color;\n}\n\n/**\n * Options for {@link SplatRelight.create}. Every one of them is also a live\n * property; the property notes say which rebuild.\n *\n * @group Lighting\n */\nexport interface SplatRelightOptions {\n /** See {@link SplatRelight.strength}. Default `1`. */\n strength?: number;\n /** See {@link SplatRelight.shadowStrength}. Default `1`. */\n shadowStrength?: number;\n /** See {@link SplatRelight.setTint}. Default white. */\n tint?: string | Color;\n /** See {@link SplatRelight.ambient}. Default `0`. */\n ambient?: number;\n /** See {@link SplatRelight.referenceLuminance}. Default `1`. */\n referenceLuminance?: number;\n /** See {@link SplatRelight.blur}. Default `true`. */\n blur?: boolean;\n /** See {@link SplatRelight.blurRadius}. Default `1`. */\n blurRadius?: number;\n /** See {@link SplatRelight.shadowBlurRadius}. Default `1`. */\n shadowBlurRadius?: number;\n /**\n * The owned key light. Default: one at the {@link RelightLightOptions}\n * defaults. `null` owns none - bring your own and hand them to\n * {@link SplatRelight.addLight}.\n */\n light?: RelightLightOptions | null;\n /**\n * Sky fill. Written to {@link Scene.ambientLight}, which is what both meshes\n * and the relight compose read, so the two can never disagree. Gamma-space,\n * as the scene's `ambientLight` option is: the compose linearizes it the\n * PlayCanvas way. Omit to leave the scene's ambient alone.\n */\n sky?: { color?: string | Color; intensity?: number };\n /** See {@link SplatRelight.resolutionScale}. Default `0.5`. */\n resolutionScale?: number;\n /** See {@link SplatRelight.receiveShadows}. Default `false`. */\n receiveShadows?: boolean;\n /** Voxelizer knobs. Defaults are {@link defaultProxySettings}. */\n proxy?: Partial<RelightProxySettings>;\n /** See {@link SplatRelight.preview}. Default `off`. */\n preview?: RelightPreviewMode;\n /** Camera the splats are viewed through. Default `scene.camera`. */\n mainCamera?: Camera;\n /** See {@link SplatRelight.environmentRefresh}. Default `auto`. */\n environmentRefresh?: EnvironmentRefreshMode;\n}\n\n/** One lit subject, and everything built for it. */\ninterface TargetEntry {\n readonly target: RelightTarget;\n readonly character: Character | null;\n readonly environment: Environment | null;\n /** The object a static proxy is built in the local space of; `null` for a character. */\n readonly node: Object3D | null;\n params: RelightTargetParams | null;\n /** Splats the params were last pushed to - re-pushed when LODs arrive. */\n pushedSplats: number;\n /** This target's voxelizer overrides. */\n proxy: Partial<RelightProxySettings>;\n readonly bounds: RelightTargetOptions['bounds'];\n readonly castShadows: boolean;\n readonly lightingReceiver: boolean;\n\n // \u2500\u2500 CPU \u2500\u2500\n /** An environment's uncropped read, once its splat exists. */\n source: EnvironmentProxySource | null;\n input: ProxyMeshInput | null;\n /** What `input` was read or cut for - the densest level, or the crop. */\n inputKey: string;\n mesh: ProxyMeshResult | null;\n meshKey: string;\n voxels: ProxyMeshResult | null;\n voxelsKey: string;\n /** Settled once `mesh` is first built. */\n readonly ready: Promise<void>;\n resolveReady: () => void;\n\n // \u2500\u2500 GPU \u2500\u2500\n gpuKey: string;\n proxyMesh: Mesh | null;\n skeleton: Skeleton | null;\n previewMesh: Mesh | null;\n debug: ProxyMeshDebug | null;\n /** What `debug` was last handed - `setVoxels` re-derives the edge list. */\n debugVoxels: ProxyMeshResult | null;\n}\n\ninterface LightEntry {\n /** The light's layer mask without any relight layer in it. */\n base: number;\n /** Created by this component, so disposed by it. */\n owned: boolean;\n}\n\n/** Every relight layer, as a mask. */\nconst RELIGHT_LAYER_MASK = (1 << RELIGHT_PROXY_LAYER) | (1 << RELIGHT_VISIBILITY_LAYER);\n\n/** Shadow resolution and distance when the options leave them out - PlayCanvas's defaults. */\nconst DEFAULT_SHADOW_RESOLUTION = 1024;\nconst DEFAULT_SHADOW_DISTANCE = 40;\n\n/**\n * Relighting for gaussian splats: one component that voxelizes a proxy mesh\n * from the splats, renders it with real three.js lights into a screen-space\n * lighting texture, and has every splat sample that texture.\n *\n * ```ts\n * const relight = SplatRelight.create(scene, {\n * light: { azimuth: 38, elevation: 38, intensity: 2.2 },\n * receiveShadows: true,\n * });\n * relight.add(character);\n * relight.voxelSize = 0.04; // rebuilds the proxy next frame\n * relight.strength = 0.5; // uniform, next frame\n * relight.preview = 'mesh';\n * ```\n *\n * The legacy {@link SunLight} / {@link SkyLight} / {@link PointLight} rig is a\n * separate lighting path and is untouched by this one.\n *\n * \u2500\u2500 Two kinds of parameter \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * Uniform-only knobs - `strength`, `shadowStrength`, `ambient`, tint,\n * `referenceLuminance`, `blur`, the key light's direction, colour and\n * intensity, the sky fill - are plain clamped setters and take effect on the\n * next frame with nothing reallocated.\n *\n * Resource-shape knobs - `resolutionScale`, `receiveShadows`, and every\n * voxelizer setting - only mark the component dirty. One idempotent allocator\n * runs at the start of the next frame (or on {@link rebuild}): it re-voxelizes\n * what is stale, tears down whatever holds a reference to the old resource\n * FIRST (the pass's shadowless twins, the preview's shared skeleton), and only\n * then builds the replacement. Several knobs moved in one frame cost one\n * rebuild.\n *\n * \u2500\u2500 Lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * {@link create} hooks the scene's `preRender`, where each frame poses the\n * proxies, renders the lighting and publishes it - before the main render, so\n * the splats it draws sample this frame's light. A canvas resize reallocates\n * the lighting targets on the next frame. {@link destroy} is final.\n * All state lives on the instance - never in module globals.\n *\n * \u2500\u2500 Why generation lives here \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * The proxy exists for lighting only. A collision mesh cannot share it (a\n * convex collider is capped at 255 hull polygons; lighting wants the detail),\n * so there is no second consumer to split a mesh component out for.\n *\n * @group Lighting\n */\nexport class SplatRelight {\n // \u2500\u2500 Uniform-only \u2500\u2500\n private _strength: number;\n private _shadowStrength: number;\n /** Raw, as the splat shader multiplies it: no colour-space conversion. */\n private readonly _tint = new Color(1, 1, 1);\n private _ambient: number;\n private _referenceLuminance: number;\n private _blurRadius: number;\n private _shadowBlurRadius: number;\n private _debug = 0;\n private _enabled = true;\n private _environmentRefresh: EnvironmentRefreshMode;\n private _lightAzimuth: number;\n private _lightElevation: number;\n /** Gamma-space, as authored. */\n private readonly _lightColor = new Color(1, 0.95, 0.85);\n private _lightIntensity: number;\n private readonly _skyColor: Color | null;\n private _skyIntensity: number;\n\n // \u2500\u2500 Resource-shape \u2500\u2500\n private _resolutionScale: number;\n private _receiveShadows: boolean;\n private readonly _proxy: RelightProxySettings;\n private _proxyKey: string;\n private _dirty = true;\n\n // \u2500\u2500 Preview \u2500\u2500\n private _preview: RelightPreviewMode;\n private _previewMaterial: MeshMatcapMaterial | null = null;\n\n private readonly _lightOpts: RelightLightOptions | null;\n private readonly _mainCameraOpt: Camera | undefined;\n private _shadowDistance = DEFAULT_SHADOW_DISTANCE;\n\n // \u2500\u2500 Runtime \u2500\u2500\n private readonly _scene: Scene;\n private _pass: RelightPass | null = null;\n private _keyLight: DirectionalLight | null = null;\n /** {@link RelightLightOptions.shadowBiasMode} is `'three'`. */\n private _threeShadowBias = false;\n /** PlayCanvas's polygon-offset slope factor for the key light's shadow. */\n private _slopeFactor = 0;\n /** The key light's bias as this instance's proxies take it. */\n private readonly _shadowBias = createProxyShadowBias();\n private readonly _targets = new Map<RelightTarget, TargetEntry>();\n private readonly _lights = new Map<Light, LightEntry>();\n private readonly _offPreRender: () => void;\n private _destroyed = false;\n private _lastRebuildMs = 0;\n\n /**\n * Build the component on `scene` and start lighting from the next frame.\n *\n * Throws when the renderer cannot render to half-float - lighting exceeds 1\n * and the target must not clamp it - and when the scene renders with WebGPU\n * but `@viggle/splat-engine-three/webgpu` was not imported.\n */\n static create(scene: Scene, opts: SplatRelightOptions = {}): SplatRelight {\n return new SplatRelight(scene, opts);\n }\n\n private constructor(scene: Scene, opts: SplatRelightOptions) {\n this._scene = scene;\n this._strength = clamp01(opts.strength ?? 1);\n this._shadowStrength = clamp01(opts.shadowStrength ?? 1);\n if (opts.tint !== undefined) setRawColor(this._tint, opts.tint);\n this._ambient = Math.max(0, opts.ambient ?? 0);\n this._referenceLuminance = Math.max(opts.referenceLuminance ?? 1, 1e-4);\n const blurDefault = (opts.blur ?? true) ? 1 : 0;\n this._blurRadius = Math.max(0, opts.blurRadius ?? blurDefault);\n this._shadowBlurRadius = Math.max(0, opts.shadowBlurRadius ?? blurDefault);\n this._environmentRefresh = opts.environmentRefresh ?? 'auto';\n\n this._lightOpts = opts.light === null ? null : { ...opts.light };\n this._lightAzimuth = opts.light?.azimuth ?? 30;\n this._lightElevation = opts.light?.elevation ?? 60;\n if (opts.light?.color !== undefined) setRawColor(this._lightColor, opts.light.color);\n this._lightIntensity = Math.max(0, opts.light?.intensity ?? 1);\n\n this._skyColor = opts.sky ? new Color(0.55, 0.62, 0.78) : null;\n if (opts.sky?.color !== undefined && this._skyColor) setRawColor(this._skyColor, opts.sky.color);\n this._skyIntensity = Math.max(0, opts.sky?.intensity ?? 0.35);\n\n this._resolutionScale = clamp(opts.resolutionScale ?? 0.5, 0.05, 1);\n this._receiveShadows = opts.receiveShadows ?? false;\n this._proxy = {\n surface: opts.proxy?.surface ?? defaultProxySettings.surface,\n voxelSize: opts.proxy?.voxelSize ?? defaultProxySettings.voxelSize,\n opacityThreshold: opts.proxy?.opacityThreshold ?? defaultProxySettings.opacityThreshold,\n dilate: opts.proxy?.dilate ?? defaultProxySettings.dilate,\n smoothIterations: opts.proxy?.smoothIterations ?? defaultProxySettings.smoothIterations,\n floorFill: opts.proxy?.floorFill ?? defaultProxySettings.floorFill,\n };\n sanitizeProxy(this._proxy);\n this._proxyKey = proxyKey(this._proxy);\n\n this._preview = opts.preview ?? 'off';\n this._mainCameraOpt = opts.mainCamera;\n\n if (this._lightOpts) this._createKeyLight();\n this._applySky();\n\n this._offPreRender = scene.on('preRender', () => this._onPreRender());\n try {\n this._ensure();\n } catch (err) {\n // Leave nothing half-built behind.\n this.destroy();\n throw err;\n }\n }\n\n /** Final teardown: proxies, targets, owned lights. Registered lights get their own layers back. Safe twice. */\n destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n this._offPreRender();\n for (const entry of this._targets.values()) this._releaseTarget(entry);\n this._targets.clear();\n this._pass?.destroy();\n this._pass = null;\n this._previewMaterial?.matcap?.dispose();\n this._previewMaterial?.dispose();\n this._previewMaterial = null;\n for (const [light, entry] of this._lights) {\n light.layers.mask = entry.base;\n if (entry.owned) {\n light.removeFromParent();\n (light as DirectionalLight).target?.removeFromParent();\n light.dispose();\n }\n }\n this._lights.clear();\n this._keyLight = null;\n }\n\n // \u2500\u2500 Targets \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Light a character, a splat or an environment. Each is voxelized at the\n * start of the next frame (a few to a few tens of milliseconds, by voxel\n * size) - a LOD-bundle environment once its first chunks have streamed in -\n * and lit from that frame on.\n *\n * Idempotent: a second call returns the first call's promise and ignores its\n * options. Drops the target once it is destroyed.\n *\n * @returns Settles once the target's proxy is first built.\n */\n add(target: RelightTarget, opts: RelightTargetOptions = {}): Promise<void> {\n const existing = this._targets.get(target);\n if (existing) return existing.ready;\n if (this._destroyed) return Promise.reject(new Error('[SplatRelight] add after destroy'));\n const environment = target instanceof Environment ? target : null;\n const character = !environment && isCharacter(target) ? target : null;\n const node = character ? null : environment ? environment.object3D : (target as Splat).object3D;\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => { resolveReady = resolve; });\n const entry: TargetEntry = {\n target,\n character,\n environment,\n node,\n params: null,\n pushedSplats: -1,\n proxy: stripUndefined(opts.proxy ?? {}),\n bounds: opts.bounds ?? null,\n castShadows: opts.castShadows ?? !environment,\n lightingReceiver: opts.lightingReceiver ?? true,\n source: null,\n input: null,\n inputKey: '',\n mesh: null,\n meshKey: '',\n voxels: null,\n voxelsKey: '',\n ready,\n resolveReady,\n gpuKey: '',\n proxyMesh: null,\n skeleton: null,\n previewMesh: null,\n debug: null,\n debugVoxels: null,\n };\n this._targets.set(target, entry);\n this._dirty = true;\n this._ensure();\n return ready;\n }\n\n /** Stop lighting a target and free its proxy. No-op when unknown. */\n remove(target: RelightTarget): void {\n const entry = this._targets.get(target);\n if (!entry) return;\n this._releaseTarget(entry);\n for (const consumer of consumersOf(entry)) this._pass?.setConsumerParams(consumer, null);\n this._targets.delete(target);\n this._pushParams();\n }\n\n /**\n * What one target is actually lit with: its overrides resolved against the\n * scene-wide knobs, every field present. `null` when the target is unknown.\n *\n * The pair to {@link setParams}, and what a panel over these knobs reads so\n * it does not have to keep a second copy of them. A copy is what goes stale:\n * a target added without overrides follows the component, and a panel\n * holding its own numbers would keep showing the ones it last wrote while\n * the scene moved underneath. The tint is a copy, so mutating it changes\n * nothing.\n */\n params(target: RelightTarget): Required<Omit<RelightTargetParams, 'tint'>> & { tint: Color } | null {\n const entry = this._targets.get(target);\n if (!entry) return null;\n const p = entry.params;\n return {\n strength: clamp01(p?.strength ?? this._strength),\n shadowStrength: clamp01(p?.shadowStrength ?? this._shadowStrength),\n ambient: Math.max(0, p?.ambient ?? this._ambient),\n tint: p?.tint !== undefined ? setRawColor(new Color(), p.tint) : this._tint.clone(),\n };\n }\n\n /**\n * Override the scene-wide knobs for one target, across all its LOD and\n * variant splats. `null` drops the override. Uniform-only.\n */\n setParams(target: RelightTarget, params: RelightTargetParams | null): void {\n const entry = this._targets.get(target);\n if (!entry) return;\n entry.params = params ? { ...entry.params, ...stripUndefined(params) } : null;\n if (!entry.params) for (const consumer of consumersOf(entry)) this._pass?.setConsumerParams(consumer, null);\n entry.pushedSplats = -1;\n this._pushParams();\n }\n\n /**\n * The voxelized proxy for a target - vertex and triangle counts, voxel\n * grid, build time. `null` for an unknown target or before its first build.\n */\n proxyMesh(target: RelightTarget): ProxyMeshResult | null {\n return this._targets.get(target)?.mesh ?? null;\n }\n\n /**\n * What a target's proxy was built from: splat counts before and after the\n * crop. `null` for an unknown target or before its source is in.\n */\n proxySource(target: RelightTarget): RelightProxySource | null {\n const entry = this._targets.get(target);\n if (!entry?.input) return null;\n const splats = Math.floor(entry.input.positions.length / 3);\n const src = entry.source;\n return {\n splats,\n sourceSplats: src ? Math.floor(src.input.positions.length / 3) : splats,\n lodLevel: src?.lodLevel ?? null,\n lodLevels: src?.lodLevels ?? 1,\n loadMs: src?.loadMs ?? 0,\n };\n }\n\n /**\n * The voxelizer settings one target is built with: the component's, then\n * {@link ENVIRONMENT_PROXY_DEFAULTS} for an environment, then the target's\n * own. A copy; `null` for an unknown target.\n */\n targetProxySettings(target: RelightTarget): RelightProxySettings | null {\n const entry = this._targets.get(target);\n return entry ? this._settingsFor(entry) : null;\n }\n\n /**\n * Override voxelizer settings for one target; `null` drops every override.\n * Only that target rebuilds, on the next frame or {@link rebuild}.\n */\n setTargetProxySettings(target: RelightTarget, next: Partial<RelightProxySettings> | null): void {\n const entry = this._targets.get(target);\n if (!entry) return;\n entry.proxy = next ? { ...entry.proxy, ...stripUndefined(next) } : {};\n this._dirty = true;\n }\n\n // \u2500\u2500 Lights \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * The owned directional key light, or `null` when built with\n * `light: null`. For the rarer three.js settings - shadow camera, map type\n * - that this component does not wrap. Its position and shadow camera are\n * refitted every frame.\n */\n get keyLight(): DirectionalLight | null { return this._keyLight; }\n\n /**\n * Have an existing three.js light reach the proxies.\n *\n * A light only reaches a proxy when it is enabled on the relight layers;\n * this adds them to the light's own. Change a registered light's layers by\n * removing and re-adding it. The light keeps three's own colour and falloff\n * semantics, except that on the proxies a point light falls off linearly to\n * its `distance`, as the PlayCanvas build's lights do.\n */\n addLight(light: Light): void {\n this._registerLight(light, false);\n }\n\n /** Undo {@link addLight}: restores the light's own layers. */\n removeLight(light: Light): void {\n const entry = this._lights.get(light);\n if (!entry) return;\n light.layers.mask = entry.base;\n this._lights.delete(light);\n if (light === this._keyLight) this._keyLight = null;\n }\n\n /**\n * Create an omni light that reaches both the app's layers and the proxies,\n * added to the scene. Owned: disposed with the component. Toggle it with\n * `visible`; move it with `position`.\n */\n addPointLight(opts: RelightPointLightOptions = {}): PointLight {\n if (this._destroyed) throw new Error('[SplatRelight] addPointLight after destroy');\n const color = new Color(1, 1, 1);\n if (opts.color !== undefined) setRawColor(color, opts.color);\n const intensity = opts.intensity ?? 1;\n const range = opts.range ?? 5;\n // Decay 0: the closest three's own falloff comes to PlayCanvas's linear\n // one, for the app's meshes. The proxies get the exact linear falloff.\n const light = new PointLight(0xffffff, intensity, range, 0);\n light.name = 'splat-relight-point';\n setPlayCanvasLightColor(light, color, intensity);\n light.castShadow = opts.castShadows ?? false;\n light.shadow.camera.near = 0.05;\n light.shadow.camera.far = range;\n light.layers.mask = layerMask(opts.layers ?? [0]);\n if (opts.position) light.position.set(opts.position.x, opts.position.y, opts.position.z);\n this._scene.threeScene.add(light);\n this._registerLight(light, true);\n return light;\n }\n\n // \u2500\u2500 Uniform-only knobs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * How far the proxy lighting replaces the baked look, 0..1. Independent of\n * {@link shadowStrength}: strength 0 with shadow strength 1 keeps the baked\n * colours and darkens only where a proxy blocks the light - the look for an\n * environment capture, whose baked lighting is real. With both at `0` on\n * every target the pass stops rendering altogether - a true no-op in pixels\n * and in cost.\n */\n get strength(): number { return this._strength; }\n set strength(v: number) { this._strength = clamp01(v); this._pushParams(); }\n\n /**\n * Cast-shadow depth on the splats, 0..1, independent of {@link strength}.\n * Inert unless {@link receiveShadows} is on.\n */\n get shadowStrength(): number { return this._shadowStrength; }\n set shadowStrength(v: number) { this._shadowStrength = clamp01(v); this._pushParams(); }\n\n /** Floor under the light term, so faces turned from every light are not black. */\n get ambient(): number { return this._ambient; }\n set ambient(v: number) { this._ambient = Math.max(0, v); this._pushParams(); }\n\n /** Tint on the received light only, never the base colour. Applied as given. */\n getTint(): Color { return this._tint.clone(); }\n setTint(c: string | Color): void { setRawColor(this._tint, c); this._pushParams(); }\n\n /**\n * The proxy brightness that counts as \"normally lit\". Lighting is divided\n * by it, so strength moves contrast rather than exposure. Calibrate it to\n * the scene's key light.\n */\n get referenceLuminance(): number { return this._referenceLuminance; }\n set referenceLuminance(v: number) {\n this._referenceLuminance = Math.max(v, 1e-4);\n this._pushParams();\n }\n\n /** The 3x3 tent over the lighting texture that keeps animated lighting stable. */\n get blur(): boolean { return this._blurRadius > 0 || this._shadowBlurRadius > 0; }\n set blur(v: boolean) {\n this._blurRadius = v ? 1 : 0;\n this._shadowBlurRadius = v ? 1 : 0;\n this._pushParams();\n }\n\n /**\n * Radius of the tent over the lighting, in texels of the proxy target.\n * Default `1`; `0` is a single tap and the raw bake.\n *\n * The knob that softens a cast shadow being read through {@link strength}\n * alone - the shadow map lives in this channel - and it softens the\n * terminator across the subject with it. For a soft shadow and a crisp\n * subject, raise {@link shadowBlurRadius} instead, or filter the shadow map\n * itself with {@link RelightLightOptions.shadowType}.\n */\n get blurRadius(): number { return this._blurRadius; }\n set blurRadius(v: number) { this._blurRadius = Math.max(0, v); this._pushParams(); }\n\n /**\n * Radius of the tent over the shadow-visibility channel, in texels of the\n * proxy target. Default `1`.\n *\n * Inert while {@link shadowStrength} is 0 or the pass was built without\n * `receiveShadows`, because nothing reads that channel then.\n */\n get shadowBlurRadius(): number { return this._shadowBlurRadius; }\n set shadowBlurRadius(v: number) { this._shadowBlurRadius = Math.max(0, v); this._pushParams(); }\n\n /** Suspend the effect without dropping anything. */\n get enabled(): boolean { return this._enabled; }\n set enabled(v: boolean) { this._enabled = v; this._pushParams(); }\n\n /**\n * See {@link EnvironmentRefreshMode}: kept for the PlayCanvas build's API.\n * Every splat in this port samples the live lighting each frame, so\n * environments are always current whatever the mode.\n */\n get environmentRefresh(): EnvironmentRefreshMode { return this._environmentRefresh; }\n set environmentRefresh(v: EnvironmentRefreshMode) { this._environmentRefresh = v; this._pushParams(); }\n\n /** See {@link RelightPass.invalidateEnvironments}. */\n invalidateEnvironments(): void { this._pass?.invalidateEnvironments(); }\n\n /** Frames on which the published lighting changed, since the pass was last built. A cost probe. */\n get environmentRefreshFrames(): number { return this._pass?.environmentRefreshFrames ?? 0; }\n\n /**\n * Paint the splats with the relight sample instead of lighting them:\n * `1` the lighting, `2` the shadow visibility, `0` off. Diagnostic.\n */\n get debug(): number { return this._debug; }\n set debug(v: number) { this._debug = v === 1 || v === 2 ? v : 0; this._pushParams(); }\n\n /** Key light azimuth, degrees. 0 = +Z, 90 = +X. */\n get lightAzimuth(): number { return this._lightAzimuth; }\n set lightAzimuth(v: number) { this._lightAzimuth = v; }\n\n /** Key light elevation, degrees, -90..90. */\n get lightElevation(): number { return this._lightElevation; }\n set lightElevation(v: number) { this._lightElevation = clamp(v, -90, 90); }\n\n /** Key light intensity. */\n get lightIntensity(): number { return this._lightIntensity; }\n set lightIntensity(v: number) { this._lightIntensity = Math.max(0, v); this._applyKeyLightColor(); }\n\n /** Key light colour, gamma-space as authored. */\n getLightColor(): Color { return this._lightColor.clone(); }\n setLightColor(c: string | Color): void { setRawColor(this._lightColor, c); this._applyKeyLightColor(); }\n\n /**\n * How dark the key light's shadow map is allowed to make a surface, `0..1`.\n *\n * Live, and the first thing to reach for when a cast shadow reads as a hole\n * rather than as shade. It lifts the shadow where it is MADE, so everything\n * downstream sees the lifted value - the proxy render, and therefore the\n * lighting channel every splat samples. Reads `1` when there is no key\n * light; setting it is then a no-op.\n */\n get lightShadowIntensity(): number { return this._keyLight?.shadow.intensity ?? 1; }\n set lightShadowIntensity(v: number) {\n if (this._keyLight) this._keyLight.shadow.intensity = clamp01(v);\n }\n\n /**\n * How the key light's shadow map is filtered. See\n * {@link RelightLightOptions.shadowType} - including which values are\n * renderer-wide in three.js. Reads `pcf3` when there is no key light.\n */\n get lightShadowType(): RelightShadowType {\n const light = this._keyLight;\n if (!light) return 'pcf3';\n const type = this._scene.renderer.shadowMap.type;\n if (type === BasicShadowMap) return 'pcf1';\n if (type === VSMShadowMap) return 'vsm16';\n return light.shadow.radius >= 2 ? 'pcf5' : 'pcf3';\n }\n set lightShadowType(v: RelightShadowType) {\n if (this._keyLight) applyShadowType(this._scene, this._keyLight, v, this.lightVsmBlurSize);\n }\n\n /** Blur kernel for the `vsm` shadow types, in texels. Inert under `pcf`. */\n get lightVsmBlurSize(): number { return this._keyLight ? this._keyLight.shadow.blurSamples : 11; }\n set lightVsmBlurSize(v: number) {\n const light = this._keyLight;\n if (!light) return;\n light.shadow.blurSamples = Math.max(1, Math.round(v));\n if (this._scene.renderer.shadowMap.type === VSMShadowMap) light.shadow.radius = Math.max(1, (light.shadow.blurSamples - 1) / 2);\n }\n\n /** Sky fill intensity. No-op unless built with `sky`. Scene-wide. */\n get skyIntensity(): number { return this._skyIntensity; }\n set skyIntensity(v: number) { this._skyIntensity = Math.max(0, v); this._applySky(); }\n\n /** Sky fill colour, or `null` when built without `sky`. */\n getSkyColor(): Color | null { return this._skyColor?.clone() ?? null; }\n setSkyColor(c: string | Color): void {\n if (!this._skyColor) return;\n setRawColor(this._skyColor, c);\n this._applySky();\n }\n\n // \u2500\u2500 Resource-shape knobs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Lighting-texture size as a fraction of the canvas, 0.05..1. Reallocates. */\n get resolutionScale(): number { return this._resolutionScale; }\n set resolutionScale(v: number) {\n const next = clamp(v, 0.05, 1);\n if (next === this._resolutionScale) return;\n this._resolutionScale = next;\n this._dirty = true;\n }\n\n /**\n * Cast shadows on the splats. Costs a second proxy render a frame, so it is\n * a rebuild: the pass is replaced.\n */\n get receiveShadows(): boolean { return this._receiveShadows; }\n set receiveShadows(v: boolean) {\n if (v === this._receiveShadows) return;\n this._receiveShadows = v;\n this._dirty = true;\n }\n\n get surface(): ProxySurfaceStyle { return this._proxy.surface; }\n set surface(v: ProxySurfaceStyle) { this.setProxySettings({ surface: v }); }\n\n get voxelSize(): number { return this._proxy.voxelSize; }\n set voxelSize(v: number) { this.setProxySettings({ voxelSize: v }); }\n\n get opacityThreshold(): number { return this._proxy.opacityThreshold; }\n set opacityThreshold(v: number) { this.setProxySettings({ opacityThreshold: v }); }\n\n get dilate(): number { return this._proxy.dilate; }\n set dilate(v: number) { this.setProxySettings({ dilate: v }); }\n\n get smoothIterations(): number { return this._proxy.smoothIterations; }\n set smoothIterations(v: number) { this.setProxySettings({ smoothIterations: v }); }\n\n get floorFill(): boolean { return this._proxy.floorFill; }\n set floorFill(v: boolean) { this.setProxySettings({ floorFill: v }); }\n\n /** Every voxelizer knob at once. A copy. */\n get proxySettings(): RelightProxySettings { return { ...this._proxy }; }\n\n /** Set several voxelizer knobs; one rebuild however many change. */\n setProxySettings(next: Partial<RelightProxySettings>): void {\n Object.assign(this._proxy, stripUndefined(next));\n sanitizeProxy(this._proxy);\n const key = proxyKey(this._proxy);\n if (key === this._proxyKey) return;\n this._proxyKey = key;\n this._dirty = true;\n }\n\n /**\n * Apply pending resource-shape changes now rather than at the start of the\n * next frame - for a script that screenshots the result straight after.\n */\n rebuild(): void {\n this._dirty = true;\n this._ensure();\n }\n\n /** Milliseconds the last rebuild that did work took, voxelizing included. */\n get lastRebuildMs(): number { return this._lastRebuildMs; }\n\n // \u2500\u2500 Preview \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Off / voxels / mesh. Runtime-switchable, and never part of the lighting:\n * voxels are lines, and the mesh preview is a separate mesh with its own\n * material on layer 0, never on a relight layer. The first switch to\n * `voxels` builds the cell overlay.\n */\n get preview(): RelightPreviewMode { return this._preview; }\n set preview(v: RelightPreviewMode) {\n if (v === this._preview) return;\n this._preview = v;\n if (v === 'voxels') this._dirty = true;\n this._syncPreview();\n }\n\n // \u2500\u2500 Introspection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** The composed lighting texture, `rgb` light and `a` coverage. Debug only. */\n get lightingTexture() { return this._pass?.lightingTexture ?? null; }\n\n /** `[width, height]` of the lighting texture; `[0, 0]` before the pass exists. */\n get resolution(): [number, number] { return this._pass?.resolution ?? [0, 0]; }\n\n /**\n * The three.js layer the proxies render on. Enabling it on a camera shows\n * the raw proxy - a debugging aid.\n */\n get proxyLayerId(): number { return RELIGHT_PROXY_LAYER; }\n\n /** Whether the pass is rendering this frame (off with every strength and shadow strength at 0). */\n get active(): boolean { return this._pass?.enabled ?? false; }\n\n // \u2500\u2500 Internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _onPreRender(): void {\n if (this._destroyed) return;\n for (const entry of Array.from(this._targets.values())) {\n // three.js objects have no destroy event, so a destroyed target is\n // noticed here and dropped, as the PlayCanvas build drops it on its\n // entity's `destroy`.\n if (targetDestroyed(entry)) { this.remove(entry.target); continue; }\n // An environment's splat arrives after `add` for a streaming bundle, and\n // a cropped one is cut in world space, so its transform is polled.\n if (entry.environment && (!entry.source || this._inputKeyFor(entry) !== entry.inputKey)) this._dirty = true;\n // A character's finer LOD levels can land after `add`; its proxy follows\n // the densest one loaded.\n if (entry.character && entry.input && densestSplatOf(entry.character).key !== entry.inputKey) this._dirty = true;\n }\n if (this._dirty) this._ensure();\n // LOD levels and variants arrive after `add`; their params have to follow.\n for (const entry of this._targets.values()) {\n if (entry.params && splatCount(entry) !== entry.pushedSplats) this._pushTargetParams(entry);\n }\n\n const pass = this._pass;\n if (!pass) return;\n for (const entry of this._targets.values()) if (entry.skeleton) poseSkeleton(entry);\n this._placeKeyLight();\n pass.render();\n }\n\n /**\n * The allocator. Idempotent: brings every resource-shape resource in line\n * with the settings and does nothing where it already is.\n */\n private _ensure(): void {\n if (this._destroyed || !this._dirty) return;\n const scene = this._scene;\n const t0 = performance.now();\n let work = false;\n\n // 1. Geometry. CPU-only.\n for (const entry of this._targets.values()) {\n const settings = this._settingsFor(entry);\n // Static proxies are built in their node's local units; the knob is in\n // world metres.\n entry.node?.updateWorldMatrix(true, false);\n const scale = entry.node ? maxAxisScale(entry.node.matrixWorld) : 1;\n const local = { ...settings, voxelSize: settings.voxelSize / scale };\n if (!this._ensureInput(entry)) continue;\n const key = `${proxyKey(settings)}|${scale}|${entry.inputKey}`;\n if (entry.meshKey !== key) {\n const before = entry.mesh;\n entry.mesh = buildProxyMesh(entry.input!, local);\n entry.meshKey = key;\n work = true;\n if (!before) entry.resolveReady();\n warnIfCoarsened(entry, local.voxelSize);\n }\n if (this._preview === 'voxels' && entry.voxelsKey !== key) {\n // The cell boundary is blocky and unsmoothed whatever the surface is;\n // when the proxy already is exactly that, it is the same build.\n const exact = local.surface === 'blocky' && local.smoothIterations === 0;\n entry.voxels = exact\n ? entry.mesh\n : buildProxyMesh(entry.input!, { ...local, surface: 'blocky', smoothIterations: 0 });\n entry.voxelsKey = key;\n work = true;\n }\n }\n\n // 2. The pass. Visibility is fixed per pass, so a change replaces it - and\n // every proxy goes first, because each holds the old pass's material and\n // shadowless twin.\n if (this._pass && this._pass.visibilityEnabled !== this._receiveShadows) {\n for (const entry of this._targets.values()) this._releaseTarget(entry);\n this._pass.destroy();\n this._pass = null;\n }\n if (!this._pass) {\n this._pass = RelightPass.create(scene, {\n resolutionScale: this._resolutionScale,\n referenceLuminance: this._referenceLuminance,\n blurRadius: this._blurRadius,\n shadowBlurRadius: this._shadowBlurRadius,\n visibility: this._receiveShadows,\n mainCamera: this._mainCameraOpt,\n environmentRefresh: this._environmentRefresh,\n shadowBias: this._shadowBias,\n });\n for (const entry of this._targets.values()) entry.pushedSplats = -1;\n this._stampLights();\n work = true;\n }\n // Size-guarded inside: a no-op unless the scale moved.\n this._pass.resolutionScale = this._resolutionScale;\n\n // 3. Proxies on the GPU.\n for (const entry of this._targets.values()) {\n if (!entry.mesh || entry.gpuKey === entry.meshKey) continue;\n this._releaseTarget(entry);\n this._attachTarget(entry, this._pass);\n entry.gpuKey = entry.meshKey;\n work = true;\n }\n\n this._syncPreview();\n this._pushParams();\n this._dirty = false;\n if (work) this._lastRebuildMs = performance.now() - t0;\n }\n\n private _attachTarget(entry: TargetEntry, pass: RelightPass): void {\n const result = entry.mesh;\n if (!result || result.indices.length === 0) return;\n const geometry = new BufferGeometry();\n geometry.setAttribute('position', new BufferAttribute(result.positions, 3));\n geometry.setAttribute('normal', new BufferAttribute(result.normals, 3));\n geometry.setIndex(new BufferAttribute(result.indices, 1));\n\n const character = entry.character;\n let proxy: Mesh;\n let parent: Object3D;\n if (character && result.boneIndices && result.boneWeights) {\n const armature = character.armature;\n const numBones = armature.numBones;\n addSkinAttributes(geometry, result.boneIndices, result.boneWeights, numBones);\n // One bone per rig bone plus an identity slot for unweighted vertices.\n // The bones are not in the scene graph: their world matrices are the\n // armature's, written each frame by `poseSkeleton`, so the skin matrix\n // is `boneWorld * inverseBind` - world space, from BIND-space vertices.\n const bones: Bone[] = [];\n const inverses: Matrix4[] = [];\n for (let b = 0; b <= numBones; b++) {\n bones.push(new Bone());\n const inv = new Matrix4();\n const src = armature.inverseBindPose[b];\n if (b < numBones && src) inv.fromArray(src.data);\n inverses.push(inv);\n }\n const skeleton = new Skeleton(bones, inverses);\n const skinned = new SkinnedMesh(geometry, pass.proxyMaterial);\n // Attached bind mode with an identity bind matrix: three evaluates\n // `objectWorld * inv(objectWorld) * skin * v`, in which the armature's\n // transform cancels and the world-space skin lands as it is. Under the\n // armature so it shows and hides with the character.\n skinned.skeleton = skeleton;\n entry.skeleton = skeleton;\n poseSkeleton(entry);\n proxy = skinned;\n parent = armature.object3D;\n } else {\n // A static target, or a character whose splats carried no weights - its\n // proxy then sits at bind under the armature, which is exactly where\n // those splats stay too.\n proxy = new Mesh(geometry, pass.proxyMaterial);\n parent = entry.node ?? character!.armature.object3D;\n }\n proxy.name = 'splat-relight-proxy';\n // Never culled: a skinned proxy's bounds are its bind pose's, and the\n // shadow render culls against them too.\n proxy.frustumCulled = false;\n // Casts into the lights' shadow maps, which is how the subject shadows\n // the floor while the proxy itself is never seen.\n proxy.castShadow = entry.castShadows;\n proxy.receiveShadow = true;\n parent.add(proxy);\n pass.addProxy(proxy, entry.lightingReceiver);\n entry.proxyMesh = proxy;\n\n // The preview: its own material, on the app's layer 0, no shadows in\n // either direction, sharing the proxy's geometry and skeleton so it can\n // never drift from what it previews. Not registered with the pass, so it\n // is never lit into the splats.\n const material = this._previewMaterialFor();\n let preview: Mesh;\n if (entry.skeleton) {\n const skinned = new SkinnedMesh(geometry, material);\n skinned.skeleton = entry.skeleton;\n preview = skinned;\n } else {\n preview = new Mesh(geometry, material);\n }\n preview.name = 'splat-relight-preview';\n preview.frustumCulled = false;\n // After the splats, which are transparent, so it reads over them.\n preview.renderOrder = 1e6;\n parent.add(preview);\n entry.previewMesh = preview;\n\n const debug = ProxyMeshDebug.create(this._scene, { mode: 'off' });\n debug.armature = entry.skeleton ? character!.armature : null;\n debug.node = entry.skeleton ? null : parent;\n entry.debug = debug;\n }\n\n /** Free one target's GPU state, holders of references first. */\n private _releaseTarget(entry: TargetEntry): void {\n if (entry.proxyMesh) {\n // The pass's twin shares the proxy's geometry and skeleton: unregister\n // before either goes away.\n this._pass?.removeProxy(entry.proxyMesh);\n entry.proxyMesh.removeFromParent();\n entry.proxyMesh.geometry.dispose();\n }\n entry.proxyMesh = null;\n entry.previewMesh?.removeFromParent();\n entry.previewMesh = null;\n entry.skeleton?.dispose();\n entry.skeleton = null;\n entry.debug?.destroy();\n entry.debug = null;\n entry.debugVoxels = null;\n entry.gpuKey = '';\n }\n\n private _previewMaterialFor(): MeshMatcapMaterial {\n if (this._previewMaterial) return this._previewMaterial;\n const mat = new MeshMatcapMaterial({ name: 'splat-relight-preview', matcap: previewMatcap(), transparent: true });\n mat.fog = false;\n this._previewMaterial = mat;\n return mat;\n }\n\n private _syncPreview(): void {\n for (const entry of this._targets.values()) {\n if (entry.previewMesh) entry.previewMesh.visible = this._preview === 'mesh';\n if (!entry.debug) continue;\n const show = this._preview === 'voxels' && entry.voxelsKey === entry.meshKey;\n if (show && entry.debugVoxels !== entry.voxels) {\n entry.debug.setVoxels(entry.voxels);\n entry.debugVoxels = entry.voxels;\n }\n entry.debug.mode = show ? 'voxels' : 'off';\n }\n }\n\n /** Push every uniform-only knob to the pass. Cheap; no allocation per call. */\n private _pushParams(): void {\n const pass = this._pass;\n if (!pass) return;\n pass.setDefaults({\n strength: this._strength,\n shadowStrength: this._shadowStrength,\n ambient: this._ambient,\n tint: { r: this._tint.r, g: this._tint.g, b: this._tint.b },\n debug: this._debug,\n });\n pass.referenceLuminance = this._referenceLuminance;\n pass.blurRadius = this._blurRadius;\n pass.shadowBlurRadius = this._shadowBlurRadius;\n pass.environmentRefresh = this._environmentRefresh;\n\n const samples = (strength: number, shadow: number) =>\n strength > 0 || (this._receiveShadows && shadow > 0);\n let live = samples(this._strength, this._shadowStrength);\n for (const entry of this._targets.values()) {\n if (entry.params) {\n this._pushTargetParams(entry);\n const p = entry.params;\n if (samples(p.strength ?? this._strength, p.shadowStrength ?? this._shadowStrength)) live = true;\n }\n }\n // Nothing samples the texture with both knobs at 0 (the debug paint\n // does), so the pass stops rendering rather than baking lighting nobody\n // reads.\n pass.enabled = this._enabled && (live || this._debug > 0);\n }\n\n private _pushTargetParams(entry: TargetEntry): void {\n const pass = this._pass;\n const p = entry.params;\n if (!pass || !p) return;\n const tint = p.tint !== undefined ? setRawColor(new Color(), p.tint) : this._tint;\n const resolved = {\n strength: clamp01(p.strength ?? this._strength),\n shadowStrength: clamp01(p.shadowStrength ?? this._shadowStrength),\n ambient: Math.max(0, p.ambient ?? this._ambient),\n tint: { r: tint.r, g: tint.g, b: tint.b },\n };\n for (const consumer of consumersOf(entry)) pass.setConsumerParams(consumer, resolved);\n entry.pushedSplats = splatCount(entry);\n }\n\n /** Make `entry.input` current. `false` while an environment has no splat to read yet. */\n private _ensureInput(entry: TargetEntry): boolean {\n const env = entry.environment;\n if (!env) {\n if (entry.character) {\n // Built from the densest loaded level, not `splats[0]`: a progressive\n // load lands its coarsest level first and appends finer ones later,\n // and a coarse level's few centres voxelize into a holed proxy whose\n // shadow falls apart. Rebuilt when a denser level arrives.\n const densest = densestSplatOf(entry.character);\n if (!entry.input || entry.inputKey !== densest.key) {\n entry.input = proxyInputFromSplat(densest.splat, entry.character.armature, this._scene);\n entry.inputKey = densest.key;\n }\n } else if (!entry.input) {\n entry.input = proxyInputFromSplat(entry.target as Splat, null, this._scene);\n }\n return true;\n }\n if (!entry.source) {\n entry.source = proxyInputFromEnvironment(env);\n if (!entry.source) return false;\n }\n const key = this._inputKeyFor(entry);\n if (entry.input && entry.inputKey === key) return true;\n const box = entry.bounds;\n entry.input = box\n ? cropInputToWorldBox(entry.source.input, env.object3D.matrixWorld.elements, box.min, box.max)\n : entry.source.input;\n entry.inputKey = key;\n return true;\n }\n\n /** The crop an environment's input is cut with, as a comparable string. */\n private _inputKeyFor(entry: TargetEntry): string {\n const box = entry.bounds;\n if (!box) return 'uncropped';\n const env = entry.environment!;\n env.object3D.updateWorldMatrix(true, false);\n return `${box.min.x},${box.min.y},${box.min.z}|${box.max.x},${box.max.y},${box.max.z}|`\n + env.object3D.matrixWorld.elements.join(',');\n }\n\n private _settingsFor(entry: TargetEntry): RelightProxySettings {\n const out: RelightProxySettings = {\n ...this._proxy,\n ...(entry.environment ? ENVIRONMENT_PROXY_DEFAULTS : {}),\n ...entry.proxy,\n };\n sanitizeProxy(out);\n return out;\n }\n\n private _createKeyLight(): void {\n const o = this._lightOpts!;\n const light = new DirectionalLight();\n light.name = 'splat-relight-key-light';\n light.castShadow = o.castShadows ?? true;\n light.layers.mask = layerMask(o.layers ?? [0]);\n const res = o.shadowResolution ?? DEFAULT_SHADOW_RESOLUTION;\n light.shadow.mapSize.set(res, res);\n this._threeShadowBias = o.shadowBiasMode === 'three';\n if (this._threeShadowBias) {\n light.shadow.bias = o.shadowBias ?? -0.0005;\n light.shadow.normalBias = o.normalOffsetBias ?? 0;\n } else {\n // PlayCanvas's light component: `light.shadowBias = -0.01 x value`,\n // drawn as polygonOffset(-1000 x that) on the casters; its shadow\n // lookup then compares 0.0001 short of the stored depth.\n this._slopeFactor = clamp01(o.shadowBias ?? 0.05) * 10;\n light.shadow.bias = PC_SHADOW_COMPARE_BIAS;\n light.shadow.normalBias = clamp01(o.normalOffsetBias ?? 0);\n relightBackendFor(this._scene).configureKeyLight(light, this._shadowBias);\n }\n light.shadow.intensity = clamp01(o.shadowIntensity ?? 1);\n light.shadow.blurSamples = Math.max(1, Math.round(o.vsmBlurSize ?? 11));\n this._shadowDistance = Math.max(0.1, o.shadowDistance ?? DEFAULT_SHADOW_DISTANCE);\n if (o.shadowType !== undefined) applyShadowType(this._scene, light, o.shadowType, light.shadow.blurSamples);\n this._scene.threeScene.add(light, light.target);\n this._keyLight = light;\n this._registerLight(light, true);\n this._applyKeyLightColor();\n }\n\n private _applyKeyLightColor(): void {\n if (this._keyLight) setPlayCanvasLightColor(this._keyLight, this._lightColor, this._lightIntensity);\n }\n\n /**\n * Point the key light along azimuth/elevation and fit its shadow camera.\n *\n * The toward-the-light vector is `(cosE sinA, sinE, cosE cosA)`. The shadow\n * covers the view frustum out to the shadow distance, as PlayCanvas fits its\n * directional shadows: the slice's bounding sphere, snapped to whole shadow\n * texels in the light's frame so a moving camera does not make the shadow\n * edges crawl.\n */\n private _placeKeyLight(): void {\n const light = this._keyLight;\n if (!light) return;\n const az = this._lightAzimuth * DEG;\n const el = this._lightElevation * DEG;\n _toLight.set(Math.cos(el) * Math.sin(az), Math.sin(el), Math.cos(el) * Math.cos(az));\n\n const camera = (this._mainCameraOpt ?? this._scene.camera) as PerspectiveCamera;\n camera.updateMatrixWorld();\n let radius = 1;\n _center.set(0, 0, 0);\n if (light.castShadow && camera.isPerspectiveCamera) {\n const near = camera.near;\n const far = Math.min(camera.far, this._shadowDistance);\n const tanV = Math.tan((camera.fov * DEG) / 2) / camera.zoom;\n const tanH = tanV * camera.aspect;\n const corners = _corners;\n let i = 0;\n for (const z of [near, far]) {\n for (const sx of [-1, 1]) {\n for (const sy of [-1, 1]) corners[i++].set(sx * z * tanH, sy * z * tanV, -z).applyMatrix4(camera.matrixWorld);\n }\n }\n for (const p of corners) _center.add(p);\n _center.multiplyScalar(1 / corners.length);\n radius = 0;\n for (const p of corners) radius = Math.max(radius, p.distanceTo(_center));\n\n // Snap in the light's frame: one texel is 2r / resolution.\n const texel = (2 * radius) / light.shadow.mapSize.x;\n _lightBasis.lookAt(_origin, _toLight, _up(_toLight));\n _lightToFrame.copy(_lightBasis).transpose();\n _snap.copy(_center).applyMatrix4(_lightInverse.copy(_lightBasis).transpose());\n _snap.x = Math.round(_snap.x / texel) * texel;\n _snap.y = Math.round(_snap.y / texel) * texel;\n _center.copy(_snap.applyMatrix4(_lightBasis));\n\n const cam = light.shadow.camera;\n cam.left = -radius;\n cam.right = radius;\n cam.top = radius;\n cam.bottom = -radius;\n // Casters up to one more radius toward the light still land in the map.\n let distance = 2 * radius;\n cam.near = 0;\n cam.far = 4 * radius;\n if (!this._threeShadowBias) {\n light.shadow.bias = PC_SHADOW_COMPARE_BIAS;\n // PlayCanvas fits the depth range to the casters in the map instead,\n // and its bias is measured in that range.\n if (this._casterDepthRange(radius)) {\n const { min, max } = _depthRange;\n // Its shadow camera sits just past the nearest caster - which can\n // be behind the slice's centre, when the light faces the camera.\n // Only the shadow camera moves there; the light keeps its\n // direction, which here the target below keeps.\n distance = max + 0.1;\n cam.near = 0.01;\n // It clamps a receiver past `far` onto it (`saturate(z)`), so the\n // receivers behind the last caster are still shadowed; three counts\n // them outside the map. Reach far enough for every receiver it\n // shadows: those in the view out to the shadow distance, which lie\n // within the radius of the centre.\n const casterFar = max - min + 0.2;\n cam.far = max - Math.min(min, -radius) + 0.2;\n // Its compare bias is a fraction of the caster range; keep the same\n // depth in the longer range.\n light.shadow.bias = (PC_SHADOW_COMPARE_BIAS * (casterFar - cam.near)) / (cam.far - cam.near);\n }\n }\n cam.updateProjectionMatrix();\n this._shadowBias.toLight.copy(_toLight);\n this._shadowBias.slope = this._threeShadowBias ? 0 : this._slopeFactor * texel;\n light.position.copy(_center).addScaledVector(_toLight, distance);\n } else {\n light.position.copy(_center).addScaledVector(_toLight, 1);\n }\n // three lights from `position - target`: aim along the light, not at the\n // centre, which the position can be past.\n light.target.position.copy(light.position).sub(_toLight);\n light.target.updateMatrixWorld();\n light.updateMatrixWorld();\n }\n\n /**\n * The depth span, along the light from {@link _center}, of the shadow\n * casters whose bounds fall in the map's `radius` square: what PlayCanvas\n * fits a directional shadow camera's near and far to. Into `_depthRange`;\n * false when no caster is in the map.\n */\n private _casterDepthRange(radius: number): boolean {\n const union = _casterUnion.makeEmpty();\n this._scene.threeScene.traverseVisible((o) => {\n const mesh = o as Mesh;\n if (!mesh.isMesh || !mesh.castShadow) return;\n const world = casterWorldBox(mesh, _casterBox);\n if (!world) return;\n // In the light's frame, the map covers |x|, |y| <= radius about the centre.\n const inLight = _casterLight.copy(world).translate(_negCenter.copy(_center).negate()).applyMatrix4(_lightToFrame);\n if (inLight.max.x < -radius || inLight.min.x > radius || inLight.max.y < -radius || inLight.min.y > radius) return;\n union.union(world);\n });\n if (union.isEmpty()) return false;\n let min = Infinity;\n let max = -Infinity;\n for (let i = 0; i < 8; i++) {\n _corner.set(i & 1 ? union.max.x : union.min.x, i & 2 ? union.max.y : union.min.y, i & 4 ? union.max.z : union.min.z);\n const d = _corner.sub(_center).dot(_toLight);\n if (d < min) min = d;\n if (d > max) max = d;\n }\n _depthRange.min = min;\n _depthRange.max = max;\n return true;\n }\n\n private _applySky(): void {\n if (!this._skyColor) return;\n // Gamma-space, as the PlayCanvas build writes its scene ambient; the\n // compose linearizes it (see RelightPass).\n const k = this._skyIntensity;\n const amb = this._scene.ambientLight;\n amb.color.setRGB(this._skyColor.r * k, this._skyColor.g * k, this._skyColor.b * k);\n amb.intensity = 1;\n }\n\n private _registerLight(light: Light, owned: boolean): void {\n if (this._destroyed || this._lights.has(light)) return;\n const entry: LightEntry = { base: light.layers.mask & ~RELIGHT_LAYER_MASK, owned };\n this._lights.set(light, entry);\n this._stampLight(light, entry);\n }\n\n private _stampLights(): void {\n for (const [light, entry] of this._lights) this._stampLight(light, entry);\n }\n\n /** The light's own layers, plus the relight layers the current pass draws. */\n private _stampLight(light: Light, entry: LightEntry): void {\n const relight = this._receiveShadows ? RELIGHT_LAYER_MASK : 1 << RELIGHT_PROXY_LAYER;\n light.layers.mask = entry.base | relight;\n }\n}\n\nconst DEG = Math.PI / 180;\n/**\n * PlayCanvas's directional shadow lookup compares this far short of the\n * stored depth, in the shadow camera's normalized range.\n */\nconst PC_SHADOW_COMPARE_BIAS = -0.0001;\nconst _depthRange = { min: 0, max: 0 };\nconst _casterUnion = new Box3();\nconst _casterBox = new Box3();\nconst _casterLight = new Box3();\nconst _negCenter = new Vector3();\nconst _corner = new Vector3();\nconst _lightToFrame = new Matrix4();\nconst _toLight = new Vector3();\nconst _center = new Vector3();\nconst _snap = new Vector3();\nconst _origin = new Vector3();\nconst _corners = Array.from({ length: 8 }, () => new Vector3());\nconst _lightBasis = new Matrix4();\nconst _lightInverse = new Matrix4();\nconst _upY = new Vector3(0, 1, 0);\nconst _upZ = new Vector3(0, 0, 1);\n\n/** An up vector that is not parallel to `dir`. */\nfunction _up(dir: Vector3): Vector3 {\n return Math.abs(dir.y) > 0.99 ? _upZ : _upY;\n}\n\n/**\n * A crop that coarsens a request this much means the bounds are the problem,\n * not the voxel size.\n */\nconst COARSEN_WARN_RATIO = 2;\n\nfunction sanitizeProxy(p: RelightProxySettings): void {\n p.voxelSize = clamp(p.voxelSize, 0.001, 10);\n p.opacityThreshold = clamp01(p.opacityThreshold);\n p.dilate = Math.max(0, Math.round(p.dilate));\n p.smoothIterations = Math.max(0, Math.round(p.smoothIterations));\n p.surface = p.surface === 'smooth' ? 'smooth' : 'blocky';\n p.floorFill = !!p.floorFill;\n}\n\nfunction isCharacter(t: RelightTarget): t is Character {\n return (t as Character).armature !== undefined && Array.isArray((t as Character).splats);\n}\n\n/** Whether a target's owner has been destroyed under us. */\nfunction targetDestroyed(entry: TargetEntry): boolean {\n if (entry.character) return entry.character.destroyed;\n // An environment's splat is null until a bundle streams in, and again once\n // the environment is destroyed; only the second follows a read.\n if (entry.environment) return !!entry.source && (!entry.environment.splat || entry.environment.splat.destroyed);\n return (entry.target as Splat).destroyed;\n}\n\nfunction consumersOf(entry: TargetEntry): RelightConsumer[] {\n const c = entry.character;\n return c ? [...c.splats, ...c.variantSplats] : [entry.target as Splat | Environment];\n}\n\n/**\n * The voxelizer's grid ceiling coarsens silently. On a static target that\n * almost always means a crop is missing, which is worth one line in the\n * console - the proxy is otherwise just quietly worse.\n */\nfunction warnIfCoarsened(entry: TargetEntry, requested: number): void {\n const used = entry.mesh?.voxelSize ?? requested;\n if (!entry.node || used <= requested * COARSEN_WARN_RATIO) return;\n console.warn(\n `[SplatRelight] ${entry.node.name}: voxel size coarsened from ${requested.toPrecision(3)} to `\n + `${used.toPrecision(3)} (local units) to fit the voxel grid ceiling. Crop the target with `\n + '`bounds` to where characters walk.',\n );\n}\n\n/**\n * A character's LOD level with the most splats, and a key that changes when a\n * denser one is loaded. Variant splats are not LOD levels and are skipped.\n *\n * @internal Exported for tests.\n */\nexport function densestSplatOf(character: Pick<Character, 'splats'>): { splat: Splat; key: string } {\n let best = 0;\n for (let i = 1; i < character.splats.length; i++) {\n if (character.splats[i].numSplats > character.splats[best].numSplats) best = i;\n }\n const splat = character.splats[best];\n return { splat, key: `${best}|${splat.numSplats}` };\n}\n\nfunction splatCount(entry: TargetEntry): number {\n const c = entry.character;\n return c ? c.splats.length + c.variantSplats.length : 1;\n}\n\n/**\n * The voxelizer's influences as three's skin attributes. A vertex with no\n * usable influence (its splats' bones have no home on this rig) goes to the\n * identity slot `numBones` with full weight, which pins it at bind - the\n * place those splats stay too. three's skinning would otherwise send it to\n * the origin.\n */\nfunction addSkinAttributes(geometry: BufferGeometry, indices: Float32Array, weights: Float32Array, numBones: number): void {\n const n = weights.length / 4;\n const skinIndex = new Uint16Array(n * 4);\n const skinWeight = new Float32Array(weights);\n for (let v = 0; v < n; v++) {\n let total = 0;\n for (let j = 0; j < 4; j++) {\n const i = v * 4 + j;\n skinIndex[i] = indices[i];\n if (weights[i] > 0) total += weights[i];\n }\n if (total > 0) continue;\n skinIndex[v * 4] = numBones;\n skinWeight[v * 4] = 1;\n }\n geometry.setAttribute('skinIndex', new Uint16BufferAttribute(skinIndex, 4));\n geometry.setAttribute('skinWeight', new BufferAttribute(skinWeight, 4));\n}\n\n/**\n * A shadow caster's world bounds as they are this frame, or null when empty.\n * A skinned mesh's come from its bones' current poses, as PlayCanvas bounds a\n * skinned mesh instance - not its bind-pose box, which a jump or a crouch\n * leaves, so the shadow camera would clip the caster.\n */\nfunction casterWorldBox(mesh: Mesh, out: Box3): Box3 | null {\n if ((mesh as SkinnedMesh).isSkinnedMesh) {\n const box = skinnedWorldBox(mesh as SkinnedMesh, out);\n if (box !== undefined) return box;\n }\n let local: Box3 | null;\n if ((mesh as unknown as InstancedMesh).isInstancedMesh || (mesh as SkinnedMesh).isSkinnedMesh) {\n const bounded = mesh as unknown as InstancedMesh;\n const version = bounded.isInstancedMesh ? bounded.instanceMatrix.version : 0;\n // An instanced mesh's box follows its instances.\n if (!bounded.boundingBox || _boundsVersion.get(mesh) !== version) {\n bounded.computeBoundingBox();\n _boundsVersion.set(mesh, version);\n }\n local = bounded.boundingBox;\n } else {\n if (!mesh.geometry.boundingBox) mesh.geometry.computeBoundingBox();\n local = mesh.geometry.boundingBox;\n }\n if (!local || local.isEmpty()) return null;\n return out.copy(local).applyMatrix4(mesh.matrixWorld);\n}\n\n/**\n * Each bone's box of the vertices it moves, in that bone's bind space: 6\n * floats per bone, min then max, min > max when it moves none. Built once per\n * mesh and geometry. Undefined when the mesh has no skin to read.\n */\nfunction boneBoxesOf(mesh: SkinnedMesh): Float32Array | undefined {\n const geometry = mesh.geometry;\n const position = geometry.getAttribute('position');\n const skinIndex = geometry.getAttribute('skinIndex');\n const skinWeight = geometry.getAttribute('skinWeight');\n const skeleton = mesh.skeleton;\n if (!position || !skinIndex || !skinWeight || !skeleton) return undefined;\n const numBones = skeleton.bones.length;\n // An interleaved attribute's version is its buffer's.\n const version = (position as BufferAttribute).isBufferAttribute\n ? (position as BufferAttribute).version\n : (position as unknown as { data: { version: number } }).data.version;\n const cached = _boneBoxes.get(mesh);\n if (cached && cached.geometry === geometry && cached.version === version && cached.numBones === numBones) {\n return cached.boxes;\n }\n const boxes = new Float32Array(numBones * 6);\n for (let b = 0; b < numBones; b++) {\n boxes.fill(Infinity, b * 6, b * 6 + 3);\n boxes.fill(-Infinity, b * 6 + 3, b * 6 + 6);\n }\n for (let i = 0; i < position.count; i++) {\n _skinVertex.fromBufferAttribute(position, i).applyMatrix4(mesh.bindMatrix);\n for (let j = 0; j < 4; j++) {\n if (skinWeight.getComponent(i, j) === 0) continue;\n const b = skinIndex.getComponent(i, j);\n const inverse = skeleton.boneInverses[b];\n if (b >= numBones || !inverse) continue;\n _boneVertex.copy(_skinVertex).applyMatrix4(inverse);\n const o = b * 6;\n if (_boneVertex.x < boxes[o]) boxes[o] = _boneVertex.x;\n if (_boneVertex.y < boxes[o + 1]) boxes[o + 1] = _boneVertex.y;\n if (_boneVertex.z < boxes[o + 2]) boxes[o + 2] = _boneVertex.z;\n if (_boneVertex.x > boxes[o + 3]) boxes[o + 3] = _boneVertex.x;\n if (_boneVertex.y > boxes[o + 4]) boxes[o + 4] = _boneVertex.y;\n if (_boneVertex.z > boxes[o + 5]) boxes[o + 5] = _boneVertex.z;\n }\n }\n _boneBoxes.set(mesh, { geometry, version, numBones, boxes });\n return boxes;\n}\n\n/**\n * A skinned mesh's world bounds from its bones' current world matrices: the\n * union of each bone's vertex box as that bone has moved it. Skinning blends\n * a vertex between its bones' placements, so the union holds it. Undefined\n * when the mesh has no skin to read; null when it has no vertices.\n */\nfunction skinnedWorldBox(mesh: SkinnedMesh, out: Box3): Box3 | null | undefined {\n const boxes = boneBoxesOf(mesh);\n if (!boxes) return undefined;\n out.makeEmpty();\n // world = matrixWorld * bindMatrixInverse * boneWorld * boneInverse * bindMatrix * v\n _skinToWorld.multiplyMatrices(mesh.matrixWorld, mesh.bindMatrixInverse);\n const bones = mesh.skeleton.bones;\n for (let b = 0; b < bones.length; b++) {\n const o = b * 6;\n if (boxes[o] > boxes[o + 3]) continue;\n _boneBox.min.set(boxes[o], boxes[o + 1], boxes[o + 2]);\n _boneBox.max.set(boxes[o + 3], boxes[o + 4], boxes[o + 5]);\n const bone = bones[b];\n _boneToWorld.copy(_skinToWorld);\n if (bone) _boneToWorld.multiply(bone.matrixWorld);\n out.union(_boneBox.applyMatrix4(_boneToWorld));\n }\n return out.isEmpty() ? null : out;\n}\n\nconst _boneBoxes = new WeakMap<SkinnedMesh, { geometry: BufferGeometry; version: number; numBones: number; boxes: Float32Array }>();\nconst _boundsVersion = new WeakMap<Mesh, number>();\nconst _skinVertex = new Vector3();\nconst _boneVertex = new Vector3();\nconst _boneBox = new Box3();\nconst _skinToWorld = new Matrix4();\nconst _boneToWorld = new Matrix4();\n\n/** Copy the armature's bone world matrices onto a proxy skeleton's bones. */\nfunction poseSkeleton(entry: TargetEntry): void {\n const bones = entry.skeleton!.bones;\n const world = entry.character!.armature.boneWorldMatrices;\n // The last bone is the identity slot and keeps its identity world matrix.\n for (let b = 0; b < bones.length - 1; b++) {\n const m = world[b];\n if (m) bones[b].matrixWorld.fromArray(m.data);\n }\n}\n\n/** The voxelizer knobs as a comparable string. */\nfunction proxyKey(p: RelightProxySettings): string {\n return `${p.surface}|${p.voxelSize}|${p.opacityThreshold}|${p.dilate}|${p.smoothIterations}|${p.floorFill}`;\n}\n\n/** Enabled on exactly `layers`. */\nfunction layerMask(layers: readonly number[]): number {\n let mask = 0;\n for (const id of layers) mask |= 1 << (id | 0);\n return mask;\n}\n\n/**\n * Give a light PlayCanvas's delivered colour: `linear(colour) * intensity`,\n * or `linear(colour * intensity)` below 1 (pow 2.2, as PlayCanvas\n * linearizes), with `colour` gamma-space. Stored as three colour * intensity,\n * so `intensity` still reads as what was asked for.\n */\nfunction setPlayCanvasLightColor(light: Light, gamma: Color, intensity: number): void {\n const k = intensity >= 1 ? intensity : 1;\n const pre = intensity >= 1 ? 1 : intensity;\n const scale = intensity > 0 ? k / intensity : 1;\n light.color.setRGB(\n Math.pow(gamma.r * pre, 2.2) * scale,\n Math.pow(gamma.g * pre, 2.2) * scale,\n Math.pow(gamma.b * pre, 2.2) * scale,\n );\n light.intensity = intensity;\n}\n\n/** See {@link RelightLightOptions.shadowType}. */\nfunction applyShadowType(scene: Scene, light: DirectionalLight, type: RelightShadowType, vsmBlurSize: number): void {\n const map = scene.renderer.shadowMap;\n if (type === 'pcf1') {\n map.type = BasicShadowMap;\n } else if (type === 'vsm16' || type === 'vsm32') {\n map.type = VSMShadowMap;\n light.shadow.radius = Math.max(1, (vsmBlurSize - 1) / 2);\n } else {\n if (map.type === BasicShadowMap || map.type === VSMShadowMap) map.type = PCFShadowMap;\n light.shadow.radius = type === 'pcf5' ? 2 : 1;\n }\n}\n\n/**\n * The preview's look: the PlayCanvas build's teal surface with a headlight\n * from above-left, as a matcap - which IS a headlight, since a matcap is\n * indexed by the view-space normal - so the preview needs no light of its\n * own that could reach the scene.\n */\nfunction previewMatcap(): DataTexture {\n const size = 64;\n const data = new Uint8Array(size * size * 4);\n const diffuse = [0.13, 0.62, 0.72].map((c) => Math.pow(c, 2.2) * 1.2);\n const floor = [0.03, 0.12, 0.15].map((c) => Math.pow(c, 2.2));\n const l = new Vector3(-0.5, 0.6, 0.62).normalize();\n for (let y = 0; y < size; y++) {\n for (let x = 0; x < size; x++) {\n const nx = ((x + 0.5) / size) * 2 - 1;\n const ny = ((y + 0.5) / size) * 2 - 1;\n const nz = Math.sqrt(Math.max(0, 1 - nx * nx - ny * ny));\n const ndl = Math.max(0, nx * l.x + ny * l.y + nz * l.z);\n const o = (y * size + x) * 4;\n for (let c = 0; c < 3; c++) {\n data[o + c] = Math.round(255 * Math.min(1, Math.pow(floor[c] + diffuse[c] * ndl, 1 / 2.2)));\n }\n data[o + 3] = 255;\n }\n }\n const tex = new DataTexture(data, size, size);\n tex.colorSpace = SRGBColorSpace;\n tex.needsUpdate = true;\n return tex;\n}\n\n/** A colour as given: a CSS string's channels, or a `Color`'s, with no colour-space conversion. */\nfunction setRawColor(out: Color, c: string | Color): Color {\n // `setStyle` converts from the given space to the working one, which is\n // linear: naming linear as the source is what makes it no conversion.\n if (typeof c === 'string') out.setStyle(c, LinearSRGBColorSpace);\n else out.copy(c);\n return out;\n}\n\nfunction clamp(v: number, lo: number, hi: number): number {\n return v < lo ? lo : v > hi ? hi : v;\n}\n\nfunction clamp01(v: number): number {\n return clamp(v, 0, 1);\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n const out: Partial<T> = {};\n for (const k of Object.keys(o) as (keyof T)[]) {\n if (o[k] !== undefined) out[k] = o[k];\n }\n return out;\n}\n", "/**\n * The pure half of reading an environment for its proxy: the world-space\n * crop. No three.js and no I/O, so it runs under `node --test`.\n * `environment-source.ts` is the half that touches the splat.\n *\n * The PlayCanvas build also keeps its LOD-bundle slicing here; this port loads\n * monolithic captures only, so that half has nothing to read yet.\n *\n * Internal.\n */\n\nimport type { ProxyMeshInput } from './voxelizer';\n\n/**\n * Keep only the splats whose WORLD position is inside `[min, max]`, given the\n * local-to-world matrix of the node the positions are local to. Returns the\n * input itself when nothing is dropped. Pure.\n *\n * Why a crop exists at all: the voxelizer sizes one dense grid to the bounds of\n * everything it is given, and a capture's bounds are set by its floaters, not\n * its floor. A room whose walls span 6 m can carry wisps 20 m out, and the\n * grid ceiling then coarsens the whole room to fit them.\n */\nexport function cropInputToWorldBox(\n input: ProxyMeshInput,\n localToWorld: ArrayLike<number>,\n min: { x: number; y: number; z: number },\n max: { x: number; y: number; z: number },\n): ProxyMeshInput {\n const p = input.positions;\n const n = Math.floor(p.length / 3);\n const m = localToWorld;\n const keep = new Uint8Array(n);\n let kept = 0;\n for (let i = 0; i < n; i++) {\n const x = p[i * 3], y = p[i * 3 + 1], z = p[i * 3 + 2];\n // Column-major, the layout of three's `Matrix4.elements`.\n const wx = m[0] * x + m[4] * y + m[8] * z + m[12];\n const wy = m[1] * x + m[5] * y + m[9] * z + m[13];\n const wz = m[2] * x + m[6] * y + m[10] * z + m[14];\n if (wx < min.x || wy < min.y || wz < min.z || wx > max.x || wy > max.y || wz > max.z) continue;\n keep[i] = 1;\n kept++;\n }\n if (kept === n) return input;\n\n const positions = new Float32Array(kept * 3);\n const opacities = input.opacities ? new Float32Array(kept) : undefined;\n let w = 0;\n for (let i = 0; i < n; i++) {\n if (!keep[i]) continue;\n positions[w * 3] = p[i * 3];\n positions[w * 3 + 1] = p[i * 3 + 1];\n positions[w * 3 + 2] = p[i * 3 + 2];\n if (opacities) opacities[w] = input.opacities![i];\n w++;\n }\n return { positions, opacities };\n}\n", "/**\n * Environment -> {@link ProxyMeshInput}.\n *\n * Reads the splat that draws the environment: its rest centres and alphas,\n * with no network and no decompress. For a monolithic capture that is the\n * whole capture. For a streaming LOD bundle it is whatever the bundle had\n * streamed in when the proxy was first built - the PlayCanvas build instead\n * fetches one chosen level's chunk files itself, which this port's bundle\n * loader does not expose yet.\n *\n * Positions come out in the environment object's LOCAL space - the proxy is\n * parented to that object, so any authored transform applies to it exactly as\n * it applies to the splats. No skinning.\n *\n * Internal. `SplatRelight` is the consumer.\n */\n\nimport { Matrix4 } from 'three';\n\nimport type { Environment } from '../environment';\n\nimport { alphasOf } from './splat-source';\nimport type { ProxyMeshInput } from './voxelizer';\n\n/** What {@link proxyInputFromEnvironment} read, and from where. */\nexport interface EnvironmentProxySource {\n input: ProxyMeshInput;\n /** LOD level read, `null` for a monolithic capture. `0` is the finest. */\n lodLevel: number | null;\n /** Levels the capture has; `1` for a monolithic capture. */\n lodLevels: number;\n /** Milliseconds from the call to the input being ready. */\n loadMs: number;\n}\n\n/**\n * The largest axis scale of a local-to-world matrix - what turns a voxel size\n * in world metres into the local units the proxy is built in.\n */\nexport function maxAxisScale(localToWorld: Matrix4): number {\n const d = localToWorld.elements;\n const sx = Math.hypot(d[0], d[1], d[2]);\n const sy = Math.hypot(d[4], d[5], d[6]);\n const sz = Math.hypot(d[8], d[9], d[10]);\n return Math.max(sx, sy, sz, 1e-6);\n}\n\nconst _relative = new Matrix4();\n\n/**\n * Read an environment's splat centres and alphas, in its local space. `null`\n * while a LOD bundle has not streamed anything in yet.\n */\nexport function proxyInputFromEnvironment(env: Environment): EnvironmentProxySource | null {\n const splat = env.splat;\n if (!splat) return null;\n const t0 = performance.now();\n const n = splat.numSplats;\n const positions = new Float32Array(splat.packed.centers.subarray(0, n * 3));\n if (splat.object3D !== env.object3D) {\n // A bundle's splat hangs under the environment's root; bring its centres\n // into the root's space, which is where the proxy is parented.\n env.object3D.updateWorldMatrix(true, true);\n _relative.copy(env.object3D.matrixWorld).invert().multiply(splat.object3D.matrixWorld);\n const m = _relative.elements;\n for (let i = 0; i < n * 3; i += 3) {\n const x = positions[i], y = positions[i + 1], z = positions[i + 2];\n positions[i] = m[0] * x + m[4] * y + m[8] * z + m[12];\n positions[i + 1] = m[1] * x + m[5] * y + m[9] * z + m[13];\n positions[i + 2] = m[2] * x + m[6] * y + m[10] * z + m[14];\n }\n }\n const input: ProxyMeshInput = { positions, opacities: alphasOf(splat.packed) };\n return { input, lodLevel: null, lodLevels: 1, loadMs: performance.now() - t0 };\n}\n", "/**\n * Splat cloud -> {@link ProxyMeshInput}.\n *\n * Three conversions the voxelizer deliberately does NOT do for you, because\n * doing them would give a pure geometry module opinions about our container\n * format:\n *\n * 1. **Unpack.** A {@link Splat} keeps its gaussians in the texel streams the\n * shaders read; the voxelizer wants one `[x,y,z]` stream and one alpha per\n * splat, because that is what every other mesh pipeline in the world wants.\n * 2. **Decode the alpha.** `packSplats` already ran the sigmoid and stored the\n * ALPHA as a half float, so it is decoded here, never pushed through\n * {@link alphaFromLogits} a second time - thresholding a twice-sigmoided\n * value against 0.04 keeps every splat, and fails silently by producing a\n * mesh that is merely a bit too fat.\n * 3. **Remap the bone indices.** A bundle's weights are authored against the\n * SOURCE rig (often 1185 or 441 bones); the armature the proxy will be\n * skinned by is usually the 86-bone body rig. `buildSourceBoneRemap` is the\n * same mapping `initializeSplatBoneMapping` applies to the GPU bone\n * textures, so the proxy and the splats end up following the same bones.\n *\n * Internal. `SplatRelight` is the consumer.\n */\n\nimport { DataUtils } from 'three';\n\nimport type { Armature } from '../armature';\nimport type { SplatEngine } from '../engine';\nimport { buildSourceBoneRemap } from '../splat/bone-binding';\nimport type { PackedSplats } from '../splat/packed-splats';\nimport type { Splat } from '../splat/splat';\n\nimport type { ProxyMeshInput } from './voxelizer';\n\n/** Influences the voxelizer reads per splat. */\nconst INFLUENCES = 4;\n\n/**\n * Pull the rest positions, alpha and (when the splat is skinned) armature-space\n * bone influences out of a loaded splat.\n *\n * Positions come out in BIND space - the space `Armature.inverseBindPose`\n * undoes - so a mesh built from them is skinned by `boneWorld * inverseBind`\n * straight into world space.\n *\n * Allocates the whole input. Call it once per character, not once per rebuild:\n * the voxel knobs are what move while tuning and none of this depends on them.\n */\nexport function proxyInputFromSplat(\n splat: Splat,\n armature: Armature | null,\n engine: SplatEngine,\n): ProxyMeshInput {\n const n = splat.numSplats;\n // Copied, not aliased: a skinned splat's `centers` is the posed buffer, and\n // the rest centres in `packed` are shared with every clone of the splat.\n const positions = new Float32Array(splat.packed.centers.subarray(0, n * 3));\n const opacities = alphasOf(splat.packed);\n\n const weights = splat.splatWeights;\n if (!weights || !armature) return { positions, opacities };\n\n const numBones = armature.numBones;\n const remap = buildSourceBoneRemap(splat, numBones, engine.skeletonLibrary);\n // `Splat` normalises its weights to exactly four slots, the heaviest first -\n // the same slice the GPU bone textures take.\n const boneIndices = new Uint32Array(n * INFLUENCES);\n const boneWeights = new Float32Array(n * INFLUENCES);\n for (let i = 0; i < n * INFLUENCES; i++) {\n const raw = weights.indices[i];\n const target = remap ? (remap[raw] ?? -1) : raw;\n // Out of range means the influence has no home on this rig - typically a\n // facial bone on a body-only armature. Weight 0 leaves the vertex to its\n // other influences instead of dragging it to the root.\n if (target < 0 || target >= numBones) continue;\n boneIndices[i] = target;\n boneWeights[i] = weights.weights[i];\n }\n\n return { positions, opacities, boneIndices, boneWeights };\n}\n\n/** Every splat's alpha, decoded from the half float `packSplats` stored. */\nexport function alphasOf(packed: PackedSplats): Float32Array {\n const n = packed.numSplats;\n const out = new Float32Array(n);\n const color = packed.color;\n for (let i = 0; i < n; i++) out[i] = DataUtils.fromHalfFloat(color[i * 4 + 3]);\n return out;\n}\n", "import { BufferAttribute, BufferGeometry, Color, DynamicDrawUsage, LineBasicMaterial, LineSegments } from 'three';\nimport type { Object3D } from 'three';\n\nimport type { Armature } from '../armature';\nimport { Mat4 } from '../math';\nimport type { Scene } from '../scene';\n\nimport type { ProxyMeshResult } from './voxelizer';\n\n/**\n * What the overlay draws.\n *\n * - `off` - nothing. Consumers still get the mesh; only the preview stops.\n * - `voxels` - the exact cell boundary, blocky on purpose. This is what you\n * judge {@link ProxySettings.voxelSize} against, and it stays blocky\n * whatever finish the real mesh is using.\n * - `mesh` - the reconstructed surface, i.e. exactly what a consumer gets.\n */\nexport type ProxyDebugMode = 'off' | 'voxels' | 'mesh';\n\n/** Configuration for {@link ProxyMeshDebug.create}. */\nexport interface ProxyMeshDebugOptions {\n /** `mesh` mode line colour, CSS hex. Default `#22d3ee`. */\n color?: string;\n /** `voxels` mode line colour, CSS hex. Default `#f59e0b`. */\n voxelColor?: string;\n /** Start in this mode. Default `off`. */\n mode?: ProxyDebugMode;\n /**\n * Hide lines behind geometry. Default `false` - the overlay reads as an\n * overlay, and splats write no depth to test against anyway.\n */\n depthTest?: boolean;\n}\n\n/**\n * Wireframe preview of a proxy mesh, skinned on the CPU by the same rig the\n * mesh is.\n *\n * The whole surface is ONE `LineSegments` whose positions are refilled each\n * drawn frame: a character proxy is thousands of quads, and an object per\n * voxel would be thousands of draws a frame.\n *\n * Edges come from {@link ProxyMeshResult.quads}, not from the triangle list.\n * The triangulation diagonals are an artefact of the index buffer, and drawing\n * them turns a readable voxel boundary into a hatched mess that hides the\n * thing you switched the overlay on to see.\n *\n * ```ts\n * const debug = ProxyMeshDebug.create(scene);\n * debug.setMesh(buildProxyMesh(input, settings));\n * debug.setVoxels(buildProxyMesh(input, { ...settings, surface: 'blocky', smoothIterations: 0 }));\n * debug.armature = character.armature;\n * debug.mode = 'voxels';\n * ```\n *\n * Internal. Not part of the published surface.\n */\nexport class ProxyMeshDebug {\n /** What to draw. Cheap to flip - no rebuild, no scene-graph churn. */\n mode: ProxyDebugMode;\n\n /**\n * Rig to skin the lines by. `null` draws the geometry where it was built,\n * which is right for a static capture and wrong for a character.\n *\n * The surface must be in BIND space, which is what the voxelizer produces\n * when it is fed the splats' rest positions.\n */\n armature: Armature | null = null;\n\n /**\n * Object the surface was built in the local space of, for a static proxy -\n * a splat that no armature drives. Ignored while {@link armature} is set,\n * whose chain already ends in world space. `null` draws the positions as\n * world-space.\n */\n node: Object3D | null = null;\n\n private readonly _color: Color;\n private readonly _voxelColor: Color;\n private readonly _material: LineBasicMaterial;\n private readonly _lines: LineSegments;\n private readonly _offPreRender: () => void;\n\n private _mesh: LineSet | null = null;\n private _voxels: LineSet | null = null;\n /** The set {@link _lines} currently holds a buffer for. */\n private _shown: LineSet | null = null;\n\n /** `boneWorld[i] * inverseBindPose[i]`, rebuilt each drawn frame. */\n private readonly _skin: Mat4[] = [];\n\n static create(scene: Scene, opts?: ProxyMeshDebugOptions): ProxyMeshDebug {\n return new ProxyMeshDebug(scene, opts);\n }\n\n private constructor(scene: Scene, opts?: ProxyMeshDebugOptions) {\n this._color = new Color(opts?.color ?? '#22d3ee');\n this._voxelColor = new Color(opts?.voxelColor ?? '#f59e0b');\n this.mode = opts?.mode ?? 'off';\n this._material = new LineBasicMaterial({\n depthTest: opts?.depthTest ?? false,\n depthWrite: false,\n transparent: true,\n toneMapped: false,\n });\n this._lines = new LineSegments(new BufferGeometry(), this._material);\n this._lines.name = 'proxy-mesh-debug';\n this._lines.frustumCulled = false;\n // After the splats, which are transparent: an overlay reads over them.\n this._lines.renderOrder = 1e6;\n this._lines.visible = false;\n scene.threeScene.add(this._lines);\n this._offPreRender = scene.on('preRender', () => this._draw());\n }\n\n /** The reconstructed surface, for `mesh` mode. `null` blanks that mode. */\n setMesh(result: ProxyMeshResult | null): void {\n this._mesh = result ? lineSetOf(result) : null;\n }\n\n /**\n * The blocky cell boundary, for `voxels` mode. Pass a build made with\n * `{ surface: 'blocky', smoothIterations: 0 }` over the SAME input and voxel\n * size - previewing the cells means showing the cells, whatever finish the\n * real mesh is using.\n */\n setVoxels(result: ProxyMeshResult | null): void {\n this._voxels = result ? lineSetOf(result) : null;\n }\n\n /** Line segments the current mode would submit. For a HUD. */\n get lineCount(): number {\n const set = this.mode === 'voxels' ? this._voxels : this.mode === 'mesh' ? this._mesh : null;\n return set ? set.edges.length / 2 : 0;\n }\n\n destroy(): void {\n this._offPreRender();\n this._lines.removeFromParent();\n this._lines.geometry.dispose();\n this._material.dispose();\n this.armature = null;\n this.node = null;\n this._mesh = null;\n this._voxels = null;\n this._shown = null;\n }\n\n private _draw(): void {\n const set = this.mode === 'voxels' ? this._voxels : this.mode === 'mesh' ? this._mesh : null;\n this._lines.visible = !!set && set.edges.length > 0;\n if (!set || !this._lines.visible) return;\n\n if (this._shown !== set) {\n // One buffer per set, sized when it is first shown: a per-frame\n // reallocation of 30k numbers is what this avoids.\n const geometry = new BufferGeometry();\n const attr = new BufferAttribute(set.buffer, 3);\n attr.setUsage(DynamicDrawUsage);\n geometry.setAttribute('position', attr);\n this._lines.geometry.dispose();\n this._lines.geometry = geometry;\n this._shown = set;\n }\n this._material.color.copy(this.mode === 'voxels' ? this._voxelColor : this._color);\n\n this._deform(set);\n const buf = set.buffer;\n const world = set.world;\n const edges = set.edges;\n for (let e = 0, w = 0; e < edges.length; e++, w += 3) {\n const v = edges[e] * 3;\n buf[w] = world[v];\n buf[w + 1] = world[v + 1];\n buf[w + 2] = world[v + 2];\n }\n this._lines.geometry.getAttribute('position').needsUpdate = true;\n }\n\n /**\n * Bind-space vertices to world, by linear blend skinning.\n *\n * The chain is `boneWorld * inverseBindPose * v`, with no object transform\n * in it: the relight's skinned proxy evaluates\n * `objectWorld * inv(objectWorld) * boneWorld * invBind * v`, in which the\n * object transform cancels. Applying it here as well would put the overlay\n * somewhere the mesh is not, by exactly that transform.\n */\n private _deform(set: LineSet): void {\n const arm = this.armature;\n const world = set.world;\n const rest = set.rest;\n\n if (!arm || !set.boneIndices || !set.boneWeights) {\n if (!this.node) { world.set(rest); return; }\n this.node.updateWorldMatrix(true, false);\n const m = this.node.matrixWorld.elements;\n for (let v = 0; v < rest.length; v += 3) {\n const rx = rest[v], ry = rest[v + 1], rz = rest[v + 2];\n world[v] = m[0] * rx + m[4] * ry + m[8] * rz + m[12];\n world[v + 1] = m[1] * rx + m[5] * ry + m[9] * rz + m[13];\n world[v + 2] = m[2] * rx + m[6] * ry + m[10] * rz + m[14];\n }\n return;\n }\n\n const boneWorld = arm.boneWorldMatrices;\n const invBind = arm.inverseBindPose;\n const numBones = Math.min(boneWorld.length, invBind.length);\n if (numBones === 0) { world.set(rest); return; }\n\n while (this._skin.length < numBones) this._skin.push(new Mat4());\n for (let i = 0; i < numBones; i++) this._skin[i].mul2(boneWorld[i], invBind[i]);\n\n const idx = set.boneIndices;\n const wts = set.boneWeights;\n const count = rest.length / 3;\n for (let v = 0; v < count; v++) {\n const rx = rest[v * 3], ry = rest[v * 3 + 1], rz = rest[v * 3 + 2];\n let ox = 0, oy = 0, oz = 0, total = 0;\n for (let j = 0; j < 4; j++) {\n const w = wts[v * 4 + j];\n if (!(w > 0)) continue;\n const b = idx[v * 4 + j];\n if (b < 0 || b >= numBones) continue;\n const m = this._skin[b].data;\n ox += w * (m[0] * rx + m[4] * ry + m[8] * rz + m[12]);\n oy += w * (m[1] * rx + m[5] * ry + m[9] * rz + m[13]);\n oz += w * (m[2] * rx + m[6] * ry + m[10] * rz + m[14]);\n total += w;\n }\n if (total > 0) {\n world[v * 3] = ox; world[v * 3 + 1] = oy; world[v * 3 + 2] = oz;\n } else {\n // No usable influence. Leaving it at bind is what the relight's proxy\n // does too, so the overlay keeps agreeing with the mesh.\n world[v * 3] = rx; world[v * 3 + 1] = ry; world[v * 3 + 2] = rz;\n }\n }\n }\n}\n\n/** One surface, pre-chewed into everything the per-frame path needs. */\ninterface LineSet {\n /** Bind-space vertex positions, `[x,y,z] * vertexCount`. */\n rest: Float32Array;\n /** Skinned output, same shape. */\n world: Float32Array;\n boneIndices: Float32Array | null;\n boneWeights: Float32Array | null;\n /** Deduplicated edge endpoints, 2 vertex indices a segment. */\n edges: Uint32Array;\n /** Flat `[x,y,z]` per endpoint, refilled each frame and uploaded as the line positions. */\n buffer: Float32Array;\n}\n\n/**\n * Deduplicate the quad edges of a surface.\n *\n * Every interior edge is shared by two quads, so this halves the segment count\n * - which on a proxy mesh is the difference between 36k and 18k points going\n * up every frame.\n */\nfunction lineSetOf(result: ProxyMeshResult): LineSet {\n const seen = new Set<number>();\n const edges: number[] = [];\n const stride = result.vertexCount;\n const quads = result.quads;\n for (let f = 0; f < quads.length; f += 4) {\n for (let k = 0; k < 4; k++) {\n const a = quads[f + k];\n const b = quads[f + ((k + 1) & 3)];\n const key = a < b ? a * stride + b : b * stride + a;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push(a, b);\n }\n }\n return {\n rest: result.positions,\n world: new Float32Array(result.positions.length),\n boneIndices: result.boneIndices,\n boneWeights: result.boneWeights,\n edges: new Uint32Array(edges),\n buffer: new Float32Array(edges.length * 3),\n };\n}\n", "/**\n * Splats in, a closed triangle surface out.\n *\n * A splat cloud is not lit geometry. Anything that needs a SURFACE from it -\n * relighting, cast shadows, coverage masks - needs the same thing first: the\n * boundary of the volume the splats occupy, closed, welded and cheap. This\n * module is that step and nothing else. It touches no GPU, no scene and no\n * PlayCanvas type, so it can be called from a worker, from a test, or from a\n * build script with equal safety.\n *\n * WHY VOXELS AND NOT A HULL OR A POINT-CLOUD RECONSTRUCTION. The surface only\n * has to be closed and roughly in the right place - it is never seen, only lit.\n * A voxel grid is the one reconstruction whose error is bounded by a number the\n * caller sets ({@link ProxySettings.voxelSize}) and whose output is watertight\n * by construction: the boundary of a set of cells is always a closed manifold.\n * Convex hulls lose every concavity, which is where the self-shadows are.\n *\n * CLOSED, NOT MANIFOLD. The output has no boundary edges - no holes, so no\n * light leaks - but two cells that meet only along a grid edge leave that edge\n * shared by four faces instead of two. A character at voxel 0.05 comes out\n * with a couple of those out of some seven thousand edges. Harmless for\n * lighting, and inherited from the Unity original; a collision cook or a mesh\n * simplifier that assumes a manifold is where it would bite, and a collider\n * wants its own simplified mesh anyway.\n *\n * ## The two finishes\n *\n * The Unity original this is ported from served two consumers from one mesh,\n * and they wanted different finishes:\n *\n * - **Proxy (relight)** - `smooth`, voxel 0.025, dilate 0, smooth 3, no merge.\n * Smoothing melts the cube staircase so the coverage silhouette and the\n * self-shadows stay stable while the mesh animates. Vertices stay on the\n * shared grid, so the Laplacian has neighbours to average over.\n * - **Collider** - `smooth` (Surface Nets), dilate 1, a relaxation pass or\n * two. One vertex per boundary cell, free to sit anywhere inside it, so a\n * sloped surface comes out sloped instead of as steps. The lighter mesh.\n *\n * We are lighting-only, so {@link defaultProxySettings} is the RELIGHT finish.\n * A collider here would want a simplified mesh built a different way anyway.\n *\n * `blocky` is not a lesser `smooth`. It is the exact boundary of the occupied\n * cells, which is what you want when the CELLS are the thing being looked at -\n * tuning voxel size against the splats. The two answer different questions.\n *\n * ## Which knob actually moves the fit\n *\n * Measured on two shipped characters, over eight yaws, by asking of every\n * splat whether the view line through it hits the proxy at all - which is\n * exactly the relight pass's coverage rule, since that lookup is screen-space\n * with no depth test:\n *\n * - **`voxelSize` is the only knob that changes what the surface resolves.**\n * At 0.05 m a person comes out as one lump: chin welded to chest, forearm\n * welded to torso. At 0.03 the neck and the elbow gap come back, the surface\n * moves from ~69 mm off the nearest splat to ~41 mm, and coverage is\n * unchanged at exact. At 0.02 a sparse capture starts to leak.\n * - **`dilate` buys nothing above 1 and fuses below the voxel scale.** At 1 no\n * splat escapes on either character, from any of the eight yaws. At 0 a\n * thousandth of them do, by up to 14 mm. At 2 the volume grows by half and\n * coverage is still exact - the same number, bought twice.\n * - **`smoothIterations` costs 1.4% of enclosed volume a pass and no\n * coverage.** Eight passes still lose no splat.\n * - **`opacityThreshold` is nearly inert on a character.** Raising it from 0\n * to 0.2 drops 42% of the splats and 0.3% of the occupied cells, because the\n * faint ones sit on top of bright ones. It is a knob for a capture with a\n * real floater halo, not for tuning fit.\n *\n * So a proxy that looks melted is a voxel-size problem every time, and reading\n * it as an erosion problem points at `dilate` and `smoothIterations`, which is\n * the wrong end of the mesh.\n *\n * ## Merging and smoothing are mutually exclusive\n *\n * By construction, not by convention: greedy merging destroys the uniform grid\n * the Laplacian averages over, leaving long thin quads whose interiors have no\n * vertices to move. {@link buildProxyMesh} throws on the combination rather\n * than quietly producing a surface that is neither merged well nor smoothed\n * well.\n *\n * ## The grid is a product of its own\n *\n * {@link buildVoxelGrid} stops after the occupancy and hands the grid back.\n * That is not a convenience wrapper - it is the half of this module a COLLIDER\n * wants, and the mesh is the half it must not have. The extracted surface is\n * closed but not manifold (see above), so a physics cook or a simplifier\n * chokes on it, while a grid lookup - topmost occupied cell in a column is the\n * floor, an occupied cell at knee height is a wall - needs no cook at all. So\n * the collider reads the grid, the extraction it would throw away never runs,\n * and neither consumer is paying for the other's finish. See\n * `../collider/scene-collider.ts`.\n *\n * @module\n */\n\n/** How the occupied set is turned into triangles. */\nexport type ProxySurfaceStyle = 'blocky' | 'smooth';\n\n/**\n * How a splat cloud should be turned into a surface. Every field is optional;\n * omitted fields take the relight finish from {@link defaultProxySettings}.\n */\nexport interface ProxySettings {\n /**\n * `blocky` = the exact cell boundary, every face a square on the grid.\n * `smooth` = Surface Nets: one vertex per boundary cell, free to sit\n * anywhere inside it, so a sloped surface comes out sloped rather than as\n * steps - truer AND lighter, and the right choice for a collider.\n *\n * Default `blocky`, the relight finish. See the module header.\n */\n surface?: ProxySurfaceStyle;\n\n /**\n * Edge length of one voxel, in metres. THE knob, and the only one that\n * changes what the surface can RESOLVE. Too coarse seals gaps that should\n * stay open and inflates the silhouette; too fine explodes the triangle\n * count and eventually leaks, because a one-voxel dilation stops being\n * enough to close the pinholes a sparse capture leaves.\n *\n * Default `0.025`. On a 1.9 m character that is ~76 cells of height, 25k\n * triangles and an ~11 ms build. The knee is real: 0.05 fuses the neck, the\n * chin and the gap between a forearm and the torso into one lump at ~69 mm\n * off the nearest splat, 0.03 brings those gaps back at ~40 mm, and 0.02\n * starts to leak on a sparse capture. See the module header.\n */\n voxelSize?: number;\n\n /**\n * Splats fainter than this do not fill a voxel. Raise it to drop the wispy\n * halo of near-transparent floaters that otherwise inflates the volume well\n * past the real surface. This is an ALPHA in `[0,1]`, not a logit - see\n * {@link ProxyMeshInput.opacities}. Default `0.04` - low, because 0.2 drops\n * the faint splats that carry a capture's thin geometry. See\n * {@link defaultProxySettings}.\n */\n opacityThreshold?: number;\n\n /**\n * Grow the volume outward this many voxels. One step closes the pinholes a\n * sparse surface leaves. For LIGHTING this wants to be at least 1, so edge\n * splats land inside the coverage mask rather than on its rim. Default `1`.\n *\n * It is also the knob that FUSES: a dilation of one bridges every gap\n * narrower than two voxels, so at a coarse voxel size it is what welds an\n * arm to a torso. Raising it does not buy coverage - coverage is already\n * exact at 1 on a character - it only inflates. When the proxy looks like a\n * melted lump, this is not the knob; {@link voxelSize} is.\n */\n dilate?: number;\n\n /**\n * Laplacian relaxation passes. On `smooth` this polishes an already-smooth\n * surface and 1-2 passes is plenty. On `blocky` it is the ONLY thing that\n * rounds the cubes and needs more passes to do it. Every pass shrinks the\n * surface slightly, which is why the volume is dilated outward first.\n * Default `3`.\n */\n smoothIterations?: number;\n\n /**\n * Fill every column solid from the grid floor up to its lowest occupied\n * voxel. A raw voxelization of an exterior capture is a SHELL: the ground is\n * one voxel thick. Filling underneath turns the shell into ground with\n * substance below it. Meaningless for a character or a prop, where there is\n * no \"underneath\" - leave it off. Default `false`.\n */\n floorFill?: boolean;\n\n /**\n * Greedily merge coplanar faces into the largest rectangles that tile them.\n * Cuts the triangle count of a blocky surface by an order of magnitude at no\n * fidelity cost - the merged surface is geometrically IDENTICAL, it just\n * stops spending four vertices on every one-voxel square.\n *\n * Rejected together with {@link smoothIterations}, and ignored entirely on\n * `smooth` (Surface Nets emits no coplanar squares to merge). Default\n * `false`.\n */\n mergeCoplanar?: boolean;\n\n /**\n * Grid ceiling, in cells. A bad voxel size on a large capture would\n * otherwise allocate a pathological grid; the build coarsens the voxel size\n * by 1.5x until it fits, because a coarser surface is still a usable surface\n * and an out-of-memory is not. Default `4_000_000`.\n */\n maxVoxels?: number;\n}\n\n/**\n * Clear cells the surface extraction needs on every side of the occupied set.\n *\n * `emitPerVoxel` reads a cell's six neighbours and treats anything off the grid\n * as empty, so one would do for it. Surface Nets reads the 2x2x2 block of\n * lattice points around each dual cell and emits a quad only where all four\n * cells around a sign-changing edge produced a vertex, so it needs a clear cell\n * one FURTHER out: with a single clear layer its boundary quads are never\n * emitted and the surface comes out with holes, which is a light leak and the\n * one invariant this module promises.\n *\n * Two places have to respect it - the bounding pad, and the floor fill, which\n * writes downward and would otherwise run into the floor of the grid. Both went\n * unseen while the defaults were `blocky` + `dilate: 1`, where the dilation's\n * own pad covered the first and the finish hid the second.\n */\nconst EXTRACTION_MARGIN = 2;\n\n/**\n * The relight finish: `smooth`, voxel 0.025, opacity 0.04, dilate 0, smooth 3,\n * no merge.\n *\n * Tuned on screen against the bundled character and capture, which is the only\n * test that sees what a reader sees. The measurements are what a future change\n * has to beat rather than rediscover, so they are kept here next to the number\n * that disagreed with them:\n *\n * - **`voxelSize` 0.025.** The measurement always said fine: at 0.05 a person\n * comes out as one lump, chin welded to chest and forearm welded to torso,\n * and the surface sits ~69 mm off the nearest splat; at 0.03 the neck and\n * the elbow gap come back at ~41 mm. This briefly read 0.05 to match the\n * Unity component's default, and that was the wrong thing to match - the\n * Unity number was itself carried over unexamined, and agreeing with it cost\n * the resolution the measurement had already paid for. 0.025 is a step finer\n * again, and on the bundled character it is 7.5k voxels, 25k triangles and\n * an ~11 ms build. Below 0.02 a sparse capture starts to leak.\n * - **`surface` `smooth`, not `blocky`.** Surface Nets puts one vertex per\n * boundary cell free to sit anywhere inside it, so a sloped surface comes\n * out sloped rather than as steps. `blocky` remains the right pick for\n * LOOKING at the cells - it is the exact occupied boundary - which is what\n * the `voxels` preview draws.\n * - **`opacityThreshold` 0.04, not 0.2.** 0.2 drops the faint splats that\n * carry a capture's thin geometry, and the proxy loses surfaces the splats\n * plainly have. 0.04 still filters the near-transparent halo.\n * - **`dilate` 0, not 1.** One ring closes pinholes a sparse capture leaves,\n * and measured, 0 lets a thousandth of the splats escape coverage by up to\n * 14 mm. But a ring is a whole voxel of inflation on a surface that is\n * already outside the splats, and the silhouette reads as a character\n * wearing its proxy. Smoothing and the fine cell absorb what escapes.\n *\n * `floorFill` stays off here and is turned on per target: it is for a capture\n * read as a one-voxel shell, not for a character. See\n * {@link ENVIRONMENT_PROXY_DEFAULTS}.\n */\nexport const defaultProxySettings: Required<ProxySettings> = Object.freeze({\n surface: 'smooth',\n voxelSize: 0.025,\n opacityThreshold: 0.04,\n dilate: 0,\n smoothIterations: 3,\n floorFill: false,\n mergeCoplanar: false,\n maxVoxels: 4_000_000,\n});\n\n/** Integer bone indices, in whatever width the source happened to use. */\nexport type BoneIndexArray = Uint8Array | Uint16Array | Uint32Array | Int32Array;\n\n/** What to voxelize. The bone arrays are optional and drive skinning when present. */\nexport interface ProxyMeshInput {\n /** `[x,y,z] * numSplats`, in the space the caller wants the mesh in. */\n positions: Float32Array;\n /**\n * Per-splat ALPHA in `[0,1]`, one per splat. Omit to count every splat.\n *\n * Our `.vsplat` containers store the LOGIT, not the alpha, so a caller\n * reading `splatData.getProp('opacity')` has to push it through a sigmoid\n * first - {@link alphaFromLogits} does that. Thresholding a logit against\n * 0.2 would keep everything down to alpha 0.55, which is the opposite of\n * what the knob is for.\n */\n opacities?: Float32Array;\n /** `[b0,b1,b2,b3] * numSplats` rig bone indices. Omit for an unskinned build. */\n boneIndices?: BoneIndexArray;\n /** `[w0,w1,w2,w3] * numSplats`, matching {@link boneIndices}. */\n boneWeights?: Float32Array;\n}\n\n/** Grid dimensions or a grid-space point. Plain object: this module has no vector type. */\nexport interface ProxyGridVec {\n x: number;\n y: number;\n z: number;\n}\n\n/**\n * The settings that shape the OCCUPANCY, which is every setting except the\n * ones that only describe a finish. {@link buildVoxelGrid} takes these; the\n * mesh-only knobs (`surface`, `smoothIterations`, `mergeCoplanar`) would have\n * nothing to act on.\n */\nexport type VoxelGridSettings = Pick<\n ProxySettings, 'voxelSize' | 'opacityThreshold' | 'dilate' | 'floorFill' | 'maxVoxels'\n>;\n\n/**\n * The settings that shape the SURFACE, which is the finish and nothing else.\n * {@link extractSurface} takes these; the occupancy already happened by then, so\n * `voxelSize`, `dilate`, `floorFill` and `opacityThreshold` have nothing left to\n * act on.\n */\nexport type SurfaceSettings = Pick<\n ProxySettings, 'surface' | 'smoothIterations' | 'mergeCoplanar'\n>;\n\n/**\n * A voxelized splat cloud, before any surface is extracted from it.\n *\n * What {@link buildProxyMesh} builds first and {@link buildVoxelGrid} stops at.\n * A collider wants exactly this and nothing after it - see the module header.\n */\nexport interface VoxelGrid {\n /**\n * `dims.x * dims.y * dims.z` bytes, 1 where the cell is solid, after\n * dilation and the floor fill. Indexed `(z * dims.y + y) * dims.x + x`.\n * Zero length when the run produced no grid at all.\n */\n occupancy: Uint8Array;\n /** Grid dimensions, in cells. */\n dims: ProxyGridVec;\n /** World position of cell `(0,0,0)`'s low corner. */\n origin: ProxyGridVec;\n /** Cell edge actually used - larger than requested if the grid had to coarsen. */\n voxelSize: number;\n /** Cell edge asked for. Differs from {@link voxelSize} when the grid coarsened. */\n requestedVoxelSize: number;\n /**\n * The grid hit `maxVoxels` and the cell size was raised. User-visible: a\n * reader colliding with a 2.6 m grid they believe is 0.1 m has no way to\n * make sense of what they are walking into.\n */\n coarsened: boolean;\n /** Solid cells after dilation and the floor fill. */\n occupiedVoxels: number;\n /** Splats that passed the opacity threshold. */\n splatsUsed: number;\n /** Milliseconds this build took. */\n buildMs: number;\n}\n\n/** The mesh, plus what the run decided along the way. */\nexport interface ProxyMeshResult {\n /** `[x,y,z] * vertexCount`. Empty when nothing was occupied. */\n positions: Float32Array;\n /** `[x,y,z] * vertexCount`, area-weighted from the faces that share each vertex. */\n normals: Float32Array;\n /** Triangle list, 3 indices a triangle. */\n indices: Uint32Array;\n /**\n * The same surface as {@link indices}, 4 indices a face, before\n * triangulation. Both extraction styles are natively quad-based; this is\n * what a wireframe should walk, because the triangulation diagonals are an\n * artefact of the triangle list and not edges of the surface.\n */\n quads: Uint32Array;\n /** `[b0,b1,b2,b3] * vertexCount` as FLOATS, or `null` when the run was unskinned. */\n boneIndices: Float32Array | null;\n /** `[w0,w1,w2,w3] * vertexCount`, summing to 1 per weighted vertex, or `null`. */\n boneWeights: Float32Array | null;\n\n /** Voxel size actually used - larger than requested if the grid had to coarsen. */\n voxelSize: number;\n /** Grid dimensions, in voxels. */\n dims: ProxyGridVec;\n /** World position of the grid's minimum corner, i.e. of cell `(0,0,0)`'s low corner. */\n origin: ProxyGridVec;\n /** Occupied voxels after dilation and floor fill. */\n occupiedVoxels: number;\n /** Splats that passed the opacity threshold. */\n splatsUsed: number;\n /** `positions.length / 3`. */\n vertexCount: number;\n /** `indices.length / 3`. */\n triangleCount: number;\n /** Milliseconds this build took. */\n buildMs: number;\n}\n\n/**\n * Sigmoid a `.vsplat` opacity column into the alpha\n * {@link ProxyMeshInput.opacities} wants.\n *\n * Allocates. Call it once per capture, not once per rebuild - the voxel knobs\n * are what move while tuning, and the alphas are not among them.\n */\nexport function alphaFromLogits(logits: Float32Array): Float32Array {\n const out = new Float32Array(logits.length);\n for (let i = 0; i < logits.length; i++) out[i] = 1 / (1 + Math.exp(-logits[i]));\n return out;\n}\n\n/**\n * Bone-index keys are packed as `slot * BONE_KEY_STRIDE + bone` into one map,\n * rather than a map per voxel: the per-voxel maps are what made the Unity\n * version allocate a dictionary per occupied cell. The widest rig we ship is\n * 1185 bones, so a 2^20 stride leaves four orders of magnitude of headroom,\n * and the largest key a 4M-cell grid can produce is ~4.2e12 - comfortably an\n * exact integer in a double.\n */\nconst BONE_KEY_STRIDE = 1 << 20;\n\n/** Influences carried per vertex. Matches the four the skinning shader reads. */\nconst INFLUENCES = 4;\n\n/**\n * Voxelize a splat cloud and stop there: the occupancy grid, no surface.\n *\n * Everything {@link buildProxyMesh} does up to the extraction - the opacity\n * threshold, the padded bounds, the coarsen loop, the dilation, the floor fill\n * - and none of what comes after. On a scanned room at a collider's voxel size\n * the extraction is most of the build and all of it would be thrown away; see\n * the module header for why a collider must not have the mesh anyway.\n *\n * Pure. Bone influences on `input` are ignored - a grid has no vertices to\n * weight.\n *\n * @throws RangeError when `voxelSize <= 0`.\n */\nexport function buildVoxelGrid(input: ProxyMeshInput, settings: VoxelGridSettings = {}): VoxelGrid {\n const t0 = now();\n const s = { ...defaultProxySettings, ...stripUndefined(settings) };\n if (!(s.voxelSize > 0)) {\n throw new RangeError(`[buildVoxelGrid] voxelSize must be > 0, got ${s.voxelSize}`);\n }\n const grid = voxelize(input, s, false, t0, '[buildVoxelGrid]');\n return {\n occupancy: grid.occupancy,\n dims: grid.dims,\n origin: grid.origin,\n voxelSize: grid.voxelSize,\n requestedVoxelSize: grid.requestedVoxelSize,\n coarsened: grid.coarsened,\n occupiedVoxels: grid.occupiedVoxels,\n splatsUsed: grid.splatsUsed,\n buildMs: grid.buildMs,\n };\n}\n\n/**\n * Voxelize a splat cloud into a closed triangle surface.\n *\n * Pure: it reads the input arrays and returns fresh ones. The input is never\n * written to and nothing is retained.\n *\n * @param input - Splat centres, opacity, and optionally per-splat bone\n * influences. When both bone arrays are present the result carries\n * per-vertex weights and can be handed straight to `ArmatureSkinAdapter`.\n * @param settings - Overrides on {@link defaultProxySettings}.\n * @throws RangeError when `voxelSize <= 0`, when the bone arrays are the wrong\n * length, or when `mergeCoplanar` is combined with `smoothIterations > 0`.\n */\nexport function buildProxyMesh(\n input: ProxyMeshInput,\n settings: ProxySettings = {},\n): ProxyMeshResult {\n const t0 = now();\n const s = { ...defaultProxySettings, ...stripUndefined(settings) };\n\n // Refused rather than silently reconciled: see the module header. Only\n // `blocky` can hit this - Surface Nets never consults mergeCoplanar.\n if (s.surface === 'blocky' && s.mergeCoplanar && s.smoothIterations > 0) {\n throw new RangeError(\n '[buildProxyMesh] mergeCoplanar and smoothIterations are mutually exclusive - '\n + 'merging destroys the uniform grid the Laplacian needs. Pick a finish: '\n + 'merge for a raw blocky surface, smooth for the relight proxy.',\n );\n }\n if (!(s.voxelSize > 0)) {\n throw new RangeError(`[buildProxyMesh] voxelSize must be > 0, got ${s.voxelSize}`);\n }\n\n const skinned = !!input.boneIndices && !!input.boneWeights;\n const grid = voxelize(input, s, skinned, t0, '[buildProxyMesh]');\n return extract(grid, s, skinned, t0);\n}\n\n/**\n * Turn a {@link VoxelGrid} into a surface, with no splats and no voxelization.\n *\n * The other half of {@link buildProxyMesh}, callable on its own so a consumer\n * that already holds a grid can ask for the surface WITHOUT re-reading the\n * splats. The collider is that consumer: it keeps the grid (that is what its\n * queries read) and extracts a surface only when something wants to look at one\n * or write one out - and because both of those come from this one call over the\n * one grid, the picture and the exported file cannot be different geometry.\n *\n * Pure. The grid is not written to. Unskinned by construction: a grid carries no\n * bone accumulation, so {@link ProxyMeshResult.boneIndices} comes back null.\n *\n * @param settings - only the finish matters here; `voxelSize`, `dilate`,\n * `floorFill` and the rest already happened and are ignored.\n * @throws RangeError when `mergeCoplanar` is combined with `smoothIterations > 0`.\n */\nexport function extractSurface(grid: VoxelGrid, settings: SurfaceSettings = {}): ProxyMeshResult {\n const t0 = now();\n const s = { ...defaultProxySettings, ...stripUndefined(settings) };\n if (s.surface === 'blocky' && s.mergeCoplanar && s.smoothIterations > 0) {\n throw new RangeError(\n '[extractSurface] mergeCoplanar and smoothIterations are mutually exclusive - '\n + 'merging destroys the uniform grid the Laplacian needs. Pick a finish: '\n + 'merge for a raw blocky surface, smooth for the relight proxy.',\n );\n }\n return extract({ ...grid, boneSlot: null, slotIndices: null, slotWeights: null }, s, false, t0);\n}\n\n/** The extraction itself. `skinned` decides whether vertices carry weights. */\nfunction extract(\n grid: VoxelizeResult,\n s: Required<ProxySettings>,\n skinned: boolean,\n t0: number,\n): ProxyMeshResult {\n const { occupancy: occ, splatsUsed, occupiedVoxels } = grid;\n const nx = grid.dims.x, ny = grid.dims.y, nz = grid.dims.z;\n const mnx = grid.origin.x, mny = grid.origin.y, mnz = grid.origin.z;\n const voxel = grid.voxelSize;\n const idx = (x: number, y: number, z: number) => (z * ny + y) * nx + x;\n const { boneSlot, slotIndices, slotWeights } = grid;\n\n if (occupiedVoxels === 0) {\n const empty = emptyResult(voxel, t0);\n empty.dims = { x: nx, y: ny, z: nz };\n empty.origin = { x: mnx, y: mny, z: mnz };\n empty.splatsUsed = splatsUsed;\n return empty;\n }\n\n // \u2500\u2500 Surface extraction.\n const verts: number[] = [];\n const quads: number[] = [];\n const vertBoneIndices: number[] | null = skinned ? [] : null;\n const vertBoneWeights: number[] | null = skinned ? [] : null;\n\n /** Copy a voxel's four influences onto the vertex just pushed. */\n const pushWeights = (sourceVoxel: number) => {\n if (!vertBoneIndices || !vertBoneWeights) return;\n const slot = boneSlot ? boneSlot[sourceVoxel] : -1;\n if (slot < 0 || !slotIndices || !slotWeights) {\n // All-zero: bound to bone 0 with weight 0, which the skinning shader\n // reads as \"no influence\" rather than as \"pinned to the root\".\n for (let j = 0; j < INFLUENCES; j++) { vertBoneIndices.push(0); vertBoneWeights.push(0); }\n return;\n }\n const base = slot * INFLUENCES;\n for (let j = 0; j < INFLUENCES; j++) {\n vertBoneIndices.push(slotIndices[base + j]);\n vertBoneWeights.push(slotWeights[base + j]);\n }\n };\n\n const solid = (x: number, y: number, z: number) =>\n x >= 0 && y >= 0 && z >= 0 && x < nx && y < ny && z < nz && occ[idx(x, y, z)] !== 0;\n\n // WELDED vertices, keyed by grid corner. Sharing is what makes the Laplacian\n // possible at all - an unwelded surface has no neighbours to average - and\n // it roughly halves the vertex count as a side effect. An Int32Array rather\n // than a Map: the corner lattice is exactly `(nx+1)(ny+1)(nz+1)` wide, and\n // the dense array is several times faster to probe than a hash on a grid\n // this size. Allocated only for the styles that weld - Surface Nets does\n // not, and the lattice is the largest allocation in the whole build.\n let cornerIndex: Int32Array | null = null;\n const cornerVert = (cx: number, cy: number, cz: number, sourceVoxel: number) => {\n const lattice = cornerIndex\n ?? (cornerIndex = new Int32Array((nx + 1) * (ny + 1) * (nz + 1)).fill(-1));\n const key = (cz * (ny + 1) + cy) * (nx + 1) + cx;\n const found = lattice[key];\n if (found >= 0) return found;\n const v = verts.length / 3;\n lattice[key] = v;\n verts.push(mnx + cx * voxel, mny + cy * voxel, mnz + cz * voxel);\n pushWeights(sourceVoxel);\n return v;\n };\n\n // Surface Nets builds its own vertices - they sit anywhere inside a cell,\n // not on grid corners, so the welding above does not apply to them.\n const freeVert = (x: number, y: number, z: number, sourceVoxel: number) => {\n const v = verts.length / 3;\n verts.push(x, y, z);\n pushWeights(sourceVoxel);\n return v;\n };\n\n const quad = (a: number, b: number, c: number, d: number) => quads.push(a, b, c, d);\n\n if (s.surface === 'smooth') {\n emitSurfaceNets(nx, ny, nz, mnx, mny, mnz, voxel, solid, idx, freeVert, quad);\n } else if (s.mergeCoplanar) {\n emitMerged(nx, ny, nz, solid, idx, cornerVert, quad);\n } else {\n emitPerVoxel(nx, ny, nz, solid, idx, cornerVert, quad);\n }\n\n if (quads.length === 0) {\n const empty = emptyResult(voxel, t0);\n empty.dims = { x: nx, y: ny, z: nz };\n empty.origin = { x: mnx, y: mny, z: mnz };\n empty.splatsUsed = splatsUsed;\n empty.occupiedVoxels = occupiedVoxels;\n return empty;\n }\n\n const vertexCount = verts.length / 3;\n const outPositions = new Float32Array(verts);\n const outQuads = new Uint32Array(quads);\n const outIndices = triangulate(outQuads);\n\n // \u2500\u2500 Laplacian relaxation: melt the cube staircase into a rounded surface.\n // Plain (shrinking) Laplacian on purpose - the volume was dilated outward\n // first, so the mild shrink pulls the surface back toward the splats\n // while it rounds off.\n if (s.smoothIterations > 0) {\n relax(outPositions, vertexCount, outQuads, s.smoothIterations);\n }\n\n const outNormals = computeNormals(outPositions, outIndices, vertexCount);\n\n return {\n positions: outPositions,\n normals: outNormals,\n indices: outIndices,\n quads: outQuads,\n boneIndices: vertBoneIndices ? new Float32Array(vertBoneIndices) : null,\n boneWeights: vertBoneWeights ? new Float32Array(vertBoneWeights) : null,\n voxelSize: voxel,\n dims: { x: nx, y: ny, z: nz },\n origin: { x: mnx, y: mny, z: mnz },\n occupiedVoxels,\n splatsUsed,\n vertexCount,\n triangleCount: outIndices.length / 3,\n buildMs: now() - t0,\n };\n}\n\n// \u2500\u2500 Occupancy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** {@link VoxelGrid} plus the per-cell bone accumulation only the mesh needs. */\ninterface VoxelizeResult extends VoxelGrid {\n /** Cell -> dense accumulator id, or `-1`. `null` on an unskinned run. */\n boneSlot: Int32Array | null;\n /** `[b0..b3] * slotCount`, the four heaviest bones per accumulator. */\n slotIndices: Float32Array | null;\n /** `[w0..w3] * slotCount`, normalized. */\n slotWeights: Float32Array | null;\n}\n\n/**\n * The occupancy stage, shared by {@link buildVoxelGrid} and\n * {@link buildProxyMesh}. `label` is the caller's name, so a thrown range\n * error names the function the caller actually called.\n */\nfunction voxelize(\n input: ProxyMeshInput,\n s: Required<ProxySettings>,\n skinned: boolean,\n t0: number,\n label: string,\n): VoxelizeResult {\n const positions = input.positions;\n const n = Math.floor(positions.length / 3);\n if (n === 0) return emptyGrid(s.voxelSize, t0);\n\n const opacities = input.opacities;\n const hasOpacity = !!opacities && opacities.length === n;\n const threshold = s.opacityThreshold;\n\n const srcBoneIndices = skinned ? input.boneIndices! : null;\n const srcBoneWeights = skinned ? input.boneWeights! : null;\n if (srcBoneIndices && srcBoneWeights) {\n const want = n * INFLUENCES;\n if (srcBoneIndices.length < want || srcBoneWeights.length < want) {\n throw new RangeError(\n `${label} bone arrays must carry ${INFLUENCES} influences per splat: `\n + `expected ${want} entries for ${n} splats, got ${srcBoneIndices.length} indices `\n + `and ${srcBoneWeights.length} weights`,\n );\n }\n }\n\n // \u2500\u2500 Bounds over the splats that count.\n let rawMnx = Infinity, rawMny = Infinity, rawMnz = Infinity;\n let rawMxx = -Infinity, rawMxy = -Infinity, rawMxz = -Infinity;\n let splatsUsed = 0;\n for (let i = 0; i < n; i++) {\n if (hasOpacity && opacities![i] < threshold) continue;\n const x = positions[i * 3], y = positions[i * 3 + 1], z = positions[i * 3 + 2];\n if (x < rawMnx) rawMnx = x; if (x > rawMxx) rawMxx = x;\n if (y < rawMny) rawMny = y; if (y > rawMxy) rawMxy = y;\n if (z < rawMnz) rawMnz = z; if (z > rawMxz) rawMxz = z;\n splatsUsed++;\n }\n if (splatsUsed === 0) return emptyGrid(s.voxelSize, t0);\n\n // \u2500\u2500 Pad so neither the dilation nor the surface extraction clips at the\n // border: the dilation loop below deliberately skips the outermost shell\n // of cells, so without a pad a splat sitting exactly on the bounding box\n // would not grow.\n //\n // TWO cells beyond the dilation, not one. Surface Nets reads the 2x2x2\n // block of lattice points around every dual cell and emits a quad only\n // where all four cells around a sign-changing edge produced a vertex, so\n // it needs a clear cell FURTHER out than the per-voxel extractor does. At\n // `dilate + 1` the two disagree: a ball at voxel 0.08 comes out of\n // `blocky` closed and out of `smooth` with twelve boundary edges - holes,\n // which is a light leak, and the one invariant this module actually\n // promises. It went unseen while the defaults were `blocky` + `dilate: 1`,\n // where the dilation's own pad happened to cover it. `dilate + 2` closes\n // `smooth` at every dilation, and makes the two finishes agree on\n // triangle count again, which is what they are meant to do.\n //\n // The pad is a number of VOXELS, so it has to move when the coarsen loop\n // moves the voxel size. Computing it once from the REQUESTED size - what\n // this did, and what the Unity original it came from does - leaves a grid\n // coarsened even one step with a pad thinner than the shell the dilation\n // skips, so a wall on the capture's edge comes out one cell thin or gone.\n // Invisible on a character, which coarsens never; a scanned scene at a\n // metric voxel size coarsens every time. The raw bounds are kept and the\n // pad is re-derived on every sizing.\n let mnx = 0, mny = 0, mnz = 0, mxx = 0, mxy = 0, mxz = 0;\n const requestedVoxelSize = s.voxelSize;\n let voxel = s.voxelSize;\n let nx = 0, ny = 0, nz = 0;\n const sizeGrid = () => {\n const pad = (s.dilate + EXTRACTION_MARGIN) * voxel;\n mnx = rawMnx - pad; mny = rawMny - pad; mnz = rawMnz - pad;\n mxx = rawMxx + pad; mxy = rawMxy + pad; mxz = rawMxz + pad;\n nx = Math.ceil((mxx - mnx) / voxel) + 1;\n ny = Math.ceil((mxy - mny) / voxel) + 1;\n nz = Math.ceil((mxz - mnz) / voxel) + 1;\n };\n sizeGrid();\n // Coarsen rather than allocate a pathological grid: a coarser surface is\n // still a usable surface and an out-of-memory is not.\n //\n // MONOTONICITY IS THE TERMINATION PROOF. A padded axis can never fall below\n // `2 * (dilate + EXTRACTION_MARGIN) + 1` cells however coarse the voxel gets,\n // so an absolute\n // floor like \"stop at 2x2x2\" is unreachable and would spin forever on an\n // absurdly low `maxVoxels`. Each step multiplies the voxel by 1.5, which\n // strictly shrinks the grid until it reaches that pad floor, and the loop\n // stops the moment a step fails to shrink it.\n let cells = nx * ny * nz;\n while (cells > s.maxVoxels) {\n voxel *= 1.5;\n sizeGrid();\n const next = nx * ny * nz;\n if (next >= cells) break;\n cells = next;\n }\n\n const nvox = nx * ny * nz;\n const idx = (x: number, y: number, z: number) => (z * ny + y) * nx + x;\n let occ = new Uint8Array(nvox);\n\n // \u2500\u2500 Occupancy, and per-voxel bone accumulation alongside it.\n //\n // `boneSlot` maps a voxel to a dense accumulator id. Only voxels a splat\n // actually landed in get one; dilation hands its id down to the cells it\n // grows, and the floor fill deliberately gets none (it is for static\n // captures, which are never skinned).\n const boneSlot = srcBoneIndices ? new Int32Array(nvox).fill(-1) : null;\n const boneAcc = srcBoneIndices ? new Map<number, number>() : null;\n let slotCount = 0;\n\n const invVoxel = 1 / voxel;\n for (let i = 0; i < n; i++) {\n if (hasOpacity && opacities![i] < threshold) continue;\n let cx = Math.floor((positions[i * 3] - mnx) * invVoxel);\n let cy = Math.floor((positions[i * 3 + 1] - mny) * invVoxel);\n let cz = Math.floor((positions[i * 3 + 2] - mnz) * invVoxel);\n if (cx < 0) cx = 0; else if (cx >= nx) cx = nx - 1;\n if (cy < 0) cy = 0; else if (cy >= ny) cy = ny - 1;\n if (cz < 0) cz = 0; else if (cz >= nz) cz = nz - 1;\n const vi = idx(cx, cy, cz);\n occ[vi] = 1;\n\n if (!boneSlot || !boneAcc) continue;\n let slot = boneSlot[vi];\n if (slot < 0) { slot = slotCount++; boneSlot[vi] = slot; }\n const base = i * INFLUENCES;\n for (let j = 0; j < INFLUENCES; j++) {\n const w = srcBoneWeights![base + j];\n if (!(w > 0)) continue;\n const bone = srcBoneIndices![base + j];\n if (bone < 0 || bone >= BONE_KEY_STRIDE) {\n throw new RangeError(\n `${label} bone index ${bone} is out of the packable range `\n + `[0, ${BONE_KEY_STRIDE})`,\n );\n }\n const key = slot * BONE_KEY_STRIDE + bone;\n boneAcc.set(key, (boneAcc.get(key) ?? 0) + w);\n }\n }\n\n // \u2500\u2500 6-neighbour dilation. Grown voxels inherit the accumulator of the voxel\n // that grew them, so dilated skin still follows the right limb.\n for (let pass = 0; pass < s.dilate; pass++) {\n const grown = occ.slice();\n for (let z = 1; z < nz - 1; z++) {\n for (let y = 1; y < ny - 1; y++) {\n for (let x = 1; x < nx - 1; x++) {\n const vi = idx(x, y, z);\n if (occ[vi]) continue;\n let src = -1;\n if (occ[idx(x - 1, y, z)]) src = idx(x - 1, y, z);\n else if (occ[idx(x + 1, y, z)]) src = idx(x + 1, y, z);\n else if (occ[idx(x, y - 1, z)]) src = idx(x, y - 1, z);\n else if (occ[idx(x, y + 1, z)]) src = idx(x, y + 1, z);\n else if (occ[idx(x, y, z - 1)]) src = idx(x, y, z - 1);\n else if (occ[idx(x, y, z + 1)]) src = idx(x, y, z + 1);\n if (src < 0) continue;\n grown[vi] = 1;\n if (boneSlot && boneSlot[vi] < 0) boneSlot[vi] = boneSlot[src];\n }\n }\n }\n occ = grown;\n }\n\n // \u2500\u2500 Solid ground under the shell.\n //\n // Down to the margin, not to row zero. The pad below the lowest splat is\n // `dilate + EXTRACTION_MARGIN` cells, and filling through it would put\n // occupied cells against the grid floor, where Surface Nets cannot close\n // them - a `smooth` proxy with `floorFill` on came out with an open\n // underside, which is the exact hole the setting exists to shut. The fill\n // still reaches below every splat in the column, so the ground is solid.\n if (s.floorFill) {\n for (let z = 0; z < nz; z++) {\n for (let x = 0; x < nx; x++) {\n let lowest = -1;\n for (let y = 0; y < ny; y++) {\n if (occ[idx(x, y, z)]) { lowest = y; break; }\n }\n for (let y = EXTRACTION_MARGIN; y < lowest; y++) occ[idx(x, y, z)] = 1;\n }\n }\n }\n\n let occupiedVoxels = 0;\n for (let i = 0; i < nvox; i++) if (occ[i]) occupiedVoxels++;\n\n // \u2500\u2500 Collapse each accumulator down to the four heaviest bones, normalized.\n // The pass over the completed map is what makes this the EXACT top four\n // rather than a running approximation: every total is final by the time\n // it is offered to the selection.\n let slotIndices: Float32Array | null = null;\n let slotWeights: Float32Array | null = null;\n if (boneAcc && occupiedVoxels > 0) {\n slotIndices = new Float32Array(slotCount * INFLUENCES);\n slotWeights = new Float32Array(slotCount * INFLUENCES);\n for (const [key, total] of boneAcc) {\n const slot = Math.floor(key / BONE_KEY_STRIDE);\n const bone = key - slot * BONE_KEY_STRIDE;\n const base = slot * INFLUENCES;\n // Replace the lightest of the four if this one outweighs it. An empty\n // slot reads as weight 0, so the first four always land.\n let worst = 0;\n for (let j = 1; j < INFLUENCES; j++) {\n if (slotWeights[base + j] < slotWeights[base + worst]) worst = j;\n }\n if (total > slotWeights[base + worst]) {\n slotWeights[base + worst] = total;\n slotIndices[base + worst] = bone;\n }\n }\n for (let slot = 0; slot < slotCount; slot++) {\n const base = slot * INFLUENCES;\n let sum = 0;\n for (let j = 0; j < INFLUENCES; j++) sum += slotWeights[base + j];\n if (sum <= 0) continue;\n for (let j = 0; j < INFLUENCES; j++) slotWeights[base + j] /= sum;\n }\n }\n\n return {\n occupancy: occ,\n dims: { x: nx, y: ny, z: nz },\n origin: { x: mnx, y: mny, z: mnz },\n voxelSize: voxel,\n requestedVoxelSize,\n coarsened: voxel > requestedVoxelSize * 1.001,\n occupiedVoxels,\n splatsUsed,\n buildMs: now() - t0,\n boneSlot,\n slotIndices,\n slotWeights,\n };\n}\n\nfunction emptyGrid(voxelSize: number, t0: number): VoxelizeResult {\n return {\n occupancy: new Uint8Array(0),\n dims: { x: 0, y: 0, z: 0 },\n origin: { x: 0, y: 0, z: 0 },\n voxelSize,\n requestedVoxelSize: voxelSize,\n coarsened: false,\n occupiedVoxels: 0,\n splatsUsed: 0,\n buildMs: now() - t0,\n boneSlot: null,\n slotIndices: null,\n slotWeights: null,\n };\n}\n\n// \u2500\u2500 Surface extraction \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ntype SolidFn = (x: number, y: number, z: number) => boolean;\ntype IdxFn = (x: number, y: number, z: number) => number;\ntype CornerVertFn = (cx: number, cy: number, cz: number, sourceVoxel: number) => number;\ntype QuadFn = (a: number, b: number, c: number, d: number) => void;\n\n/**\n * One quad per voxel face that borders empty space.\n *\n * The corner orders are not free to permute: each one is wound so that\n * `(v1-v0) x (v2-v0)` points OUT of the volume under the right-hand rule,\n * which is what WebGL's default counter-clockwise front face wants and what\n * makes {@link computeNormals} come out pointing outward without a fixup pass.\n * (They are the Unity original's orders unchanged - Unity reads the same\n * ordering as outward under its own left-handed rule.)\n */\nfunction emitPerVoxel(\n nx: number, ny: number, nz: number,\n solid: SolidFn, idx: IdxFn, vert: CornerVertFn, quad: QuadFn,\n): void {\n for (let z = 0; z < nz; z++) {\n for (let y = 0; y < ny; y++) {\n for (let x = 0; x < nx; x++) {\n if (!solid(x, y, z)) continue;\n const s = idx(x, y, z);\n if (!solid(x - 1, y, z)) {\n quad(vert(x, y, z, s), vert(x, y, z + 1, s), vert(x, y + 1, z + 1, s), vert(x, y + 1, z, s));\n }\n if (!solid(x + 1, y, z)) {\n quad(vert(x + 1, y, z, s), vert(x + 1, y + 1, z, s), vert(x + 1, y + 1, z + 1, s), vert(x + 1, y, z + 1, s));\n }\n if (!solid(x, y - 1, z)) {\n quad(vert(x, y, z, s), vert(x + 1, y, z, s), vert(x + 1, y, z + 1, s), vert(x, y, z + 1, s));\n }\n if (!solid(x, y + 1, z)) {\n quad(vert(x, y + 1, z, s), vert(x, y + 1, z + 1, s), vert(x + 1, y + 1, z + 1, s), vert(x + 1, y + 1, z, s));\n }\n if (!solid(x, y, z - 1)) {\n quad(vert(x, y, z, s), vert(x, y + 1, z, s), vert(x + 1, y + 1, z, s), vert(x + 1, y, z, s));\n }\n if (!solid(x, y, z + 1)) {\n quad(vert(x, y, z + 1, s), vert(x + 1, y, z + 1, s), vert(x + 1, y + 1, z + 1, s), vert(x, y + 1, z + 1, s));\n }\n }\n }\n }\n}\n\n/**\n * Greedy meshing. For each of the six face directions, sweep the slices\n * perpendicular to it; in each slice build the 2D mask of faces that border\n * empty space, then repeatedly take the largest axis-aligned rectangle of\n * still-unclaimed mask cells anchored at the first free cell.\n *\n * The emitted surface is geometrically identical to {@link emitPerVoxel}'s -\n * the same planes, the same coverage - with one quad where there were many.\n * Which is also why it cannot be smoothed afterwards: the long thin quads have\n * no interior vertices for the Laplacian to move.\n */\nfunction emitMerged(\n nx: number, ny: number, nz: number,\n solid: SolidFn, idx: IdxFn, vert: CornerVertFn, quad: QuadFn,\n): void {\n // axis: 0 = x, 1 = y, 2 = z. For each axis the slice runs over that axis and\n // the mask spans the other two, in (u, v) order as named per axis below.\n for (let axis = 0; axis < 3; axis++) {\n const uN = axis === 0 ? ny : nx; // x: u=y v=z | y: u=x v=z | z: u=x v=y\n const vN = axis === 2 ? ny : nz;\n const sN = axis === 0 ? nx : (axis === 1 ? ny : nz);\n const mask = new Uint8Array(uN * vN);\n\n for (let sign = -1; sign <= 1; sign += 2) {\n for (let sl = 0; sl < sN; sl++) {\n let any = false;\n for (let v = 0; v < vN; v++) {\n for (let u = 0; u < uN; u++) {\n let x: number, y: number, z: number;\n if (axis === 0) { x = sl; y = u; z = v; }\n else if (axis === 1) { x = u; y = sl; z = v; }\n else { x = u; y = v; z = sl; }\n const here = solid(x, y, z);\n const nbr = solid(\n x + (axis === 0 ? sign : 0),\n y + (axis === 1 ? sign : 0),\n z + (axis === 2 ? sign : 0),\n );\n const on = here && !nbr;\n mask[v * uN + u] = on ? 1 : 0;\n any = any || on;\n }\n }\n if (!any) continue;\n\n for (let v = 0; v < vN; v++) {\n for (let u = 0; u < uN; u++) {\n if (!mask[v * uN + u]) continue;\n let w = 1;\n while (u + w < uN && mask[v * uN + u + w]) w++;\n let h = 1;\n let grow = true;\n while (v + h < vN && grow) {\n for (let k = 0; k < w; k++) {\n if (!mask[(v + h) * uN + u + k]) { grow = false; break; }\n }\n if (grow) h++;\n }\n for (let b = 0; b < h; b++) {\n for (let a = 0; a < w; a++) mask[(v + b) * uN + u + a] = 0;\n }\n\n // Grid-corner extents of the claimed rectangle, and the plane it\n // sits on.\n const u0 = u, u1 = u + w, v0 = v, v1 = v + h;\n const plane = sign > 0 ? sl + 1 : sl;\n // Source voxel for bone weights: the rectangle's anchor cell.\n // Skinned runs never merge in practice (the proxy smooths\n // instead), so this only has to be defined, not representative.\n let sx: number, sy: number, sz: number;\n if (axis === 0) { sx = sl; sy = u0; sz = v0; }\n else if (axis === 1) { sx = u0; sy = sl; sz = v0; }\n else { sx = u0; sy = v0; sz = sl; }\n const src = idx(sx, sy, sz);\n\n // Winding matches emitPerVoxel's per-direction corner order exactly.\n if (axis === 0) {\n if (sign < 0) {\n quad(vert(plane, u0, v0, src), vert(plane, u0, v1, src),\n vert(plane, u1, v1, src), vert(plane, u1, v0, src));\n } else {\n quad(vert(plane, u0, v0, src), vert(plane, u1, v0, src),\n vert(plane, u1, v1, src), vert(plane, u0, v1, src));\n }\n } else if (axis === 1) {\n if (sign < 0) {\n quad(vert(u0, plane, v0, src), vert(u1, plane, v0, src),\n vert(u1, plane, v1, src), vert(u0, plane, v1, src));\n } else {\n quad(vert(u0, plane, v0, src), vert(u0, plane, v1, src),\n vert(u1, plane, v1, src), vert(u1, plane, v0, src));\n }\n } else {\n if (sign < 0) {\n quad(vert(u0, v0, plane, src), vert(u0, v1, plane, src),\n vert(u1, v1, plane, src), vert(u1, v0, plane, src));\n } else {\n quad(vert(u0, v0, plane, src), vert(u1, v0, plane, src),\n vert(u1, v1, plane, src), vert(u0, v1, plane, src));\n }\n }\n }\n }\n }\n }\n }\n}\n\n/** The eight corners of a dual cell, as `(dx, dy, dz)` bit triples. */\nconst CORNER = [\n [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0],\n [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1],\n] as const;\n\n/** The twelve edges joining corners that differ in exactly one axis. */\nconst EDGE = [\n [0, 1], [2, 3], [4, 5], [6, 7], // along x\n [0, 2], [1, 3], [4, 6], [5, 7], // along y\n [0, 4], [1, 5], [2, 6], [3, 7], // along z\n] as const;\n\n/**\n * Surface Nets, the \"naive\" dual-contouring variant. Occupancy is sampled at\n * CELL CENTRES; every dual cell whose eight surrounding centres are not all-in\n * or all-out straddles the boundary and gets exactly one vertex, placed at the\n * centroid of the cell edges the surface crosses. Faces then join the four\n * dual cells around each sign-changing lattice edge.\n *\n * WHY THIS AND NOT MARCHING CUBES. With binary occupancy every marching-cubes\n * crossing lands at an edge midpoint, so it reproduces the staircase and needs\n * heavy smoothing to hide it - and the smoothing is what then pulls the\n * surface off the geometry. Surface Nets puts one free vertex per boundary\n * cell instead: a wall at 30 degrees comes out at 30 degrees with no smoothing\n * at all. It also produces roughly one vertex per boundary cell rather than\n * four-plus, so it is the cheaper mesh as well as the truer one.\n *\n * The vertex is confined to its own cell, so the reconstruction can never\n * wander further than one voxel from the blocky surface it came from - the\n * error stays bounded by the voxel size, which is the number being tuned.\n */\nfunction emitSurfaceNets(\n nx: number, ny: number, nz: number,\n mnx: number, mny: number, mnz: number, voxel: number,\n solid: SolidFn, idx: IdxFn,\n addVert: (x: number, y: number, z: number, sourceVoxel: number) => number,\n quad: QuadFn,\n): void {\n // Dual grid: one cell per (nx-1) x (ny-1) x (nz-1) block of lattice points.\n const dx = nx - 1, dy = ny - 1, dz = nz - 1;\n if (dx <= 0 || dy <= 0 || dz <= 0) return;\n\n const cellVert = new Int32Array(dx * dy * dz).fill(-1);\n const dIdx = (x: number, y: number, z: number) => (z * dy + y) * dx + x;\n\n const occ8 = [false, false, false, false, false, false, false, false];\n for (let z = 0; z < dz; z++) {\n for (let y = 0; y < dy; y++) {\n for (let x = 0; x < dx; x++) {\n let inside = 0;\n for (let c = 0; c < 8; c++) {\n const o = solid(x + CORNER[c][0], y + CORNER[c][1], z + CORNER[c][2]);\n occ8[c] = o;\n if (o) inside++;\n }\n // Wholly outside or wholly inside: no surface through this cell.\n if (inside === 0 || inside === 8) continue;\n\n // Centroid of the crossing edges' midpoints, in the cell's own [0,1]\n // coordinates.\n let ax = 0, ay = 0, az = 0, crossings = 0;\n for (let e = 0; e < 12; e++) {\n const a = EDGE[e][0], b = EDGE[e][1];\n if (occ8[a] === occ8[b]) continue;\n ax += (CORNER[a][0] + CORNER[b][0]) * 0.5;\n ay += (CORNER[a][1] + CORNER[b][1]) * 0.5;\n az += (CORNER[a][2] + CORNER[b][2]) * 0.5;\n crossings++;\n }\n if (crossings === 0) continue;\n ax /= crossings; ay /= crossings; az /= crossings;\n\n // Lattice points are cell CENTRES, hence the half-voxel offset.\n const wx = mnx + (x + 0.5 + ax) * voxel;\n const wy = mny + (y + 0.5 + ay) * voxel;\n const wz = mnz + (z + 0.5 + az) * voxel;\n\n // Bone weights come from a corner that is actually solid; an empty one\n // carries none.\n let src = idx(x, y, z);\n for (let c = 0; c < 8; c++) {\n if (occ8[c]) { src = idx(x + CORNER[c][0], y + CORNER[c][1], z + CORNER[c][2]); break; }\n }\n cellVert[dIdx(x, y, z)] = addVert(wx, wy, wz, src);\n }\n }\n }\n\n // One quad per sign-changing lattice edge, joining the four dual cells\n // around it. Each of those four straddles the boundary by construction, so\n // its vertex exists. The corner ORDER matches emitPerVoxel's winding for the\n // same face direction.\n for (let z = 1; z < nz - 1; z++) {\n for (let y = 1; y < ny - 1; y++) {\n for (let x = 0; x < nx - 1; x++) {\n const a = solid(x, y, z), b = solid(x + 1, y, z);\n if (a === b) continue;\n const v00 = cellVert[dIdx(x, y - 1, z - 1)], v10 = cellVert[dIdx(x, y, z - 1)];\n const v11 = cellVert[dIdx(x, y, z)], v01 = cellVert[dIdx(x, y - 1, z)];\n if (v00 < 0 || v10 < 0 || v11 < 0 || v01 < 0) continue;\n if (a) quad(v00, v10, v11, v01); // solid at x: face points +x\n else quad(v00, v01, v11, v10);\n }\n }\n }\n for (let z = 1; z < nz - 1; z++) {\n for (let y = 0; y < ny - 1; y++) {\n for (let x = 1; x < nx - 1; x++) {\n const a = solid(x, y, z), b = solid(x, y + 1, z);\n if (a === b) continue;\n const v00 = cellVert[dIdx(x - 1, y, z - 1)], v01 = cellVert[dIdx(x - 1, y, z)];\n const v11 = cellVert[dIdx(x, y, z)], v10 = cellVert[dIdx(x, y, z - 1)];\n if (v00 < 0 || v01 < 0 || v11 < 0 || v10 < 0) continue;\n if (a) quad(v00, v01, v11, v10); // solid at y: face points +y\n else quad(v00, v10, v11, v01);\n }\n }\n }\n for (let z = 0; z < nz - 1; z++) {\n for (let y = 1; y < ny - 1; y++) {\n for (let x = 1; x < nx - 1; x++) {\n const a = solid(x, y, z), b = solid(x, y, z + 1);\n if (a === b) continue;\n const v00 = cellVert[dIdx(x - 1, y - 1, z)], v10 = cellVert[dIdx(x, y - 1, z)];\n const v11 = cellVert[dIdx(x, y, z)], v01 = cellVert[dIdx(x - 1, y, z)];\n if (v00 < 0 || v10 < 0 || v11 < 0 || v01 < 0) continue;\n if (a) quad(v00, v10, v11, v01); // solid at z: face points +z\n else quad(v00, v01, v11, v10);\n }\n }\n }\n}\n\n// \u2500\u2500 Post-processing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** `(0,1,2) (0,2,3)` per quad - the same split Unity's `Quad` helper used. */\nfunction triangulate(quads: Uint32Array): Uint32Array {\n const faces = quads.length / 4;\n const out = new Uint32Array(faces * 6);\n for (let f = 0; f < faces; f++) {\n const a = quads[f * 4], b = quads[f * 4 + 1], c = quads[f * 4 + 2], d = quads[f * 4 + 3];\n out[f * 6] = a; out[f * 6 + 1] = b; out[f * 6 + 2] = c;\n out[f * 6 + 3] = a; out[f * 6 + 4] = c; out[f * 6 + 5] = d;\n }\n return out;\n}\n\n/**\n * `smoothIterations` passes of `v <- lerp(v, mean(neighbours), 0.5)`.\n *\n * Adjacency comes off the QUAD edges rather than the triangle edges: the\n * triangulation diagonals are an artefact of the index buffer, and feeding\n * them in would weight one corner of every quad twice and shear the surface\n * along the diagonal. The Unity original averaged the triangle list, which\n * carries that bias; it is invisible at three passes on a blocky surface and\n * this is the cheaper thing to get right than to replicate.\n *\n * Built as CSR rather than a set per vertex - a `Set<number>` per vertex is\n * what made the original allocate one object per vertex on every rebuild.\n */\nfunction relax(positions: Float32Array, vertexCount: number, quads: Uint32Array, passes: number): void {\n const faces = quads.length / 4;\n\n // Pass 1: degree count, both directions of each of the four edges.\n const counts = new Uint32Array(vertexCount + 1);\n for (let f = 0; f < faces; f++) {\n for (let k = 0; k < 4; k++) {\n counts[quads[f * 4 + k]] += 2;\n }\n }\n const starts = new Uint32Array(vertexCount + 1);\n let total = 0;\n for (let i = 0; i < vertexCount; i++) { starts[i] = total; total += counts[i]; }\n starts[vertexCount] = total;\n\n // Pass 2: fill, then sort and unique each row so a vertex shared by many\n // faces is not counted once per face.\n const cursor = starts.slice();\n const adj = new Uint32Array(total);\n for (let f = 0; f < faces; f++) {\n const q = f * 4;\n for (let k = 0; k < 4; k++) {\n const a = quads[q + k];\n const b = quads[q + ((k + 1) & 3)];\n adj[cursor[a]++] = b;\n adj[cursor[b]++] = a;\n }\n }\n const rowEnd = new Uint32Array(vertexCount);\n for (let i = 0; i < vertexCount; i++) {\n const lo = starts[i], hi = starts[i + 1];\n if (hi <= lo) { rowEnd[i] = lo; continue; }\n const row = adj.subarray(lo, hi);\n row.sort();\n let w = lo + 1;\n for (let r = lo + 1; r < hi; r++) {\n if (adj[r] !== adj[w - 1]) adj[w++] = adj[r];\n }\n rowEnd[i] = w;\n }\n\n const next = new Float32Array(positions.length);\n for (let pass = 0; pass < passes; pass++) {\n for (let i = 0; i < vertexCount; i++) {\n const lo = starts[i], hi = rowEnd[i];\n const deg = hi - lo;\n if (deg === 0) {\n next[i * 3] = positions[i * 3];\n next[i * 3 + 1] = positions[i * 3 + 1];\n next[i * 3 + 2] = positions[i * 3 + 2];\n continue;\n }\n let ax = 0, ay = 0, az = 0;\n for (let r = lo; r < hi; r++) {\n const j = adj[r] * 3;\n ax += positions[j]; ay += positions[j + 1]; az += positions[j + 2];\n }\n ax /= deg; ay /= deg; az /= deg;\n next[i * 3] = (positions[i * 3] + ax) * 0.5;\n next[i * 3 + 1] = (positions[i * 3 + 1] + ay) * 0.5;\n next[i * 3 + 2] = (positions[i * 3 + 2] + az) * 0.5;\n }\n positions.set(next);\n }\n}\n\n/**\n * Area-weighted vertex normals: accumulate each triangle's UNnormalized cross\n * product onto its three corners, then normalize once. Area weighting falls\n * out of not normalizing the cross product, and is what keeps a smoothed\n * blocky surface from over-weighting the slivers the relaxation leaves behind.\n */\nfunction computeNormals(positions: Float32Array, indices: Uint32Array, vertexCount: number): Float32Array {\n const normals = new Float32Array(vertexCount * 3);\n for (let t = 0; t < indices.length; t += 3) {\n const a = indices[t] * 3, b = indices[t + 1] * 3, c = indices[t + 2] * 3;\n const e1x = positions[b] - positions[a];\n const e1y = positions[b + 1] - positions[a + 1];\n const e1z = positions[b + 2] - positions[a + 2];\n const e2x = positions[c] - positions[a];\n const e2y = positions[c + 1] - positions[a + 1];\n const e2z = positions[c + 2] - positions[a + 2];\n const nx = e1y * e2z - e1z * e2y;\n const ny = e1z * e2x - e1x * e2z;\n const nz = e1x * e2y - e1y * e2x;\n normals[a] += nx; normals[a + 1] += ny; normals[a + 2] += nz;\n normals[b] += nx; normals[b + 1] += ny; normals[b + 2] += nz;\n normals[c] += nx; normals[c + 1] += ny; normals[c + 2] += nz;\n }\n for (let v = 0; v < vertexCount; v++) {\n const i = v * 3;\n const len = Math.hypot(normals[i], normals[i + 1], normals[i + 2]);\n if (len > 1e-12) {\n normals[i] /= len; normals[i + 1] /= len; normals[i + 2] /= len;\n } else {\n // A vertex whose faces cancel out. Up is arbitrary but finite, which is\n // what the vertex buffer needs; NaN here would poison the whole draw.\n normals[i] = 0; normals[i + 1] = 1; normals[i + 2] = 0;\n }\n }\n return normals;\n}\n\n// \u2500\u2500 Plumbing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst now = (): number =>\n (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\n/**\n * Drop explicitly-`undefined` fields so a caller can spread a partial settings\n * object without its holes punching through the defaults.\n */\nfunction stripUndefined(s: ProxySettings): ProxySettings {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(s)) if (v !== undefined) out[k] = v;\n return out as ProxySettings;\n}\n\nfunction emptyResult(voxelSize: number, t0: number): ProxyMeshResult {\n return {\n positions: new Float32Array(0),\n normals: new Float32Array(0),\n indices: new Uint32Array(0),\n quads: new Uint32Array(0),\n boneIndices: null,\n boneWeights: null,\n voxelSize,\n dims: { x: 0, y: 0, z: 0 },\n origin: { x: 0, y: 0, z: 0 },\n occupiedVoxels: 0,\n splatsUsed: 0,\n vertexCount: 0,\n triangleCount: 0,\n buildMs: now() - t0,\n };\n}\n", "import {\n Color,\n Matrix4,\n Mesh,\n MeshBasicMaterial,\n OrthographicCamera,\n PerspectiveCamera,\n SkinnedMesh,\n Vector2,\n Vector3,\n Vector4,\n} from 'three';\nimport type {\n Camera,\n Material,\n RenderTarget,\n Scene as ThreeScene,\n Texture,\n WebGLRenderer,\n} from 'three';\n\nimport type { Environment } from '../environment';\nimport type { Scene } from '../scene';\nimport { SplatRelightBinding } from '../splat/relight-binding';\nimport { Splat } from '../splat/splat';\nimport type { RelightBackend, RelightComposeParams, RelightComposer } from './backend';\nimport { getRelightWebGPUBackend } from './backend';\nimport { getRelightPlaceholder } from './relight-placeholder';\nimport { createProxyShadowBias } from './shadow-bias';\nimport type { ProxyShadowBias } from './shadow-bias';\nimport { webglRelightBackend } from './webgl-backend';\n\n/** Per-consumer relight knobs. See {@link RelightPass.setConsumerParams}. */\nexport interface RelightParams {\n /**\n * How much of the splat's baked colour is replaced by proxy lighting.\n * `0` (default) skips the texture fetch entirely, so the effect costs\n * nothing until it is dialled up.\n */\n strength?: number;\n /** Tints the received light only, never the base colour. Default white. */\n tint?: { r: number; g: number; b: number };\n /** Floor under the light term so unlit faces do not go black. Default `0`. */\n ambient?: number;\n /**\n * Cast-shadow depth, sampled from the visibility channel. `0` (default) is\n * off; `1` takes a fully shadowed splat to black. Requires\n * {@link RelightPassOptions.visibility}.\n */\n shadowStrength?: number;\n /**\n * Paint every splat with the outcome of its own relight sample instead of\n * lighting it: magenta = no texture published, yellow = behind the camera,\n * red = projects off-screen, blue = the sampled texel has no proxy coverage,\n * orange = coverage found at the MIRRORED row (which convicts the y-flip\n * specifically), greys = the real sample.\n *\n * `2` paints the shadow-visibility sample instead: greys = the ratio,\n * magenta = no proxy coverage at that texel.\n */\n debug?: boolean | number;\n}\n\n/** Options for {@link RelightPass.create}. */\nexport interface RelightPassOptions {\n /**\n * Lighting-texture size as a fraction of the canvas. Default `0.5`.\n * Lighting is low-frequency and is sampled once per splat rather than per\n * pixel, so half resolution is normally indistinguishable and costs a\n * quarter of the bandwidth. Settable later via\n * {@link RelightPass.resolutionScale}.\n */\n resolutionScale?: number;\n /**\n * The proxy brightness that counts as \"normally lit\". Sampled lighting is\n * divided by this, so `strength` changes lighting CONTRAST rather than\n * overall brightness. Default `1`.\n */\n referenceLuminance?: number;\n /**\n * Run the 3x3 tent blur. Default `true`. This is what keeps the lighting\n * temporally stable while the proxy animates; turn it off only to see the\n * raw bake.\n *\n * Shorthand for the two radii below: `true` is 1 on each, `false` is 0.\n * Whichever of the three is given last wins.\n */\n blur?: boolean;\n /**\n * Radius of the tent over the LIGHTING, in texels of the proxy target.\n * Default `1`, the original tent; `0` is a single tap. See the compose\n * shader's header.\n */\n blurRadius?: number;\n /**\n * Radius of the tent over the SHADOW-VISIBILITY channel, in texels of the\n * proxy target. Default `1`. Inert unless `visibility` is on.\n */\n shadowBlurRadius?: number;\n /**\n * Allocate the second proxy draw that makes the shadow-visibility channel\n * work. Default `false`, because it costs a second proxy render per frame.\n * Without it `shadowStrength` is inert and the visibility channel reads a\n * constant 1.\n */\n visibility?: boolean;\n /**\n * Camera the lighting texture is rendered from. Default `scene.camera`. It\n * must be the camera the splats are viewed through - the lookup is\n * screen-space.\n */\n mainCamera?: Camera;\n /** See {@link EnvironmentRefreshMode}. Default `auto`. */\n environmentRefresh?: EnvironmentRefreshMode;\n /**\n * The owning relight's key-light bias, which the proxy material reads\n * under WebGL. Default: a zero bias of the pass's own. @internal\n */\n shadowBias?: ProxyShadowBias;\n}\n\n/**\n * When environment splats pick up a changed lighting texture.\n *\n * In the PlayCanvas build an environment keeps the colour its last work-buffer\n * copy computed, and this mode decides when it re-copies. This port has no\n * work buffer to keep: every splat - environments included - samples the live\n * lighting texture each frame it draws, so environments are always current\n * and all three modes light them the same way. The mode is kept so code\n * written against the PlayCanvas build carries over.\n *\n * - `auto` - the PlayCanvas default.\n * - `always` - every frame.\n * - `never` - only on {@link RelightPass.invalidateEnvironments}.\n */\nexport type EnvironmentRefreshMode = 'auto' | 'always' | 'never';\n\n/** Something whose relight knobs can be overridden. */\nexport type RelightConsumer = Splat | Environment;\n\n/**\n * The three.js layer the lit proxies render on. Proxies live on it ALONE, so\n * no app camera on the default layer 0 ever draws one. A light reaches the\n * proxies when it is enabled on this layer too - see {@link RelightPass.lightLayerIds}.\n */\nexport const RELIGHT_PROXY_LAYER = 29;\n\n/** The layer the unshadowed twins render on, for the shadow-visibility channel. */\nexport const RELIGHT_VISIBILITY_LAYER = 28;\n// 30 and 31 are the post-processing masks' (effects/postfx/mask.ts): a proxy\n// on one of them would draw into the outline or pixel-art mask.\n\n/**\n * Scene properties that would paint the proxy targets, cleared around a proxy\n * render: a background fills coverage = 1 everywhere, an override material\n * replaces the proxy material. Fog is NOT cleared - the proxy materials ignore\n * it, and toggling it on a WebGPU scene rebuilds every material in it. The\n * environment map is cleared only where the backend's proxy material reads it\n * ({@link RelightBackend.proxyReadsEnvironment}): under WebGL, where it would\n * add image-based light to the proxies; not under WebGPU, where they ignore it\n * and the toggle would rebuild every material.\n */\nconst SCENE_STATE_KEYS = ['background', 'backgroundNode', 'overrideMaterial', 'environment'] as const;\n\n/** The slice of `WebGLRenderer` / `WebGPURenderer` the pass drives; both have it. */\ntype RelightRenderer = Pick<WebGLRenderer,\n 'getRenderTarget' | 'setRenderTarget' | 'render' | 'getClearColor' | 'setClearColor'\n | 'getClearAlpha' | 'autoClear' | 'shadowMap' | 'getDrawingBufferSize' | 'coordinateSystem'\n>;\n\n/**\n * Screen-space relighting of gaussian splats from a proxy mesh.\n *\n * A proxy mesh of the same subject - a voxelized shell - is rendered with\n * three.js's real lights into an offscreen half-resolution texture. Every\n * splat then samples the texel it projects to and blends that lighting over\n * its own baked appearance.\n *\n * Screen-space and not per-splat N.L on purpose: every splat along a view ray\n * reads the SAME texel, so overlapping semi-transparent splats agree and the\n * per-frame depth re-sort cannot expose a contrast between them. The cost is\n * view dependence - you see the shading of the surfaces that face you.\n *\n * \u2500\u2500 The pipeline \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * 1. The app's three.js scene is rendered through a copy of the main camera\n * that sees only {@link RELIGHT_PROXY_LAYER}, into `_litRT`, with the\n * backend's proxy material (white lambertian, no ambient, PlayCanvas's\n * light model): rgb = sum over lights of `colour * N.L * attenuation *\n * shadow`, a = 1 (the coverage mask). Only lights enabled on that layer\n * take part, and the scene's background is held off for the duration.\n * 2. Optionally the same through {@link RELIGHT_VISIBILITY_LAYER}, where a\n * twin of every proxy with `receiveShadow = false` lives, into `_rawRT`:\n * the same sum with every shadow map ignored.\n * 3. The compose turns those into `lightingTexture` (rgb = lighting, a =\n * coverage) and `visibilityTexture` (r = visibility, g = coverage),\n * applying the tent blur, un-premultiplying by coverage, and adding the\n * scene ambient back in.\n * 4. The pair, plus the view-projection they were rendered with, is\n * published to every live splat in the scene through its\n * {@link SplatRelightBinding}.\n *\n * \u2500\u2500 No frame lag \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * The PlayCanvas build computes splat colour before its cameras render, so a\n * splat there samples the texture rendered the frame before. Here the whole\n * pass runs in the scene's `preRender`, before the main render that draws the\n * splats, so a splat samples THIS frame's lighting.\n *\n * \u2500\u2500 Why two draws and not MRT on the proxy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * Lighting comes from three's own light loop, which writes exactly one output.\n * The visibility ratio is instead recovered from a second draw of the same\n * geometry with `receiveShadow = false`, which is arithmetically identical -\n * see `relight-shaders.ts`.\n *\n * \u2500\u2500 Shadows \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * `renderer.shadowMap.enabled` is switched on for the proxy draws and put back\n * after, so the relight's shadows never change how the app's own meshes\n * compile. Shadow casters are gathered by the rendering camera's layers in\n * both renderers, so only proxies cast into the lighting - the app's meshes\n * on layer 0 do not shadow the splats.\n *\n * Built per scene, never as a module global.\n *\n * Internal. Consumers use {@link SplatRelight}.\n */\nexport class RelightPass {\n /** The layer lit proxies render on. See {@link RELIGHT_PROXY_LAYER}. */\n readonly proxyLayerId = RELIGHT_PROXY_LAYER;\n\n /**\n * Every layer a light must be enabled on for the proxies to be lit by it,\n * beside whichever layers it lights the app's meshes on.\n */\n readonly lightLayerIds: readonly number[];\n\n /** The material lighting-receiving proxies are drawn with. See {@link RelightBackend.createProxyMaterial}. */\n readonly proxyMaterial: Material;\n\n /**\n * The material of a proxy that casts into the shadow maps but is not drawn\n * into the lighting: it writes neither colour nor depth, so the lit render\n * passes through it while the depth-only shadow render still sees it.\n */\n readonly casterMaterial: Material;\n\n private readonly _scene: Scene;\n private readonly _renderer: RelightRenderer;\n private readonly _backend: RelightBackend;\n private readonly _mainCamera: Camera;\n private readonly _camera: PerspectiveCamera | OrthographicCamera;\n private readonly _composer: RelightComposer;\n\n private _litRT: RenderTarget | null = null;\n private _rawRT: RenderTarget | null = null;\n private _lightingRT: RenderTarget | null = null;\n private _visibilityRT: RenderTarget | null = null;\n private _rtWidth = 0;\n private _rtHeight = 0;\n\n /** Registered proxies -> their unshadowed twin, when visibility is on. */\n private readonly _proxies = new Map<Mesh, Mesh | null>();\n\n private _resolutionScale: number;\n private _referenceLuminance: number;\n private _blurRadius: number;\n private _shadowBlurRadius: number;\n private readonly _visibility: boolean;\n private _environmentRefresh: EnvironmentRefreshMode;\n private _flipY: boolean;\n private _enabled = true;\n private _destroyed = false;\n private _framesRendered = 0;\n private _environmentRefreshFrames = 0;\n\n /** Scene-wide defaults, overridden per {@link Splat} by `setConsumerParams`. */\n private readonly _defaults: Required<RelightParams> = {\n strength: 0,\n tint: { r: 1, g: 1, b: 1 },\n ambient: 0,\n shadowStrength: 0,\n debug: 0,\n };\n /** What every splat without an override reads. */\n private readonly _defaultBinding = new SplatRelightBinding();\n /**\n * Keyed by the consumer, not its splat: a LOD-bundle environment swaps the\n * splat that draws it as levels stream, and the override has to follow.\n */\n private readonly _overrides = new Map<RelightConsumer, { params: RelightParams; binding: SplatRelightBinding }>();\n /** This frame's splat -> override binding, rebuilt by `_publish`. */\n private readonly _overrideBySplat = new Map<Splat, SplatRelightBinding>();\n /** Splats this pass has attached a binding to, for detaching on destroy. */\n private readonly _bound = new Set<Splat>();\n\n private readonly _viewProjection = new Matrix4();\n private readonly _params = new Vector4();\n private readonly _composeParams: RelightComposeParams = {\n texelX: 0, texelY: 0, blurRadius: 0, shadowBlurRadius: 0, ambient: new Vector3(),\n };\n private readonly _clearColor = new Color();\n private readonly _size = new Vector2();\n\n /**\n * Build the pass for `scene`'s renderer.\n *\n * Throws when the renderer cannot render to half-float, which the lighting\n * texture requires - lighting legitimately exceeds 1 and clamping it would\n * flatten exactly the highlights relighting exists for - and when the scene\n * renders with WebGPU but the `/webgpu` entry point has not been imported.\n */\n static create(scene: Scene, opts: RelightPassOptions = {}): RelightPass {\n return new RelightPass(scene, opts);\n }\n\n private constructor(scene: Scene, opts: RelightPassOptions) {\n this._scene = scene;\n this._renderer = scene.renderer as unknown as RelightRenderer;\n this._backend = relightBackendFor(scene);\n\n const mainCamera = opts.mainCamera ?? scene.camera;\n // A camera of the same kind, synced field by field each frame - not a\n // clone, which would copy the main camera's children along with it.\n let proxyCamera: PerspectiveCamera | OrthographicCamera;\n if ((mainCamera as PerspectiveCamera).isPerspectiveCamera) proxyCamera = new PerspectiveCamera();\n else if ((mainCamera as OrthographicCamera).isOrthographicCamera) proxyCamera = new OrthographicCamera();\n else throw new Error('[RelightPass] mainCamera must be a PerspectiveCamera or an OrthographicCamera');\n proxyCamera.name = 'relight-proxy-camera';\n this._mainCamera = mainCamera;\n this._camera = proxyCamera;\n\n this._resolutionScale = clamp(opts.resolutionScale ?? 0.5, 0.05, 1);\n this._referenceLuminance = Math.max(opts.referenceLuminance ?? 1, 1e-4);\n // `blur` is the old boolean surface and still works; a radius given\n // explicitly overrides whatever it implied.\n const blurDefault = (opts.blur ?? true) ? 1 : 0;\n this._blurRadius = Math.max(0, opts.blurRadius ?? blurDefault);\n this._shadowBlurRadius = Math.max(0, opts.shadowBlurRadius ?? blurDefault);\n this._visibility = opts.visibility ?? false;\n this._environmentRefresh = opts.environmentRefresh ?? 'auto';\n this._flipY = this._backend.flipY;\n\n this.lightLayerIds = this._visibility\n ? [RELIGHT_PROXY_LAYER, RELIGHT_VISIBILITY_LAYER]\n : [RELIGHT_PROXY_LAYER];\n\n // There is deliberately no material override slot on this class: the\n // output contract (direct light only, alpha = coverage) is what the splat\n // shader assumes, and an arbitrary material here bakes the proxy's own\n // surface appearance into the texture - blotches on the character that\n // flicker during animation.\n this.proxyMaterial = this._backend.createProxyMaterial(opts.shadowBias ?? createProxyShadowBias());\n this.casterMaterial = new MeshBasicMaterial({ name: 'relight-shadow-caster', colorWrite: false, depthWrite: false });\n this._composer = this._backend.createComposer();\n\n this._ensureTargets();\n }\n\n // \u2500\u2500 Public surface \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * The composed lighting texture: `rgb` = full lighting, `a` = proxy\n * coverage. `null` before the first frame has rendered. Exposed for debug\n * overlays; the splats read it through their bindings.\n */\n get lightingTexture(): Texture | null { return this._framesRendered > 0 ? this._lightingRT?.texture ?? null : null; }\n\n /** `r` = shadow visibility, `g` = proxy coverage. See {@link lightingTexture}. */\n get visibilityTexture(): Texture | null { return this._framesRendered > 0 ? this._visibilityRT?.texture ?? null : null; }\n\n /** `[width, height]` of the lighting texture. */\n get resolution(): [number, number] { return [this._rtWidth, this._rtHeight]; }\n\n /** Lighting-texture size as a fraction of the canvas. Reallocates. */\n get resolutionScale(): number { return this._resolutionScale; }\n set resolutionScale(v: number) {\n const next = clamp(v, 0.05, 1);\n if (next === this._resolutionScale) return;\n this._resolutionScale = next;\n this._ensureTargets();\n }\n\n /** See {@link RelightPassOptions.referenceLuminance}. Uniform-only. */\n get referenceLuminance(): number { return this._referenceLuminance; }\n set referenceLuminance(v: number) { this._referenceLuminance = Math.max(v, 1e-4); }\n\n /**\n * Whether either tent runs at all. Reading it asks \"is anything blurred\";\n * writing it sets both radii to 1 or 0. Uniform-only.\n */\n get blur(): boolean { return this._blurRadius > 0 || this._shadowBlurRadius > 0; }\n set blur(v: boolean) {\n this.blurRadius = v ? 1 : 0;\n this.shadowBlurRadius = v ? 1 : 0;\n }\n\n /** Tent radius over the lighting, in proxy-target texels. Uniform-only. */\n get blurRadius(): number { return this._blurRadius; }\n set blurRadius(v: number) { this._blurRadius = Math.max(0, v); }\n\n /** Tent radius over the shadow-visibility channel. Uniform-only. */\n get shadowBlurRadius(): number { return this._shadowBlurRadius; }\n set shadowBlurRadius(v: number) { this._shadowBlurRadius = Math.max(0, v); }\n\n /** Whether the shadow-visibility channel is live (fixed at construction). */\n get visibilityEnabled(): boolean { return this._visibility; }\n\n /**\n * Mirror the sampled row of the lighting texture.\n *\n * The backend's measured answer by default: `false` under WebGLRenderer,\n * whose render-target rows run bottom-up exactly as `uv = ndc * 0.5 + 0.5`\n * reads them, and whatever the WebGPU backend measured for WebGPURenderer.\n * Kept settable because it is exactly the knob you want when a future\n * three.js changes that behaviour: set {@link RelightParams.debug}, look\n * for orange (coverage at the MIRRORED row), flip this and watch it turn\n * grey.\n */\n get flipY(): boolean { return this._flipY; }\n set flipY(v: boolean) { this._flipY = v; }\n\n /** See {@link EnvironmentRefreshMode}. */\n get environmentRefresh(): EnvironmentRefreshMode { return this._environmentRefresh; }\n set environmentRefresh(v: EnvironmentRefreshMode) { this._environmentRefresh = v; }\n\n /**\n * Mark every binding changed, so a backend that caches on\n * {@link SplatRelightBinding.version} recomputes. For what the pass cannot\n * see itself.\n */\n invalidateEnvironments(): void {\n this._defaultBinding.version++;\n for (const o of this._overrides.values()) o.binding.version++;\n }\n\n /** Frames on which a published binding changed, since creation. A cost probe. */\n get environmentRefreshFrames(): number { return this._environmentRefreshFrames; }\n\n /**\n * Stop rendering the proxy. Consumers fall back to their baked colour on the\n * same frame (the published `valid` flag goes to 0), so this is a true\n * no-op, not a frozen last frame.\n */\n get enabled(): boolean { return this._enabled; }\n set enabled(v: boolean) {\n if (this._enabled === v) return;\n this._enabled = v;\n if (!v) this._framesRendered = 0;\n }\n\n /** Scene-wide relight defaults, applied to every splat without an override. */\n setDefaults(params: RelightParams): void {\n Object.assign(this._defaults, stripUndefined(params));\n }\n\n /** Read back the scene-wide defaults. */\n getDefaults(): Required<RelightParams> {\n return { ...this._defaults, tint: { ...this._defaults.tint } };\n }\n\n /**\n * Override the relight knobs for one {@link Splat} or {@link Environment}.\n * Pass `null` to drop the override and fall back to {@link setDefaults}.\n */\n setConsumerParams(consumer: RelightConsumer, params: RelightParams | null): void {\n const prev = this._overrides.get(consumer);\n if (params === null) {\n // Its splats go back on the shared binding on the next publish.\n this._overrides.delete(consumer);\n return;\n }\n const next = stripUndefined(params);\n if (prev) Object.assign(prev.params, next);\n else this._overrides.set(consumer, { params: { ...next }, binding: new SplatRelightBinding() });\n }\n\n /**\n * Register a proxy mesh. It is moved onto {@link proxyLayerId} and given\n * {@link proxyMaterial}, or {@link casterMaterial} when it only casts.\n *\n * When {@link RelightPassOptions.visibility} is on, a receiver also gets\n * the unshadowed twin the visibility ratio is measured against: a child of\n * the proxy sharing its geometry and, for a skinned proxy, its skeleton and\n * bind matrices - so it needs no second skinning setup and cannot drift\n * from the proxy it twins. Idempotent.\n */\n addProxy(mesh: Mesh, lightingReceiver = true): void {\n if (this._destroyed || this._proxies.has(mesh)) return;\n mesh.layers.set(RELIGHT_PROXY_LAYER);\n if (!lightingReceiver) {\n mesh.material = this.casterMaterial;\n this._proxies.set(mesh, null);\n return;\n }\n mesh.material = this.proxyMaterial;\n let twin: Mesh | null = null;\n if (this._visibility) {\n if (mesh instanceof SkinnedMesh) {\n const skinned = new SkinnedMesh(mesh.geometry, this.proxyMaterial);\n skinned.skeleton = mesh.skeleton;\n skinned.bindMatrix = mesh.bindMatrix;\n skinned.bindMode = mesh.bindMode;\n twin = skinned;\n } else {\n twin = new Mesh(mesh.geometry, this.proxyMaterial);\n }\n twin.name = 'relight-proxy-noshadow';\n // The whole point of the twin: same lighting, shadow maps ignored.\n twin.receiveShadow = false;\n twin.castShadow = false;\n twin.frustumCulled = mesh.frustumCulled;\n twin.layers.set(RELIGHT_VISIBILITY_LAYER);\n mesh.add(twin);\n }\n this._proxies.set(mesh, twin);\n }\n\n /** Drop a proxy registered with {@link addProxy}. No-op if unknown. */\n removeProxy(mesh: Mesh): void {\n if (!this._proxies.has(mesh)) return;\n // Removed, never disposed: the geometry and skeleton belong to the\n // caller's proxy.\n this._proxies.get(mesh)?.removeFromParent();\n this._proxies.delete(mesh);\n }\n\n /**\n * Render the lighting for this frame and publish it. Called once a frame\n * from the owner's `preRender`, after the proxies are posed.\n */\n render(): void {\n if (this._destroyed) return;\n this._ensureTargets();\n this._syncCamera();\n if (this._enabled) {\n this._renderProxies();\n this._framesRendered++;\n }\n this._publish(this._enabled && this._framesRendered > 0);\n }\n\n /** Tear everything down. Safe to call twice. */\n destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n for (const mesh of Array.from(this._proxies.keys())) this.removeProxy(mesh);\n // Leave every consumer reading its baked colour rather than a freed\n // texture: detaching the binding recompiles the splat without the relight.\n for (const splat of this._bound) if (!splat.destroyed) splat.setRelightBinding(null);\n this._bound.clear();\n this._overrides.clear();\n this._releaseTargets();\n this._composer.dispose();\n this.proxyMaterial.dispose();\n this.casterMaterial.dispose();\n }\n\n // \u2500\u2500 Internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Idempotent, size-guarded allocator. No-op when the size already matches. */\n private _ensureTargets(): void {\n const size = this._renderer.getDrawingBufferSize(this._size);\n const w = Math.max(1, Math.round(size.x * this._resolutionScale));\n const h = Math.max(1, Math.round(size.y * this._resolutionScale));\n if (this._litRT && w === this._rtWidth && h === this._rtHeight) return;\n\n this._releaseTargets();\n this._rtWidth = w;\n this._rtHeight = h;\n const make = (name: string, depth: boolean) => {\n const rt = this._backend.createTarget(this._renderer, w, h, depth);\n rt.texture.name = name;\n return rt;\n };\n // Depth on the proxy targets: proxies are opaque geometry that has to\n // occlude itself - an arm in front of a torso must win.\n this._litRT = make('relight-proxy-lit', true);\n if (this._visibility) this._rawRT = make('relight-proxy-raw', true);\n this._lightingRT = make('relight-lighting', false);\n // Visibility and coverage are both 0..1 but half-float rather than 8-bit:\n // the compose divides one by the other, and 8-bit coverage quantizes that\n // ratio into visible banding across a soft shadow edge.\n this._visibilityRT = make('relight-visibility', false);\n\n // A freshly sized target holds nothing; consumers fall back to their\n // baked colour until the next compose fills it.\n this._framesRendered = 0;\n }\n\n private _releaseTargets(): void {\n this._litRT?.dispose();\n this._rawRT?.dispose();\n this._lightingRT?.dispose();\n this._visibilityRT?.dispose();\n this._litRT = this._rawRT = this._lightingRT = this._visibilityRT = null;\n }\n\n /**\n * Copy the main camera's view and projection onto the proxy camera, with\n * the aspect taken from the TARGET rather than the canvas: the rounding of\n * a scaled size can differ from the canvas ratio by a fraction of a\n * percent, and the splat lookup uses this same matrix.\n */\n private _syncCamera(): void {\n const main = this._mainCamera;\n const cam = this._camera;\n main.updateMatrixWorld();\n main.matrixWorld.decompose(cam.position, cam.quaternion, cam.scale);\n if (cam instanceof PerspectiveCamera) {\n const src = main as PerspectiveCamera;\n cam.fov = src.fov;\n cam.near = src.near;\n cam.far = src.far;\n cam.zoom = src.zoom;\n cam.focus = src.focus;\n cam.filmGauge = src.filmGauge;\n cam.filmOffset = src.filmOffset;\n cam.aspect = this._rtWidth / this._rtHeight;\n } else {\n const src = main as OrthographicCamera;\n cam.left = src.left;\n cam.right = src.right;\n cam.top = src.top;\n cam.bottom = src.bottom;\n cam.near = src.near;\n cam.far = src.far;\n cam.zoom = src.zoom;\n }\n // WebGPU's clip space has a different depth range; a camera built for the\n // other one would also be rebuilt by the renderer mid-frame.\n cam.coordinateSystem = this._renderer.coordinateSystem;\n cam.updateProjectionMatrix();\n cam.updateMatrixWorld(true);\n this._viewProjection.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse);\n }\n\n private _renderProxies(): void {\n const r = this._renderer;\n const scene = this._scene.threeScene;\n const cam = this._camera;\n\n const saved = saveSceneState(scene, this._backend.proxyReadsEnvironment);\n const prevTarget = r.getRenderTarget();\n r.getClearColor(this._clearColor);\n const prevAlpha = r.getClearAlpha();\n const prevAutoClear = r.autoClear;\n const prevShadows = r.shadowMap.enabled;\n try {\n r.setClearColor(0x000000, 0);\n r.autoClear = true;\n r.shadowMap.enabled = true;\n\n cam.layers.set(RELIGHT_PROXY_LAYER);\n r.setRenderTarget(this._litRT as never);\n r.render(scene, cam);\n\n if (this._rawRT) {\n cam.layers.set(RELIGHT_VISIBILITY_LAYER);\n r.setRenderTarget(this._rawRT as never);\n r.render(scene, cam);\n }\n\n const p = this._composeParams;\n p.texelX = 1 / this._rtWidth;\n p.texelY = 1 / this._rtHeight;\n p.blurRadius = this._blurRadius;\n p.shadowBlurRadius = this._shadowBlurRadius;\n // The ambient the proxy material was denied, added back here. The\n // scene's ambient is the PlayCanvas build's gamma-space grey (the\n // `ambientLight` scene option is that build's), so it is linearized the\n // way PlayCanvas linearizes `light_globalAmbient` - and, like there, not\n // exposure-scaled and with no 1/pi.\n const amb = this._scene.ambientLight;\n const k = amb.visible ? amb.intensity : 0;\n p.ambient.set(Math.pow(amb.color.r * k, 2.2), Math.pow(amb.color.g * k, 2.2), Math.pow(amb.color.b * k, 2.2));\n this._composer.render(\n r, this._litRT!.texture, this._rawRT?.texture ?? null, this._lightingRT!, this._visibilityRT!, p,\n );\n } finally {\n r.shadowMap.enabled = prevShadows;\n r.autoClear = prevAutoClear;\n r.setClearColor(this._clearColor, prevAlpha);\n r.setRenderTarget(prevTarget);\n restoreSceneState(scene, saved);\n }\n }\n\n /**\n * Point every live splat of this scene at its binding and write the frame's\n * values into each binding once. Splats appear after the pass is built - LOD\n * levels, variants, characters loaded later - so the scan runs every frame;\n * a splat is only (re)attached when its binding changes, since that\n * recompiles its shader.\n */\n private _publish(valid: boolean): void {\n const placeholder = getRelightPlaceholder();\n const lighting = valid ? this._lightingRT?.texture ?? placeholder : placeholder;\n const visibility = valid ? this._visibilityRT?.texture ?? placeholder : placeholder;\n this._params.set(\n this._rtWidth > 0 ? 1 / this._rtWidth : 0,\n this._rtHeight > 0 ? 1 / this._rtHeight : 0,\n 1 / this._referenceLuminance,\n valid ? 1 : 0,\n );\n\n const bySplat = this._overrideBySplat;\n bySplat.clear();\n for (const [consumer, o] of this._overrides) {\n const splat = consumer instanceof Splat ? consumer : consumer.splat;\n if (splat && !splat.destroyed) bySplat.set(splat, o.binding);\n }\n\n const root = this._scene.threeScene;\n for (const splat of Splat._liveInstances) {\n if (!isUnder(splat.object3D, root)) continue;\n const binding = bySplat.get(splat) ?? this._defaultBinding;\n if (splat.relightBinding !== binding) splat.setRelightBinding(binding);\n this._bound.add(splat);\n }\n for (const splat of this._bound) if (splat.destroyed) this._bound.delete(splat);\n\n let changed = this._write(this._defaultBinding, this._defaults, lighting, visibility);\n for (const o of this._overrides.values()) {\n if (this._write(o.binding, { ...this._defaults, ...o.params }, lighting, visibility)) changed = true;\n }\n if (changed) this._environmentRefreshFrames++;\n }\n\n /** Write one binding; `true` when anything in it changed. */\n private _write(b: SplatRelightBinding, p: Required<RelightParams>, lighting: Texture, visibility: Texture): boolean {\n const shadowStrength = this._visibility ? clamp01(p.shadowStrength) : 0;\n const debug = debugMode(p.debug);\n const flipY = this._flipY ? 1 : 0;\n const changed = b.texture !== lighting\n || b.shadowTexture !== visibility\n || !b.viewProjection.equals(this._viewProjection)\n || !b.params.equals(this._params)\n || b.strength !== p.strength\n || b.tint.x !== p.tint.r || b.tint.y !== p.tint.g || b.tint.z !== p.tint.b\n || b.ambient !== p.ambient\n || b.shadowStrength !== shadowStrength\n || b.flipY !== flipY\n || b.debug !== debug;\n if (!changed) return false;\n b.texture = lighting;\n b.shadowTexture = visibility;\n b.viewProjection.copy(this._viewProjection);\n b.params.copy(this._params);\n b.strength = p.strength;\n b.tint.set(p.tint.r, p.tint.g, p.tint.b);\n b.ambient = p.ambient;\n b.shadowStrength = shadowStrength;\n b.flipY = flipY;\n b.debug = debug;\n b.version++;\n return true;\n }\n}\n\n/**\n * The backend for the renderer `scene` draws with.\n *\n * @throws when the scene renders with WebGPU and the `/webgpu` entry point,\n * which registers the TSL backend, has not been imported.\n */\n/** The relight backend for `scene`'s renderer. @internal */\nexport function relightBackendFor(scene: Scene): RelightBackend {\n if (scene.backendName !== 'webgpu') return webglRelightBackend;\n const backend = getRelightWebGPUBackend();\n if (!backend) {\n throw new Error(\n \"[RelightPass] the scene renders with WebGPU; import '@viggle/splat-engine-three/webgpu' to relight it\",\n );\n }\n return backend;\n}\n\ntype SceneState = Partial<Record<(typeof SCENE_STATE_KEYS)[number], unknown>>;\n\nfunction saveSceneState(scene: ThreeScene, clearEnvironment: boolean): SceneState {\n const s = scene as unknown as Record<string, unknown>;\n const saved: SceneState = {};\n for (const key of SCENE_STATE_KEYS) {\n if (key === 'environment' && !clearEnvironment) continue;\n if (s[key] === undefined || s[key] === null) continue;\n saved[key] = s[key];\n s[key] = null;\n }\n return saved;\n}\n\nfunction restoreSceneState(scene: ThreeScene, saved: SceneState): void {\n const s = scene as unknown as Record<string, unknown>;\n for (const key of Object.keys(saved) as (keyof SceneState)[]) s[key] = saved[key];\n}\n\n/** Whether `object` hangs, however deep, under `root`. */\nfunction isUnder(object: { parent: unknown }, root: object): boolean {\n let o = object.parent as { parent: unknown } | null;\n while (o) {\n if (o === root) return true;\n o = o.parent as { parent: unknown } | null;\n }\n return false;\n}\n\n/** `true` means the lighting paint; a number selects the mode directly. */\nfunction debugMode(v: boolean | number): number {\n return typeof v === 'number' ? v : v ? 1 : 0;\n}\n\nfunction clamp(v: number, lo: number, hi: number): number {\n return v < lo ? lo : v > hi ? hi : v;\n}\n\nfunction clamp01(v: number): number {\n return clamp(v, 0, 1);\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n const out: Partial<T> = {};\n for (const k of Object.keys(o) as (keyof T)[]) {\n if (o[k] !== undefined) out[k] = o[k];\n }\n return out;\n}\n", "import { Matrix4, Vector3, Vector4 } from 'three';\nimport type { Texture } from 'three';\n\n/**\n * What a relight writes for one splat: the screen-space lighting it rendered\n * for the splat's proxy, and how to sample it. The splat shader projects each\n * splat centre through {@link viewProjection} into {@link texture} and\n * multiplies its colour by the lighting found there.\n *\n * The {@link SplatRelight} system owns and updates these; a splat only reads\n * them. Every field is bound by reference, so a relight updates a binding in\n * place and the next frame picks it up.\n *\n * Mirrors the PlayCanvas build's `uRelight*` work-buffer uniforms.\n *\n * @internal\n */\nexport class SplatRelightBinding {\n /** rgb = lighting, a = proxy coverage. */\n texture: Texture | null = null;\n /** r = shadow visibility, g = coverage. */\n shadowTexture: Texture | null = null;\n /** The view-projection the textures were rendered with. */\n readonly viewProjection = new Matrix4();\n /** xy = 1 / texture size, z = 1 / reference luminance, w = 1 when the textures are valid. */\n readonly params = new Vector4(0, 0, 1, 0);\n /** 0..1: how much of the lighting is applied. */\n strength = 0;\n readonly tint = new Vector3(1, 1, 1);\n /** Lighting floor, so a splat in full shade keeps some of its colour. */\n ambient = 0;\n /** 0..1: how much of the shadow is applied. */\n shadowStrength = 0;\n /** 1 when the textures' rows run top-down. */\n flipY = 0;\n /** 0 off, 1 lighting debug colours, 2 shadow visibility. */\n debug = 0;\n /** Bumped by the relight whenever a field changes, so a backend can skip work. */\n version = 0;\n}\n", "import type { DirectionalLight, Material, RenderTarget, Texture, Vector3 } from 'three';\nimport type { ProxyShadowBias } from './shadow-bias';\n\n/**\n * The renderer-facing half of the relight: the proxy's material, its render\n * targets and the compose pass. Everything else - layers, cameras, lights,\n * skinning, publishing - is plain three.js and shared by both renderers.\n *\n * Two implementations, as with the splat backends: GLSL for\n * `THREE.WebGLRenderer` (the default, `webgl-backend.ts`) and TSL for\n * `WebGPURenderer`, registered by the `/webgpu` entry point so the default\n * entry never loads `three/webgpu`.\n *\n * @internal\n */\nexport interface RelightBackend {\n /**\n * The material every lighting-receiving proxy is drawn with. Its output\n * contract is what the compose and the splat shader assume, so it is fixed:\n *\n * rgb = SUM over lights of colour * N.L * attenuation * shadow\n * a = 1 (the coverage mask)\n *\n * That is a white lambertian with NO ambient and PlayCanvas's light model:\n * no 1/pi in the diffuse term, and the linear `(range - d) / range` falloff\n * on point and spot lights, where three's own lights fall off by the\n * inverse square with a smooth window. Shadows come from three's own shadow\n * maps, so a light's `castShadow` and `shadow.*` work as they do anywhere.\n * `bias` is the owning relight's key-light bias, where the backend applies\n * it in the material.\n */\n createProxyMaterial(bias: ProxyShadowBias): Material;\n /**\n * A half-float RGBA target, linear-filtered: lighting exceeds 1 and must\n * not clamp, and half rather than full float because some mobile GPUs\n * cannot filter float32.\n *\n * @throws when the renderer cannot render to half float.\n */\n createTarget(renderer: unknown, width: number, height: number, depth: boolean): RenderTarget;\n /** The compose pass. One per {@link RelightPass}. */\n createComposer(): RelightComposer;\n /**\n * Whether the lighting texture's rows run top-down as seen through\n * `uv = ndc * 0.5 + 0.5`, i.e. whether the splat lookup must mirror its\n * row. A property of the renderer, measured rather than reasoned - see\n * {@link RelightPass.flipY}.\n */\n readonly flipY: boolean;\n /**\n * Whether the proxy materials would read `scene.environment`, so the pass\n * must clear it around the proxy render. True under `WebGLRenderer`, which\n * feeds the environment to every Lambert material.\n */\n readonly proxyReadsEnvironment: boolean;\n /**\n * Make `light`'s shadow on the proxies take `bias` (shadow-bias.ts), where\n * the backend does it on the light rather than in the proxy material.\n */\n configureKeyLight(light: DirectionalLight, bias: ProxyShadowBias): void;\n}\n\n/** Values the compose reads. See `relight-shaders.ts`. */\nexport interface RelightComposeParams {\n /** One texel of the proxy targets, in uv. */\n texelX: number;\n texelY: number;\n /** Tent radius over the lighting, in texels. `0` is a single tap. */\n blurRadius: number;\n /** Tent radius over the shadow visibility, in texels. */\n shadowBlurRadius: number;\n /** Ambient added back to the direct light, linear. */\n ambient: Vector3;\n}\n\n/**\n * The compose pass: tent-blur the raw proxy renders, un-premultiply by\n * coverage, add the ambient back, and split out the shadow visibility. See\n * `relight-shaders.ts` for the arithmetic.\n *\n * Two draws, one per output, where the PlayCanvas build writes an MRT pair\n * from one: the outputs are half-resolution and the second draw is cheaper\n * than the per-renderer MRT plumbing.\n *\n * @internal\n */\nexport interface RelightComposer {\n /**\n * Write `lighting` (rgb lighting, a coverage) and `visibility` (r shadow\n * visibility, g coverage) from `lit` and, when there is one, `raw` - the\n * same proxies with every shadow map ignored. Without `raw` the visibility\n * is 1.\n */\n render(\n renderer: unknown,\n lit: Texture,\n raw: Texture | null,\n lighting: RenderTarget,\n visibility: RenderTarget,\n params: RelightComposeParams,\n ): void;\n dispose(): void;\n}\n\nlet webgpuBackend: RelightBackend | null = null;\n\n/**\n * Make the relight available under `WebGPURenderer`. Called by the\n * `@viggle/splat-engine-three/webgpu` entry point.\n * @internal\n */\nexport function registerRelightWebGPUBackend(backend: RelightBackend): void {\n webgpuBackend = backend;\n}\n\n/** The WebGPU backend, or `null` before the `/webgpu` entry point has loaded. @internal */\nexport function getRelightWebGPUBackend(): RelightBackend | null {\n return webgpuBackend;\n}\n", "import { ClampToEdgeWrapping, DataTexture, HalfFloatType, LinearFilter, RGBAFormat } from 'three';\nimport type { Texture } from 'three';\n\n/**\n * 1x1 stand-in for the relight textures.\n *\n * A splat shader compiled with a relight samples its textures on every draw,\n * so a binding never points at `null`: WebGPU builds its texture node from\n * whatever the binding holds when the shader is made, and WebGL would bind\n * whatever happens to sit on the unit. This is what a binding holds before\n * the first lighting render and after the pass is gone.\n *\n * Zero coverage in the alpha channel, so a consumer that somehow reaches the\n * sample despite `params.w == 0` still falls back to its baked colour rather\n * than to black.\n *\n * One per page: a `DataTexture` is uploaded lazily by whichever renderer\n * first binds it, so it is not tied to a device the way a PlayCanvas texture\n * is.\n */\nlet placeholder: DataTexture | null = null;\n\nexport function getRelightPlaceholder(): Texture {\n if (placeholder) return placeholder;\n const tex = new DataTexture(new Uint16Array(4), 1, 1, RGBAFormat, HalfFloatType);\n tex.name = 'relightPlaceholder';\n tex.minFilter = LinearFilter;\n tex.magFilter = LinearFilter;\n tex.wrapS = ClampToEdgeWrapping;\n tex.wrapT = ClampToEdgeWrapping;\n tex.generateMipmaps = false;\n tex.needsUpdate = true;\n placeholder = tex;\n return tex;\n}\n", "import { Vector3 } from 'three';\n\n/**\n * The key light's PlayCanvas depth bias, as the proxies take it when they\n * receive its shadow. PlayCanvas offsets every caster's depth by\n * `polygonOffset(f, f)` while it draws the shadow map (`f` from the light's\n * `shadowBias`); the proxies, which are both the casters and the receivers\n * that matter here, take the same offset at the receiving end instead:\n * `f x one shadow texel x tan(angle to the light)`, toward the light. One per\n * {@link SplatRelight}, written as it places its key light and read by that\n * instance's proxy material (WebGL) or key light (WebGPU), so two instances\n * never share a slope.\n * @internal\n */\nexport interface ProxyShadowBias {\n /** Unit vector toward the key light, world space. */\n readonly toLight: Vector3;\n /** Polygon-offset slope factor times one shadow texel, in world units. 0: none. */\n slope: number;\n}\n\n/** A zero bias, pointing straight up. @internal */\nexport function createProxyShadowBias(): ProxyShadowBias {\n return { toLight: new Vector3(0, 1, 0), slope: 0 };\n}\n\n/**\n * The receiver offset in GLSL: `relightSlopeOffset(worldNormal)` is the\n * world-space shift toward the key light. @internal\n */\nexport const PROXY_SHADOW_BIAS_GLSL = /* glsl */ `\nuniform vec3 uRelightToLight;\nuniform float uRelightSlopeBias;\nvec3 relightSlopeOffset(vec3 n) {\n float c = dot(normalize(n), uRelightToLight);\n if (c <= 0.0 || uRelightSlopeBias == 0.0) return vec3(0.0);\n return uRelightToLight * (uRelightSlopeBias * sqrt(max(1.0 - c * c, 0.0)) / max(c, 1e-3));\n}\n`;\n", "import {\n GLSL3,\n HalfFloatType,\n LinearFilter,\n Mesh,\n MeshLambertMaterial,\n OrthographicCamera,\n PlaneGeometry,\n RGBAFormat,\n ShaderChunk,\n ShaderMaterial,\n Vector3,\n Vector4,\n WebGLRenderTarget,\n} from 'three';\nimport type { Material, RenderTarget, Texture, WebGLRenderer } from 'three';\n\nimport type { RelightBackend, RelightComposeParams, RelightComposer } from './backend';\nimport { getRelightPlaceholder } from './relight-placeholder';\nimport { COMPOSE_FRAGMENT_GLSL, COMPOSE_VERTEX_GLSL } from './relight-shaders';\nimport { PROXY_SHADOW_BIAS_GLSL } from './shadow-bias';\nimport type { ProxyShadowBias } from './shadow-bias';\n\n/**\n * three's `getDistanceAttenuation` - inverse-square with a smooth window -\n * swapped for PlayCanvas's `LIGHTFALLOFF_LINEAR`, the falloff the proxy's\n * lights have in the PlayCanvas build. Both point and spot lights go through\n * it. `cutoffDistance` 0 is three's \"infinite range\", which PlayCanvas has no\n * equivalent of; it keeps full strength.\n */\nconst PC_FALLOFF_GLSL = /* glsl */ `float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif ( cutoffDistance <= 0.0 ) return 1.0;\n\treturn max( ( cutoffDistance - lightDistance ) / cutoffDistance, 0.0 );\n}\n`;\n\nconst ATTENUATION_FN = /float getDistanceAttenuation\\([\\s\\S]*?\\n}\\n/;\n\nlet lightsParsWithPcFalloff: string | null = null;\n\nfunction lightsPars(): string {\n if (lightsParsWithPcFalloff) return lightsParsWithPcFalloff;\n const src = ShaderChunk.lights_pars_begin;\n if (!ATTENUATION_FN.test(src)) {\n // A three.js upgrade moved the function: fail loudly rather than light the\n // proxy with a falloff the PlayCanvas build does not have.\n throw new Error('[SplatRelight] three.js lights_pars_begin no longer defines getDistanceAttenuation');\n }\n lightsParsWithPcFalloff = src.replace(ATTENUATION_FN, PC_FALLOFF_GLSL);\n return lightsParsWithPcFalloff;\n}\n\nconst DIR_SHADOW_POSITION =\n 'shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );';\nlet shadowmapVertexWithBias: string | null = null;\n\nfunction shadowmapVertex(): string {\n if (shadowmapVertexWithBias) return shadowmapVertexWithBias;\n const src = ShaderChunk.shadowmap_vertex;\n if (!src.includes(DIR_SHADOW_POSITION)) {\n throw new Error('[SplatRelight] three.js shadowmap_vertex no longer places directional shadow lookups the same way');\n }\n shadowmapVertexWithBias = src.replace(\n DIR_SHADOW_POSITION,\n 'shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias'\n + ' + relightSlopeOffset( shadowWorldNormal ), 0 );',\n );\n return shadowmapVertexWithBias;\n}\n\nclass WebGLRelightComposer implements RelightComposer {\n private readonly _uniforms = {\n uProxyLitTex: { value: getRelightPlaceholder() as Texture },\n uProxyRawTex: { value: getRelightPlaceholder() as Texture },\n uComposeParams: { value: new Vector4() },\n uComposeHasRaw: { value: 0 },\n uComposeAmbient: { value: new Vector3() },\n };\n private readonly _lighting: ShaderMaterial;\n private readonly _visibility: ShaderMaterial;\n private readonly _quad: Mesh;\n private readonly _camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);\n\n constructor() {\n const material = (visibility: boolean) => new ShaderMaterial({\n name: visibility ? 'relight-compose-visibility' : 'relight-compose-lighting',\n glslVersion: GLSL3,\n uniforms: this._uniforms,\n defines: visibility ? { RELIGHT_VISIBILITY: '' } : {},\n vertexShader: COMPOSE_VERTEX_GLSL,\n fragmentShader: COMPOSE_FRAGMENT_GLSL,\n depthTest: false,\n depthWrite: false,\n toneMapped: false,\n });\n this._lighting = material(false);\n this._visibility = material(true);\n this._quad = new Mesh(new PlaneGeometry(2, 2), this._lighting);\n this._quad.frustumCulled = false;\n }\n\n render(\n renderer: unknown,\n lit: Texture,\n raw: Texture | null,\n lighting: RenderTarget,\n visibility: RenderTarget,\n params: RelightComposeParams,\n ): void {\n const r = renderer as WebGLRenderer;\n const u = this._uniforms;\n u.uProxyLitTex.value = lit;\n u.uProxyRawTex.value = raw ?? lit;\n u.uComposeHasRaw.value = raw ? 1 : 0;\n u.uComposeParams.value.set(params.texelX, params.texelY, params.blurRadius, params.shadowBlurRadius);\n u.uComposeAmbient.value.copy(params.ambient);\n\n this._quad.material = this._lighting;\n r.setRenderTarget(lighting as WebGLRenderTarget);\n r.render(this._quad, this._camera);\n this._quad.material = this._visibility;\n r.setRenderTarget(visibility as WebGLRenderTarget);\n r.render(this._quad, this._camera);\n }\n\n dispose(): void {\n this._quad.geometry.dispose();\n this._lighting.dispose();\n this._visibility.dispose();\n }\n}\n\n/** The relight for `THREE.WebGLRenderer`. Registered by default. @internal */\nexport const webglRelightBackend: RelightBackend = {\n flipY: false,\n proxyReadsEnvironment: true,\n // The proxy material takes the bias itself (see createProxyMaterial).\n configureKeyLight() {},\n\n createProxyMaterial(bias: ProxyShadowBias): Material {\n const mat = new MeshLambertMaterial({ name: 'relight-proxy' });\n // Per material, so each relight's proxies read their own key light's bias.\n const toLightUniform = { value: bias.toLight };\n const slopeUniform = { get value() { return bias.slope; } };\n // three's lambert divides by pi; PlayCanvas's does not. An albedo of pi is\n // what makes the output `colour * N.L` - the sum the compose expects.\n mat.color.setScalar(Math.PI);\n mat.fog = false;\n mat.toneMapped = false;\n mat.onBeforeCompile = (shader) => {\n shader.fragmentShader = shader.fragmentShader.replace('#include <lights_pars_begin>', lightsPars());\n // The key light's PlayCanvas depth bias, taken at the receiving end:\n // directional shadows are looked up from a point moved toward the light.\n shader.uniforms.uRelightToLight = toLightUniform;\n shader.uniforms.uRelightSlopeBias = slopeUniform;\n shader.vertexShader = shader.vertexShader\n .replace('void main() {', `${PROXY_SHADOW_BIAS_GLSL}\\nvoid main() {`)\n .replace('#include <shadowmap_vertex>', shadowmapVertex());\n };\n // One program for every proxy material: the patch never varies.\n mat.customProgramCacheKey = () => 'relight-proxy-pc-falloff-bias';\n return mat;\n },\n\n createTarget(renderer: unknown, width: number, height: number, depth: boolean): RenderTarget {\n const ext = (renderer as WebGLRenderer).extensions;\n if (!ext.has('EXT_color_buffer_float') && !ext.has('EXT_color_buffer_half_float')) {\n throw new Error(\n '[RelightPass] the device cannot render to half-float textures, which the ' +\n 'lighting target requires (lighting exceeds 1 and must not be clamped).',\n );\n }\n return new WebGLRenderTarget(width, height, {\n type: HalfFloatType,\n format: RGBAFormat,\n // Bilinear, not point: an animated splat's screen position drifts across\n // this texture every frame and a point read pops at texel boundaries.\n minFilter: LinearFilter,\n magFilter: LinearFilter,\n generateMipmaps: false,\n depthBuffer: depth,\n stencilBuffer: false,\n });\n },\n\n createComposer(): RelightComposer {\n return new WebGLRelightComposer();\n },\n};\n", "// Compose + blur for the proxy relight pass.\n//\n// Input: the two raw proxy renders (see `relight-pass.ts`).\n//\n// uProxyLitTex rgb = SUM over lights of colour * N.L * attenuation * shadow\n// a = proxy coverage (1 where the proxy drew, 0 elsewhere)\n// uProxyRawTex rgb = the same sum with every shadow map ignored\n// a = the same coverage\n//\n// Both are rendered by the backend's proxy material, which has no ambient\n// term, so the rgb of each is the DIRECT light only - which is what makes the\n// visibility ratio below come out as Unity's `weightLit / weightTotal`\n// exactly, with the ambient term added back here rather than baked into\n// either input.\n//\n// Output, one draw each (the PlayCanvas build writes them as an MRT pair):\n//\n// lighting RGBA16F rgb = full lighting (direct + ambient), a = coverage\n// visibility RGBA16F r = shadow visibility, g = coverage\n//\n// The 3x3 tent (weights 1-2-1 x 1-2-1, total 16) is what keeps the lighting\n// temporally stable while the proxy animates: a blocky proxy's silhouette and\n// its self-shadow re-rasterize differently every frame at half resolution, and\n// splats sampling those hard edges pop between values.\n//\n// \u2500\u2500 Why there are two radii \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// The tap offsets are the proxy target's texel scaled by a radius, and the two\n// inputs get their OWN radius. They carry different things and want different\n// amounts:\n//\n// lit -> the lighting, shadow map included. Softening it softens the cast\n// shadow AND the terminator running across the subject, because both\n// live in the same channel. This is the one that matters when the\n// shadow is being read through `strength` alone.\n// raw -> the same light with every shadow map ignored, which exists only to\n// divide into `lit` and leave the shadow VISIBILITY. Softening it\n// alone softens the cast shadow and nothing else.\n//\n// A radius of 1 is the original tent and the default. 0 is a single tap - the\n// raw bake, which is what you want to look at and not what you want to ship.\n// Above about 3 the nine taps stop overlapping and the tent starts reading as\n// a sparse cross rather than a blur; bilinear filtering hides it for a while,\n// and the knob's range says where that ends.\n//\n// Widening either one also widens the coverage ramp it carries, and coverage\n// is what the un-premultiply divides by - so a large radius spreads a\n// subject's lighting slightly past its own silhouette. At half resolution and\n// a radius of a few texels that is a pixel or two, which is why this is a\n// radius and not an arbitrary kernel.\n//\n// rgb is premultiplied by coverage on the way in (the bake writes rgb only\n// where a = 1 and the target clears to 0), so averaging it raw would mix in the\n// black outside the silhouette and put a dark rim exactly where edge splats\n// sample. Un-premultiply on output: colour stays full strength to the very edge\n// while the coverage alpha fades.\n//\n// The WebGPU twin of this is TSL, in `webgpu/backend.ts`.\n\n/** Full-screen triangle pair; `uv` comes from the plane, bottom-left origin like the targets. */\nexport const COMPOSE_VERTEX_GLSL = /* glsl */ `\nout vec2 vUv0;\n\nvoid main(void) {\n vUv0 = uv;\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n`;\n\n/** `RELIGHT_VISIBILITY` defined writes the visibility output, undefined the lighting. */\nexport const COMPOSE_FRAGMENT_GLSL = /* glsl */ `\nin vec2 vUv0;\nlayout(location = 0) out highp vec4 outColor;\n\nuniform sampler2D uProxyLitTex;\nuniform sampler2D uProxyRawTex;\n// xy = one texel of the proxy target in uv; z = the lighting tent's radius in\n// texels, w = the shadow-visibility tent's. 0 on either is a single tap.\nuniform vec4 uComposeParams;\n// 1 when uProxyRawTex holds a real unshadowed render, 0 when it is a stand-in.\nuniform float uComposeHasRaw;\nuniform vec3 uComposeAmbient;\n\nvec4 tent(sampler2D src, vec2 uv, vec2 texel, float radius) {\n vec4 c = textureLod(src, uv, 0.0);\n if (radius <= 0.0) return c;\n vec2 t = texel * radius;\n vec4 sum = c * 4.0;\n sum += textureLod(src, uv + vec2(-t.x, -t.y), 0.0);\n sum += textureLod(src, uv + vec2( 0.0, -t.y), 0.0) * 2.0;\n sum += textureLod(src, uv + vec2( t.x, -t.y), 0.0);\n sum += textureLod(src, uv + vec2(-t.x, 0.0), 0.0) * 2.0;\n sum += textureLod(src, uv + vec2( t.x, 0.0), 0.0) * 2.0;\n sum += textureLod(src, uv + vec2(-t.x, t.y), 0.0);\n sum += textureLod(src, uv + vec2( 0.0, t.y), 0.0) * 2.0;\n sum += textureLod(src, uv + vec2( t.x, t.y), 0.0);\n return sum / 16.0;\n}\n\nvoid main(void) {\n vec2 t = uComposeParams.xy;\n\n vec4 lit = tent(uProxyLitTex, vUv0, t, uComposeParams.z);\n float cov = clamp(lit.a, 0.0, 1.0);\n // Un-premultiply. Below the threshold there is no proxy here at all, and\n // the lighting value is never read (the consumer gates on coverage).\n vec3 direct = cov > 1e-4 ? lit.rgb / cov : vec3(0.0);\n\n#ifndef RELIGHT_VISIBILITY\n outColor = vec4(direct + uComposeAmbient, cov);\n#else\n float visibility = 1.0;\n if (uComposeHasRaw > 0.5) {\n vec4 raw = tent(uProxyRawTex, vUv0, t, uComposeParams.w);\n float rawCov = clamp(raw.a, 0.0, 1.0);\n vec3 unshadowed = rawCov > 1e-4 ? raw.rgb / rawCov : vec3(0.0);\n // Luminance of the direct sums, exactly Unity's\n // weightTotal = Luminance(lightColor) * ndl * distanceAttenuation\n // weightLit = weightTotal * shadowAttenuation\n // summed over lights. The ratio therefore carries no N.L, no light\n // colour and no ambient of its own: a surface merely turned away from\n // every light has no light to lose and reports 1 (unshadowed) rather\n // than the darkness the relight path exists to express.\n float total = dot(unshadowed, vec3(0.2126, 0.7152, 0.0722));\n float reaching = dot(direct, vec3(0.2126, 0.7152, 0.0722));\n visibility = total > 1e-4 ? clamp(reaching / total, 0.0, 1.0) : 1.0;\n }\n outColor =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KAAK,OAAO,KAAK,CAAC,GAAkB;AAC7C,QAAI,EAAE,CAAC,MAAM,OAAW,KAAI,CAAC,IAAI,EAAE,CAAC;AAAA,EACtC;AACA,SAAO;AACT;",
|
|
6
|
-
"names": ["Matrix4", "Vector3", "Vector3", "extract", "cache", "normalize", "pending", "converted", "inflight", "idx", "idx", "remap", "idx", "relax", "Group", "Matrix4", "Vector3", "Matrix4", "Vector3", "Group", "width", "DataUtils", "ClampToEdgeWrapping", "DataTexture", "FloatType", "NearestFilter", "RGBAFormat", "Sphere", "Vector2", "Vector3", "Vector4", "BufferAttribute", "Quaternion", "Vector3", "ClampToEdgeWrapping", "DataTexture", "FloatType", "NearestFilter", "RGBAFormat", "Vector3", "Quaternion", "_scale", "BufferAttribute", "width", "DataTexture", "NearestFilter", "ClampToEdgeWrapping", "Vector4", "Vector2", "Sphere", "RGBAFormat", "FloatType", "Vector3", "at", "SH_C0", "width", "width", "out", "SH_C0", "fail", "SH_C0", "SH_C0", "FIRST_PLANAR_VERSION", "_f16Buf", "_f16U32", "_f16F32", "f16ToF32", "SH_C0", "BYTES_PER_ELEMENT", "idx", "cacheKeyFor", "inflight", "idx", "Vector3", "Vector3", "Matrix4", "GLB_MAGIC", "Color", "SRGBColorSpace", "Vector3", "Color", "ClampToEdgeWrapping", "HalfFloatType", "RGBAFormat", "BufferAttribute", "BufferGeometry", "CustomBlending", "Mesh", "OneFactor", "Vector2", "Vector3", "Vector4", "BufferGeometry", "BufferAttribute", "CustomBlending", "OneFactor", "Mesh", "webgpuBackend", "width", "HalfFloatType", "RGBAFormat", "ClampToEdgeWrapping", "width", "width", "Vector3", "BufferGeometry", "Euler", "Matrix4", "Quaternion", "Vector3", "Vector3", "Quaternion", "_pos", "_scale", "Euler", "_mat", "_mat2", "BufferGeometry", "Matrix4", "Vector3", "Color", "SRGBColorSpace", "Vector3", "width", "width", "Color", "width", "width", "Quaternion", "Vector3", "Vector3", "Quaternion", "BufferAttribute", "BufferGeometry", "Group", "Matrix4", "Object3D", "Quaternion", "Vector3", "idx", "Vector3", "Group", "Object3D", "BufferGeometry", "BufferAttribute", "anchorWorld", "jointWorldMat", "frameInChildRot", "frameInParentMat", "frameInParentRot", "Quaternion", "Matrix4", "Euler", "MathUtils", "Group", "Matrix4", "Vector3", "Matrix4", "Vector3", "Group", "clamp", "width", "ENVIRONMENT_RENDER_ORDER", "_euler", "Euler", "MathUtils", "FileLoader", "Loader", "Loader", "FileLoader", "Color", "Vector3", "Color", "Vector3", "Color", "Color", "Color", "Vector3", "Vector3", "Color", "Group", "Vector3", "BufferGeometry", "Color", "Mesh", "MeshBasicMaterial", "Quaternion", "Vector3", "AddEquation", "CustomBlending", "DoubleSide", "Euler", "Matrix4", "NormalBlending", "OneFactor", "Quaternion", "SRGBColorSpace", "Vector3", "_euler", "BufferGeometry", "Vector3", "Quaternion", "_pos", "Mesh", "MeshBasicMaterial", "Color", "AddEquation", "BufferAttribute", "BufferGeometry", "ClampToEdgeWrapping", "CustomBlending", "DataTexture", "DoubleSide", "DynamicDrawUsage", "LinearFilter", "Matrix3", "Matrix4", "Mesh", "MeshBasicMaterial", "NormalBlending", "Object3D", "OneFactor", "Quaternion", "SRGBColorSpace", "Color", "Vector3", "_nodeScale", "_right", "_up", "_pos", "Vector3", "resolveUrl", "idx", "Group", "Color", "DataTexture", "LinearFilter", "Mesh", "NoColorSpace", "MeshBasicMaterial", "Quaternion", "SRGBColorSpace", "DataTexture", "pending", "LinearFilter", "NoColorSpace", "SRGBColorSpace", "Quaternion", "_pos", "MeshBasicMaterial", "Color", "Mesh", "GLSL3", "Matrix3", "Matrix4", "Mesh", "RawShaderMaterial", "warned", "warnOnce", "Matrix4", "Matrix3", "RawShaderMaterial", "GLSL3", "_pos", "Mesh", "Group", "resolveUrl", "Group", "Matrix4", "Quaternion", "Vector3", "_up", "_parentQuat", "now", "BufferAttribute", "BufferGeometry", "DynamicDrawUsage", "LineBasicMaterial", "LineSegments", "FACIAL_PREFIX", "Color", "Mesh", "MeshBasicMaterial", "MeshBasicMaterial", "Color", "Mesh", "Box3", "BufferAttribute", "BufferGeometry", "Color", "DataTexture", "LinearSRGBColorSpace", "Matrix4", "Mesh", "PointLight", "SRGBColorSpace", "Skeleton", "SkinnedMesh", "Vector3", "Matrix4", "DataUtils", "DataUtils", "Matrix4", "BufferAttribute", "BufferGeometry", "Color", "DynamicDrawUsage", "LineBasicMaterial", "LineSegments", "Color", "LineBasicMaterial", "LineSegments", "BufferGeometry", "BufferAttribute", "DynamicDrawUsage", "idx", "INFLUENCES", "idx", "Color", "Matrix4", "Mesh", "MeshBasicMaterial", "OrthographicCamera", "PerspectiveCamera", "Vector2", "Vector3", "Vector4", "Matrix4", "Vector3", "Vector4", "webgpuBackend", "ClampToEdgeWrapping", "DataTexture", "HalfFloatType", "LinearFilter", "RGBAFormat", "Vector3", "GLSL3", "HalfFloatType", "LinearFilter", "Mesh", "OrthographicCamera", "RGBAFormat", "ShaderMaterial", "Vector3", "Vector4", "WebGLRenderTarget", "Vector4", "Vector3", "OrthographicCamera", "ShaderMaterial", "GLSL3", "Mesh", "width", "WebGLRenderTarget", "HalfFloatType", "RGBAFormat", "LinearFilter", "Matrix4", "Vector4", "Vector3", "Color", "Vector2", "PerspectiveCamera", "OrthographicCamera", "clamp", "MeshBasicMaterial", "stripUndefined", "Mesh", "placeholder", "Color", "clamp01", "clamp", "stripUndefined", "PointLight", "BufferGeometry", "BufferAttribute", "Matrix4", "Skeleton", "SkinnedMesh", "Mesh", "DEG", "_up", "Box3", "Vector3", "DataTexture", "SRGBColorSpace", "LinearSRGBColorSpace"]
|
|
7
|
-
}
|