{"version":3,"file":"pixijs-3d.min.mjs","names":["_shared","_sharedMatrix","_identityMatrix","_multiplyMatrices","_shared","UID","classCache","GL_FLOAT","_position","_quaternion","_scale","_identityMatrix","_bounds","cache","cache","cache","_shared"],"sources":["../src/animation/Animation.ts","../src/math/utils/clamp.ts","../src/math/vector/Vector3.ts","../src/math/matrix/Matrix4.ts","../src/math/rotation/Quaternion.ts","../src/math/rotation/ObservableQuaternion.ts","../src/math/shapes/Box.ts","../src/math/vector/EulerDegrees.ts","../src/math/vector/ObservableVector3.ts","../src/utils/Destroy3DOptions.ts","../src/scene/utils/getLocalBounds3D.ts","../src/scene/utils/updateTransformBackwards3D.ts","../src/scene/Container3D.ts","../src/core/render-passes/passBitRegistry.ts","../src/core/shader/ShaderBitTemplate.ts","../src/core/shader/bitRegistry.ts","../src/core/shader/codegen/assertOutputName.ts","../src/core/shader/codegen/collectFragmentOutputs.ts","../src/core/shader/ShaderDescriptor.ts","../src/materials/PassDescriptor.ts","../src/core/batcher/Mesh3DData.ts","../src/utils/copyState.ts","../src/core/batcher/updateMesh3DKeys.ts","../src/core/render-graph/SceneOutput.ts","../src/core/render-graph/sceneOutputs.ts","../src/core/render-passes/RenderPass.ts","../src/math/shapes/Sphere.ts","../src/utils/UnstableList.ts","../src/geometry/utils/Geometry3DUtils.ts","../src/geometry/Geometry3D.ts","../src/events/resolveHitVolume.ts","../src/core/batcher/textureSetId.ts","../src/core/shader/codegen/packStructFields.ts","../src/core/shader/codegen/parseBindingType.ts","../src/core/shader/codegen/materialStruct.ts","../src/core/textures/DefaultTextures.ts","../src/utils/warnOnce.ts","../src/core/buffers/dataTextureLayout.ts","../src/core/shader/codegen/structLayout.ts","../src/materials/utils/createMaterialDataClass.ts","../src/materials/utils/createMaterialTexturesClass.ts","../src/materials/utils/refreshBindGroup.ts","../src/materials/utils/validateMaterialTextureSlots.ts","../src/materials/BaseMaterial3D.ts","../src/scene/Morph.ts","../src/scene/Mesh3D.ts","../src/animation/AnimationState.ts","../src/animation/bindings/Binding.ts","../src/animation/bindings/FloatArrayBinding.ts","../src/animation/bindings/NumberBinding.ts","../src/animation/bindings/QuaternionBinding.ts","../src/animation/bindings/SkeletonPositionBinding.ts","../src/animation/bindings/SkeletonRotationBinding.ts","../src/animation/bindings/SkeletonScaleBinding.ts","../src/animation/bindings/Vector3Binding.ts","../src/animation/bindings/createBinding.ts","../src/animation/PropertyAccumulator.ts","../src/animation/AnimationPlayer.ts","../src/animation/tracks/Track.ts","../src/animation/tracks/NumberTrack.ts","../src/animation/tracks/QuaternionTrack.ts","../src/animation/tracks/Vector3Track.ts","../src/assets/loaders/cubemap/loadCubemap.ts","../src/assets/loaders/gltf/utils/gltfAttributeMap.ts","../src/assets/loaders/gltf/utils/widenColorToRgba.ts","../src/assets/loaders/gltf/draco/worker/draco.worker.ts?worker&inline","../src/assets/loaders/gltf/draco/setDracoDecoderPath.ts","../src/assets/loaders/gltf/draco/worker/loadDracoOnWorker.ts","../src/assets/loaders/gltf/draco/decodeDracoPrimitive.ts","../src/assets/loaders/gltf/meshopt/decodeMeshoptBufferViews.ts","../src/assets/loaders/gltf/meshopt/normalizeMeshopt.ts","../src/assets/Scene3DSource.ts","../src/assets/loaders/gltf/utils/accessorToVertexFormat.ts","../src/assets/loaders/gltf/utils/getBuffer.ts","../src/assets/loaders/gltf/process/processAnimations.ts","../src/assets/loaders/gltf/process/processCameras.ts","../src/core/shader/bits/alphaMaskBit.ts","../src/core/shader/bits/uvTransformBit.ts","../src/materials/flat/bits/flatMaterialBit.ts","../src/materials/flat/FlatMaterial.ts","../src/core/shader/bits/derivativeTangentFrameBit.ts","../src/core/shader/bits/mathConstantsBit.ts","../src/core/shader/bits/anisotropyBit.ts","../src/core/shader/bits/emissiveBit.ts","../src/materials/utils/createFeaturePropsClass.ts","../src/materials/utils/emissiveProps.ts","../src/materials/pbr/bits/clearcoatBit.ts","../src/materials/pbr/bits/iblBit.ts","../src/materials/pbr/bits/iridescenceBit.ts","../src/core/lightLimits.ts","../src/core/LightTiles.ts","../src/core/shader/createLightingBit.ts","../src/materials/pbr/bits/pbrLightingBit.ts","../src/materials/pbr/bits/pbrMaterialBit.ts","../src/materials/pbr/bits/sheenBit.ts","../src/materials/pbr/bits/specularBit.ts","../src/materials/pbr/bits/screenSpaceFuncsBit.ts","../src/materials/pbr/bits/transmissionBit.ts","../src/materials/pbr/Material3D.ts","../src/assets/loaders/gltf/process/processMaterials.ts","../src/assets/loaders/gltf/process/processLights.ts","../src/assets/loaders/gltf/process/processMeshes.ts","../src/assets/loaders/gltf/process/processNodes.ts","../src/assets/loaders/gltf/process/processScenes.ts","../src/assets/loaders/gltf/process/processSkins.ts","../src/assets/loaders/gltf/process/processTextures.ts","../src/assets/loaders/gltf/parseGltf.ts","../src/assets/loaders/gltf/utils/glbToGltf.ts","../src/assets/loaders/gltf/utils/loadImages.ts","../src/assets/loaders/gltf/loadGlb.ts","../src/assets/loaders/gltf/loadGltf.ts","../src/core/fullscreenTriangleGeometry.ts","../src/core/shader/bits/decodeToLinearBit.ts","../src/core/shader/bits/iblSamplingFuncsBit.ts","../src/core/textures/floatRenderTargets.ts","../src/core/ibl/generateIblSpecialCubemap.ts","../src/assets/loaders/hdr/equirectToCube.ts","../src/assets/loaders/hdr/parseRadianceHdr.ts","../src/assets/loaders/hdr/loadHdr.ts","../src/core/batcher/batchConstants.ts","../src/core/batcher/BatchInstanceData.ts","../src/core/buffers/Buffer3D.ts","../src/core/buffers/DirtySlots.ts","../src/core/buffers/DataStoreBuffer.ts","../src/core/buffers/Mesh3DDataStoreBuffer.ts","../src/core/batcher/BatchMatrices.ts","../src/core/batcher/DrawCommand.ts","../src/core/batcher/DrawCommandCapture.ts","../src/core/batcher/DrawCommandList.ts","../src/core/batcher/instanceDataLayout.ts","../src/core/buffers/InstanceDataStoreBuffer.ts","../src/core/batcher/SortedMesh3DView.ts","../src/core/buffers/DrawArgs.ts","../src/core/buffers/RenderInstanceBuffer.ts","../src/core/render-passes/DrawList.ts","../src/core/batcher/Mesh3DSlot.ts","../src/core/batcher/Mesh3DBatch.ts","../src/core/batcher/Mesh3DBatcher.ts","../src/core/buffers/BonePit.ts","../src/core/buffers/emptyBufferResource.ts","../src/core/buffers/GeometryDataStoreBuffer.ts","../src/core/buffers/IndirectDrawData.ts","../src/core/buffers/MaterialRowResource.ts","../src/core/buffers/MaterialDataStoreBuffer.ts","../src/core/buffers/MorphStoreBuffer.ts","../src/core/buffers/RenderInstanceTexture.ts","../src/math/shapes/Plane.ts","../src/math/misc/Frustum.ts","../src/core/CameraData.ts","../src/core/cull.ts","../src/core/detectSharedCacheInvalidation.ts","../src/core/render-passes/shadow/csmUtils.ts","../src/core/render-passes/shadow/shadowPassUtils.ts","../src/core/GlobalUniformGroup.ts","../src/core/ibl/brdfLutGlslTemplate.ts","../src/core/ibl/brdfLutWgslTemplate.ts","../src/core/ibl/generateBrdfLut.ts","../src/core/LightDataList.ts","../src/core/render-graph/frameToPhysicalViewport.ts","../src/core/prepareCamera.ts","../src/core/render-graph/assertColorAttachmentLimits.ts","../src/core/render-graph/PassBuilder.ts","../src/core/render-graph/RenderTargetCache.ts","../src/core/render-graph/RenderGraph.ts","../src/scene/lights/environment/Hemisphere.ts","../src/core/writeHemisphere.ts","../src/core/render-passes/background/backgroundPassUtils.ts","../src/core/render-passes/background/BackgroundPass.ts","../src/core/render-passes/CullResult.ts","../src/core/render-passes/CullResults.ts","../src/core/render-passes/ForwardRenderPass.ts","../src/core/render-passes/blended-refraction/BlendedRefractionPass.ts","../src/core/render-passes/copy-depth/CopyDepthPass.ts","../src/core/render-passes/copy-opaque/CopyOpaquePass.ts","../src/core/render-passes/depth-clear/DepthClearPass.ts","../src/core/render-passes/opaque/OpaqueRenderPass.ts","../src/core/shader/bits/tonemapping/acesToneMappingBit.ts","../src/core/shader/bits/tonemapping/reinhardToneMappingBit.ts","../src/core/shader/bits/tonemapping/srgbEncodeBit.ts","../src/core/shader/bits/tonemapping/uncharted2ToneMappingBit.ts","../src/core/shader/bits/tonemapping/toneMappingBits.ts","../src/core/render-passes/output/ColorOutputDraw.ts","../src/core/render-passes/RenderForwardDescriptor.ts","../src/core/render-passes/shadow/ShadowRenderPassBase.ts","../src/core/render-passes/transmission/TransmissionRenderPass.ts","../src/core/render-passes/transparent/TransparentRenderPass.ts","../src/core/render-passes/transparent/transparentSortUtils.ts","../src/core/shader/bits/alphaOpaqueBit.ts","../src/core/shader/bits/cameraBit.ts","../src/core/shader/bits/colorSpaceBits.ts","../src/core/shader/bits/doubleSidedNormalBit.ts","../src/core/shader/bits/envSourceCubeBit.ts","../src/core/shader/bits/envSourceDefaultBit.ts","../src/core/shader/bits/envSourceHemisphereBit.ts","../src/core/shader/bits/flatShadingBit.ts","../src/core/shader/bits/fog/exp2FogBit.ts","../src/core/shader/bits/fog/exponentialFogBit.ts","../src/core/shader/bits/fog/linearFogBit.ts","../src/core/shader/bits/instanceFetchBitGl.ts","../src/core/shader/bits/materialBindingsBit.ts","../src/core/shader/bits/meshBillboardBits.ts","../src/core/shader/bits/normalBit.ts","../src/core/shader/bits/normalMappingBit.ts","../src/core/shader/bits/noShadowBit.ts","../src/core/shader/bits/positionBit.ts","../src/core/shader/bits/shaderStructs.ts","../src/core/shader/bits/shadowTaps.ts","../src/core/shader/bits/tangentNormalMappingBit.ts","../src/core/shader/bits/uvsBit.ts","../src/core/shader/bits/vertexColorBit.ts","../src/core/shader/codegen/collectAttributes.ts","../src/core/shader/codegen/collectSlotCode.ts","../src/core/shader/codegen/fillTemplateSlots.ts","../src/core/shader/codegen/generateGroupMap.ts","../src/core/shader/codegen/getTemplateSlots.ts","../src/core/shader/codegen/instanceAccess.ts","../src/core/shader/codegen/materialStructPackPlugin.ts","../src/core/shader/codegen/structTexelLayout.ts","../src/core/shader/collectOverrideDefs.ts","../src/core/shader/compileShader.ts","../src/core/shader/resolveShaderBits.ts","../src/core/ShadowDataList.ts","../src/core/textures/ColorCubeTexture.ts","../src/core/textures/ContainerSource.ts","../src/core/textures/ContainerTexture.ts","../src/core/textures/isResolvableFormat.ts","../src/core/validateCamera.ts","../src/core/View3DGCRegistry.ts","../src/math/shapes/Ray.ts","../src/math/vector/Vector2.ts","../src/events/HitResult3D.ts","../src/events/intersectRayGeometry.ts","../src/events/intersectRayHitVolume.ts","../src/events/Pointer3DEvent.ts","../src/events/EventBoundary3D.ts","../src/events/FederatedEventTarget3D.ts","../src/events/View3DEvents.ts","../src/geometry/utils/clampSegments.ts","../src/geometry/CapsuleGeometry.ts","../src/geometry/utils/buildCylinderBuffers.ts","../src/geometry/ConeGeometry.ts","../src/geometry/CubeGeometry.ts","../src/geometry/CylinderGeometry.ts","../src/geometry/GeometryAtlas.ts","../src/geometry/GeometryAtlasPool.ts","../src/geometry/IcosahedronGeometry.ts","../src/geometry/PlaneGeometry.ts","../src/geometry/SphereGeometry.ts","../src/geometry/TorusGeometry.ts","../src/geometry/TorusKnotGeometry.ts","../src/geometry/utils/getAttributeData.ts","../src/materials/phong/bits/phongLightingBit.ts","../src/materials/phong/bits/phongMaterialBit.ts","../src/materials/phong/bits/phongSpecularTextureBit.ts","../src/materials/phong/PhongMaterial.ts","../src/math/matrix/Matrix3.ts","../src/math/shapes/Cylindrical.ts","../src/math/shapes/Spherical.ts","../src/math/utils/seededRandom.ts","../src/math/vector/Vector4.ts","../src/post-processing/effects/fullscreenEffectShader.ts","../src/post-processing/effects/FullscreenPass.ts","../src/post-processing/effects/OutputPass.ts","../src/post-processing/Pass3D.ts","../src/post-processing/effects/PostEffect.ts","../src/post-processing/passes/MeshPass.ts","../src/scene/BatchedMesh3D.ts","../src/scene/cameras/Camera3D.ts","../src/scene/lights/Light.ts","../src/scene/lights/AmbientLight.ts","../src/scene/lights/DirectionalLight.ts","../src/scene/lights/PointLight.ts","../src/scene/lights/SpotLight.ts","../src/scene/Skeleton.ts","../src/scene/Model3D.ts","../src/scene/particles/bits/particleAlphaOverLifeBit.ts","../src/scene/particles/bits/particleBit.ts","../src/scene/particles/bits/particleColorOverLifeBit.ts","../src/scene/particles/bits/particleFlipbookBits.ts","../src/scene/particles/bits/particleLifetimeBit.ts","../src/scene/particles/bits/particleMotionBit.ts","../src/scene/particles/bits/particleSizeOverLifeBit.ts","../src/scene/particles/bits/particleSpinBit.ts","../src/scene/particles/ParticleMaterial.ts","../src/scene/particles/utils/packParticleColor.ts","../src/scene/particles/utils/packParticleFrames.ts","../src/scene/particles/utils/packUnorm.ts","../src/scene/particles/utils/particleGeometry.ts","../src/scene/particles/utils/particleLayout.ts","../src/scene/particles/ParticleContainer3D.ts","../src/scene/Sprite3D.ts","../src/scene/utils/createDefaultGraph3D.ts","../src/scene/utils/frameCamera.ts","../src/scene/utils/updateView3DTransforms.ts","../src/scene/utils/updateView3DScene.ts","../src/utils/StableList.ts","../src/scene/View3D.ts","../src/scene/View3DGlobalData.ts","../src/utils/addUniformParsers.ts","../src/assets/init.ts","../src/events/init.ts","../src/init.ts"],"sourcesContent":["import type { Track } from './tracks/Track';\n\n/**\n * Options for creating an animation\n * @example\n * ```ts\n * const options: AnimationOptions = {\n *   label: 'bob',\n *   tracks: [\n *     new Vector3Track({ label: 'Crate.position', times: [0, 0.5, 1], values: [0, 0, 0, 0, 1, 0, 0, 0, 0] }),\n *   ],\n * };\n * ```\n * @category animation\n * @standard\n */\nexport interface AnimationOptions {\n  /**\n   * Sets {@link Animation#label}\n   * @example\n   * ```ts\n   * player.addAnimations([new Animation({ label: 'wave', tracks })]);\n   * player.play('wave');\n   * ```\n   */\n  label: string;\n  /**\n   * Tracks the animation plays, each driving one property\n   * @example\n   * ```ts\n   * const shake = new Animation({\n   *   label: 'shake',\n   *   tracks: [new NumberTrack({ label: 'Camera.x', times: [0, 0.1, 0.2], values: [0, 0.2, 0] })],\n   * });\n   * ```\n   */\n  tracks?: readonly Track[];\n  /**\n   * Length in seconds; left out, it is the time of the last keyframe across all tracks\n   *\n   * Set it past the last keyframe to hold the final pose before the animation loops.\n   * @example\n   * ```ts\n   * const blink = new Animation({\n   *   label: 'blink',\n   *   tracks: [\n   *     new Vector3Track({ label: 'Eyelid.scale', times: [0, 0.1, 0.2], values: [1, 1, 1, 1, 0.1, 1, 1, 1, 1] }),\n   *   ],\n   *   duration: 4,\n   * });\n   * ```\n   */\n  duration?: number;\n}\n\n/**\n * A named set of keyframe tracks, holding no playback state\n *\n * A {@link Model3D} loaded from glTF comes with its animations already registered on its\n * {@link Model3D#player | player}. Build one yourself to animate in code, then register it on an\n * {@link AnimationPlayer}. One animation can play on many players at once; each player keeps its\n * own {@link AnimationState} for it.\n * @example\n * ```ts\n * const crate = new Container3D({ label: 'Crate' });\n * const bob = new Animation({\n *   label: 'bob',\n *   tracks: [\n *     new Vector3Track({ label: 'Crate.position', times: [0, 0.5, 1], values: [0, 0, 0, 0, 1, 0, 0, 0, 0] }),\n *   ],\n * });\n *\n * const player = new AnimationPlayer({ target: crate, animations: [bob], autoPlay: 'bob' });\n * ```\n * @category animation\n * @standard\n */\nexport class Animation {\n  /**\n   * Label {@link AnimationPlayer#addAnimations} registers this animation under when given an array\n   * @example\n   * ```ts\n   * player.addAnimations([bob]);\n   * player.play(bob.label);\n   * ```\n   */\n  public label: string;\n  /**\n   * Tracks this animation plays\n   * @advanced\n   */\n  public readonly tracks: readonly Track[];\n  /**\n   * Length in seconds\n   * @example\n   * ```ts\n   * const walk = player.getAnimation('walk')!;\n   *\n   * player.getState(walk).gotoAndStop(walk.duration / 2);\n   * ```\n   */\n  public duration = 0;\n\n  /**\n   * @param options - Label, tracks and duration\n   */\n  constructor(options: AnimationOptions) {\n    this.label = options.label;\n    this.tracks = options.tracks || [];\n    this.duration = options.duration ?? this._getDuration();\n  }\n\n  private _getDuration(): number {\n    let maxTime = 0;\n    for (let i = 0; i < this.tracks.length; i++) {\n      const track = this.tracks[i];\n      const trackTime = track.times[track.times.length - 1];\n      if (trackTime > maxTime) {\n        maxTime = trackTime;\n      }\n    }\n\n    return maxTime;\n  }\n}\n","/** @internal */\nexport function clamp(value: number, min: number, max: number): number {\n  return Math.max(min, Math.min(max, value));\n}\n","import type { Matrix3 } from '../matrix/Matrix3';\nimport type { Matrix4 } from '../matrix/Matrix4';\nimport type { Quaternion } from '../rotation/Quaternion';\nimport type { Cylindrical } from '../shapes/Cylindrical';\nimport type { Spherical } from '../shapes/Spherical';\nimport { clamp } from '../utils/clamp';\nimport type { PointData3D } from './PointData3D';\nimport type { PointLike3D } from './PointLike3D';\n\n/**\n * A point or direction in 3D, such as a position, a velocity or an offset\n *\n * Math methods change the vector they're called on and return it, so calls chain. Pass an `out`\n * vector as the last argument to write the result there instead and leave this one as it is. In code\n * that runs every frame, create `out` vectors once and reuse them: a `new Vector3()` per frame is\n * garbage the collector has to clean up.\n *\n * Where a method takes a point, any {@link PointData3D} works, such as a node's `position` or a\n * plain `{ x, y, z }` object.\n * @example\n * ```ts\n * const toPlayer = new Vector3();\n *\n * app.ticker.add((ticker) => {\n *   player.position.subtract(enemy.position, toPlayer).normalize();\n *   enemy.position.addScaledVector(toPlayer, enemy.speed * (ticker.deltaMS / 1000));\n * });\n * ```\n * @category maths\n * @standard\n */\nexport class Vector3 implements PointLike3D {\n  /**\n   * The x component\n   * @example\n   * ```ts\n   * const groundSpeed = Math.hypot(velocity.x, velocity.z);\n   * ```\n   */\n  public x = 0;\n  /**\n   * The y component\n   * @example\n   * ```ts\n   * velocity.y -= gravity * dt;\n   * ```\n   */\n  public y = 0;\n  /**\n   * The z component\n   * @example\n   * ```ts\n   * velocity.z = runSpeed;\n   * ```\n   */\n  public z = 0;\n\n  /**\n   * A static `Vector3` reset to `(0, 0, 0)` on every access, for a result used straight away\n   *\n   * > [!IMPORTANT] This vector is shared and temporary. Do not store references to it.\n   * @example\n   * ```ts\n   * const inRange = enemy.getGlobalPosition(Vector3.shared).distanceTo(player.position) < attackRange;\n   * ```\n   */\n  static get shared(): Vector3 {\n    _shared.x = 0;\n    _shared.y = 0;\n    _shared.z = 0;\n\n    return _shared;\n  }\n\n  /**\n   * Creates a new `Vector3`\n   * @param x - The x component\n   * @param y - The y component\n   * @param z - The z component\n   */\n  constructor(x = 0, y = 0, z = 0) {\n    this.x = x;\n    this.y = y;\n    this.z = z;\n  }\n\n  /**\n   * Sets the x, y and z components\n   * @example\n   * ```ts\n   * velocity.set(0, jumpSpeed, 0);\n   * size.set(1); // (1, 1, 1)\n   * ```\n   * @param x - The x component\n   * @param y - The y component, defaults to `x`\n   * @param z - The z component, defaults to `x`\n   */\n  public set(x = 0, y = x, z = x): this {\n    this.x = x;\n    this.y = y;\n    this.z = z;\n\n    return this;\n  }\n\n  /**\n   * Copies x, y, z from the given point into this vector\n   * @example\n   * ```ts\n   * respawnPoint.copyFrom(player.position);\n   * ```\n   * @param p - The point to copy from\n   */\n  public copyFrom(p: PointData3D): this {\n    this.x = p.x;\n    this.y = p.y;\n    this.z = p.z;\n\n    return this;\n  }\n\n  /**\n   * Copies this vector's x, y, z into the given point\n   * @example\n   * ```ts\n   * respawnPoint.copyTo(player.position);\n   * ```\n   * @param p - The point to copy into\n   * @returns The given point with values updated\n   */\n  public copyTo<T extends PointLike3D>(p: T): T {\n    p.set(this.x, this.y, this.z);\n\n    return p;\n  }\n\n  /**\n   * Checks whether `x`, `y` and `z` all match `p` exactly, with no tolerance\n   * @example\n   * ```ts\n   * if (!aimPoint.equals(lastAimPoint)) recomputeAim();\n   * ```\n   * @param p - The point to compare against\n   */\n  public equals(p: PointData3D): boolean {\n    return p.x === this.x && p.y === this.y && p.z === this.z;\n  }\n\n  /**\n   * Creates a copy of this vector\n   * @example\n   * ```ts\n   * const startVelocity = velocity.clone();\n   * ```\n   */\n  public clone(): Vector3 {\n    return new Vector3(this.x, this.y, this.z);\n  }\n\n  /**\n   * Returns a readable string representation of this vector\n   * @example\n   * ```ts\n   * console.log(velocity.toString());\n   * ```\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Vector3 x=${this.x} y=${this.y} z=${this.z}]`;\n  }\n\n  /**\n   * Reads `x`, `y`, `z` from `array` starting at `offset`\n   * @example\n   * ```ts\n   * vertex.fromArray(positions, vertexIndex * 3);\n   * ```\n   * @param array - The array to read from\n   * @param offset - The index of the first component\n   */\n  public fromArray(array: number[] | Float32Array, offset = 0): this {\n    this.x = array[offset];\n    this.y = array[offset + 1];\n    this.z = array[offset + 2];\n\n    return this;\n  }\n\n  /**\n   * Writes this vector's values into `array` starting at `offset`\n   *\n   * Allocates a new array when one is not supplied.\n   * @example\n   * ```ts\n   * velocity.toArray(velocities, particleIndex * 3);\n   * ```\n   * @param array - The array to write into\n   * @param offset - The index to write the first component at\n   * @returns The array the values were written into\n   */\n  public toArray<T extends number[] | Float32Array = number[]>(array: T = [] as unknown as T, offset = 0): T {\n    array[offset] = this.x;\n    array[offset + 1] = this.y;\n    array[offset + 2] = this.z;\n\n    return array;\n  }\n\n  /**\n   * Adds `v` to this vector\n   * @example\n   * ```ts\n   * waypoint.add({ x: 0, y: 2, z: 0 });\n   * barrelBase.add(muzzleOffset, muzzlePosition);\n   * ```\n   * @param v - The point to add\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public add(v: PointData3D, out: PointLike3D = this): this {\n    out.x = this.x + v.x;\n    out.y = this.y + v.y;\n    out.z = this.z + v.z;\n\n    return out as this;\n  }\n\n  /**\n   * Subtracts `v` from this vector\n   * @example\n   * ```ts\n   * const toTarget = new Vector3();\n   *\n   * targetPosition.subtract(turretPosition, toTarget);\n   * ```\n   * @param v - The point to subtract\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public subtract(v: PointData3D, out: PointLike3D = this): this {\n    out.x = this.x - v.x;\n    out.y = this.y - v.y;\n    out.z = this.z - v.z;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies each component of this vector by the matching component of `v`\n   * @example\n   * ```ts\n   * velocity.multiply({ x: 1, y: 0, z: 1 }, groundVelocity);\n   * ```\n   * @param v - The point to multiply by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public multiply(v: PointData3D, out: PointLike3D = this): this {\n    out.x = this.x * v.x;\n    out.y = this.y * v.y;\n    out.z = this.z * v.z;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies each component of this vector by the scalar `s`\n   * @example\n   * ```ts\n   * velocity.multiplyScalar(friction);\n   * direction.multiplyScalar(speed * dt, step);\n   * ```\n   * @param s - The scalar to multiply by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public multiplyScalar(s: number, out: PointLike3D = this): this {\n    out.x = this.x * s;\n    out.y = this.y * s;\n    out.z = this.z * s;\n\n    return out as this;\n  }\n\n  /**\n   * Divides each component of this vector by the matching component of `v`\n   * @example\n   * ```ts\n   * worldPosition.divide(cellSize, cell);\n   * const column = Math.floor(cell.x);\n   * ```\n   * @param v - The point to divide by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public divide(v: PointData3D, out: PointLike3D = this): this {\n    out.x = this.x / v.x;\n    out.y = this.y / v.y;\n    out.z = this.z / v.z;\n\n    return out as this;\n  }\n\n  /**\n   * Divides each component of this vector by the scalar `s`\n   * @example\n   * ```ts\n   * const center = new Vector3();\n   *\n   * for (const point of points) center.add(point);\n   * center.divideScalar(points.length);\n   * ```\n   * @param s - The scalar to divide by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public divideScalar(s: number, out: PointLike3D = this): this {\n    return this.multiplyScalar(1 / s, out);\n  }\n\n  /**\n   * Adds `v * s` to this vector, such as a velocity times the frame time\n   * @example\n   * ```ts\n   * velocity.addScaledVector(gravity, dt);\n   * rayOrigin.addScaledVector(rayDirection, hitDistance, hitPoint);\n   * ```\n   * @param v - The point to scale and add\n   * @param s - The scalar to multiply `v` by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public addScaledVector(v: PointData3D, s: number, out: PointLike3D = this): this {\n    out.x = this.x + v.x * s;\n    out.y = this.y + v.y * s;\n    out.z = this.z + v.z * s;\n\n    return out as this;\n  }\n\n  /**\n   * Negates each component of this vector, reversing its direction\n   * @example\n   * ```ts\n   * toThreat.negate(fleeDirection);\n   * ```\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public negate(out: PointLike3D = this): this {\n    out.x = -this.x;\n    out.y = -this.y;\n    out.z = -this.z;\n\n    return out as this;\n  }\n\n  /**\n   * Sets each component to the smaller of this vector's and `v`'s\n   * @example\n   * ```ts\n   * const boundsMin = new Vector3(Infinity, Infinity, Infinity);\n   *\n   * for (const point of points) boundsMin.min(point);\n   * ```\n   * @param v - The point to compare with\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public min(v: PointData3D, out: PointLike3D = this): this {\n    out.x = Math.min(this.x, v.x);\n    out.y = Math.min(this.y, v.y);\n    out.z = Math.min(this.z, v.z);\n\n    return out as this;\n  }\n\n  /**\n   * Sets each component to the larger of this vector's and `v`'s\n   * @example\n   * ```ts\n   * const boundsMax = new Vector3(-Infinity, -Infinity, -Infinity);\n   *\n   * for (const point of points) boundsMax.max(point);\n   * ```\n   * @param v - The point to compare with\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public max(v: PointData3D, out: PointLike3D = this): this {\n    out.x = Math.max(this.x, v.x);\n    out.y = Math.max(this.y, v.y);\n    out.z = Math.max(this.z, v.z);\n\n    return out as this;\n  }\n\n  /**\n   * Clamps each component of this vector between the matching components of `min` and `max`\n   *\n   * Assumes `min <= max` componentwise.\n   * @example\n   * ```ts\n   * cameraTarget.clamp(levelMin, levelMax);\n   * ```\n   * @param min - The lower bound per component\n   * @param max - The upper bound per component\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public clamp(min: PointData3D, max: PointData3D, out: PointLike3D = this): this {\n    out.x = clamp(this.x, min.x, max.x);\n    out.y = clamp(this.y, min.y, max.y);\n    out.z = clamp(this.z, min.z, max.z);\n\n    return out as this;\n  }\n\n  /**\n   * Scales this vector to unit length, keeping its direction\n   *\n   * A zero vector stays zero.\n   * @example\n   * ```ts\n   * input.normalize();\n   * toTarget.normalize(aimDirection);\n   * ```\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public normalize(out: PointLike3D = this): this {\n    const len = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z) || 1;\n    const inv = 1 / len;\n    out.x = this.x * inv;\n    out.y = this.y * inv;\n    out.z = this.z * inv;\n\n    return out as this;\n  }\n\n  /**\n   * Scales this vector so its length equals `length`, keeping its direction\n   *\n   * A zero vector stays zero.\n   * @example\n   * ```ts\n   * if (velocity.magnitude() > maxSpeed) velocity.setLength(maxSpeed);\n   * ```\n   * @param length - The target length\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public setLength(length: number, out: PointLike3D = this): this {\n    const len = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z) || 1;\n    const inv = length / len;\n    out.x = this.x * inv;\n    out.y = this.y * inv;\n    out.z = this.z * inv;\n\n    return out as this;\n  }\n\n  /**\n   * Computes the length of this vector\n   * @example\n   * ```ts\n   * const speed = velocity.magnitude();\n   * ```\n   */\n  public magnitude(): number {\n    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);\n  }\n\n  /**\n   * Computes the squared length of this vector\n   *\n   * Cheaper than {@link Vector3#magnitude}, since it skips the square root, and enough to compare\n   * lengths.\n   * @example\n   * ```ts\n   * if (velocity.magnitudeSquared() < 0.0001) velocity.set(0);\n   * ```\n   */\n  public magnitudeSquared(): number {\n    return this.x * this.x + this.y * this.y + this.z * this.z;\n  }\n\n  /**\n   * Computes the distance from this point to `v`\n   * @example\n   * ```ts\n   * const reached = waypoint.distanceTo(player.position) < 0.5;\n   * ```\n   * @param v - The point to measure to\n   */\n  public distanceTo(v: PointData3D): number {\n    return Math.sqrt(this.distanceToSquared(v));\n  }\n\n  /**\n   * Computes the squared distance from this point to `v`\n   *\n   * Cheaper than {@link Vector3#distanceTo} and enough to compare distances.\n   * @example\n   * ```ts\n   * if (bulletPosition.distanceToSquared(target.position) < hitRadius * hitRadius) hit(target);\n   * ```\n   * @param v - The point to measure to\n   */\n  public distanceToSquared(v: PointData3D): number {\n    const dx = this.x - v.x;\n    const dy = this.y - v.y;\n    const dz = this.z - v.z;\n\n    return dx * dx + dy * dy + dz * dz;\n  }\n\n  /**\n   * Computes the dot product of this vector and `v`\n   *\n   * For unit vectors it's the cosine of the angle between them: 1 when they point the same way, 0 at\n   * right angles and -1 when opposite.\n   * @example\n   * ```ts\n   * const targetIsAhead = forward.dot(toTarget) > 0;\n   * ```\n   * @param v - The other vector\n   */\n  public dot(v: PointData3D): number {\n    return this.x * v.x + this.y * v.y + this.z * v.z;\n  }\n\n  /**\n   * Computes the angle between this vector and `v`\n   *\n   * Returns π/2 when either vector has zero length.\n   * @example\n   * ```ts\n   * const canSeePlayer = forward.angleTo(toPlayer) < visionHalfAngle;\n   * ```\n   * @param v - The other vector\n   * @returns The angle in radians, from 0 to π\n   */\n  public angleTo(v: PointData3D): number {\n    const denominator = Math.sqrt(this.magnitudeSquared() * (v.x * v.x + v.y * v.y + v.z * v.z));\n    if (denominator === 0) return Math.PI / 2;\n    const theta = this.dot(v) / denominator;\n\n    return Math.acos(clamp(theta, -1, 1));\n  }\n\n  /**\n   * Computes the cross product `this × v`, a vector at right angles to both\n   * @example\n   * ```ts\n   * edgeA.cross(edgeB, faceNormal).normalize();\n   * ```\n   * @param v - The other vector\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public cross(v: PointData3D, out: PointLike3D = this): this {\n    const ax = this.x;\n    const ay = this.y;\n    const az = this.z;\n    const bx = v.x;\n    const by = v.y;\n    const bz = v.z;\n    out.x = ay * bz - az * by;\n    out.y = az * bx - ax * bz;\n    out.z = ax * by - ay * bx;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies this vector by the 3x3 matrix `m`, such as a normal matrix\n   * @example\n   * ```ts\n   * const normalMatrix = new Matrix3().getNormalMatrix(mesh.worldTransform);\n   *\n   * worldNormal.copyFrom(localNormal).applyMatrix3(normalMatrix).normalize();\n   * ```\n   * @param m - The matrix to apply\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public applyMatrix3(m: Matrix3, out: PointLike3D = this): this {\n    const x = this.x;\n    const y = this.y;\n    const z = this.z;\n    const e = m.elements;\n    out.x = e[0] * x + e[3] * y + e[6] * z;\n    out.y = e[1] * x + e[4] * y + e[7] * z;\n    out.z = e[2] * x + e[5] * y + e[8] * z;\n\n    return out as this;\n  }\n\n  /**\n   * Transforms this point by `m`, translation included, then divides by the resulting `w`\n   *\n   * The divide is what a projection matrix needs: with a camera's\n   * {@link Camera3D#viewProjection | viewProjection}, x and y come out from -1 to 1 across the\n   * visible area, and z from -1 at the near plane to 1 at the far plane. A point behind the camera\n   * can land inside that x and y range too, so check z as well. Use\n   * {@link Vector3#applyAffineMatrix4} for transforms that don't project, and\n   * {@link Vector3#transformDirection} for directions.\n   * @example\n   * ```ts\n   * point.applyMatrix4(camera.viewProjection, ndc);\n   * const onScreen = Math.abs(ndc.x) <= 1 && Math.abs(ndc.y) <= 1 && Math.abs(ndc.z) <= 1;\n   * ```\n   * @param m - The matrix to apply\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public applyMatrix4(m: Matrix4, out: PointLike3D = this): this {\n    const x = this.x;\n    const y = this.y;\n    const z = this.z;\n    const e = m.elements;\n    const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);\n    out.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;\n    out.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;\n    out.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;\n\n    return out as this;\n  }\n\n  /**\n   * Transforms this point by `m`, translation included, without the divide\n   * {@link Vector3#applyMatrix4} does\n   *\n   * Cheaper, and correct for any transform that doesn't project, such as a node's world transform.\n   * @example\n   * ```ts\n   * muzzleOffset.applyAffineMatrix4(gun.worldTransform, muzzleWorldPosition);\n   * ```\n   * @param m - The matrix to apply\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public applyAffineMatrix4(m: Matrix4, out: PointLike3D = this): this {\n    const x = this.x;\n    const y = this.y;\n    const z = this.z;\n    const e = m.elements;\n    out.x = e[0] * x + e[4] * y + e[8] * z + e[12];\n    out.y = e[1] * x + e[5] * y + e[9] * z + e[13];\n    out.z = e[2] * x + e[6] * y + e[10] * z + e[14];\n\n    return out as this;\n  }\n\n  /**\n   * Rotates this vector by the unit {@link Quaternion} `q`\n   * @example\n   * ```ts\n   * forward.set(0, 0, 1).applyQuaternion(ship.quaternion);\n   * ```\n   * @param q - The unit quaternion to rotate by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public applyQuaternion(q: Quaternion, out: PointLike3D = this): this {\n    const x = this.x;\n    const y = this.y;\n    const z = this.z;\n    const qx = q.x;\n    const qy = q.y;\n    const qz = q.z;\n    const qw = q.w;\n\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\n    out.x = ix * qw - iw * qx - iy * qz + iz * qy;\n    out.y = iy * qw - iw * qy - iz * qx + ix * qz;\n    out.z = iz * qw - iw * qz - ix * qy + iy * qx;\n\n    return out as this;\n  }\n\n  /**\n   * Turns this direction by the rotation and scale in `m`, ignoring its translation, then normalizes it\n   * @example\n   * ```ts\n   * const cameraForward = new Vector3(0, 0, -1).transformDirection(camera.worldTransform);\n   * ```\n   * @param m - The matrix whose rotation to apply\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The point the result was written into\n   */\n  public transformDirection(m: Matrix4, out: PointLike3D = this): this {\n    const x = this.x;\n    const y = this.y;\n    const z = this.z;\n    const e = m.elements;\n    const tx = e[0] * x + e[4] * y + e[8] * z;\n    const ty = e[1] * x + e[5] * y + e[9] * z;\n    const tz = e[2] * x + e[6] * y + e[10] * z;\n    const len = Math.sqrt(tx * tx + ty * ty + tz * tz) || 1;\n    const inv = 1 / len;\n    out.x = tx * inv;\n    out.y = ty * inv;\n    out.z = tz * inv;\n\n    return out as this;\n  }\n\n  /**\n   * Sets this point to the position the {@link Spherical} coordinate `s` describes\n   *\n   * `phi` is the angle down from the +Y axis and `theta` the angle around Y, starting at +Z and turning\n   * toward +X.\n   * @example\n   * ```ts\n   * orbit.theta += turnSpeed * dt;\n   * cameraOffset.setFromSpherical(orbit);\n   * ```\n   * @param s - The spherical coordinate to convert\n   */\n  public setFromSpherical(s: Spherical): this {\n    const sinPhiRadius = Math.sin(s.phi) * s.radius;\n\n    this.x = sinPhiRadius * Math.sin(s.theta);\n    this.y = Math.cos(s.phi) * s.radius;\n    this.z = sinPhiRadius * Math.cos(s.theta);\n\n    return this;\n  }\n\n  /**\n   * Sets this point to the position the {@link Cylindrical} coordinate `c` describes\n   *\n   * `theta` is the angle around Y, starting at +Z and turning toward +X, and `y` is the height above the\n   * XZ plane.\n   * @example\n   * ```ts\n   * const slot = new Cylindrical(towerRadius, 0, 2);\n   *\n   * for (let i = 0; i < torchCount; i++) {\n   *   slot.theta = (i / torchCount) * Math.PI * 2;\n   *   torchPositions[i].setFromCylindrical(slot);\n   * }\n   * ```\n   * @param c - The cylindrical coordinate to convert\n   */\n  public setFromCylindrical(c: Cylindrical): this {\n    this.x = c.radius * Math.sin(c.theta);\n    this.y = c.y;\n    this.z = c.radius * Math.cos(c.theta);\n\n    return this;\n  }\n\n  /**\n   * Reads the first three values of column `index` of `m` into this vector\n   *\n   * In a transform, column 3 is the translation and columns 0 to 2 are the X, Y and Z axes, scaled.\n   * @example\n   * ```ts\n   * const worldPosition = new Vector3().setFromMatrixColumn(node.worldTransform, 3);\n   * ```\n   * @param m - The matrix to read from\n   * @param index - The column index, `0` to `3`\n   */\n  public setFromMatrixColumn(m: Matrix4, index: number): this {\n    return this.fromArray(m.elements, index * 4);\n  }\n}\n\nconst _shared = new Vector3();\n","import { warn } from 'pixi.js';\n\nimport type { Quaternion } from '../rotation/Quaternion';\nimport type { TypedFixedArray } from '../utils/misc';\nimport type { PointData3D } from '../vector/PointData3D';\nimport type { PointLike3D } from '../vector/PointLike3D';\nimport { Vector3 } from '../vector/Vector3';\n\n/**\n * A 4x4 matrix for 3D transforms and projections\n *\n * {@link Matrix4#elements} holds the sixteen values column by column, the order shaders use, and a\n * `Matrix4` can be the value of a `mat4x4<f32>` uniform as it is. Points are columns, so in `a * b`\n * the matrix `b` applies to a point first: `projection * view * world` takes a point on a model\n * to clip space.\n *\n * Methods that change the matrix do so in place, or write into an `out` matrix when you pass one\n * and leave this matrix as it is.\n * @example\n * ```ts\n * const cameraWorld = new Matrix4().lookAt(eye, target, { x: 0, y: 1, z: 0 }).setPosition(eye);\n * const view = new Matrix4().getInverse(cameraWorld);\n * const projection = new Matrix4().makePerspective(Math.PI / 3, width / height, 0.1, 500);\n * const viewProjection = new Matrix4().multiplyMatrices(projection, view);\n * ```\n * @see {@link Vector3#applyMatrix4} For applying this matrix to a point\n * @category maths\n * @standard\n */\nexport class Matrix4 {\n  /**\n   * The sixteen values, column by column: the translation sits at indices 12, 13 and 14\n   * @example\n   * ```ts\n   * const worldHeight = mesh.worldTransform.elements[13];\n   * ```\n   */\n  public elements: TypedFixedArray<16>;\n\n  /**\n   * A `Float64Array` over the same memory as {@link Matrix4#elements}, for copying the matrix as\n   * eight 64-bit moves instead of sixteen 32-bit ones\n   *\n   * > [!IMPORTANT] Each entry is two of the matrix's floats read as one 64-bit number, which means\n   * > nothing on its own. Use it only to copy into another `Float64Array` view of float data.\n   * @example\n   * ```ts\n   * const instanceData = new Float32Array(instanceCount * 16);\n   * const instanceData64 = new Float64Array(instanceData.buffer);\n   *\n   * instanceData64.set(mesh.worldTransform.elements64, index * 8);\n   * ```\n   * @advanced\n   */\n  public elements64: Float64Array;\n\n  /**\n   * The array {@link Matrix4#toArray} writes into when given no `out`; `null` until its first call\n   * @example\n   * ```ts\n   * worldMatrix.toArray(true);\n   * const rowMajor = worldMatrix.array!;\n   * ```\n   * @default null\n   * @advanced\n   */\n  public array: Float32Array | null = null;\n\n  /**\n   * Multiplies two affine matrices, `out = a * b`, and writes the result as three rows of four\n   *\n   * The rows land as `[m00 m01 m02 m03][m10 m11 m12 m13][m20 m21 m22 m23]`, translation last in\n   * each, so a shader can read them as three `vec4`s and transform a point with three dot products.\n   * The bottom rows of `a` and `b` are never read.\n   * @example\n   * ```ts\n   * const boneRows = new Float32Array(boneCount * 12);\n   *\n   * for (let i = 0; i < boneCount; i++) {\n   *   Matrix4.multiplyAffineTo3x4(boneRows, i * 12, boneWorlds, i * 16, inverseBinds, i * 16);\n   * }\n   * ```\n   * @param out - Destination, 12 floats per entry.\n   * @param outOffset - Float offset of the destination entry.\n   * @param a - Left operand, 16 floats per entry (column-major).\n   * @param aOffset - Float offset of the left entry.\n   * @param b - Right operand, 16 floats per entry (column-major).\n   * @param bOffset - Float offset of the right entry.\n   * @advanced\n   */\n  public static multiplyAffineTo3x4(\n    out: Float32Array,\n    outOffset: number,\n    a: Float32Array,\n    aOffset: number,\n    b: Float32Array,\n    bOffset: number,\n  ): void {\n    const a00 = a[aOffset + 0];\n    const a01 = a[aOffset + 1];\n    const a02 = a[aOffset + 2];\n    const a10 = a[aOffset + 4];\n    const a11 = a[aOffset + 5];\n    const a12 = a[aOffset + 6];\n    const a20 = a[aOffset + 8];\n    const a21 = a[aOffset + 9];\n    const a22 = a[aOffset + 10];\n    const a30 = a[aOffset + 12];\n    const a31 = a[aOffset + 13];\n    const a32 = a[aOffset + 14];\n\n    const b00 = b[bOffset + 0];\n    const b01 = b[bOffset + 1];\n    const b02 = b[bOffset + 2];\n    const b10 = b[bOffset + 4];\n    const b11 = b[bOffset + 5];\n    const b12 = b[bOffset + 6];\n    const b20 = b[bOffset + 8];\n    const b21 = b[bOffset + 9];\n    const b22 = b[bOffset + 10];\n    const b30 = b[bOffset + 12];\n    const b31 = b[bOffset + 13];\n    const b32 = b[bOffset + 14];\n\n    out[outOffset + 0] = a00 * b00 + a10 * b01 + a20 * b02;\n    out[outOffset + 1] = a00 * b10 + a10 * b11 + a20 * b12;\n    out[outOffset + 2] = a00 * b20 + a10 * b21 + a20 * b22;\n    out[outOffset + 3] = a00 * b30 + a10 * b31 + a20 * b32 + a30;\n\n    out[outOffset + 4] = a01 * b00 + a11 * b01 + a21 * b02;\n    out[outOffset + 5] = a01 * b10 + a11 * b11 + a21 * b12;\n    out[outOffset + 6] = a01 * b20 + a11 * b21 + a21 * b22;\n    out[outOffset + 7] = a01 * b30 + a11 * b31 + a21 * b32 + a31;\n\n    out[outOffset + 8] = a02 * b00 + a12 * b01 + a22 * b02;\n    out[outOffset + 9] = a02 * b10 + a12 * b11 + a22 * b12;\n    out[outOffset + 10] = a02 * b20 + a12 * b21 + a22 * b22;\n    out[outOffset + 11] = a02 * b30 + a12 * b31 + a22 * b32 + a32;\n  }\n\n  /**\n   * Multiplies two affine matrices held in flat arrays, `out = a * b`, skipping the bottom row\n   *\n   * Reads only the top three rows of `a` and `b` and writes `0, 0, 0, 1` as the bottom row, so it\n   * does 36 multiplies where a full 4x4 product does 64. `out` may be the same array as `a` or `b`.\n   * @example\n   * ```ts\n   * for (let i = 0; i < nodeCount; i++) {\n   *   Matrix4.multiplyAffine(worlds, i * 16, worlds, parentIndices[i] * 16, locals, i * 16);\n   * }\n   * ```\n   * @param out - Buffer receiving the product\n   * @param outOffset - Index of the product's first element in `out`\n   * @param a - Buffer holding the left operand\n   * @param aOffset - Index of the left operand's first element in `a`\n   * @param b - Buffer holding the right operand\n   * @param bOffset - Index of the right operand's first element in `b`\n   * @advanced\n   */\n  public static multiplyAffine(\n    out: Float32Array,\n    outOffset: number,\n    a: Float32Array,\n    aOffset: number,\n    b: Float32Array,\n    bOffset: number,\n  ): void {\n    const a00 = a[aOffset + 0];\n    const a01 = a[aOffset + 1];\n    const a02 = a[aOffset + 2];\n    const a10 = a[aOffset + 4];\n    const a11 = a[aOffset + 5];\n    const a12 = a[aOffset + 6];\n    const a20 = a[aOffset + 8];\n    const a21 = a[aOffset + 9];\n    const a22 = a[aOffset + 10];\n    const a30 = a[aOffset + 12];\n    const a31 = a[aOffset + 13];\n    const a32 = a[aOffset + 14];\n\n    const b00 = b[bOffset + 0];\n    const b01 = b[bOffset + 1];\n    const b02 = b[bOffset + 2];\n    const b10 = b[bOffset + 4];\n    const b11 = b[bOffset + 5];\n    const b12 = b[bOffset + 6];\n    const b20 = b[bOffset + 8];\n    const b21 = b[bOffset + 9];\n    const b22 = b[bOffset + 10];\n    const b30 = b[bOffset + 12];\n    const b31 = b[bOffset + 13];\n    const b32 = b[bOffset + 14];\n\n    out[outOffset + 0] = a00 * b00 + a10 * b01 + a20 * b02;\n    out[outOffset + 1] = a01 * b00 + a11 * b01 + a21 * b02;\n    out[outOffset + 2] = a02 * b00 + a12 * b01 + a22 * b02;\n    out[outOffset + 3] = 0;\n\n    out[outOffset + 4] = a00 * b10 + a10 * b11 + a20 * b12;\n    out[outOffset + 5] = a01 * b10 + a11 * b11 + a21 * b12;\n    out[outOffset + 6] = a02 * b10 + a12 * b11 + a22 * b12;\n    out[outOffset + 7] = 0;\n\n    out[outOffset + 8] = a00 * b20 + a10 * b21 + a20 * b22;\n    out[outOffset + 9] = a01 * b20 + a11 * b21 + a21 * b22;\n    out[outOffset + 10] = a02 * b20 + a12 * b21 + a22 * b22;\n    out[outOffset + 11] = 0;\n\n    out[outOffset + 12] = a00 * b30 + a10 * b31 + a20 * b32 + a30;\n    out[outOffset + 13] = a01 * b30 + a11 * b31 + a21 * b32 + a31;\n    out[outOffset + 14] = a02 * b30 + a12 * b31 + a22 * b32 + a32;\n    out[outOffset + 15] = 1;\n  }\n\n  /**\n   * A shared `Matrix4`, reset to identity on every access, for a one-off calculation\n   *\n   * > [!IMPORTANT] This matrix is shared and temporary. Do not store references to it.\n   * @example\n   * ```ts\n   * localHit.copyFrom(worldHit).applyMatrix4(Matrix4.shared.getInverse(mesh.worldTransform));\n   * ```\n   */\n  static get shared(): Matrix4 {\n    return _sharedMatrix.identity();\n  }\n\n  /**\n   * A read-only identity matrix\n   *\n   * > [!IMPORTANT] This is a shared instance; do not mutate it. Use {@link Matrix4.shared} when you\n   * > need a writable temporary.\n   * @example\n   * ```ts\n   * const atRest = bone.localTransform.equals(Matrix4.IDENTITY);\n   * ```\n   */\n  static get IDENTITY(): Readonly<Matrix4> {\n    return _identityMatrix.identity();\n  }\n\n  /**\n   * Creates a new `Matrix4`, defaulting to the identity matrix\n   * @param elements - Optional column-major `Float32Array` of 16 floats, used as is rather than\n   *   copied. Its byte offset must be a multiple of 8, or this throws, since\n   *   {@link Matrix4#elements64} views the same memory.\n   */\n  constructor(elements?: TypedFixedArray<16>) {\n    this.elements =\n      elements || (new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) as TypedFixedArray<16>);\n\n    const f32 = this.elements;\n    this.elements64 = new Float64Array(f32.buffer, f32.byteOffset, 8);\n  }\n\n  /**\n   * Sets the 16 elements from arguments given row by row, as the matrix is written on paper\n   * @example\n   * ```ts\n   * const shearX = new Matrix4().set(\n   *   1, 0.5, 0, 0,\n   *   0, 1, 0, 0,\n   *   0, 0, 1, 0,\n   *   0, 0, 0, 1,\n   * );\n   * ```\n   * @param n11 - Row 1, column 1\n   * @param n12 - Row 1, column 2\n   * @param n13 - Row 1, column 3\n   * @param n14 - Row 1, column 4\n   * @param n21 - Row 2, column 1\n   * @param n22 - Row 2, column 2\n   * @param n23 - Row 2, column 3\n   * @param n24 - Row 2, column 4\n   * @param n31 - Row 3, column 1\n   * @param n32 - Row 3, column 2\n   * @param n33 - Row 3, column 3\n   * @param n34 - Row 3, column 4\n   * @param n41 - Row 4, column 1\n   * @param n42 - Row 4, column 2\n   * @param n43 - Row 4, column 3\n   * @param n44 - Row 4, column 4\n   * @returns This matrix\n   */\n  public set(\n    n11: number,\n    n12: number,\n    n13: number,\n    n14: number,\n    n21: number,\n    n22: number,\n    n23: number,\n    n24: number,\n    n31: number,\n    n32: number,\n    n33: number,\n    n34: number,\n    n41: number,\n    n42: number,\n    n43: number,\n    n44: number,\n  ): this {\n    const te = this.elements;\n\n    te[0] = n11;\n    te[1] = n21;\n    te[2] = n31;\n    te[3] = n41;\n    te[4] = n12;\n    te[5] = n22;\n    te[6] = n32;\n    te[7] = n42;\n    te[8] = n13;\n    te[9] = n23;\n    te[10] = n33;\n    te[11] = n43;\n    te[12] = n14;\n    te[13] = n24;\n    te[14] = n34;\n    te[15] = n44;\n\n    return this;\n  }\n\n  /**\n   * Resets this matrix to the identity matrix\n   * @example\n   * ```ts\n   * transform.identity().setPosition(spawnPoint);\n   * ```\n   * @returns This matrix\n   */\n  public identity(): this {\n    return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);\n  }\n\n  /**\n   * Checks whether this matrix equals the identity matrix exactly\n   * @example\n   * ```ts\n   * const untouched = node.localTransform.isIdentity();\n   * ```\n   * @returns True when every element matches the identity matrix\n   */\n  public isIdentity(): boolean {\n    const e = this.elements;\n\n    return (\n      e[0] === 1 &&\n      e[1] === 0 &&\n      e[2] === 0 &&\n      e[3] === 0 &&\n      e[4] === 0 &&\n      e[5] === 1 &&\n      e[6] === 0 &&\n      e[7] === 0 &&\n      e[8] === 0 &&\n      e[9] === 0 &&\n      e[10] === 1 &&\n      e[11] === 0 &&\n      e[12] === 0 &&\n      e[13] === 0 &&\n      e[14] === 0 &&\n      e[15] === 1\n    );\n  }\n\n  /**\n   * Copies the elements of `m` into this matrix\n   * @example\n   * ```ts\n   * previousWorld.copyFrom(mesh.worldTransform);\n   * ```\n   * @param m - Matrix to copy from\n   * @returns This matrix\n   */\n  public copyFrom(m: Matrix4): this {\n    const te = this.elements;\n    const me = m.elements;\n\n    te[0] = me[0];\n    te[1] = me[1];\n    te[2] = me[2];\n    te[3] = me[3];\n    te[4] = me[4];\n    te[5] = me[5];\n    te[6] = me[6];\n    te[7] = me[7];\n    te[8] = me[8];\n    te[9] = me[9];\n    te[10] = me[10];\n    te[11] = me[11];\n    te[12] = me[12];\n    te[13] = me[13];\n    te[14] = me[14];\n    te[15] = me[15];\n\n    return this;\n  }\n\n  /**\n   * Copies this matrix's elements into `target`\n   * @example\n   * ```ts\n   * mesh.worldTransform.copyTo(previousWorld);\n   * ```\n   * @param target - Matrix to copy into\n   * @returns The given target matrix\n   */\n  public copyTo<T extends Matrix4>(target: T): T {\n    const te = target.elements;\n    const me = this.elements;\n\n    te[0] = me[0];\n    te[1] = me[1];\n    te[2] = me[2];\n    te[3] = me[3];\n    te[4] = me[4];\n    te[5] = me[5];\n    te[6] = me[6];\n    te[7] = me[7];\n    te[8] = me[8];\n    te[9] = me[9];\n    te[10] = me[10];\n    te[11] = me[11];\n    te[12] = me[12];\n    te[13] = me[13];\n    te[14] = me[14];\n    te[15] = me[15];\n\n    return target;\n  }\n\n  /**\n   * Checks whether all 16 elements of this matrix match `m` exactly, with no tolerance\n   * @example\n   * ```ts\n   * const moved = !mesh.worldTransform.equals(previousWorld);\n   * ```\n   * @param m - Matrix to compare against\n   * @returns True when every element matches\n   */\n  public equals(m: Matrix4): boolean {\n    const te = this.elements;\n    const me = m.elements;\n\n    return (\n      te[0] === me[0] &&\n      te[1] === me[1] &&\n      te[2] === me[2] &&\n      te[3] === me[3] &&\n      te[4] === me[4] &&\n      te[5] === me[5] &&\n      te[6] === me[6] &&\n      te[7] === me[7] &&\n      te[8] === me[8] &&\n      te[9] === me[9] &&\n      te[10] === me[10] &&\n      te[11] === me[11] &&\n      te[12] === me[12] &&\n      te[13] === me[13] &&\n      te[14] === me[14] &&\n      te[15] === me[15]\n    );\n  }\n\n  /**\n   * Creates a new `Matrix4` with the same elements\n   * @example\n   * ```ts\n   * const restPose = bone.localTransform.clone();\n   * ```\n   * @returns The new matrix\n   */\n  public clone(): Matrix4 {\n    return new Matrix4().copyFrom(this);\n  }\n\n  /**\n   * Formats this matrix as a readable row-by-row string\n   * @returns The string representation\n   * @advanced\n   */\n  public toString(): string {\n    const e = this.elements;\n\n    return `[@pixi/3d/math:Matrix4 [${e[0]}, ${e[4]}, ${e[8]}, ${e[12]} | ${e[1]}, ${e[5]}, ${e[9]}, ${e[13]} | ${e[2]}, ${e[6]}, ${e[10]}, ${e[14]} | ${e[3]}, ${e[7]}, ${e[11]}, ${e[15]}]]`;\n  }\n\n  /**\n   * Reads the 16 elements from `array` (column-major) starting at `offset`\n   * @example\n   * ```ts\n   * const instanceMatrix = new Matrix4().fromArray(instanceData, index * 16);\n   * ```\n   * @param array - Source array of column-major elements\n   * @param offset - Index of the first element to read\n   * @returns This matrix\n   */\n  public fromArray(array: ArrayLike<number>, offset = 0): this {\n    const e = this.elements;\n\n    e[0] = array[offset];\n    e[1] = array[offset + 1];\n    e[2] = array[offset + 2];\n    e[3] = array[offset + 3];\n    e[4] = array[offset + 4];\n    e[5] = array[offset + 5];\n    e[6] = array[offset + 6];\n    e[7] = array[offset + 7];\n    e[8] = array[offset + 8];\n    e[9] = array[offset + 9];\n    e[10] = array[offset + 10];\n    e[11] = array[offset + 11];\n    e[12] = array[offset + 12];\n    e[13] = array[offset + 13];\n    e[14] = array[offset + 14];\n    e[15] = array[offset + 15];\n\n    return this;\n  }\n\n  /**\n   * Writes this matrix's elements into a Float32Array\n   *\n   * Without `out`, writes into and returns {@link Matrix4#array}.\n   * @example\n   * ```ts\n   * const rowMajor = new Float32Array(16);\n   *\n   * mesh.worldTransform.toArray(true, rowMajor);\n   * ```\n   * @param transpose - `true` writes row-major instead of column-major\n   * @param out - Optional destination array\n   * @returns The populated array\n   */\n  public toArray(transpose?: boolean, out?: Float32Array): Float32Array {\n    if (!this.array) this.array = new Float32Array(16);\n    const arr = out || this.array;\n    const e = this.elements;\n\n    if (transpose) {\n      arr[0] = e[0];\n      arr[1] = e[4];\n      arr[2] = e[8];\n      arr[3] = e[12];\n      arr[4] = e[1];\n      arr[5] = e[5];\n      arr[6] = e[9];\n      arr[7] = e[13];\n      arr[8] = e[2];\n      arr[9] = e[6];\n      arr[10] = e[10];\n      arr[11] = e[14];\n      arr[12] = e[3];\n      arr[13] = e[7];\n      arr[14] = e[11];\n      arr[15] = e[15];\n    } else {\n      arr[0] = e[0];\n      arr[1] = e[1];\n      arr[2] = e[2];\n      arr[3] = e[3];\n      arr[4] = e[4];\n      arr[5] = e[5];\n      arr[6] = e[6];\n      arr[7] = e[7];\n      arr[8] = e[8];\n      arr[9] = e[9];\n      arr[10] = e[10];\n      arr[11] = e[11];\n      arr[12] = e[12];\n      arr[13] = e[13];\n      arr[14] = e[14];\n      arr[15] = e[15];\n    }\n\n    return arr;\n  }\n\n  /**\n   * Multiplies this matrix by `m`: `this = this * m`, so `m` applies to a point first\n   * @example\n   * ```ts\n   * const muzzleWorld = new Matrix4();\n   *\n   * gun.worldTransform.multiply(muzzleOffset, muzzleWorld);\n   * ```\n   * @param m - Matrix to multiply by\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public multiply(m: Matrix4, out: Matrix4 = this): this {\n    _multiplyMatrices(this, m, out);\n\n    return out as this;\n  }\n\n  /**\n   * Pre-multiplies this matrix by `m`: `this = m * this`, so `m` applies to a point last\n   * @example\n   * ```ts\n   * const spin = new Matrix4().makeRotationY(0.01);\n   *\n   * app.ticker.add(() => orbit.premultiply(spin));\n   * ```\n   * @param m - Matrix to pre-multiply by\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public premultiply(m: Matrix4, out: Matrix4 = this): this {\n    _multiplyMatrices(m, this, out);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this matrix to `a * b`, so `b` applies to a point first\n   * @example\n   * ```ts\n   * const toClip = new Matrix4().multiplyMatrices(camera.viewProjection, mesh.worldTransform);\n   * ```\n   * @param a - Left operand\n   * @param b - Right operand\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public multiplyMatrices(a: Matrix4, b: Matrix4, out: Matrix4 = this): this {\n    _multiplyMatrices(a, b, out);\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies every element of this matrix by the scalar `s`\n   * @param s - Scalar to multiply by\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   * @advanced\n   */\n  public multiplyScalar(s: number, out: Matrix4 = this): this {\n    const te = out.elements;\n    const se = this.elements;\n\n    te[0] = se[0] * s;\n    te[4] = se[4] * s;\n    te[8] = se[8] * s;\n    te[12] = se[12] * s;\n    te[1] = se[1] * s;\n    te[5] = se[5] * s;\n    te[9] = se[9] * s;\n    te[13] = se[13] * s;\n    te[2] = se[2] * s;\n    te[6] = se[6] * s;\n    te[10] = se[10] * s;\n    te[14] = se[14] * s;\n    te[3] = se[3] * s;\n    te[7] = se[7] * s;\n    te[11] = se[11] * s;\n    te[15] = se[15] * s;\n\n    return out as this;\n  }\n\n  /**\n   * Pixi-style alias for {@link Matrix4#multiply}: `this = this * m`\n   * @example\n   * ```ts\n   * gun.worldTransform.append(muzzleOffset, muzzleWorld);\n   * ```\n   * @param m - Matrix to append\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public append(m: Matrix4, out: Matrix4 = this): this {\n    return this.multiply(m, out);\n  }\n\n  /**\n   * Pixi-style alias for {@link Matrix4#premultiply}: `this = m * this`\n   * @example\n   * ```ts\n   * orbit.prepend(spin);\n   * ```\n   * @param m - Matrix to prepend\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public prepend(m: Matrix4, out: Matrix4 = this): this {\n    return this.premultiply(m, out);\n  }\n\n  /**\n   * Alias for {@link Matrix4#multiplyMatrices}: this matrix becomes `a * b`\n   * @example\n   * ```ts\n   * viewProjection.appendFrom(camera.projection, camera.view);\n   * ```\n   * @param a - Left operand\n   * @param b - Right operand\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public appendFrom(a: Matrix4, b: Matrix4, out: Matrix4 = this): this {\n    return this.multiplyMatrices(a, b, out);\n  }\n\n  /**\n   * Computes the determinant of this matrix\n   *\n   * Negative when the transform mirrors, as a negative scale does, and 0 when it flattens a\n   * dimension and can't be inverted.\n   * @example\n   * ```ts\n   * const mirrored = mesh.worldTransform.determinant() < 0;\n   * ```\n   * @returns The determinant\n   */\n  public determinant(): number {\n    const te = this.elements;\n\n    const n11 = te[0];\n    const n12 = te[4];\n    const n13 = te[8];\n    const n14 = te[12];\n    const n21 = te[1];\n    const n22 = te[5];\n    const n23 = te[9];\n    const n24 = te[13];\n    const n31 = te[2];\n    const n32 = te[6];\n    const n33 = te[10];\n    const n34 = te[14];\n    const n41 = te[3];\n    const n42 = te[7];\n    const n43 = te[11];\n    const n44 = te[15];\n\n    return (\n      n41 *\n        (n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) +\n      n42 *\n        (n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) +\n      n43 *\n        (n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) +\n      n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31)\n    );\n  }\n\n  /**\n   * Transposes this matrix\n   * @example\n   * ```ts\n   * const normalMatrix = new Matrix4().getInverse(mesh.worldTransform).transpose();\n   * ```\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public transpose(out: Matrix4 = this): this {\n    const me = this.elements;\n    const te = out.elements;\n\n    const m0 = me[0];\n    const m1 = me[1];\n    const m2 = me[2];\n    const m3 = me[3];\n    const m4 = me[4];\n    const m5 = me[5];\n    const m6 = me[6];\n    const m7 = me[7];\n    const m8 = me[8];\n    const m9 = me[9];\n    const m10 = me[10];\n    const m11 = me[11];\n    const m12 = me[12];\n    const m13 = me[13];\n    const m14 = me[14];\n    const m15 = me[15];\n\n    te[0] = m0;\n    te[1] = m4;\n    te[4] = m1;\n    te[2] = m8;\n    te[8] = m2;\n    te[5] = m5;\n    te[6] = m9;\n    te[9] = m6;\n    te[10] = m10;\n    te[3] = m12;\n    te[12] = m3;\n    te[7] = m13;\n    te[13] = m7;\n    te[11] = m14;\n    te[14] = m11;\n    te[15] = m15;\n\n    return out as this;\n  }\n\n  /**\n   * Sets this matrix to the inverse of `m`\n   *\n   * When `m` can't be inverted (its determinant is 0), the result is the identity and a warning is\n   * logged.\n   * @example\n   * ```ts\n   * const worldToLocal = new Matrix4().getInverse(mesh.worldTransform);\n   * ```\n   * @param m - Matrix to invert\n   * @param throwOnDegenerate - `true` throws instead of warning when `m` can't be inverted\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public getInverse(m: Matrix4, throwOnDegenerate?: boolean, out: Matrix4 = this): this {\n    const te = out.elements;\n    const me = m.elements;\n\n    const n11 = me[0];\n    const n21 = me[1];\n    const n31 = me[2];\n    const n41 = me[3];\n    const n12 = me[4];\n    const n22 = me[5];\n    const n32 = me[6];\n    const n42 = me[7];\n    const n13 = me[8];\n    const n23 = me[9];\n    const n33 = me[10];\n    const n43 = me[11];\n    const n14 = me[12];\n    const n24 = me[13];\n    const n34 = me[14];\n    const n44 = me[15];\n\n    const t11 =\n      n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;\n    const t12 =\n      n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;\n    const t13 =\n      n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;\n    const t14 =\n      n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;\n\n    const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;\n\n    if (det === 0) {\n      const msg = \"Matrix4: .getInverse() can't invert matrix, determinant is 0\";\n\n      if (throwOnDegenerate === true) {\n        throw new Error(msg);\n      } else {\n        warn(msg);\n      }\n\n      out.identity();\n      return out as this;\n    }\n\n    const detInv = 1 / det;\n\n    te[0] = t11 * detInv;\n    te[1] =\n      (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) *\n      detInv;\n    te[2] =\n      (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) *\n      detInv;\n    te[3] =\n      (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) *\n      detInv;\n\n    te[4] = t12 * detInv;\n    te[5] =\n      (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) *\n      detInv;\n    te[6] =\n      (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) *\n      detInv;\n    te[7] =\n      (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) *\n      detInv;\n\n    te[8] = t13 * detInv;\n    te[9] =\n      (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) *\n      detInv;\n    te[10] =\n      (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) *\n      detInv;\n    te[11] =\n      (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) *\n      detInv;\n\n    te[12] = t14 * detInv;\n    te[13] =\n      (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) *\n      detInv;\n    te[14] =\n      (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) *\n      detInv;\n    te[15] =\n      (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) *\n      detInv;\n\n    return out as this;\n  }\n\n  /**\n   * Composes this matrix from a translation, rotation and scale\n   *\n   * A point is scaled first, then rotated, then moved: the order a {@link Container3D} builds its\n   * {@link Container3D#localTransform} in.\n   * @example\n   * ```ts\n   * const instance = new Matrix4();\n   * const unitScale = { x: 1, y: 1, z: 1 };\n   *\n   * for (let i = 0; i < treeCount; i++) {\n   *   instance.compose(treePositions[i], treeRotations[i], unitScale);\n   *   instanceData.set(instance.elements, i * 16);\n   * }\n   * ```\n   * @param position - Translation component\n   * @param quaternion - Rotation component\n   * @param scale - Scale component\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public compose(position: PointData3D, quaternion: Quaternion, scale: PointData3D, out: Matrix4 = this): this {\n    const te = out.elements;\n\n    const x = quaternion.x;\n    const y = quaternion.y;\n    const z = quaternion.z;\n    const w = quaternion.w;\n\n    const x2 = x + x;\n    const y2 = y + y;\n    const z2 = z + z;\n    const xx = x * x2;\n    const xy = x * y2;\n    const xz = x * z2;\n    const yy = y * y2;\n    const yz = y * z2;\n    const zz = z * z2;\n    const wx = w * x2;\n    const wy = w * y2;\n    const wz = w * z2;\n\n    const sx = scale.x;\n    const sy = scale.y;\n    const sz = scale.z;\n\n    te[0] = (1 - (yy + zz)) * sx;\n    te[1] = (xy + wz) * sx;\n    te[2] = (xz - wy) * sx;\n    te[3] = 0;\n\n    te[4] = (xy - wz) * sy;\n    te[5] = (1 - (xx + zz)) * sy;\n    te[6] = (yz + wx) * sy;\n    te[7] = 0;\n\n    te[8] = (xz + wy) * sz;\n    te[9] = (yz - wx) * sz;\n    te[10] = (1 - (xx + yy)) * sz;\n    te[11] = 0;\n\n    te[12] = position.x;\n    te[13] = position.y;\n    te[14] = position.z;\n    te[15] = 1;\n\n    return out as this;\n  }\n\n  /**\n   * Splits this matrix into a translation, rotation and scale\n   *\n   * A mirroring matrix (negative determinant) comes back with a negative X scale, so the rotation\n   * stays a rotation. A sheared matrix has no exact split; the result only approximates it.\n   * @example\n   * ```ts\n   * const position = new Vector3();\n   * const rotation = new Quaternion();\n   * const scale = new Vector3();\n   *\n   * mesh.worldTransform.decompose(position, rotation, scale);\n   * ```\n   * @param position - Receives the translation component\n   * @param quaternion - Receives the rotation component\n   * @param scale - Receives the scale component\n   * @param out - Matrix that receives a copy of this one first; decomposing changes no matrix\n   * @returns `out`, which is this matrix when omitted\n   */\n  public decompose(position: Vector3, quaternion: Quaternion, scale: Vector3, out: Matrix4 = this): this {\n    if (out !== this) out.copyFrom(this);\n    const te = out.elements;\n\n    const m11 = te[0];\n    const m21 = te[1];\n    const m31 = te[2];\n    const m12 = te[4];\n    const m22 = te[5];\n    const m32 = te[6];\n    const m13 = te[8];\n    const m23 = te[9];\n    const m33 = te[10];\n\n    let sx = Math.sqrt(m11 * m11 + m21 * m21 + m31 * m31);\n    const sy = Math.sqrt(m12 * m12 + m22 * m22 + m32 * m32);\n    const sz = Math.sqrt(m13 * m13 + m23 * m23 + m33 * m33);\n\n    const det3 = m11 * (m22 * m33 - m32 * m23) - m12 * (m21 * m33 - m31 * m23) + m13 * (m21 * m32 - m31 * m22);\n    if (det3 < 0) sx = -sx;\n\n    position.x = te[12];\n    position.y = te[13];\n    position.z = te[14];\n\n    const invSX = 1 / sx;\n    const invSY = 1 / sy;\n    const invSZ = 1 / sz;\n\n    const me = matrix.elements;\n    me[0] = m11 * invSX;\n    me[1] = m21 * invSX;\n    me[2] = m31 * invSX;\n    me[4] = m12 * invSY;\n    me[5] = m22 * invSY;\n    me[6] = m32 * invSY;\n    me[8] = m13 * invSZ;\n    me[9] = m23 * invSZ;\n    me[10] = m33 * invSZ;\n\n    quaternion.setFromRotationMatrix(matrix);\n\n    scale.x = sx;\n    scale.y = sy;\n    scale.z = sz;\n\n    return out as this;\n  }\n\n  /**\n   * Sets this matrix to a pure translation by `(x, y, z)`\n   * @example\n   * ```ts\n   * const eyeOffset = new Matrix4().makeTranslation(0, 1.7, 0);\n   * ```\n   * @param x - Translation along x\n   * @param y - Translation along y\n   * @param z - Translation along z\n   * @returns This matrix\n   */\n  public makeTranslation(x: number, y: number, z: number): this {\n    return this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);\n  }\n\n  /**\n   * Sets this matrix to a scale by `(x, y, z)`; a negative factor mirrors that axis\n   * @example\n   * ```ts\n   * const mirrorX = new Matrix4().makeScale(-1, 1, 1);\n   * ```\n   * @param x - Scale along x\n   * @param y - Scale along y\n   * @param z - Scale along z\n   * @returns This matrix\n   */\n  public makeScale(x: number, y: number, z: number): this {\n    return this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);\n  }\n\n  /**\n   * Sets this matrix to a shear, where each factor adds that multiple of a point's coordinate on\n   * its axis to the point's other two coordinates\n   *\n   * With `y = 0.2`, a point 1 unit up moves 0.2 along both x and z. To shear one axis only, write\n   * the matrix with {@link Matrix4#set}.\n   * @example\n   * ```ts\n   * const lean = new Matrix4().makeShear(0, 0.2, 0);\n   * ```\n   * @param x - How much a point's x adds to its y and z\n   * @param y - How much a point's y adds to its x and z\n   * @param z - How much a point's z adds to its x and y\n   * @returns This matrix\n   */\n  public makeShear(x: number, y: number, z: number): this {\n    return this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);\n  }\n\n  /**\n   * Sets this matrix to a rotation of `theta` radians around the X axis; positive angles turn +Y\n   * toward +Z\n   * @example\n   * ```ts\n   * const layFlat = new Matrix4().makeRotationX(-Math.PI / 2);\n   * ```\n   * @param theta - Rotation angle in radians\n   * @returns This matrix\n   */\n  public makeRotationX(theta: number): this {\n    const c = Math.cos(theta);\n    const s = Math.sin(theta);\n\n    return this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);\n  }\n\n  /**\n   * Sets this matrix to a rotation of `theta` radians around the Y axis; positive angles turn +Z\n   * toward +X\n   * @example\n   * ```ts\n   * const heading = new Matrix4().makeRotationY(yaw);\n   * ```\n   * @param theta - Rotation angle in radians\n   * @returns This matrix\n   */\n  public makeRotationY(theta: number): this {\n    const c = Math.cos(theta);\n    const s = Math.sin(theta);\n\n    return this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);\n  }\n\n  /**\n   * Sets this matrix to a rotation of `theta` radians around the Z axis; positive angles turn +X\n   * toward +Y\n   * @example\n   * ```ts\n   * const roll = new Matrix4().makeRotationZ(bankAngle);\n   * ```\n   * @param theta - Rotation angle in radians\n   * @returns This matrix\n   */\n  public makeRotationZ(theta: number): this {\n    const c = Math.cos(theta);\n    const s = Math.sin(theta);\n\n    return this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);\n  }\n\n  /**\n   * Sets this matrix to a rotation of `angle` radians around `axis`\n   *\n   * Positive angles turn counter-clockwise as seen from the tip of `axis`, like the single-axis\n   * methods.\n   * @example\n   * ```ts\n   * const wobble = new Matrix4().makeRotationAxis(new Vector3(1, 0, 1).normalize(), 0.2);\n   * ```\n   * @param axis - Unit-length rotation axis\n   * @param angle - Rotation angle in radians\n   * @returns This matrix\n   */\n  public makeRotationAxis(axis: PointData3D, angle: number): this {\n    const c = Math.cos(angle);\n    const s = Math.sin(angle);\n    const t = 1 - c;\n    const x = axis.x;\n    const y = axis.y;\n    const z = axis.z;\n    const tx = t * x;\n    const ty = t * y;\n\n    return this.set(\n      tx * x + c,\n      tx * y - s * z,\n      tx * z + s * y,\n      0,\n      tx * y + s * z,\n      ty * y + c,\n      ty * z - s * x,\n      0,\n      tx * z - s * y,\n      ty * z + s * x,\n      t * z * z + c,\n      0,\n      0,\n      0,\n      0,\n      1,\n    );\n  }\n\n  /**\n   * Sets this matrix to a rotation derived from XYZ Euler angles in `rotation` (radians)\n   *\n   * The matrix is `Rx * Ry * Rz`, the convention {@link Container3D#rotation} and\n   * {@link Quaternion#setFromEuler} use, so the same angles give the same orientation.\n   * @example\n   * ```ts\n   * const facing = new Matrix4().makeRotationFromEuler({ x: 0, y: Math.PI / 2, z: 0 });\n   * ```\n   * @param rotation - Euler angles in radians\n   * @returns This matrix\n   */\n  public makeRotationFromEuler(rotation: PointData3D): this {\n    const te = this.elements;\n\n    const a = Math.cos(rotation.x);\n    const b = Math.sin(rotation.x);\n    const c = Math.cos(rotation.y);\n    const d = Math.sin(rotation.y);\n    const e = Math.cos(rotation.z);\n    const f = Math.sin(rotation.z);\n\n    const ae = a * e;\n    const af = a * f;\n    const be = b * e;\n    const bf = b * f;\n\n    te[0] = c * e;\n    te[4] = -c * f;\n    te[8] = d;\n\n    te[1] = af + be * d;\n    te[5] = ae - bf * d;\n    te[9] = -b * c;\n\n    te[2] = bf - ae * d;\n    te[6] = be + af * d;\n    te[10] = a * c;\n\n    te[3] = 0;\n    te[7] = 0;\n    te[11] = 0;\n\n    te[12] = 0;\n    te[13] = 0;\n    te[14] = 0;\n    te[15] = 1;\n\n    return this;\n  }\n\n  /**\n   * Sets this matrix to a rotation derived from the quaternion `q`\n   * @example\n   * ```ts\n   * const quarterTurn = new Quaternion().setFromAxisAngle({ x: 0, y: 1, z: 0 }, Math.PI / 2);\n   * const rotation = new Matrix4().makeRotationFromQuaternion(quarterTurn);\n   * ```\n   * @param q - Rotation quaternion\n   * @returns This matrix\n   */\n  public makeRotationFromQuaternion(q: Quaternion): this {\n    return this.compose(zero, q, one);\n  }\n\n  /**\n   * Sets this matrix to a perspective projection from a vertical field-of-view (radians), for a\n   * camera looking down -Z\n   *\n   * Clip-space depth runs from -1 at `near` to 1 at `far`, as WebGL expects, and\n   * {@link Camera3D#projection} is built the same way. On WebGPU, whose depth runs from 0 to 1, the\n   * renderer remaps the copy it draws with, but a matrix you bind yourself, the camera's included,\n   * needs the same remap. `fovy` is in radians, unlike {@link Camera3D#fov}, which is in degrees.\n   * @example\n   * ```ts\n   * const projection = new Matrix4().makePerspective(Math.PI / 3, width / height, 0.1, 500);\n   * ```\n   * @param fovy - Vertical field-of-view in radians\n   * @param aspect - Viewport width / height\n   * @param near - Near clip distance\n   * @param far - Far clip distance; leave it out or pass `Infinity` for no far plane\n   * @returns This matrix\n   */\n  public makePerspective(fovy: number, aspect: number, near: number, far?: number): this {\n    const te = this.elements;\n\n    const f = 1.0 / Math.tan(fovy / 2);\n\n    te[0] = f / aspect;\n    te[1] = 0;\n    te[2] = 0;\n    te[3] = 0;\n    te[4] = 0;\n    te[5] = f;\n    te[6] = 0;\n    te[7] = 0;\n    te[8] = 0;\n    te[9] = 0;\n    te[11] = -1;\n    te[12] = 0;\n    te[13] = 0;\n    te[15] = 0;\n\n    if (far !== undefined && far !== Infinity) {\n      const nf = 1 / (near - far);\n      te[10] = (far + near) * nf;\n      te[14] = 2 * far * near * nf;\n    } else {\n      te[10] = -1;\n      te[14] = -2 * near;\n    }\n\n    return this;\n  }\n\n  /**\n   * Sets this matrix to an orthographic projection of the box between the given planes, for a\n   * camera looking down -Z\n   *\n   * `top` comes before `bottom` in the arguments. Clip-space depth runs from -1 at `near` to 1 at\n   * `far`, as with {@link Matrix4#makePerspective}.\n   * @example\n   * ```ts\n   * const shadowProjection = new Matrix4().makeOrthographic(-20, 20, 20, -20, 0.5, 100);\n   * ```\n   * @param left - Left clip plane\n   * @param right - Right clip plane\n   * @param top - Top clip plane\n   * @param bottom - Bottom clip plane\n   * @param near - Near clip distance\n   * @param far - Far clip distance\n   * @returns This matrix\n   */\n  public makeOrthographic(left: number, right: number, top: number, bottom: number, near: number, far: number): this {\n    const te = this.elements;\n    const lr = 1 / (left - right);\n    const bt = 1 / (bottom - top);\n    const nf = 1 / (near - far);\n\n    te[0] = -2 * lr;\n    te[1] = 0;\n    te[2] = 0;\n    te[3] = 0;\n    te[4] = 0;\n    te[5] = -2 * bt;\n    te[6] = 0;\n    te[7] = 0;\n    te[8] = 0;\n    te[9] = 0;\n    te[10] = 2 * nf;\n    te[11] = 0;\n    te[12] = (left + right) * lr;\n    te[13] = (top + bottom) * bt;\n    te[14] = (far + near) * nf;\n    te[15] = 1;\n\n    return this;\n  }\n\n  /**\n   * Sets this matrix's rotation so its -Z axis points from `eye` toward `target`, with its +Y axis\n   * as close to `up` as it can be\n   *\n   * That turns a camera at `eye` to face `target`. Only the rotation part is written; the\n   * translation and bottom row stay (copied into `out` first when it is another matrix). Set the\n   * position and invert the result to get the camera's view matrix. When `up` lies along the view\n   * direction, the direction is nudged slightly so the result is still a rotation.\n   * @example\n   * ```ts\n   * const cameraWorld = new Matrix4().lookAt(eye, target, { x: 0, y: 1, z: 0 }).setPosition(eye);\n   * const view = new Matrix4().getInverse(cameraWorld);\n   * ```\n   * @param eye - Viewer position\n   * @param target - Point to look toward\n   * @param up - Up direction\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public lookAt(eye: PointData3D, target: PointData3D, up: PointData3D, out: Matrix4 = this): this {\n    if (out !== this) out.copyFrom(this);\n    const x = vector;\n    const y = vector2;\n    const z = vector3;\n\n    const te = out.elements;\n\n    z.x = eye.x - target.x;\n    z.y = eye.y - target.y;\n    z.z = eye.z - target.z;\n\n    if (z.magnitudeSquared() === 0) {\n      z.z = 1;\n    }\n\n    z.normalize();\n    x.copyFrom(up).cross(z);\n\n    if (x.magnitudeSquared() === 0) {\n      if (Math.abs(up.z) === 1) {\n        z.x += 0.0001;\n      } else {\n        z.z += 0.0001;\n      }\n\n      z.normalize();\n      x.copyFrom(up).cross(z);\n    }\n\n    x.normalize();\n    y.copyFrom(z).cross(x);\n\n    te[0] = x.x;\n    te[4] = y.x;\n    te[8] = z.x;\n    te[1] = x.y;\n    te[5] = y.y;\n    te[9] = z.y;\n    te[2] = x.z;\n    te[6] = y.z;\n    te[10] = z.z;\n\n    return out as this;\n  }\n\n  /**\n   * Writes `(v.x, v.y, v.z)` into the translation column of this matrix, leaving the rest intact\n   * @example\n   * ```ts\n   * const spawn = new Matrix4().makeRotationY(heading).setPosition(spawnPoint);\n   * ```\n   * @param v - Position to write\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public setPosition(v: PointData3D, out: Matrix4 = this): this {\n    if (out !== this) out.copyFrom(this);\n    const te = out.elements;\n\n    te[12] = v.x;\n    te[13] = v.y;\n    te[14] = v.z;\n\n    return out as this;\n  }\n\n  /**\n   * Scales this matrix along its own axes by `(v.x, v.y, v.z)`\n   *\n   * Multiplies the first three columns, which is the same as multiplying by\n   * {@link Matrix4#makeScale} on the right: the scale applies to a point first.\n   * @example\n   * ```ts\n   * const doubled = mesh.worldTransform.clone().scale({ x: 2, y: 2, z: 2 });\n   * ```\n   * @param v - Per-axis scale factors\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public scale(v: PointData3D, out: Matrix4 = this): this {\n    if (out !== this) out.copyFrom(this);\n    const te = out.elements;\n    const x = v.x;\n    const y = v.y;\n    const z = v.z;\n\n    te[0] *= x;\n    te[4] *= y;\n    te[8] *= z;\n    te[1] *= x;\n    te[5] *= y;\n    te[9] *= z;\n    te[2] *= x;\n    te[6] *= y;\n    te[10] *= z;\n    te[3] *= x;\n    te[7] *= y;\n    te[11] *= z;\n\n    return out as this;\n  }\n\n  /**\n   * Writes the translation column into `out`\n   * @example\n   * ```ts\n   * const worldPosition = mesh.worldTransform.extractPosition(new Vector3());\n   * ```\n   * @param out - Point that receives the translation\n   * @returns The given output point\n   */\n  public extractPosition<T extends PointLike3D>(out: T): T {\n    const te = this.elements;\n\n    out.set(te[12], te[13], te[14]);\n\n    return out;\n  }\n\n  /**\n   * Writes the per-axis scale (column magnitudes) into `out`\n   *\n   * The lengths are never negative, so a mirrored axis reads as a positive scale;\n   * {@link Matrix4#decompose} reports the mirror.\n   * @example\n   * ```ts\n   * const worldScale = mesh.worldTransform.extractScale(new Vector3());\n   * ```\n   * @param out - Point that receives the scale\n   * @returns The given output point\n   */\n  public extractScale<T extends PointLike3D>(out: T): T {\n    const te = this.elements;\n\n    out.set(\n      Math.sqrt(te[0] * te[0] + te[1] * te[1] + te[2] * te[2]),\n      Math.sqrt(te[4] * te[4] + te[5] * te[5] + te[6] * te[6]),\n      Math.sqrt(te[8] * te[8] + te[9] * te[9] + te[10] * te[10]),\n    );\n\n    return out;\n  }\n\n  /**\n   * Writes the three basis vectors of this matrix into `xAxis`, `yAxis` and `zAxis`\n   *\n   * They are the first three columns: the matrix's own axes, scale included.\n   * @example\n   * ```ts\n   * const right = new Vector3();\n   * const up = new Vector3();\n   * const back = new Vector3();\n   *\n   * camera.worldTransform.extractBasis(right, up, back);\n   * ```\n   * @param xAxis - Receives the X basis vector\n   * @param yAxis - Receives the Y basis vector\n   * @param zAxis - Receives the Z basis vector\n   * @param out - Optional matrix that receives a copy of this matrix first\n   * @returns The matrix the basis was read from\n   */\n  public extractBasis(xAxis: Vector3, yAxis: Vector3, zAxis: Vector3, out: Matrix4 = this): this {\n    if (out !== this) out.copyFrom(this);\n    xAxis.setFromMatrixColumn(out, 0);\n    yAxis.setFromMatrixColumn(out, 1);\n    zAxis.setFromMatrixColumn(out, 2);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this matrix using the three basis vectors as its columns, with no translation\n   *\n   * Unit-length axes at right angles to each other make a rotation when `zAxis` is `xAxis` cross\n   * `yAxis`, and a mirror when it points the other way.\n   * @example\n   * ```ts\n   * const orientation = new Matrix4().makeBasis(right, up, back);\n   * ```\n   * @param xAxis - X basis vector\n   * @param yAxis - Y basis vector\n   * @param zAxis - Z basis vector\n   * @returns This matrix\n   */\n  public makeBasis(xAxis: PointData3D, yAxis: PointData3D, zAxis: PointData3D): this {\n    return this.set(\n      xAxis.x,\n      yAxis.x,\n      zAxis.x,\n      0,\n      xAxis.y,\n      yAxis.y,\n      zAxis.y,\n      0,\n      xAxis.z,\n      yAxis.z,\n      zAxis.z,\n      0,\n      0,\n      0,\n      0,\n      1,\n    );\n  }\n\n  /**\n   * Sets this matrix to `m` with each axis scaled to unit length and the translation cleared\n   *\n   * That removes only the scale: a mirroring matrix (negative determinant) gives a mirrored result,\n   * and shear stays.\n   * @example\n   * ```ts\n   * const rotationOnly = new Matrix4().extractRotation(mesh.worldTransform);\n   * ```\n   * @param m - Matrix to extract the rotation from\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public extractRotation(m: Matrix4, out: Matrix4 = this): this {\n    const te = out.elements;\n    const me = m.elements;\n\n    const scaleX = 1 / vector.setFromMatrixColumn(m, 0).magnitude();\n    const scaleY = 1 / vector.setFromMatrixColumn(m, 1).magnitude();\n    const scaleZ = 1 / vector.setFromMatrixColumn(m, 2).magnitude();\n\n    te[0] = me[0] * scaleX;\n    te[1] = me[1] * scaleX;\n    te[2] = me[2] * scaleX;\n    te[3] = 0;\n\n    te[4] = me[4] * scaleY;\n    te[5] = me[5] * scaleY;\n    te[6] = me[6] * scaleY;\n    te[7] = 0;\n\n    te[8] = me[8] * scaleZ;\n    te[9] = me[9] * scaleZ;\n    te[10] = me[10] * scaleZ;\n    te[11] = 0;\n\n    te[12] = 0;\n    te[13] = 0;\n    te[14] = 0;\n    te[15] = 1;\n\n    return out as this;\n  }\n\n  /**\n   * Writes the negated Z column (forward direction, length 1) into `out`\n   *\n   * That is the way a {@link Camera3D} or a light faces. Other {@link Container3D}s, such as meshes,\n   * face +Z, so for them this points backwards.\n   * @example\n   * ```ts\n   * const aim = camera.worldTransform.extractForward(new Vector3());\n   * ```\n   * @param out - Point that receives the direction\n   * @returns The given output point\n   */\n  public extractForward<T extends PointLike3D>(out: T): T {\n    const e = this.elements;\n    let x = -e[8];\n    let y = -e[9];\n    let z = -e[10];\n    const inv = 1 / (Math.sqrt(x * x + y * y + z * z) || 1);\n    x *= inv;\n    y *= inv;\n    z *= inv;\n    out.set(x, y, z);\n\n    return out;\n  }\n\n  /**\n   * Writes the X column (right direction, length 1) into `out`\n   * @example\n   * ```ts\n   * camera.worldTransform.extractRight(right);\n   * player.position.addScaledVector(right, strafeSpeed);\n   * ```\n   * @param out - Point that receives the direction\n   * @returns The given output point\n   */\n  public extractRight<T extends PointLike3D>(out: T): T {\n    const e = this.elements;\n    let x = e[0];\n    let y = e[1];\n    let z = e[2];\n    const inv = 1 / (Math.sqrt(x * x + y * y + z * z) || 1);\n    x *= inv;\n    y *= inv;\n    z *= inv;\n    out.set(x, y, z);\n\n    return out;\n  }\n\n  /**\n   * Writes the Y column (up direction, length 1) into `out`\n   * @example\n   * ```ts\n   * drone.worldTransform.extractUp(thrustDirection);\n   * ```\n   * @param out - Point that receives the direction\n   * @returns The given output point\n   */\n  public extractUp<T extends PointLike3D>(out: T): T {\n    const e = this.elements;\n    let x = e[4];\n    let y = e[5];\n    let z = e[6];\n    const inv = 1 / (Math.sqrt(x * x + y * y + z * z) || 1);\n    x *= inv;\n    y *= inv;\n    z *= inv;\n    out.set(x, y, z);\n\n    return out;\n  }\n\n  /**\n   * Computes the largest of the three axis scales: the length of the longest of the first three\n   * columns\n   *\n   * Scaling a bounding radius by it covers rotation and per-axis scale. Under shear, as when a\n   * non-uniformly scaled parent holds a rotated child, the matrix can stretch some other direction\n   * further; {@link Matrix4#getMaxSingularValueSq} measures that.\n   * @example\n   * ```ts\n   * const worldRadius = localRadius * mesh.worldTransform.getMaxScaleOnAxis();\n   * ```\n   * @returns The largest axis scale\n   */\n  public getMaxScaleOnAxis(): number {\n    const te = this.elements;\n\n    const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];\n    const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];\n    const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];\n\n    return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));\n  }\n\n  /**\n   * Largest singular value of the upper-left 3x3, squared: the square of the most this matrix\n   * stretches any direction\n   *\n   * A bounding radius scaled by its square root covers the transformed shape even under shear,\n   * where {@link Matrix4#getMaxScaleOnAxis} can fall short; without shear, it's the square of that.\n   * It comes back squared so a comparison against squared distances skips a square root.\n   * @example\n   * ```ts\n   * const worldRadius = localRadius * Math.sqrt(mesh.worldTransform.getMaxSingularValueSq());\n   * ```\n   */\n  public getMaxSingularValueSq(): number {\n    const e = this.elements;\n    const c0x = e[0];\n    const c0y = e[1];\n    const c0z = e[2];\n    const c1x = e[4];\n    const c1y = e[5];\n    const c1z = e[6];\n    const c2x = e[8];\n    const c2y = e[9];\n    const c2z = e[10];\n\n    const a11 = c0x * c0x + c0y * c0y + c0z * c0z;\n    const a22 = c1x * c1x + c1y * c1y + c1z * c1z;\n    const a33 = c2x * c2x + c2y * c2y + c2z * c2z;\n    const a12 = c0x * c1x + c0y * c1y + c0z * c1z;\n    const a13 = c0x * c2x + c0y * c2y + c0z * c2z;\n    const a23 = c1x * c2x + c1y * c2y + c1z * c2z;\n\n    const p1 = a12 * a12 + a13 * a13 + a23 * a23;\n    if (p1 === 0) {\n      return Math.max(a11, a22, a33);\n    }\n\n    const q = (a11 + a22 + a33) / 3;\n    const d11 = a11 - q;\n    const d22 = a22 - q;\n    const d33 = a33 - q;\n    const p = Math.sqrt((d11 * d11 + d22 * d22 + d33 * d33 + 2 * p1) / 6);\n\n    const b11 = d11 / p;\n    const b22 = d22 / p;\n    const b33 = d33 / p;\n    const b12 = a12 / p;\n    const b13 = a13 / p;\n    const b23 = a23 / p;\n    const detB = b11 * (b22 * b33 - b23 * b23) - b12 * (b12 * b33 - b23 * b13) + b13 * (b12 * b23 - b22 * b13);\n    const r = Math.max(-1, Math.min(1, detB / 2));\n\n    const eigMax = q + 2 * p * Math.cos(Math.acos(r) / 3);\n    return Math.max(eigMax, 0);\n  }\n}\n\nfunction _multiplyMatrices(a: Matrix4, b: Matrix4, target: Matrix4): Matrix4 {\n  const ae = a.elements;\n  const be = b.elements;\n  const te = target.elements;\n\n  const a11 = ae[0];\n  const a12 = ae[4];\n  const a13 = ae[8];\n  const a14 = ae[12];\n  const a21 = ae[1];\n  const a22 = ae[5];\n  const a23 = ae[9];\n  const a24 = ae[13];\n  const a31 = ae[2];\n  const a32 = ae[6];\n  const a33 = ae[10];\n  const a34 = ae[14];\n  const a41 = ae[3];\n  const a42 = ae[7];\n  const a43 = ae[11];\n  const a44 = ae[15];\n\n  const b11 = be[0];\n  const b12 = be[4];\n  const b13 = be[8];\n  const b14 = be[12];\n  const b21 = be[1];\n  const b22 = be[5];\n  const b23 = be[9];\n  const b24 = be[13];\n  const b31 = be[2];\n  const b32 = be[6];\n  const b33 = be[10];\n  const b34 = be[14];\n  const b41 = be[3];\n  const b42 = be[7];\n  const b43 = be[11];\n  const b44 = be[15];\n\n  te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;\n  te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;\n  te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;\n  te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;\n\n  te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;\n  te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;\n  te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;\n  te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;\n\n  te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;\n  te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;\n  te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;\n  te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;\n\n  te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;\n  te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;\n  te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;\n  te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;\n\n  return target;\n}\n\nconst vector = new Vector3();\nconst vector2 = new Vector3();\nconst vector3 = new Vector3();\n\nconst matrix = new Matrix4();\n\nconst zero = new Vector3(0, 0, 0);\nconst one = new Vector3(1, 1, 1);\n\nconst _sharedMatrix = new Matrix4();\nconst _identityMatrix = new Matrix4();\n","import type { Matrix4 } from '../matrix/Matrix4';\nimport { clamp } from '../utils/clamp';\nimport type { PointData3D } from '../vector/PointData3D';\n\n/**\n * Minimal `{ x, y, z, w }` shape of a quaternion, accepted across the math API\n *\n * {@link Quaternion} and {@link ObservableQuaternion} implement it, and so does any plain object with\n * these four numbers. For a turn of `angle` radians around the unit vector `axis`, `(x, y, z)` is\n * `axis * sin(angle / 2)` and `w` is `cos(angle / 2)`.\n * @example\n * ```ts\n * const quarterTurnAroundY: QuaternionData = { x: 0, y: Math.SQRT1_2, z: 0, w: Math.SQRT1_2 };\n *\n * door.quaternion.copyFrom(quarterTurnAroundY);\n * ```\n * @category maths\n * @standard\n */\nexport interface QuaternionData {\n  /**\n   * The x component\n   * @example\n   * ```ts\n   * const axisX = rotation.x / Math.sqrt(1 - rotation.w * rotation.w);\n   * ```\n   */\n  x: number;\n  /**\n   * The y component\n   * @example\n   * ```ts\n   * const axisY = rotation.y / Math.sqrt(1 - rotation.w * rotation.w);\n   * ```\n   */\n  y: number;\n  /**\n   * The z component\n   * @example\n   * ```ts\n   * const axisZ = rotation.z / Math.sqrt(1 - rotation.w * rotation.w);\n   * ```\n   */\n  z: number;\n  /**\n   * The w component\n   * @example\n   * ```ts\n   * const angle = 2 * Math.acos(rotation.w);\n   * ```\n   */\n  w: number;\n}\n\n/**\n * A rotation in 3D, stored as four numbers `(x, y, z, w)`\n *\n * Unlike Euler angles, a quaternion doesn't lose a degree of freedom when two axes line up, and\n * {@link Quaternion#slerp} blends between two of them smoothly. {@link QuaternionData} says what the\n * four numbers mean. A rotation quaternion has length 1. Most methods assume so, and long chains of\n * {@link Quaternion#multiply} drift from it, which {@link Quaternion#normalize} fixes.\n *\n * Methods change the quaternion they're called on and return it, so calls chain. Pass an `out`\n * target last to write the result there instead and leave this one as it is.\n * @example\n * ```ts\n * const up = { x: 0, y: 1, z: 0 };\n * const spin = new Quaternion();\n *\n * app.ticker.add((ticker) => {\n *   spin.setFromAxisAngle(up, spinSpeed * (ticker.deltaMS / 1000));\n *   coin.quaternion.multiply(spin);\n * });\n * ```\n * @see {@link Vector3#applyQuaternion} For applying a quaternion rotation to a point\n * @category maths\n * @standard\n */\nexport class Quaternion implements QuaternionData {\n  /**\n   * The x component; {@link QuaternionData} says what it means\n   * @example\n   * ```ts\n   * const axisX = rotation.x / Math.sqrt(1 - rotation.w * rotation.w);\n   * ```\n   */\n  public x = 0;\n  /**\n   * The y component; {@link QuaternionData} says what it means\n   * @example\n   * ```ts\n   * const axisY = rotation.y / Math.sqrt(1 - rotation.w * rotation.w);\n   * ```\n   */\n  public y = 0;\n  /**\n   * The z component; {@link QuaternionData} says what it means\n   * @example\n   * ```ts\n   * const axisZ = rotation.z / Math.sqrt(1 - rotation.w * rotation.w);\n   * ```\n   */\n  public z = 0;\n  /**\n   * The w component; {@link QuaternionData} says what it means\n   * @example\n   * ```ts\n   * const angle = 2 * Math.acos(rotation.w);\n   * ```\n   */\n  public w = 0;\n\n  /**\n   * A static `Quaternion` reset to identity on every access, for a result used straight away\n   *\n   * > [!IMPORTANT] This quaternion is shared and temporary. Do not store references to it.\n   * @example\n   * ```ts\n   * kickOffset.applyQuaternion(Quaternion.shared.setFromEuler(recoil));\n   * ```\n   */\n  static get shared(): Quaternion {\n    _shared.x = 0;\n    _shared.y = 0;\n    _shared.z = 0;\n    _shared.w = 1;\n\n    return _shared;\n  }\n\n  /**\n   * Spherically interpolates between two quaternions stored in flat arrays, writing the result into\n   * `dst` without creating a `Quaternion`\n   *\n   * Like {@link Quaternion#slerp}, it takes the shorter way round. It costs one `Math.sin` where the\n   * textbook form costs three, so it suits blending many rotations every frame.\n   * @example\n   * ```ts\n   * Quaternion.slerpFlat(pose, boneIndex * 4, keyframes, frame * 4, keyframes, (frame + 1) * 4, blend);\n   * ```\n   * @param dst - The array to write the result into\n   * @param dstOffset - The offset into `dst` to write at\n   * @param src0 - The array holding the start quaternion\n   * @param srcOffset0 - The offset into `src0` to read from\n   * @param src1 - The array holding the end quaternion\n   * @param srcOffset1 - The offset into `src1` to read from\n   * @param t - The interpolation factor in `[0, 1]`\n   * @advanced\n   */\n  public static slerpFlat(\n    dst: number[],\n    dstOffset: number,\n    src0: number[],\n    srcOffset0: number,\n    src1: number[],\n    srcOffset1: number,\n    t: number,\n  ): void {\n    let x0 = src0[srcOffset0 + 0];\n    let y0 = src0[srcOffset0 + 1];\n    let z0 = src0[srcOffset0 + 2];\n    let w0 = src0[srcOffset0 + 3];\n\n    let x1 = src1[srcOffset1 + 0];\n    let y1 = src1[srcOffset1 + 1];\n    let z1 = src1[srcOffset1 + 2];\n    let w1 = src1[srcOffset1 + 3];\n\n    if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {\n      let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;\n\n      if (dot < 0) {\n        x1 = -x1;\n        y1 = -y1;\n        z1 = -z1;\n        w1 = -w1;\n        dot = -dot;\n      }\n\n      let k0 = 1 - t;\n      let k1 = t;\n\n      if (dot < 0.9995) {\n        const sinT = Math.sin(t * Math.acos(dot));\n\n        k1 = sinT / Math.sqrt(1 - dot * dot);\n        k0 = Math.sqrt(1 - sinT * sinT) - dot * k1;\n\n        x0 = x0 * k0 + x1 * k1;\n        y0 = y0 * k0 + y1 * k1;\n        z0 = z0 * k0 + z1 * k1;\n        w0 = w0 * k0 + w1 * k1;\n      } else {\n        x0 = x0 * k0 + x1 * k1;\n        y0 = y0 * k0 + y1 * k1;\n        z0 = z0 * k0 + z1 * k1;\n        w0 = w0 * k0 + w1 * k1;\n\n        const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);\n        x0 *= f;\n        y0 *= f;\n        z0 *= f;\n        w0 *= f;\n      }\n    }\n\n    dst[dstOffset] = x0;\n    dst[dstOffset + 1] = y0;\n    dst[dstOffset + 2] = z0;\n    dst[dstOffset + 3] = w0;\n  }\n\n  /**\n   * Creates a new `Quaternion`, defaulting to identity `(0, 0, 0, 1)`\n   * @param x - The x component\n   * @param y - The y component\n   * @param z - The z component\n   * @param w - The w component\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  /**\n   * Sets the components of this quaternion\n   * @example\n   * ```ts\n   * rotation.set(0, Math.SQRT1_2, 0, Math.SQRT1_2);\n   * ```\n   * @param x - The x component\n   * @param y - The y component\n   * @param z - The z component\n   * @param w - The w component\n   * @returns This quaternion for chaining\n   */\n  public 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\n    return this;\n  }\n\n  /**\n   * Copies `q` into this quaternion\n   * @example\n   * ```ts\n   * savedRotation.copyFrom(door.quaternion);\n   * ```\n   * @param q - The quaternion to copy from\n   * @returns This quaternion for chaining\n   */\n  public copyFrom(q: QuaternionData): this {\n    this.x = q.x;\n    this.y = q.y;\n    this.z = q.z;\n    this.w = q.w;\n\n    return this;\n  }\n\n  /**\n   * Copies this quaternion into `target` and returns it\n   * @example\n   * ```ts\n   * savedRotation.copyTo(door.quaternion);\n   * ```\n   * @param target - The quaternion to copy into\n   * @returns The given `target`\n   */\n  public copyTo<T extends QuaternionData>(target: T): T {\n    target.x = this.x;\n    target.y = this.y;\n    target.z = this.z;\n    target.w = this.w;\n\n    return target;\n  }\n\n  /**\n   * Creates a new `Quaternion` with the same values\n   * @example\n   * ```ts\n   * const restRotation = aimRotation.clone();\n   * ```\n   * @returns The new quaternion\n   */\n  public clone(): Quaternion {\n    return new Quaternion(this.x, this.y, this.z, this.w);\n  }\n\n  /**\n   * Resets this quaternion to identity `(0, 0, 0, 1)`, no rotation\n   * @example\n   * ```ts\n   * aimOffset.identity();\n   * ```\n   * @returns This quaternion for chaining\n   */\n  public identity(): this {\n    this.x = 0;\n    this.y = 0;\n    this.z = 0;\n    this.w = 1;\n\n    return this;\n  }\n\n  /**\n   * Returns true when `x`, `y`, `z` and `w` match `q` exactly, with no tolerance\n   *\n   * `q` and its negation are the same rotation but don't compare equal.\n   * @example\n   * ```ts\n   * if (!aimRotation.equals(lastAimRotation)) updateCrosshair();\n   * ```\n   * @param q - The quaternion to compare with\n   * @returns Whether all components match\n   */\n  public equals(q: QuaternionData): boolean {\n    return q.x === this.x && q.y === this.y && q.z === this.z && q.w === this.w;\n  }\n\n  /**\n   * Sets this quaternion from Euler angles in radians\n   *\n   * Uses the XYZ order of {@link Container3D#rotation}, so it gives the rotation a node with those\n   * angles has.\n   * @example\n   * ```ts\n   * const facing = new Quaternion().setFromEuler({ x: 0, y: heading, z: 0 });\n   * ```\n   * @param rotation - The Euler angles as `(x, y, z)` radians\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromEuler(rotation: PointData3D, out: QuaternionData = this): this {\n    const halfX = rotation.x * 0.5;\n    const halfY = rotation.y * 0.5;\n    const halfZ = rotation.z * 0.5;\n    const c1 = Math.cos(halfX);\n    const c2 = Math.cos(halfY);\n    const c3 = Math.cos(halfZ);\n    const s1 = Math.sin(halfX);\n    const s2 = Math.sin(halfY);\n    const s3 = Math.sin(halfZ);\n\n    out.x = s1 * c2 * c3 + c1 * s2 * s3;\n    out.y = c1 * s2 * c3 - s1 * c2 * s3;\n    out.z = c1 * c2 * s3 + s1 * s2 * c3;\n    out.w = c1 * c2 * c3 - s1 * s2 * s3;\n\n    return out as this;\n  }\n\n  /**\n   * Sets this quaternion to a turn of `angle` radians around the unit-length `axis`\n   * @example\n   * ```ts\n   * const up = { x: 0, y: 1, z: 0 };\n   *\n   * Quaternion.shared.setFromAxisAngle(up, yaw, rigidBody.quaternion);\n   * ```\n   * @param axis - The unit-length rotation axis\n   * @param angle - The rotation angle in radians\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromAxisAngle(axis: PointData3D, angle: number, out: QuaternionData = this): this {\n    const halfAngle = angle / 2;\n    const s = Math.sin(halfAngle);\n\n    out.x = axis.x * s;\n    out.y = axis.y * s;\n    out.z = axis.z * s;\n    out.w = Math.cos(halfAngle);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this quaternion to the rotation in `m`\n   *\n   * The upper-left 3x3 of `m` must be a pure rotation, with no scale. Use\n   * {@link Quaternion#setFromScaledRotationMatrix} for a matrix with scale, such as a node's world\n   * transform.\n   * @example\n   * ```ts\n   * const cameraRotation = new Quaternion().setFromRotationMatrix(new Matrix4().lookAt(eye, target, up));\n   * ```\n   * @param m - The rotation matrix to extract from\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromRotationMatrix(m: Matrix4, out: QuaternionData = this): this {\n    const te = m.elements;\n\n    _setFromOrthonormalElements(out, te[0], te[4], te[8], te[1], te[5], te[9], te[2], te[6], te[10]);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this quaternion to the rotation in `m`, a transform that may also scale each axis\n   *\n   * A matrix with a zero scale has no rotation to read and gives `NaN`. A mirrored one (negative\n   * determinant) gives a quaternion that isn't a rotation; {@link Matrix4#decompose} handles it.\n   * @example\n   * ```ts\n   * const worldRotation = new Quaternion().setFromScaledRotationMatrix(node.worldTransform);\n   * ```\n   * @param m - The transform to extract from\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromScaledRotationMatrix(m: Matrix4, out: QuaternionData = this): this {\n    const te = m.elements;\n\n    let m11 = te[0];\n    let m21 = te[1];\n    let m31 = te[2];\n    let m12 = te[4];\n    let m22 = te[5];\n    let m32 = te[6];\n    let m13 = te[8];\n    let m23 = te[9];\n    let m33 = te[10];\n\n    const invSx = 1 / Math.sqrt(m11 * m11 + m21 * m21 + m31 * m31);\n    const invSy = 1 / Math.sqrt(m12 * m12 + m22 * m22 + m32 * m32);\n    const invSz = 1 / Math.sqrt(m13 * m13 + m23 * m23 + m33 * m33);\n\n    m11 *= invSx;\n    m21 *= invSx;\n    m31 *= invSx;\n    m12 *= invSy;\n    m22 *= invSy;\n    m32 *= invSy;\n    m13 *= invSz;\n    m23 *= invSz;\n    m33 *= invSz;\n\n    _setFromOrthonormalElements(out, m11, m12, m13, m21, m22, m23, m31, m32, m33);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this quaternion to the shortest turn that takes unit-length `vFrom` to unit-length `vTo`\n   *\n   * When `vTo` points exactly opposite `vFrom`, the result is a half turn around some axis at right\n   * angles to `vFrom`.\n   * @example\n   * ```ts\n   * const tilt = new Quaternion().setFromUnitVectors({ x: 0, y: 1, z: 0 }, groundNormal);\n   * ```\n   * @param vFrom - The unit-length start direction\n   * @param vTo - The unit-length end direction\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromUnitVectors(vFrom: PointData3D, vTo: PointData3D, out: QuaternionData = this): this {\n    const EPS = 0.000001;\n    let r = vFrom.x * vTo.x + vFrom.y * vTo.y + vFrom.z * vTo.z + 1;\n\n    if (r < EPS) {\n      r = 0;\n      if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {\n        out.x = -vFrom.y;\n        out.y = vFrom.x;\n        out.z = 0;\n      } else {\n        out.x = 0;\n        out.y = -vFrom.z;\n        out.z = vFrom.y;\n      }\n    } else {\n      out.x = vFrom.y * vTo.z - vFrom.z * vTo.y;\n      out.y = vFrom.z * vTo.x - vFrom.x * vTo.z;\n      out.z = vFrom.x * vTo.y - vFrom.y * vTo.x;\n    }\n    out.w = r;\n\n    return _normalize(out) as this;\n  }\n\n  /**\n   * Returns the dot product of this quaternion and `q`\n   *\n   * For unit quaternions its absolute value is the cosine of half the angle between the two rotations:\n   * 1 for the same rotation.\n   * @example\n   * ```ts\n   * const sameRotation = Math.abs(current.dot(target)) > 0.99999;\n   * ```\n   * @param q - The other quaternion\n   * @returns The dot product\n   */\n  public dot(q: QuaternionData): number {\n    return this.x * q.x + this.y * q.y + this.z * q.z + this.w * q.w;\n  }\n\n  /**\n   * Returns the angle of the turn from this rotation to `q`\n   *\n   * Both quaternions are assumed unit-length.\n   * @example\n   * ```ts\n   * if (aimRotation.angleTo(targetRotation) < 0.01) fire();\n   * ```\n   * @param q - The other quaternion\n   * @returns The angle in radians, from 0 to π\n   */\n  public angleTo(q: QuaternionData): number {\n    return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));\n  }\n\n  /**\n   * Returns the length of this quaternion as a 4D vector, 1 for a rotation\n   * @example\n   * ```ts\n   * if (Math.abs(rotation.magnitude() - 1) > 1e-6) rotation.normalize();\n   * ```\n   * @returns The magnitude\n   */\n  public magnitude(): number {\n    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n  }\n\n  /**\n   * Returns the squared length of this quaternion\n   *\n   * Cheaper than {@link Quaternion#magnitude} and enough to check for drift.\n   * @example\n   * ```ts\n   * if (Math.abs(rotation.magnitudeSquared() - 1) > 1e-6) rotation.normalize();\n   * ```\n   * @returns The squared magnitude\n   */\n  public magnitudeSquared(): number {\n    return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;\n  }\n\n  /**\n   * Scales this quaternion to unit length, undoing the drift of repeated multiplies\n   *\n   * A zero quaternion becomes identity.\n   * @example\n   * ```ts\n   * rotation.multiply(step).normalize();\n   * ```\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public normalize(out: QuaternionData = this): this {\n    const len = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n    if (len === 0) {\n      out.x = 0;\n      out.y = 0;\n      out.z = 0;\n      out.w = 1;\n    } else {\n      const inv = 1 / len;\n      out.x = this.x * inv;\n      out.y = this.y * inv;\n      out.z = this.z * inv;\n      out.w = this.w * inv;\n    }\n\n    return out as this;\n  }\n\n  /**\n   * Inverts this rotation, so it turns the other way\n   *\n   * Computes the {@link Quaternion#conjugate | conjugate}, which is the inverse of a unit quaternion.\n   * For any other quaternion, call {@link Quaternion#normalize} first.\n   * @example\n   * ```ts\n   * parentWorldRotation.inverse(worldToLocal);\n   * direction.applyQuaternion(worldToLocal);\n   * ```\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public inverse(out: QuaternionData = this): this {\n    return this.conjugate(out);\n  }\n\n  /**\n   * Negates `x`, `y` and `z`, leaving `w`, which reverses a unit quaternion's turn\n   * @example\n   * ```ts\n   * recoil.conjugate(recovery);\n   * ```\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public conjugate(out: QuaternionData = this): this {\n    out.x = -this.x;\n    out.y = -this.y;\n    out.z = -this.z;\n    out.w = this.w;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies this quaternion by `q` (`this = this * q`)\n   *\n   * The result turns by `q` first, then by this. On a node's rotation, that turns by `q` around the\n   * node's own axes; {@link Quaternion#premultiply} turns around its parent's axes.\n   * @example\n   * ```ts\n   * roll.setFromAxisAngle(forwardAxis, rollSpeed * dt);\n   * shipRotation.multiply(roll);\n   * ```\n   * @param q - The quaternion to multiply by\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public multiply(q: QuaternionData, out: QuaternionData = this): this {\n    return multiplyQuaternionData(this, q, out) as this;\n  }\n\n  /**\n   * Pre-multiplies this quaternion by `q` (`this = q * this`)\n   *\n   * The result turns by this first, then by `q`. On a node's rotation, that turns by `q` around the\n   * parent's axes; {@link Quaternion#multiply} turns around the node's own.\n   * @example\n   * ```ts\n   * spin.setFromAxisAngle(worldUp, spinSpeed * dt);\n   * globeRotation.premultiply(spin);\n   * ```\n   * @param q - The quaternion to pre-multiply by\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public premultiply(q: QuaternionData, out: QuaternionData = this): this {\n    return multiplyQuaternionData(q, this, out) as this;\n  }\n\n  /**\n   * Blends from this rotation toward `qb` by `t`, turning at an even rate the shorter way round\n   * @example\n   * ```ts\n   * aimRotation.slerp(targetRotation, 1 - Math.exp(-turnRate * dt));\n   * fromRotation.slerp(toRotation, t, blended);\n   * ```\n   * @param qb - The quaternion to interpolate towards\n   * @param t - The interpolation factor in `[0, 1]`\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public slerp(qb: QuaternionData, t: number, out: QuaternionData = this): this {\n    if (t === 0) {\n      if (out !== this) {\n        out.x = this.x;\n        out.y = this.y;\n        out.z = this.z;\n        out.w = this.w;\n      }\n\n      return out as this;\n    }\n    if (t === 1) {\n      out.x = qb.x;\n      out.y = qb.y;\n      out.z = qb.z;\n      out.w = qb.w;\n\n      return out as this;\n    }\n\n    const x0 = this.x;\n    const y0 = this.y;\n    const z0 = this.z;\n    const w0 = this.w;\n    let qbx = qb.x;\n    let qby = qb.y;\n    let qbz = qb.z;\n    let qbw = qb.w;\n    let dot = x0 * qbx + y0 * qby + z0 * qbz + w0 * qbw;\n\n    if (dot < 0) {\n      qbx = -qbx;\n      qby = -qby;\n      qbz = -qbz;\n      qbw = -qbw;\n      dot = -dot;\n    }\n\n    let k0 = 1 - t;\n    let k1 = t;\n    if (dot < 0.9995) {\n      const theta = Math.acos(dot);\n      const sin = Math.sin(theta);\n\n      k0 = Math.sin(k0 * theta) / sin;\n      k1 = Math.sin(t * theta) / sin;\n\n      out.x = x0 * k0 + qbx * k1;\n      out.y = y0 * k0 + qby * k1;\n      out.z = z0 * k0 + qbz * k1;\n      out.w = w0 * k0 + qbw * k1;\n\n      return out as this;\n    }\n\n    out.x = x0 * k0 + qbx * k1;\n    out.y = y0 * k0 + qby * k1;\n    out.z = z0 * k0 + qbz * k1;\n    out.w = w0 * k0 + qbw * k1;\n\n    return _normalize(out) as this;\n  }\n\n  /**\n   * Reads `x`, `y`, `z`, `w` from `array` starting at `offset`\n   * @example\n   * ```ts\n   * keyRotation.fromArray(keyframes, frame * 4);\n   * ```\n   * @param array - The array to read from\n   * @param offset - The offset into `array` to read at\n   * @returns This quaternion for chaining\n   */\n  public fromArray(array: number[] | Float32Array, offset = 0): this {\n    this.x = array[offset];\n    this.y = array[offset + 1];\n    this.z = array[offset + 2];\n    this.w = array[offset + 3];\n\n    return this;\n  }\n\n  /**\n   * Writes this quaternion's values into `array` starting at `offset`\n   * @example\n   * ```ts\n   * rotation.toArray(instanceRotations, instanceIndex * 4);\n   * ```\n   * @param array - The array to write into; a new array when omitted\n   * @param offset - The offset into `array` to write at\n   * @returns The written array\n   */\n  public toArray<T extends number[] | Float32Array = number[]>(array: T = [] as unknown as T, offset = 0): T {\n    array[offset] = this.x;\n    array[offset + 1] = this.y;\n    array[offset + 2] = this.z;\n    array[offset + 3] = this.w;\n\n    return array;\n  }\n\n  /**\n   * Returns a string representation of this quaternion\n   * @example\n   * ```ts\n   * console.log(aimRotation.toString());\n   * ```\n   * @returns A string in the form `[@pixi/3d/math:Quaternion x=0 y=0 z=0 w=1]`\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Quaternion x=${this.x} y=${this.y} z=${this.z} w=${this.w}]`;\n  }\n}\n\nfunction _setFromOrthonormalElements(\n  q: QuaternionData,\n  m11: number,\n  m12: number,\n  m13: number,\n  m21: number,\n  m22: number,\n  m23: number,\n  m31: number,\n  m32: number,\n  m33: number,\n): void {\n  const trace = m11 + m22 + m33;\n  let s;\n\n  if (trace > 0) {\n    s = 0.5 / Math.sqrt(trace + 1.0);\n    q.w = 0.25 / s;\n    q.x = (m32 - m23) * s;\n    q.y = (m13 - m31) * s;\n    q.z = (m21 - m12) * s;\n  } else if (m11 > m22 && m11 > m33) {\n    s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);\n    q.w = (m32 - m23) / s;\n    q.x = 0.25 * s;\n    q.y = (m12 + m21) / s;\n    q.z = (m13 + m31) / s;\n  } else if (m22 > m33) {\n    s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);\n    q.w = (m13 - m31) / s;\n    q.x = (m12 + m21) / s;\n    q.y = 0.25 * s;\n    q.z = (m23 + m32) / s;\n  } else {\n    s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);\n    q.w = (m21 - m12) / s;\n    q.x = (m13 + m31) / s;\n    q.y = (m23 + m32) / s;\n    q.z = 0.25 * s;\n  }\n}\n\n/**\n * `target = a * b`; `target` may be `a` or `b`, so every input is read before any write\n * @internal\n */\nexport function multiplyQuaternionData(a: QuaternionData, b: QuaternionData, target: QuaternionData): QuaternionData {\n  const qax = a.x;\n  const qay = a.y;\n  const qaz = a.z;\n  const qaw = a.w;\n  const qbx = b.x;\n  const qby = b.y;\n  const qbz = b.z;\n  const qbw = b.w;\n\n  target.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;\n  target.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;\n  target.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;\n  target.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;\n\n  return target;\n}\n\nfunction _normalize(q: QuaternionData): QuaternionData {\n  const len = Math.sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);\n  if (len === 0) {\n    q.x = 0;\n    q.y = 0;\n    q.z = 0;\n    q.w = 1;\n  } else {\n    const inv = 1 / len;\n    q.x *= inv;\n    q.y *= inv;\n    q.z *= inv;\n    q.w *= inv;\n  }\n\n  return q;\n}\n\nconst _shared = new Quaternion();\n","import type { Observer } from 'pixi.js';\n\nimport type { Matrix4 } from '../matrix/Matrix4';\nimport { clamp } from '../utils/clamp';\nimport type { PointData3D } from '../vector/PointData3D';\nimport { multiplyQuaternionData, Quaternion } from './Quaternion';\nimport type { QuaternionData } from './Quaternion';\n\n/**\n * A {@link Quaternion} that tells an observer when it changes\n *\n * A node's {@link Container3D#quaternion | quaternion} is one, so changing it turns the node. It has\n * the same methods as {@link Quaternion}. Each in-place method notifies the observer at most once,\n * and not at all when no component changed. Given an `out` target, a method writes there and leaves\n * this quaternion and its observer alone.\n * @example\n * ```ts\n * const up = { x: 0, y: 1, z: 0 };\n *\n * app.ticker.add((ticker) => {\n *   coin.quaternion.setFromAxisAngle(up, (ticker.lastTime / 1000) * spinSpeed);\n * });\n * ```\n * @category maths\n * @standard\n */\nexport class ObservableQuaternion implements QuaternionData {\n  /** @ignore */\n  public _x = 0;\n  /** @ignore */\n  public _y = 0;\n  /** @ignore */\n  public _z = 0;\n  /** @ignore */\n  public _w = 0;\n\n  private readonly _observer: Observer<ObservableQuaternion>;\n\n  /**\n   * The x component; assigning a different value notifies the observer\n   * @example\n   * ```ts\n   * const axisX = node.quaternion.x / Math.sqrt(1 - node.quaternion.w ** 2);\n   * ```\n   */\n  get x(): number {\n    return this._x;\n  }\n\n  /**\n   * Sets the x component\n   * @param value - New x component\n   */\n  set x(value: number) {\n    if (this._x !== value) {\n      this._x = value;\n      this._observer._onUpdate(this);\n    }\n  }\n\n  /**\n   * The y component; assigning a different value notifies the observer\n   * @example\n   * ```ts\n   * const axisY = node.quaternion.y / Math.sqrt(1 - node.quaternion.w ** 2);\n   * ```\n   */\n  get y(): number {\n    return this._y;\n  }\n\n  /**\n   * Sets the y component\n   * @param value - New y component\n   */\n  set y(value: number) {\n    if (this._y !== value) {\n      this._y = value;\n      this._observer._onUpdate(this);\n    }\n  }\n\n  /**\n   * The z component; assigning a different value notifies the observer\n   * @example\n   * ```ts\n   * const axisZ = node.quaternion.z / Math.sqrt(1 - node.quaternion.w ** 2);\n   * ```\n   */\n  get z(): number {\n    return this._z;\n  }\n\n  /**\n   * Sets the z component\n   * @param value - New z component\n   */\n  set z(value: number) {\n    if (this._z !== value) {\n      this._z = value;\n      this._observer._onUpdate(this);\n    }\n  }\n\n  /**\n   * The w component; assigning a different value notifies the observer\n   * @example\n   * ```ts\n   * const angle = 2 * Math.acos(node.quaternion.w);\n   * ```\n   */\n  get w(): number {\n    return this._w;\n  }\n\n  /**\n   * Sets the w component\n   * @param value - New w component\n   */\n  set w(value: number) {\n    if (this._w !== value) {\n      this._w = value;\n      this._observer._onUpdate(this);\n    }\n  }\n\n  /**\n   * Creates a new `ObservableQuaternion`, defaulting to identity `(0, 0, 0, 1)`\n   * @param observer - Observer notified when any component changes\n   * @param x - The x component\n   * @param y - The y component\n   * @param z - The z component\n   * @param w - The w component\n   */\n  constructor(observer: Observer<ObservableQuaternion>, 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    this._observer = observer;\n  }\n\n  /**\n   * Sets the components of this quaternion\n   * @example\n   * ```ts\n   * door.quaternion.set(0, Math.SQRT1_2, 0, Math.SQRT1_2);\n   * ```\n   * @param x - The x component\n   * @param y - The y component\n   * @param z - The z component\n   * @param w - The w component\n   * @returns This quaternion for chaining\n   */\n  public set(x: number, y: number, z: number, w: number): this {\n    if (this._x !== x || this._y !== y || this._z !== z || this._w !== w) {\n      this._x = x;\n      this._y = y;\n      this._z = z;\n      this._w = w;\n      this._observer._onUpdate(this);\n    }\n\n    return this;\n  }\n\n  /**\n   * Copies `q` into this quaternion\n   * @example\n   * ```ts\n   * door.quaternion.copyFrom(closedRotation);\n   * ```\n   * @param q - The quaternion to copy from\n   * @returns This quaternion for chaining\n   */\n  public copyFrom(q: QuaternionData): this {\n    if (this._x !== q.x || this._y !== q.y || this._z !== q.z || this._w !== q.w) {\n      this._x = q.x;\n      this._y = q.y;\n      this._z = q.z;\n      this._w = q.w;\n      this._observer._onUpdate(this);\n    }\n\n    return this;\n  }\n\n  /**\n   * Copies this quaternion into `target` and returns it\n   * @example\n   * ```ts\n   * door.quaternion.copyTo(closedRotation);\n   * ```\n   * @param target - The quaternion to copy into\n   * @returns The given `target`\n   */\n  public copyTo<T extends QuaternionData>(target: T): T {\n    target.x = this._x;\n    target.y = this._y;\n    target.z = this._z;\n    target.w = this._w;\n\n    return target;\n  }\n\n  /**\n   * Creates a copy of this quaternion that notifies `observer`, or this quaternion's observer when\n   * left out\n   *\n   * A copy of a node's `quaternion` that keeps the node as its observer makes the node recompute its\n   * transform on every change, though the node doesn't turn. For a plain copy, use\n   * `new Quaternion().copyFrom(node.quaternion)`.\n   * @param observer - Observer for the copy\n   * @returns The new quaternion\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- a copy that keeps the observer is rarely wanted\n  public clone(observer?: Observer<ObservableQuaternion>): ObservableQuaternion {\n    return new ObservableQuaternion(observer ?? this._observer, this._x, this._y, this._z, this._w);\n  }\n\n  /**\n   * Resets this quaternion to identity `(0, 0, 0, 1)`, no rotation\n   * @example\n   * ```ts\n   * crate.quaternion.identity();\n   * ```\n   * @returns This quaternion for chaining\n   */\n  public identity(): this {\n    return this.set(0, 0, 0, 1);\n  }\n\n  /**\n   * Returns true when `x`, `y`, `z` and `w` match `q` exactly, with no tolerance\n   * @example\n   * ```ts\n   * const closed = door.quaternion.equals(closedRotation);\n   * ```\n   * @param q - The quaternion to compare with\n   * @returns Whether all components match\n   */\n  public equals(q: QuaternionData): boolean {\n    return q.x === this._x && q.y === this._y && q.z === this._z && q.w === this._w;\n  }\n\n  /**\n   * Sets this quaternion from Euler angles in radians, in the XYZ order of\n   * {@link Container3D#rotation}\n   * @example\n   * ```ts\n   * door.quaternion.setFromEuler({ x: 0, y: openAngle, z: 0 });\n   * ```\n   * @param rotation - The Euler angles as `(x, y, z)` radians\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromEuler(rotation: PointData3D, out: QuaternionData = this): this {\n    if (out === this) {\n      _tempQuat.setFromEuler(rotation);\n\n      return this.set(_tempQuat.x, _tempQuat.y, _tempQuat.z, _tempQuat.w);\n    }\n    _tempQuat.setFromEuler(rotation, out);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this quaternion to a turn of `angle` radians around the unit-length `axis`\n   * @example\n   * ```ts\n   * wheel.quaternion.setFromAxisAngle({ x: 1, y: 0, z: 0 }, distanceDriven / wheelRadius);\n   * ```\n   * @param axis - The unit-length rotation axis\n   * @param angle - The rotation angle in radians\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromAxisAngle(axis: PointData3D, angle: number, out: QuaternionData = this): this {\n    if (out === this) {\n      _tempQuat.setFromAxisAngle(axis, angle);\n\n      return this.set(_tempQuat.x, _tempQuat.y, _tempQuat.z, _tempQuat.w);\n    }\n    _tempQuat.setFromAxisAngle(axis, angle, out);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this quaternion to the rotation in `m`\n   *\n   * The upper-left 3x3 of `m` must be a pure rotation, with no scale. Use\n   * {@link ObservableQuaternion#setFromScaledRotationMatrix} for a matrix with scale.\n   * @example\n   * ```ts\n   * securityCamera.quaternion.setFromRotationMatrix(new Matrix4().lookAt(eye, target, up));\n   * ```\n   * @param m - The rotation matrix to extract from\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromRotationMatrix(m: Matrix4, out: QuaternionData = this): this {\n    if (out === this) {\n      _tempQuat.setFromRotationMatrix(m);\n\n      return this.set(_tempQuat.x, _tempQuat.y, _tempQuat.z, _tempQuat.w);\n    }\n    _tempQuat.setFromRotationMatrix(m, out);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this quaternion to the rotation in `m`, a transform that may also scale each axis\n   *\n   * {@link Quaternion#setFromScaledRotationMatrix} says what a zero or mirrored scale gives.\n   * @example\n   * ```ts\n   * debris.quaternion.setFromScaledRotationMatrix(wreck.worldTransform);\n   * ```\n   * @param m - The transform to extract from\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromScaledRotationMatrix(m: Matrix4, out: QuaternionData = this): this {\n    if (out === this) {\n      _tempQuat.setFromScaledRotationMatrix(m);\n\n      return this.set(_tempQuat.x, _tempQuat.y, _tempQuat.z, _tempQuat.w);\n    }\n    _tempQuat.setFromScaledRotationMatrix(m, out);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this quaternion to the shortest turn that takes unit-length `vFrom` to unit-length `vTo`\n   *\n   * {@link Quaternion#setFromUnitVectors} says what happens when they point opposite ways.\n   * @example\n   * ```ts\n   * tree.quaternion.setFromUnitVectors({ x: 0, y: 1, z: 0 }, groundNormal);\n   * ```\n   * @param vFrom - The unit-length start direction\n   * @param vTo - The unit-length end direction\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public setFromUnitVectors(vFrom: PointData3D, vTo: PointData3D, out: QuaternionData = this): this {\n    if (out === this) {\n      _tempQuat.setFromUnitVectors(vFrom, vTo);\n\n      return this.set(_tempQuat.x, _tempQuat.y, _tempQuat.z, _tempQuat.w);\n    }\n    _tempQuat.setFromUnitVectors(vFrom, vTo, out);\n\n    return out as this;\n  }\n\n  /**\n   * Returns the dot product of this quaternion and `q`\n   * @example\n   * ```ts\n   * const facingTarget = Math.abs(turret.quaternion.dot(aimRotation)) > 0.99999;\n   * ```\n   * @param q - The other quaternion\n   * @returns The dot product\n   */\n  public dot(q: QuaternionData): number {\n    return this._x * q.x + this._y * q.y + this._z * q.z + this._w * q.w;\n  }\n\n  /**\n   * Returns the angle of the turn from this rotation to `q`\n   *\n   * Both quaternions are assumed unit-length.\n   * @example\n   * ```ts\n   * if (turret.quaternion.angleTo(aimRotation) < 0.01) fire();\n   * ```\n   * @param q - The other quaternion\n   * @returns The angle in radians, from 0 to π\n   */\n  public angleTo(q: QuaternionData): number {\n    return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));\n  }\n\n  /**\n   * Returns the length of this quaternion as a 4D vector, 1 for a rotation\n   * @example\n   * ```ts\n   * if (Math.abs(ship.quaternion.magnitude() - 1) > 1e-6) ship.quaternion.normalize();\n   * ```\n   * @returns The magnitude\n   */\n  public magnitude(): number {\n    return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);\n  }\n\n  /**\n   * Returns the squared length of this quaternion\n   *\n   * Cheaper than {@link ObservableQuaternion#magnitude} and enough to check for drift.\n   * @example\n   * ```ts\n   * if (Math.abs(ship.quaternion.magnitudeSquared() - 1) > 1e-6) ship.quaternion.normalize();\n   * ```\n   * @returns The squared magnitude\n   */\n  public magnitudeSquared(): number {\n    return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;\n  }\n\n  /**\n   * Scales this quaternion to unit length, undoing the drift of repeated multiplies\n   *\n   * A zero quaternion becomes identity.\n   * @example\n   * ```ts\n   * ship.quaternion.multiply(roll).normalize();\n   * ```\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public normalize(out: QuaternionData = this): this {\n    const len = Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);\n    let x: number;\n    let y: number;\n    let z: number;\n    let w: number;\n    if (len === 0) {\n      x = 0;\n      y = 0;\n      z = 0;\n      w = 1;\n    } else {\n      const inv = 1 / len;\n      x = this._x * inv;\n      y = this._y * inv;\n      z = this._z * inv;\n      w = this._w * inv;\n    }\n\n    if (out === this) return this.set(x, y, z, w);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n    out.w = w;\n\n    return out as this;\n  }\n\n  /**\n   * Inverts this rotation, so it turns the other way\n   *\n   * Computes the {@link ObservableQuaternion#conjugate | conjugate}, which is the inverse of a unit\n   * quaternion.\n   * @example\n   * ```ts\n   * turret.quaternion.inverse(parentToTurret);\n   * ```\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public inverse(out: QuaternionData = this): this {\n    return this.conjugate(out);\n  }\n\n  /**\n   * Negates `x`, `y` and `z`, leaving `w`, which reverses a unit quaternion's turn\n   * @example\n   * ```ts\n   * const reverseTurn = door.quaternion.conjugate(new Quaternion());\n   * ```\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public conjugate(out: QuaternionData = this): this {\n    if (out === this) return this.set(-this._x, -this._y, -this._z, this._w);\n    out.x = -this._x;\n    out.y = -this._y;\n    out.z = -this._z;\n    out.w = this._w;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies this quaternion by `q` (`this = this * q`), turning the node by `q` around its own axes\n   *\n   * {@link Quaternion#multiply} explains the order.\n   * @example\n   * ```ts\n   * roll.setFromAxisAngle(forwardAxis, rollSpeed * dt);\n   * ship.quaternion.multiply(roll);\n   * ```\n   * @param q - The quaternion to multiply by\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public multiply(q: QuaternionData, out: QuaternionData = this): this {\n    if (out === this) {\n      multiplyQuaternionData(this, q, _tempQuat);\n\n      return this.set(_tempQuat.x, _tempQuat.y, _tempQuat.z, _tempQuat.w);\n    }\n    multiplyQuaternionData(this, q, out);\n\n    return out as this;\n  }\n\n  /**\n   * Pre-multiplies this quaternion by `q` (`this = q * this`), turning the node by `q` around its\n   * parent's axes\n   * @example\n   * ```ts\n   * spin.setFromAxisAngle(worldUp, spinSpeed * dt);\n   * globe.quaternion.premultiply(spin);\n   * ```\n   * @param q - The quaternion to pre-multiply by\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public premultiply(q: QuaternionData, out: QuaternionData = this): this {\n    if (out === this) {\n      multiplyQuaternionData(q, this, _tempQuat);\n\n      return this.set(_tempQuat.x, _tempQuat.y, _tempQuat.z, _tempQuat.w);\n    }\n    multiplyQuaternionData(q, this, out);\n\n    return out as this;\n  }\n\n  /**\n   * Blends from this rotation toward `qb` by `t`, turning at an even rate the shorter way round\n   * @example\n   * ```ts\n   * turret.quaternion.slerp(aimRotation, 1 - Math.exp(-turnRate * dt));\n   * ```\n   * @param qb - The quaternion to interpolate towards\n   * @param t - The interpolation factor in `[0, 1]`\n   * @param out - Target to write the result into instead of this quaternion\n   * @returns The result quaternion for chaining\n   */\n  public slerp(qb: QuaternionData, t: number, out: QuaternionData = this): this {\n    _tempQuat.set(this._x, this._y, this._z, this._w).slerp(qb, t);\n    if (out === this) return this.set(_tempQuat.x, _tempQuat.y, _tempQuat.z, _tempQuat.w);\n    out.x = _tempQuat.x;\n    out.y = _tempQuat.y;\n    out.z = _tempQuat.z;\n    out.w = _tempQuat.w;\n\n    return out as this;\n  }\n\n  /**\n   * Reads `x`, `y`, `z`, `w` from `array` starting at `offset`\n   * @example\n   * ```ts\n   * crates.forEach((crate: Container3D, i: number) => crate.quaternion.fromArray(savedRotations, i * 4));\n   * ```\n   * @param array - The array to read from\n   * @param offset - The offset into `array` to read at\n   * @returns This quaternion for chaining\n   */\n  public fromArray(array: number[] | Float32Array, offset = 0): this {\n    return this.set(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n  }\n\n  /**\n   * Writes this quaternion's values into `array` starting at `offset`\n   * @example\n   * ```ts\n   * crates.forEach((crate: Container3D, i: number) => crate.quaternion.toArray(savedRotations, i * 4));\n   * ```\n   * @param array - The array to write into; a new array when omitted\n   * @param offset - The offset into `array` to write at\n   * @returns The written array\n   */\n  public toArray<T extends number[] | Float32Array = number[]>(array: T = [] as unknown as T, offset = 0): T {\n    array[offset] = this._x;\n    array[offset + 1] = this._y;\n    array[offset + 2] = this._z;\n    array[offset + 3] = this._w;\n\n    return array;\n  }\n\n  /**\n   * Returns a string representation of this quaternion\n   * @example\n   * ```ts\n   * console.log(ship.quaternion.toString());\n   * ```\n   * @returns A string in the form `[@pixi/3d/math:ObservableQuaternion x=0 y=0 z=0 w=1]`\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:ObservableQuaternion x=${this._x} y=${this._y} z=${this._z} w=${this._w}]`;\n  }\n}\n\nconst _tempQuat = new Quaternion();\n","import type { Matrix4 } from '../matrix/Matrix4';\nimport type { SHAPE_PRIMITIVE_3D } from '../misc/const';\nimport type { PointData3D } from '../vector/PointData3D';\nimport { Vector3 } from '../vector/Vector3';\nimport type { Plane } from './Plane';\nimport type { Ray } from './Ray';\nimport type { Sphere } from './Sphere';\n\n/**\n * An axis-aligned bounding box (AABB), spanning from its `min` corner to its `max` corner\n *\n * Use one to bound a mesh or a group and to run cheap overlap, culling and picking tests before\n * precise ones. {@link Container3D#getLocalBounds} measures one for a subtree.\n * @example\n * ```ts\n * const squadBounds = new Box();\n *\n * for (const soldier of squad) squadBounds.expandByPoint(soldier.position);\n *\n * const rallyPoint = squadBounds.getCenter(new Vector3());\n * ```\n * @see {@link Ray#intersectBox} For the point where a ray hits the box\n * @category maths\n * @standard\n */\nexport class Box {\n  /**\n   * The corner with the smallest x, y and z; `+Infinity` on every axis in a new, empty box\n   * @example\n   * ```ts\n   * const floorHeight = levelBounds.min.y;\n   * ```\n   */\n  public readonly min: Vector3;\n  /**\n   * The corner with the largest x, y and z; `-Infinity` on every axis in a new, empty box\n   * @example\n   * ```ts\n   * const roofHeight = levelBounds.max.y;\n   * ```\n   */\n  public readonly max: Vector3;\n\n  /**\n   * Names the shape without an `instanceof` check, like the `type` on pixi's 2D shapes\n   * @readonly\n   * @default 'box'\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type: SHAPE_PRIMITIVE_3D = 'box';\n\n  /**\n   * Creates a new `Box`\n   *\n   * Left out, the box starts empty, so the first {@link Box#expandByPoint} gives a tight fit.\n   * Vectors passed in become the box's corners; they are not copied.\n   * @param min - The minimum corner of the box\n   * @param max - The maximum corner of the box\n   */\n  constructor(min?: Vector3, max?: Vector3) {\n    this.min = min !== undefined ? min : new Vector3(Infinity, Infinity, Infinity);\n    this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);\n  }\n\n  /**\n   * Creates a box centred at `center` with the given full `size`\n   *\n   * A number makes a cube; a point sets the size of each axis.\n   * @example\n   * ```ts\n   * const crate = Box.fromCenterSize({ x: 0, y: 0.5, z: 0 }, 1);\n   * const pickupZone = Box.fromCenterSize(player.position, { x: 4, y: 2, z: 4 });\n   * ```\n   * @param center - The center of the box\n   * @param size - The full size of the box, uniform or per-axis\n   * @returns The new box\n   */\n  public static fromCenterSize(center: PointData3D, size: number | PointData3D): Box {\n    const hx = (typeof size === 'number' ? size : size.x) * 0.5;\n    const hy = (typeof size === 'number' ? size : size.y) * 0.5;\n    const hz = (typeof size === 'number' ? size : size.z) * 0.5;\n\n    return new Box(\n      new Vector3(center.x - hx, center.y - hy, center.z - hz),\n      new Vector3(center.x + hx, center.y + hy, center.z + hz),\n    );\n  }\n\n  /**\n   * Sets the corners of this box to `min` and `max`, copying their values\n   * @example\n   * ```ts\n   * triggerZone.set({ x: -2, y: 0, z: -2 }, { x: 2, y: 3, z: 2 });\n   * ```\n   * @param min - The minimum corner\n   * @param max - The maximum corner\n   * @returns This box for chaining\n   */\n  public set(min: PointData3D, max: PointData3D): this {\n    this.min.copyFrom(min);\n    this.max.copyFrom(max);\n\n    return this;\n  }\n\n  /**\n   * Copies `box` into this box\n   * @example\n   * ```ts\n   * const bounds = new Box().copyFrom(geometry.bounds3D);\n   * ```\n   * @param box - The box to copy from\n   * @returns This box for chaining\n   */\n  public copyFrom(box: Box): this {\n    this.min.copyFrom(box.min);\n    this.max.copyFrom(box.max);\n\n    return this;\n  }\n\n  /**\n   * Copies this box into `target` and returns it\n   * @example\n   * ```ts\n   * geometry.bounds3D.copyTo(cachedBounds);\n   * ```\n   * @param target - The box to copy into\n   * @returns The given `target`\n   */\n  public copyTo<T extends Box>(target: T): T {\n    target.min.copyFrom(this.min);\n    target.max.copyFrom(this.max);\n\n    return target;\n  }\n\n  /**\n   * Creates a new `Box` with the same corners\n   * @example\n   * ```ts\n   * const padded = bounds.clone().expandByPoint(spawnPoint);\n   * ```\n   * @returns The new box\n   */\n  public clone(): Box {\n    return new Box().copyFrom(this);\n  }\n\n  /**\n   * Resets this box to empty (`min` at `+Infinity`, `max` at `-Infinity`), ready to grow again\n   * @example\n   * ```ts\n   * trailBounds.makeEmpty();\n   * for (const point of trail) trailBounds.expandByPoint(point);\n   * ```\n   * @returns This box for chaining\n   */\n  public makeEmpty(): this {\n    this.min.x = this.min.y = this.min.z = Infinity;\n    this.max.x = this.max.y = this.max.z = -Infinity;\n\n    return this;\n  }\n\n  /**\n   * Returns true when `max` is below `min` on any axis, as in a new box\n   *\n   * A flat box, with `min` equal to `max` on an axis, is not empty: it holds the points on it.\n   * @example\n   * ```ts\n   * if (!selectionBounds.isEmpty()) camera.lookAt(selectionBounds.getCenter());\n   * ```\n   * @returns Whether this box is empty\n   */\n  public isEmpty(): boolean {\n    return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;\n  }\n\n  /**\n   * Returns true when both corners match `box` exactly (no epsilon tolerance)\n   * @example\n   * ```ts\n   * if (!bounds.equals(lastBounds)) rebuildNavGrid(bounds);\n   * ```\n   * @param box - The box to compare with\n   * @returns Whether both corners match\n   */\n  public equals(box: Box): boolean {\n    return box.min.equals(this.min) && box.max.equals(this.max);\n  }\n\n  /**\n   * Grows this box to enclose `point`\n   * @example\n   * ```ts\n   * const routeBounds = new Box();\n   *\n   * for (const waypoint of route) routeBounds.expandByPoint(waypoint);\n   * ```\n   * @param point - The point to enclose\n   * @param out - Target to write the result into instead of mutating this box\n   * @returns The result box for chaining\n   */\n  public expandByPoint(point: PointData3D, out: Box = this): this {\n    if (out !== this) out.copyFrom(this);\n    out.min.min(point);\n    out.max.max(point);\n\n    return out as this;\n  }\n\n  /**\n   * Grows this box to enclose `box`\n   * @example\n   * ```ts\n   * const levelBounds = new Box();\n   *\n   * for (const room of rooms) levelBounds.union(room.bounds);\n   * ```\n   * @param box - The box to enclose\n   * @param out - Target to write the result into instead of mutating this box\n   * @returns The result box for chaining\n   */\n  public union(box: Box, out: Box = this): this {\n    if (out !== this) out.copyFrom(this);\n    out.min.min(box.min);\n    out.max.max(box.max);\n\n    return out as this;\n  }\n\n  /**\n   * Writes the center of this box into `out` (or a new `Vector3`)\n   *\n   * Empty boxes return `(0, 0, 0)`.\n   * @example\n   * ```ts\n   * const center = new Vector3();\n   *\n   * camera.lookAt(model.getLocalBounds().getCenter(center));\n   * ```\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The center of this box\n   */\n  public getCenter(out?: Vector3): Vector3 {\n    out ||= new Vector3();\n    if (this.isEmpty()) return out.set(0, 0, 0);\n    out.x = (this.min.x + this.max.x) * 0.5;\n    out.y = (this.min.y + this.max.y) * 0.5;\n    out.z = (this.min.z + this.max.z) * 0.5;\n\n    return out;\n  }\n\n  /**\n   * Writes the size (`max - min`) of this box into `out` (or a new `Vector3`)\n   *\n   * Empty boxes return `(0, 0, 0)`.\n   * @example\n   * ```ts\n   * const size = model.getLocalBounds().getSize(new Vector3());\n   *\n   * model.scale.set(2 / Math.max(size.x, size.y, size.z));\n   * ```\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The size of this box\n   */\n  public getSize(out?: Vector3): Vector3 {\n    out ||= new Vector3();\n    if (this.isEmpty()) return out.set(0, 0, 0);\n    out.x = this.max.x - this.min.x;\n    out.y = this.max.y - this.min.y;\n    out.z = this.max.z - this.min.z;\n\n    return out;\n  }\n\n  /**\n   * Returns the Euclidean distance from `point` to the closest point on this box (`0` if inside)\n   * @example\n   * ```ts\n   * const inReach = doorBounds.distanceToPoint(player.position) < 1.5;\n   * ```\n   * @param point - The point to measure from\n   * @returns The distance to the closest point on this box\n   */\n  public distanceToPoint(point: PointData3D): number {\n    return _scratchPoint.copyFrom(point).clamp(this.min, this.max).distanceTo(point);\n  }\n\n  /**\n   * Writes the closest point on this box to `point` into `out` (or a new `Vector3`)\n   *\n   * A point inside the box comes back unchanged.\n   * @example\n   * ```ts\n   * const kept = new Vector3();\n   *\n   * app.ticker.add(() => {\n   *   arena.clampPoint(player.position, kept);\n   *   player.position.copyFrom(kept);\n   * });\n   * ```\n   * @param point - The point to clamp\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The closest point on this box\n   */\n  public clampPoint(point: PointData3D, out?: Vector3): Vector3 {\n    out ||= new Vector3();\n\n    return out.copyFrom(point).clamp(this.min, this.max);\n  }\n\n  /**\n   * Returns true when `point` is inside this box (boundary is inclusive)\n   * @example\n   * ```ts\n   * if (pickupZone.containsPoint(player.position)) collect(pickup);\n   * ```\n   * @param point - The point to test\n   * @returns Whether the point is inside this box\n   */\n  public containsPoint(point: PointData3D): boolean {\n    return !(\n      point.x < this.min.x ||\n      point.x > this.max.x ||\n      point.y < this.min.y ||\n      point.y > this.max.y ||\n      point.z < this.min.z ||\n      point.z > this.max.z\n    );\n  }\n\n  /**\n   * Returns true when `box` is fully inside this box (boundary is inclusive)\n   *\n   * A new, empty `box` counts as inside any box.\n   * @example\n   * ```ts\n   * const fitsOnShelf = shelfBounds.containsBox(itemBounds);\n   * ```\n   * @param box - The box to test\n   * @returns Whether the box is fully inside this box\n   */\n  public containsBox(box: Box): boolean {\n    return (\n      this.min.x <= box.min.x &&\n      box.max.x <= this.max.x &&\n      this.min.y <= box.min.y &&\n      box.max.y <= this.max.y &&\n      this.min.z <= box.min.z &&\n      box.max.z <= this.max.z\n    );\n  }\n\n  /**\n   * Returns true when this box and `box` overlap; boxes that only touch count\n   * @example\n   * ```ts\n   * if (playerBounds.intersectsBox(doorBounds)) openDoor();\n   * ```\n   * @param box - The box to test\n   * @returns Whether the boxes overlap\n   */\n  public intersectsBox(box: Box): boolean {\n    return !(\n      box.max.x < this.min.x ||\n      box.min.x > this.max.x ||\n      box.max.y < this.min.y ||\n      box.min.y > this.max.y ||\n      box.max.z < this.min.z ||\n      box.min.z > this.max.z\n    );\n  }\n\n  /**\n   * Returns true when this box and `sphere` overlap; an empty sphere never does\n   * @example\n   * ```ts\n   * for (const crate of crates) {\n   *   if (crate.bounds.intersectsSphere(blastRadius)) crate.shatter();\n   * }\n   * ```\n   * @param sphere - The sphere to test\n   * @returns Whether the box and sphere overlap\n   */\n  public intersectsSphere(sphere: Sphere): boolean {\n    if (sphere.radius < 0) return false;\n    this.clampPoint(sphere.center, _scratchPoint);\n\n    return _scratchPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;\n  }\n\n  /**\n   * Returns true when `plane` passes through this box or touches it\n   * @example\n   * ```ts\n   * const wading = playerBounds.intersectsPlane(waterSurface);\n   * ```\n   * @param plane - The plane to test\n   * @returns Whether the plane passes through or touches the box\n   */\n  public intersectsPlane(plane: Plane): boolean {\n    let min: number;\n    let max: number;\n\n    if (plane.normal.x > 0) {\n      min = plane.normal.x * this.min.x;\n      max = plane.normal.x * this.max.x;\n    } else {\n      min = plane.normal.x * this.max.x;\n      max = plane.normal.x * this.min.x;\n    }\n\n    if (plane.normal.y > 0) {\n      min += plane.normal.y * this.min.y;\n      max += plane.normal.y * this.max.y;\n    } else {\n      min += plane.normal.y * this.max.y;\n      max += plane.normal.y * this.min.y;\n    }\n\n    if (plane.normal.z > 0) {\n      min += plane.normal.z * this.min.z;\n      max += plane.normal.z * this.max.z;\n    } else {\n      min += plane.normal.z * this.max.z;\n      max += plane.normal.z * this.min.z;\n    }\n\n    return min <= -plane.constant && max >= -plane.constant;\n  }\n\n  /**\n   * Returns true when `ray` hits this box; same as {@link Ray#intersectsBox}\n   * @example\n   * ```ts\n   * view3d.on('pointermove', (e) => {\n   *   hovered = buttonBounds.intersectsRay(view3d.screenToRay(e.global, pointerRay));\n   * });\n   * ```\n   * @param ray - The ray to test\n   * @returns Whether the ray hits this box\n   */\n  public intersectsRay(ray: Ray): boolean {\n    return ray.intersectsBox(this);\n  }\n\n  /**\n   * Transforms this box by an affine `matrix`, then fits a new axis-aligned box around the result\n   *\n   * The new box holds all eight transformed corners, so rotating a box can grow it. An empty box\n   * stays empty.\n   *\n   * `matrix` must be affine (bottom row `[0, 0, 0, 1]`), as a {@link Container3D#worldTransform}\n   * always is and a projection matrix isn't.\n   * @example\n   * ```ts\n   * const worldBounds = new Box();\n   *\n   * mesh.geometry.bounds3D.applyMatrix4(mesh.worldTransform, worldBounds);\n   * ```\n   * @param matrix - The affine matrix to transform by\n   * @param out - Target to write the result into instead of mutating this box\n   * @returns The result box for chaining\n   */\n  public applyMatrix4(matrix: Matrix4, out: Box = this): this {\n    if (out !== this) out.copyFrom(this);\n    if (out.isEmpty()) return out as this;\n\n    const e = matrix.elements;\n\n    const cx = (out.min.x + out.max.x) * 0.5;\n    const cy = (out.min.y + out.max.y) * 0.5;\n    const cz = (out.min.z + out.max.z) * 0.5;\n    const hx = (out.max.x - out.min.x) * 0.5;\n    const hy = (out.max.y - out.min.y) * 0.5;\n    const hz = (out.max.z - out.min.z) * 0.5;\n\n    const ncx = e[0] * cx + e[4] * cy + e[8] * cz + e[12];\n    const ncy = e[1] * cx + e[5] * cy + e[9] * cz + e[13];\n    const ncz = e[2] * cx + e[6] * cy + e[10] * cz + e[14];\n\n    const nhx = Math.abs(e[0]) * hx + Math.abs(e[4]) * hy + Math.abs(e[8]) * hz;\n    const nhy = Math.abs(e[1]) * hx + Math.abs(e[5]) * hy + Math.abs(e[9]) * hz;\n    const nhz = Math.abs(e[2]) * hx + Math.abs(e[6]) * hy + Math.abs(e[10]) * hz;\n\n    out.min.set(ncx - nhx, ncy - nhy, ncz - nhz);\n    out.max.set(ncx + nhx, ncy + nhy, ncz + nhz);\n\n    return out as this;\n  }\n\n  /**\n   * Copies this box into `out` (or a new `Box`), so a box answers `getBounds` like a {@link Sphere}\n   * @example\n   * ```ts\n   * const bounds = volume.getBounds(scratchBox);\n   * ```\n   * @param out - Optional box to write into; a new `Box` when omitted\n   * @returns The bounds of this box\n   */\n  public getBounds(out?: Box): Box {\n    out ||= new Box();\n\n    return out.copyFrom(this);\n  }\n\n  /**\n   * The width (X extent) of this box; `-Infinity` for a new, empty box, where\n   * {@link Box#getSize} gives `0`\n   * @example\n   * ```ts\n   * const footprint = bounds.width * bounds.depth;\n   * ```\n   */\n  public get width(): number {\n    return this.max.x - this.min.x;\n  }\n\n  /**\n   * The height (Y extent) of this box; `-Infinity` for a new, empty box\n   * @example\n   * ```ts\n   * nameTag.position.y = bounds.max.y + 0.1 * bounds.height;\n   * ```\n   */\n  public get height(): number {\n    return this.max.y - this.min.y;\n  }\n\n  /**\n   * The depth (Z extent) of this box; `-Infinity` for a new, empty box\n   * @example\n   * ```ts\n   * const footprint = bounds.width * bounds.depth;\n   * ```\n   */\n  public get depth(): number {\n    return this.max.z - this.min.z;\n  }\n\n  /**\n   * Returns a string representation of this box\n   * @returns A string in the form `[@pixi/3d/math:Box min=(0, 0, 0) max=(1, 1, 1)]`\n   * @advanced\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Box min=(${this.min.x}, ${this.min.y}, ${this.min.z}) max=(${this.max.x}, ${this.max.y}, ${this.max.z})]`;\n  }\n}\n\nconst _scratchPoint = new Vector3();\n","import { DEG_TO_RAD, RAD_TO_DEG } from 'pixi.js';\n\nimport type { ObservableVector3 } from './ObservableVector3';\nimport type { PointData3D } from './PointData3D';\nimport type { PointLike3D } from './PointLike3D';\n\n/**\n * Reads and writes a node's radian `rotation` in degrees and stores nothing, so `angle` and `rotation` always agree\n * @internal\n */\nexport class EulerDegrees implements PointLike3D {\n  constructor(private readonly _radians: ObservableVector3) {}\n\n  get x(): number {\n    return this._radians._x * RAD_TO_DEG;\n  }\n\n  set x(value: number) {\n    this._radians.x = value * DEG_TO_RAD;\n  }\n\n  get y(): number {\n    return this._radians._y * RAD_TO_DEG;\n  }\n\n  set y(value: number) {\n    this._radians.y = value * DEG_TO_RAD;\n  }\n\n  get z(): number {\n    return this._radians._z * RAD_TO_DEG;\n  }\n\n  set z(value: number) {\n    this._radians.z = value * DEG_TO_RAD;\n  }\n\n  public set(x = 0, y = x, z = x): this {\n    this._radians.set(x * DEG_TO_RAD, y * DEG_TO_RAD, z * DEG_TO_RAD);\n\n    return this;\n  }\n\n  public copyFrom(p: PointData3D): this {\n    return this.set(p.x, p.y, p.z);\n  }\n\n  public copyTo<T extends PointLike3D>(p: T): T {\n    return p.set(this.x, this.y, this.z);\n  }\n\n  public equals(p: PointData3D): boolean {\n    return p.x === this.x && p.y === this.y && p.z === this.z;\n  }\n}\n","import type { Observer } from 'pixi.js';\n\nimport type { Matrix3 } from '../matrix/Matrix3';\nimport type { Matrix4 } from '../matrix/Matrix4';\nimport type { Quaternion } from '../rotation/Quaternion';\nimport type { Cylindrical } from '../shapes/Cylindrical';\nimport type { Spherical } from '../shapes/Spherical';\nimport { clamp } from '../utils/clamp';\nimport type { PointData3D } from './PointData3D';\nimport type { PointLike3D } from './PointLike3D';\n\n/**\n * A {@link Vector3} that tells an observer when it changes\n *\n * A node's {@link Container3D#position | position}, {@link Container3D#scale | scale},\n * {@link Container3D#rotation | rotation} and {@link Container3D#origin | origin} use this class,\n * so a change to one updates the node. It has the same methods as {@link Vector3}. Each in-place method\n * notifies the observer at most once, and not at all when no component changed. Given an `out`\n * target, a method writes there and leaves this point and its observer alone.\n * @example\n * ```ts\n * app.ticker.add((ticker) => {\n *   player.position.addScaledVector(velocity, ticker.deltaMS / 1000);\n * });\n * ```\n * @category maths\n * @standard\n */\nexport class ObservableVector3 implements PointLike3D {\n  /** @ignore */\n  public _x = 0;\n  /** @ignore */\n  public _y = 0;\n  /** @ignore */\n  public _z = 0;\n\n  private readonly _observer: Observer<ObservableVector3>;\n\n  /**\n   * The x component; assigning a different value notifies the observer\n   * @example\n   * ```ts\n   * player.position.x += strafeSpeed * dt;\n   * ```\n   */\n  get x(): number {\n    return this._x;\n  }\n\n  /**\n   * Sets the x component\n   * @param value - The new x\n   */\n  set x(value: number) {\n    if (this._x !== value) {\n      this._x = value;\n      this._observer._onUpdate(this);\n    }\n  }\n\n  /**\n   * The y component; assigning a different value notifies the observer\n   * @example\n   * ```ts\n   * if (player.position.y < killPlaneY) respawn(player);\n   * ```\n   */\n  get y(): number {\n    return this._y;\n  }\n\n  /**\n   * Sets the y component\n   * @param value - The new y\n   */\n  set y(value: number) {\n    if (this._y !== value) {\n      this._y = value;\n      this._observer._onUpdate(this);\n    }\n  }\n\n  /**\n   * The z component; assigning a different value notifies the observer\n   * @example\n   * ```ts\n   * crate.position.z = -10;\n   * ```\n   */\n  get z(): number {\n    return this._z;\n  }\n\n  /**\n   * Sets the z component\n   * @param value - The new z\n   */\n  set z(value: number) {\n    if (this._z !== value) {\n      this._z = value;\n      this._observer._onUpdate(this);\n    }\n  }\n\n  /**\n   * Creates a new `ObservableVector3`\n   * @param observer - Observer notified when any component changes\n   * @param x - The x component\n   * @param y - The y component\n   * @param z - The z component\n   */\n  constructor(observer: Observer<ObservableVector3>, x = 0, y = 0, z = 0) {\n    this._x = x;\n    this._y = y;\n    this._z = z;\n    this._observer = observer;\n  }\n\n  /**\n   * Sets the x, y and z components\n   * @example\n   * ```ts\n   * crate.position.set(0, 1, -5);\n   * crate.scale.set(2);\n   * ```\n   * @param x - The x component\n   * @param y - The y component, defaults to `x`\n   * @param z - The z component, defaults to `x`\n   */\n  public set(x = 0, y = x, z = x): this {\n    if (this._x !== x || this._y !== y || this._z !== z) {\n      this._x = x;\n      this._y = y;\n      this._z = z;\n      this._observer._onUpdate(this);\n    }\n\n    return this;\n  }\n\n  /**\n   * Copies x, y, z from the given point into this point\n   * @example\n   * ```ts\n   * loot.position.copyFrom(enemy.position);\n   * ```\n   * @param p - The point to copy from\n   */\n  public copyFrom(p: PointData3D): this {\n    if (this._x !== p.x || this._y !== p.y || this._z !== p.z) {\n      this._x = p.x;\n      this._y = p.y;\n      this._z = p.z;\n      this._observer._onUpdate(this);\n    }\n\n    return this;\n  }\n\n  /**\n   * Copies this point's x, y, z into the given point\n   * @example\n   * ```ts\n   * player.position.copyTo(lastCheckpoint);\n   * ```\n   * @param p - The point to copy into\n   * @returns The given point with values updated\n   */\n  public copyTo<T extends PointLike3D>(p: T): T {\n    p.set(this._x, this._y, this._z);\n\n    return p;\n  }\n\n  /**\n   * Checks whether `x`, `y` and `z` all match `p` exactly, with no tolerance\n   * @example\n   * ```ts\n   * if (!player.position.equals(lastSentPosition)) sendPosition(player.position);\n   * ```\n   * @param p - The point to compare against\n   */\n  public equals(p: PointData3D): boolean {\n    return p.x === this._x && p.y === this._y && p.z === this._z;\n  }\n\n  /**\n   * Creates a copy of this point that notifies `observer`, or this point's own observer when left out\n   *\n   * A clone of a node's `position` that keeps the node as its observer marks the node's transform for\n   * an update whenever the clone changes, though the node hasn't moved. For a plain copy, use\n   * `new Vector3().copyFrom(node.position)`.\n   * @param observer - Optional observer for the clone\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- observer-linked copy; plain copies use Vector3#copyFrom\n  public clone(observer?: Observer<ObservableVector3>): ObservableVector3 {\n    return new ObservableVector3(observer ?? this._observer, this._x, this._y, this._z);\n  }\n\n  /**\n   * Returns a readable string representation of this point\n   * @example\n   * ```ts\n   * console.log(player.position.toString());\n   * ```\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:ObservableVector3 x=${this._x} y=${this._y} z=${this._z}]`;\n  }\n\n  /**\n   * Reads `x`, `y`, `z` from `array` starting at `offset`\n   * @example\n   * ```ts\n   * crates.forEach((crate: Container3D, i: number) => crate.position.fromArray(savedPositions, i * 3));\n   * ```\n   * @param array - The array to read from\n   * @param offset - The index of the first component\n   */\n  public fromArray(array: number[] | Float32Array, offset = 0): this {\n    return this.set(array[offset], array[offset + 1], array[offset + 2]);\n  }\n\n  /**\n   * Writes this point's values into `array` starting at `offset`\n   *\n   * Allocates a new array when one is not supplied.\n   * @example\n   * ```ts\n   * crates.forEach((crate: Container3D, i: number) => crate.position.toArray(savedPositions, i * 3));\n   * ```\n   * @param array - The array to write into\n   * @param offset - The index to write the first component at\n   * @returns The array the values were written into\n   */\n  public toArray<T extends number[] | Float32Array = number[]>(array: T = [] as unknown as T, offset = 0): T {\n    array[offset] = this._x;\n    array[offset + 1] = this._y;\n    array[offset + 2] = this._z;\n\n    return array;\n  }\n\n  /**\n   * Adds `v` to this point\n   * @example\n   * ```ts\n   * rider.position.add(platformMovement);\n   * player.position.add(cameraOffset, cameraTarget);\n   * ```\n   * @param v - The point to add\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public add(v: PointData3D, out: PointLike3D = this): this {\n    const x = this._x + v.x;\n    const y = this._y + v.y;\n    const z = this._z + v.z;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Subtracts `v` from this point\n   * @example\n   * ```ts\n   * target.position.subtract(turret.position, aimDirection);\n   * ```\n   * @param v - The point to subtract\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public subtract(v: PointData3D, out: PointLike3D = this): this {\n    const x = this._x - v.x;\n    const y = this._y - v.y;\n    const z = this._z - v.z;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies each component of this point by the matching component of `v`\n   * @example\n   * ```ts\n   * jelly.scale.multiply({ x: 1.2, y: 0.8, z: 1.2 });\n   * ```\n   * @param v - The point to multiply by\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public multiply(v: PointData3D, out: PointLike3D = this): this {\n    const x = this._x * v.x;\n    const y = this._y * v.y;\n    const z = this._z * v.z;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies each component of this point by the scalar `s`\n   * @example\n   * ```ts\n   * balloon.scale.multiplyScalar(1 + inflateRate * dt);\n   * ```\n   * @param s - The scalar to multiply by\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public multiplyScalar(s: number, out: PointLike3D = this): this {\n    const x = this._x * s;\n    const y = this._y * s;\n    const z = this._z * s;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Divides each component of this point by the matching component of `v`\n   * @example\n   * ```ts\n   * player.position.divide(cellSize, cell);\n   * const column = Math.floor(cell.x);\n   * ```\n   * @param v - The point to divide by\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public divide(v: PointData3D, out: PointLike3D = this): this {\n    const x = this._x / v.x;\n    const y = this._y / v.y;\n    const z = this._z / v.z;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Divides each component of this point by the scalar `s`\n   * @example\n   * ```ts\n   * pickup.scale.divideScalar(2);\n   * ```\n   * @param s - The scalar to divide by\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public divideScalar(s: number, out: PointLike3D = this): this {\n    return this.multiplyScalar(1 / s, out);\n  }\n\n  /**\n   * Adds `v * s` to this point, such as a velocity times the frame time\n   * @example\n   * ```ts\n   * player.position.addScaledVector(velocity, dt);\n   * ```\n   * @param v - The point to scale and add\n   * @param s - The scalar to multiply `v` by\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public addScaledVector(v: PointData3D, s: number, out: PointLike3D = this): this {\n    const x = this._x + v.x * s;\n    const y = this._y + v.y * s;\n    const z = this._z + v.z * s;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Negates each component of this point, mirroring it through the origin\n   * @example\n   * ```ts\n   * reflection.position.copyFrom(player.position).negate();\n   * ```\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public negate(out: PointLike3D = this): this {\n    const x = -this._x;\n    const y = -this._y;\n    const z = -this._z;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Sets each component to the smaller of this point's and `v`'s\n   * @example\n   * ```ts\n   * player.position.min({ x: Infinity, y: ceilingHeight, z: Infinity });\n   * ```\n   * @param v - The point to compare with\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public min(v: PointData3D, out: PointLike3D = this): this {\n    const x = Math.min(this._x, v.x);\n    const y = Math.min(this._y, v.y);\n    const z = Math.min(this._z, v.z);\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Sets each component to the larger of this point's and `v`'s\n   * @example\n   * ```ts\n   * player.position.max({ x: -Infinity, y: floorHeight, z: -Infinity });\n   * ```\n   * @param v - The point to compare with\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public max(v: PointData3D, out: PointLike3D = this): this {\n    const x = Math.max(this._x, v.x);\n    const y = Math.max(this._y, v.y);\n    const z = Math.max(this._z, v.z);\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Clamps each component of this point between the matching components of `min` and `max`\n   *\n   * Assumes `min <= max` componentwise.\n   * @example\n   * ```ts\n   * player.position.clamp(arenaMin, arenaMax);\n   * ```\n   * @param min - The lower bound per component\n   * @param max - The upper bound per component\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public clamp(min: PointData3D, max: PointData3D, out: PointLike3D = this): this {\n    const x = clamp(this._x, min.x, max.x);\n    const y = clamp(this._y, min.y, max.y);\n    const z = clamp(this._z, min.z, max.z);\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Scales this point to unit length, keeping its direction from the origin\n   *\n   * A zero point stays zero.\n   * @example\n   * ```ts\n   * player.position.normalize(surfaceUp);\n   * ```\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public normalize(out: PointLike3D = this): this {\n    const len = Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z) || 1;\n    const inv = 1 / len;\n    const x = this._x * inv;\n    const y = this._y * inv;\n    const z = this._z * inv;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Scales this point so its distance from the origin equals `length`, keeping its direction\n   *\n   * A zero point stays zero.\n   * @example\n   * ```ts\n   * satellite.position.setLength(orbitRadius);\n   * ```\n   * @param length - The target length\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public setLength(length: number, out: PointLike3D = this): this {\n    const len = Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z) || 1;\n    const inv = length / len;\n    const x = this._x * inv;\n    const y = this._y * inv;\n    const z = this._z * inv;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Computes the length of this point, its distance from the origin\n   * @example\n   * ```ts\n   * const altitude = player.position.magnitude() - planetRadius;\n   * ```\n   */\n  public magnitude(): number {\n    return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z);\n  }\n\n  /**\n   * Computes the squared length of this point\n   *\n   * Cheaper than {@link ObservableVector3#magnitude}, since it skips the square root, and enough to\n   * compare lengths.\n   * @example\n   * ```ts\n   * if (ball.position.magnitudeSquared() > arenaRadius * arenaRadius) resetBall();\n   * ```\n   */\n  public magnitudeSquared(): number {\n    return this._x * this._x + this._y * this._y + this._z * this._z;\n  }\n\n  /**\n   * Computes the distance from this point to `v`\n   * @example\n   * ```ts\n   * const distanceToExit = player.position.distanceTo(exit.position);\n   * ```\n   * @param v - The point to measure to\n   */\n  public distanceTo(v: PointData3D): number {\n    return Math.sqrt(this.distanceToSquared(v));\n  }\n\n  /**\n   * Computes the squared distance from this point to `v`\n   *\n   * Cheaper than {@link ObservableVector3#distanceTo} and enough to compare distances.\n   * @example\n   * ```ts\n   * if (player.position.distanceToSquared(coin.position) < pickupRadius * pickupRadius) collect(coin);\n   * ```\n   * @param v - The point to measure to\n   */\n  public distanceToSquared(v: PointData3D): number {\n    const dx = this._x - v.x;\n    const dy = this._y - v.y;\n    const dz = this._z - v.z;\n\n    return dx * dx + dy * dy + dz * dz;\n  }\n\n  /**\n   * Computes the dot product of this point and `v`\n   * @example\n   * ```ts\n   * const distanceAlongTrack = car.position.dot(trackDirection);\n   * ```\n   * @param v - The other point\n   */\n  public dot(v: PointData3D): number {\n    return this._x * v.x + this._y * v.y + this._z * v.z;\n  }\n\n  /**\n   * Computes the angle between this point and `v`, both seen from the origin\n   *\n   * Returns π/2 when either has zero length.\n   * @example\n   * ```ts\n   * const distanceOverSurface = player.position.angleTo(base.position) * planetRadius;\n   * ```\n   * @param v - The other point\n   * @returns The angle in radians, from 0 to π\n   */\n  public angleTo(v: PointData3D): number {\n    const denominator = Math.sqrt(this.magnitudeSquared() * (v.x * v.x + v.y * v.y + v.z * v.z));\n    if (denominator === 0) return Math.PI / 2;\n    const theta = this.dot(v) / denominator;\n\n    return Math.acos(clamp(theta, -1, 1));\n  }\n\n  /**\n   * Computes the cross product `this × v`, a vector at right angles to both\n   * @example\n   * ```ts\n   * player.position.cross(planetAxis, travelDirection).normalize();\n   * ```\n   * @param v - The other point\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public cross(v: PointData3D, out: PointLike3D = this): this {\n    const ax = this._x;\n    const ay = this._y;\n    const az = this._z;\n    const bx = v.x;\n    const by = v.y;\n    const bz = v.z;\n    const x = ay * bz - az * by;\n    const y = az * bx - ax * bz;\n    const z = ax * by - ay * bx;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies this point by the 3x3 matrix `m`\n   * @example\n   * ```ts\n   * satellite.position.applyMatrix3(orbitTilt);\n   * ```\n   * @param m - The matrix to apply\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public applyMatrix3(m: Matrix3, out: PointLike3D = this): this {\n    const ex = this._x;\n    const ey = this._y;\n    const ez = this._z;\n    const e = m.elements;\n    const x = e[0] * ex + e[3] * ey + e[6] * ez;\n    const y = e[1] * ex + e[4] * ey + e[7] * ez;\n    const z = e[2] * ex + e[5] * ey + e[8] * ez;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Transforms this point by `m`, translation included, then divides by the resulting `w`\n   *\n   * {@link Vector3#applyMatrix4} explains when the divide matters.\n   * @example\n   * ```ts\n   * enemy.position.applyMatrix4(camera.viewProjection, ndc);\n   * const onScreen = Math.abs(ndc.x) <= 1 && Math.abs(ndc.y) <= 1 && Math.abs(ndc.z) <= 1;\n   * ```\n   * @param m - The matrix to apply\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public applyMatrix4(m: Matrix4, out: PointLike3D = this): this {\n    const ex = this._x;\n    const ey = this._y;\n    const ez = this._z;\n    const e = m.elements;\n    const w = 1 / (e[3] * ex + e[7] * ey + e[11] * ez + e[15]);\n    const x = (e[0] * ex + e[4] * ey + e[8] * ez + e[12]) * w;\n    const y = (e[1] * ex + e[5] * ey + e[9] * ez + e[13]) * w;\n    const z = (e[2] * ex + e[6] * ey + e[10] * ez + e[14]) * w;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Transforms this point by `m`, translation included, without the divide\n   * {@link ObservableVector3#applyMatrix4} does\n   *\n   * Cheaper, and correct for any transform that doesn't project, such as a node's world transform.\n   * @example\n   * ```ts\n   * muzzle.position.applyAffineMatrix4(gun.worldTransform, muzzleWorldPosition);\n   * ```\n   * @param m - The matrix to apply\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public applyAffineMatrix4(m: Matrix4, out: PointLike3D = this): this {\n    const ex = this._x;\n    const ey = this._y;\n    const ez = this._z;\n    const e = m.elements;\n    const x = e[0] * ex + e[4] * ey + e[8] * ez + e[12];\n    const y = e[1] * ex + e[5] * ey + e[9] * ez + e[13];\n    const z = e[2] * ex + e[6] * ey + e[10] * ez + e[14];\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Rotates this point around the origin by the unit {@link Quaternion} `q`\n   * @example\n   * ```ts\n   * chaseCamera.position.copyFrom(followOffset).applyQuaternion(car.quaternion).add(car.position);\n   * ```\n   * @param q - The unit quaternion to rotate by\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  public applyQuaternion(q: Quaternion, out: PointLike3D = this): this {\n    const ex = this._x;\n    const ey = this._y;\n    const ez = this._z;\n    const qx = q.x;\n    const qy = q.y;\n    const qz = q.z;\n    const qw = q.w;\n\n    const ix = qw * ex + qy * ez - qz * ey;\n    const iy = qw * ey + qz * ex - qx * ez;\n    const iz = qw * ez + qx * ey - qy * ex;\n    const iw = -qx * ex - qy * ey - qz * ez;\n\n    const x = ix * qw - iw * qx - iy * qz + iz * qy;\n    const y = iy * qw - iw * qy - iz * qx + ix * qz;\n    const z = iz * qw - iw * qz - ix * qy + iy * qx;\n\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Turns this point, read as a direction, by the rotation and scale in `m`, ignoring its translation,\n   * then normalizes it\n   * @param m - The matrix whose rotation to apply\n   * @param out - The target to write the result into, defaults to this point\n   * @returns The point the result was written into\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- direction math; see Vector3#transformDirection\n  public transformDirection(m: Matrix4, out: PointLike3D = this): this {\n    const ex = this._x;\n    const ey = this._y;\n    const ez = this._z;\n    const e = m.elements;\n    const tx = e[0] * ex + e[4] * ey + e[8] * ez;\n    const ty = e[1] * ex + e[5] * ey + e[9] * ez;\n    const tz = e[2] * ex + e[6] * ey + e[10] * ez;\n    const len = Math.sqrt(tx * tx + ty * ty + tz * tz) || 1;\n    const inv = 1 / len;\n    const x = tx * inv;\n    const y = ty * inv;\n    const z = tz * inv;\n    if (out === this) return this.set(x, y, z);\n    out.x = x;\n    out.y = y;\n    out.z = z;\n\n    return out as this;\n  }\n\n  /**\n   * Sets this point to the position the {@link Spherical} coordinate `s` describes\n   *\n   * {@link Vector3#setFromSpherical} describes the angles.\n   * @example\n   * ```ts\n   * orbit.theta += turnSpeed * dt;\n   * camera.position.setFromSpherical(orbit).add(target.position);\n   * ```\n   * @param s - The spherical coordinate to convert\n   */\n  public setFromSpherical(s: Spherical): this {\n    const sinPhiRadius = Math.sin(s.phi) * s.radius;\n\n    return this.set(sinPhiRadius * Math.sin(s.theta), Math.cos(s.phi) * s.radius, sinPhiRadius * Math.cos(s.theta));\n  }\n\n  /**\n   * Sets this point to the position the {@link Cylindrical} coordinate `c` describes\n   *\n   * {@link Vector3#setFromCylindrical} describes the angle and height.\n   * @example\n   * ```ts\n   * const slot = new Cylindrical(towerRadius, 0, 2);\n   *\n   * torches.forEach((torch: Mesh3D, i: number) => {\n   *   slot.theta = (i / torches.length) * Math.PI * 2;\n   *   torch.position.setFromCylindrical(slot);\n   * });\n   * ```\n   * @param c - The cylindrical coordinate to convert\n   */\n  public setFromCylindrical(c: Cylindrical): this {\n    return this.set(c.radius * Math.sin(c.theta), c.y, c.radius * Math.cos(c.theta));\n  }\n\n  /**\n   * Reads the first three values of column `index` of `m` into this point\n   *\n   * In a transform, column 3 is the translation and columns 0 to 2 are the X, Y and Z axes, scaled.\n   * @example\n   * ```ts\n   * marker.position.setFromMatrixColumn(target.worldTransform, 3);\n   * ```\n   * @param m - The matrix to read from\n   * @param index - The column index, `0` to `3`\n   */\n  public setFromMatrixColumn(m: Matrix4, index: number): this {\n    return this.fromArray(m.elements, index * 4);\n  }\n}\n","import type { BaseDestroyOptions, TextureDestroyOptions, TypeOrBool } from 'pixi.js';\n\n/**\n * What a 3D node's `destroy()` takes down with it\n *\n * The flags are pixi.js's `children`, `texture` and `textureSource`, plus `geometry` and\n * `material` for meshes. Each defaults to `false`, since children, geometries, materials and\n * textures are often shared. `true` sets every flag, so it also destroys resources other nodes\n * still use. A node passes the same options to the children it destroys.\n *\n * `texture` frees the textures of the materials the call destroys, so on a {@link Mesh3D},\n * `texture` alone frees nothing and `material` alone keeps the textures. On a {@link Sprite3D},\n * `texture` always frees the sprite's texture. `textureSource` also frees the sources behind those\n * textures and, as in pixi.js, does nothing alone.\n *\n * What a node made for itself always goes, whatever the flags: a {@link View3D}'s GPU resources,\n * a {@link BatchedMesh3D}'s batch, the material a {@link Sprite3D} built for its texture.\n * @example\n * ```ts\n * sprite.destroy({ texture: true });               // the sprite, the material it built, its texture\n * mesh.destroy({ geometry: true, material: true }); // keeps the material's textures\n * model.destroy(true);                               // everything it can reach, shared or not\n * ```\n * @category scene\n * @standard\n */\nexport type Destroy3DOptions = TypeOrBool<\n  BaseDestroyOptions &\n    TextureDestroyOptions & {\n      /**\n       * Destroy each destroyed mesh's {@link Geometry3D} and its GPU buffers\n       * @default false\n       * @example\n       * ```ts\n       * mesh.destroy({ geometry: true });\n       * ```\n       */\n      geometry?: boolean;\n      /**\n       * Destroy each destroyed mesh's {@link BaseMaterial3D}; its textures follow `texture` /\n       * `textureSource`\n       * @default false\n       * @example\n       * ```ts\n       * mesh.destroy({ material: true, texture: true });\n       * ```\n       */\n      material?: boolean;\n    }\n>;\n\n/** @internal */\nexport function resolveDestroy3DFlag(\n  options: Destroy3DOptions | undefined,\n  key: keyof Exclude<Destroy3DOptions, boolean>,\n): boolean {\n  if (typeof options === 'boolean') return options;\n  return options?.[key] ?? false;\n}\n","import { Matrix4 } from '../../math/matrix/Matrix4';\nimport { Box } from '../../math/shapes/Box';\nimport type { Container3D } from '../Container3D';\nimport type { Mesh3D } from '../Mesh3D';\n\nconst tempBox = new Box();\n\n/** One scratch matrix per tree depth, grown on demand, so a walk allocates nothing once warm */\nconst matrixStack: Matrix4[] = [];\n\n/**\n * Measures as {@link Container3D#getLocalBounds} documents\n * @returns `out`\n * @internal\n */\nexport function getLocalBounds3D(container: Container3D, out: Box, skipHidden = true): Box {\n  out.makeEmpty();\n\n  addBounds(container, out, null, 0, skipHidden);\n\n  if (out.isEmpty()) {\n    out.min.set(0, 0, 0);\n    out.max.set(0, 0, 0);\n  }\n\n  return out;\n}\n\nfunction addBounds(container: Container3D, out: Box, matrix: Matrix4 | null, depth: number, skipHidden: boolean): void {\n  const boundsVolume = container.boundsVolume;\n\n  if (boundsVolume) {\n    unionTransformed(boundsVolume, out, matrix);\n\n    return;\n  }\n\n  const geometry = (container as Mesh3D).geometry;\n\n  if (geometry) unionTransformed(geometry.bounds3D, out, matrix);\n\n  const children = container.children;\n\n  if (children.length === 0) return;\n\n  const childMatrix = (matrixStack[depth] ??= new Matrix4());\n\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n\n    if (skipHidden && !child.visible) continue;\n\n    child.updateLocalTransform();\n\n    if (matrix) childMatrix.copyFrom(matrix).multiply(child.localTransform);\n    else childMatrix.copyFrom(child.localTransform);\n\n    addBounds(child, out, childMatrix, depth + 1, skipHidden);\n  }\n}\n\nfunction unionTransformed(box: Box, out: Box, matrix: Matrix4 | null): void {\n  out.union(matrix ? box.applyMatrix4(matrix, tempBox) : box);\n}\n","import { Matrix4 } from '../../math/matrix/Matrix4';\nimport type { Container3D } from '../Container3D';\n\nconst _scratch = new Matrix4();\n/**\n * Pooled so the walk allocates nothing; each call nulls the slots past its depth so removed subtrees can be collected\n */\nconst _ancestors: (Container3D | null)[] = [];\n\n/**\n * Computes the world transform of `target.parent` into `out`, without writing any stored `worldTransform`\n * @returns `out`\n * @internal\n */\nexport function updateTransformBackwards3D(target: Container3D, out: Matrix4): Matrix4 {\n  let depth = 0;\n  let cur = target.parent;\n  while (cur) {\n    _ancestors[depth++] = cur;\n    cur = cur.parent;\n  }\n\n  for (let i = depth; _ancestors[i]; i++) {\n    _ancestors[i] = null;\n  }\n\n  if (depth === 0) return out.identity();\n\n  const root = _ancestors[depth - 1]!;\n  if (root._localTransformDirty) {\n    root.updateLocalTransform();\n    root._localTransformDirty = false;\n  }\n  out.copyFrom(root.localTransform);\n\n  let src = out;\n  let dst = _scratch;\n  for (let i = depth - 2; i >= 0; i--) {\n    const ancestor = _ancestors[i]!;\n    if (ancestor._localTransformDirty) {\n      ancestor.updateLocalTransform();\n      ancestor._localTransformDirty = false;\n    }\n    Matrix4.multiplyAffine(\n      dst.elements as Float32Array,\n      0,\n      src.elements as Float32Array,\n      0,\n      ancestor.localTransform.elements as Float32Array,\n      0,\n    );\n    const tmp = src;\n    src = dst;\n    dst = tmp;\n  }\n\n  if (src !== out) out.copyFrom(src);\n\n  return out;\n}\n","import { assignWithIgnore, DEG_TO_RAD, EventEmitter } from 'pixi.js';\n\nimport { Matrix4 } from '../math/matrix/Matrix4';\nimport { ObservableQuaternion } from '../math/rotation/ObservableQuaternion';\nimport { Quaternion } from '../math/rotation/Quaternion';\nimport type { QuaternionData } from '../math/rotation/Quaternion';\nimport { Box } from '../math/shapes/Box';\nimport { EulerDegrees } from '../math/vector/EulerDegrees';\nimport { ObservableVector3 } from '../math/vector/ObservableVector3';\nimport type { PointData3D } from '../math/vector/PointData3D';\nimport type { PointLike3D } from '../math/vector/PointLike3D';\nimport { Vector3 } from '../math/vector/Vector3';\nimport type { Destroy3DOptions } from '../utils/Destroy3DOptions';\nimport { resolveDestroy3DFlag } from '../utils/Destroy3DOptions';\nimport { getLocalBounds3D } from './utils/getLocalBounds3D';\nimport { updateTransformBackwards3D } from './utils/updateTransformBackwards3D';\nimport type { View3D } from './View3D';\n\ndeclare global {\n  namespace PixiMixins {\n    /**\n     * Augmentation hook for members mixed into {@link Container3D}\n     *\n     * Declare the added members here and add their implementation with pixi.js's\n     * `extensions.mixin(Container3D, myMixin)`, as pixi's 2D `Container` does.\n     */\n    interface Container3D {}\n    /** Augmentation hook for extra {@link Container3DOptions} members */\n    interface Container3DOptions {}\n    /** Augmentation hook for extra {@link Container3DEvents} event signatures */\n    interface Container3DEvents {}\n  }\n}\n\nlet UID = 0;\n\nconst _lookAtParentWorld = new Matrix4();\nconst _lookAtPos = new Vector3();\nconst _lookAtMatrix = new Matrix4();\nconst _lookAtWorldQuat = new Quaternion();\nconst _lookAtParentQuat = new Quaternion();\nconst _lookAtDefaultUp: PointData3D = { x: 0, y: 1, z: 0 };\n\nconst _originOffset = new Vector3();\n\nconst _convertMatrix = new Matrix4();\nconst _convertVec = new Vector3();\nconst _convertFromVec = new Vector3();\n\nconst _reparentChildWorld = new Matrix4();\nconst _reparentParentWorld = new Matrix4();\nconst _reparentPos = new Vector3();\nconst _reparentScale = new Vector3();\nconst _reparentQuat = new Quaternion();\n\nconst _measureBox = new Box();\n\nfunction scaleForSize(size: number, localSize: number, currentScale: number): number {\n  const sign = Math.sign(currentScale) || 1;\n\n  return localSize !== 0 ? (size / localSize) * sign : sign;\n}\n\n/** Returns `false` for an unlabelled node first, since a pattern would test the string `'null'` */\nfunction labelMatches(value: string | null, label: string | RegExp): boolean {\n  if (value === null) return false;\n\n  return value === label || (label instanceof RegExp && label.test(value));\n}\n\n/**\n * Width, height and depth of a {@link Container3D}, as returned by {@link Container3D.getSize}\n * @example\n * ```ts\n * const { width, height, depth }: Size3D = model.getSize();\n *\n * crate.setSize({ width: 2, height: 1, depth: 1 });\n * ```\n * @category scene\n * @standard\n */\nexport interface Size3D {\n  /** Extent along x */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- result field, read back from getSize\n  width: number;\n  /** Extent along y */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- result field, read back from getSize\n  height: number;\n  /** Extent along z */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- result field, read back from getSize\n  depth: number;\n}\n\n/**\n * Events a {@link Container3D} emits, with the same names and payloads as pixi's 2D `Container`\n *\n * Listen with `on`, `once` and `off`. The pointer events, such as `pointerdown` and `click`, are\n * typed here too.\n * @example\n * ```ts\n * level.on('childAdded', (child) => colliders.add(child));\n * level.on('childRemoved', (child) => colliders.delete(child));\n * ```\n * @category scene\n * @standard\n */\nexport interface Container3DEvents extends PixiMixins.Container3DEvents {\n  /**\n   * Emitted on a child after it joins a parent; passes the parent\n   * @example\n   * ```ts\n   * enemy.on('added', () => enemyCount++);\n   * ```\n   */\n  added: [container: Container3D];\n  /**\n   * Emitted on a child after it leaves its parent; passes the former parent\n   * @example\n   * ```ts\n   * enemy.on('removed', () => enemyCount--);\n   * ```\n   */\n  removed: [container: Container3D];\n  /**\n   * Emitted on a parent after it gains a child; passes the child, this parent and the child's\n   * index\n   * @example\n   * ```ts\n   * level.on('childAdded', (child) => colliders.add(child));\n   * ```\n   */\n  childAdded: [child: Container3D, container: Container3D, index: number];\n  /**\n   * Emitted on a parent after it loses a child; passes the child, this parent and an index\n   *\n   * From `removeChild`, the index is where the child was. From `removeChildren`, it is the child's\n   * place in the returned array, as in pixi.\n   * @example\n   * ```ts\n   * level.on('childRemoved', (child) => colliders.delete(child));\n   * ```\n   */\n  childRemoved: [child: Container3D, container: Container3D, index: number];\n  /**\n   * Emitted once {@link Container3D.destroy} has emptied and detached this container; passes the\n   * container\n   * @example\n   * ```ts\n   * crate.once('destroyed', () => colliders.delete(crate));\n   * ```\n   */\n  destroyed: [container: Container3D];\n  /**\n   * Emitted when {@link Container3D.visible} changes value; passes the new value\n   * @example\n   * ```ts\n   * door.on('visibleChanged', (visible) => {\n   *   doorCollider.enabled = visible;\n   * });\n   * ```\n   */\n  visibleChanged: [visible: boolean];\n}\n\n/**\n * Constructor options for {@link Container3D}, the 3D counterpart of pixi.js's `ContainerOptions`\n *\n * A key set to `undefined` is skipped. The rest apply in the order you write them, as if assigned\n * afterwards, so `{ position, x }` ends with `x`, and of `rotation`, `angle` and `quaternion` the\n * last one wins. `children`, `hitVolume`, `width`, `height` and `depth` wait until after the rest,\n * in that order, so a `'box'` hit volume and the sizes measure the children.\n *\n * The interaction options, such as `eventMode`, `cursor` and the `on*` handlers, are accepted\n * too, and take effect once the node joins a {@link View3D}'s scene.\n * @example\n * ```ts\n * const arm = new Container3D({\n *   label: 'arm',\n *   position: { x: 0, y: 1, z: 0 },\n *   rotation: { x: 0, y: Math.PI / 2, z: 0 },\n *   scale: 2,\n *   children: [hand],\n *   parent: body,\n *   eventMode: 'static',\n * });\n * ```\n * @see {@link Federated3DOptions} For the interaction members and their semantics.\n * @category scene\n * @standard\n */\nexport interface Container3DOptions extends PixiMixins.Container3DOptions {\n  /**\n   * Name to find the node by; see {@link Container3D#label}\n   * @default null\n   * @example\n   * ```ts\n   * const turret = new Container3D({ label: 'turret' });\n   * ```\n   */\n  label?: string | null;\n  /**\n   * Local position\n   * @default { x: 0, y: 0, z: 0 }\n   * @example\n   * ```ts\n   * const lamp = new Container3D({ position: { x: 0, y: 3, z: 0 } });\n   * ```\n   */\n  position?: PointData3D;\n  /**\n   * Local position on x; the same as `position.x`\n   * @example\n   * ```ts\n   * const left = new Container3D({ x: -2 });\n   * ```\n   */\n  x?: number;\n  /**\n   * Local position on y; the same as `position.y`\n   * @example\n   * ```ts\n   * const shelf = new Container3D({ y: 1.2 });\n   * ```\n   */\n  y?: number;\n  /**\n   * Local position on z; the same as `position.z`\n   * @example\n   * ```ts\n   * const back = new Container3D({ z: -5 });\n   * ```\n   */\n  z?: number;\n  /**\n   * Local scale; a number scales all three axes\n   * @default 1\n   * @example\n   * ```ts\n   * const giant = new Container3D({ scale: 3 });\n   * ```\n   */\n  scale?: PointData3D | number;\n  /**\n   * Local rotation as Euler angles in radians: turns around Z, then Y, then X, each about the parent's axes\n   * @default { x: 0, y: 0, z: 0 }\n   * @example\n   * ```ts\n   * const turned = new Container3D({ rotation: { x: 0, y: Math.PI / 2, z: 0 } });\n   * ```\n   */\n  rotation?: PointData3D;\n  /**\n   * Local rotation as Euler angles in degrees: turns around Z, then Y, then X, each about the parent's axes\n   * @default { x: 0, y: 0, z: 0 }\n   * @example\n   * ```ts\n   * const turned = new Container3D({ angle: { x: 0, y: 90, z: 0 } });\n   * ```\n   */\n  angle?: PointData3D;\n  /**\n   * Local rotation as a unit quaternion\n   * @default { x: 0, y: 0, z: 0, w: 1 }\n   * @example\n   * ```ts\n   * const turned = new Container3D({ quaternion: { x: 0, y: Math.SQRT1_2, z: 0, w: Math.SQRT1_2 } });\n   * ```\n   */\n  quaternion?: QuaternionData;\n  /**\n   * Point in local space that rotation and scale happen around; see {@link Container3D#origin}\n   * @default { x: 0, y: 0, z: 0 }\n   * @example\n   * ```ts\n   * const hinge = new Container3D({ origin: { x: 0.5, y: 0, z: 0 } });\n   * ```\n   */\n  origin?: PointData3D | number;\n  /**\n   * Whether this node and its descendants draw\n   * @default true\n   * @example\n   * ```ts\n   * const hiddenUntilSpawn = new Container3D({ visible: false });\n   * ```\n   */\n  visible?: boolean;\n  /**\n   * Target width along x; sets `scale.x` from the local bounds of the node and its `children`\n   * @example\n   * ```ts\n   * const crate = new Container3D({ children: [crateMesh], width: 2 });\n   * ```\n   */\n  width?: number;\n  /**\n   * Target height along y; sets `scale.y` from the local bounds of the node and its `children`\n   * @example\n   * ```ts\n   * const tree = new Container3D({ children: [treeMesh], height: 6 });\n   * ```\n   */\n  height?: number;\n  /**\n   * Target depth along z; sets `scale.z` from the local bounds of the node and its `children`\n   * @example\n   * ```ts\n   * const bench = new Container3D({ children: [benchMesh], depth: 0.5 });\n   * ```\n   */\n  depth?: number;\n  /**\n   * Fixed local-space box used in place of this node's subtree when measuring bounds; see\n   * {@link Container3D.boundsVolume}\n   * @example\n   * ```ts\n   * const swarm = new Container3D({ boundsVolume: new Box(new Vector3(-10, 0, -10), new Vector3(10, 5, 10)) });\n   * ```\n   */\n  boundsVolume?: Box;\n  /**\n   * Children to add, in order\n   * @example\n   * ```ts\n   * const car = new Container3D({ children: [body, frontWheels, rearWheels] });\n   * ```\n   */\n  children?: Container3D[];\n  /**\n   * Parent to add this node to, once everything else is applied\n   * @example\n   * ```ts\n   * const crate = new Container3D({ label: 'crate', parent: view.root });\n   * ```\n   */\n  parent?: Container3D;\n}\n\n/**\n * Keys the constructor applies after the rest: `children` and `parent` go through `addChild`, and\n * `hitVolume: 'box'` and the sizes measure the children\n */\nconst OPTIONS_APPLIED_LATER: Record<string, boolean> = {\n  children: true,\n  hitVolume: true,\n  parent: true,\n  width: true,\n  height: true,\n  depth: true,\n};\n\n// oxlint-disable-next-line pixijs-3d/require-export-jsdoc, pixijs-3d/require-member-api-doc\nexport interface Container3D extends PixiMixins.Container3D {}\n\n/** `{} & string` keys rather than `string`, which would swallow the literal keys of the known events */\ntype AnyEvent = {\n  // oxlint-disable-next-line typescript/no-explicit-any -- custom event payloads are untyped, as on pixi's Container\n  [K: ({} & string) | ({} & symbol)]: any;\n};\n\n/**\n * A node in a 3D scene, the 3D counterpart of pixi.js's `Container`\n *\n * It has a local transform, made of {@link Container3D.position | position},\n * {@link Container3D.scale | scale} and a rotation set through either\n * {@link Container3D.rotation | rotation} or {@link Container3D.quaternion | quaternion}, plus a\n * parent and children. Put it under a view's {@link View3D.root | root}, at any depth, and the\n * view draws the meshes and uses the lights in its subtree.\n *\n * Changing a transform only marks the node. The view works out world transforms once per frame,\n * however many changes you make. The child methods and events match pixi's `Container`.\n * @example\n * ```ts\n * const arm = new Container3D();\n * arm.position.set(0, 1, 0);\n *\n * const hand = new Container3D();\n * hand.scale.set(2);\n * arm.addChild(hand);\n *\n * arm.lookAt({ x: 0, y: 0, z: 0 });\n * ```\n * @see {@link Container3DOptions} For the constructor options.\n * @category scene\n * @standard\n */\nexport class Container3D extends EventEmitter<Container3DEvents & AnyEvent> {\n  /**\n   * Unique id, assigned at construction\n   * @advanced\n   */\n  public readonly uid: number = UID++;\n\n  /**\n   * Name to find the node by, with {@link Container3D.getChildByLabel | getChildByLabel}\n   *\n   * Animation tracks find their target by it too. A plain `Container3D` starts with `null`;\n   * built-in subclasses such as `Mesh3D` start with their class name.\n   * @example\n   * ```ts\n   * turret.label = 'turret';\n   * tank.getChildByLabel('turret', true)?.lookAt(target);\n   * ```\n   */\n  public label: string | null = null;\n\n  /**\n   * Whether the next {@link Container3D.updateLocalTransform} rebuilds the quaternion from\n   * `rotation`; that call clears it, so copy it first\n   * @internal\n   */\n  public rotationDirty = false;\n\n  /**\n   * Local transform matrix, built from the position, rotation, scale and\n   * {@link Container3D.origin | origin}\n   *\n   * It catches up with changes in the view's transform pass, or when you call\n   * {@link Container3D.updateLocalTransform | updateLocalTransform}. Read it, but change the\n   * components instead: the next rebuild overwrites it.\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- rebuilt by the view, never set by hand\n  public localTransform: Matrix4 = new Matrix4();\n  /**\n   * World transform: the parent's world transform times this node's\n   * {@link Container3D.localTransform | localTransform}\n   *\n   * The view updates it once per frame, before drawing, for visible nodes only, and not at all\n   * while the view holds no mesh. So it can be out of date after a change this frame or while the\n   * node or an ancestor is hidden, and a node outside any view keeps the identity matrix.\n   * {@link Container3D.getGlobalTransform | getGlobalTransform} always works out a current one.\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- rebuilt by the view, never set by hand\n  public worldTransform: Matrix4 = new Matrix4();\n\n  private readonly _position = new ObservableVector3(this, 0, 0, 0);\n  private readonly _scale = new ObservableVector3(this, 1, 1, 1);\n  private readonly _rotation = new ObservableVector3(this, 0, 0, 0);\n  private readonly _quaternion = new ObservableQuaternion(this, 0, 0, 0, 1);\n  private _angle: EulerDegrees | null = null;\n  /** `null` until {@link Container3D.origin} is first read, so a node without one skips the origin maths */\n  protected _origin: ObservableVector3 | null = null;\n\n  /**\n   * Child nodes\n   *\n   * Their order doesn't decide what draws first. Read the array, but change it through\n   * {@link Container3D.addChild | addChild} and {@link Container3D.removeChild | removeChild}.\n   * To visit the whole subtree, use {@link Container3D.traverse | traverse}.\n   * @example\n   * ```ts\n   * for (const child of group.children) child.visible = false;\n   * ```\n   */\n  public children: Container3D[] = [];\n\n  /** Parent node, or `null` for a node with none, such as a view's root */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- set by addChild and removeChild, never by hand\n  public parent: Container3D | null = null;\n\n  /** @internal */\n  public _view3d: View3D | null = null;\n\n  /**\n   * A fixed local-space box measured in place of this container and its subtree, or `null` to\n   * measure the geometry\n   *\n   * Set one on a large subtree whose extent you already know, such as a level chunk, to skip walking\n   * it. {@link Container3D.getLocalBounds | getLocalBounds} and the size members read it. It's pixi's\n   * `boundsArea`; it doesn't change culling.\n   * @example\n   * ```ts\n   * swarm.boundsVolume = new Box(new Vector3(-10, 0, -10), new Vector3(10, 5, 10));\n   * ```\n   */\n  public boundsVolume: Box | null = null;\n\n  /** Whether {@link Container3D.destroy | destroy} has run, as in pixi's `Container` */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only state\n  public destroyed = false;\n\n  /** Set while this node waits for a transform pass, so it's queued once @internal */\n  public didChange = false;\n\n  /** @internal */\n  public _worldTransformDirty = true;\n\n  /** @internal */\n  public _worldVisibleDirty = true;\n\n  /** @internal */\n  public _localTransformDirty = false;\n\n  /** 0 or 1 rather than a boolean, so the visibility pass multiplies instead of branching @internal */\n  public _visible = 1;\n\n  /** @internal */\n  public _worldVisible = 1;\n\n  /** @internal */\n  public _updateTick = -1;\n\n  /** @internal */\n  public _relativeSceneDepth = 0;\n\n  /**\n   * Whether the scene update rewrites this node's whole store row; a move or a visibility flip\n   * doesn't need it, since the transform pass writes those lanes\n   * @internal\n   */\n  public _storeDirty = false;\n\n  /** Bumped each time {@link Container3D.worldTransform} is recomputed @internal */\n  public _worldTransformId = 0;\n\n  /** @internal */\n  protected _lookAtForwardIsPositiveZ: boolean = true;\n\n  constructor(options: Container3DOptions = {}) {\n    super();\n\n    assignWithIgnore(this as Container3DOptions, options, OPTIONS_APPLIED_LATER);\n\n    const { children, hitVolume, width, height, depth, parent } = options;\n\n    if (children) {\n      for (let i = 0; i < children.length; i++) this.addChild(children[i]);\n    }\n\n    if (hitVolume !== undefined) this.hitVolume = hitVolume;\n\n    if (width !== undefined) this.width = width;\n    if (height !== undefined) this.height = height;\n    if (depth !== undefined) this.depth = depth;\n\n    parent?.addChild(this);\n  }\n\n  /**\n   * Local position\n   *\n   * Assigning copies the values in; the object itself never changes.\n   * @example\n   * ```ts\n   * node.position.set(0, 1, 0);\n   * node.position = { x: 0, y: 1, z: 0 };\n   * ```\n   */\n  get position(): ObservableVector3 {\n    return this._position;\n  }\n\n  /**\n   * Sets the local position\n   * @param value - The new position\n   */\n  set position(value: PointData3D) {\n    this._position.copyFrom(value);\n  }\n\n  /**\n   * Local scale\n   *\n   * Assigning copies the values in, and a single number scales all three axes; the object itself\n   * never changes.\n   * @example\n   * ```ts\n   * node.scale.set(2, 1, 1);\n   * node.scale = 2; // uniform\n   * ```\n   */\n  get scale(): ObservableVector3 {\n    return this._scale;\n  }\n\n  /**\n   * Sets the local scale; a number sets all three axes\n   * @param value - The new scale\n   */\n  set scale(value: PointData3D | number) {\n    if (typeof value === 'number') this._scale.set(value);\n    else this._scale.copyFrom(value);\n  }\n\n  /**\n   * Local rotation as Euler angles in radians: turns around Z, then Y, then X, each about the parent's axes\n   *\n   * The node keeps both this and {@link Container3D.quaternion | quaternion}, and whichever you\n   * set last is the rotation in use. Assigning copies the values in. Writing unchanged values to\n   * either through a component, `set` or `copyFrom` doesn't switch which one is in use; assign it\n   * whole.\n   * @example\n   * ```ts\n   * node.rotation.y = Math.PI / 2;\n   * node.rotation = { x: 0, y: Math.PI / 2, z: 0 };\n   * ```\n   */\n  get rotation(): ObservableVector3 {\n    return this._rotation;\n  }\n\n  /**\n   * Sets the Euler rotation and makes it the rotation in use, even when the values are unchanged\n   * @param value - The new Euler angles, in radians\n   */\n  set rotation(value: PointData3D) {\n    this._rotation.copyFrom(value);\n\n    if (!this.rotationDirty) this._onUpdate(this._rotation);\n  }\n\n  /**\n   * {@link Container3D.rotation | rotation} in degrees, as in pixi.js\n   *\n   * It reads and writes `rotation`, so the two always agree. Reading converts back from radians, so\n   * a value can come back a hair off, such as 30 as 29.999999999999996; compare with a tolerance.\n   * @example\n   * ```ts\n   * node.angle.y = 90; // same as node.rotation.y = Math.PI / 2\n   * node.angle = { x: 0, y: 45, z: 0 };\n   * ```\n   */\n  get angle(): PointLike3D {\n    return (this._angle ??= new EulerDegrees(this._rotation));\n  }\n\n  /**\n   * Sets the Euler rotation and makes it the rotation in use, even when the values are unchanged\n   * @param value - The new Euler angles, in degrees\n   */\n  set angle(value: PointData3D) {\n    this._rotation.set(value.x * DEG_TO_RAD, value.y * DEG_TO_RAD, value.z * DEG_TO_RAD);\n\n    if (!this.rotationDirty) this._onUpdate(this._rotation);\n  }\n\n  /**\n   * Local rotation as a unit quaternion; see {@link Container3D.rotation | rotation} for which of\n   * the two is in use\n   *\n   * Assigning copies the values in, so `node.quaternion = other.quaternion` doesn't link the two.\n   * @example\n   * ```ts\n   * node.quaternion = other.quaternion;\n   * node.quaternion = { x: 0, y: Math.SQRT1_2, z: 0, w: Math.SQRT1_2 };\n   * ```\n   */\n  get quaternion(): ObservableQuaternion {\n    return this._quaternion;\n  }\n\n  /**\n   * Sets the quaternion and makes it the rotation in use, even when the values are unchanged\n   * @param value - The new rotation, as a unit quaternion\n   */\n  set quaternion(value: QuaternionData) {\n    this._quaternion.copyFrom(value);\n\n    if (this.rotationDirty) this._onUpdate(this._quaternion);\n  }\n\n  /**\n   * Point in local space that rotation and scale happen around, as in pixi.js\n   *\n   * Unlike a pivot, it leaves an unrotated, unscaled node where it is: the origin sits at\n   * `position + origin` in the parent. Assigning copies the values in, and a single number sets\n   * all three axes.\n   * @example\n   * ```ts\n   * // Tip a crate over its bottom-right edge without moving it first.\n   * crate.origin = { x: 0.5, y: -0.5, z: 0 };\n   * crate.angle.z = -90;\n   * ```\n   */\n  get origin(): ObservableVector3 {\n    return (this._origin ??= new ObservableVector3(this, 0, 0, 0));\n  }\n\n  /**\n   * Sets the origin; a number sets all three axes\n   * @param value - The new origin, in local space\n   */\n  set origin(value: PointData3D | number) {\n    const origin = this.origin;\n\n    if (typeof value === 'number') origin.set(value);\n    else origin.copyFrom(value);\n  }\n\n  /**\n   * Local position on the x axis; the same as `position.x`\n   * @example\n   * ```ts\n   * player.x += speed * dt;\n   * ```\n   */\n  get x(): number {\n    return this._position._x;\n  }\n\n  /**\n   * Sets `position.x`\n   * @param value - The new x position\n   */\n  set x(value: number) {\n    this._position.x = value;\n  }\n\n  /**\n   * Local position on the y axis; the same as `position.y`\n   * @example\n   * ```ts\n   * ball.y = Math.abs(Math.sin(time)) * 2;\n   * ```\n   */\n  get y(): number {\n    return this._position._y;\n  }\n\n  /**\n   * Sets `position.y`\n   * @param value - The new y position\n   */\n  set y(value: number) {\n    this._position.y = value;\n  }\n\n  /**\n   * Local position on the z axis; the same as `position.z`\n   * @example\n   * ```ts\n   * if (car.z > finishLine) finish();\n   * ```\n   */\n  get z(): number {\n    return this._position._z;\n  }\n\n  /**\n   * Sets `position.z`\n   * @param value - The new z position\n   */\n  set z(value: number) {\n    this._position.z = value;\n  }\n\n  /**\n   * Adds one or more children to the end of this container's child list\n   *\n   * A child with another parent leaves it first. A child that is already here moves to the end,\n   * without events.\n   * @example\n   * ```ts\n   * view.root.addChild(crate, lamp);\n   * ```\n   * @param children - The children to add\n   * @returns The first added child\n   */\n  public addChild<U extends Container3D[]>(...children: U): U[0] {\n    if (children.length > 1) {\n      for (let i = 0; i < children.length; i++) {\n        this.addChild(children[i]);\n      }\n\n      return children[0];\n    }\n\n    const child = children[0];\n\n    if (child.parent === this) {\n      this.children.splice(this.children.indexOf(child), 1);\n      this.children.push(child);\n\n      return child;\n    }\n\n    if (child.parent) {\n      child.parent.removeChild(child);\n    }\n\n    this.children.push(child);\n\n    child._worldTransformDirty = true;\n    child._worldVisibleDirty = true;\n    child.didChange = true;\n    child.parent = this;\n\n    if (this._view3d) {\n      this._view3d._attach(child);\n    }\n\n    this.emit('childAdded', child, this, this.children.length - 1);\n    child.emit('added', this);\n\n    return child;\n  }\n\n  /**\n   * Removes one or more children from this container; a node that isn't a child is ignored\n   * @example\n   * ```ts\n   * view.root.removeChild(crate);\n   * ```\n   * @param children - The children to remove\n   * @returns The first child passed in\n   */\n  public removeChild<U extends Container3D[]>(...children: U): U[0] {\n    if (children.length > 1) {\n      for (let i = 0; i < children.length; i++) {\n        this.removeChild(children[i]);\n      }\n\n      return children[0];\n    }\n\n    const child = children[0];\n\n    const index = this.children.indexOf(child);\n\n    if (index > -1) {\n      this.children.splice(index, 1);\n\n      if (child._view3d) child._view3d._detach(child);\n\n      child.parent = null;\n\n      this.emit('childRemoved', child, this, index);\n      child.emit('removed', this);\n    }\n\n    return child;\n  }\n\n  /**\n   * Removes the children from `beginIndex` up to, but not including, `endIndex`\n   * @example\n   * ```ts\n   * const debris = level.removeChildren();\n   * ```\n   * @param beginIndex - First index to remove\n   * @param endIndex - End of the range, exclusive; defaults to the child count\n   * @returns The removed children, last child first\n   * @throws {RangeError} When `beginIndex` is negative or past `endIndex`, or equal to it while\n   * this container has children.\n   */\n  public removeChildren(beginIndex = 0, endIndex?: number): Container3D[] {\n    const end = endIndex ?? this.children.length;\n    const range = end - beginIndex;\n    const removed: Container3D[] = [];\n\n    if (range > 0 && range <= end) {\n      for (let i = end - 1; i >= beginIndex; i--) {\n        const child = this.children[i];\n\n        if (!child) continue;\n\n        removed.push(child);\n\n        if (child._view3d) child._view3d._detach(child);\n\n        child.parent = null;\n      }\n\n      this.children.splice(beginIndex, range);\n\n      for (let i = 0; i < removed.length; i++) {\n        const child = removed[i];\n\n        this.emit('childRemoved', child, this, i);\n        child.emit('removed', this);\n      }\n\n      return removed;\n    } else if (range === 0 && this.children.length === 0) {\n      return removed;\n    }\n\n    throw new RangeError('removeChildren: numeric values are outside the acceptable range.');\n  }\n\n  /**\n   * Removes the child at `index`\n   * @example\n   * ```ts\n   * const newest = queue.removeChildAt(queue.children.length - 1);\n   * ```\n   * @param index - Index of the child to remove\n   * @returns The removed child\n   * @throws {Error} When `index` is out of bounds.\n   */\n  public removeChildAt<U extends Container3D>(index: number): U {\n    const child = this.getChildAt<U>(index);\n\n    return this.removeChild(child);\n  }\n\n  /**\n   * Gets the child at `index`\n   * @example\n   * ```ts\n   * const first = group.getChildAt(0);\n   * ```\n   * @param index - Index of the child to fetch\n   * @returns The child at `index`\n   * @throws {Error} When `index` is out of bounds.\n   */\n  public getChildAt<U extends Container3D>(index: number): U {\n    if (index < 0 || index >= this.children.length) {\n      throw new Error(`getChildAt: Index (${index}) does not exist.`);\n    }\n\n    return this.children[index] as U;\n  }\n\n  /**\n   * Gets the index of `child` within this container\n   * @example\n   * ```ts\n   * const slot = rack.getChildIndex(sword);\n   * ```\n   * @param child - The child to look up\n   * @returns The child's index\n   * @throws {Error} When `child` is not a child of this container.\n   */\n  public getChildIndex(child: Container3D): number {\n    const index = this.children.indexOf(child);\n\n    if (index === -1) {\n      throw new Error('getChildIndex: The supplied Container3D must be a child of the caller.');\n    }\n\n    return index;\n  }\n\n  /**\n   * Moves an existing `child` to `index` within this container\n   * @example\n   * ```ts\n   * rack.setChildIndex(sword, 0);\n   * ```\n   * @param child - The child to move\n   * @param index - The destination index\n   * @throws {Error} When `index` is out of bounds or `child` is not a child of this container.\n   */\n  public setChildIndex(child: Container3D, index: number): void {\n    if (index < 0 || index >= this.children.length) {\n      throw new Error(`setChildIndex: The index ${index} supplied is out of bounds ${this.children.length}.`);\n    }\n\n    this.getChildIndex(child);\n\n    this.addChildAt(child, index);\n  }\n\n  /**\n   * Adds `child` at `index`, or moves it there when it is already a child of this container\n   *\n   * A move within this container emits no events.\n   * @example\n   * ```ts\n   * rack.addChildAt(sword, 0);\n   * ```\n   * @param child - The child to add or move\n   * @param index - The destination index\n   * @returns The added child\n   * @throws {Error} When `index` is out of bounds.\n   */\n  public addChildAt<U extends Container3D>(child: U, index: number): U {\n    const { children } = this;\n\n    if (index < 0 || index > children.length) {\n      throw new Error(`addChildAt: The index ${index} supplied is out of bounds ${children.length}.`);\n    }\n\n    const sameParent = child.parent === this;\n\n    if (child.parent) {\n      if (sameParent) {\n        const currentIndex = children.indexOf(child);\n\n        if (currentIndex === index) return child;\n\n        children.splice(currentIndex, 1);\n      } else {\n        child.parent.removeChild(child);\n      }\n    }\n\n    if (index === children.length) {\n      children.push(child);\n    } else {\n      children.splice(index, 0, child);\n    }\n\n    if (sameParent) return child;\n\n    child._worldTransformDirty = true;\n    child._worldVisibleDirty = true;\n    child.didChange = true;\n    child.parent = this;\n\n    if (this._view3d) {\n      this._view3d._attach(child);\n    }\n\n    this.emit('childAdded', child, this, index);\n    child.emit('added', this);\n\n    return child;\n  }\n\n  /**\n   * Swaps the places of two children in this container's list\n   * @example\n   * ```ts\n   * rack.swapChildren(sword, shield);\n   * ```\n   * @param child - The first child\n   * @param child2 - The second child\n   * @throws {Error} When either argument is not a child of this container.\n   */\n  public swapChildren<U extends Container3D>(child: U, child2: U): void {\n    if (child === child2) return;\n\n    const index1 = this.getChildIndex(child);\n    const index2 = this.getChildIndex(child2);\n\n    this.children[index1] = child2;\n    this.children[index2] = child;\n  }\n\n  /**\n   * Returns the first child whose label matches, or `null`\n   *\n   * Each container checks its direct children before searching inside them. An unlabelled node\n   * never matches, even a pattern.\n   * @param label - Exact label, or a pattern to test labels against\n   * @param deep - Whether to search the whole subtree, not only direct children\n   * @returns The first match, or `null` when nothing matches\n   * @example\n   * ```ts\n   * const wheel = car.getChildByLabel('wheel_front_left', true);\n   * const anyWheel = car.getChildByLabel(/^wheel_/, true);\n   * ```\n   */\n  public getChildByLabel(label: string | RegExp, deep = false): Container3D | null {\n    const children = this.children;\n\n    for (let i = 0; i < children.length; i++) {\n      if (labelMatches(children[i].label, label)) return children[i];\n    }\n\n    if (deep) {\n      for (let i = 0; i < children.length; i++) {\n        const found = children[i].getChildByLabel(label, true);\n\n        if (found) return found;\n      }\n    }\n\n    return null;\n  }\n\n  /**\n   * Collects every child whose label matches, in the order {@link Container3D.getChildByLabel}\n   * visits them\n   * @param label - Exact label, or a pattern to test labels against\n   * @param deep - Whether to search the whole subtree, not only direct children\n   * @param out - Array the matches are appended to; a new one when omitted\n   * @returns `out`\n   * @example\n   * ```ts\n   * const wheels = car.getChildrenByLabel(/^wheel_/, true);\n   * ```\n   */\n  public getChildrenByLabel(label: string | RegExp, deep = false, out: Container3D[] = []): Container3D[] {\n    const children = this.children;\n\n    for (let i = 0; i < children.length; i++) {\n      if (labelMatches(children[i].label, label)) out.push(children[i]);\n    }\n\n    if (deep) {\n      for (let i = 0; i < children.length; i++) {\n        children[i].getChildrenByLabel(label, true, out);\n      }\n    }\n\n    return out;\n  }\n\n  /**\n   * Calls `callback` with this container, then with every container under it, depth first\n   *\n   * Each container comes before its children, and hidden ones are visited too. A {@link Skeleton}'s\n   * bones and a {@link BatchedMesh3D}'s {@link BatchedMesh3D.items | items} aren't containers, so\n   * the walk doesn't reach them. It can't stop early or skip a subtree.\n   *\n   * The callback may remove, destroy or {@link Container3D.replaceChild | replace} the container\n   * it's given. A container it adds with {@link Container3D.addChild | addChild} is visited only if\n   * its new parent hasn't been visited yet. Other changes to the tree during the walk can skip a\n   * container or visit one twice.\n   * @example\n   * ```ts\n   * const robot = new Model3D(source);\n   *\n   * robot.traverse((container) => {\n   *   if (container instanceof Mesh3D) container.enablePass('outline');\n   * });\n   * ```\n   * @param callback - Called once with each container, this one first\n   */\n  public traverse(callback: (container: Container3D) => void): void {\n    const children = this.children;\n    let count = children.length;\n\n    callback(this);\n\n    for (let i = 0; i < count && i < children.length;) {\n      const child = children[i];\n      const next = children[i + 1];\n\n      child.traverse(callback);\n\n      if (children[i] === next) count--;\n      else i++;\n    }\n  }\n\n  /**\n   * Removes this container from its parent, if it has one\n   * @example\n   * ```ts\n   * pickup.removeFromParent();\n   * ```\n   */\n  public removeFromParent(): void {\n    this.parent?.removeChild(this);\n  }\n\n  /**\n   * Moves one or more nodes under this container without moving them in the world; see\n   * {@link Container3D.reparentChildAt | reparentChildAt}\n   * @example\n   * ```ts\n   * hand.reparentChild(sword);\n   * ```\n   * @param child - The children to reparent\n   * @returns The first reparented child\n   */\n  public reparentChild<U extends Container3D[]>(...child: U): U[0] {\n    if (child.length === 1) {\n      return this.reparentChildAt(child[0], this.children.length);\n    }\n\n    for (let i = 0; i < child.length; i++) {\n      this.reparentChildAt(child[i], this.children.length);\n    }\n\n    return child[0];\n  }\n\n  /**\n   * Moves `child` under this container at `index` without moving it in the world\n   *\n   * Its local position, rotation and scale change so that it renders where it did, and it keeps\n   * its {@link Container3D.origin | origin}. Unlike pixi, it uses current world transforms, so a\n   * move earlier in the frame counts. A child that is already here only changes index.\n   * @example\n   * ```ts\n   * rack.reparentChildAt(sword, 0);\n   * ```\n   * @param child - The child to reparent\n   * @param index - The destination index\n   * @returns The reparented child\n   */\n  public reparentChildAt<U extends Container3D>(child: U, index: number): U {\n    if (child.parent === this) {\n      this.setChildIndex(child, index);\n\n      return child;\n    }\n\n    updateTransformBackwards3D(child, _reparentChildWorld);\n    if (child._localTransformDirty) {\n      child.updateLocalTransform();\n      child._localTransformDirty = false;\n    }\n    _reparentChildWorld.multiply(child.localTransform);\n\n    child.removeFromParent();\n    this.addChildAt(child, index);\n\n    updateTransformBackwards3D(this, _reparentParentWorld);\n    if (this._localTransformDirty) {\n      this.updateLocalTransform();\n      this._localTransformDirty = false;\n    }\n    _reparentParentWorld.multiply(this.localTransform);\n\n    _reparentParentWorld.getInverse(_reparentParentWorld);\n    _reparentChildWorld.premultiply(_reparentParentWorld);\n    _reparentChildWorld.decompose(_reparentPos, _reparentQuat, _reparentScale);\n\n    child.scale.copyFrom(_reparentScale);\n    child.quaternion.copyFrom(_reparentQuat);\n\n    if (child._origin !== null) {\n      child.updateLocalTransform();\n      _reparentPos.subtract(child._getOriginOffset(_originOffset));\n    }\n\n    child.position.copyFrom(_reparentPos);\n\n    return child;\n  }\n\n  /**\n   * Replaces `oldChild` with `newChild` at the same index, copying `oldChild`'s local position,\n   * rotation and scale onto `newChild`\n   *\n   * `newChild` keeps its own {@link Container3D.origin | origin}, and its position is solved so it\n   * sits exactly where `oldChild` did.\n   * @example\n   * ```ts\n   * car.replaceChild(flatTyre, spareWheel);\n   * ```\n   * @param oldChild - The child to replace\n   * @param newChild - The child that takes its place\n   * @throws {Error} When `oldChild` is not a child of this container.\n   */\n  public replaceChild<U extends Container3D, T extends Container3D>(oldChild: U, newChild: T): void {\n    const index = this.getChildIndex(oldChild);\n\n    this.addChildAt(newChild, index);\n\n    newChild.scale.copyFrom(oldChild.scale);\n    newChild.rotation.copyFrom(oldChild.rotation);\n    newChild.quaternion.copyFrom(oldChild.quaternion);\n    newChild.rotationDirty = oldChild.rotationDirty;\n\n    const position = newChild.position.copyFrom(oldChild.position);\n\n    if (oldChild._origin !== null) {\n      oldChild.updateLocalTransform();\n      position.add(oldChild._getOriginOffset(_originOffset));\n    }\n\n    if (newChild._origin !== null) {\n      newChild.updateLocalTransform();\n      position.subtract(newChild._getOriginOffset(_originOffset));\n    }\n\n    this.removeChild(oldChild);\n  }\n\n  /**\n   * Rebuilds {@link Container3D.localTransform | localTransform} from the position, rotation,\n   * scale and {@link Container3D.origin | origin}\n   *\n   * The view calls it for each node that changed, so you only need it to read a current\n   * `localTransform` before the next frame. When {@link Container3D.rotation | rotation} is the\n   * rotation in use, it updates the quaternion to match.\n   * @example\n   * ```ts\n   * crate.rotation.y = Math.PI / 4;\n   * crate.updateLocalTransform();\n   * const local = crate.localTransform.clone();\n   * ```\n   * @advanced\n   */\n  public updateLocalTransform(): void {\n    const quat = this._quaternion;\n\n    if (this.rotationDirty) {\n      this.rotationDirty = false;\n\n      const rx = this._rotation._x;\n      const ry = this._rotation._y;\n      const rz = this._rotation._z;\n\n      const c1 = Math.cos(rx / 2);\n      const c2 = Math.cos(ry / 2);\n      const c3 = Math.cos(rz / 2);\n\n      const s1 = Math.sin(rx / 2);\n      const s2 = Math.sin(ry / 2);\n      const s3 = Math.sin(rz / 2);\n\n      quat._x = s1 * c2 * c3 + c1 * s2 * s3;\n      quat._y = c1 * s2 * c3 - s1 * c2 * s3;\n      quat._z = c1 * c2 * s3 + s1 * s2 * c3;\n      quat._w = c1 * c2 * c3 - s1 * s2 * s3;\n    }\n\n    const x = quat._x;\n    const y = quat._y;\n    const z = quat._z;\n    const w = quat._w;\n\n    const x2 = x + x;\n    const y2 = y + y;\n    const z2 = z + z;\n\n    const xx = x * x2;\n    const xy = x * y2;\n    const xz = x * z2;\n    const yy = y * y2;\n    const yz = y * z2;\n    const zz = z * z2;\n    const wx = w * x2;\n    const wy = w * y2;\n    const wz = w * z2;\n\n    const out = this.localTransform.elements;\n\n    const sx = this._scale._x;\n    const sy = this._scale._y;\n    const sz = this._scale._z;\n\n    out[0] = (1 - (yy + zz)) * sx;\n    out[1] = (xy + wz) * sx;\n    out[2] = (xz - wy) * sx;\n    out[4] = (xy - wz) * sy;\n    out[5] = (1 - (xx + zz)) * sy;\n    out[6] = (yz + wx) * sy;\n    out[8] = (xz + wy) * sz;\n    out[9] = (yz - wx) * sz;\n    out[10] = (1 - (xx + yy)) * sz;\n\n    out[12] = this._position._x;\n    out[13] = this._position._y;\n    out[14] = this._position._z;\n\n    if (this._origin !== null) this._addOriginOffset();\n  }\n\n  /** Adds the {@link Container3D.origin | origin} offset to the local matrix; only call when `_origin` is set */\n  protected _addOriginOffset(): void {\n    const offset = this._getOriginOffset(_originOffset);\n    const out = this.localTransform.elements;\n\n    out[12] += offset.x;\n    out[13] += offset.y;\n    out[14] += offset.z;\n  }\n\n  /**\n   * Writes `origin - M·origin` into `out`, M being `localTransform`'s basis, so rebuild that first;\n   * only call when `_origin` is set. `Sprite3D` overrides it, since its basis also carries its size\n   * @param out - Receives the offset\n   * @returns `out`\n   */\n  protected _getOriginOffset(out: Vector3): Vector3 {\n    const e = this.localTransform.elements;\n    const origin = this._origin!;\n\n    const ox = origin._x;\n    const oy = origin._y;\n    const oz = origin._z;\n\n    out.x = ox - (e[0] * ox + e[4] * oy + e[8] * oz);\n    out.y = oy - (e[1] * ox + e[5] * oy + e[9] * oz);\n    out.z = oz - (e[2] * ox + e[6] * oy + e[10] * oz);\n\n    return out;\n  }\n\n  /**\n   * Measures the bounding box of this container and its descendants, in this container's local\n   * space\n   *\n   * A subtree with a {@link Container3D.boundsVolume | boundsVolume} counts as that box. Hidden\n   * descendants are left out; this container counts whether or not it is visible. An empty subtree\n   * measures as a zero box at the origin. Each call walks the subtree, so cache the result if you\n   * need it every frame.\n   * @param out - Box to write into; a new one when omitted\n   * @returns `out`\n   * @example\n   * ```ts\n   * const bounds = model.getLocalBounds();\n   * const center = bounds.getCenter();\n   * ```\n   */\n  public getLocalBounds(out: Box = new Box()): Box {\n    return getLocalBounds3D(this, out);\n  }\n\n  /**\n   * Width along local x: `|scale.x| × local bounds width`\n   *\n   * Assigning writes `scale.x` only. To set several axes, {@link Container3D.setSize | setSize}\n   * measures the bounds once instead of once per axis.\n   * @example\n   * ```ts\n   * crate.width = 2;\n   * ```\n   */\n  get width(): number {\n    return Math.abs(this._scale._x * this.getLocalBounds(_measureBox).width);\n  }\n\n  /**\n   * Scales along x so the width becomes `value`\n   * @param value - Target width along x\n   */\n  set width(value: number) {\n    this._scale.x = scaleForSize(value, this.getLocalBounds(_measureBox).width, this._scale._x);\n  }\n\n  /**\n   * Height along local y: `|scale.y| × local bounds height`\n   *\n   * Assigning writes `scale.y` only; see {@link Container3D.width | width}.\n   * @example\n   * ```ts\n   * tree.height = 6;\n   * ```\n   */\n  get height(): number {\n    return Math.abs(this._scale._y * this.getLocalBounds(_measureBox).height);\n  }\n\n  /**\n   * Scales along y so the height becomes `value`\n   * @param value - Target height along y\n   */\n  set height(value: number) {\n    this._scale.y = scaleForSize(value, this.getLocalBounds(_measureBox).height, this._scale._y);\n  }\n\n  /**\n   * Depth along local z: `|scale.z| × local bounds depth`\n   *\n   * Assigning writes `scale.z` only; see {@link Container3D.width | width}.\n   * @example\n   * ```ts\n   * bench.depth = 0.5;\n   * ```\n   */\n  get depth(): number {\n    return Math.abs(this._scale._z * this.getLocalBounds(_measureBox).depth);\n  }\n\n  /**\n   * Scales along z so the depth becomes `value`\n   * @param value - Target depth along z\n   */\n  set depth(value: number) {\n    this._scale.z = scaleForSize(value, this.getLocalBounds(_measureBox).depth, this._scale._z);\n  }\n\n  /**\n   * Returns the scaled size of this container, measuring the local bounds once\n   * @param out - Object to write into; a new one when omitted\n   * @returns The size, written into `out`\n   * @example\n   * ```ts\n   * const { width, height, depth } = model.getSize();\n   * ```\n   */\n  public getSize(out: Size3D = { width: 0, height: 0, depth: 0 }): Size3D {\n    const bounds = this.getLocalBounds(_measureBox);\n\n    out.width = Math.abs(this._scale._x * bounds.width);\n    out.height = Math.abs(this._scale._y * bounds.height);\n    out.depth = Math.abs(this._scale._z * bounds.depth);\n\n    return out;\n  }\n\n  /**\n   * Rescales this container so its size matches the given width, height and depth\n   *\n   * A missing `height` or `depth` takes the width. An axis whose local extent is zero, such as a\n   * flat plane's depth, keeps a unit scale. The sign of each scale axis is kept, so a mirrored node\n   * stays mirrored.\n   * @param value - Target width, or an object with `width` and optional `height` / `depth`\n   * @param height - Target height; defaults to the width\n   * @param depth - Target depth; defaults to the width\n   * @example\n   * ```ts\n   * model.setSize(2); // stretch each axis to 2\n   * model.setSize(4, 2, 1);\n   * model.setSize({ width: 4, height: 2 }); // depth follows width: 4\n   * ```\n   */\n  public setSize(value: number | (Pick<Size3D, 'width'> & Partial<Size3D>), height?: number, depth?: number): void {\n    let width: number;\n\n    if (typeof value === 'object') {\n      width = value.width;\n      height = value.height ?? width;\n      depth = value.depth ?? width;\n    } else {\n      width = value;\n      height ??= width;\n      depth ??= width;\n    }\n\n    const bounds = this.getLocalBounds(_measureBox);\n    const scale = this._scale;\n\n    scale.set(\n      scaleForSize(width, bounds.width, scale._x),\n      scaleForSize(height, bounds.height, scale._y),\n      scaleForSize(depth, bounds.depth, scale._z),\n    );\n  }\n\n  /**\n   * Turns this node so its forward axis, local +Z, points at a world-space `target`\n   *\n   * Cameras and lights aim local -Z instead. The node aims from `position + origin`, and uses the\n   * parent's current world transform, so a move earlier in the frame counts.\n   * @example\n   * ```ts\n   * turret.lookAt(enemy.getGlobalPosition());\n   * ```\n   * @param target - World-space point to face\n   * @param up - World-space up reference; defaults to `(0, 1, 0)`\n   */\n  public lookAt(target: PointData3D, up: PointData3D = _lookAtDefaultUp): void {\n    updateTransformBackwards3D(this, _lookAtParentWorld.identity());\n\n    _lookAtPos.copyFrom(this.position);\n    if (this._origin !== null) _lookAtPos.add(this._origin);\n    _lookAtPos.applyAffineMatrix4(_lookAtParentWorld);\n\n    if (this._lookAtForwardIsPositiveZ) {\n      _lookAtMatrix.lookAt(target, _lookAtPos, up);\n    } else {\n      _lookAtMatrix.lookAt(_lookAtPos, target, up);\n    }\n    _lookAtWorldQuat.setFromRotationMatrix(_lookAtMatrix);\n\n    if (this.parent) {\n      _lookAtParentQuat.setFromScaledRotationMatrix(_lookAtParentWorld);\n      _lookAtParentQuat.inverse();\n      _lookAtWorldQuat.premultiply(_lookAtParentQuat);\n    }\n\n    this.quaternion.copyFrom(_lookAtWorldQuat);\n  }\n\n  /**\n   * Works out this container's current world transform into `out`\n   *\n   * It walks up the parent chain, so the result is right even before the view's transform pass\n   * has run this frame. With `skipUpdate` it copies the cached\n   * {@link Container3D.worldTransform | worldTransform} instead, which is cheaper but can be stale.\n   * @param out - Matrix the result is written into. Defaults to a new `Matrix4`.\n   * @param skipUpdate - `true` to copy the cached world transform instead of recomputing.\n   * @example\n   * ```ts\n   * const world = mesh.getGlobalTransform();\n   * const localRay = ray.applyMatrix4(world.getInverse(world), new Ray());\n   * ```\n   */\n  public getGlobalTransform(out: Matrix4 = new Matrix4(), skipUpdate = false): Matrix4 {\n    if (skipUpdate) return out.copyFrom(this.worldTransform);\n\n    updateTransformBackwards3D(this, out);\n\n    if (this._localTransformDirty) {\n      this.updateLocalTransform();\n      this._localTransformDirty = false;\n    }\n\n    return out.multiply(this.localTransform);\n  }\n\n  /**\n   * Converts a point from this container's local space to world space\n   *\n   * Pass the result to {@link View3D.worldToScreen} to go on to 2D screen coordinates.\n   * @param position - The local-space point to convert.\n   * @param out - Point the result is written into. Defaults to a new {@link Vector3}.\n   * @param skipUpdate - `true` to use the cached world transform (see {@link Container3D.getGlobalTransform}).\n   * @example\n   * ```ts\n   * const aboveHead = player.toGlobal({ x: 0, y: 2, z: 0 });\n   * ```\n   * @see {@link Container3D.getGlobalPosition} For this container's own world position.\n   */\n  public toGlobal<T extends PointLike3D = Vector3>(position: PointData3D, out?: T, skipUpdate = false): T {\n    out ??= new Vector3() as unknown as T;\n\n    this.getGlobalTransform(_convertMatrix, skipUpdate);\n    _convertVec.copyFrom(position).applyAffineMatrix4(_convertMatrix, out);\n\n    return out;\n  }\n\n  /**\n   * Converts a point into this container's local space\n   * @param position - The point to convert.\n   * @param from - Container whose local space `position` is in. Defaults to world space.\n   * @param out - Point the result is written into. Defaults to a new {@link Vector3}.\n   * @param skipUpdate - `true` to use cached world transforms (see {@link Container3D.getGlobalTransform}).\n   * @example\n   * ```ts\n   * const targetFromTurret = turret.toLocal({ x: 0, y: 0, z: 0 }, target);\n   * ```\n   */\n  public toLocal<T extends PointLike3D = Vector3>(\n    position: PointData3D,\n    from?: Container3D,\n    out?: T,\n    skipUpdate = false,\n  ): T {\n    out ??= new Vector3() as unknown as T;\n\n    if (from) position = from.toGlobal(position, _convertFromVec, skipUpdate);\n\n    this.getGlobalTransform(_convertMatrix, skipUpdate);\n    _convertMatrix.getInverse(_convertMatrix);\n    _convertVec.copyFrom(position).applyAffineMatrix4(_convertMatrix, out);\n\n    return out;\n  }\n\n  /**\n   * Returns this container's position in world space: `parent.toGlobal(this.position)`, or a copy\n   * of `position` with no parent\n   * @param out - Point the result is written into. Defaults to a new {@link Vector3}.\n   * @param skipUpdate - `true` to use the parent's cached world transform (see\n   *   {@link Container3D.getGlobalTransform}); this node's own `position` is always read as it stands.\n   * @example\n   * ```ts\n   * const screenPos = view3d.worldToScreen(mesh.getGlobalPosition());\n   * ```\n   */\n  public getGlobalPosition(out: Vector3 = new Vector3(), skipUpdate = false): Vector3 {\n    if (this.parent) return this.parent.toGlobal(this.position, out, skipUpdate);\n\n    return out.copyFrom(this.position);\n  }\n\n  /**\n   * Prints this container's subtree to the console as an indented tree of `ConstructorName \"label\"`\n   * lines, for debugging\n   * @example\n   * ```ts\n   * model.logHierarchy();\n   * ```\n   * @param depth - Indentation level to start at; used by the recursion\n   * @advanced\n   */\n  public logHierarchy(depth: number = 0): void {\n    const indent = '  '.repeat(depth);\n    const type = this.constructor.name;\n    const label = this.label ? ` \"${this.label}\"` : '';\n    // oxlint-disable-next-line no-restricted-globals -- logHierarchy prints by design\n    console.log(`${indent}${type}${label}`);\n\n    for (const child of this.children) {\n      child.logHierarchy(depth + 1);\n    }\n  }\n\n  /**\n   * Whether this container and its descendants draw\n   *\n   * Hiding is cheap, and a hidden node stays in the scene; to take it out, remove it with\n   * {@link Container3D.removeChild | removeChild}. Emits\n   * {@link Container3DEvents.visibleChanged | visibleChanged} when the value changes.\n   * @example\n   * ```ts\n   * door.visible = false;\n   * ```\n   */\n  public get visible(): boolean {\n    return !!this._visible;\n  }\n\n  /**\n   * Shows or hides this container and its descendants\n   * @param value - Whether they draw\n   */\n  public set visible(value: boolean) {\n    const num = value ? 1 : 0;\n    if (this._visible === num) return;\n    this._visible = num;\n    this._worldVisibleDirty = true;\n\n    if (!this.didChange) {\n      this.didChange = true;\n      this._view3d?._onChildUpdate(this);\n    }\n\n    this.emit('visibleChanged', value);\n  }\n\n  /**\n   * `1` when this node and every ancestor are visible, otherwise `0`\n   *\n   * The view works it out once per frame, so it lags a `visible` change until the next render.\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only state\n  get worldVisible(): number {\n    return this._worldVisible;\n  }\n\n  /** The {@link View3D} this node is in, or `null` when it isn't in a scene */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only state\n  get view3d(): View3D | null {\n    return this._view3d;\n  }\n\n  /** @internal */\n  public _onUpdate(pointOrQuat?: ObservableVector3 | ObservableQuaternion): void {\n    if (pointOrQuat) {\n      if (pointOrQuat === this._rotation) {\n        this.rotationDirty = true;\n      } else if (pointOrQuat === this._quaternion) {\n        this.rotationDirty = false;\n      }\n    }\n\n    this._localTransformDirty = true;\n    this._worldTransformDirty = true;\n\n    if (this.didChange) return;\n    this.didChange = true;\n\n    if (this._view3d) {\n      this._view3d._onChildUpdate(this);\n    }\n  }\n\n  /**\n   * Unloads the geometry of every mesh in this subtree, for a part of the scene you'll show again\n   * later\n   *\n   * Each {@link Mesh3D.unload | mesh} keeps its vertex data, so the next render that draws it\n   * uploads it again; remove the subtree from the scene first. {@link Geometry3D.unload} says what\n   * GPU memory that frees. Materials are left alone, since\n   * they're usually shared, except under a {@link Model3D}, which unloads its own; unload any other\n   * material yourself.\n   * @example\n   * ```ts\n   * view.root.removeChild(level);\n   * level.unload();\n   * ```\n   */\n  public unload(): void {\n    const children = this.children;\n    for (let i = 0; i < children.length; i++) children[i].unload();\n  }\n\n  /** Called by the transform pass right after {@link Container3D.worldTransform} is recomputed @internal */\n  public _storeWorldTransform(): void {}\n\n  /** Called by the transform pass right after {@link Container3D.worldVisible} is recomputed @internal */\n  public _storeWorldVisible(): void {}\n\n  /**\n   * Destroys this container: it removes its children, leaves its parent and its view, emits\n   * {@link Container3DEvents.destroyed | destroyed}, and drops its listeners\n   *\n   * Children, and the geometry, materials and textures a mesh uses, are destroyed only when the\n   * matching {@link Destroy3DOptions} flag is set, and destroyed children get the same `options`.\n   * Unlike pixi, `position`, `scale` and the transform matrices stay readable afterwards. Calling\n   * it again does nothing.\n   * @example\n   * ```ts\n   * crate.destroy({ children: true });\n   * ```\n   * @param options - `true` destroys everything reachable; an object picks each resource; left\n   * out or `false`, only this node and the GPU resources it alone owns go.\n   */\n  public destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n    this.destroyed = true;\n\n    const destroyChildren = resolveDestroy3DFlag(options, 'children');\n    const oldChildren = destroyChildren ? this.children.slice() : null;\n\n    this.removeChildren(0, this.children.length);\n\n    this.removeFromParent();\n\n    this.emit('destroyed', this);\n    this.removeAllListeners();\n\n    if (destroyChildren && oldChildren) {\n      for (let i = 0; i < oldChildren.length; i++) {\n        oldChildren[i].destroy(options);\n      }\n    }\n\n    this.parent = null;\n    this._view3d = null;\n  }\n}\n","import { warn } from 'pixi.js';\n\n/** @internal */\nclass PassBitRegistry {\n  /**\n   * Built-in pass names at their `RenderPassBit` values in `RenderPass.ts` (`blendedRefraction` is\n   * missing), written out because importing them is a cycle; change the two together\n   */\n  private _bitsByName: Record<string, number> = Object.assign(Object.create(null), {\n    shadow: 1 << 0,\n    opaque: 1 << 1,\n    transparent: 1 << 2,\n    background: 1 << 3,\n    transmission: 1 << 4,\n  });\n\n  /** Custom bits start here, one per new name; bitwise ops are 32-bit, so about 23 fit */\n  private _nextBit = 1 << 8;\n\n  public getOrAllocate(name: string, explicitBit?: number): number {\n    const existing = this._bitsByName[name];\n    if (existing !== undefined) {\n      if (explicitBit !== undefined && explicitBit !== existing) {\n        warn(\n          `[@pixi/3d] pass \"${name}\" already registered with bit ${existing}; ignoring explicit bit ${explicitBit}.`,\n        );\n      }\n      return existing;\n    }\n    const bit = explicitBit ?? this._nextBit;\n    if (explicitBit === undefined) this._nextBit <<= 1;\n    this._bitsByName[name] = bit;\n    return bit;\n  }\n\n  /** Never allocates, so disabling a name nothing has used spends no bit */\n  public get(name: string): number | undefined {\n    return this._bitsByName[name];\n  }\n\n  public nameOf(bit: number): string | undefined {\n    return Object.keys(this._bitsByName).find((name) => this._bitsByName[name] === bit);\n  }\n}\n\n/**\n * One for the page, not per renderer, so a material's pass names map to the same bits in every view\n * @internal\n */\nexport const passBitRegistry = new PassBitRegistry();\n","/**\n * One bind group of a {@link ShaderBitTemplate}: its name, or its name with options\n *\n * A bare name is the same as `{ name }` with every option off.\n * @category rendering\n * @advanced\n */\nexport type TemplateBindGroup =\n  | string\n  | {\n      /** The group's name, which bits use as the key of their `bindings` */\n      readonly name: string;\n      /**\n       * Whether WebGL declares the group's uniform fields as one `std140` uniform block, named after\n       * the group, rather than as plain uniforms\n       *\n       * A block doesn't count against the device's uniform vector limit. The `UniformGroup` bound to\n       * the group must then be made with `ubo: true`. WebGPU ignores it.\n       * @default false\n       */\n      readonly ubo?: boolean;\n    };\n\n/** @internal */\nexport interface ResolvedBindGroup {\n  readonly name: string;\n  readonly ubo: boolean;\n}\n\n/**\n * The source a shader compiles from: its entry points, with `{{slot}}` markers the bits fill\n *\n * `{{header}}` takes every bit's header code and the generated declarations for the attributes,\n * varyings and bindings. Every other marker takes the bits' code for that slot, in bit order, and a\n * marker no bit fills is removed.\n *\n * The WGSL template holds both entry points, so its slots carry the stage as a prefix: a bit's\n * `vertex.body` fills `{{vertexBody}}`. Each GLSL template holds one stage, so `vertex.body` fills\n * the vertex template's `{{body}}`. To write the bits' `outputs`, a template adds the slots\n * {@link ShaderBit#outputs} lists; any other template writes its fragment outputs itself.\n *\n * Shaders are cached by template identity, so build a template once and don't change it.\n * @example\n * ```ts\n * const pbrTemplate: ShaderBitTemplate = {\n *   bindGroups: [{ name: \"global\", ubo: true }, \"camera\", \"batch\"],\n *   gpu: `\n *     {{header}}\n *     @vertex fn mainVertex(input: VertexInput) -> VertexOutput {\n *       var output: VertexOutput;\n *       {{vertexBody}}\n *       return output;\n *     }\n *     @fragment fn mainFragment(input: FragmentInput) -> @location(0) vec4<f32> {\n *       {{fragmentBody}}\n *     }\n *   `,\n *   gl: {\n *     vertex: `#version 300 es\n *       {{header}}\n *       void main() {\n *         {{body}}\n *       }\n *     `,\n *     fragment: `#version 300 es\n *       {{header}}\n *       void main() {\n *         {{body}}\n *       }\n *     `,\n *   },\n * };\n * ```\n * @category rendering\n * @advanced\n */\nexport interface ShaderBitTemplate {\n  /**\n   * The bind groups the shader binds, in `@group` index order\n   *\n   * A template that draws meshes lists `global` then `camera`, since the engine binds those by\n   * index, and a material's template adds `batch` after them for the material's data. List\n   * `global` as `{ name: 'global', ubo: true }` wherever it appears, or the compile throws.\n   */\n  readonly bindGroups: readonly TemplateBindGroup[];\n\n  /** The WGSL source for WebGPU, holding both entry points, named `mainVertex` and `mainFragment` */\n  readonly gpu?: string;\n\n  /** The GLSL sources for WebGL, one per stage, each with a `#version 300 es` line */\n  readonly gl?: {\n    /** GLSL vertex shader template */\n    readonly vertex: string;\n    /** GLSL fragment shader template */\n    readonly fragment: string;\n  };\n\n  /** @internal */\n  _uid?: number;\n}\n\n/** @internal */\nexport function resolveBindGroups(template: ShaderBitTemplate): readonly ResolvedBindGroup[] {\n  return template.bindGroups.map((group) =>\n    typeof group === 'string' ? { name: group, ubo: false } : { name: group.name, ubo: group.ubo ?? false },\n  );\n}\n","import type { ShaderBit } from './ShaderBit';\nimport { resolveBindGroups } from './ShaderBitTemplate';\nimport type { ResolvedBindGroup, ShaderBitTemplate } from './ShaderBitTemplate';\n\nconst registry = new Map<string, ShaderBit>();\n\n/** Leaves out the `_` fields stamped on a bit, which differ between a checked bit and its copy */\nfunction contentSnapshot(bit: ShaderBit): string {\n  return (bit._contentSnapshot ??= JSON.stringify(bit, (key, value) => (key.startsWith('_') ? undefined : value)));\n}\n\n/**\n * Throws when a different bit owns `bit`'s name, since cache keys hold bit names; a bit with the same\n * content is one module loaded twice, such as after a hot reload, and takes the name over\n * @internal\n */\nexport function assertBitIdentity(bit: ShaderBit): void {\n  if (bit._identityChecked) return;\n\n  const existing = registry.get(bit.name);\n\n  if (existing === undefined || existing === bit) {\n    registry.set(bit.name, bit);\n    bit._identityChecked = true;\n    return;\n  }\n\n  if (contentSnapshot(existing) === contentSnapshot(bit)) {\n    registry.set(bit.name, bit);\n    bit._identityChecked = true;\n    return;\n  }\n\n  throw new Error(\n    `[bitRegistry] Two different shader bits share the name '${bit.name}'. Bit names are shader-cache ` +\n      `identities, so this would silently serve one bit's compiled shader for the other. Rename one of ` +\n      `them — or, if you didn't define a second '${bit.name}', two copies of a module/library are loaded.`,\n  );\n}\n\nconst ENGINE_BIND_GROUPS: readonly ResolvedBindGroup[] = [\n  { name: 'global', ubo: true },\n  { name: 'camera', ubo: false },\n  { name: 'batch', ubo: false },\n];\n\nfunction templateEntry(group: ResolvedBindGroup): string {\n  return group.ubo ? `\\`{ name: '${group.name}', ubo: true }\\`` : `\\`'${group.name}'\\``;\n}\n\n/**\n * Throws, naming the fix, where a template and its bits disagree about the engine's bind groups;\n * each case otherwise fails later with an error that names nothing\n * @internal\n */\nexport function assertBindGroups(bits: readonly ShaderBit[], template: ShaderBitTemplate): void {\n  const groups = resolveBindGroups(template);\n\n  for (const engineGroup of ENGINE_BIND_GROUPS) {\n    const { name, ubo } = engineGroup;\n    const listed = groups.find((group) => group.name === name);\n    const declaredBy = bits.find((bit) => bit.bindings?.[name]);\n\n    if (declaredBy && !listed) {\n      throw new Error(\n        `The shader bit '${declaredBy.name}' declares the '${name}' bind group, but the shader template ` +\n          `doesn't list it. Add ${templateEntry(engineGroup)} to the template's \\`bindGroups\\`.`,\n      );\n    }\n    if (name === 'camera' && listed && !declaredBy) {\n      throw new Error(\n        \"The shader template lists a 'camera' bind group but no bit declares it. \" +\n          'Leave `includeCamera` on (the default), or list `cameraBit` in the descriptor.',\n      );\n    }\n    if (listed && listed.ubo !== ubo) {\n      throw new Error(\n        `The shader template lists the '${name}' bind group ${ubo ? 'without' : 'with'} \\`ubo: true\\`. ` +\n          `List it as ${templateEntry(engineGroup)} in \\`bindGroups\\`, because the engine binds '${name}' as ` +\n          `${ubo ? 'one uniform block' : 'plain uniforms'} on WebGL.`,\n      );\n    }\n  }\n}\n","const OUTPUT_NAME = /^[a-z][A-Za-z0-9]*$/;\n\n/** GLSL ES 3.20 keywords (section 3.7), a superset of 3.00's */\nconst GLSL_KEYWORDS =\n  'const uniform buffer shared coherent volatile restrict readonly writeonly layout centroid flat smooth patch ' +\n  'sample invariant precise break continue do for while switch case default if else in out inout int void bool ' +\n  'true false float discard return vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 uint uvec2 uvec3 uvec4 mat2 ' +\n  'mat3 mat4 mat2x2 mat2x3 mat2x4 mat3x2 mat3x3 mat3x4 mat4x2 mat4x3 mat4x4 lowp mediump highp precision sampler2D ' +\n  'sampler2DShadow sampler2DArray sampler2DArrayShadow isampler2D isampler2DArray usampler2D usampler2DArray ' +\n  'sampler2DMS isampler2DMS usampler2DMS sampler2DMSArray isampler2DMSArray usampler2DMSArray sampler3D isampler3D ' +\n  'usampler3D samplerCube samplerCubeShadow isamplerCube usamplerCube samplerCubeArray samplerCubeArrayShadow ' +\n  'isamplerCubeArray usamplerCubeArray samplerBuffer isamplerBuffer usamplerBuffer image2D iimage2D uimage2D ' +\n  'image2DArray iimage2DArray uimage2DArray image3D iimage3D uimage3D imageCube iimageCube uimageCube ' +\n  'imageCubeArray iimageCubeArray uimageCubeArray imageBuffer iimageBuffer uimageBuffer struct';\n\n/** GLSL ES 3.20 words reserved for future use (section 3.7) */\nconst GLSL_RESERVED =\n  'attribute varying noperspective subroutine common partition active asm class union enum typedef template this ' +\n  'resource goto inline noinline public static extern external interface long short half fixed unsigned superp ' +\n  'double input output hvec2 hvec3 hvec4 fvec2 fvec3 fvec4 dvec2 dvec3 dvec4 dmat2 dmat3 dmat4 dmat2x2 dmat2x3 ' +\n  'dmat2x4 dmat3x2 dmat3x3 dmat3x4 dmat4x2 dmat4x3 dmat4x4 filter sizeof cast namespace using sampler1D ' +\n  'sampler1DShadow sampler1DArray sampler1DArrayShadow isampler1D isampler1DArray usampler1D usampler1DArray ' +\n  'sampler2DRect sampler2DRectShadow isampler2DRect usampler2DRect sampler3DRect image1D iimage1D uimage1D ' +\n  'image1DArray iimage1DArray uimage1DArray image2DRect iimage2DRect uimage2DRect image2DMS iimage2DMS uimage2DMS ' +\n  'image2DMSArray iimage2DMSArray uimage2DMSArray';\n\n/** WGSL keywords (\"Keyword Summary\") */\nconst WGSL_KEYWORDS =\n  'alias break case const continue continuing default diagnostic discard else enable false fn for if let loop ' +\n  'override requires return struct switch true var while';\n\n/** WGSL reserved words (\"Reserved Words\") */\nconst WGSL_RESERVED =\n  'abstract active alignas alignof as asm async attribute auto await become cast catch class coherent common ' +\n  'compile concept consteval constexpr constinit crate debugger decltype delete demote do enum explicit export ' +\n  'extends extern external fallthrough filter final finally friend from fxgroup get goto groupshared highp impl ' +\n  'implements import inline instanceof interface layout lowp macro match mediump meta mod module move mut mutable ' +\n  'namespace new nil noexcept noinline nointerpolation noncoherent noperspective null nullptr of operator package ' +\n  'packoffset partition pass patch pixelfragment precise precision premerge priv protected pub public readonly ref ' +\n  'regardless register require resource restrict self set shared sizeof smooth snorm static std subroutine super ' +\n  'target template this throw trait try type typedef typeid typename typeof union unless unorm unsafe unsized use ' +\n  'using varying virtual volatile wgsl where with writeonly yield';\n\nconst RESERVED = new Set([GLSL_KEYWORDS, GLSL_RESERVED, WGSL_KEYWORDS, WGSL_RESERVED].join(' ').split(' '));\n\n/**\n * The lowercase start keeps two names off one GLSL output variable, `frag<Name>`\n * @internal\n */\nexport function assertOutputName(name: string, where: string): void {\n  if (!OUTPUT_NAME.test(name)) {\n    throw new Error(\n      `${where}: '${name}' can't name a fragment output. Start it with a lowercase letter and use only ` +\n        'letters and digits, such as \"velocity\" or \"objectId\".',\n    );\n  }\n  if (RESERVED.has(name)) {\n    throw new Error(\n      `${where}: '${name}' can't name a fragment output, because WGSL or GLSL reserves the word. Pick ` +\n        'another name, such as one with a prefix.',\n    );\n  }\n}\n","import type { FragmentOutputType, ShaderBit } from '../ShaderBit';\nimport { assertOutputName } from './assertOutputName';\n\n/**\n * Compared by identity, which leaves the default out of descriptor cache keys\n * @internal\n */\nexport const DEFAULT_OUTPUT_LOCATIONS: readonly string[] = Object.freeze(['color']);\n\n/** @internal */\nexport function collectFragmentOutputs(bits: readonly ShaderBit[]): Record<string, FragmentOutputType> {\n  const declared: Record<string, FragmentOutputType> = Object.create(null);\n  const declaredBy: Record<string, string> = Object.create(null);\n\n  for (const bit of bits) {\n    if (!bit.outputs) continue;\n\n    for (const [name, type] of Object.entries(bit.outputs)) {\n      const existing = declared[name];\n\n      if (existing === undefined) {\n        assertOutputName(name, `Bit '${bit.name}'`);\n        declared[name] = type;\n        declaredBy[name] = bit.name;\n      } else if (existing !== type) {\n        throw new Error(\n          `[collectFragmentOutputs] Output \"${name}\" is \"${existing}\" in bit \"${declaredBy[name]}\" ` +\n            `and \"${type}\" in bit \"${bit.name}\". Bits that share an output must agree on its type.`,\n        );\n      }\n    }\n  }\n\n  return declared;\n}\n","import { assertBitIdentity } from './bitRegistry';\nimport { DEFAULT_OUTPUT_LOCATIONS } from './codegen/collectFragmentOutputs';\nimport type { ShaderBit } from './ShaderBit';\nimport type { ShaderBitTemplate } from './ShaderBitTemplate';\n\nlet nextTemplateUid = 0;\n\nconst outputKeys = new WeakMap<readonly string[], string>();\n\n/**\n * Options for a {@link ShaderDescriptor}: the {@link ShaderBit}s a shader is built from\n *\n * Each backend takes its own list, because a few bits exist for one backend only. Most lists name\n * the same bits.\n * @category rendering\n * @advanced\n */\nexport interface ShaderDescriptorOptions {\n  /**\n   * Shader bits for the WebGPU (WGSL) backend\n   * @default []\n   */\n  bitsGpu?: ShaderBit[];\n  /**\n   * Shader bits for the WebGL (GLSL) backend\n   * @default []\n   */\n  bitsGl?: ShaderBit[];\n  /**\n   * Custom shader template\n   *\n   * Left out, a material's `descriptor` uses the engine's material template. A pass's descriptor\n   * has no default and must set one.\n   */\n  template?: ShaderBitTemplate;\n  /**\n   * Values for the bits' specialization constants ({@link ShaderOverrideDef}), such as\n   * `{ OUTLINE_WIDTH: 0.1 }`\n   *\n   * Each distinct set of values compiles its own shader.\n   */\n  overrides?: Record<string, number>;\n  /**\n   * Which of the bits' {@link ShaderBit#outputs} each location writes, by name: entry `n` is\n   * location `n`, the target's colour attachment `n`\n   *\n   * An output left out never reaches the GPU, and a name no bit declares leaves its attachment\n   * alone. A material's `descriptor` ignores it, since the engine sets a material shader's\n   * locations. Each distinct list compiles its own shader. A template without the output slots\n   * ignores it.\n   * @default ['color']\n   */\n  outputLocations?: readonly string[];\n  /**\n   * Whether the compiler adds the view-wide values, such as the lights and fog, in the `global` bind\n   * group\n   *\n   * Set `false` for a template with no `global` group, or when the bits declare a `global` group of\n   * their own. A material's `descriptor` ignores it and always has them.\n   * @default true\n   */\n  includeGlobal?: boolean;\n  /**\n   * Whether the compiler adds the camera's position and matrices in the `camera` bind group\n   *\n   * Set it to match the template: `false` for one with no `camera` group. The compile throws when\n   * they disagree. A material's `descriptor` ignores it and always has them.\n   * @default true\n   */\n  includeCamera?: boolean;\n}\n\n/**\n * The {@link ShaderBit}s a shader is built from, per backend, with its template and overrides\n *\n * A material's `descriptor` option sets the bits of its main shader. Its `passes` option gives an\n * extra render pass, such as an outline, a descriptor of its own, keyed by pass name, as options\n * or as a built descriptor. The renderer adds the bits a mesh needs, such as skinning, so a\n * material lists only its own.\n * @example\n * ```ts\n * new BaseMaterial3D({\n *   descriptor: { bitsGpu: [myBit], bitsGl: [myBit] },\n * });\n *\n * new BaseMaterial3D({\n *   descriptor: { bitsGpu: [myBit], bitsGl: [myBit] },\n *   passes: {\n *     outline: {\n *       shaderDescriptor: {\n *         bitsGpu: [outlineBit], bitsGl: [outlineBit],\n *         template: outlineTemplate,\n *       },\n *     },\n *   },\n * });\n * ```\n * @category rendering\n * @advanced\n */\nexport class ShaderDescriptor {\n  /** Shader bits for the WebGPU (WGSL) backend */\n  public bitsGpu: ShaderBit[];\n  /** Shader bits for the WebGL (GLSL) backend */\n  public bitsGl: ShaderBit[];\n  /** Custom shader template; see {@link ShaderDescriptorOptions#template} */\n  public template?: ShaderBitTemplate;\n  /** Values for the bits' specialization constants; see {@link ShaderDescriptorOptions#overrides} */\n  public overrides?: Record<string, number>;\n  /** Which output each location writes, by name; see {@link ShaderDescriptorOptions#outputLocations} */\n  public outputLocations: readonly string[];\n  /** See {@link ShaderDescriptorOptions#includeGlobal} */\n  public includeGlobal?: boolean;\n  /** See {@link ShaderDescriptorOptions#includeCamera} */\n  public includeCamera?: boolean;\n\n  /** @internal */\n  public keyGpu!: string;\n  /** @internal */\n  public keyGl!: string;\n\n  constructor(options: ShaderDescriptorOptions) {\n    this.bitsGpu = options.bitsGpu ?? [];\n    this.bitsGl = options.bitsGl ?? [];\n    this.template = options.template;\n    this.overrides = options.overrides;\n    this.outputLocations = options.outputLocations ?? DEFAULT_OUTPUT_LOCATIONS;\n    this.includeGlobal = options.includeGlobal;\n    this.includeCamera = options.includeCamera;\n    this._updateKeys();\n  }\n\n  /**\n   * Replaces every field from `options`, as the constructor would; a field left out goes back to\n   * its default\n   * @param options - The new descriptor contents\n   * @returns This descriptor, for chaining\n   */\n  public update(options: ShaderDescriptorOptions): this {\n    this.bitsGpu = options.bitsGpu ?? [];\n    this.bitsGl = options.bitsGl ?? [];\n    this.template = options.template;\n    this.overrides = options.overrides;\n    this.outputLocations = options.outputLocations ?? DEFAULT_OUTPUT_LOCATIONS;\n    this.includeGlobal = options.includeGlobal;\n    this.includeCamera = options.includeCamera;\n    this._updateKeys();\n\n    return this;\n  }\n\n  /** Checks each bit's claim to its name first, since the keys hold bit names in place of the bits */\n  private _updateKeys(): void {\n    for (let i = 0; i < this.bitsGpu.length; i++) assertBitIdentity(this.bitsGpu[i]);\n    for (let i = 0; i < this.bitsGl.length; i++) assertBitIdentity(this.bitsGl[i]);\n\n    let keyGpu = this.bitsGpu.map((b) => b.name).join('|');\n    let keyGl = this.bitsGl.map((b) => b.name).join('|');\n\n    if (this.overrides) {\n      const overrideKey = Object.entries(this.overrides)\n        .map(([k, v]) => `${k}=${v}`)\n        .join(',');\n      keyGpu += `[${overrideKey}]`;\n      keyGl += `[${overrideKey}]`;\n    }\n\n    if (this.outputLocations !== DEFAULT_OUTPUT_LOCATIONS) {\n      let outputKey = outputKeys.get(this.outputLocations);\n      if (outputKey === undefined) {\n        outputKey = `|out:${this.outputLocations.join(',')}`;\n        outputKeys.set(this.outputLocations, outputKey);\n      }\n      keyGpu += outputKey;\n      keyGl += outputKey;\n    }\n\n    if (this.template) {\n      const uid = (this.template._uid ??= nextTemplateUid++);\n      keyGpu += `|tpl:${uid}`;\n      keyGl += `|tpl:${uid}`;\n    }\n\n    this.keyGpu = keyGpu;\n    this.keyGl = keyGl;\n  }\n}\n","import type { State, Topology } from 'pixi.js';\n\nimport { ShaderDescriptor } from '../core/shader/ShaderDescriptor';\nimport type { ShaderDescriptorOptions } from '../core/shader/ShaderDescriptor';\n\n/**\n * A material's or a pass's overrides for one render pass\n *\n * Given per pass name in the `passes` option of {@link BaseMaterial3D}, and as `descriptor` when\n * creating a `RenderPass`; {@link PassDescriptor} says how they combine.\n * @category materials\n * @advanced\n */\nexport interface PassDescriptorOptions {\n  /** Shader to draw with in this pass; plain options are wrapped in a {@link ShaderDescriptor} */\n  shaderDescriptor?: ShaderDescriptor | ShaderDescriptorOptions;\n  /** Render state (blending, depth, culling) for this pass */\n  state?: State;\n  /** Primitive topology for this pass; see {@link BaseMaterial3DOptions#topology} for `'line-list'` */\n  topology?: Topology;\n}\n\n/**\n * Pass overrides as the engine stores them: {@link PassDescriptorOptions} with the shader always a\n * {@link ShaderDescriptor}\n *\n * When the material's entry for a pass, or the pass's own descriptor, sets `shaderDescriptor`, as\n * an outline or the shadow pass does, the pass takes each field from the first that is set:\n *\n * - `shaderDescriptor`: the material's entry, then the pass's own.\n * - `state`: the material's entry, the pass's own, then `material.state`.\n * - `topology`: the material's entry, the pass's own, `material.topology`, then the geometry's.\n *\n * That shader can't read the material's values or textures. Otherwise a material's main pass\n * (opaque, transparent, transmission or blended refraction) draws with the material's shader, from\n * {@link BaseMaterial3D#getPrimaryDescriptor}, and skips the pass's own entry: `state` comes from\n * the material's entry, then `material.state`, and `topology` from the material's entry,\n * `material.topology`, then the geometry's.\n *\n * Meshes resolve these values when they build their draw data, so giving a field a new value after\n * a render isn't supported: {@link BaseMaterial3D#clone | clone} the material with the new entry\n * and assign the copy. A changed field of a `state`\n * object reaches the meshes after {@link Mesh3D#invalidate} on each one.\n * @example\n * ```ts\n * // Per-material override for one pass\n * new BaseMaterial3D({\n *   passes: {\n *     outline: {\n *       state: customState,\n *       shaderDescriptor: { bitsGpu: [outlineBitGpu], bitsGl: [outlineBitGl], template: outlineTemplate },\n *     },\n *   },\n * });\n *\n * // Pass-level default for every mesh in the pass\n * new MeshPass({\n *   name: 'xray',\n *   descriptor: { state: xrayState, shaderDescriptor: xrayShader },\n * });\n * ```\n * @category materials\n * @advanced\n */\nexport interface PassDescriptor {\n  /** Shader to draw with in this pass */\n  shaderDescriptor?: ShaderDescriptor;\n  /** Render state (blending, depth, culling) for this pass */\n  state?: State;\n  /** Primitive topology for this pass */\n  topology?: Topology;\n}\n\n/**\n * Wraps plain shader options in a {@link ShaderDescriptor}\n * @internal\n */\nexport function normalizePassEntry(options: PassDescriptorOptions): PassDescriptor {\n  return {\n    shaderDescriptor:\n      options.shaderDescriptor === undefined\n        ? undefined\n        : options.shaderDescriptor instanceof ShaderDescriptor\n          ? options.shaderDescriptor\n          : new ShaderDescriptor(options.shaderDescriptor),\n    state: options.state,\n    topology: options.topology,\n  };\n}\n","import type { Shader, State, Topology } from 'pixi.js';\n\nimport type { Geometry3D } from '../../geometry/Geometry3D';\nimport type { BaseMaterial3D } from '../../materials/BaseMaterial3D';\nimport type { Sphere } from '../../math/shapes/Sphere';\nimport type { BillboardMode } from '../../scene/Mesh3D';\nimport type { Morph } from '../../scene/Morph';\nimport type { Skeleton } from '../../scene/Skeleton';\n\n/**\n * What one mesh draws with in one pass; a class, so the batcher's reads of every entry stay monomorphic\n * @internal\n */\nexport class MeshPassCache {\n  public shader: Shader;\n  /** WebGPU only: the merged-run form of `shader`, `null` until a run merges and whenever `shader` is rebuilt */\n  public mergedShader: Shader | null = null;\n  public state: State;\n  public topology: Topology;\n  public batchKey = 0;\n  /**\n   * The geometry uid the entry was resolved from, or -1 to resolve it again; a uid, so the entry never\n   * pins a destroyed geometry\n   */\n  public lastGeometryUid = -1;\n  public lastMaterialUid = -1;\n\n  constructor(shader: Shader, state: State, topology: Topology) {\n    this.shader = shader;\n    this.state = state;\n    this.topology = topology;\n  }\n\n  /**\n   * Whether a pass with a shader of its own has to resolve the entry again; the uids are compared\n   * apart, since packing them would truncate one\n   */\n  public isStaleFor(item: Mesh3DData): boolean {\n    return (\n      this.shader._destroyed || this.lastGeometryUid !== item.geometry.uid || this.lastMaterialUid !== item.material.uid\n    );\n  }\n\n  public claimBuiltFrom(item: Mesh3DData): void {\n    this.lastGeometryUid = item.geometry.uid;\n    this.lastMaterialUid = item.material.uid;\n  }\n}\n\n/**\n * Anything the renderer draws: a scene {@link Mesh3D}, or a slot of a {@link BatchedMesh3D}\n * @internal\n */\nexport interface Mesh3DData {\n  /** The item's id, unique within its batch; sorted views key items by it */\n  uid: number;\n\n  /**\n   * The draw-order key `updateMesh3DKeys` writes; the transparent pass overwrites it each frame with\n   * the negated squared distance to the camera\n   */\n  _sortKey: number;\n\n  geometry: Geometry3D;\n  material: BaseMaterial3D;\n\n  /** The item's row in its batch's store, or -1 while it has none */\n  _storeIndex: number;\n\n  /** Whether the item's shader, keys and pass data wait for a rebuild; a slot with it set is queued */\n  _batchDirty: boolean;\n\n  /** `RenderPassBit` flags of the passes the item is in */\n  _lastRenderPass: number;\n\n  /**\n   * The material's `_descriptorDirtyId` at the last rebuild; -1 marks a new material, which the draw\n   * lists take as an edit rather than a rebuild\n   */\n  _lastDescriptorDirtyId: number;\n\n  skeleton?: Skeleton;\n  _morph?: Morph;\n\n  /**\n   * The item's pass-cache entry per `RenderPassBit`; on a material's own pass bit `ensureMaterial`\n   * writes first, so a pass's own shader wins\n   */\n  _passCache: Record<number, MeshPassCache>;\n\n  receiveShadow: boolean;\n\n  /** How the item turns to face the camera; never `undefined`, so every implementation keeps one hidden class */\n  billboardMode: BillboardMode;\n\n  /** Whether the item is visible, as 0 or 1; a hidden item stays in its draw lists */\n  readonly _worldVisible: number;\n\n  /**\n   * The item's bounding sphere: world space for a scene mesh, relative to the {@link BatchedMesh3D} for a slot\n   *\n   * Dynamic geometry gives an empty sphere (`radius < 0`). The sphere is shared: `clone()` it to keep\n   * a copy.\n   */\n  readonly boundingSphere: Sphere;\n}\n","import type { State } from 'pixi.js';\n\n/**\n * Gives `target` every setting of `source`; `data` goes last, because the `blendMode` and\n * `polygonOffset` setters also write flags into it\n * @internal\n */\nexport function copyState(target: State, source: State): void {\n  target.blendMode = source.blendMode;\n  target.polygonOffset = source.polygonOffset;\n  target.data = source.data;\n}\n","import { State } from 'pixi.js';\n\nimport type { AlphaMode } from '../../materials/BaseMaterial3D';\nimport { copyState } from '../../utils/copyState';\n\nconst PIPELINE_OFFSET = 0x1_0000_0000;\nconst FIELD_MASK = 0xfff;\nconst GEOM_OFFSET = 1 << 12;\nconst TEXTURE_SET_OFFSET = 1 << 24;\nconst TEXTURE_SET_MASK = 0xffff;\nconst PIPELINE_SORT_OFFSET = 2 ** 40;\nconst PIPELINE_FIELD_MASK = 0xff;\nconst LAYOUT_OFFSET = 2 ** 48;\nconst LAYOUT_MAX = 15;\nconst CUTOUT_OFFSET = LAYOUT_OFFSET * (LAYOUT_MAX + 1);\nconst ATLAS_SHIFT = 8;\n\n/** Counted ids for the backends' pipeline keys, never freed, like pixi's `uid()`; exact in a batch key up to 2^21 */\nconst pipelineIdsByKey = new Map<number, number>();\nlet nextPipelineId = 0;\n\nfunction getOrAllocatePipelineId(key: number): number {\n  let id = pipelineIdsByKey.get(key);\n\n  if (id === undefined) {\n    id = nextPipelineId++;\n    pipelineIdsByKey.set(key, id);\n  }\n\n  return id;\n}\n\nconst pipelineStates: State[] = [];\n\n/**\n * The pipeline's own copy of a mesh's state, never freed, for commands to bind, since materials change theirs in place\n *\n * It's exact while the pipeline key covers every field a draw applies (`packGlBatchKey` on WebGL).\n * @internal\n */\nexport function pipelineState(batchKey: number, state: State): State {\n  const id = Math.floor(batchKey / PIPELINE_OFFSET);\n  let copy = pipelineStates[id];\n\n  if (!copy) {\n    copy = pipelineStates[id] = new State();\n    copyState(copy, state);\n  }\n\n  return copy;\n}\n\ninterface KeyedMesh {\n  _sortKey: number;\n  geometry: { uid: number; _geometryAtlasAllocation: { atlas: { uid: number } } | null };\n  material: { uid: number; _textures: ArrayLike<unknown>; _textureSetId: number; alphaMode: AlphaMode };\n}\n\n/**\n * Writes a mesh's batch key into its pass-cache entry and its sort key onto the mesh\n *\n * The batch key, `pipelineId * 2^32 + geometry.uid`, stays exact: equal keys draw as one. Sort keys may collide.\n * Cutout meshes sort last, so the depth test rejects their hidden fragments before they shade, and material\n * lowest, so a run meets each material once.\n * @param renderable - The mesh whose `_sortKey` is written\n * @param cache - The pass-cache entry the caller already holds, which receives the batch key\n * @param pipelineKey - The backend's pipeline key\n * @internal\n */\nexport function updateMesh3DKeys(renderable: KeyedMesh, cache: { batchKey: number }, pipelineKey: number): void {\n  const pipelineId = getOrAllocatePipelineId(pipelineKey);\n  const geometry = renderable.geometry;\n  const alloc = geometry._geometryAtlasAllocation;\n\n  cache.batchKey = pipelineId * PIPELINE_OFFSET + geometry.uid;\n\n  const geomLocality = alloc ? (alloc.atlas.uid << ATLAS_SHIFT) | (geometry.uid & 0xff) : geometry.uid;\n  const material = renderable.material;\n\n  renderable._sortKey =\n    (material.alphaMode === 'mask' ? CUTOUT_OFFSET : 0) +\n    Math.min(material._textures.length, LAYOUT_MAX) * LAYOUT_OFFSET +\n    (pipelineId & PIPELINE_FIELD_MASK) * PIPELINE_SORT_OFFSET +\n    (material._textureSetId & TEXTURE_SET_MASK) * TEXTURE_SET_OFFSET +\n    (geomLocality & FIELD_MASK) * GEOM_OFFSET +\n    (material.uid & FIELD_MASK);\n}\n","import type { RgbaArray, TEXTURE_FORMATS } from 'pixi.js';\n\nimport { assertOutputName } from '../shader/codegen/assertOutputName';\nimport type { ShaderBit } from '../shader/ShaderBit';\n\n/**\n * The scene passes a {@link SceneOutput#bits | scene output's bits} can name\n * @category rendering\n * @advanced\n */\nexport type SceneOutputPass = 'opaque' | 'transmission' | 'transparent';\n\nconst BIT_PASSES = Object.keys({\n  opaque: true,\n  transmission: true,\n  transparent: true,\n} satisfies Record<SceneOutputPass, true>) as SceneOutputPass[];\n\nconst checked = new WeakSet<SceneOutput>();\n\n/**\n * A texture the scene draw writes besides its colour, such as object IDs, for passes to read\n *\n * A plain object known by its name, like a {@link ShaderBit}: two with the same name and content\n * count as one, and two that differ throw when a view collects them. A view creates and writes the\n * texture only while an enabled pass lists the output in {@link Pass3D#requiredOutputs}, or\n * {@link DefaultGraph3DOptions#sceneOutputs} does, and passes reach it with\n * {@link RenderGraph#getSceneOutput}. Three things write it: its {@link SceneOutput#bits | bits}, a\n * material's own bits that declare it in `outputs`, and a pass that draws into it.\n *\n * Each frame it starts cleared to its {@link SceneOutput#clearValue | clearValue}, and a draw that\n * doesn't write it leaves it alone. It lasts only for the frame: to keep it past `render()`, copy\n * it into a texture the app owns, for example with a {@link FullscreenPass} running\n * {@link passthroughFragment}. A pass that only reads it, such as a readback to the CPU, needs\n * {@link PassBuilder#sideEffect}.\n *\n * Each output is one more colour attachment on the scene passes, and GPUs cap those. WebGPU allows 8,\n * and 32 bytes per pixel across the colour and every output, where `rgba8unorm` counts 8 bytes, as\n * `rgba16float` does. WebGL allows at least 4. Pick the smallest format that holds the value; a\n * view over the cap throws when it renders.\n *\n * On a canvas with `antialias`, the output is multisampled with the scene, which takes four times\n * its texture's memory, and an edge pixel reads the average of its samples, the clear value\n * included where nothing drew. An integer or 32-bit float format turns that off, and so does\n * `rgba8unorm` on WebGL: while one is attached, the view draws its scene single-sample and its\n * edges go jagged.\n * @example\n * ```ts\n * const objectIdOutput: SceneOutput = { name: 'objectId', format: 'r32uint', clearValue: [0xffffffff, 0, 0, 0] };\n *\n * class MyPickingPass extends Pass3D {\n *   public readonly stage = 'afterTransparent';\n *   public readonly requiredOutputs = [objectIdOutput];\n *\n *   public build(graph: RenderGraph): void {\n *     graph.addPass(new MyPickReadbackPass(graph.getSceneOutput(objectIdOutput)));\n *   }\n * }\n * ```\n * @category rendering\n * @advanced\n */\nexport interface SceneOutput {\n  /**\n   * The field material shaders write as `outputs.<name>`, and the texture's label\n   *\n   * A lowercase letter, then letters and digits, such as `objectId`. Not `color`, which is the scene\n   * colour's, or a word WGSL or GLSL reserves.\n   */\n  readonly name: string;\n  /** Format of the output's texture; some formats turn the view's MSAA off, see {@link SceneOutput} */\n  readonly format: TEXTURE_FORMATS;\n  /**\n   * The bit each scene pass gives its materials so they write the output, keyed by pass name; see\n   * {@link RenderPass#materialBits}\n   *\n   * `{ opaque: myBit }` is the usual form: opaque surfaces write it, and transparent and glass\n   * surfaces leave what is behind them. Add `transparent` or `transmission` for those surfaces to\n   * write it too. Leave `bits` out for an output only some materials write, through their own bits,\n   * or one a pass draws into. Each bit must declare the output in its `outputs`.\n   *\n   * Blended surfaces blend what they write, so a `transparent` bit must write a float or normalized\n   * output as a `vec4`, or the view throws. Integer formats such as `r32uint` never blend, so a\n   * blended surface overwrites what is behind it: use one for IDs and masks.\n   *\n   * A material with a template of its own, or a pass with a shader of its own such as a\n   * {@link MeshPass}, leaves every output as it was.\n   */\n  readonly bits?: Readonly<Partial<Record<SceneOutputPass, ShaderBit>>>;\n  /**\n   * What the texture holds before anything draws into it each frame, as four numbers in the\n   * format's channel order; integer formats take them as integers\n   *\n   * Pick a value no writer produces, so a reader can tell where nothing drew, such as the far\n   * distance for a depth-like output or `0xffffffff` for an object ID.\n   * @default [0, 0, 0, 0]\n   */\n  readonly clearValue?: RgbaArray;\n}\n\n/** @internal */\nexport function assertSceneOutput(output: SceneOutput): void {\n  if (checked.has(output)) return;\n\n  const { name, bits } = output;\n  assertOutputName(name, 'SceneOutput');\n  if (name === 'color') {\n    throw new Error(\"SceneOutput: 'color' is the scene colour's own output. Give the output another name.\");\n  }\n  for (const pass in bits) {\n    const bit = bits[pass as SceneOutputPass]!;\n    const type = bit.outputs?.[name];\n    if (!type) {\n      throw new Error(\n        `SceneOutput '${name}': bit '${bit.name}' for the ${pass} pass doesn't declare it. Add \\`${name}\\` ` +\n          \"to the bit's `outputs`.\",\n      );\n    }\n    if (pass === 'transparent' && type !== 'vec4<f32>' && !output.format.includes('int')) {\n      throw new Error(\n        `SceneOutput '${name}': bit '${bit.name}' for the transparent pass writes it as ${type}. A blended ` +\n          \"surface blends what it writes, and WebGPU's blend reads the alpha, so write a float output as \" +\n          'vec4<f32>, or give the output an integer format, which never blends.',\n      );\n    }\n  }\n\n  checked.add(output);\n}\n\n/**\n * Compares bits by name, their identity across the engine\n * @internal\n */\nexport function sameSceneOutput(a: SceneOutput, b: SceneOutput): boolean {\n  if (a === b) return true;\n  if (a.name !== b.name || a.format !== b.format) return false;\n\n  const ca = a.clearValue;\n  const cb = b.clearValue;\n  if (ca !== cb && (!ca || !cb || ca[0] !== cb[0] || ca[1] !== cb[1] || ca[2] !== cb[2] || ca[3] !== cb[3])) {\n    return false;\n  }\n\n  for (let i = 0; i < BIT_PASSES.length; i++) {\n    const pass = BIT_PASSES[i];\n    if (a.bits?.[pass]?.name !== b.bits?.[pass]?.name) return false;\n  }\n  return true;\n}\n","import type { Pass3D } from '../../post-processing/Pass3D';\nimport type { RenderPass } from '../render-passes/RenderPass';\nimport type { ShaderBit } from '../shader/ShaderBit';\nimport { assertSceneOutput, sameSceneOutput } from './SceneOutput';\nimport type { SceneOutput, SceneOutputPass } from './SceneOutput';\n\n/**\n * Sorted by name, so the same set of outputs always gives the same attachments and material shaders\n * @internal\n */\nexport function collectSceneOutputs(passes: readonly Pass3D[], extra: readonly SceneOutput[] = []): SceneOutput[] {\n  const outputs: SceneOutput[] = [];\n  const add = (output: SceneOutput, user: string): void => {\n    assertSceneOutput(output);\n    const named = outputs.find((o) => o.name === output.name);\n    if (named && sameSceneOutput(named, output)) return;\n    if (named) {\n      throw new Error(\n        `${user} uses a scene output named '${output.name}', and another pass uses a ` +\n          'different one with that name. Share one definition between them, or rename one.',\n      );\n    }\n    outputs.push(output);\n  };\n\n  for (let i = 0; i < passes.length; i++) {\n    const pass = passes[i];\n    const used = pass.enabled ? pass.requiredOutputs : undefined;\n    if (!used) continue;\n    for (let r = 0; r < used.length; r++) add(used[r], pass.constructor.name);\n  }\n  for (let i = 0; i < extra.length; i++) add(extra[i], \"createDefaultGraph3D's `sceneOutputs`\");\n\n  return outputs.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\n/** @internal */\nexport function materialBitsFor(outputs: readonly SceneOutput[], pass: string): ShaderBit[] {\n  const bits: ShaderBit[] = [];\n  for (let i = 0; i < outputs.length; i++) {\n    const bit = outputs[i].bits?.[pass as SceneOutputPass];\n    if (bit) bits.push(bit);\n  }\n  return bits;\n}\n\n/**\n * Returns `undefined`, which compiles the colour alone, when there's no `pass` yet or `ownTemplate` is set\n * @internal\n */\nexport function addPassMaterialBits(\n  bits: ShaderBit[],\n  pass: RenderPass | undefined,\n  ownTemplate: boolean,\n): readonly string[] | undefined {\n  if (!pass || ownTemplate) return undefined;\n\n  const materialBits = pass.materialBits;\n  for (let i = 0; i < materialBits.length; i++) bits.push(materialBits[i]);\n\n  return pass.outputLocations;\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport { normalizePassEntry } from '../../materials/PassDescriptor';\nimport type { PassDescriptor, PassDescriptorOptions } from '../../materials/PassDescriptor';\nimport type { Camera3D } from '../../scene/cameras/Camera3D';\nimport type { Mesh3DBatch } from '../batcher/Mesh3DBatch';\nimport { MeshPassCache } from '../batcher/Mesh3DData';\nimport type { Mesh3DData } from '../batcher/Mesh3DData';\nimport { updateMesh3DKeys } from '../batcher/updateMesh3DKeys';\nimport type { PassBuilder } from '../render-graph/PassBuilder';\nimport type { SceneOutput } from '../render-graph/SceneOutput';\nimport { materialBitsFor } from '../render-graph/sceneOutputs';\nimport { DEFAULT_OUTPUT_LOCATIONS } from '../shader/codegen/collectFragmentOutputs';\nimport type { ShaderBit } from '../shader/ShaderBit';\nimport type { View3DPipe } from '../View3DPipe';\nimport { passBitRegistry } from './passBitRegistry';\nimport type { RenderSession } from './RenderSession';\n\n/**\n * The render passes a mesh can belong to, as bit flags\n *\n * A mesh rarely needs these set by hand: its `castShadow` puts it in `SHADOW`, and its material\n * puts it in `OPAQUE`, in `TRANSPARENT` when its `alphaMode` is `'blend'`, or in `TRANSMISSION`\n * when it has `transmission`. {@link BatchedMesh3D} slots are the exception, and take these\n * through {@link BatchedMesh3D#setPassesAt}.\n *\n * A custom pass, such as an outline, gets its own bit, from bit 8 up, the first time anything uses\n * its name: the pass itself, a material's `passes` option, {@link BaseMaterial3D#enablePass} or\n * {@link Mesh3D#enablePass}. A page has room for 24 such names: a later name gets no bit, and its\n * pass draws no meshes, with no warning. The built-in passes answer to their names too, so\n * `passes: { shadow: ... }` on a material overrides the shadow pass.\n * @example\n * ```ts\n * batched.setPassesAt(0, RenderPassBit.OPAQUE | RenderPassBit.SHADOW);\n * ```\n * @category rendering\n * @standard\n */\nexport const RenderPassBit = {\n  /**\n   * No pass\n   *\n   * A mesh with it draws nowhere. Give it to a custom pass that draws no meshes, such as a\n   * fullscreen effect, so it uses up no bit; any number of such passes can share a view.\n   */\n  NONE: 0,\n\n  /** Casts shadows; set from the mesh's `castShadow` */\n  SHADOW: 1 << 0,\n  /** Drawn in the opaque pass, where a material goes by default */\n  OPAQUE: 1 << 1,\n  /** Drawn in the transparent pass, back to front; set by a material `alphaMode` of `'blend'` */\n  TRANSPARENT: 1 << 2,\n  /** The sky drawn behind the scene */\n  BACKGROUND: 1 << 3,\n  /**\n   * Glass and other transmissive materials, drawn over a copy of the opaque picture\n   *\n   * Runs after the opaque copy and before {@link RenderPassBit.BLENDED_REFRACTION}.\n   */\n  TRANSMISSION: 1 << 4,\n  /**\n   * Blended materials that refract, such as water, drawn over copies of the opaque colour and depth\n   *\n   * Runs after {@link RenderPassBit.TRANSMISSION} and before {@link RenderPassBit.TRANSPARENT}.\n   */\n  BLENDED_REFRACTION: 1 << 5,\n\n  /** @internal */\n  MATERIAL_PASS_MASK: (1 << 1) | (1 << 2) | (1 << 4) | (1 << 5),\n} as const;\n\n/**\n * Options for constructing a {@link RenderPass}\n * @category rendering\n * @advanced\n */\nexport interface RenderPassOptions {\n  /** Renderer the pass draws with: the {@link PassContext#renderer} a {@link Pass3D#build} call receives */\n  renderer: WebGLRenderer | WebGPURenderer;\n  /**\n   * Stable string identifier for this pass, such as `'shadow'` or `'outline'`\n   *\n   * Materials name the pass by it in their `passes` option, so they never need its bit. Several\n   * passes in a view can share a name to draw the same meshes from different cameras, but only one\n   * of them may leave out `camera`.\n   */\n  name: string;\n  /** Human-readable explanation shown by tooling that inspects the render graph */\n  description?: string;\n  /**\n   * Bit for this pass; leave it out on a custom pass that draws meshes, so its name gets one, and\n   * give {@link RenderPassBit.NONE} to one that draws none\n   */\n  bit?: number;\n  /**\n   * Shader, state and topology this pass uses for every mesh it draws\n   *\n   * Each field is optional, and a material's own entry for this pass name, in its `passes`\n   * option, wins over it; {@link PassDescriptor} lists the full order. Of the passes sharing a\n   * name, only the one with no `camera`, or the first when they all have one, may set this.\n   *\n   * On one of a material's main passes, such as `'opaque'`, a pass with a shader here must be the\n   * only pass with that name, or the others can throw on WebGL.\n   */\n  descriptor?: PassDescriptorOptions;\n  /**\n   * Camera this pass draws from\n   *\n   * Omit it and the pass draws from the view's own camera onto the view. Give it a `Camera3D` in\n   * the same view and the pass culls and draws from that camera instead. Give the camera a\n   * `renderTexture` and the image lands in that texture, for a security feed, a mirror, a portal,\n   * or a minimap shown in a 2D sprite; add such a pass at the `'beforeOpaque'` stage so the scene\n   * can sample the texture the same frame.\n   *\n   * A feed with glass needs its own copies and glass passes. From the {@link Pass3D#build} that\n   * adds the feed's draws, give this camera to a {@link CopyDepthPass}, a {@link CopyOpaquePass}, a\n   * {@link TransmissionRenderPass} and a {@link BlendedRefractionPass}, in that order after the\n   * feed's opaque draw. Allocate the copies' textures with {@link RenderGraph#createColor} and\n   * {@link RenderGraph#createDepth}; {@link PassContext#opaqueColor} and\n   * {@link PassContext#opaqueDepth} hold the view camera's.\n   */\n  camera?: Camera3D;\n  /**\n   * The scene outputs this pass draws into after its colour, in order; see {@link SceneOutput}\n   *\n   * Output `i` is written by the shader's fragment output at location `i + 1`, and a draw leaves\n   * alone any output its shader doesn't write. This differs from {@link Pass3D#requiredOutputs},\n   * which only makes the outputs exist this frame. The default graph gives its scene outputs to its\n   * depth clear, background, opaque, transmission and transparent passes; see\n   * {@link DefaultGraph3DOptions#sceneOutputs}.\n   */\n  attachedOutputs?: readonly SceneOutput[];\n}\n\n/**\n * Base class for all render passes in the pipeline\n *\n * Each view runs its passes in order through its {@link RenderGraph}. A pass goes through these\n * steps:\n * - `setup(builder)` runs once, when the pass is added to the graph, and declares what the pass\n *   reads and writes.\n * - `condition(session)`, if the pass has one, can skip the pass for a frame.\n * - `prepare(session)` runs before any render target is bound.\n * - `render(session)` runs once the graph has bound the pass's target. A pass that declares only\n *   `produce`, `sample` or `read` accesses gets no target bound and does its own GPU work.\n *\n * `P` is the pipe type. Leave it as `View3DPipe` to run on both backends.\n * @category rendering\n * @advanced\n */\nexport class RenderPass<P extends View3DPipe = View3DPipe> {\n  /** The pass's name; see {@link RenderPassOptions#name} */\n  public readonly name: string;\n\n  /** Human-readable explanation of what this pass contributes to the frame */\n  public readonly description?: string;\n\n  /** Bit for this pass: the built-in one it was given, or the one its name was assigned */\n  public bit = 0;\n\n  /** The view pipe of the renderer this pass was built for */\n  public readonly pipe: P;\n\n  /** Shader, state and topology this pass uses for every mesh, from {@link RenderPassOptions#descriptor} */\n  public descriptor?: PassDescriptor;\n\n  /**\n   * Camera this pass draws from, or `null` to draw from the view's own camera\n   *\n   * See {@link RenderPassOptions#camera}. While `render` runs, the GPU viewport is the camera's rect.\n   */\n  public readonly camera: Camera3D | null;\n\n  /** Whether this pass draws in key order; `false` for a pass sorted by distance, which re-sorts every frame */\n  protected _updatesViewKey = true;\n\n  /** The scene outputs attached after the target colour; see {@link RenderPassOptions#attachedOutputs} */\n  public readonly attachedOutputs: readonly SceneOutput[];\n\n  /**\n   * Shader bits a material adds when it draws in this pass, so it writes the attached outputs\n   *\n   * Each attached output's {@link SceneOutput#bits | bits} entry for this pass's name, in order. A\n   * material with a template of its own ignores them.\n   */\n  public readonly materialBits: readonly ShaderBit[];\n\n  /** The output each fragment location of a material shader in this pass writes: `color`, then each attached output */\n  public readonly outputLocations: readonly string[];\n\n  constructor(options: RenderPassOptions) {\n    this.name = options.name;\n    this.description = options.description;\n    this.bit = passBitRegistry.getOrAllocate(options.name, options.bit);\n    this.descriptor = options.descriptor ? normalizePassEntry(options.descriptor) : undefined;\n    this.camera = options.camera ?? null;\n    this.attachedOutputs = options.attachedOutputs ?? [];\n    this.materialBits = materialBitsFor(this.attachedOutputs, this.name);\n    this.outputLocations =\n      this.attachedOutputs.length > 0\n        ? ['color', ...this.attachedOutputs.map((output) => output.name)]\n        : DEFAULT_OUTPUT_LOCATIONS;\n    this.pipe = options.renderer.renderPipes.view3d as unknown as P;\n  }\n\n  /**\n   * Declares writes of its camera's whole target: the colour, the attached outputs, then the depth\n   * @param b - The builder recording this pass's resource accesses\n   */\n  protected _writeTarget(b: PassBuilder): void {\n    b.writeColor(b.targetColor);\n    for (let i = 0; i < this.attachedOutputs.length; i++) b.writeColor(b.getSceneOutput(this.attachedOutputs[i]));\n    b.writeDepth(b.targetDepth);\n  }\n\n  /**\n   * Declares what resources this pass reads, writes, and samples\n   *\n   * The graph calls it once, when the pass is added. The graph only runs a pass whose output the\n   * frame needs, so a pass that keeps this default, which declares nothing, never runs.\n   * @param _builder - The builder recording this pass's resource accesses\n   */\n  public setup(_builder: PassBuilder): void {}\n\n  /**\n   * Optional per-frame check; returning `false` skips the pass, `prepare` and `render` included\n   *\n   * The graph asks it before any pass draws, once the scene's transforms and the view's camera are\n   * up to date for the frame. Without one, the pass runs every frame.\n   * @param session - The current frame's render session\n   * @returns Whether the pass should run this frame\n   */\n  public condition?(session: RenderSession): boolean;\n\n  /**\n   * Runs before any pass draws or any render target is bound, once every pass's camera is current\n   *\n   * Override it to upload GPU buffers early. The default does nothing.\n   * @param _session - The current frame's render session\n   */\n  public prepare(_session: RenderSession): void {}\n\n  /**\n   * Draws this pass's contribution to the frame, once the graph has bound its target\n   *\n   * The default does nothing.\n   * @param _session - The current frame's render session\n   */\n  public render(_session: RenderSession): void {}\n\n  /**\n   * Re-keys a mesh of this pass whose shader, material or geometry changed\n   * @internal\n   */\n  public onRenderableDirty(item: Mesh3DData, batch: Mesh3DBatch, rebuildsLists: boolean): void {\n    const bit = this.bit;\n    const pd = batch.drawLists[bit];\n    const material = item.material;\n\n    if (rebuildsLists || !this._updatesViewKey) {\n      pd.drawDirtyId++;\n    } else {\n      pd.move(item);\n      batch._editsPending = true;\n    }\n\n    const matPd = material._passes[bit];\n    const passPd = this.descriptor;\n    const descriptor = (matPd && matPd.shaderDescriptor) || (passPd && passPd.shaderDescriptor);\n\n    if (descriptor) {\n      const cached = item._passCache[bit];\n      if (!cached || cached.isStaleFor(item)) {\n        const shader = this.pipe.renderer.material3d.compileShader(descriptor, item, batch);\n        const state = (matPd && matPd.state) || (passPd && passPd.state) || material.state;\n        const topology =\n          (matPd && matPd.topology) || (passPd && passPd.topology) || material.topology || item.geometry.topology;\n\n        if (cached) {\n          cached.shader = shader;\n          cached.mergedShader = null;\n          cached.state = state;\n          cached.topology = topology;\n          cached.claimBuiltFrom(item);\n        } else {\n          (item._passCache[bit] = new MeshPassCache(shader, state, topology)).claimBuiltFrom(item);\n        }\n      }\n    }\n\n    const cache = item._passCache[bit];\n    if (!cache) return;\n    updateMesh3DKeys(item, cache, this.pipe.renderer.material3d.computeBatchKey(item, bit));\n    if (this._updatesViewKey) pd.view.updateKey(item.uid, item._sortKey);\n  }\n\n  /**\n   * Releases the GPU resources this pass owns alone\n   *\n   * The graph calls it when the graph is destroyed. Override it to free the shaders, bind groups\n   * or render targets your pass created, leaving alone anything it only borrowed.\n   */\n  public destroy(): void {}\n}\n","import type { Matrix4 } from '../matrix/Matrix4';\nimport type { SHAPE_PRIMITIVE_3D } from '../misc/const';\nimport type { PointData3D } from '../vector/PointData3D';\nimport { Vector3 } from '../vector/Vector3';\nimport { Box } from './Box';\nimport type { Plane } from './Plane';\nimport type { Ray } from './Ray';\n\n/**\n * A sphere from `center` and `radius`, mostly used as a bounding volume\n *\n * The cheapest volume to test, and unlike a {@link Box} it doesn't grow when rotated.\n * {@link Mesh3D#boundingSphere} gives a mesh's bounding sphere in world space.\n * @example\n * ```ts\n * const blast = new Sphere(new Vector3(), 4);\n *\n * blast.center.copyFrom(grenade.position);\n * for (const enemy of enemies) {\n *   if (blast.intersectsSphere(enemy.boundingSphere)) enemy.takeDamage(50);\n * }\n * ```\n * @see {@link Ray#intersectSphere} For the point where a ray hits the sphere\n * @category maths\n * @standard\n */\nexport class Sphere {\n  /**\n   * The center of the sphere\n   * @example\n   * ```ts\n   * pickupRange.center.copyFrom(player.position);\n   * ```\n   */\n  public readonly center: Vector3;\n  /**\n   * The radius of the sphere; negative values mark the sphere as empty\n   * @example\n   * ```ts\n   * shield.radius = 2 + Math.sin(time * 4) * 0.1;\n   * ```\n   */\n  public radius = 0;\n\n  /**\n   * Names the shape without an `instanceof` check, like the `type` on pixi's 2D shapes\n   * @readonly\n   * @default 'sphere'\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type: SHAPE_PRIMITIVE_3D = 'sphere';\n\n  /**\n   * Creates a new `Sphere`\n   *\n   * Left out, the center is the origin and the radius is `-1`, which makes the sphere empty. A center\n   * passed in becomes the sphere's own; it is not copied.\n   * @param center - The center of the sphere\n   * @param radius - The radius of the sphere\n   */\n  constructor(center?: Vector3, radius = -1) {\n    this.center = center !== undefined ? center : new Vector3();\n    this.radius = radius;\n  }\n\n  /**\n   * Sets the center and radius of this sphere, copying the center\n   * @example\n   * ```ts\n   * hearingRange.set(guard.position, 6);\n   * ```\n   * @param center - The center of the sphere\n   * @param radius - The radius of the sphere\n   * @returns This sphere for chaining\n   */\n  public set(center: PointData3D, radius: number): this {\n    this.center.copyFrom(center);\n    this.radius = radius;\n\n    return this;\n  }\n\n  /**\n   * Sets this sphere to the smallest sphere around `box`'s corners; an empty box gives an empty sphere\n   * @example\n   * ```ts\n   * const bounds = new Sphere().setFromBox(model.getLocalBounds());\n   * ```\n   * @param box - The box to bound\n   * @returns This sphere for chaining\n   */\n  public setFromBox(box: Box): this {\n    if (box.isEmpty()) return this.makeEmpty();\n\n    const { min, max } = box;\n    this.center.set((min.x + max.x) * 0.5, (min.y + max.y) * 0.5, (min.z + max.z) * 0.5);\n    const dx = max.x - min.x;\n    const dy = max.y - min.y;\n    const dz = max.z - min.z;\n    this.radius = 0.5 * Math.sqrt(dx * dx + dy * dy + dz * dz);\n\n    return this;\n  }\n\n  /**\n   * Copies `sphere` into this sphere\n   * @example\n   * ```ts\n   * const cached = new Sphere().copyFrom(mesh.boundingSphere);\n   * ```\n   * @param sphere - The sphere to copy from\n   * @returns This sphere for chaining\n   */\n  public copyFrom(sphere: Sphere): this {\n    this.center.copyFrom(sphere.center);\n    this.radius = sphere.radius;\n\n    return this;\n  }\n\n  /**\n   * Copies this sphere into `target` and returns it\n   * @example\n   * ```ts\n   * mesh.boundingSphere.copyTo(cachedBounds);\n   * ```\n   * @param target - The sphere to copy into\n   * @returns The given `target`\n   */\n  public copyTo<T extends Sphere>(target: T): T {\n    target.center.copyFrom(this.center);\n    target.radius = this.radius;\n\n    return target;\n  }\n\n  /**\n   * Creates a new `Sphere` with the same center and radius\n   * @example\n   * ```ts\n   * const snapshot = mesh.boundingSphere.clone();\n   * ```\n   * @returns The new sphere\n   */\n  public clone(): Sphere {\n    return new Sphere().copyFrom(this);\n  }\n\n  /**\n   * Resets this sphere to the empty state (`center = 0`, `radius = -1`)\n   * @example\n   * ```ts\n   * if (!grenade.armed) blast.makeEmpty();\n   * ```\n   * @returns This sphere for chaining\n   */\n  public makeEmpty(): this {\n    this.center.set(0, 0, 0);\n    this.radius = -1;\n\n    return this;\n  }\n\n  /**\n   * Returns true when this sphere is empty (`radius < 0`)\n   * @example\n   * ```ts\n   * if (!mesh.boundingSphere.isEmpty()) zoomTo(mesh.boundingSphere);\n   * ```\n   * @returns Whether this sphere is empty\n   */\n  public isEmpty(): boolean {\n    return this.radius < 0;\n  }\n\n  /**\n   * Returns true when `center` and `radius` match `sphere` exactly (no epsilon tolerance)\n   * @example\n   * ```ts\n   * if (!mesh.boundingSphere.equals(lastBounds)) markShadowDirty();\n   * ```\n   * @param sphere - The sphere to compare with\n   * @returns Whether the center and radius match\n   */\n  public equals(sphere: Sphere): boolean {\n    return sphere.center.equals(this.center) && sphere.radius === this.radius;\n  }\n\n  /**\n   * Returns the signed distance from `point` to the surface of this sphere (negative when inside)\n   * @example\n   * ```ts\n   * const fade = Math.min(1, Math.max(0, -forceField.distanceToPoint(player.position)));\n   * ```\n   * @param point - The point to measure from\n   * @returns The signed distance to the sphere surface\n   */\n  public distanceToPoint(point: PointData3D): number {\n    return this.center.distanceTo(point) - this.radius;\n  }\n\n  /**\n   * Returns true when `point` is inside this sphere (boundary is inclusive)\n   * @example\n   * ```ts\n   * if (pickupRange.containsPoint(coin.position)) collect(coin);\n   * ```\n   * @param point - The point to test\n   * @returns Whether the point is inside this sphere\n   */\n  public containsPoint(point: PointData3D): boolean {\n    return this.center.distanceToSquared(point) <= this.radius * this.radius;\n  }\n\n  /**\n   * Returns true when this sphere and `box` overlap; an empty sphere never does\n   * @example\n   * ```ts\n   * if (blast.intersectsBox(crate.bounds)) crate.shatter();\n   * ```\n   * @param box - The box to test\n   * @returns Whether the sphere and box overlap\n   */\n  public intersectsBox(box: Box): boolean {\n    return box.intersectsSphere(this);\n  }\n\n  /**\n   * Returns true when this sphere and `sphere` overlap; an empty sphere never does\n   * @example\n   * ```ts\n   * if (ball.boundingSphere.intersectsSphere(paddle.boundingSphere)) bounce();\n   * ```\n   * @param sphere - The sphere to test\n   * @returns Whether the spheres overlap\n   */\n  public intersectsSphere(sphere: Sphere): boolean {\n    if (this.radius < 0 || sphere.radius < 0) return false;\n    const radiusSum = this.radius + sphere.radius;\n\n    return this.center.distanceToSquared(sphere.center) <= radiusSum * radiusSum;\n  }\n\n  /**\n   * Returns true when `plane` passes through this sphere or touches it; never for an empty sphere\n   * @example\n   * ```ts\n   * const splashing = ball.boundingSphere.intersectsPlane(water);\n   * ```\n   * @param plane - The plane to test\n   * @returns Whether the plane passes through or touches the sphere\n   */\n  public intersectsPlane(plane: Plane): boolean {\n    if (this.radius < 0) return false;\n\n    return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;\n  }\n\n  /**\n   * Returns true when `ray` hits this sphere; same as {@link Ray#intersectsSphere}\n   * @example\n   * ```ts\n   * const hovered = mesh.boundingSphere.intersectsRay(pointerRay);\n   * ```\n   * @param ray - The ray to test\n   * @returns Whether the ray hits this sphere\n   */\n  public intersectsRay(ray: Ray): boolean {\n    return ray.intersectsSphere(this);\n  }\n\n  /**\n   * Transforms this sphere by an affine `matrix`\n   *\n   * The radius scales by the matrix's largest axis scale, so the sphere still bounds the shape under\n   * rotation and per-axis scale. Under shear, as when a non-uniformly scaled parent holds a rotated\n   * child, the radius can come out too small; for one that always fits, multiply the original\n   * radius by the square root of {@link Matrix4#getMaxSingularValueSq} yourself. An empty sphere\n   * stays empty.\n   *\n   * `matrix` must be affine (bottom row `[0, 0, 0, 1]`), as a {@link Container3D#worldTransform}\n   * always is and a projection matrix isn't.\n   * @example\n   * ```ts\n   * const worldBounds = new Sphere();\n   *\n   * mesh.geometry.boundsSphere.applyMatrix4(mesh.worldTransform, worldBounds);\n   * ```\n   * @param matrix - The affine matrix to transform by\n   * @param out - Target to write the result into instead of mutating this sphere\n   * @returns The result sphere for chaining\n   */\n  public applyMatrix4(matrix: Matrix4, out: Sphere = this): this {\n    if (out !== this) out.copyFrom(this);\n    if (out.isEmpty()) return out as this;\n    out.center.applyAffineMatrix4(matrix);\n    out.radius = out.radius * matrix.getMaxScaleOnAxis();\n\n    return out as this;\n  }\n\n  /**\n   * Writes the axis-aligned box around this sphere into `out` (or a new `Box`)\n   *\n   * An empty sphere gives an empty box.\n   * @example\n   * ```ts\n   * const bounds = mesh.boundingSphere.getBounds(scratchBox);\n   * ```\n   * @param out - Optional box to write into; a new `Box` when omitted\n   * @returns The bounds of this sphere\n   */\n  public getBounds(out?: Box): Box {\n    out ||= new Box();\n    if (this.isEmpty()) return out.makeEmpty();\n    out.min.set(this.center.x - this.radius, this.center.y - this.radius, this.center.z - this.radius);\n    out.max.set(this.center.x + this.radius, this.center.y + this.radius, this.center.z + this.radius);\n\n    return out;\n  }\n\n  /**\n   * Returns a string representation of this sphere\n   * @returns A string in the form `[@pixi/3d/math:Sphere center=(0, 0, 0) radius=1]`\n   * @advanced\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Sphere center=(${this.center.x}, ${this.center.y}, ${this.center.z}) radius=${this.radius}]`;\n  }\n}\n","type IndexKey<T> = { [K in keyof T]-?: T[K] extends number ? K : never }[keyof T];\n\ntype Indexed<T> = Record<IndexKey<T>, number>;\n\n/**\n * Removing an item moves the last one into its slot and updates its index property; an index kept elsewhere goes stale\n * @internal\n */\nexport class UnstableList<T> {\n  public items: T[] = [];\n  private readonly _indexKey: IndexKey<T>;\n\n  /**\n   * @param indexKey - Item property holding its index, `-1` while unlisted; items start at `-1` and need one per list\n   */\n  constructor(indexKey: IndexKey<T>) {\n    this._indexKey = indexKey;\n  }\n\n  /** Doesn't check for duplicates: adding a listed item leaves a copy `remove` can't reach */\n  public add(item: T): void {\n    (item as Indexed<T>)[this._indexKey] = this.items.length;\n    this.items.push(item);\n  }\n\n  public remove(item: T): void {\n    const index = (item as Indexed<T>)[this._indexKey];\n\n    if (index > -1) {\n      const lastIndex = this.items.length - 1;\n      const lastItem = this.items[lastIndex];\n\n      this.items[index] = lastItem;\n      (lastItem as Indexed<T>)[this._indexKey] = index;\n\n      this.items.length = lastIndex;\n\n      (item as Indexed<T>)[this._indexKey] = -1;\n    }\n  }\n\n  public clear(): void {\n    for (let i = 0; i < this.items.length; i++) {\n      (this.items[i] as Indexed<T>)[this._indexKey] = -1;\n    }\n    this.items.length = 0;\n  }\n}\n","import { Buffer, BufferUsage, getAttributeInfoFromFormat } from 'pixi.js';\nimport type { Attribute, TypedArray, VertexFormat } from 'pixi.js';\n\nimport { Box } from '../../math/shapes/Box';\nimport { Vector3 } from '../../math/vector/Vector3';\nimport type { Geometry3DOptions } from '../Geometry3D';\n\n/** @internal */\nexport function resolveAttributeInput(\n  input: TypedArray | Attribute | undefined,\n): { data: TypedArray; format?: VertexFormat } | undefined {\n  if (!input) return undefined;\n  if (ArrayBuffer.isView(input)) return { data: input };\n  return { data: input.buffer.data, format: input.format };\n}\n\n/** @internal */\nexport type IntegerFormat = 'norm' | 'int';\n\n/**\n * Positions and UVs pass no `integerFormat`, as glTF stores them as normalized or raw integers and only an\n * `Attribute`'s format can say which\n * @internal\n */\nexport function resolveAttribute(\n  input: TypedArray | Attribute | undefined,\n  name: string,\n  size: number,\n  integerFormat?: IntegerFormat,\n  quantize = false,\n): { data: TypedArray; size: number; format: VertexFormat } | undefined {\n  const resolved = resolveAttributeInput(input);\n  if (!resolved) return undefined;\n\n  if (resolved.format) {\n    return {\n      data: resolved.data,\n      size: getAttributeInfoFromFormat(resolved.format).size,\n      format: resolved.format,\n    };\n  }\n\n  if (!integerFormat && !(resolved.data instanceof Float32Array)) {\n    throw new Error(\n      `[Geometry3D] ${name} got ${resolved.data.constructor.name} data, which could be normalized or raw integers. ` +\n        'Pass a Float32Array, or an Attribute whose format says which.',\n    );\n  }\n\n  const prepared = prepareAttributeData(resolved.data, size, integerFormat !== 'int', quantize);\n  return {\n    data: prepared.data,\n    size: prepared.size,\n    format: getAttributeFormat(prepared.data, prepared.size, prepared.normalized),\n  };\n}\n\n/**\n * WebGPU has no three-component vertex format for 8- or 16-bit integers\n * @internal\n */\nexport function padTo4Components<T extends TypedArray>(data: T): T {\n  const Ctor = data.constructor as new (len: number) => T;\n  const vertexCount = data.length / 3;\n  const out = new Ctor(vertexCount * 4);\n\n  for (let i = 0; i < vertexCount; i++) {\n    const src = i * 3;\n    const dst = i * 4;\n    out[dst] = data[src];\n    out[dst + 1] = data[src + 1];\n    out[dst + 2] = data[src + 2];\n  }\n  return out;\n}\n\n/** Clamps with ternaries, not `Math.min`/`Math.max`, as it runs per component of every quantized normal and tangent */\nfunction prepareAttributeData(\n  data: TypedArray,\n  size: number,\n  normalized: boolean,\n  quantize: boolean,\n): { data: TypedArray; size: number; normalized: boolean } {\n  if (quantize && data instanceof Float32Array) {\n    const vertexCount = data.length / size;\n    const outSize = size === 3 ? 4 : size;\n    const quantized = new Int16Array(vertexCount * outSize);\n\n    for (let i = 0; i < vertexCount; i++) {\n      const src = i * size;\n      const dst = i * outSize;\n      for (let j = 0; j < size; j++) {\n        const v = data[src + j];\n        quantized[dst + j] = (v < -1 ? -1 : v > 1 ? 1 : v) * 32767;\n      }\n    }\n\n    return { data: quantized, size: outSize, normalized: true };\n  }\n\n  if (size === 3 && !(data instanceof Float32Array)) {\n    return { data: padTo4Components(data), size: 4, normalized };\n  }\n\n  return { data, size, normalized };\n}\n\n/** @internal */\nexport function computeBoundsFromPositions(positions: TypedArray): Box {\n  let minX = Infinity;\n  let minY = Infinity;\n  let minZ = Infinity;\n  let maxX = -Infinity;\n  let maxY = -Infinity;\n  let maxZ = -Infinity;\n\n  for (let i = 0; i < positions.length; i += 3) {\n    const x = positions[i];\n    const y = positions[i + 1];\n    const z = positions[i + 2];\n    if (x < minX) minX = x;\n    if (y < minY) minY = y;\n    if (z < minZ) minZ = z;\n    if (x > maxX) maxX = x;\n    if (y > maxY) maxY = y;\n    if (z > maxZ) maxZ = z;\n  }\n\n  return new Box(new Vector3(minX, minY, minZ), new Vector3(maxX, maxY, maxZ));\n}\n\nfunction getAttributeFormat(data: TypedArray, size: number, normalized: boolean): VertexFormat {\n  if (data instanceof Float32Array) {\n    if (size === 1) return 'float32';\n    if (size === 2) return 'float32x2';\n    if (size === 3) return 'float32x3';\n    return 'float32x4';\n  }\n\n  const suffix = size === 3 ? 'x4' : `x${size}`;\n\n  if (normalized) {\n    if (data instanceof Int8Array) return `snorm8${suffix}` as VertexFormat;\n    if (data instanceof Uint8Array) return `unorm8${suffix}` as VertexFormat;\n    if (data instanceof Int16Array) return `snorm16${suffix}` as VertexFormat;\n    if (data instanceof Uint16Array) return `unorm16${suffix}` as VertexFormat;\n  } else {\n    if (data instanceof Int8Array) return `sint8${suffix}` as VertexFormat;\n    if (data instanceof Uint8Array) return `uint8${suffix}` as VertexFormat;\n    if (data instanceof Int16Array) return `sint16${suffix}` as VertexFormat;\n    if (data instanceof Uint16Array) return `uint16${suffix}` as VertexFormat;\n    if (data instanceof Int32Array) return `sint32${suffix}` as VertexFormat;\n    if (data instanceof Uint32Array) return `uint32${suffix}` as VertexFormat;\n  }\n\n  return 'float32x4';\n}\n\n/**\n * The copy is unrolled for 2, 3 and 4 components, as that beats a loop per component\n * @internal\n */\nexport function interleaveData(options: Geometry3DOptions, shrinkToFit?: boolean): Record<string, Attribute> {\n  const arrays: {\n    data: TypedArray;\n    attribute: string;\n    size: number;\n    bytesPerElement: number;\n    format: VertexFormat;\n  }[] = [];\n\n  const add = (\n    input: TypedArray | Attribute | undefined,\n    attribute: string,\n    size: number,\n    integerFormat?: IntegerFormat,\n    quantize?: boolean,\n  ) => {\n    const r = resolveAttribute(input, attribute, size, integerFormat, quantize);\n    if (!r) return;\n\n    arrays.push({\n      data: r.data,\n      attribute,\n      size: r.size,\n      bytesPerElement: r.data.BYTES_PER_ELEMENT,\n      format: r.format,\n    });\n  };\n\n  add(options.positions, 'aPosition', 3);\n  add(options.uvs, 'aUV', 2);\n  add(options.normals, 'aNormal', 3, 'norm', options.quantizeNormals ?? true);\n  add(options.tangents, 'aTangent', 4, 'norm', options.quantizeTangents ?? true);\n  add(options.joints, 'aJoints', 4, 'int');\n  add(options.weights, 'aWeights', 4, 'norm');\n  add(options.colors, 'aColor', 4, 'norm');\n  add(options.colors1, 'aColor1', 4, 'norm');\n\n  let stride = 0;\n  const offsets: number[] = [];\n\n  for (let i = 0; i < arrays.length; i++) {\n    const info = arrays[i];\n    stride = alignTo4Bytes(stride);\n    offsets.push(stride);\n    stride += info.size * info.bytesPerElement;\n  }\n\n  stride = alignTo4Bytes(stride);\n\n  let positionsEntry: (typeof arrays)[number] | undefined;\n  for (let i = 0; i < arrays.length; i++) {\n    if (arrays[i].attribute === 'aPosition') {\n      positionsEntry = arrays[i];\n      break;\n    }\n  }\n  const vertexCount = positionsEntry!.data.length / positionsEntry!.size;\n  const totalSize = stride * vertexCount;\n\n  const interleavedBuffer = new ArrayBuffer(totalSize);\n\n  const attributes: Record<string, Attribute> = {};\n  const buffer = new Buffer({\n    data: new Uint8Array(interleavedBuffer),\n    label: 'interleaved-mesh-buffer',\n    shrinkToFit,\n    usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,\n  });\n\n  for (let index = 0; index < arrays.length; index++) {\n    const info = arrays[index];\n    const { data, attribute, size, bytesPerElement } = info;\n    const offset = offsets[index];\n\n    const Type = data.constructor as new (buffer: ArrayBuffer) => TypedArray;\n    const view = new Type(interleavedBuffer);\n    const strideInElements = stride / bytesPerElement;\n    const offsetInElements = offset / bytesPerElement;\n\n    if (size === 2) {\n      for (let i = 0; i < vertexCount; i++) {\n        const dst = i * strideInElements + offsetInElements;\n        const src = i * 2;\n        view[dst] = data[src];\n        view[dst + 1] = data[src + 1];\n      }\n    } else if (size === 3) {\n      for (let i = 0; i < vertexCount; i++) {\n        const dst = i * strideInElements + offsetInElements;\n        const src = i * 3;\n        view[dst] = data[src];\n        view[dst + 1] = data[src + 1];\n        view[dst + 2] = data[src + 2];\n      }\n    } else if (size === 4) {\n      for (let i = 0; i < vertexCount; i++) {\n        const dst = i * strideInElements + offsetInElements;\n        const src = i * 4;\n        view[dst] = data[src];\n        view[dst + 1] = data[src + 1];\n        view[dst + 2] = data[src + 2];\n        view[dst + 3] = data[src + 3];\n      }\n    } else {\n      for (let i = 0; i < vertexCount; i++) {\n        const destIndex = i * strideInElements + offsetInElements;\n        const srcIndex = i * size;\n        for (let j = 0; j < size; j++) {\n          view[destIndex + j] = data[srcIndex + j];\n        }\n      }\n    }\n\n    attributes[attribute] = {\n      buffer,\n      format: info.format,\n      stride,\n      offset,\n    };\n  }\n\n  return attributes;\n}\n\n/**\n * Pixi's own `Geometry.vertexCount` assumes 4-byte elements, so it miscounts quantized buffers\n * @internal\n */\nexport function vertexCountFromAttributes(attributes: Record<string, Attribute>): number {\n  for (const i in attributes) {\n    const attribute = attributes[i];\n    if (attribute.instance) continue;\n    const stride = attribute.stride;\n    if (!stride) continue;\n    return attribute.buffer.data.byteLength / stride;\n  }\n  return 0;\n}\n\n/**\n * Indexes every geometry, as the atlas packs by index range, and widens an odd-length `Uint16Array`, as\n * WebGPU writes buffers in 4-byte steps\n * @internal\n */\nexport function createIndexBuffer(\n  indices: Uint16Array | Uint32Array | undefined,\n  attributes: Record<string, Attribute>,\n  shrinkToFit?: boolean,\n): Buffer | undefined {\n  if (!indices) {\n    const vertexCount = vertexCountFromAttributes(attributes);\n    if (vertexCount === 0) return undefined;\n\n    indices = vertexCount > 65536 ? new Uint32Array(vertexCount) : new Uint16Array(vertexCount);\n    for (let v = 0; v < vertexCount; v++) indices[v] = v;\n  }\n\n  if (indices instanceof Uint16Array && indices.byteLength % 4 !== 0) {\n    indices = new Uint32Array(indices);\n  }\n\n  return new Buffer({\n    data: indices,\n    label: 'index-mesh-buffer',\n    shrinkToFit,\n    usage: BufferUsage.INDEX | BufferUsage.COPY_DST,\n  });\n}\n\n/**\n * WebGPU requires vertex attribute offsets and strides to be multiples of 4\n * @internal\n */\nexport function alignTo4Bytes(bytes: number): number {\n  return (bytes + 3) & ~3;\n}\n","import { Buffer, BufferUsage, Geometry, NOOP } from 'pixi.js';\nimport type { Attribute, Topology, TypedArray } from 'pixi.js';\n\nimport type { GeometryDataStoreBuffer } from '../core/buffers/GeometryDataStoreBuffer';\nimport type { MorphStoreBuffer } from '../core/buffers/MorphStoreBuffer';\nimport { Box } from '../math/shapes/Box';\nimport { Sphere } from '../math/shapes/Sphere';\nimport type { Mesh3D } from '../scene/Mesh3D';\nimport { UnstableList } from '../utils/UnstableList';\nimport type { GeometryAllocation } from './GeometryAtlas';\nimport {\n  computeBoundsFromPositions,\n  createIndexBuffer,\n  interleaveData,\n  resolveAttribute,\n  resolveAttributeInput,\n  vertexCountFromAttributes,\n} from './utils/Geometry3DUtils';\nimport type { IntegerFormat } from './utils/Geometry3DUtils';\n\n/**\n * Options for {@link Geometry3D}\n *\n * Each vertex attribute takes a typed array with its components packed vertex after vertex, or a\n * pixi `Attribute` whose `format` says how to read it, which is how quantized data comes in. An\n * `Attribute` is read by its format alone, not its `stride` or `offset`, so pack its data vertex\n * after vertex too, in a typed array with the format's bit width, such as an `Int16Array` for\n * `snorm16x4`. Pass an interleaved layout through `attributes`.\n * @example\n * ```ts\n * const options: Geometry3DOptions = { positions, normals, uvs, indices };\n * const geometry = new Geometry3D(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface Geometry3DOptions {\n  /**\n   * Vertex positions, three floats per vertex\n   *\n   * Integer positions come in as an `Attribute`, since only its format says how to read them:\n   * `snorm` as -1 to 1, `unorm` as 0 to 1, and `sint` or `uint` as the stored integers. An integer\n   * typed array throws. Pad 8- and 16-bit xyz to four components per vertex, and pass `bounds3D`.\n   * @example\n   * ```ts\n   * const triangle = new Geometry3D({ positions: new Float32Array([0, 1, 0, -1, -1, 0, 1, -1, 0]) });\n   * ```\n   */\n  positions?: Float32Array | Attribute;\n  /**\n   * Texture coordinates, two floats per vertex\n   *\n   * Integer coordinates come in as an `Attribute`, read as integer positions are: `unorm16x2` as\n   * 0 to 1, `uint16x2` as the stored integers, which the material's\n   * {@link BaseMaterial3D#uvTransform} has to scale back down.\n   * @example\n   * ```ts\n   * const quad = new Geometry3D({ positions, uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]) });\n   * ```\n   */\n  uvs?: Float32Array | Attribute;\n  /**\n   * Vertex normals, three floats per vertex\n   *\n   * Without them the geometry shades as if every normal were `(0, 0, 1)`, which suits unlit\n   * billboards and ribbons. `quantizeNormals` decides how they are stored.\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, normals });\n   * ```\n   */\n  normals?: Float32Array | Attribute;\n  /**\n   * Vertex tangents, four floats per vertex: the tangent direction, then `1` or `-1` for which way\n   * the bitangent points\n   *\n   * Normal maps use them when present and otherwise derive a tangent frame per pixel.\n   * `quantizeTangents` decides how they are stored.\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, normals, uvs, tangents });\n   * ```\n   */\n  tangents?: Float32Array | Attribute;\n  /**\n   * Vertex indices, three per triangle for the default `triangle-list` topology\n   *\n   * Left out, the vertices are drawn in order. A `Uint16Array` of odd length is copied into a\n   * `Uint32Array`. A `Buffer` is used as it is, so several geometries can share one.\n   * @example\n   * ```ts\n   * const quad = new Geometry3D({\n   *   positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),\n   *   indices: new Uint16Array([0, 1, 2, 0, 2, 3]),\n   * });\n   * ```\n   */\n  indices?: Uint16Array | Uint32Array | Buffer;\n  /**\n   * How many indices to draw, when that is fewer than the index buffer holds\n   *\n   * `0` draws the whole buffer. Only a `dynamic` geometry honours it; any other draws its whole\n   * index buffer. Use it to draw a prefix of an index buffer several geometries share.\n   * @default 0\n   * @example\n   * ```ts\n   * const firstTen = new Geometry3D({ positions, indices: sharedQuadIndices, indexCount: 10 * 6, dynamic: true });\n   * ```\n   */\n  indexCount?: number;\n  /**\n   * Primitive topology used when drawing the mesh\n   * @default 'triangle-list'\n   * @example\n   * ```ts\n   * const wireframe = new Geometry3D({ positions, indices: edgeIndices, topology: 'line-list' });\n   * ```\n   */\n  topology?: Topology;\n  /**\n   * Whether the geometry's own GPU buffers may shrink to fit their data when it gets smaller\n   * @default false\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, shrinkBuffersToFit: true });\n   * ```\n   */\n  shrinkBuffersToFit?: boolean;\n  /**\n   * The geometry's local bounding box; computed from float `positions` when omitted\n   *\n   * Pass it when you already know the box, to skip scanning the positions. Integer positions throw\n   * without it, and need it in the values their format reads as: within -1 to 1 for `snorm16x4`,\n   * the stored integers for `sint16x4`.\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({\n   *   positions,\n   *   bounds3D: new Box(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)),\n   * });\n   * ```\n   */\n  bounds3D?: Box;\n  /**\n   * Four bone indices per vertex, for skinning\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, joints: new Uint8Array(vertexCount * 4), weights });\n   * ```\n   */\n  joints?: Uint16Array | Uint8Array | Attribute;\n  /**\n   * Four bone weights per vertex, matching `joints`\n   *\n   * A `Float32Array` is used as floats; an integer array is read as normalized, 0 to 1.\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, joints, weights: new Float32Array(vertexCount * 4) });\n   * ```\n   */\n  weights?: Float32Array | Uint16Array | Uint8Array | Attribute;\n  /**\n   * Vertex colours, four components per vertex (RGBA)\n   *\n   * A `Float32Array` is used as floats; an integer array is read as normalized, 0 to 1. Widen RGB\n   * colours to RGBA with an opaque alpha first. {@link BaseMaterial3D#vertexColors} decides whether\n   * they tint.\n   * @example\n   * ```ts\n   * const red = new Uint8Array([255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255]);\n   * const geometry = new Geometry3D({ positions, colors: red });\n   * ```\n   */\n  colors?: Float32Array | Uint16Array | Uint8Array | Attribute;\n  /**\n   * A second set of vertex colours, read as `aColor1`, with the same rules as `colors`\n   *\n   * Materials never tint with it; only a custom shader bit that declares `aColor1` reads it, which\n   * makes it the place for data that isn't really a colour, such as a wind mask.\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, colors1: windMask });\n   * ```\n   */\n  colors1?: Float32Array | Uint16Array | Uint8Array | Attribute;\n  /**\n   * Whether to pack the attributes into one interleaved buffer\n   *\n   * Only a `dynamic` geometry draws from its own buffers; for any other, this changes how its own\n   * data is laid out, not how it draws. Per-triangle picking, a\n   * {@link Container3D#hitVolume | hitVolume} of `'geometry'`, never hits an interleaved geometry.\n   * @default false\n   * @example\n   * ```ts\n   * const trail = new Geometry3D({ positions, colors, interleave: true, dynamic: true });\n   * ```\n   */\n  interleave?: boolean;\n  /**\n   * Whether to store `Float32Array` normals as 16-bit signed integers\n   *\n   * They then take 8 bytes per vertex instead of 12, with negligible visual difference. Read them\n   * back as floats with {@link getAttributeData}.\n   * @default true\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, normals, quantizeNormals: false });\n   * ```\n   */\n  quantizeNormals?: boolean;\n  /**\n   * Whether to store `Float32Array` tangents as 16-bit signed integers\n   *\n   * They then take 8 bytes per vertex instead of 16, with negligible visual difference. Read them\n   * back as floats with {@link getAttributeData}.\n   * @default true\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, normals, tangents, quantizeTangents: false });\n   * ```\n   */\n  quantizeTangents?: boolean;\n  /**\n   * A prebuilt attribute map, keyed by shader attribute name\n   *\n   * Use it to supply your own buffers or interleaved layout. The names the other options fill are\n   * `aPosition`, `aUV`, `aNormal`, `aTangent`, `aJoints`, `aWeights`, `aColor` and `aColor1`.\n   *\n   * With a map, the per-attribute options build nothing, so pass `bounds3D` too: a geometry with\n   * empty bounds is never culled, and picking never hits it.\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({\n   *   attributes: { aPosition: { buffer, format: 'float32x3', stride: 12, offset: 0 } },\n   *   bounds3D: new Box(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)),\n   * });\n   * ```\n   */\n  attributes?: Record<string, Attribute>;\n  /**\n   * Draw the geometry from its own buffers, so later writes to them reach the screen\n   *\n   * Set it when you rewrite the vertices every frame, as a trail or a particle system does. A\n   * dynamic geometry is never frustum-culled. Fixed at construction.\n   * @default false\n   * @example\n   * ```ts\n   * const trail = new Geometry3D({ positions: new Float32Array(64 * 3), dynamic: true });\n   *\n   * app.ticker.add(() => {\n   *   writeTrailPoints(trail.positions);\n   *   trail.attributes.aPosition.buffer.update();\n   * });\n   * ```\n   */\n  dynamic?: boolean;\n  /**\n   * Morph targets (blend shapes), each a set of per-vertex offsets from `positions`\n   *\n   * A {@link Mesh3D} drawing the geometry blends the targets by its {@link Mesh3D#weights}.\n   * Normal offsets are used only when every target has them. A geometry morphs in one renderer\n   * only: once a second renderer draws it, even a new `Application` made after the first is\n   * destroyed, it draws unmorphed from then on and warns once.\n   *\n   * Culling allows for weights from 0 to 1. For weights outside that range, pass a larger\n   * `bounds3D`.\n   * @example\n   * ```ts\n   * const geometry = new Geometry3D({ positions, morphTargets: [{ positions: smileOffsets }] });\n   * const face = new Mesh3D({ geometry, material, weights: new Float32Array([0.5]) });\n   * ```\n   */\n  morphTargets?: {\n    /**\n     * Offsets from the base positions, three floats per vertex\n     * @example\n     * ```ts\n     * const raise = new Float32Array(vertexCount * 3);\n     * for (let i = 1; i < raise.length; i += 3) raise[i] = 0.5;\n     * const geometry = new Geometry3D({ positions, morphTargets: [{ positions: raise }] });\n     * ```\n     */\n    positions: Float32Array;\n    /**\n     * Offsets from the base normals, three floats per vertex\n     * @example\n     * ```ts\n     * const geometry = new Geometry3D({\n     *   positions,\n     *   normals,\n     *   morphTargets: [{ positions: bulgeOffsets, normals: bulgeNormalOffsets }],\n     * });\n     * ```\n     */\n    normals?: Float32Array;\n  }[];\n}\n\n/**\n * A mesh's vertex and index data: positions plus optional normals, UVs, tangents, colours and\n * skinning data, in separate buffers or interleaved in one\n *\n * Only positions are required. Inputs can be raw `Float32Array` data or pixi `Attribute`s,\n * including the quantized integer formats glTF files use (KHR_mesh_quantization).\n * {@link getAttributeData} reads any attribute back as floats, however it is stored.\n *\n * The first time a geometry is drawn it's copied into buffers shared with other geometries, so\n * later edits to its data don't show. Build a new geometry for a new shape, call\n * {@link Geometry3D#unload | unload} after an occasional edit, or make it\n * {@link Geometry3DOptions#dynamic} if you rewrite it every frame.\n * @example\n * ```ts\n * const geometry = new Geometry3D({\n *   positions: new Float32Array([\n *     -1, -1, 0,\n *      1, -1, 0,\n *      0,  1, 0,\n *   ]),\n *   indices: new Uint16Array([0, 1, 2]),\n * });\n * ```\n * @see {@link Geometry3DOptions} For the constructor options\n * @category geometry\n * @standard\n */\nexport class Geometry3D extends Geometry {\n  /**\n   * Defaults for every new `Geometry3D`\n   *\n   * Each primitive, such as {@link SphereGeometry}, copies these into its own `defaultOptions` when\n   * its module loads, so changing one of them here later doesn't reach the primitives; set theirs\n   * instead.\n   * @example\n   * ```ts\n   * Geometry3D.defaultOptions.quantizeNormals = false;\n   * ```\n   */\n  public static defaultOptions: Geometry3DOptions = {\n    topology: 'triangle-list',\n    shrinkBuffersToFit: false,\n    interleave: false,\n    quantizeNormals: true,\n    quantizeTangents: true,\n  };\n\n  /** Built on first read, so importing the module builds nothing */\n  private static _empty: Geometry3D | null = null;\n\n  /**\n   * A shared geometry with no vertices, which a {@link Mesh3D} holds until it's given a geometry\n   *\n   * A mesh on it draws nothing and compiles no shader. Assign it to a mesh's `geometry` to stop the\n   * mesh drawing; to hide a mesh for a while, `visible = false` is cheaper to toggle. Only `Mesh3D`\n   * takes it: a {@link BatchedMesh3D} slot in a pass needs a real geometry.\n   *\n   * Its `destroy` does nothing, as with pixi's `Texture.EMPTY`, so destroying a mesh with\n   * `geometry: true` can't free it from under other meshes.\n   * @example\n   * ```ts\n   * if (mesh.geometry === Geometry3D.EMPTY) mesh.geometry = new SphereGeometry();\n   * ```\n   * @advanced\n   */\n  public static get EMPTY(): Geometry3D {\n    return (Geometry3D._empty ??= (() => {\n      const empty = new Geometry3D({ attributes: {} });\n      empty.destroy = NOOP;\n      return empty;\n    })());\n  }\n\n  /**\n   * The geometry's local bounding box, used for picking and for a mesh's local bounds\n   *\n   * Culling tests {@link Geometry3D#boundsSphere} instead.\n   * @example\n   * ```ts\n   * const size = geometry.bounds3D.getSize();\n   * ```\n   */\n  public bounds3D: Box;\n\n  /**\n   * The sphere around {@link Geometry3D#bounds3D}, which frustum culling tests\n   *\n   * Computed once, at construction, so later edits to the positions or to `bounds3D` don't reach\n   * culling.\n   * @example\n   * ```ts\n   * const radius = geometry.boundsSphere.radius;\n   * ```\n   */\n  public boundsSphere: Sphere;\n\n  /**\n   * Number of vertices\n   * @example\n   * ```ts\n   * const colors = new Float32Array(geometry.vertexCount * 4);\n   * ```\n   */\n  get vertexCount(): number {\n    return vertexCountFromAttributes(this.attributes);\n  }\n\n  /**\n   * Where the geometry sits in a `GeometryAtlas`; `null` while it isn't packed\n   * @internal\n   */\n  public _geometryAtlasAllocation: GeometryAllocation | null = null;\n\n  /**\n   * Whether the geometry left an atlas range since it was last packed; draw commands may still read\n   * that range, so a repack rebuilds them and a first pack doesn't\n   * @internal\n   */\n  public _atlasVacated = false;\n\n  /**\n   * The meshes in a scene that draw this geometry; batch slots aren't listed\n   * @internal\n   */\n  public readonly _meshes = new UnstableList<Mesh3D>('_geometryMeshIndex');\n\n  /**\n   * Row in the renderer's `GeometryDataStoreBuffer`; -1 until the store assigns one\n   * @internal\n   */\n  public _geometryDataIndex = -1;\n\n  /**\n   * The `DrawCommandList.captureTick` of the build that last captured this geometry's buffers, so a\n   * build captures them once\n   * @internal\n   */\n  public _captureTick = -1;\n\n  /**\n   * The store that assigned `_geometryDataIndex`, so `destroy` can free the row without a renderer\n   * @internal\n   */\n  public _geometryDataStore: GeometryDataStoreBuffer | null = null;\n\n  /**\n   * Whether the geometry stays out of the shared buffers; see {@link Geometry3DOptions#dynamic}\n   * @advanced\n   */\n  public readonly dynamic: boolean;\n\n  /**\n   * Count of morph targets; a mesh drawing the geometry takes one weight per target\n   * @example\n   * ```ts\n   * const weights = new Float32Array(geometry.morphTargetCount);\n   * ```\n   */\n  public readonly morphTargetCount: number = 0;\n\n  /**\n   * Float offset of the packed morph offsets in the morph store; -1 while unpacked\n   * @internal\n   */\n  public _morphDeltaBase = -1;\n\n  /**\n   * Float length of the packed block, kept because packing drops the raw targets\n   * @internal\n   */\n  public _morphDeltaFloats = 0;\n\n  /**\n   * The morph store holding the packed block, so `destroy` can hand it back without a renderer\n   * @internal\n   */\n  public _morphStore: MorphStoreBuffer | null = null;\n\n  /**\n   * Whether the morph targets bend the normals as well as the positions; see\n   * {@link Geometry3DOptions#morphTargets}\n   * @advanced\n   */\n  public readonly hasMorphNormals: boolean;\n\n  /**\n   * How far weights from 0 to 1 can move a vertex, which culling adds to the bounding sphere's radius\n   * @internal\n   */\n  public _morphBoundsExpansion = 0;\n\n  /**\n   * The raw morph targets; `null` once packed into the morph store\n   * @internal\n   */\n  public _morphTargets: { positions: Float32Array; normals?: Float32Array }[] | null = null;\n\n  private _attributeKey: string | null = null;\n  /**\n   * Set before pixi's `destroy` runs `unload`, so this class's `unload` can't free buffers that\n   * `destroy(false)` leaves to the geometries sharing them\n   */\n  private _destroyed = false;\n\n  /**\n   * The attribute names and formats, ignoring strides, offsets and buffers\n   *\n   * Geometries with the same key are packed into the same shared buffers. A geometry with\n   * positions, normals and UVs has the key `aNormal:snorm16x4|aPosition:float32x3|aUV:float32x2|`.\n   * @advanced\n   */\n  get attributeKey(): string {\n    if (this._attributeKey) return this._attributeKey;\n\n    const attributes = this.attributes;\n    const keys = Object.keys(attributes).sort();\n    let key = '';\n\n    for (let i = 0; i < keys.length; i++) {\n      const name = keys[i];\n      const attr = attributes[name];\n\n      if (attr.instance) continue;\n\n      key += `${name}:${attr.format}|`;\n    }\n\n    this._attributeKey = key;\n    return key;\n  }\n\n  /**\n   * Creates a new `Geometry3D`\n   * @param options - See {@link Geometry3DOptions} for available options\n   */\n  constructor(options: Geometry3DOptions) {\n    options = { ...Geometry3D.defaultOptions, ...options };\n    const { positions, uvs, normals, tangents, joints, weights, colors, colors1 } = options;\n\n    const shrinkToFit = options.shrinkBuffersToFit;\n\n    let attributes: Record<string, Attribute> = {};\n\n    if (options.attributes) {\n      attributes = options.attributes;\n    } else if (options.interleave) {\n      attributes = interleaveData(options, shrinkToFit);\n    } else {\n      const addAttribute = (\n        input: TypedArray | Attribute | undefined,\n        name: string,\n        size: number,\n        integerFormat?: IntegerFormat,\n        quantize?: boolean,\n      ) => {\n        const r = resolveAttribute(input, name, size, integerFormat, quantize);\n        if (!r) return;\n\n        const buffer = new Buffer({\n          data: r.data,\n          label: `attribute-mesh-${name.toLowerCase().substring(1)}`,\n          shrinkToFit,\n          usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,\n        });\n\n        attributes[name] = {\n          buffer,\n          format: r.format,\n          stride: r.size * r.data.BYTES_PER_ELEMENT,\n          offset: 0,\n        };\n      };\n\n      addAttribute(positions, 'aPosition', 3);\n      addAttribute(uvs, 'aUV', 2);\n      addAttribute(normals, 'aNormal', 3, 'norm', options.quantizeNormals ?? true);\n      addAttribute(tangents, 'aTangent', 4, 'norm', options.quantizeTangents ?? true);\n      addAttribute(joints, 'aJoints', 4, 'int');\n      addAttribute(weights, 'aWeights', 4, 'norm');\n      addAttribute(colors, 'aColor', 4, 'norm');\n      addAttribute(colors1, 'aColor1', 4, 'norm');\n    }\n\n    super({\n      attributes,\n      indexBuffer:\n        options.indices instanceof Buffer\n          ? options.indices\n          : createIndexBuffer(options.indices, attributes, shrinkToFit),\n      indexCount: options.indexCount,\n      topology: options.topology,\n    });\n\n    this._morphTargets = options.morphTargets ?? null;\n    this.morphTargetCount = options.morphTargets?.length ?? 0;\n    this.hasMorphNormals = this.morphTargetCount > 0 && options.morphTargets!.every((target) => !!target.normals);\n    this.dynamic = options.dynamic ?? false;\n\n    if (options.bounds3D) {\n      this.bounds3D = options.bounds3D;\n    } else if (positions) {\n      const { data, format } = resolveAttributeInput(positions)!;\n      if (format && !format.startsWith('float32')) {\n        throw new Error(`[Geometry3D] ${format} positions need bounds3D: only float positions are scanned for it.`);\n      }\n      this.bounds3D = computeBoundsFromPositions(data);\n    } else {\n      this.bounds3D = new Box();\n    }\n\n    this.boundsSphere = new Sphere().setFromBox(this.bounds3D);\n  }\n\n  /**\n   * Frees the geometry for good\n   *\n   * Its own buffers are destroyed only with `destroyBuffers`, since other geometries may share\n   * them. Calling it again does nothing.\n   * @param destroyBuffers - Whether to destroy the geometry's own buffers as well\n   * @example\n   * ```ts\n   * view.root.removeChild(mesh);\n   * mesh.geometry.destroy(true);\n   * ```\n   * @see {@link Geometry3D.unload} To hand back the GPU memory but keep the geometry usable.\n   */\n  public override destroy(destroyBuffers?: boolean): void {\n    if (this._destroyed) return;\n\n    this._geometryAtlasAllocation?.atlas.remove(this);\n\n    this._geometryDataStore?.remove(this);\n    this._geometryDataStore = null;\n    this._morphStore?.freeDeltas(this);\n\n    super.unload();\n    // oxlint-disable-next-line pixijs-3d/destroy-release -- a mesh still using the destroyed geometry removes itself from this list when it detaches or swaps geometry, and clear() resets its index so that remove is a no-op\n    this._meshes.clear();\n    this._destroyed = true;\n\n    super.destroy(destroyBuffers);\n  }\n\n  /**\n   * Unloads this geometry from the GPU, keeping its CPU data so it can be rebuilt\n   *\n   * A {@link Geometry3DOptions#dynamic | dynamic} geometry frees its own GPU buffers; any other\n   * leaves its place in the shared buffers, which never shrink, for later geometries. The next\n   * render that draws it uploads it again, and the image comes out the same: a geometry out of the\n   * scene comes back when its mesh does, one still drawn on the next frame. A\n   * {@link BatchedMesh3D} slot that draws it also needs {@link BatchedMesh3D#invalidate | invalidate}.\n   * Safe to call more than once, and does nothing after {@link Geometry3D.destroy}.\n   * @example\n   * ```ts\n   * view.root.removeChild(mesh);\n   * mesh.geometry.unload(); // adding the mesh again uploads it again\n   * ```\n   * @see {@link Geometry3D.destroy} To free the geometry for good.\n   */\n  public override unload(): void {\n    if (this._destroyed) return;\n\n    const allocation = this._geometryAtlasAllocation;\n    allocation?.atlas.remove(this);\n\n    const buffers = this.buffers;\n    for (let i = 0; i < buffers.length; i++) buffers[i].unload();\n\n    super.unload();\n\n    if (allocation === null && !this.dynamic) return;\n\n    const meshes = this._meshes.items;\n    for (let i = 0; i < meshes.length; i++) meshes[i]._markBatchDirty();\n  }\n\n  /**\n   * The position data as stored\n   *\n   * A `Float32Array`, unless the geometry was built from quantized positions; on an interleaved\n   * geometry, the whole interleaved buffer as a `Uint8Array`. On a\n   * {@link Geometry3DOptions#dynamic | dynamic} geometry that isn't interleaved, write through it\n   * and update its buffer. To read positions as floats, three per vertex, use\n   * {@link getAttributeData}.\n   * @example\n   * ```ts\n   * const trail = new Geometry3D({ positions: new Float32Array(64 * 3), dynamic: true });\n   *\n   * trail.positions.set(points);\n   * trail.attributes.aPosition.buffer.update();\n   * ```\n   */\n  get positions(): TypedArray {\n    return this.attributes.aPosition.buffer.data;\n  }\n\n  /**\n   * Sets the position data\n   * @param value - New data, covering at least as many vertices as before\n   */\n  set positions(value: TypedArray) {\n    this.attributes.aPosition.buffer.data = value;\n  }\n\n  /**\n   * The UV data as stored, or `undefined` when the geometry has no UVs\n   *\n   * Read them as floats, two per vertex, with {@link getAttributeData}.\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- raw stored data; getAttributeData has the read example\n  get uvs(): TypedArray | undefined {\n    return this.attributes.aUV?.buffer.data;\n  }\n\n  /**\n   * Sets the UV data; ignored when the geometry has no UVs\n   * @param value - New data, covering every vertex\n   */\n  set uvs(value: TypedArray) {\n    if (!this.attributes.aUV) return;\n    this.attributes.aUV.buffer.data = value;\n  }\n\n  /**\n   * The normal data as stored, or `undefined` when the geometry has no normals\n   *\n   * With {@link Geometry3DOptions#quantizeNormals} (the default) it's an `Int16Array` with four\n   * values per vertex; on an interleaved geometry, the whole interleaved buffer as a `Uint8Array`.\n   * To read normals as floats, three per vertex, use {@link getAttributeData}.\n   * @example\n   * ```ts\n   * const normals = getAttributeData(geometry, 'aNormal', 3);\n   * const normal = new Vector3().fromArray(normals, vertexIndex * 3);\n   * ```\n   */\n  get normals(): TypedArray | undefined {\n    return this.attributes.aNormal?.buffer.data;\n  }\n\n  /**\n   * Sets the normal data; ignored when the geometry has no normals\n   * @param value - New data, in the format the normals are stored in\n   */\n  set normals(value: TypedArray) {\n    if (!this.attributes.aNormal) return;\n    this.attributes.aNormal.buffer.data = value;\n  }\n\n  /**\n   * The tangent data as stored, or `undefined` when the geometry has no tangents\n   *\n   * With {@link Geometry3DOptions#quantizeTangents} (the default) it is an `Int16Array` with four\n   * values per vertex. Read tangents as floats, four per vertex, with {@link getAttributeData}.\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- raw stored data; getAttributeData has the read example\n  get tangents(): TypedArray | undefined {\n    return this.attributes.aTangent?.buffer.data;\n  }\n\n  /**\n   * Sets the tangent data; ignored when the geometry has no tangents\n   * @param value - New data, in the format the tangents are stored in\n   */\n  set tangents(value: TypedArray) {\n    if (!this.attributes.aTangent) return;\n    this.attributes.aTangent.buffer.data = value;\n  }\n\n  /**\n   * The index data\n   * @example\n   * ```ts\n   * const triangleCount = geometry.indices.length / 3;\n   * ```\n   */\n  get indices(): Uint32Array | Uint16Array {\n    return this.indexBuffer.data as Uint32Array | Uint16Array;\n  }\n\n  /**\n   * Sets the index data\n   * @param value - New indices, three per triangle for `triangle-list`\n   */\n  set indices(value: Uint32Array | Uint16Array) {\n    this.indexBuffer.data = value;\n  }\n}\n","import { warn } from 'pixi.js';\n\nimport { Geometry3D } from '../geometry/Geometry3D';\nimport { Box } from '../math/shapes/Box';\nimport { Sphere } from '../math/shapes/Sphere';\nimport type { Container3D } from '../scene/Container3D';\nimport { getLocalBounds3D } from '../scene/utils/getLocalBounds3D';\nimport type { HitVolume3D, HitVolume3DInput } from './HitResult3D';\n\ninterface MeshLike {\n  geometry: Geometry3D;\n}\n\n/** Not `instanceof Mesh3D`, since `Mesh3D` imports this module and importing it back makes a cycle */\nfunction hasGeometry(node: Container3D): node is Container3D & MeshLike {\n  return (node as Container3D & Partial<MeshLike>).geometry instanceof Geometry3D;\n}\n\n/**\n * A string resolves against the node's current geometry, so `Mesh3D`'s `geometry` setter resolves it again\n * @returns The shape to pick against, or `null` for none or invalid input.\n * @internal\n */\nexport function resolveHitVolume(node: Container3D, input: HitVolume3DInput): HitVolume3D | null {\n  if (input === null) return null;\n\n  if (typeof input === 'string') {\n    if (input === 'box') {\n      if (hasGeometry(node)) return node.geometry.bounds3D;\n      return getLocalBounds3D(node, new Box(), false);\n    }\n    if (input === 'geometry') {\n      if (hasGeometry(node)) return node.geometry;\n      warn(\"hitVolume: 'geometry' requires a Mesh3D — plain Container3D has no geometry; ignoring hitVolume\");\n      return null;\n    }\n    warn(`hitVolume: unsupported string '${String(input)}'. Expected 'box' or 'geometry'; ignoring hitVolume`);\n    return null;\n  }\n\n  if (input instanceof Box) return input;\n  if (input instanceof Sphere) {\n    if (input.radius < 0) {\n      warn('hitVolume: Sphere has a negative radius (empty) — ignoring hitVolume. Did you omit the radius argument?');\n      return null;\n    }\n    return input;\n  }\n  if (input instanceof Geometry3D) return input;\n\n  if (typeof input.raycast === 'function' && typeof input.boundingRadiusSq === 'number') return input;\n\n  warn('hitVolume: expected Box, Sphere, Geometry3D, an IHitVolume3D, string shorthand, or null; ignoring hitVolume');\n  return null;\n}\n","const textureSetIdsByHash = new Map<number, number>();\nlet nextTextureSetId = 0;\n\n/**\n * The id every material with these sources in these slots shares, counted from 0 so the sort key's 16-bit\n * field keeps the first 65,536 sets apart; never freed, like pixi's `uid()`\n *\n * Looked up by a 53-bit hash of the source uids in slot order; two sets on one hash would draw as one.\n * @internal\n */\nexport function textureSetId(textures: ArrayLike<{ source: { uid: number } }>): number {\n  let lo = 0x811c9dc5;\n  let hi = 0x9e3779b9;\n\n  for (let t = 0; t < textures.length; t++) {\n    const uid = textures[t].source.uid;\n    lo = Math.imul(lo ^ uid, 0x01000193);\n    hi = Math.imul(hi + uid, 0x85ebca6b);\n    hi ^= hi >>> 13;\n  }\n\n  const hash = (hi >>> 11) * 0x1_0000_0000 + (lo >>> 0);\n  let id = textureSetIdsByHash.get(hash);\n\n  if (id === undefined) {\n    id = nextTextureSetId++;\n    textureSetIdsByHash.set(hash, id);\n  }\n\n  return id;\n}\n","import { WGSL_ALIGN_SIZE_DATA } from 'pixi.js';\n\nimport type { StructDefinition } from '../ShaderBit';\n\n/**\n * Ties keep declaration order, so one `def` always packs the same way\n * @internal\n */\nexport function packStructFields(def: StructDefinition): StructDefinition {\n  const entries = Object.keys(def).map((name, index) => {\n    const info = WGSL_ALIGN_SIZE_DATA[def[name]];\n\n    return { name, align: info?.align ?? 0, size: info?.size ?? 0, index };\n  });\n\n  entries.sort((a, b) => b.align - a.align || b.size - a.size || a.index - b.index);\n\n  const wide = entries.filter((e) => e.align >= 8);\n  const scalars = entries.filter((e) => e.align > 0 && e.align < 8);\n  const unknown = entries.filter((e) => e.align === 0);\n\n  const packed: StructDefinition = {};\n  let scalarCursor = 0;\n\n  for (const e of wide) {\n    packed[e.name] = def[e.name];\n\n    if (e.align === 16 && e.size === 12 && scalarCursor < scalars.length) {\n      const s = scalars[scalarCursor++];\n      packed[s.name] = def[s.name];\n    }\n  }\n\n  for (let i = scalarCursor; i < scalars.length; i++) packed[scalars[i].name] = def[scalars[i].name];\n  for (const e of unknown) packed[e.name] = def[e.name];\n\n  return packed;\n}\n","import type { BindingGroup, BindingSpec, BindingVisibility, ResourceType, UniformGroupBindings } from '../ShaderBit';\n\n/** @internal */\nexport function bindingType(spec: BindingSpec): string {\n  return typeof spec === 'string' ? spec : spec.type;\n}\n\n/** @internal */\nexport function bindingVisibility(spec: BindingSpec): BindingVisibility {\n  return typeof spec === 'string' ? 'both' : (spec.visibility ?? 'both');\n}\n\ninterface BindingField {\n  name: string;\n  spec: BindingSpec;\n  /** The bind group's name, unless the field sits in a nested {@link UniformGroupBindings} */\n  uniformGroup: string;\n}\n\nfunction isUniformGroup(entry: BindingSpec | UniformGroupBindings): entry is UniformGroupBindings {\n  return typeof entry === 'object' && typeof entry.type !== 'string';\n}\n\n/**\n * @yields Each binding, a nested uniform group's fields in place of the group\n * @internal\n */\nexport function* bindingFields(bindings: BindingGroup, bindGroupName: string): Generator<BindingField> {\n  for (const [name, entry] of Object.entries(bindings)) {\n    if (isUniformGroup(entry)) {\n      for (const [fieldName, spec] of Object.entries(entry)) yield { name: fieldName, spec, uniformGroup: name };\n    } else {\n      yield { name, spec: entry, uniformGroup: bindGroupName };\n    }\n  }\n}\n\n/** @internal */\nexport function capitalize(groupName: string): string {\n  return groupName.charAt(0).toUpperCase() + groupName.slice(1);\n}\n\n/** @internal */\nexport const RESOURCE_TYPES: ReadonlySet<string> = new Set(\n  Object.keys({\n    'texture_2d<f32>': true,\n    'texture_2d<u32>': true,\n    'texture_2d<i32>': true,\n    'texture_2d_array<f32>': true,\n    'texture_3d<f32>': true,\n    'texture_cube<f32>': true,\n    'texture_cube_array<f32>': true,\n    texture_depth_2d: true,\n    texture_depth_2d_array: true,\n    texture_depth_cube: true,\n    texture_depth_cube_array: true,\n    sampler: true,\n    sampler_comparison: true,\n  } satisfies Record<ResourceType, true>),\n);\n\n/**\n * Matches a malformed `storage<>` too, so the caller can warn; `parseStorageType` returns `null` for it\n * @internal\n */\nexport function isStorageType(type: string): boolean {\n  return /^storage<.*>$/.test(type);\n}\n\n/** @internal */\nexport function parseStorageType(type: string): string | null {\n  const match = type.match(/^storage<(\\w+(?:<\\w+>)?)>$/);\n  return match ? match[1] : null;\n}\n\n/**\n * Matches a malformed `uniform<>` too, so the caller can warn; `parseUniformBufferType` returns `null` for it\n * @internal\n */\nexport function isUniformBufferType(type: string): boolean {\n  return /^uniform<.*>$/.test(type);\n}\n\n/** @internal */\nexport function parseUniformBufferType(type: string): string | null {\n  const match = type.match(/^uniform<(\\w+)>$/);\n  return match ? match[1] : null;\n}\n","import { warn } from 'pixi.js';\n\nimport type { ShaderBit, StructDefinition } from '../ShaderBit';\nimport { packStructFields } from './packStructFields';\nimport { bindingFields, bindingType, isStorageType, isUniformBufferType, RESOURCE_TYPES } from './parseBindingType';\n\n/** Each fits one texel; integers are scalars only, since the material data class writes vectors as floats */\nconst MATERIAL_FIELD_TYPES = new Set(['f32', 'vec2<f32>', 'vec3<f32>', 'vec4<f32>', 'mat2x2<f32>', 'u32', 'i32']);\n\n/**\n * The one source of a material's layout: the shader (`materialStructPackPlugin`) and the material\n * at construction both take it from here, and `validateMaterialStruct` checks they match\n * @internal\n */\nexport function mergeMaterialStruct(bits: readonly ShaderBit[]): StructDefinition {\n  const fields: StructDefinition = {};\n\n  for (const bit of bits) {\n    const declared = bit.bindings?.material;\n    if (!declared) continue;\n\n    for (const { name, spec } of bindingFields(declared, 'material')) {\n      const type = bindingType(spec);\n      if (RESOURCE_TYPES.has(type) || isStorageType(type) || isUniformBufferType(type)) continue;\n\n      if (!MATERIAL_FIELD_TYPES.has(type)) {\n        throw new Error(\n          `[mergeMaterialStruct] Material field \"${name}\" in bit \"${bit.name}\" is \"${type}\". ` +\n            `Material fields must be f32, u32, i32, a vec2, vec3 or vec4 of f32, or mat2x2<f32>.`,\n        );\n      }\n\n      const existing = fields[name];\n      if (existing === undefined) {\n        fields[name] = type as StructDefinition[string];\n      } else if (existing !== type) {\n        warn(\n          `[mergeMaterialStruct] Material field \"${name}\" redefined by bit \"${bit.name}\" with a different ` +\n            `type: \"${existing}\" → \"${type}\". Keeping original.`,\n        );\n      }\n    }\n  }\n\n  return packStructFields(fields);\n}\n\n/**\n * Keeps field order, which sets the offsets\n * @internal\n */\nexport function materialStructSnapshot(def: StructDefinition): string {\n  return JSON.stringify(def);\n}\n","import { BufferImageSource, CubeTexture, Texture, TextureSource, TextureView } from 'pixi.js';\n\n/**\n * The flat normal map a material without one binds; code compares against it to mean \"no normal map\"\n * @internal\n */\nexport const NORMAL_MAP = new Texture({\n  source: new BufferImageSource({\n    resource: new Uint8Array([128, 128, 255, 255]),\n    width: 1,\n    height: 1,\n    alphaMode: 'premultiply-alpha-on-upload',\n    label: 'NORMAL',\n  }),\n  label: 'NORMAL',\n});\n\n/**\n * Process-wide singletons, so any code that destroys textures it holds must skip these\n * @internal\n */\nexport const SHARED_DEFAULT_TEXTURES: ReadonlySet<Texture> = new Set([Texture.WHITE, Texture.EMPTY, NORMAL_MAP]);\n\n/** @internal */\nexport const CUBETEXTURE_EMPTY = CubeTexture.from({\n  faces: {\n    left: Texture.EMPTY,\n    right: Texture.EMPTY,\n    top: Texture.EMPTY,\n    bottom: Texture.EMPTY,\n    front: Texture.EMPTY,\n    back: Texture.EMPTY,\n  },\n  label: 'pixijs-3d-empty-skybox',\n});\n\n/**\n * Placeholder for integer-texture slots, where `Texture.EMPTY` fails the draw on WebGL and the bind\n * group on WebGPU, even when the shader never reads it\n * @internal\n */\nexport const UINT_EMPTY = new Texture({\n  source: new BufferImageSource({\n    resource: new Uint32Array(4),\n    width: 1,\n    height: 1,\n    format: 'rgba32uint',\n    scaleMode: 'nearest',\n    alphaMode: 'no-premultiply-alpha',\n    label: 'UINT_EMPTY',\n  }),\n  label: 'UINT_EMPTY',\n});\n\n/**\n * Placeholder shadow map, with no pixels since WebGPU can't copy into `depth32float`, and comparison\n * on, since WebGL fails a draw whose `sampler2DArrayShadow` reads a depth texture with it off\n * @internal\n */\nexport const DEPTH_EMPTY = new Texture({\n  source: new TextureSource({\n    width: 1,\n    height: 1,\n    format: 'depth32float',\n    scaleMode: 'nearest',\n    viewDimension: '2d-array',\n    autoGenerateMipmaps: false,\n    arrayLayerCount: 4,\n    compare: 'less',\n    label: 'DEPTH_EMPTY',\n  }),\n  label: 'DEPTH_EMPTY',\n});\n\nconst DEPTH_STENCIL_EMPTY = new Texture({\n  source: new TextureSource({\n    width: 1,\n    height: 1,\n    format: 'depth24plus-stencil8',\n    scaleMode: 'nearest',\n    viewDimension: '2d',\n    autoGenerateMipmaps: false,\n    label: 'DEPTH_2D_EMPTY',\n  }),\n  label: 'DEPTH_2D_EMPTY',\n});\n\n/**\n * Placeholder for a sampled depth slot; a depth-only view, since a WebGPU `texture_depth_2d` binding\n * takes only the depth aspect of a depth-stencil texture\n * @internal\n */\nexport const DEPTH_VIEW_PLACEHOLDER = new TextureView(DEPTH_STENCIL_EMPTY.source, { aspect: 'depth-only' });\n","import { GlobalResourceRegistry, warn } from 'pixi.js';\n\nconst seen = new Set<string>();\n\nGlobalResourceRegistry.register({ clear: () => seen.clear() });\n\n/**\n * Warns once per key for the whole page, not per object, until `GlobalResourceRegistry` is released\n * @internal\n */\nexport function warnOnce(key: string, ...args: unknown[]): void {\n  if (seen.has(key)) return;\n  seen.add(key);\n  warn(...args);\n}\n","import { BufferImageSource } from 'pixi.js';\n\n/**\n * Width of every data texture past one row; a power of two, since the shaders address a texel with\n * a mask and a shift. WebGL2 guarantees only 2048, so 4096 is a device requirement\n * @internal\n */\nexport const DATA_TEXTURE_WIDTH = 4096;\n\n/** @internal */\nexport const WORDS_PER_TEXEL = 4;\n\nconst ROW_FLOATS = DATA_TEXTURE_WIDTH * WORDS_PER_TEXEL;\n\nconst INDEX_MASK = DATA_TEXTURE_WIDTH - 1;\nconst INDEX_SHIFT = Math.log2(DATA_TEXTURE_WIDTH);\n\n/**\n * Rounds a float count past one row up to whole rows; a shorter one stays exact, as a row is 64 KB and\n * every batch has a store\n * @internal\n */\nexport function alignToDataTextureRows(floatCount: number): number {\n  if (floatCount <= ROW_FLOATS || floatCount % ROW_FLOATS === 0) return floatCount;\n\n  return floatCount + ROW_FLOATS - (floatCount % ROW_FLOATS);\n}\n\n/** @internal */\nexport function dataTextureSize(floatCount: number): { width: number; height: number } {\n  const pixelCount = floatCount / WORDS_PER_TEXEL;\n  const width = Math.min(pixelCount, DATA_TEXTURE_WIDTH);\n\n  return { width, height: Math.ceil(pixelCount / width) };\n}\n\n/**\n * An `rgba32uint` view of the store: a small integer's bits read as a denormal float, which a float\n * fetch may flush to zero. Size the array with {@link alignToDataTextureRows}\n * @internal\n */\nexport function createDataTextureSource(data: Float32Array): BufferImageSource {\n  const { width, height } = dataTextureSize(data.length);\n\n  return new BufferImageSource({\n    resource: new Uint32Array(data.buffer),\n    width,\n    height,\n    format: 'rgba32uint',\n    scaleMode: 'nearest',\n    alphaMode: 'no-premultiply-alpha',\n  });\n}\n\n/**\n * Widens a range of a row or more to whole rows, which pixi sends as one upload rather than three\n * @internal\n */\nexport function uploadTexelRange(source: BufferImageSource, start: number, end: number): void {\n  if (end - start >= DATA_TEXTURE_WIDTH) {\n    start &= ~INDEX_MASK;\n    end = (end + INDEX_MASK) & ~INDEX_MASK;\n  }\n\n  source.update(start, end);\n}\n\n/** @internal */\nexport function uploadFloatRange(source: BufferImageSource, start: number, end: number): void {\n  uploadTexelRange(source, Math.floor(start / WORDS_PER_TEXEL), Math.ceil(end / WORDS_PER_TEXEL));\n}\n\n/**\n * A mask and a shift, not `%` and `/`, whose sign correction on an `int` costs about 20% of the fetch\n * @internal\n */\nexport function glTexelAddress(index: string): string {\n  return `ivec2((${index}) & ${INDEX_MASK}, (${index}) >> ${INDEX_SHIFT})`;\n}\n\n/**\n * Masks and shifts for the reason {@link glTexelAddress} gives\n * @internal\n */\nexport function wgslTexelAddress(index: string): string {\n  return `vec2<i32>((${index}) & ${INDEX_MASK}, (${index}) >> ${INDEX_SHIFT})`;\n}\n","import { WGSL_ALIGN_SIZE_DATA } from 'pixi.js';\n\ninterface StructElement {\n  name: string;\n  type: string;\n  offset: number;\n  size: number;\n  /** Size in 32-bit words, so 4 for a `mat2x2<f32>` */\n  components: number;\n}\n\ninterface StructLayout {\n  elements: StructElement[];\n  /** Where the last field ends, in bytes, not rounded up to the struct's alignment as WGSL does */\n  size: number;\n}\n\n/**\n * The material data class writes at these offsets and `layoutStructTexels` reads at them\n * @internal\n */\nexport function createStructLayout(fields: Record<string, string>): StructLayout {\n  const elements: StructElement[] = [];\n  let offset = 0;\n\n  for (var name in fields) {\n    const type = fields[name];\n    const info = WGSL_ALIGN_SIZE_DATA[type];\n\n    if (!info) continue;\n\n    offset = Math.ceil(offset / info.align) * info.align;\n\n    elements.push({\n      name,\n      type,\n      offset,\n      size: info.size,\n      components: info.size / 4,\n    });\n\n    offset += info.size;\n  }\n\n  return { elements, size: offset };\n}\n","import { WORDS_PER_TEXEL } from '../../core/buffers/dataTextureLayout';\nimport { createStructLayout } from '../../core/shader/codegen/structLayout';\nimport type { StructDefinition } from '../../core/shader/ShaderBit';\nimport type { BaseMaterial3D } from '../BaseMaterial3D';\n\n/**\n * A material's GPU-side values, as `material.data`, with a property per field its bits declare\n *\n * - Scalars read and write as numbers.\n * - Vectors read as live `Float32Array` views and are set by copying from any array-like no longer\n *   than the field; a longer one throws. Writing into a view queues no upload, so call\n *   `material.update()` afterwards.\n * - Assigning a field queues an upload; repeat writes in one frame upload once.\n *\n * A material with fixed fields narrows the type, as {@link Material3DData} does.\n * @category materials\n * @advanced\n */\nexport interface MaterialData {\n  /** @internal */\n  readonly _f32: Float32Array;\n  /**\n   * Base colour in linear light, alpha in the last lane; absent when the struct doesn't declare it\n   *\n   * Set `material.baseColor` and `material.alpha` instead, which keep `displayBaseColor` in step.\n   */\n  baseColor?: Float32Array;\n  /** Base colour in display space, alpha in the last lane, for unlit bits; absent when not declared */\n  displayBaseColor?: Float32Array;\n  /** Cutoff for `alphaMode: 'mask'`; absent when the struct doesn't declare it */\n  alphaCutoff?: number;\n  /** The UV transform's 2x2 part, row-major as `[m00, m01, m10, m11]`; absent when the struct doesn't declare it */\n  uvTransformRow0?: Float32Array;\n  /** The UV transform's offset; absent when the struct doesn't declare it */\n  uvOffset?: Float32Array;\n  /** Any other field the struct declares */\n  [field: string]: number | ArrayLike<number> | undefined;\n}\n\ntype MaterialDataClass = new (material: BaseMaterial3D) => MaterialData;\n\nconst classCache = new Map<string, MaterialDataClass>();\n\nconst TEXEL_BYTES = WORDS_PER_TEXEL * 4;\n\n/**\n * Float setters compare with `Math.fround(value)`, integer ones raw since rounding would merge\n * distinct integers; accessors sit on the prototype so each layout has one hidden class\n * @internal\n */\nexport function getOrCreateMaterialDataClass(def: StructDefinition, snapshot: string): MaterialDataClass {\n  const cached = classCache.get(snapshot);\n  if (cached) return cached;\n\n  const layout = createStructLayout(def);\n  const bytes = Math.max(1, Math.ceil(layout.size / TEXEL_BYTES)) * TEXEL_BYTES;\n\n  class GeneratedMaterialData {\n    public readonly _f32: Float32Array;\n    public readonly _u32: Uint32Array;\n    public readonly _material: BaseMaterial3D;\n    public readonly _views: Record<string, Float32Array> = Object.create(null);\n\n    constructor(material: BaseMaterial3D) {\n      this._material = material;\n      const buffer = new ArrayBuffer(bytes);\n      this._f32 = new Float32Array(buffer);\n      this._u32 = new Uint32Array(buffer);\n    }\n  }\n\n  const prototype = GeneratedMaterialData.prototype;\n\n  for (const element of layout.elements) {\n    const floatOffset = element.offset / 4;\n    const { components } = element;\n\n    if (components === 1) {\n      const integer = element.type === 'u32' || element.type === 'i32';\n      Object.defineProperty(prototype, element.name, {\n        enumerable: true,\n        get(this: GeneratedMaterialData): number {\n          return (integer ? this._u32 : this._f32)[floatOffset];\n        },\n        set(this: GeneratedMaterialData, value: number) {\n          const words = integer ? this._u32 : this._f32;\n          if (words[floatOffset] === (integer ? value : Math.fround(value))) return;\n          words[floatOffset] = value;\n          this._material.update();\n        },\n      });\n    } else {\n      const end = floatOffset + components;\n      const name = element.name;\n      Object.defineProperty(prototype, name, {\n        enumerable: true,\n        get(this: GeneratedMaterialData): Float32Array {\n          return (this._views[name] ??= this._f32.subarray(floatOffset, end));\n        },\n        set(this: GeneratedMaterialData, value: ArrayLike<number>) {\n          (this._views[name] ??= this._f32.subarray(floatOffset, end)).set(value);\n          this._material.update();\n        },\n      });\n    }\n  }\n\n  const cls = GeneratedMaterialData as unknown as MaterialDataClass;\n  classCache.set(snapshot, cls);\n  return cls;\n}\n","import type { Texture } from 'pixi.js';\n\nimport type { BaseMaterial3D } from '../BaseMaterial3D';\n\n/**\n * A material's `textures`: one property per texture slot its shader declares; see\n * {@link BaseMaterial3D#textures}\n *\n * A slot you never set holds the material's default, usually `Texture.WHITE`. Each material narrows\n * this type with its own slots, as {@link Material3DTextures} does. The index type includes\n * `undefined` only so those can list optional slots: assigning `undefined` type-checks, but it\n * throws and leaves the slot empty.\n * @example\n * ```ts\n * const water = new BaseMaterial3D({\n *   descriptor: { bitsGpu: [myRippleBit], bitsGl: [myRippleBit] },\n *   textures: { ripples: rippleTexture },\n * });\n * water.textures.ripples = calmRippleTexture;\n * ```\n * @category materials\n * @standard\n */\nexport interface MaterialTextures {\n  [slot: string]: Texture | undefined;\n}\n\ntype MaterialTexturesClass = new (material: BaseMaterial3D) => object;\n\nconst classCache = new Map<string, MaterialTexturesClass>();\n\n/**\n * One class per slot list, each accessor with its slot index baked in; instances are sealed, so a\n * misspelt slot name throws\n * @internal\n */\nexport function getOrCreateMaterialTexturesClass(names: readonly string[]): MaterialTexturesClass {\n  const key = names.join('\\n');\n  let TexturesClass = classCache.get(key);\n  if (TexturesClass) return TexturesClass;\n\n  class MaterialTextures {\n    public readonly _material: BaseMaterial3D;\n\n    constructor(material: BaseMaterial3D) {\n      this._material = material;\n      Object.seal(this);\n    }\n  }\n\n  names.forEach((name, index) => {\n    Object.defineProperty(MaterialTextures.prototype, name, {\n      get(this: MaterialTextures): Texture {\n        return this._material._textures[index];\n      },\n      set(this: MaterialTextures, value: Texture) {\n        this._material._setTextureSlot(index, value);\n      },\n      enumerable: true,\n      configurable: false,\n    });\n  });\n\n  TexturesClass = MaterialTextures;\n  classCache.set(key, TexturesClass);\n  return TexturesClass;\n}\n","import type { BindGroup, BindResource } from 'pixi.js';\n\ninterface BindGroupKeys {\n  resources: Record<number, BindResource | null>;\n  _keyedIds: number[];\n  _rekey(index: number, id: number): void;\n}\n\n/**\n * Does for a group set unwatched what pixi does on a resource's `change`; reads pixi's private key\n * state until pixi has a `BindGroup.refresh()`\n * @internal\n */\nexport function refreshBindGroup(group: BindGroup): void {\n  const keyed = group as unknown as BindGroupKeys;\n  const resources = keyed.resources;\n  const keys = group._resourceKeys;\n\n  for (let i = 0; i < keys.length; i++) {\n    const index = keys[i];\n    const resource = resources[index];\n    if (!resource) continue;\n\n    if (resource.destroyed) {\n      resources[index] = null;\n      keyed._rekey(index, -1);\n      continue;\n    }\n\n    const id = resource._resourceId;\n    if (keyed._keyedIds[index] !== id) keyed._rekey(index, id);\n  }\n}\n","import { materialStructSnapshot, mergeMaterialStruct } from '../../core/shader/codegen/materialStruct';\nimport type { ShaderBit } from '../../core/shader/ShaderBit';\nimport type { BaseMaterial3D } from '../BaseMaterial3D';\n\n/**\n * Built once per compiled shader and kept beside it, so validating a material on a cache hit stays cheap\n * @internal\n */\nexport interface MaterialLayout {\n  structSnapshot: string;\n  textureNames: string[];\n}\n\n/**\n * Builds the {@link MaterialLayout} a bit list declares\n * @internal\n */\nexport function getMaterialLayout(bits: readonly ShaderBit[]): MaterialLayout {\n  return {\n    structSnapshot: materialStructSnapshot(mergeMaterialStruct(bits)),\n    textureNames: collectTextureNames(bits),\n  };\n}\n\n/**\n * Throws unless the compiled struct matches the one `material.data` was laid out in at construction\n * @internal\n */\nexport function validateMaterialStruct(layout: MaterialLayout, material: BaseMaterial3D): void {\n  const compiled = layout.structSnapshot;\n\n  if (compiled !== material._materialStructSnapshot) {\n    throw new Error(\n      `[validateMaterialStruct] Compiled Material struct does not match the material's construction-time ` +\n        `layout.\\n  compiled:     ${compiled}\\n  construction: ${material._materialStructSnapshot}\\n` +\n        `Material-group struct fields may only come from construction-pinned bits — a per-mesh/per-view ` +\n        `bit is declaring \\`bindings.material\\` fields, or a custom getPrimaryDescriptor diverges from ` +\n        `its constructor.`,\n    );\n  }\n}\n\n/**\n * Texture names across `bits`, in the order the textures plugins number the shader's samplers\n * @internal\n */\nexport function collectTextureNames(bits: readonly ShaderBit[]): string[] {\n  const names: string[] = [];\n\n  for (const bit of bits) {\n    if (!bit.textures) continue;\n    for (const name of bit.textures) names.push(name);\n  }\n\n  return names;\n}\n\n/**\n * Throws unless the shader's texture order matches the material's slots, which its bind groups bind\n * by position\n * @internal\n */\nexport function validateMaterialTextureSlots(layout: MaterialLayout, material: BaseMaterial3D): void {\n  const names = layout.textureNames;\n\n  for (let i = 0; i < names.length; i++) {\n    if (material._slotByName[names[i]] !== i) {\n      throw new Error(\n        `[validateMaterialTextureSlots] Shader texture slots do not match the material's derived layout. ` +\n          `Shader order: [${names.join(', ')}]; material slots: ${JSON.stringify(material._slotByName)}. ` +\n          `Every texture-bearing bit must be part of the material's texture derivation.`,\n      );\n    }\n  }\n\n  if (names.length !== material._textures.length) {\n    throw new Error(\n      `[validateMaterialTextureSlots] Material allocates ${material._textures.length} texture slot(s) but the ` +\n        `shader declares ${names.length} ([${names.join(', ')}]). Slots and bit declarations must derive together.`,\n    );\n  }\n}\n","import { BindGroup, Color, definedProps, Matrix, NOOP, State, Texture, warn } from 'pixi.js';\nimport type { BufferResource, ColorSource, TextureDestroyOptions, TextureSource, Topology, TypeOrBool } from 'pixi.js';\n\nimport { textureSetId } from '../core/batcher/textureSetId';\nimport { passBitRegistry } from '../core/render-passes/passBitRegistry';\nimport { RenderPassBit } from '../core/render-passes/RenderPass';\nimport { materialStructSnapshot, mergeMaterialStruct } from '../core/shader/codegen/materialStruct';\nimport type { ShaderBit } from '../core/shader/ShaderBit';\nimport { ShaderDescriptor } from '../core/shader/ShaderDescriptor';\nimport type { ShaderDescriptorOptions } from '../core/shader/ShaderDescriptor';\nimport { SHARED_DEFAULT_TEXTURES } from '../core/textures/DefaultTextures';\nimport type { Mesh3D } from '../scene/Mesh3D';\nimport type { View3D } from '../scene/View3D';\nimport { copyState } from '../utils/copyState';\nimport { resolveDestroy3DFlag } from '../utils/Destroy3DOptions';\nimport { UnstableList } from '../utils/UnstableList';\nimport { warnOnce } from '../utils/warnOnce';\nimport { normalizePassEntry } from './PassDescriptor';\nimport type { PassDescriptor, PassDescriptorOptions } from './PassDescriptor';\nimport { getOrCreateMaterialDataClass } from './utils/createMaterialDataClass';\nimport type { MaterialData } from './utils/createMaterialDataClass';\nimport { getOrCreateMaterialTexturesClass } from './utils/createMaterialTexturesClass';\nimport type { MaterialTextures } from './utils/createMaterialTexturesClass';\nimport { refreshBindGroup } from './utils/refreshBindGroup';\nimport { collectTextureNames } from './utils/validateMaterialTextureSlots';\n\n/** @internal */\nexport interface MaterialUploadQueue {\n  enqueueDirty(material: BaseMaterial3D): void;\n  /** Reads the material's `data` for the length of its place, so call it before `data` is dropped */\n  remove(material: BaseMaterial3D): void;\n  uniformResource(material: BaseMaterial3D): BufferResource;\n}\n\n/**\n * Creates a render `State` with the defaults every material starts from: depth test on, blending\n * off, back-face culling on\n * @category materials\n * @advanced\n */\nexport function stateFor3D(): State {\n  const state = new State();\n\n  state.depthTest = true;\n  state.blend = false;\n  state.culling = true;\n\n  return state;\n}\n\n/**\n * How a material treats alpha, matching glTF's `alphaMode`\n *\n * - `'opaque'` (default): draws fully opaque, ignoring {@link BaseMaterial3D#alpha} and the alpha\n *   of textures and vertex colours. In an image pixi premultiplies, such as a PNG, a texel with\n *   alpha 0 draws black.\n * - `'mask'`: fragments with alpha below {@link BaseMaterial3D#alphaCutoff} are discarded\n * - `'blend'`: alpha-blended over what is behind it. Blended meshes draw back to front by each\n *   mesh's origin, not per triangle, so large or overlapping ones can draw in the wrong order.\n * @example\n * ```ts\n * const leaves = new Material3D({ baseColorTexture: leafTexture, alphaMode: 'mask' });\n * ```\n * @category materials\n * @standard\n */\nexport type AlphaMode = 'opaque' | 'mask' | 'blend';\n\n/**\n * The colour space a material's shader does its colour maths in; see {@link BaseMaterial3D#colorSpace}\n *\n * - `'linear'` (default): decodes colours to linear light, works there, and encodes for display at\n *   the end. Lighting needs it.\n * - `'display'`: works on colours as authored, skipping the decode and the encode. Cheaper on phones,\n *   for an unlit material that only multiplies colours.\n * @example\n * ```ts\n * class MyStickerMaterial extends BaseMaterial3D {\n *   public override colorSpace: ColorSpace = 'display';\n *   public override lit = false;\n * }\n * ```\n * @category materials\n * @advanced\n */\nexport type ColorSpace = 'linear' | 'display';\n\n/**\n * Constructor options shared by every {@link BaseMaterial3D} subclass\n * @example\n * ```ts\n * interface MyGlowMaterialOptions extends BaseMaterial3DOptions {\n *   intensity?: number;\n * }\n * ```\n * @category materials\n * @standard\n */\nexport interface BaseMaterial3DOptions {\n  /**\n   * Name for debugging and for finding the material; the glTF loader sets it to the name in the file\n   * @example\n   * ```ts\n   * new Material3D({ label: 'Paint' });\n   * ```\n   */\n  label?: string;\n  /**\n   * Base colour tint; the source's alpha is ignored, {@link BaseMaterial3DOptions#alpha} sets opacity\n   * @example\n   * ```ts\n   * new Material3D({ baseColor: 0xff7733 });\n   * ```\n   */\n  baseColor?: ColorSource;\n  /**\n   * Base opacity; `alphaMode: 'opaque'` ignores it\n   * @default 1\n   * @example\n   * ```ts\n   * new Material3D({ alphaMode: 'blend', alpha: 0.4 });\n   * ```\n   */\n  alpha?: number;\n  /**\n   * Base colour (albedo) texture\n   * @default Texture.WHITE\n   * @example\n   * ```ts\n   * new Material3D({ baseColorTexture: crateTexture });\n   * ```\n   */\n  baseColorTexture?: Texture;\n\n  /**\n   * Textures by slot name, for the slots a `descriptor` or `extraBits` declares\n   *\n   * The bits' `textures` arrays decide which slots exist; this map only fills them. A slot left out\n   * gets `Texture.WHITE`. A `baseColor` entry here wins over\n   * {@link BaseMaterial3DOptions#baseColorTexture}.\n   * @example\n   * ```ts\n   * new BaseMaterial3D({\n   *   descriptor: { bitsGpu: [waterBit], bitsGl: [waterBit] },\n   *   textures: { waterNormal: waterNormalTexture },\n   * });\n   * ```\n   * @advanced\n   */\n  textures?: Record<string, Texture | undefined>;\n\n  /**\n   * Extra shader bits composed into the material's shader, fixed for its lifetime\n   *\n   * {@link Material3D}, {@link PhongMaterial} and {@link FlatMaterial} each document where they sit\n   * in their bit list; on a material built from a raw `descriptor`, as `ToonMaterial` and\n   * `PortalMaterial` are, they follow its bits. A bit may declare material fields and textures;\n   * fill its textures through the `textures` option, or later through\n   * {@link BaseMaterial3D#textures}. A bit that uses `PI` or `INV_PI` lists\n   * {@link mathConstantsBit} in its {@link ShaderBit#requires} rather than declaring them, and one that\n   * calls `screenUVFromWorld` or `sampleScreenCopy` lists {@link screenSpaceFuncsBit}. To add bits to a\n   * material that exists, such as one the glTF loader built, `material.clone({ extraBits })` makes a\n   * copy with them and everything else the material has. For billboarding, set\n   * {@link Mesh3D#billboardMode} instead.\n   * @example\n   * ```ts\n   * new Material3D({ baseColor: 0xff3355, extraBits: [glossBit] });\n   * ```\n   * @advanced\n   */\n  extraBits?: readonly ShaderBit[];\n\n  /**\n   * How alpha is treated; see {@link AlphaMode}\n   * @default 'opaque'\n   * @example\n   * ```ts\n   * new Material3D({ baseColorTexture: leafTexture, alphaMode: 'mask' });\n   * ```\n   */\n  alphaMode?: AlphaMode;\n\n  /**\n   * Alpha below which fragments are discarded when `alphaMode` is `'mask'`\n   * @default 0.5\n   * @example\n   * ```ts\n   * new Material3D({ baseColorTexture: leafTexture, alphaMode: 'mask', alphaCutoff: 0.3 });\n   * ```\n   */\n  alphaCutoff?: number;\n\n  /**\n   * When `true`, back faces are drawn too and lit with their normal flipped\n   *\n   * Fixed at construction.\n   * @default false\n   * @example\n   * ```ts\n   * new Material3D({ baseColorTexture: leafTexture, alphaMode: 'mask', doubleSided: true });\n   * ```\n   */\n  doubleSided?: boolean;\n  /**\n   * When `true`, each triangle is shaded with its face normal instead of the smooth vertex normal\n   *\n   * Gives a faceted, low-poly look with no duplicated vertices, so one geometry can draw smooth or\n   * faceted depending on its material. A normal map still applies on top. No visible effect on an\n   * unlit material such as {@link FlatMaterial}. Fixed at construction.\n   * @default false\n   * @example\n   * ```ts\n   * new Material3D({ baseColor: 0x8a7f72, flatShading: true });\n   * ```\n   */\n  flatShading?: boolean;\n  /**\n   * Whether the view's distance {@link View3D#fog | fog} may reach this material\n   *\n   * Turn it off for skyboxes, water and anything else with its own distance falloff; a sky dome\n   * past the fog's far distance would turn flat fog colour. Fixed at construction.\n   * @default true\n   * @example\n   * ```ts\n   * new Material3D({ baseColorTexture: skyTexture, fog: false });\n   * ```\n   */\n  fog?: boolean;\n  /**\n   * Whether a geometry's vertex colours (its `colors`) tint this material; see\n   * {@link BaseMaterial3D#vertexColors}\n   * @default false\n   * @example\n   * ```ts\n   * new Material3D({ vertexColors: true });\n   * ```\n   */\n  vertexColors?: boolean;\n\n  /**\n   * Shader bits for the material's main pass, for a custom material\n   *\n   * The material's textures and data are laid out from `bitsGpu`, so `bitsGl` must declare the same\n   * texture names in the same order, or the constructor throws. A material whose bits change with\n   * its settings overrides {@link BaseMaterial3D#getPrimaryDescriptor} instead.\n   * @example\n   * ```ts\n   * new BaseMaterial3D({\n   *   descriptor: { bitsGpu: [myBit], bitsGl: [myBit] },\n   * });\n   * ```\n   * @advanced\n   */\n  descriptor?: ShaderDescriptorOptions;\n\n  /**\n   * Extra render passes this material draws in, keyed by the pass's `name`\n   *\n   * - `true`: draw in the pass with the pass's own shader and state.\n   * - a {@link PassDescriptorOptions} object: draw in it with your own shader, state or topology.\n   *   {@link PassDescriptor} says how these combine with the pass's own; they can't change later.\n   * - `false`, or left out: don't draw in it. Useful for opting out of a pass that spread options\n   *   or a subclass default turned on.\n   *\n   * A material can name a pass before the pass exists. A page has room for 24 custom pass names,\n   * `'outline'` included, each taken the first time anything names it; a name past that joins\n   * nothing, and a pass with it draws no meshes, without a warning.\n   * @example\n   * ```ts\n   * view.passes = [new OutlinePass({ width: 0.05 })];\n   * const hero = new Material3D({ baseColor: 0xff7733, passes: { outline: true } });\n   * ```\n   */\n  passes?: Record<string, PassDescriptorOptions | boolean>;\n\n  /**\n   * Primitive topology for every pass that doesn't set its own; left out, the geometry's is used\n   *\n   * `'line-list'` joins the indices in pairs, so a triangle index buffer drawn that way isn't a\n   * wireframe: it draws some edges and misses others. Use a geometry with line indices for that.\n   * @example\n   * ```ts\n   * new FlatMaterial({ baseColor: 0x00ff00, topology: 'point-list' });\n   * ```\n   */\n  topology?: Topology;\n\n  /**\n   * UV transform for every texture of the material; see {@link BaseMaterial3D#uvTransform}\n   *\n   * Leave it out to let a framed (spritesheet) base colour texture set the transform.\n   * @example\n   * ```ts\n   * new Material3D({ baseColorTexture: tileTexture, uvTransform: new Matrix().scale(4, 4) });\n   * ```\n   */\n  uvTransform?: Matrix;\n}\n\nlet UID = 0;\n\nconst IDENTITY_UV_ROW0 = new Float32Array([1, 0, 0, 1]);\n\n/** Pixi's base `TextureSource` `uploadMethodId`, which render textures and `ContainerSource` don't override */\nconst GPU_ONLY_UPLOAD_METHOD = 'unknown';\n\nfunction isFullFrame(texture: Texture): boolean {\n  if (texture.rotate !== 0) return false;\n  if (texture.noFrame) return true;\n  const frame = texture.frame;\n  return (\n    frame.x === 0 && frame.y === 0 && frame.width === texture.source.width && frame.height === texture.source.height\n  );\n}\n\n/**\n * Converts a display (sRGB) channel to linear light\n *\n * It uses a 2.2 gamma, the curve the shaders decode textures and encode their output with, rather\n * than the piecewise sRGB curve. Material colours you set as a `ColorSource` are display colours,\n * decoded with it.\n * @param channel - Display channel, from 0 to 1\n * @returns The linear-light channel value.\n * @category materials\n * @advanced\n */\nexport function srgbToLinear(channel: number): number {\n  return Math.pow(channel, 2.2);\n}\n\n/**\n * Converts a linear-light channel to display (sRGB); the inverse of {@link srgbToLinear}\n * @param channel - Linear-light channel value.\n * @returns The display channel value.\n * @category materials\n * @advanced\n */\nexport function linearToSrgb(channel: number): number {\n  return Math.pow(channel, 1 / 2.2);\n}\n\n/**\n * Writes a display colour's rgb into `target` at `offset` in linear light, times `scale`\n * @internal\n */\nexport function writeLinearRgb(target: Float32Array, offset: number, color: Color, scale = 1): void {\n  target[offset] = srgbToLinear(color.red) * scale;\n  target[offset + 1] = srgbToLinear(color.green) * scale;\n  target[offset + 2] = srgbToLinear(color.blue) * scale;\n}\n\n/**\n * Adds a display colour's rgb to `target` at `offset` in linear light, times `scale`\n * @internal\n */\nexport function addLinearRgb(target: Float32Array, offset: number, color: Color, scale: number): void {\n  target[offset] += srgbToLinear(color.red) * scale;\n  target[offset + 1] += srgbToLinear(color.green) * scale;\n  target[offset + 2] += srgbToLinear(color.blue) * scale;\n}\n\n/**\n * Whether `value` is an object literal, such as a feature group, rather than a texture, colour or\n * array, so `clone` merges it into the option it changes instead of replacing that\n * @param value - An option value\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype;\n}\n\n/** Data fields the base sets from its own options, which `clone` leaves to those options rather than copying */\nconst BASE_OWNED_FIELDS = new Set(['baseColor', 'displayBaseColor', 'alphaCutoff', 'uvTransformRow0', 'uvOffset']);\n\n/**\n * Base class for all 3D materials\n *\n * Holds what every material shares: base colour and alpha, the alpha mode, render state, texture\n * slots, a UV transform, and the data its shader reads. {@link Material3D}, {@link PhongMaterial}\n * and {@link FlatMaterial} build on it; a custom material passes its shader bits as `descriptor`.\n *\n * ## Sharing\n *\n * Many meshes can draw one material, and a change to it shows on all of them. A loaded model's\n * meshes draw its source's materials, shared with every model built from that source.\n * {@link BaseMaterial3D#clone} makes a copy of its own, with any constructor options changed, and\n * {@link Model3D#materials} gives one model copies to draw:\n * `model.materials = (material) => material.clone()`.\n *\n * ## Changing a material that has rendered\n *\n * Meshes pick up most changes on the next render: property setters, texture swaps, joining or\n * leaving a pass, and the view's `toneMapping`, `fog`, `environment` and `shadowFilter`. A few\n * need a call from you:\n *\n * - A {@link BatchedMesh3D} slot sees a texture swap, a new `alphaMode` or another change to the\n *   material's shader only after {@link BatchedMesh3D#invalidate}. A slot switching to or from\n *   `'blend'` also needs {@link BatchedMesh3D#setPassesAt} to move it between the opaque and\n *   transparent passes.\n * - After changing {@link BaseMaterial3D#colorSpace}, {@link BaseMaterial3D#vertexColors},\n *   {@link BaseMaterial3D#lit} or a field of {@link BaseMaterial3D#state}, call\n *   {@link Mesh3D#invalidate} on each mesh using the material.\n * - The `passes` overrides can't change; {@link BaseMaterial3D#clone | clone} the material with the new\n *   entry and assign the copy instead.\n * @example\n * ```ts\n * class MyGlowMaterial extends BaseMaterial3D {\n *   public override lit = false;\n *\n *   constructor(options: BaseMaterial3DOptions = {}) {\n *     super({ ...options, descriptor: { bitsGpu: [myGlowBit], bitsGl: [myGlowBit] } });\n *   }\n * }\n *\n * const orb = new Mesh3D({ geometry: new SphereGeometry(), material: new MyGlowMaterial() });\n * ```\n * @typeParam TData - Type of {@link BaseMaterial3D#data}, the material's struct fields.\n * @typeParam TTextures - Type of {@link BaseMaterial3D#textures}, the material's texture slots.\n * @typeParam TOptions - The class's constructor options, which {@link BaseMaterial3D#clone} takes.\n * A subclass with options of its own passes them here, and reads them back in `_toOptions`.\n * @category materials\n * @standard\n */\nexport class BaseMaterial3D<\n  TData extends MaterialData = MaterialData,\n  TTextures extends MaterialTextures = MaterialTextures,\n  TOptions extends object = BaseMaterial3DOptions,\n> {\n  /** Built on first read of `EMPTY`, so importing the module builds nothing */\n  private static _empty: BaseMaterial3D | null = null;\n\n  /**\n   * A shared material with no shader, which a {@link Mesh3D} holds until it's given a material\n   *\n   * A mesh on it draws nothing and compiles no shader, though its skeleton and morph targets still\n   * upload. Assign it to a mesh's `material` to stop the mesh drawing; to hide a mesh for a\n   * while, `visible = false` is cheaper. Don't give it to a {@link BatchedMesh3D} slot that's in a\n   * pass, even a hidden one: such a slot needs a real material.\n   *\n   * Every waiting mesh shares it, so don't edit it. Its `destroy` does nothing, as with pixi's\n   * `Texture.EMPTY`.\n   * @example\n   * ```ts\n   * if (mesh.material === BaseMaterial3D.EMPTY) mesh.material = new Material3D();\n   * ```\n   * @advanced\n   */\n  public static get EMPTY(): BaseMaterial3D {\n    return (BaseMaterial3D._empty ??= (() => {\n      const empty = new BaseMaterial3D();\n      empty.destroy = NOOP;\n      return empty;\n    })());\n  }\n\n  /**\n   * Unique id for this material instance\n   * @advanced\n   */\n  public uid = UID++;\n\n  /**\n   * Render state (blending, depth, culling) for every draw with this material\n   *\n   * `alphaMode` and `doubleSided` set parts of it. To change a field after the material has\n   * rendered, see {@link BaseMaterial3D}. `polygonOffset` works on WebGL only; WebGPU ignores it.\n   * @example\n   * ```ts\n   * // 'blend' draws it after the opaque meshes, so with no depth test it shows through them\n   * const overlay = new FlatMaterial({ baseColor: 0xffcc00, alphaMode: 'blend' });\n   * overlay.state.depthTest = false;\n   * ```\n   */\n  public state: State;\n\n  /** Whether `destroy()` has run */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only state\n  public destroyed = false;\n\n  /**\n   * Primitive topology for every pass that doesn't set its own; set by the\n   * {@link BaseMaterial3DOptions#topology | topology} option, and {@link PassDescriptor} lists what overrides it\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only state\n  public readonly topology?: Topology;\n\n  /**\n   * Every texture, in the order the shader numbers its samplers; `validateMaterialTextureSlots` checks it\n   * @internal\n   */\n  public _textures: Texture[] = [];\n\n  /**\n   * The `DrawCommandList.captureTick` that last captured these textures, so a build captures them once\n   * @internal\n   */\n  public _captureTick = -1;\n\n  /** @internal */\n  public _slotByName: Record<string, number> = Object.create(null);\n\n  private _bindGroup: BindGroup | null = null;\n\n  private _mergedBindGroup: BindGroup | null = null;\n\n  /**\n   * From `textureSetId`: equal on materials that bind the same sources in slot order\n   * @internal\n   */\n  public _textureSetId = 0;\n\n  private readonly _baseColorLinear = new Float32Array([1, 1, 1]);\n  private _baseColorTint = 0xffffff;\n  private _alpha = 1;\n  private _alphaCutoff: number = 0.5;\n  protected _alphaMode: AlphaMode = 'opaque';\n\n  /**\n   * The passes the material draws in, read live by meshes; joining one goes through\n   * `_markDescriptorDirty` so a joining mesh builds its pass cache that frame; leaving one only queues meshes\n   * @internal\n   */\n  public _passBit: number = RenderPassBit.OPAQUE;\n\n  /**\n   * The scene meshes drawing this material; batch slots aren't listed\n   * @internal\n   */\n  public readonly _meshes = new UnstableList<Mesh3D>('_materialMeshIndex');\n\n  /**\n   * First texel of the material's place in its store, `-1` while it has none\n   * @internal\n   */\n  public _materialIndex = -1;\n\n  /** @internal */\n  public _lastTextureDirtyId = -1;\n\n  /**\n   * The store's `BufferResource` over the material's place, `null` until the store makes one; `unload`\n   * keeps it, as it keeps the place\n   * @internal\n   */\n  public _uniformResource: BufferResource | null = null;\n\n  /**\n   * Each mesh compares it with its `_lastDescriptorDirtyId`; bump it only through `_markDescriptorDirty`\n   * @internal\n   */\n  public _descriptorDirtyId = 0;\n\n  /** Whether back faces are drawn too, lit with their normal flipped; set by the `doubleSided` option */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only state\n  public readonly doubleSided: boolean;\n\n  /**\n   * Set on a material whose colour already went through the view's curve, such as a portal's; it\n   * takes the display encode alone\n   * @internal\n   */\n  public _skipsToneCurve = false;\n\n  /**\n   * The colour space this material's shader works in; see {@link ColorSpace}\n   *\n   * `'display'` takes effect only on an unlit material, in a view with `toneMapping: 'none'` and no\n   * enabled `'beforeToneMapping'` effect, on a mesh no fog or vertex colours reach. Anywhere else\n   * the shader works in linear light. To change it after the material has rendered, see\n   * {@link BaseMaterial3D}.\n   *\n   * Bits on a `'display'` material should read colours through these helpers, which exist in both\n   * shader stages and return the colour in the shader's space:\n   *\n   * - `decodeColor(c: vec3)`: a display colour, such as a texture sample.\n   * - `inputTint(linearTint: vec4, displayTint: vec4)`: pass `material.baseColor` and\n   *   `material.displayBaseColor`, which the material fills once a bit declares them in\n   *   `bindings.material`.\n   * - `decodeFrame(c: vec3)`: a colour from a frame this view drew, such as a render-texture feed.\n   *\n   * Multiplying colours read this way gives the same bytes in both spaces. Adding, blending or\n   * scaling them by a number doesn't, so the result changes when fog moves the shader to linear\n   * light. On the display path, a {@link SceneOutput} bit that reads `albedo` sees display colours.\n   * @default 'linear'\n   * @example\n   * ```ts\n   * class MyStickerMaterial extends BaseMaterial3D {\n   *   public override colorSpace: ColorSpace = 'display';\n   *   public override lit = false;\n   * }\n   * ```\n   * @advanced\n   */\n  public colorSpace: ColorSpace = 'linear';\n\n  /**\n   * Whether the view's {@link View3D#fog | fog} may reach this material; set by the\n   * {@link BaseMaterial3DOptions#fog | fog} option\n   * @example\n   * ```ts\n   * const sky = new Material3D({ baseColorTexture: skyTexture, fog: false });\n   * ```\n   */\n  public readonly fog: boolean;\n\n  /**\n   * Whether triangles are shaded with their face normal; set by the\n   * {@link BaseMaterial3DOptions#flatShading | flatShading} option\n   * @example\n   * ```ts\n   * const rock = new Material3D({ baseColor: 0x8a7f72, flatShading: true });\n   * ```\n   */\n  public readonly flatShading: boolean;\n\n  /**\n   * Whether a geometry's vertex colours (its `colors`) tint this material\n   *\n   * Off by default, since exporters often fill the colour set with masks or weights; put data that\n   * isn't colour in {@link Geometry3DOptions#colors1 | colors1} when you can. The glTF loader turns\n   * it on, as glTF's `COLOR_0` is a base colour multiplier in linear light; convert colours picked\n   * in sRGB with {@link srgbToLinear}. To change it after the material has rendered, see\n   * {@link BaseMaterial3D}.\n   * @default false\n   * @example\n   * ```ts\n   * const painted = new Material3D();\n   * painted.vertexColors = true;\n   * ```\n   */\n  public vertexColors = false;\n\n  /**\n   * Whether the material's shader does lighting\n   *\n   * Set it to `false` for a shader that does none, as {@link FlatMaterial} does. That leaves out\n   * `calculateShadow`, so a shader that calls it fails to compile. To change it after the material\n   * has rendered, see {@link BaseMaterial3D}.\n   * @default true\n   * @example\n   * ```ts\n   * class MyUnlitMaterial extends BaseMaterial3D {\n   *   public override lit = false;\n   * }\n   * ```\n   */\n  public lit = true;\n\n  /**\n   * Name for debugging and for finding the material, such as the glTF material name the loader\n   * gives it; a {@link Model3DOptions#materials} record matches it\n   * @example\n   * ```ts\n   * const paint = source.materials.filter((material) => material.label === 'Paint');\n   * ```\n   */\n  public label?: string;\n\n  /** `undefined` when the bits have no `uvTransformBit` */\n  private _uvTransformRow0?: Float32Array;\n\n  private _uvOffset?: Float32Array;\n\n  private _uvTransformExplicit: boolean;\n\n  private _uvTransform?: Matrix;\n\n  private _initialUvTransform?: Matrix;\n\n  /**\n   * The construction bits' merged struct, which `validateMaterialStruct` holds every compiled shader\n   * to; `'{}'` when it has no fields\n   * @internal\n   */\n  public _materialStructSnapshot = '{}';\n\n  /**\n   * The values the material's shader reads, one property per field its bits declare; see\n   * {@link MaterialData} for how they read and write\n   * @example\n   * ```ts\n   * const toon = new ToonMaterial({ bands: 3 });\n   * toon.data.bands = 5;\n   * ```\n   */\n  public data!: TData;\n\n  /**\n   * The material's textures by slot name, the same names the `textures` option takes\n   *\n   * Assigning swaps the slot, and a name the material doesn't have throws. A swap reuses the\n   * compiled shader, except that a real map in the `normal` slot, or the default put back, switches\n   * normal mapping on or off.\n   *\n   * Wrap mode, filtering and anisotropy come from each texture's `source.style`, which clamps by\n   * default. To tile a texture, set `texture.source.style.addressMode = 'repeat'`, then call\n   * `style.update()`.\n   * @example\n   * ```ts\n   * material.textures.baseColor = crateTexture;\n   * ```\n   */\n  public textures!: TTextures;\n\n  /**\n   * The store the data uploads through, `null` until a mesh first draws the material and after `destroy`\n   * @internal\n   */\n  public _uploadQueue: MaterialUploadQueue | null = null;\n\n  /**\n   * Whether the material waits in its store's upload queue\n   * @internal\n   */\n  public _storeQueued = false;\n\n  /**\n   * Queues this material's data for upload\n   *\n   * Property setters and `data` field assignments call it for you. Call it yourself after writing\n   * into a `data` vector in place. Calls in one frame upload once.\n   * @example\n   * ```ts\n   * const scroll = material.data.scrollOffset;\n   * scroll[0] += 0.01;\n   * material.update();\n   * ```\n   */\n  public update(): void {\n    this._uploadQueue?.enqueueDirty(this);\n  }\n\n  /**\n   * Whether `getPrimaryDescriptor` must rebuild its bit list; the override that rebuilds clears it\n   * @internal\n   */\n  protected _variantDirty = true;\n\n  /**\n   * The `passes` overrides by pass bit, fixed at construction since each mesh resolves its entry only\n   * when it builds its draw data\n   * @internal\n   */\n  public _passes: Record<number, PassDescriptor> = {};\n\n  /**\n   * The shader bits this material was built with on top of its own, from the\n   * {@link BaseMaterial3DOptions#extraBits | extraBits} option\n   *\n   * Fixed for the material's lifetime. {@link BaseMaterial3D#clone} makes a copy with more.\n   * @example\n   * ```ts\n   * const dissolving = materials.filter((material) => material.extraBits.includes(dissolveBit));\n   * ```\n   * @advanced\n   */\n  public readonly extraBits: readonly ShaderBit[];\n\n  /** The `descriptor` option as given, without the extra bits, for `_toOptions` to pass again */\n  private readonly _descriptorOptions?: ShaderDescriptorOptions;\n\n  /** @internal */\n  protected _descriptor?: ShaderDescriptor;\n\n  constructor(options: BaseMaterial3DOptions = {}) {\n    if (options.baseColor !== undefined) this.baseColor = options.baseColor;\n    this._alpha = options.alpha ?? 1;\n    this._alphaCutoff = options.alphaCutoff ?? 0.5;\n\n    this.state = stateFor3D();\n\n    this.alphaMode = options.alphaMode ?? 'opaque';\n    this.doubleSided = options.doubleSided ?? false;\n    this.state.culling = !this.doubleSided;\n    this.flatShading = options.flatShading ?? false;\n    this.fog = options.fog ?? true;\n    this.label = options.label;\n    this.vertexColors = options.vertexColors ?? false;\n    this.extraBits = options.extraBits ?? [];\n\n    this._uvTransformExplicit = !!options.uvTransform;\n    this._initialUvTransform = options.uvTransform;\n\n    if (options.descriptor) {\n      const descriptor = (this._descriptorOptions = options.descriptor);\n      const extra = this.extraBits;\n\n      this._descriptor = new ShaderDescriptor(\n        extra.length === 0\n          ? descriptor\n          : {\n              ...descriptor,\n              bitsGpu: [...(descriptor.bitsGpu ?? []), ...extra],\n              bitsGl: [...(descriptor.bitsGl ?? []), ...extra],\n            },\n      );\n\n      this._deriveLayoutFromBits(this._descriptor.bitsGpu, {\n        baseColor: options.baseColorTexture,\n        ...options.textures,\n      });\n\n      const glNames = collectTextureNames(this._descriptor.bitsGl).join('|');\n      const gpuNames = collectTextureNames(this._descriptor.bitsGpu).join('|');\n      if (glNames !== gpuNames) {\n        throw new Error(\n          `[BaseMaterial3D] descriptor.bitsGl declares textures [${glNames}] but bitsGpu declares ` +\n            `[${gpuNames}]. Both backends bind from the same derived slots, so the sequences must match.`,\n        );\n      }\n    }\n\n    if (options.passes) {\n      for (const name in options.passes) {\n        const value = options.passes[name];\n        if (!value) continue;\n        const bit = passBitRegistry.getOrAllocate(name);\n        if (value !== true) {\n          this._passes[bit] = normalizePassEntry(value);\n        }\n        this._passBit |= bit;\n      }\n    }\n    this.topology = options.topology;\n\n    this.data ??= new (getOrCreateMaterialDataClass({}, '{}'))(this) as TData;\n  }\n\n  /**\n   * Texture `t` at `2t`, its style at `2t + 1`, then the row if the struct has fields (`materialBindingsBit`);\n   * the row is re-fetched each call and bound unwatched, since the store destroys the one it replaces\n   * @internal\n   */\n  public _getBindGroup(): BindGroup {\n    let group = this._bindGroup;\n    const textures = this._textures;\n\n    if (!group) {\n      group = this._bindGroup = new BindGroup();\n      this._refreshTextureBindingsOf(group);\n    }\n\n    if (this._materialStructSnapshot !== '{}') {\n      const queue = this._uploadQueue;\n      if (!queue) {\n        throw new Error(\n          '[BaseMaterial3D] _getBindGroup on a material no store has registered; a mesh drawing it registers it first',\n        );\n      }\n      const binding = textures.length * 2;\n      const resource = queue.uniformResource(this);\n      if (group.getResource(binding) !== resource) group.setResourceUnwatched(resource, binding);\n    }\n\n    return group;\n  }\n\n  /**\n   * The textures of `_getBindGroup` with no row; a merged run binds its first material's group for\n   * every material in it\n   * @internal\n   */\n  public _getMergedBindGroup(): BindGroup {\n    let group = this._mergedBindGroup;\n\n    if (!group) {\n      group = this._mergedBindGroup = new BindGroup();\n      this._refreshTextureBindingsOf(group);\n    }\n\n    return group;\n  }\n\n  /**\n   * Lays out `data` and `textures` from `bits`; a subclass that builds its own bits calls it once,\n   * from its constructor\n   *\n   * `bits` must declare every material field and texture that\n   * {@link BaseMaterial3D#getPrimaryDescriptor} can compile, such as the fields of\n   * {@link uvTransformBit}, with the textures in the same order, or the shader is rejected when it's\n   * built. `data` and `textures` are cast to `TData` and `TTextures` unchecked, so the type\n   * arguments must match what the bits declare. A raw `descriptor` is laid out for you.\n   * @param bits - The bits that declare the material's fields and textures\n   * @param textures - Slot contents by texture name; the rest get `Texture.WHITE`\n   * @throws If two bits declare the same texture name.\n   */\n  protected _deriveLayoutFromBits(\n    bits: readonly ShaderBit[],\n    textures: Record<string, Texture | undefined> = {},\n  ): void {\n    const _textures = this._textures;\n    _textures.length = 0;\n\n    this._slotByName = Object.create(null);\n\n    const structDef = mergeMaterialStruct(bits);\n    this._materialStructSnapshot = materialStructSnapshot(structDef);\n    this.data = new (getOrCreateMaterialDataClass(structDef, this._materialStructSnapshot))(this) as TData;\n\n    const baseColor = this.data.baseColor;\n    if (baseColor) {\n      baseColor.set(this._baseColorLinear);\n      baseColor[3] = this._alpha;\n    }\n    const displayBaseColor = this.data.displayBaseColor;\n    if (displayBaseColor) {\n      for (let i = 0; i < 3; i++) displayBaseColor[i] = linearToSrgb(this._baseColorLinear[i]);\n      displayBaseColor[3] = this._alpha;\n    }\n    if (typeof this.data.alphaCutoff === 'number') this.data.alphaCutoff = this._alphaCutoff;\n    if (this.data.uvTransformRow0 !== undefined) {\n      this._uvTransformRow0 = this.data.uvTransformRow0;\n      this._uvOffset = this.data.uvOffset;\n      this._uvTransformRow0.set(IDENTITY_UV_ROW0);\n      if (this._initialUvTransform) {\n        this.uvTransform = this._initialUvTransform;\n        this._initialUvTransform = undefined;\n      }\n    }\n\n    const slotNames: string[] = [];\n    for (const bit of bits) {\n      if (!bit.textures) continue;\n      for (const name of bit.textures) {\n        if (this._slotByName[name] !== undefined) {\n          throw new Error(\n            `[BaseMaterial3D] Duplicate texture '${name}' — bit \"${bit.name}\" redeclares a name another ` +\n              `bit in this material already claimed.`,\n          );\n        }\n        this._slotByName[name] = _textures.length;\n        _textures.push(textures[name] ?? Texture.WHITE);\n        slotNames.push(name);\n      }\n    }\n\n    this.textures = new (getOrCreateMaterialTexturesClass(slotNames))(this) as TTextures;\n    this._textureSetId = textureSetId(_textures);\n\n    this._deriveUvFrame();\n  }\n\n  /**\n   * Re-keys only when the source changes, since bind groups and sort keys follow the source, so an\n   * atlas frame flip costs at most a UV data write\n   * @internal\n   */\n  public _setTextureSlot(index: number, value: Texture): void {\n    const prev = this._textures[index];\n    if (prev === value) return;\n    this._textures[index] = value;\n\n    if (prev?.source !== value.source) {\n      this._textureSetId = textureSetId(this._textures);\n      this._releaseBindGroup();\n      this._markDescriptorDirty();\n    }\n\n    if (index === this._slotByName.baseColor) {\n      this._deriveUvFrame();\n    } else if (this._uvTransformRow0 && !isFullFrame(value) && !this._frameMatchesTransform(value)) {\n      warnOnce(\n        'pixijs-3d-uv-frame-secondary',\n        '[@pixi/3d] A framed texture landed in a non-baseColor slot but the material UV transform ' +\n          \"(derived from the baseColor slot, or set explicitly) doesn't match its frame. The shared \" +\n          'transform cannot serve per-slot frames — pack secondary maps to match the baseColor frame.',\n      );\n    }\n  }\n\n  /**\n   * Returns the shader descriptor for the material's main pass\n   *\n   * The base returns the `descriptor` the material was built with. Override it when the bits depend\n   * on the material's settings or on the view, and call `_invalidateDescriptor` when a setting\n   * changes the answer. Bits that declare material fields or textures must also go through\n   * `_deriveLayoutFromBits` in the constructor.\n   * @param _view - The view about to render this material.\n   * @example\n   * ```ts\n   * class MyWaterMaterial extends BaseMaterial3D {\n   *   private readonly _plain = new ShaderDescriptor({ bitsGpu: [waterBit], bitsGl: [waterBit] });\n   *   private readonly _reflective = new ShaderDescriptor({\n   *     bitsGpu: [waterBit, skyReflectionBit],\n   *     bitsGl: [waterBit, skyReflectionBit],\n   *   });\n   *\n   *   constructor() {\n   *     super();\n   *     this._deriveLayoutFromBits([waterBit]);\n   *   }\n   *\n   *   public override getPrimaryDescriptor(view: View3D): ShaderDescriptor {\n   *     return view.environment ? this._reflective : this._plain;\n   *   }\n   * }\n   * ```\n   * @advanced\n   */\n  public getPrimaryDescriptor(_view: View3D): ShaderDescriptor {\n    return this._descriptor!;\n  }\n\n  /**\n   * Adds this material to a custom render pass, such as an {@link OutlinePass}, as naming it `true`\n   * in the `passes` option does\n   *\n   * Meshes using the material draw in the pass from the next render, except one that left it\n   * through {@link Mesh3D#disablePass}. {@link BatchedMesh3D} slots take their passes from\n   * {@link BatchedMesh3D#setPassesAt} instead. Overrides for the pass can only be given at\n   * construction, and the {@link BaseMaterial3DOptions#passes | passes} option has the limit on\n   * custom pass names.\n   * @param name - The pass's `name`, such as `'outline'`.\n   * @example\n   * ```ts\n   * view.passes = [new OutlinePass()];\n   * material.enablePass('outline');\n   * ```\n   */\n  public enablePass(name: string): void {\n    const prev = this._passBit;\n\n    this._passBit |= passBitRegistry.getOrAllocate(name);\n    if (this._passBit !== prev) this._markDescriptorDirty();\n  }\n\n  /**\n   * Removes this material from a custom render pass\n   *\n   * Meshes using the material leave the pass on the next render, except one that joined it through\n   * {@link Mesh3D#enablePass}. An override given for the pass in the `passes` option is kept, so\n   * {@link BaseMaterial3D#enablePass} brings it back.\n   * @param name - The pass's `name`, such as `'outline'`.\n   * @example\n   * ```ts\n   * material.disablePass('outline');\n   * ```\n   */\n  public disablePass(name: string): void {\n    const bit = passBitRegistry.get(name);\n    if (bit === undefined || (this._passBit & bit) === 0) return;\n    this._passBit &= ~bit;\n    const meshes = this._meshes.items;\n    for (let i = 0; i < meshes.length; i++) meshes[i]._queueMeshUpdate();\n  }\n\n  private _markDescriptorDirty(): void {\n    this._descriptorDirtyId++;\n    const meshes = this._meshes.items;\n    for (let i = 0; i < meshes.length; i++) meshes[i]._markBatchDirty();\n  }\n\n  /**\n   * Makes every mesh using the material rebuild its shader; call it from a subclass setter that\n   * changes what {@link BaseMaterial3D#getPrimaryDescriptor} returns\n   */\n  protected _invalidateDescriptor(): void {\n    this._variantDirty = true;\n    this._markDescriptorDirty();\n  }\n\n  /**\n   * How the material treats alpha; see {@link AlphaMode}\n   *\n   * Setting it also sets the blending and depth writes of `state`. `'blend'` turns depth writes\n   * off, and its meshes cast no shadow. On a material built from a raw `descriptor`, `'mask'`\n   * discards only if the descriptor's bits include {@link alphaMaskBit}.\n   * @example\n   * ```ts\n   * material.alphaMode = 'blend';\n   * material.alpha = 0.5;\n   * ```\n   */\n  get alphaMode(): AlphaMode {\n    return this._alphaMode;\n  }\n\n  /**\n   * Sets the alpha mode\n   * @param value - How alpha is treated\n   */\n  set alphaMode(value: AlphaMode) {\n    if (this._alphaMode === value) return;\n    this._alphaMode = value;\n    const isBlend = value === 'blend';\n    this.state.blend = isBlend;\n    this.state.depthMask = !isBlend;\n\n    const coreMask = RenderPassBit.OPAQUE | RenderPassBit.TRANSPARENT;\n    this._passBit = (this._passBit & ~coreMask) | (isBlend ? RenderPassBit.TRANSPARENT : RenderPassBit.OPAQUE);\n    this.update();\n    this._invalidateDescriptor();\n  }\n\n  /**\n   * Base colour tint, read back as a hex number\n   *\n   * Takes any `ColorSource` in display (sRGB) space, like `Container.tint`. The source's alpha is\n   * ignored; {@link BaseMaterial3D#alpha} is the opacity.\n   * @example\n   * ```ts\n   * material.baseColor = 'tomato';\n   * material.baseColor; // 0xff6347\n   * ```\n   */\n  public get baseColor(): number {\n    return this._baseColorTint;\n  }\n\n  /**\n   * Sets the base colour tint\n   * @param value - Display colour; its alpha is ignored\n   */\n  public set baseColor(value: ColorSource) {\n    const colour = Color.shared.setValue(value);\n    this._baseColorTint = colour.toNumber();\n    writeLinearRgb(this._baseColorLinear, 0, colour);\n    const packed = this.data?.baseColor;\n    if (packed) {\n      packed.set(this._baseColorLinear);\n      const displayBaseColor = this.data.displayBaseColor;\n      if (displayBaseColor) colour.toRgbArray(displayBaseColor);\n      this.update();\n    }\n  }\n\n  /**\n   * Base opacity, from 0 to 1; `alphaMode: 'opaque'` ignores it\n   * @default 1\n   * @example\n   * ```ts\n   * material.alphaMode = 'blend';\n   * material.alpha = 0.5;\n   * ```\n   */\n  public get alpha(): number {\n    return this._alpha;\n  }\n\n  /**\n   * Sets the base opacity\n   * @param value - From 0 (transparent) to 1 (opaque)\n   */\n  public set alpha(value: number) {\n    if (this._alpha === value) return;\n    this._alpha = value;\n    const packed = this.data?.baseColor;\n    if (packed) {\n      packed[3] = value;\n      const display = this.data.displayBaseColor;\n      if (display) display[3] = value;\n      this.update();\n    }\n  }\n\n  /**\n   * Alpha below which fragments are discarded while {@link BaseMaterial3D#alphaMode} is `'mask'`\n   * @default 0.5\n   * @example\n   * ```ts\n   * material.alphaMode = 'mask';\n   * material.alphaCutoff = 0.3;\n   * ```\n   */\n  public get alphaCutoff(): number {\n    return this._alphaCutoff;\n  }\n\n  /**\n   * Sets the alpha cutoff\n   * @param value - Alpha below which fragments are discarded\n   */\n  public set alphaCutoff(value: number) {\n    if (this._alphaCutoff === value) return;\n    this._alphaCutoff = value;\n    if (typeof this.data?.alphaCutoff === 'number') this.data.alphaCutoff = value;\n  }\n\n  /**\n   * The UV transform you set, or `undefined` while the base colour texture's frame sets it\n   *\n   * One transform, as glTF's `KHR_texture_transform` defines it, applies to every texture of the\n   * material. Setting a matrix takes over from a framed (spritesheet) base colour texture, and a\n   * framed texture assigned while it's set warns that its frame is ignored; setting `undefined`\n   * hands it back. Either is a data write, never a shader rebuild. On a material whose bits lack\n   * {@link uvTransformBit}, setting a matrix warns and does nothing.\n   *\n   * A UV `(u, v)` becomes `(a * u + b * v + tx, c * u + d * v + ty)`, transposed from pixi's\n   * `Matrix.apply`, so `new Matrix().rotate(rotation).scale(sx, sy).translate(x, y)` gives the\n   * `KHR_texture_transform` result for those values. The getter returns the material's own matrix;\n   * changing it in place does nothing until you assign it again.\n   * @example\n   * ```ts\n   * material.uvTransform = new Matrix().scale(4, 4);\n   * material.uvTransform = undefined;\n   * ```\n   */\n  public get uvTransform(): Matrix | undefined {\n    return this._uvTransform;\n  }\n\n  /**\n   * Sets the UV transform\n   * @param m - The transform, or `undefined` to follow the base colour texture's frame\n   */\n  public set uvTransform(m: Matrix | undefined) {\n    if (!this._uvTransformRow0) {\n      if (m) {\n        warn(\n          \"BaseMaterial3D: uvTransform is inert — this material's descriptor bits declare no \" +\n            'uvTransform fields (include uvTransformBit to enable it).',\n        );\n      }\n      return;\n    }\n\n    if (!m) {\n      this._uvTransformExplicit = false;\n      this._uvTransform = undefined;\n      this._uvTransformRow0.set(IDENTITY_UV_ROW0);\n      this._uvOffset!.fill(0);\n      this.update();\n      this._deriveUvFrame();\n      return;\n    }\n\n    this._uvTransformExplicit = true;\n    this._uvTransform ??= new Matrix();\n\n    this._uvTransform.copyFrom(m);\n    this._uvTransformRow0[0] = m.a;\n    this._uvTransformRow0[1] = m.b;\n    this._uvTransformRow0[2] = m.c;\n    this._uvTransformRow0[3] = m.d;\n    this._uvOffset![0] = m.tx;\n    this._uvOffset![1] = m.ty;\n\n    this.update();\n  }\n\n  /**\n   * Call after changing the base colour texture's frame in place; rounds to float32 so an unchanged\n   * frame queues no upload\n   * @internal\n   */\n  public _deriveUvFrame(): void {\n    const row0 = this._uvTransformRow0;\n    const offset = this._uvOffset;\n    if (!row0 || !offset) return;\n\n    const slot = this._slotByName.baseColor;\n    const texture = slot === undefined ? undefined : this._textures[slot];\n    const framed = texture !== undefined && !isFullFrame(texture);\n\n    if (this._uvTransformExplicit) {\n      if (framed) {\n        warnOnce(\n          'pixijs-3d-uv-frame-explicit',\n          '[@pixi/3d] A framed baseColor texture was assigned but the material has an explicit ' +\n            'uvTransform, which wins — the frame is not applied. Clear material.uvTransform to ' +\n            'derive from the texture frame.',\n        );\n      }\n      return;\n    }\n\n    let a = 1;\n    let b = 0;\n    let c = 0;\n    let d = 1;\n    let tx = 0;\n    let ty = 0;\n\n    if (framed) {\n      if (texture.trim) {\n        warnOnce(\n          'pixijs-3d-uv-frame-trimmed',\n          '[@pixi/3d] The baseColor texture is trimmed. Trims describe where a sprite quad shrank ' +\n            'and cannot map onto arbitrary mesh UVs — the trim is ignored; only the frame applies. ' +\n            'Pack 3D textures without trimming.',\n        );\n      }\n      const uvs = texture.uvs;\n      a = Math.fround(uvs.x1 - uvs.x0);\n      b = Math.fround(uvs.x3 - uvs.x0);\n      c = Math.fround(uvs.y1 - uvs.y0);\n      d = Math.fround(uvs.y3 - uvs.y0);\n      tx = Math.fround(uvs.x0);\n      ty = Math.fround(uvs.y0);\n    }\n\n    if (row0[0] === a && row0[1] === b && row0[2] === c && row0[3] === d && offset[0] === tx && offset[1] === ty) {\n      return;\n    }\n\n    row0[0] = a;\n    row0[1] = b;\n    row0[2] = c;\n    row0[3] = d;\n    offset[0] = tx;\n    offset[1] = ty;\n    this.update();\n  }\n\n  private _frameMatchesTransform(texture: Texture): boolean {\n    const row0 = this._uvTransformRow0!;\n    const offset = this._uvOffset!;\n    const uvs = texture.uvs;\n    return (\n      row0[0] === Math.fround(uvs.x1 - uvs.x0) &&\n      row0[1] === Math.fround(uvs.x3 - uvs.x0) &&\n      row0[2] === Math.fround(uvs.y1 - uvs.y0) &&\n      row0[3] === Math.fround(uvs.y3 - uvs.y0) &&\n      offset[0] === Math.fround(uvs.x0) &&\n      offset[1] === Math.fround(uvs.y0)\n    );\n  }\n\n  /**\n   * Makes a material of the same class that draws as this one does now, with the options you pass\n   * changed\n   *\n   * `options` are the class's constructor options. `clone` reads this material's current values\n   * back as those options, merges yours over them, and passes the result to the class's\n   * constructor. An option left out, or set to `undefined`, keeps this material's value. One that\n   * takes an object, such as a feature group or `passes`, is merged one level deep:\n   * `emissive: { strength: 2 }` on a {@link Material3D} keeps its emissive colour. `descriptor` is\n   * replaced whole. A group the material doesn't have, such as `clearcoat`, adds the feature.\n   *\n   * `extraBits` adds to this material's {@link BaseMaterial3D#extraBits}, skipping a bit it already\n   * has. Fields a new bit declares start at 0 and its texture slots hold `Texture.WHITE`, so set\n   * them on the copy. The fields of the extra bits it already had keep their values.\n   *\n   * A raw-`descriptor` material, or any class that inherits `BaseMaterial3D`'s `_toOptions`\n   * unchanged, keeps every field value and texture it has, except those an option you pass sets.\n   *\n   * What isn't an option comes across too: `colorSpace`, `lit`, the passes joined with\n   * {@link BaseMaterial3D#enablePass}, and `state` with any change made through it, except the\n   * flags an option you pass sets, such as `alphaMode`'s blending. Colour options read back as\n   * 8-bit hex, as their getters return them.\n   *\n   * Textures are shared, not copied. Everything else belongs to the copy: assign it to meshes and\n   * `destroy()` it when you're done, which leaves the shared textures alive. Materials with the same\n   * bits share compiled shaders, so a copy compiles nothing new unless its bits are new.\n   * @param options - Constructor options to change on the copy; left out, it's a plain copy.\n   * @returns The copy, of the same class.\n   * @example\n   * ```ts\n   * const dissolving = mesh.material.clone({ extraBits: [dissolveBit] });\n   * dissolving.data.dissolve = 0.5;\n   * mesh.material = dissolving;\n   *\n   * const ghost = mesh.material.clone({ alphaMode: 'blend', alpha: 0.4 });\n   * ```\n   */\n  public clone(options?: TOptions): this {\n    const merged = this._toOptions() as Record<string, unknown>;\n    const overrides: BaseMaterial3DOptions = definedProps(options ?? {});\n\n    for (const [key, value] of Object.entries(overrides)) {\n      const current = merged[key];\n      merged[key] =\n        key !== 'descriptor' && isPlainObject(value) && isPlainObject(current)\n          ? { ...current, ...definedProps(value) }\n          : value;\n    }\n\n    const extraBits = this.extraBits;\n    const added = overrides.extraBits?.filter((bit) => !extraBits.some((own) => own.name === bit.name)) ?? [];\n    merged.extraBits = [...extraBits, ...added];\n\n    const copy = new (this.constructor as new (options: object) => this)(merged);\n    const data = copy.data as MaterialData;\n\n    if (this._toOptions === BaseMaterial3D.prototype._toOptions) {\n      for (const name of Object.keys(Object.getPrototypeOf(this.data))) {\n        if (!BASE_OWNED_FIELDS.has(name) && name in data) data[name] = this.data[name];\n      }\n\n      const textures = overrides.textures ?? {};\n      for (const name in this._slotByName) {\n        const index = copy._slotByName[name];\n        const named = name === 'baseColor' ? (overrides.baseColorTexture ?? textures.baseColor) : textures[name];\n        if (index !== undefined && named === undefined) {\n          copy._setTextureSlot(index, this._textures[this._slotByName[name]]);\n        }\n      }\n    } else {\n      for (const bit of extraBits) {\n        for (const name in bit.bindings?.material) data[name] = this.data[name];\n      }\n    }\n\n    const state = copy.state;\n    const { blend, depthMask, culling, blendMode } = state;\n\n    copyState(state, this.state);\n\n    if ('alphaMode' in overrides) {\n      state.blend = blend;\n      state.depthMask = depthMask;\n    }\n    if ('doubleSided' in overrides) state.culling = culling;\n    if ('blendMode' in overrides) state.blendMode = blendMode;\n\n    copy.colorSpace = this.colorSpace;\n    copy.lit = this.lit;\n\n    return copy;\n  }\n\n  /**\n   * This material's current values as its constructor's options, for {@link BaseMaterial3D#clone}\n   *\n   * The base reads back its own options, the texture slots of its `extraBits` as `textures`, and\n   * the custom passes it's in as `passes`. While a class keeps this method, `clone` copies every\n   * other field and texture slot onto the copy after building it. A subclass with options of its\n   * own overrides this and adds them to `super`'s. `clone` then copies only the `extraBits` fields,\n   * so the override has to read back every value and texture its constructor sets.\n   * @returns Options that build a material like this one.\n   * @advanced\n   */\n  protected _toOptions(): TOptions {\n    const passes: NonNullable<BaseMaterial3DOptions['passes']> = {};\n    for (let custom = this._passBit & ~RenderPassBit.MATERIAL_PASS_MASK; custom; custom &= custom - 1) {\n      const bit = custom & -custom;\n      const name = passBitRegistry.nameOf(bit);\n      if (name) passes[name] = this._passes[bit] ?? true;\n    }\n\n    const textures: Record<string, Texture> = {};\n    for (const name of collectTextureNames(this.extraBits)) textures[name] = this._textures[this._slotByName[name]];\n\n    const options: BaseMaterial3DOptions = {\n      label: this.label,\n      descriptor: this._descriptorOptions,\n      baseColor: this.baseColor,\n      alpha: this.alpha,\n      baseColorTexture: this._textures[this._slotByName.baseColor],\n      textures,\n      alphaMode: this.alphaMode,\n      alphaCutoff: this.alphaCutoff,\n      doubleSided: this.doubleSided,\n      flatShading: this.flatShading,\n      fog: this.fog,\n      vertexColors: this.vertexColors,\n      topology: this.topology,\n      passes,\n      uvTransform: this._uvTransformExplicit ? this.uvTransform : undefined,\n    };\n\n    return options as TOptions;\n  }\n\n  /**\n   * Frees the GPU memory of this material's textures until a frame draws them again\n   *\n   * The next frame that draws the material re-uploads them from their CPU copies, so it keeps\n   * drawing the same. Texture sources are shared, so every other material using one re-uploads it\n   * too, as with `texture.source.unload()`. The engine's default textures are skipped, and so are\n   * render textures and {@link ContainerTexture}s, whose pixels exist only on the GPU.\n   *\n   * Call {@link BatchedMesh3D#invalidate} for each batch slot that draws the material. Does nothing\n   * once the material is destroyed.\n   * @example\n   * ```ts\n   * view.root.removeChild(model);\n   * material.unload(); // hand the texture memory back until the model is shown again\n   * ```\n   * @see {@link Model3D.unload} For giving back a whole model's geometry and textures at once.\n   */\n  public unload(): void {\n    if (this.destroyed) return;\n\n    this._releaseBindGroup();\n    this._markDescriptorDirty();\n\n    const seenSources = new Set<TextureSource>();\n    for (const texture of this._textures) {\n      if (!texture || SHARED_DEFAULT_TEXTURES.has(texture)) continue;\n      const source = texture.source;\n      if (!source || seenSources.has(source)) continue;\n      seenSources.add(source);\n      if (source.uploadMethodId === GPU_ONLY_UPLOAD_METHOD) continue;\n      source.unload();\n    }\n  }\n\n  /**\n   * Frees the material for good; a second call does nothing\n   *\n   * Its textures stay alive unless `options` asks for them. The engine's default textures are never\n   * destroyed, and compiled shaders stay cached in the renderer.\n   * @param options - `{ texture: true }` destroys the material's textures; add `textureSource: true`,\n   * or pass `true`, to destroy their sources too\n   * @example\n   * ```ts\n   * mesh.material = new Material3D({ baseColor: 0x3366ff });\n   * oldMaterial.destroy({ texture: true });\n   * ```\n   */\n  public destroy(options?: TypeOrBool<TextureDestroyOptions>): void {\n    if (this.destroyed) return;\n    this.destroyed = true;\n\n    this._releaseBindGroup();\n\n    if (resolveDestroy3DFlag(options, 'texture')) {\n      const destroySource = resolveDestroy3DFlag(options, 'textureSource');\n      const seenSources = destroySource ? new Set<TextureSource>() : undefined;\n      for (const texture of this._textures) {\n        if (!texture || SHARED_DEFAULT_TEXTURES.has(texture)) continue;\n        if (seenSources) {\n          const source = texture.source;\n          texture.destroy(false);\n          if (source && !seenSources.has(source)) {\n            seenSources.add(source);\n            source.destroy();\n          }\n        } else {\n          texture.destroy(false);\n        }\n      }\n    }\n\n    this._uploadQueue?.remove(this);\n    this._uploadQueue = null;\n    this._storeQueued = false;\n    // oxlint-disable-next-line pixijs-3d/destroy-release -- a mesh still using the destroyed material removes itself from this list when it detaches or swaps material, and clear() resets its index so that remove is a no-op\n    this._meshes.clear();\n    this._uniformResource?.destroy(false);\n    this._uniformResource = null;\n\n    (this.data as TData | null) = null;\n    (this.textures as TTextures | null) = null;\n    (this._textures as Texture[] | null) = null;\n    (this._slotByName as Record<string, number> | null) = null;\n    this._descriptor = undefined;\n    (this._passes as Record<number, PassDescriptor> | null) = null;\n    this._uvTransformRow0 = undefined;\n    this._uvOffset = undefined;\n    (this._descriptorOptions as ShaderDescriptorOptions | null) = null;\n  }\n\n  /**\n   * The bind groups hold their resources unwatched, since a listener per material on a shared texture\n   * makes teardown N²; `DrawCommandList.refreshMaterialBindings` calls this once a texture changes\n   * @internal\n   */\n  public _refreshTextureBindings(): void {\n    if (this._bindGroup) this._refreshTextureBindingsOf(this._bindGroup);\n    if (this._mergedBindGroup) this._refreshTextureBindingsOf(this._mergedBindGroup);\n  }\n\n  /**\n   * Binds a destroyed source too, so the draw fails loudly rather than sampling the slot's previous\n   * source; such a source has no style, so the previous style binding stays\n   */\n  private _refreshTextureBindingsOf(group: BindGroup): void {\n    const textures = this._textures;\n    for (let t = 0; t < textures.length; t++) {\n      const source = textures[t].source;\n      group.setResourceUnwatched(source, t * 2);\n      if (source.style) group.setResourceUnwatched(source.style, t * 2 + 1);\n    }\n    refreshBindGroup(group);\n  }\n\n  /** Drops the groups without destroying them, since a draw command built earlier may still bind one */\n  private _releaseBindGroup(): void {\n    this._bindGroup = null;\n    this._mergedBindGroup = null;\n  }\n}\n","import type { MorphStoreBuffer } from '../core/buffers/MorphStoreBuffer';\n\n/**\n * A mesh's morph weights and its slot in the shared morph store; `Mesh3D._morph` holds one only\n * while the geometry has morph targets\n * @internal\n */\nexport class Morph {\n  public weights: Float32Array;\n\n  /**\n   * Absolute float offset of the weights in the morph store, which the mesh's store row carries\n   * @internal\n   */\n  public _weightIndex = 0;\n  /**\n   * Weight slot relative to the store's weights base; `-1` when unallocated\n   * @internal\n   */\n  public _slot = -1;\n  /**\n   * Bucket size the slot was allocated with, which freeing it must match\n   * @internal\n   */\n  public _slotSize = 0;\n  /**\n   * The store that holds the slot, so the mesh can free it without the renderer; `null` when unallocated\n   * @internal\n   */\n  public _store: MorphStoreBuffer | null = null;\n\n  constructor(weights: Float32Array) {\n    this.weights = weights;\n  }\n}\n","import { definedProps } from 'pixi.js';\n\nimport type { Mesh3DData, MeshPassCache } from '../core/batcher/Mesh3DData';\nimport { passBitRegistry } from '../core/render-passes/passBitRegistry';\nimport { RenderPassBit } from '../core/render-passes/RenderPass';\nimport type { HitVolume3D } from '../events/HitResult3D';\nimport { resolveHitVolume } from '../events/resolveHitVolume';\nimport { Geometry3D } from '../geometry/Geometry3D';\nimport { BaseMaterial3D } from '../materials/BaseMaterial3D';\nimport { Sphere } from '../math/shapes/Sphere';\nimport type { Destroy3DOptions } from '../utils/Destroy3DOptions';\nimport { resolveDestroy3DFlag } from '../utils/Destroy3DOptions';\nimport type { Container3DOptions } from './Container3D';\nimport { Container3D } from './Container3D';\nimport { Morph } from './Morph';\nimport type { Skeleton } from './Skeleton';\n\nconst _morphExpandedSphere = new Sphere();\n\n/**\n * How a mesh turns to face the camera; see {@link Mesh3D#billboardMode}\n *\n * - `'none'`: no turning; the mesh draws as authored.\n * - `'spherical'`: lies square to the screen however the camera turns. Suits glows, impact\n *   flashes, icons and distance markers.\n * - `'cylindrical'`: turns around its own up axis toward the camera but never tips, so it stays\n *   planted. Suits trees, grass, crowd cutouts and flat stand-ins for distant models.\n * @example\n * ```ts\n * const mode: BillboardMode = upright ? 'cylindrical' : 'spherical';\n * const marker = new Sprite3D({ texture, billboardMode: mode });\n * ```\n * @category scene\n * @standard\n */\nexport type BillboardMode = 'none' | 'spherical' | 'cylindrical';\n\n/**\n * Constructor options for {@link Mesh3D}\n *\n * `geometry` and `material` can be left out: a mesh built without them draws nothing until both\n * are assigned. The {@link Container3DOptions} apply too, and `label` defaults to `'Mesh3D'`.\n * @example\n * ```ts\n * const mesh = new Mesh3D({\n *   geometry,\n *   material,\n *   castShadow: true,\n *   receiveShadow: true,\n *   position: { x: 0, y: 1, z: 0 },\n *   parent: view.root,\n * });\n * ```\n * @category scene\n * @standard\n */\nexport interface Mesh3DOptions extends Container3DOptions {\n  /**\n   * The geometry to draw\n   *\n   * Left out, the mesh holds {@link Geometry3D.EMPTY} and draws nothing until you assign\n   * {@link Mesh3D#geometry}.\n   * @example\n   * ```ts\n   * const ball = new Mesh3D({ geometry: new SphereGeometry(), material });\n   * ```\n   */\n  geometry?: Geometry3D;\n  /**\n   * The material to draw the geometry with\n   *\n   * Left out, the mesh holds {@link BaseMaterial3D.EMPTY} and draws nothing until you assign\n   * {@link Mesh3D#material}.\n   * @example\n   * ```ts\n   * const ball = new Mesh3D({ geometry, material: new Material3D({ baseColor: 0xff8844 }) });\n   * ```\n   */\n  material?: BaseMaterial3D;\n  /**\n   * Skeleton that deforms the mesh; leave it out for a mesh that doesn't bend\n   *\n   * The geometry needs `joints` and `weights` for it to act on.\n   * @example\n   * ```ts\n   * const tailMesh = new Mesh3D({ geometry: tailGeometry, material, skeleton: tail });\n   * ```\n   */\n  skeleton?: Skeleton;\n  /**\n   * Whether the mesh casts shadows; see {@link Mesh3D#castShadow}\n   * @default true\n   * @example\n   * ```ts\n   * const decal = new Mesh3D({ geometry, material, castShadow: false });\n   * ```\n   */\n  castShadow?: boolean;\n  /**\n   * Whether the mesh is shadowed; see {@link Mesh3D#receiveShadow}\n   * @default true\n   * @example\n   * ```ts\n   * const water = new Mesh3D({ geometry, material, receiveShadow: false });\n   * ```\n   */\n  receiveShadow?: boolean;\n  /**\n   * Starting morph target weights, one per target in the geometry; left out, they're all 0\n   *\n   * Ignored when the geometry has no morph targets, or isn't given yet: weights exist only once\n   * the mesh has a morph geometry, so set {@link Mesh3D#weights} after assigning one.\n   * @example\n   * ```ts\n   * const face = new Mesh3D({ geometry: faceGeometry, material, weights: new Float32Array([0, 1]) });\n   * ```\n   */\n  weights?: Float32Array;\n  /**\n   * How the mesh turns to face the camera; see {@link Mesh3D#billboardMode}\n   * @default 'none'\n   * @example\n   * ```ts\n   * const card = new Mesh3D({ geometry: new PlaneGeometry(), material, billboardMode: 'cylindrical' });\n   * ```\n   */\n  billboardMode?: BillboardMode;\n}\n\n/**\n * A drawable node: a {@link Geometry3D} drawn with a {@link BaseMaterial3D}\n *\n * Add it anywhere under {@link View3D.root | view.root} and the view draws it in the passes its\n * material and settings call for: opaque, transparent, shadow and so on. A mesh with a\n * {@link Skeleton} bends with its bones, and one whose geometry has morph targets blends them by\n * its {@link Mesh3D#weights | weights}. For thousands of copies, {@link BatchedMesh3D} draws them\n * without a node each.\n *\n * The geometry and material can come later: until it has both, a mesh draws nothing. Assigning\n * them, before or after the mesh joins a view, gives the same mesh as passing them to the\n * constructor, and a {@link Mesh3D#castShadow}, {@link Mesh3D#enablePass} or\n * {@link Mesh3D#disablePass} change made while it waits applies once it has both.\n * @example\n * ```ts\n * import { Mesh3D, Material3D } from '@pixi/3d';\n *\n * const mesh = new Mesh3D({ geometry, material: new Material3D({ baseColor: 0xff8844 }) });\n * mesh.position.set(0, 1, 0);\n * view.root.addChild(mesh);\n *\n * // Skinned mesh:\n * const skinned = new Mesh3D({ geometry: skinnedGeometry, material, skeleton });\n *\n * // Geometry and material assigned later:\n * const later = new Mesh3D({ parent: view.root });\n * later.geometry = geometry;\n * later.material = material;\n *\n * // Toggle shadow casting at runtime:\n * mesh.castShadow = false;\n * ```\n * @see {@link Mesh3DOptions} For the constructor options.\n * @category scene\n * @standard\n */\nexport class Mesh3D extends Container3D implements Mesh3DData {\n  /**\n   * Defaults for every new `Mesh3D`; an option passed as `undefined` keeps its default\n   * @example\n   * ```ts\n   * Mesh3D.defaultOptions.castShadow = false;\n   * const mesh = new Mesh3D({ geometry, material }); // picks up the override above\n   * ```\n   */\n  public static defaultOptions: Partial<Mesh3DOptions> = {\n    castShadow: true,\n    receiveShadow: true,\n    billboardMode: 'none',\n  };\n\n  private _geometry: Geometry3D;\n  private _material: BaseMaterial3D;\n  /** `0` while the geometry or material is a placeholder, else `~0`; cached to skip the `EMPTY` getters per frame */\n  private _placeholderMask = 0;\n  private _billboardMode: BillboardMode;\n\n  private _worldBoundsSphere: Sphere | null = null;\n  private _worldBoundsCacheId = -1;\n\n  /**\n   * Skeleton that deforms this mesh; `undefined` for a mesh that doesn't bend\n   *\n   * Fixed at construction: to change it, build a new mesh.\n   * @example\n   * ```ts\n   * const head = mesh.skeleton?.indexOf('Head');\n   * ```\n   */\n  public readonly skeleton?: Skeleton;\n\n  /**\n   * Whether this mesh is shadowed by lights that cast shadows\n   *\n   * Only lit materials take shadows. After changing it at runtime, call\n   * {@link Mesh3D#invalidate | invalidate}.\n   * @example\n   * ```ts\n   * water.receiveShadow = false;\n   * water.invalidate();\n   * ```\n   */\n  public receiveShadow: boolean;\n\n  /** @internal */\n  public _morph?: Morph;\n\n  /** @internal */\n  public _enabledPassBits = 0;\n\n  /** @internal */\n  public _disabledPassBits = 0;\n\n  /** @internal */\n  public _passCache: Record<number, MeshPassCache> = Object.create(null);\n\n  /** @internal */\n  public _storeIndex = -1;\n\n  /** @internal */\n  public _lastBonePitIndex = -1;\n\n  /** @internal */\n  public _sortKey = 0;\n\n  /**\n   * Raise it with `_markBatchDirty`; the flag alone does nothing until the mesh is queued\n   * @internal\n   */\n  public _batchDirty = true;\n\n  /**\n   * Whether the mesh is in its view's update queue\n   * @internal\n   */\n  public didRenderableUpdate = false;\n\n  /** @internal */\n  // unused-internal-disable-next-line -- `Geometry3D._meshes` reads and writes it through its UnstableList index key\n  public _geometryMeshIndex = -1;\n\n  /** @internal */\n  // unused-internal-disable-next-line -- `BaseMaterial3D._meshes` reads and writes it through its UnstableList index key\n  public _materialMeshIndex = -1;\n\n  /** @internal */\n  public _lastRenderPass = 0;\n\n  /** @internal */\n  public _lastDescriptorDirtyId = -1;\n\n  /** @internal */\n  public _lastWorldVisible = 1;\n\n  /** @internal */\n  public _skinnedMeshIndex = -1;\n\n  /** @internal */\n  public _morphedMeshIndex = -1;\n\n  /** @internal */\n  public _allMeshIndex = -1;\n\n  /**\n   * Creates a new `Mesh3D`; add it under {@link View3D.root | view.root} to draw it\n   * @example\n   * ```ts\n   * const mesh = new Mesh3D({ geometry, material });\n   * view.root.addChild(mesh);\n   * ```\n   * @param options - Construction options; see {@link Mesh3DOptions}.\n   */\n  constructor(options: Mesh3DOptions = {}) {\n    /** Held out of `Container3D`'s constructor, which would assign them before the mesh is ready */\n    const {\n      geometry = Geometry3D.EMPTY,\n      material = BaseMaterial3D.EMPTY,\n      skeleton,\n      castShadow,\n      receiveShadow,\n      billboardMode,\n      weights,\n      hitVolume,\n      width,\n      height,\n      depth,\n      parent,\n      ...rest\n    } = {\n      ...Mesh3D.defaultOptions,\n      ...definedProps(options),\n    };\n\n    super({ label: 'Mesh3D', ...rest });\n\n    this._geometry = geometry;\n    this._material = material;\n    this._updatePlaceholderMask();\n    this.skeleton = skeleton;\n    if (castShadow) this._enabledPassBits = RenderPassBit.SHADOW;\n    this.receiveShadow = receiveShadow!;\n    this._billboardMode = billboardMode!;\n    if (geometry.morphTargetCount > 0) {\n      this._morph = new Morph(weights ?? new Float32Array(geometry.morphTargetCount));\n    }\n    if (hitVolume !== undefined) this.hitVolume = hitVolume;\n    if (width !== undefined) this.width = width;\n    if (height !== undefined) this.height = height;\n    if (depth !== undefined) this.depth = depth;\n    parent?.addChild(this);\n  }\n\n  /**\n   * Morph target weights, one per target; `undefined` when the geometry has no morph targets\n   *\n   * Change its values at any time rather than assigning a new array: a playing animation keeps\n   * writing the old one, and the parts a model node's mesh splits into share one array, so a new\n   * array cuts this mesh loose from both.\n   * @example\n   * ```ts\n   * if (face.weights) face.weights[smileIndex] = 0.8;\n   * ```\n   */\n  get weights(): Float32Array | undefined {\n    return this._morph?.weights;\n  }\n\n  /**\n   * Replaces the weights array; does nothing when the geometry has no morph targets or `value` is\n   * `undefined`\n   * @param value - New weights, one per morph target.\n   */\n  set weights(value: Float32Array | undefined) {\n    if (this._morph && value) this._morph.weights = value;\n  }\n\n  /**\n   * The geometry this mesh draws; {@link Geometry3D.EMPTY} until it's given one\n   * @example\n   * ```ts\n   * rock.geometry = isFar ? lowDetailRock : highDetailRock;\n   * ```\n   */\n  get geometry(): Geometry3D {\n    return this._geometry;\n  }\n\n  /**\n   * Swaps the geometry, refitting a `hitVolume` given as `'box'` or `'geometry'`\n   *\n   * A geometry with as many morph targets as there are {@link Mesh3D#weights} keeps them; one with\n   * a different count gets new weights, all 0; one with none leaves `weights` undefined.\n   * @param value - Geometry to draw.\n   */\n  set geometry(value: Geometry3D) {\n    if (this._geometry === value) return;\n    if (this._view3d) {\n      this._geometry._meshes.remove(this);\n      value._meshes.add(this);\n    }\n    this._geometry = value;\n    this._markBatchDirty();\n    this._markStoreDirty();\n    this._worldBoundsCacheId = -1;\n    this._updatePlaceholderMask();\n    if (value.morphTargetCount !== (this._morph?.weights.length ?? 0)) this._replaceMorph();\n    if (typeof this._hitVolumeInput === 'string') {\n      this._hitVolumeResolved = resolveHitVolume(this, this._hitVolumeInput);\n    }\n  }\n\n  private _replaceMorph(): void {\n    const old = this._morph;\n    old?._store?.freeSlot(old);\n\n    const count = this._geometry.morphTargetCount;\n    const morph = count > 0 ? new Morph(new Float32Array(count)) : undefined;\n    this._morph = morph;\n\n    const view = this._view3d;\n    if (!view) return;\n    if (old && !morph) view._morphedMeshes.remove(this);\n    else if (!old && morph) view._morphedMeshes.add(this);\n  }\n\n  /** @internal */\n  public override _getDefaultHitVolume(): HitVolume3D {\n    return this._geometry.bounds3D;\n  }\n\n  /**\n   * The material this mesh draws with; {@link BaseMaterial3D.EMPTY} until it's given one\n   *\n   * Many meshes can draw one material, and a value written to it shows on all of them. A\n   * {@link Model3D}'s meshes draw its source's materials, shared with every model built from that\n   * source; {@link Model3D#materials} gives one model copies of its own. For one mesh alone, assign\n   * `mesh.material.clone({ baseColor: 0xff0000 })`, and destroy the copy when you're done with it.\n   * @example\n   * ```ts\n   * crate.material = selected ? highlightMaterial : crateMaterial;\n   * ```\n   */\n  get material(): BaseMaterial3D {\n    return this._material;\n  }\n\n  /**\n   * Swaps the material\n   * @param value - Material to draw the geometry with.\n   */\n  set material(value: BaseMaterial3D) {\n    if (this._material === value) return;\n    if (this._view3d) {\n      this._material._meshes.remove(this);\n      value._meshes.add(this);\n    }\n    this._material = value;\n    this._markBatchDirty();\n    this._markStoreDirty();\n    this._lastDescriptorDirtyId = -1;\n    this._updatePlaceholderMask();\n  }\n\n  private _updatePlaceholderMask(): void {\n    this._placeholderMask = this._geometry === Geometry3D.EMPTY || this._material === BaseMaterial3D.EMPTY ? 0 : ~0;\n  }\n\n  /** @internal */\n  public _markBatchDirty(): void {\n    this._batchDirty = true;\n    this._queueMeshUpdate();\n  }\n\n  /** @internal */\n  public _markStoreDirty(): void {\n    this._storeDirty = true;\n    this._queueMeshUpdate();\n  }\n\n  /** @internal */\n  public _queueMeshUpdate(): void {\n    if (this.didRenderableUpdate || !this._view3d) return;\n    this.didRenderableUpdate = true;\n    this._view3d._onRenderableUpdate(this);\n  }\n\n  /**\n   * Whether this mesh casts shadows\n   *\n   * A mesh whose material has `alphaMode: 'blend'`, or uses transmission, casts none even while\n   * this is `true`. Setting it is `enablePass('shadow')` or `disablePass('shadow')`.\n   * @example\n   * ```ts\n   * grass.castShadow = false;\n   * ```\n   */\n  get castShadow(): boolean {\n    return (this._enabledPassBits & RenderPassBit.SHADOW) !== 0;\n  }\n\n  /**\n   * Sets whether the mesh casts shadows, from the next render\n   * @param value - Whether the mesh casts shadows.\n   */\n  set castShadow(value: boolean) {\n    if (value) this._enablePassBit(RenderPassBit.SHADOW);\n    else this._disablePassBit(RenderPassBit.SHADOW);\n  }\n\n  /**\n   * Adds this mesh to a render pass, whatever its material says\n   *\n   * {@link BaseMaterial3D#enablePass} for one mesh: the pass draws this mesh from the next render,\n   * and other meshes sharing the material don't follow. It undoes this mesh's own `disablePass`\n   * for the pass. `'shadow'` is the same as setting `castShadow`.\n   * @param name - The pass's `name`, such as `'outline'`.\n   * @example\n   * ```ts\n   * hovered.enablePass('outline');\n   * ```\n   */\n  public enablePass(name: string): void {\n    this._enablePassBit(passBitRegistry.getOrAllocate(name));\n  }\n\n  /**\n   * Takes this mesh out of a render pass, whatever its material says\n   *\n   * The mesh leaves the pass on the next render, and other meshes sharing the material stay in it.\n   * `disablePass('opaque')` draws nothing of the mesh while it still casts its shadow. Only the\n   * named pass is left, so a material that later turns `'blend'` brings the mesh into the\n   * transparent pass. {@link Mesh3D#enablePass} undoes it. Does nothing for a pass name nothing\n   * has used yet.\n   * @param name - The pass's `name`, such as `'opaque'`.\n   * @example\n   * ```ts\n   * shadowProxy.disablePass('opaque');\n   * ```\n   */\n  public disablePass(name: string): void {\n    const bit = passBitRegistry.get(name);\n    if (bit !== undefined) this._disablePassBit(bit);\n  }\n\n  private _enablePassBit(bit: number): void {\n    if (this._enabledPassBits & bit) return;\n    this._enabledPassBits |= bit;\n    this._disabledPassBits &= ~bit;\n    this._markBatchDirty();\n  }\n\n  private _disablePassBit(bit: number): void {\n    if (this._disabledPassBits & bit) return;\n    this._enabledPassBits &= ~bit;\n    this._disabledPassBits |= bit;\n    this._queueMeshUpdate();\n  }\n\n  /**\n   * How this mesh turns to face the camera; see {@link BillboardMode} for the modes\n   *\n   * Local `+Z` turns to face the viewer, so author a card facing `+Z`; any material works, lit or\n   * unlit. A solid mesh keeps its depth and the scale along each axis as it turns, but loses the\n   * shear of a non-uniformly scaled parent under a rotation. Its shadow and its culling use the\n   * unturned mesh, so geometry off-centre from its origin can be culled while on screen, and meshes\n   * with different modes don't share a draw.\n   * @example\n   * ```ts\n   * card.billboardMode = 'cylindrical';\n   * ```\n   */\n  get billboardMode(): BillboardMode {\n    return this._billboardMode;\n  }\n\n  /**\n   * Sets how the mesh turns to face the camera\n   * @param value - How to orient the mesh toward the camera, or `'none'` to draw it as authored.\n   */\n  set billboardMode(value: BillboardMode) {\n    if (this._billboardMode === value) return;\n    this._billboardMode = value;\n    this._markBatchDirty();\n  }\n\n  /**\n   * The {@link RenderPassBit} flags of the passes that draw this mesh: its material's passes, plus\n   * `SHADOW` while it casts shadows, or none while it holds {@link Geometry3D.EMPTY} or\n   * {@link BaseMaterial3D.EMPTY}\n   *\n   * The mesh's own {@link Mesh3D#enablePass} and {@link Mesh3D#disablePass} win over its\n   * material's, and a blended or transmissive material casts no shadow.\n   * @example\n   * ```ts\n   * const castsShadow = (mesh.renderPassMask & RenderPassBit.SHADOW) !== 0;\n   * ```\n   * @advanced\n   */\n  get renderPassMask(): number {\n    const passBit = this._material._passBit;\n    const mask = (this._enabledPassBits | passBit) & ~this._disabledPassBits & this._placeholderMask;\n\n    return passBit & (RenderPassBit.TRANSPARENT | RenderPassBit.TRANSMISSION) ? mask & ~RenderPassBit.SHADOW : mask;\n  }\n\n  /**\n   * This mesh's bounding {@link Sphere} in world space, large enough for morph weights from 0 to 1\n   *\n   * Cached until the world transform or geometry changes, so reading it often is cheap. It follows\n   * {@link Container3D.worldTransform | worldTransform}, so it can be out of date after a change\n   * this frame. Dynamic geometry gives an empty sphere (`radius < 0`). The sphere is shared: don't\n   * change it, and `clone()` it to keep a copy.\n   * @example\n   * ```ts\n   * if (camera.frustum.intersectsSphere(enemy.boundingSphere)) enemy.lookAt(player.position);\n   * ```\n   */\n  public get boundingSphere(): Sphere {\n    const sphere = (this._worldBoundsSphere ||= new Sphere());\n    if (this._worldBoundsCacheId !== this._worldTransformId) {\n      this._worldBoundsCacheId = this._worldTransformId;\n      const geometry = this._geometry;\n      if (geometry.dynamic) {\n        sphere.makeEmpty();\n      } else if (this._morph && geometry._morphBoundsExpansion > 0) {\n        _morphExpandedSphere.copyFrom(geometry.boundsSphere);\n        _morphExpandedSphere.radius += geometry._morphBoundsExpansion;\n        _morphExpandedSphere.applyMatrix4(this.worldTransform, sphere);\n      } else {\n        geometry.boundsSphere.applyMatrix4(this.worldTransform, sphere);\n      }\n    }\n    return sphere;\n  }\n\n  /**\n   * Makes the mesh rebuild its shader and draw state on the next frame\n   *\n   * Assigning `geometry`, `material` or `billboardMode` does this for you, and so do most material\n   * changes; {@link BaseMaterial3D} lists the ones that need this call. Call it too after changing\n   * {@link Mesh3D#receiveShadow | receiveShadow}. It doesn't re-read vertex data edited in place;\n   * call {@link Geometry3D.unload} for that.\n   * @example\n   * ```ts\n   * mesh.receiveShadow = false;\n   * mesh.invalidate();\n   * ```\n   */\n  public invalidate(): void {\n    this._markBatchDirty();\n  }\n\n  /**\n   * Unloads this mesh's geometry now\n   *\n   * The vertex data stays on the CPU, so the next frame that draws the mesh uploads it again.\n   * Remove the mesh from the scene first, or that happens straight away. The material is left\n   * alone, since it's usually shared: call {@link BaseMaterial3D.unload} for that, or\n   * {@link Model3D.unload} to free a model's geometry and textures together.\n   * @example\n   * ```ts\n   * view.root.removeChild(mesh);\n   * mesh.unload(); // adding it back re-uploads and re-packs the geometry\n   * ```\n   * @see {@link Geometry3D.unload} For what this frees.\n   * @see {@link Mesh3D.destroy} For permanent teardown.\n   */\n  public override unload(): void {\n    if (this.destroyed) return;\n\n    super.unload();\n    this._geometry.unload();\n\n    this._markBatchDirty();\n    this._markStoreDirty();\n  }\n\n  /** @internal */\n  public override _storeWorldTransform(): void {\n    const index = this._storeIndex;\n\n    if (index < 0) {\n      this._markStoreDirty();\n\n      return;\n    }\n\n    const store = this._view3d!._sceneBatch.storeBuffer;\n    const worldTransform = this.worldTransform;\n    store.writeWorldTransform(index, worldTransform.elements64);\n    if (store.writesSpheres) {\n      const geometry = this._geometry;\n      store.writeBoundingSphere(\n        index,\n        worldTransform.elements,\n        0,\n        geometry,\n        this._morph ? geometry._morphBoundsExpansion : 0,\n      );\n    }\n  }\n\n  /** @internal */\n  public override _storeWorldVisible(): void {\n    if (this._worldVisible === this._lastWorldVisible) return;\n    this._lastWorldVisible = this._worldVisible;\n    const batch = this._view3d!._sceneBatch;\n    if (this._storeIndex < 0) this._markStoreDirty();\n    else batch.storeBuffer.writeVisibility(this._storeIndex, this._worldVisible);\n    batch._visibilityDirtyId++;\n  }\n\n  /**\n   * Destroys this mesh\n   *\n   * Geometry and material are often shared, so they stay unless you pass `geometry` or\n   * `material`. `texture` then frees the destroyed material's textures, and `textureSource` their\n   * sources. The placeholders {@link Geometry3D.EMPTY} and {@link BaseMaterial3D.EMPTY} always\n   * stay. The {@link Mesh3D#skeleton | skeleton} is never destroyed here: its {@link Model3D}, or\n   * whoever built it, owns it.\n   * @example\n   * ```ts\n   * mesh.destroy({ geometry: true, material: true });\n   * ```\n   * @param options - Teardown flags; see {@link Destroy3DOptions}.\n   */\n  public override destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n\n    super.destroy(options);\n\n    this._passCache = Object.create(null);\n    this._storeIndex = -1;\n    this._allMeshIndex = -1;\n    this._geometry._meshes.remove(this);\n    this._material._meshes.remove(this);\n    this._skinnedMeshIndex = -1;\n    this._morphedMeshIndex = -1;\n\n    if (resolveDestroy3DFlag(options, 'geometry')) this._destroyGeometry();\n\n    if (resolveDestroy3DFlag(options, 'material')) this._material.destroy(options);\n\n    this._geometry = null!;\n    this._material = null!;\n  }\n\n  /** Frees the geometry for `destroy`; a subclass that doesn't own its geometry overrides it as a no-op */\n  protected _destroyGeometry(): void {\n    this._geometry.destroy(true);\n  }\n}\n","import type { Animation } from './Animation';\nimport type { AnimationPlayer } from './AnimationPlayer';\nimport type { PropertyAccumulator } from './PropertyAccumulator';\n\n/**\n * Playback state for a single {@link Animation} on an {@link AnimationPlayer}\n *\n * {@link AnimationPlayer#play} and {@link AnimationPlayer#getState} return one. Use it to control\n * playback, looping, speed and blend weight. The playback methods follow pixi's `AnimatedSprite`:\n * {@link AnimationState#stop | stop()} freezes in place and {@link AnimationState#play | play()}\n * resumes from there.\n * @example\n * ```ts\n * const walk = model.player.play('walk');\n *\n * walk.animationSpeed = 0.5;\n * walk.stop(); // freeze at the current pose\n * walk.play(); // resume from the same time\n * walk.gotoAndStop(0); // rewind and show the first pose\n * ```\n * @category animation\n * @standard\n */\nexport class AnimationState {\n  /**\n   * Animation this state plays\n   * @example\n   * ```ts\n   * walk.gotoAndStop(walk.animation.duration);\n   * ```\n   */\n  public readonly animation: Animation;\n  /**\n   * Player that owns this state\n   * @example\n   * ```ts\n   * attack.onComplete = () => attack.player.play('idle');\n   * ```\n   */\n  public readonly player: AnimationPlayer;\n  /**\n   * Current playback time in seconds\n   *\n   * Writing it moves the playhead without applying the pose. Use\n   * {@link AnimationState#gotoAndStop | gotoAndStop()} to seek and show the pose at once.\n   * @example\n   * ```ts\n   * const progress = walk.time / walk.animation.duration;\n   * ```\n   * @default 0\n   */\n  public time: number = 0;\n  /**\n   * Playback speed multiplier; negative values play backwards\n   * @example\n   * ```ts\n   * walk.animationSpeed = 2;\n   * rewind.animationSpeed = -1;\n   * ```\n   * @default 1\n   */\n  public animationSpeed: number = 1;\n  /**\n   * Whether playback wraps around at the animation's ends\n   * @example\n   * ```ts\n   * const jump = player.play('jump');\n   *\n   * jump.loop = false;\n   * ```\n   * @default true\n   */\n  public loop: boolean = true;\n  /**\n   * Share of the blend when several playing states drive the same property through tracks with the\n   * same label\n   *\n   * Weights are relative: at 1 and 3, the property ends up a quarter one state and three quarters\n   * the other. They don't fade a state against the rest pose; a state that is the only one driving\n   * a property applies in full at any weight above 0. At 0 the state keeps advancing but writes\n   * nothing.\n   * @example\n   * ```ts\n   * const walk = player.play('walk');\n   * const run = player.play('run');\n   *\n   * walk.weight = 1 - speed;\n   * run.weight = speed;\n   * ```\n   * @default 1\n   */\n  public weight: number = 1;\n  /**\n   * Called once when a non-looping state reaches its end\n   *\n   * The state has already stopped, holding its final pose, so the callback can\n   * start the next animation.\n   * @example\n   * ```ts\n   * const attack = player.getState('attack');\n   *\n   * attack.loop = false;\n   * attack.onComplete = () => player.play('idle');\n   * attack.gotoAndPlay(0);\n   * ```\n   * @default null\n   */\n  public onComplete: (() => void) | null = null;\n  /**\n   * Called each time a looping state wraps around its duration\n   * @example\n   * ```ts\n   * walk.onLoop = () => footsteps.play();\n   * ```\n   * @default null\n   */\n  public onLoop: (() => void) | null = null;\n\n  private _playing: boolean = false;\n  private _completed: boolean = false;\n  private _looped: boolean = false;\n  private readonly _trackIndices: Int32Array;\n  /** @internal */\n  public _accumulators: PropertyAccumulator[] = [];\n\n  /** Grown by the constructor to the widest track, since a morph weights track can exceed 4 components */\n  private static _scratchBuffer = new Float32Array(4);\n\n  /** @internal */\n  constructor(player: AnimationPlayer, animation: Animation) {\n    this.player = player;\n    this.animation = animation;\n\n    this._trackIndices = new Int32Array(animation.tracks.length);\n\n    for (let i = 0; i < animation.tracks.length; i++) {\n      if (animation.tracks[i].valueSize > AnimationState._scratchBuffer.length) {\n        AnimationState._scratchBuffer = new Float32Array(animation.tracks[i].valueSize);\n      }\n    }\n  }\n\n  /**\n   * Whether this state is advancing on its player's updates\n   * @example\n   * ```ts\n   * if (!attack.playing) attack.gotoAndPlay(0);\n   * ```\n   */\n  public get playing(): boolean {\n    return this._playing;\n  }\n\n  /**\n   * Starts or resumes playback from the current {@link AnimationState#time | time}\n   *\n   * A one-shot animation that already finished completes again on the next update; use\n   * {@link AnimationState#gotoAndPlay | gotoAndPlay(0)} to restart it, or\n   * `gotoAndPlay(animation.duration)` for one a negative `animationSpeed` plays backwards. Does\n   * nothing once the owning player is destroyed.\n   * @example\n   * ```ts\n   * pauseButton.on('pointertap', () => (walk.playing ? walk.stop() : walk.play()));\n   * ```\n   * @returns This state for chaining\n   */\n  public play(): this {\n    if (this._playing || this.player.destroyed) return this;\n\n    this._playing = true;\n    this.player._activate(this);\n\n    return this;\n  }\n\n  /**\n   * Stops playback, holding the current time and pose\n   *\n   * To rewind, call {@link AnimationState#gotoAndStop | gotoAndStop(0)}.\n   * @example\n   * ```ts\n   * player.getState('walk').stop();\n   * ```\n   * @returns This state for chaining\n   */\n  public stop(): this {\n    if (!this._playing) return this;\n\n    this._playing = false;\n    this.player._deactivate();\n\n    return this;\n  }\n\n  /**\n   * Jumps to a time and starts playing from there\n   * @example\n   * ```ts\n   * attackButton.on('pointertap', () => attack.gotoAndPlay(0));\n   * ```\n   * @param time - Playback time in seconds\n   * @returns This state for chaining\n   */\n  public gotoAndPlay(time: number): this {\n    this.time = time;\n\n    return this.play();\n  }\n\n  /**\n   * Stops playback at a time and applies that pose to the target right away\n   *\n   * The pose is this state's alone, not blended with others; a state still playing overwrites\n   * the properties it drives on the next update. Does nothing once the owning player is destroyed.\n   * @example\n   * ```ts\n   * slider.on('change', (value: number) => walk.gotoAndStop(value * walk.animation.duration));\n   * ```\n   * @param time - Playback time in seconds\n   * @returns This state for chaining\n   */\n  public gotoAndStop(time: number): this {\n    if (this.player.destroyed) return this;\n\n    this.stop();\n    this.time = time;\n    this._applyPose();\n\n    return this;\n  }\n\n  /**\n   * A one-shot state that runs past an end stops but still samples this frame, so its end pose holds\n   * @internal\n   */\n  public _update(seconds: number): void {\n    if (!this._playing) return;\n\n    const duration = this.animation.duration;\n    let time = this.time + seconds * this.animationSpeed;\n\n    if (time >= duration || time < 0) {\n      if (!this.loop) {\n        time = time < 0 ? 0 : duration;\n        this._completed = true;\n        this.stop();\n      } else if (duration > 0) {\n        time %= duration;\n        if (time < 0) time += duration;\n        this._looped = true;\n      } else {\n        time = 0;\n      }\n    }\n\n    this.time = time;\n\n    const weight = this.weight;\n    if (weight === 0) return;\n\n    const scratch = AnimationState._scratchBuffer;\n    const tracks = this.animation.tracks;\n    const accumulators = this._accumulators;\n    const trackIndices = this._trackIndices;\n\n    if (accumulators.length === 0) return;\n\n    for (let i = 0; i < tracks.length; i++) {\n      const track = tracks[i];\n      const acc = accumulators[i];\n\n      if (!acc) continue;\n\n      const lastIndex = trackIndices[i];\n\n      if (!acc.dirty) {\n        trackIndices[i] = track.evaluate(this.time, lastIndex, acc.values);\n        acc.weight = weight;\n        acc.dirty = true;\n      } else {\n        trackIndices[i] = track.evaluate(this.time, lastIndex, scratch);\n\n        const newWeight = acc.weight + weight;\n        if (newWeight > 0) {\n          track.blendInto(acc.values, scratch, weight / newWeight);\n        }\n        acc.weight = newWeight;\n      }\n    }\n  }\n\n  /** @internal */\n  public _emitCallbacks(): void {\n    if (this._looped) {\n      this._looped = false;\n      this.onLoop?.();\n    }\n\n    if (this._completed) {\n      this._completed = false;\n      this.onComplete?.();\n    }\n  }\n\n  private _applyPose(): void {\n    this.player._bind(this);\n\n    const tracks = this.animation.tracks;\n    const accumulators = this._accumulators;\n    const trackIndices = this._trackIndices;\n\n    for (let i = 0; i < tracks.length; i++) {\n      const acc = accumulators[i];\n\n      trackIndices[i] = tracks[i].evaluate(this.time, trackIndices[i], acc.values);\n      acc.binding.apply(acc.values);\n    }\n  }\n}\n","/** @internal */\nexport abstract class Binding {\n  public abstract apply(value: Float32Array): void;\n}\n","import { Binding } from './Binding';\n\n/** @internal */\nexport class FloatArrayBinding extends Binding {\n  constructor(private readonly _target: Float32Array | Float64Array | number[]) {\n    super();\n  }\n\n  public apply(value: Float32Array): void {\n    const arr = this._target;\n    const len = value.length;\n    for (let i = 0; i < len; i++) {\n      arr[i] = value[i];\n    }\n  }\n}\n","import { Binding } from './Binding';\n\n/** @internal */\nexport class NumberBinding<TTarget extends object = object> extends Binding {\n  constructor(\n    private readonly _target: TTarget,\n    private readonly _key: keyof TTarget,\n  ) {\n    super();\n  }\n\n  public apply(value: Float32Array): void {\n    this._target[this._key] = value[0] as TTarget[keyof TTarget];\n  }\n}\n","import type { QuaternionData } from '../../math/rotation/Quaternion';\nimport { Binding } from './Binding';\n\n/** Written through `set` so an `ObservableQuaternion` notifies once per sample, not four times */\ninterface QuaternionSettable extends QuaternionData {\n  set: (x: number, y: number, z: number, w: number) => this;\n}\n\n/**\n * Renormalises each sample, since a blend of unit quaternions comes out shorter and would scale the transform\n * @internal\n */\nexport class QuaternionBinding extends Binding {\n  constructor(private readonly _target: QuaternionSettable) {\n    super();\n  }\n\n  public apply(value: Float32Array): void {\n    const x = value[0];\n    const y = value[1];\n    const z = value[2];\n    const w = value[3];\n    const lengthSq = x * x + y * y + z * z + w * w;\n\n    if (lengthSq === 0) {\n      this._target.set(0, 0, 0, 1);\n\n      return;\n    }\n    const inv = 1 / Math.sqrt(lengthSq);\n\n    this._target.set(x * inv, y * inv, z * inv, w * inv);\n  }\n}\n","import type { Skeleton } from '../../scene/Skeleton';\nimport { Binding } from './Binding';\n\n/** @internal */\nexport class SkeletonPositionBinding extends Binding {\n  constructor(\n    private readonly _skel: Skeleton,\n    private readonly _offset3: number,\n  ) {\n    super();\n  }\n\n  public apply(value: Float32Array): void {\n    const p = this._offset3;\n    const arr = this._skel.localPosition;\n    arr[p] = value[0];\n    arr[p + 1] = value[1];\n    arr[p + 2] = value[2];\n    this._skel.dirty = true;\n  }\n}\n","import type { Skeleton } from '../../scene/Skeleton';\nimport { Binding } from './Binding';\n\n/**\n * Renormalises each sample, as {@link QuaternionBinding} does\n * @internal\n */\nexport class SkeletonRotationBinding extends Binding {\n  constructor(\n    private readonly _skel: Skeleton,\n    private readonly _offset4: number,\n  ) {\n    super();\n  }\n\n  public apply(value: Float32Array): void {\n    const r = this._offset4;\n    const arr = this._skel.localRotation;\n    const x = value[0];\n    const y = value[1];\n    const z = value[2];\n    const w = value[3];\n    const lengthSq = x * x + y * y + z * z + w * w;\n    const inv = lengthSq > 0 ? 1 / Math.sqrt(lengthSq) : 0;\n\n    arr[r] = x * inv;\n    arr[r + 1] = y * inv;\n    arr[r + 2] = z * inv;\n    arr[r + 3] = inv === 0 ? 1 : w * inv;\n    this._skel.dirty = true;\n  }\n}\n","import type { Skeleton } from '../../scene/Skeleton';\nimport { Binding } from './Binding';\n\n/** @internal */\nexport class SkeletonScaleBinding extends Binding {\n  constructor(\n    private readonly _skel: Skeleton,\n    private readonly _offset3: number,\n  ) {\n    super();\n  }\n\n  public apply(value: Float32Array): void {\n    const s = this._offset3;\n    const arr = this._skel.localScale;\n    arr[s] = value[0];\n    arr[s + 1] = value[1];\n    arr[s + 2] = value[2];\n    this._skel.dirty = true;\n  }\n}\n","import type { PointLike3D } from '../../math/vector/PointLike3D';\nimport { Binding } from './Binding';\n\n/** @internal */\nexport class Vector3Binding extends Binding {\n  constructor(private readonly _target: PointLike3D) {\n    super();\n  }\n\n  public apply(value: Float32Array): void {\n    this._target.set(value[0], value[1], value[2]);\n  }\n}\n","import { ObservableQuaternion } from '../../math/rotation/ObservableQuaternion';\nimport { Quaternion } from '../../math/rotation/Quaternion';\nimport { ObservableVector3 } from '../../math/vector/ObservableVector3';\nimport { Vector3 } from '../../math/vector/Vector3';\nimport type { Container3D } from '../../scene/Container3D';\nimport type { Skeleton } from '../../scene/Skeleton';\nimport { Binding } from './Binding';\nimport { FloatArrayBinding } from './FloatArrayBinding';\nimport { NumberBinding } from './NumberBinding';\nimport { QuaternionBinding } from './QuaternionBinding';\nimport { SkeletonPositionBinding } from './SkeletonPositionBinding';\nimport { SkeletonRotationBinding } from './SkeletonRotationBinding';\nimport { SkeletonScaleBinding } from './SkeletonScaleBinding';\nimport { Vector3Binding } from './Vector3Binding';\n\ninterface BindingOptions {\n  target?: Container3D;\n  channel: string;\n  skeleton?: Skeleton;\n  boneIndex?: number;\n}\n\n/** @internal */\nclass DummyBinding extends Binding {\n  public apply(): void {}\n}\n\n/**\n * Must bind every property type {@link TrackOptions#label} lists\n * @internal\n */\nexport function createBinding(options: BindingOptions): Binding {\n  if (options.skeleton && options.boneIndex !== undefined && options.boneIndex !== -1) {\n    const i = options.boneIndex;\n    switch (options.channel) {\n      case 'position':\n        return new SkeletonPositionBinding(options.skeleton, i * 3);\n      case 'quaternion':\n        return new SkeletonRotationBinding(options.skeleton, i * 4);\n      case 'scale':\n        return new SkeletonScaleBinding(options.skeleton, i * 3);\n    }\n  }\n\n  const target = options.target;\n  if (!target) return new DummyBinding();\n\n  const channel = options.channel as keyof Container3D;\n  const prop = target[channel];\n\n  if (prop instanceof Vector3 || prop instanceof ObservableVector3) {\n    return new Vector3Binding(prop);\n  } else if (prop instanceof Quaternion || prop instanceof ObservableQuaternion) {\n    return new QuaternionBinding(prop);\n  } else if (typeof prop === 'number') {\n    return new NumberBinding(target, channel);\n  } else if (isNumericArray(prop)) {\n    return new FloatArrayBinding(prop);\n  }\n\n  return new DummyBinding();\n}\n\nfunction isNumericArray(value: unknown): value is Float32Array | Float64Array | number[] {\n  return Array.isArray(value) || value instanceof Float32Array || value instanceof Float64Array;\n}\n","import type { Binding } from './bindings/Binding';\n\n/** @internal */\nexport class PropertyAccumulator {\n  public binding: Binding;\n  public values: Float32Array;\n  public weight: number = 0;\n  /** `false` until a state samples into `values` this update, so the first one overwrites rather than blends */\n  public dirty: boolean = false;\n\n  constructor(binding: Binding, valueSize: number) {\n    this.binding = binding;\n    this.values = new Float32Array(valueSize);\n  }\n}\n","import { definedProps, Ticker, UPDATE_PRIORITY } from 'pixi.js';\n\nimport { Container3D } from '../scene/Container3D';\nimport { Mesh3D } from '../scene/Mesh3D';\nimport type { Skeleton } from '../scene/Skeleton';\nimport type { Animation } from './Animation';\nimport { AnimationState } from './AnimationState';\nimport { createBinding } from './bindings/createBinding';\nimport { PropertyAccumulator } from './PropertyAccumulator';\nimport type { Track } from './tracks/Track';\n\n/** @internal */\nexport type AnimationTarget = Container3D | { skeleton: Skeleton; boneIndex: number };\n\n/**\n * Options for creating an animation player\n * @example\n * ```ts\n * const player = new AnimationPlayer({\n *   target: robot,\n *   animations: [walk, run],\n *   autoPlay: 'walk',\n * });\n * ```\n * @category animation\n * @standard\n */\nexport interface AnimationPlayerOptions {\n  /**\n   * Root of the hierarchy to animate; tracks find their nodes in its subtree, itself included\n   * @example\n   * ```ts\n   * const player = new AnimationPlayer({ target: robot, animations: [walk] });\n   * ```\n   */\n  target: Container3D;\n  /**\n   * Animations to register, keyed as {@link AnimationPlayer#addAnimations} describes\n   * @example\n   * ```ts\n   * const player = new AnimationPlayer({ target: robot, animations: { walk, run } });\n   * ```\n   */\n  animations?: Record<string, Animation> | Animation[];\n  /**\n   * Targets by glTF node index, the node part of a loaded track's label\n   * @internal\n   */\n  nodeMap?: Record<number, AnimationTarget>;\n  /**\n   * Whether playback advances on {@link Ticker.shared}; see {@link AnimationPlayer#autoUpdate}\n   * @example\n   * ```ts\n   * const player = new AnimationPlayer({ target: robot, animations: [walk], autoUpdate: false });\n   *\n   * app.ticker.add((ticker) => player.update(ticker));\n   * ```\n   * @default true\n   */\n  autoUpdate?: boolean;\n  /**\n   * Animation to start playing on construction\n   *\n   * `true` plays the first registered animation, and a string plays the animation\n   * registered under that label.\n   * @example\n   * ```ts\n   * const player = new AnimationPlayer({ target: robot, animations: [idle, walk], autoPlay: 'idle' });\n   * ```\n   * @default false\n   */\n  autoPlay?: boolean | string;\n}\n\n/**\n * Plays animations on a {@link Container3D} and its children\n *\n * A {@link Model3D} loaded with animations already has one as {@link Model3D#player | player}.\n * Build your own to play animations authored in code.\n *\n * Each animation gets one {@link AnimationState} per player, holding its time, speed and weight.\n * Any number can play at once. Where two playing states drive the same property through tracks\n * with the same label, the player blends their values by {@link AnimationState#weight}, which is\n * how crossfades work. Playback\n * advances on {@link Ticker.shared} unless {@link AnimationPlayer#autoUpdate} is off.\n * @example\n * ```ts\n * const player = new AnimationPlayer({ target: robot, animations: [idle, walk] });\n * const walking = player.play('walk');\n *\n * walking.animationSpeed = 1.5;\n * ```\n * @category animation\n * @standard\n */\nexport class AnimationPlayer {\n  /**\n   * Defaults for every new `AnimationPlayer`; an option passed as `undefined` keeps its default\n   *\n   * A {@link Model3D} passes its own `autoUpdate` and `autoPlay`, so its player follows\n   * {@link Model3D.defaultOptions} instead.\n   * @example\n   * ```ts\n   * AnimationPlayer.defaultOptions.autoUpdate = false;\n   * ```\n   */\n  public static defaultOptions: Partial<AnimationPlayerOptions> = {\n    autoUpdate: true,\n    autoPlay: false,\n  };\n\n  /**\n   * Root of the hierarchy this player animates\n   * @advanced\n   */\n  public readonly target: Container3D;\n\n  private readonly _states: AnimationState[] = [];\n  private readonly _stateCache: Map<Animation, AnimationState> = new Map();\n  private readonly _animations: Map<string, Animation> = new Map();\n  private _animationLabels: string[] | null = null;\n\n  private _autoUpdate: boolean;\n  private _isConnectedToTicker: boolean = false;\n  /** Set while `update` or `stop` walks `_states`; a state that stops then stays listed until the walk ends */\n  private _updating: boolean = false;\n  private _destroyed: boolean = false;\n\n  private _accumulators: Record<string, PropertyAccumulator> = {};\n  private readonly _accumulatorList: PropertyAccumulator[] = [];\n  private readonly _nodeMap?: Record<number, AnimationTarget>;\n  private readonly _onTick = (ticker: Ticker): void => {\n    this.update(ticker);\n  };\n\n  constructor(options: AnimationPlayerOptions) {\n    const { target, animations, nodeMap, autoUpdate, autoPlay } = {\n      ...AnimationPlayer.defaultOptions,\n      ...definedProps(options),\n    };\n\n    this.target = target;\n    this._nodeMap = nodeMap;\n    this._autoUpdate = autoUpdate!;\n\n    if (animations) {\n      this.addAnimations(animations);\n    }\n\n    const label = autoPlay === true ? this.animationLabels[0] : autoPlay;\n\n    if (typeof label === 'string') this.play(label);\n  }\n\n  /**\n   * Labels of every registered animation, in registration order\n   *\n   * Pass one to {@link AnimationPlayer#play} or {@link AnimationPlayer#getState}.\n   * @example\n   * ```ts\n   * for (const label of player.animationLabels) {\n   *   addButton(label, () => player.play(label));\n   * }\n   * ```\n   */\n  public get animationLabels(): readonly string[] {\n    return (this._animationLabels ??= Array.from(this._animations.keys()));\n  }\n\n  /**\n   * Registers animations for playback\n   *\n   * Array entries are keyed by each animation's own label. Record entries are keyed\n   * by the record property name.\n   * @example\n   * ```ts\n   * player.addAnimations([wave]);\n   * player.addAnimations({ cheer: celebrate });\n   * player.play('cheer');\n   * ```\n   * @param animations - Animations to register\n   */\n  public addAnimations(animations: Record<string, Animation> | Animation[]): void {\n    if (Array.isArray(animations)) {\n      animations.forEach((animation) => this._animations.set(animation.label, animation));\n    } else {\n      Object.entries(animations).forEach(([label, animation]) => this._animations.set(label, animation));\n    }\n\n    this._animationLabels = null;\n  }\n\n  /**\n   * Returns a registered animation by label\n   * @example\n   * ```ts\n   * const walkDuration = player.getAnimation('walk')?.duration ?? 0;\n   * ```\n   * @param label - Registered animation label\n   * @returns The animation, or `undefined` when nothing is registered under the label\n   */\n  public getAnimation(label: string): Animation | undefined {\n    return this._animations.get(label);\n  }\n\n  /**\n   * Starts or resumes an animation from its state's current time\n   *\n   * Animations already playing carry on and blend with it; call {@link AnimationPlayer#stop}\n   * first to switch from one to another. {@link AnimationState#play} covers restarting a one-shot\n   * animation that already finished.\n   * @example\n   * ```ts\n   * player.stop();\n   * player.play('run');\n   * ```\n   * @param animation - The animation, or the label it's registered under\n   * @returns The playback state for the animation\n   */\n  public play(animation: Animation | string): AnimationState {\n    return this.getState(animation).play();\n  }\n\n  /**\n   * Stops every playing animation, each holding its current time and pose\n   * @example\n   * ```ts\n   * menu.on('open', () => player.stop());\n   * ```\n   */\n  public stop(): void {\n    const states = this._states;\n    const updating = this._updating;\n\n    this._updating = true;\n\n    for (let i = 0; i < states.length; i++) {\n      states[i].stop();\n    }\n\n    this._updating = updating;\n\n    if (!updating) this._removeStopped();\n  }\n\n  /**\n   * Whether any animation on this player is playing\n   * @example\n   * ```ts\n   * if (!player.playing) player.play('idle');\n   * ```\n   */\n  public get playing(): boolean {\n    const states = this._states;\n\n    for (let i = 0; i < states.length; i++) {\n      if (states[i].playing) return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * Returns the reusable playback state for an animation without starting playback\n   *\n   * Each animation has one state per player, created on first request. Throws for a label nothing\n   * is registered under; {@link AnimationPlayer#getAnimation} returns `undefined` instead.\n   * @example\n   * ```ts\n   * const jump = player.getState('jump');\n   *\n   * jump.loop = false;\n   * jump.gotoAndPlay(0);\n   * ```\n   * @param animation - The animation, or the label it's registered under\n   * @returns The playback state for the animation\n   */\n  public getState(animation: Animation | string): AnimationState {\n    if (typeof animation === 'string') {\n      const registered = this._animations.get(animation);\n\n      if (!registered) {\n        throw new Error(`[AnimationPlayer] Animation \"${animation}\" is not registered.`);\n      }\n\n      animation = registered;\n    }\n\n    let state = this._stateCache.get(animation);\n\n    if (!state) {\n      state = new AnimationState(this, animation);\n      this._stateCache.set(animation, state);\n    }\n\n    return state;\n  }\n\n  /**\n   * Whether playback advances on {@link Ticker.shared}\n   *\n   * Turn it off to drive playback from your own ticker or fixed-step loop with\n   * {@link AnimationPlayer#update}.\n   * @example\n   * ```ts\n   * player.autoUpdate = false;\n   * app.ticker.add((ticker) => player.update(ticker));\n   * ```\n   */\n  public get autoUpdate(): boolean {\n    return this._autoUpdate;\n  }\n\n  /**\n   * Sets whether playback advances on `Ticker.shared`\n   * @param value - `false` to call `update` yourself\n   */\n  public set autoUpdate(value: boolean) {\n    if (value === this._autoUpdate) return;\n\n    this._autoUpdate = value;\n\n    if (!this._autoUpdate) {\n      this._disconnectTicker();\n    } else if (this.playing) {\n      this._connectTicker();\n    }\n  }\n\n  /** @internal */\n  public _activate(state: AnimationState): void {\n    if (this._destroyed) return;\n\n    if (this._states.indexOf(state) === -1) {\n      this._states.push(state);\n    }\n\n    this._bind(state);\n\n    if (this._autoUpdate) {\n      this._connectTicker();\n    }\n  }\n\n  /** @internal */\n  public _bind(state: AnimationState): void {\n    if (state._accumulators.length > 0) return;\n\n    const tracks = state.animation.tracks;\n\n    for (let i = 0; i < tracks.length; i++) {\n      state._accumulators[i] = this._getAccumulator(tracks[i]);\n    }\n  }\n\n  /** @internal */\n  public _deactivate(): void {\n    if (!this._updating) this._removeStopped();\n  }\n\n  /**\n   * Advances all playing states and applies the blended results to their targets\n   *\n   * Runs every frame from `Ticker.shared` while {@link AnimationPlayer#autoUpdate | autoUpdate}\n   * is on and something is playing. Call it yourself when driving playback from your own loop.\n   *\n   * `onComplete` and `onLoop` callbacks run once every pose is applied, so they see this frame's\n   * final pose and may play, stop or seek any state. A state they start begins advancing on the\n   * next update.\n   * @example\n   * ```ts\n   * player.autoUpdate = false;\n   * app.ticker.add((ticker) => player.update(ticker));\n   * ```\n   * @param ticker - The ticker driving this update; its `deltaMS` sets how far playback\n   *   advances. Omitted, one 60 fps frame is assumed.\n   */\n  public update(ticker?: Ticker): void {\n    const seconds = ticker ? ticker.deltaMS / 1000 : 1 / 60;\n    const states = this._states;\n    const count = states.length;\n\n    this._updating = true;\n\n    for (let i = 0; i < count; i++) {\n      states[i]._update(seconds);\n    }\n\n    const accumulators = this._accumulatorList;\n    const len = accumulators.length;\n\n    for (let i = 0; i < len; i++) {\n      const acc = accumulators[i];\n\n      if (acc.dirty) {\n        acc.binding.apply(acc.values);\n        acc.dirty = false;\n        acc.weight = 0;\n      }\n    }\n\n    for (let i = 0; i < count; i++) {\n      states[i]._emitCallbacks();\n\n      if (this._destroyed) return;\n    }\n\n    this._updating = false;\n    this._removeStopped();\n  }\n\n  /**\n   * Whether {@link AnimationPlayer#destroy} has been called on this player\n   * @example\n   * ```ts\n   * if (!player.destroyed) player.play('idle');\n   * ```\n   */\n  public get destroyed(): boolean {\n    return this._destroyed;\n  }\n\n  /**\n   * Stops every animation and takes the player off the ticker for good\n   *\n   * Calling it again does nothing, and `play` and `gotoAndStop` on an {@link AnimationState} kept\n   * from before are ignored. A {@link Model3D} destroys its own player; call this for one you built.\n   * @example\n   * ```ts\n   * player.destroy();\n   * crate.destroy();\n   * ```\n   */\n  public destroy(): void {\n    if (this._destroyed) return;\n\n    this._destroyed = true;\n    this._updating = false;\n    this._disconnectTicker();\n    this.stop();\n\n    this._stateCache.forEach((state) => {\n      state.onComplete = null;\n      state.onLoop = null;\n    });\n\n    /* oxlint-disable pixijs-3d/destroy-release -- kept states, playing, stop and update still read these after destroy */\n    this._states.length = 0;\n    this._stateCache.clear();\n    this._animations.clear();\n    this._animationLabels = null;\n    this._accumulators = {};\n    this._accumulatorList.length = 0;\n    /* oxlint-enable pixijs-3d/destroy-release */\n  }\n\n  private _removeStopped(): void {\n    const states = this._states;\n    let kept = 0;\n\n    for (let i = 0; i < states.length; i++) {\n      if (states[i].playing) states[kept++] = states[i];\n    }\n\n    states.length = kept;\n\n    if (kept === 0) this._disconnectTicker();\n  }\n\n  private _connectTicker(): void {\n    if (this._isConnectedToTicker) return;\n\n    Ticker.shared.add(this._onTick, undefined, UPDATE_PRIORITY.HIGH);\n    this._isConnectedToTicker = true;\n  }\n\n  private _disconnectTicker(): void {\n    if (!this._isConnectedToTicker) return;\n\n    Ticker.shared.remove(this._onTick);\n    this._isConnectedToTicker = false;\n  }\n\n  /** Tracks with the same label share one accumulator, which is how states driving one property blend */\n  private _getAccumulator(track: Track): PropertyAccumulator {\n    const trackLabel = track.label;\n\n    if (this._accumulators[trackLabel]) return this._accumulators[trackLabel];\n\n    const split = trackLabel.split('.');\n    const channel = split.pop()!;\n    const nodeLabel = split.join('.');\n\n    let target: Container3D | undefined;\n    let foundSkeleton: Skeleton | undefined;\n    let foundBoneIndex = -1;\n\n    if (this._nodeMap) {\n      const index = parseInt(nodeLabel, 10);\n      if (!isNaN(index)) {\n        const mapped = this._nodeMap[index];\n        if (mapped) {\n          if (mapped instanceof Container3D) {\n            target = mapped;\n          } else {\n            foundSkeleton = mapped.skeleton;\n            foundBoneIndex = mapped.boneIndex;\n          }\n        }\n      }\n    }\n\n    if (!target && !foundSkeleton) {\n      const found = findTarget(this.target, nodeLabel);\n      target = found?.node;\n      foundSkeleton = found?.skeleton;\n      foundBoneIndex = found?.boneIndex ?? -1;\n    }\n\n    const binding = createBinding({\n      target,\n      channel,\n      skeleton: foundSkeleton,\n      boneIndex: foundBoneIndex,\n    });\n\n    const acc = new PropertyAccumulator(binding, track.valueSize);\n\n    this._accumulators[trackLabel] = acc;\n    this._accumulatorList.push(acc);\n\n    return acc;\n  }\n}\n\n/** The empty `catch` is for `Skeleton.indexOf`, which throws for a name that isn't a bone */\nfunction findTarget(\n  target: Container3D,\n  label: string,\n): { node?: Container3D; skeleton?: Skeleton; boneIndex?: number } | undefined {\n  if (target.label === label) return { node: target };\n\n  if (target instanceof Mesh3D && target.skeleton) {\n    try {\n      return { skeleton: target.skeleton, boneIndex: target.skeleton.indexOf(label) };\n    } catch {}\n  }\n\n  for (const child of target.children) {\n    const result = findTarget(child, label);\n    if (result) return result;\n  }\n\n  return undefined;\n}\n","/**\n * How a track fills the time between two keyframes\n *\n * - `'LINEAR'` blends straight from one keyframe to the next; a {@link QuaternionTrack} slerps.\n * - `'STEP'` holds each keyframe until the next one.\n * - `'CUBICSPLINE'` follows a smooth curve shaped by tangents stored with each keyframe;\n *   {@link TrackOptions#values} has the layout.\n * @category animation\n * @advanced\n */\nexport type InterpolationMode = 'LINEAR' | 'STEP' | 'CUBICSPLINE';\n\n/**\n * Options for constructing a keyframe track\n * @category animation\n * @advanced\n */\nexport interface TrackOptions {\n  /** Keyframe times in seconds, in ascending order */\n  times: number[] | Float32Array;\n  /**\n   * Keyframe values, `valueSize` numbers per keyframe, in the order of `times`\n   *\n   * A `'CUBICSPLINE'` track stores three groups per keyframe instead: in-tangent, value and\n   * out-tangent, each `valueSize` long. Tangents are rates of change per second, as glTF stores them.\n   */\n  values: number[] | Float32Array;\n  /**\n   * Interpolation algorithm used between keyframes\n   * @default 'LINEAR'\n   */\n  interpolation?: InterpolationMode;\n  /**\n   * The property this track drives, as `'<node>.<property>'`, such as `'Hips.quaternion'`\n   *\n   * The player splits the label at its last `.` and looks for a node with that label, or a bone\n   * of a skinned mesh with that name, in the subtree of {@link AnimationPlayerOptions#target}.\n   * On a bone the property is `position`, `quaternion` or `scale`. On a node it is a `Vector3` or\n   * `ObservableVector3`, quaternion, number or numeric array property, such as `position`, `x` or\n   * `weights`. A label that matches nothing, or a property of another type, is ignored without a\n   * warning.\n   *\n   * Tracks loaded from glTF name their node by its index in the file, which only the player of a\n   * {@link Model3D} resolves.\n   */\n  label: string;\n  /**\n   * Number of numeric components in each keyframe value, such as the morph-target\n   * count of a weights track\n   *\n   * {@link NumberTrack}, {@link Vector3Track} and {@link QuaternionTrack} set it for you.\n   * @default 1\n   */\n  valueSize?: number;\n}\n\n/**\n * Kept out of {@link Track#evaluate} so V8 still inlines the forward search that forward playback takes\n * @param times - Keyframe times, with `times[0] < time < times[after]`\n * @param time - Time in seconds\n * @param after - A keyframe index past `time`\n */\nfunction bisectKeyframe(times: Float32Array, time: number, after: number): number {\n  let low = 0;\n  let high = after;\n\n  while (high - low > 1) {\n    const mid = (low + high) >> 1;\n\n    if (times[mid] <= time) low = mid;\n    else high = mid;\n  }\n\n  return low;\n}\n\n/**\n * Keyframes for one animated property\n *\n * The glTF loader builds tracks for you. Build them yourself to author an animation in code, and\n * pass them to {@link AnimationOptions#tracks}. Use `Track` itself for numeric arrays such as\n * morph-target weights, and {@link NumberTrack}, {@link Vector3Track} or {@link QuaternionTrack}\n * for numbers, vectors and rotations.\n * @example\n * ```ts\n * const weights = new Track({\n *   label: 'Face.weights',\n *   times: [0, 1],\n *   values: [0, 0, 1, 0.5],\n *   valueSize: 2,\n * });\n * ```\n * @category animation\n * @advanced\n */\nexport class Track {\n  /** The property this track drives; {@link TrackOptions#label} has the format */\n  public label: string;\n  /** Keyframe times in seconds */\n  public times: Float32Array;\n  /** Keyframe values; {@link TrackOptions#values} has the layout */\n  public values: Float32Array;\n  /** Interpolation algorithm used between keyframes */\n  public interpolation: InterpolationMode;\n  /** Number of numeric components in each sampled value */\n  public readonly valueSize: number = 0;\n  /**\n   * @param options - Keyframes, target label and value size\n   */\n  constructor(options: TrackOptions) {\n    this.label = options.label;\n    this.times = options.times instanceof Float32Array ? options.times : new Float32Array(options.times);\n    this.values = options.values instanceof Float32Array ? options.values : new Float32Array(options.values);\n    this.interpolation = options.interpolation || 'LINEAR';\n    this.valueSize = options.valueSize ?? 1;\n  }\n\n  /**\n   * Blends a freshly sampled value into a running weighted average\n   *\n   * The player calls it every frame while two or more playing states drive the same property.\n   * Override it where a component-wise lerp is wrong for the value, as {@link QuaternionTrack} does.\n   * @param values - The running weighted average, updated in place\n   * @param sample - The freshly evaluated value to blend in\n   * @param t - Blend factor for `sample` against `values`\n   */\n  public blendInto(values: Float32Array, sample: Float32Array, t: number): void {\n    const size = this.valueSize;\n\n    for (let k = 0; k < size; k++) {\n      values[k] += (sample[k] - values[k]) * t;\n    }\n  }\n\n  /**\n   * Samples the track at a time, holding the first or last keyframe outside their range\n   * @param time - Time in seconds\n   * @param index - Keyframe index this returned last time, which shortens the search; `0` always works\n   * @param target - Receives `valueSize` numbers\n   * @returns The keyframe index to pass back as `index` next time\n   */\n  public evaluate(time: number, index: number, target: Float32Array | number[]): number {\n    const times = this.times;\n    const values = this.values;\n    const len = times.length;\n    const valueSize = this.valueSize;\n\n    if (time <= times[0]) {\n      if (this.interpolation === 'CUBICSPLINE') {\n        const firstValueOffset = valueSize;\n        for (let i = 0; i < valueSize; i++) target[i] = values[firstValueOffset + i];\n      } else {\n        for (let i = 0; i < valueSize; i++) target[i] = values[i];\n      }\n      return 0;\n    }\n\n    if (time >= times[len - 1]) {\n      if (this.interpolation === 'CUBICSPLINE') {\n        const lastValueOffset = (len - 1) * 3 * valueSize + valueSize;\n        for (let i = 0; i < valueSize; i++) target[i] = values[lastValueOffset + i];\n      } else {\n        const offset = (len - 1) * valueSize;\n        for (let i = 0; i < valueSize; i++) target[i] = values[offset + i];\n      }\n      return len - 2;\n    }\n\n    if (times[index] > time) index = bisectKeyframe(times, time, index);\n    while (index < len - 1 && times[index + 1] <= time) index++;\n\n    const nextIndex = index + 1;\n\n    if (this.interpolation === 'STEP') {\n      const offset = index * valueSize;\n      for (let i = 0; i < valueSize; i++) target[i] = values[offset + i];\n      return index;\n    }\n\n    const t1 = times[index];\n    const t2 = times[nextIndex];\n    const duration = t2 - t1;\n    const t = (time - t1) / duration;\n\n    this.interpolate(index, nextIndex, t, duration, target);\n\n    return index;\n  }\n\n  /**\n   * Writes the value between two keyframes for `'LINEAR'` and `'CUBICSPLINE'`; {@link Track#evaluate} handles `'STEP'`\n   * @param index - Keyframe at or before the sample time\n   * @param nextIndex - Keyframe after it\n   * @param t - How far the sample sits between the two, from 0 to 1\n   * @param duration - Seconds between the two keyframes, which scales the cubic tangents\n   * @param target - Receives `valueSize` numbers\n   */\n  protected interpolate(\n    index: number,\n    nextIndex: number,\n    t: number,\n    duration: number,\n    target: Float32Array | number[],\n  ): void {\n    const values = this.values;\n    const valueSize = this.valueSize;\n\n    if (this.interpolation === 'CUBICSPLINE') {\n      const stride = valueSize * 3;\n      const offset1 = index * stride;\n      const offset2 = nextIndex * stride;\n\n      const t2 = t * t;\n      const t3 = t2 * t;\n\n      const s2 = 3 * t2 - 2 * t3;\n      const s3 = t3 - t2;\n      const s0 = 1 - s2;\n      const s1 = s3 - t2 + t;\n\n      for (let i = 0; i < valueSize; i++) {\n        const p0 = values[offset1 + valueSize + i];\n        const m0 = values[offset1 + valueSize * 2 + i] * duration;\n        const m1 = values[offset2 + i] * duration;\n        const p1 = values[offset2 + valueSize + i];\n\n        target[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;\n      }\n    } else {\n      const offset1 = index * valueSize;\n      const offset2 = nextIndex * valueSize;\n\n      for (let i = 0; i < valueSize; i++) {\n        const v1 = values[offset1 + i];\n        const v2 = values[offset2 + i];\n        target[i] = v1 + (v2 - v1) * t;\n      }\n    }\n  }\n}\n","import { Track } from './Track';\nimport type { TrackOptions } from './Track';\n\n/**\n * Track for a number property, such as a node's `x` or a number field on your own subclass\n * @category animation\n * @advanced\n */\nexport class NumberTrack extends Track {\n  /**\n   * @param options - Keyframes and target label\n   */\n  constructor(options: Omit<TrackOptions, 'valueSize'>) {\n    super({ ...options, valueSize: 1 });\n  }\n\n  /**\n   * Blends a sample in with the single-component lerp unrolled\n   * @param values - The running weighted average, updated in place\n   * @param sample - The freshly evaluated value to blend in\n   * @param t - Blend factor for `sample` against `values`\n   */\n  public override blendInto(values: Float32Array, sample: Float32Array, t: number): void {\n    values[0] += (sample[0] - values[0]) * t;\n  }\n}\n","import { Quaternion } from '../../math/rotation/Quaternion';\nimport { Track } from './Track';\nimport type { TrackOptions } from './Track';\n\n/**\n * Track for a rotation stored as a quaternion, such as a node's `quaternion`\n *\n * It slerps `'LINEAR'` keyframes rather than blending each component, and renormalises\n * `'CUBICSPLINE'` samples to unit length.\n * @category animation\n * @advanced\n */\nexport class QuaternionTrack extends Track {\n  /**\n   * @param options - Keyframes and target label\n   */\n  constructor(options: Omit<TrackOptions, 'valueSize'>) {\n    super({ ...options, valueSize: 4 });\n  }\n\n  /**\n   * Blends a sample in along the shortest arc, negating it first when it sits in the opposite\n   * hemisphere from the running average, so the blend doesn't cancel toward zero\n   * @param values - The running weighted average, updated in place\n   * @param sample - The freshly evaluated quaternion to blend in\n   * @param t - Blend factor for `sample` against `values`\n   */\n  public override blendInto(values: Float32Array, sample: Float32Array, t: number): void {\n    const v0 = values[0];\n    const v1 = values[1];\n    const v2 = values[2];\n    const v3 = values[3];\n\n    let s0 = sample[0];\n    let s1 = sample[1];\n    let s2 = sample[2];\n    let s3 = sample[3];\n\n    if (v0 * s0 + v1 * s1 + v2 * s2 + v3 * s3 < 0) {\n      s0 = -s0;\n      s1 = -s1;\n      s2 = -s2;\n      s3 = -s3;\n    }\n\n    values[0] = v0 + (s0 - v0) * t;\n    values[1] = v1 + (s1 - v1) * t;\n    values[2] = v2 + (s2 - v2) * t;\n    values[3] = v3 + (s3 - v3) * t;\n  }\n\n  protected interpolate(\n    index: number,\n    nextIndex: number,\n    t: number,\n    duration: number,\n    target: Float32Array | number[],\n  ): void {\n    if (this.interpolation === 'CUBICSPLINE') {\n      super.interpolate(index, nextIndex, t, duration, target);\n\n      const x = target[0];\n      const y = target[1];\n      const z = target[2];\n      const w = target[3];\n      const invLen = 1.0 / Math.sqrt(x * x + y * y + z * z + w * w);\n      target[0] *= invLen;\n      target[1] *= invLen;\n      target[2] *= invLen;\n      target[3] *= invLen;\n    } else {\n      Quaternion.slerpFlat(\n        target as number[],\n        0,\n        this.values as unknown as number[],\n        index * 4,\n        this.values as unknown as number[],\n        nextIndex * 4,\n        t,\n      );\n    }\n  }\n}\n","import { Track } from './Track';\nimport type { TrackOptions } from './Track';\n\n/**\n * Track for a three-component vector property, such as a node's `position` or `scale`\n * @category animation\n * @advanced\n */\nexport class Vector3Track extends Track {\n  /**\n   * @param options - Keyframes and target label\n   */\n  constructor(options: Omit<TrackOptions, 'valueSize'>) {\n    super({ ...options, valueSize: 3 });\n  }\n\n  /**\n   * Blends a sample in with the three-wide lerp unrolled\n   * @param values - The running weighted average, updated in place\n   * @param sample - The freshly evaluated value to blend in\n   * @param t - Blend factor for `sample` against `values`\n   */\n  public override blendInto(values: Float32Array, sample: Float32Array, t: number): void {\n    values[0] += (sample[0] - values[0]) * t;\n    values[1] += (sample[1] - values[1]) * t;\n    values[2] += (sample[2] - values[2]) * t;\n  }\n\n  /**\n   * Writes the value between two keyframes with the three-wide `'LINEAR'` lerp unrolled\n   * @param index - Keyframe at or before the sample time\n   * @param nextIndex - Keyframe after it\n   * @param t - How far the sample sits between the two, from 0 to 1\n   * @param duration - Seconds between the two keyframes, which scales the cubic tangents\n   * @param target - Receives three numbers\n   */\n  protected override interpolate(\n    index: number,\n    nextIndex: number,\n    t: number,\n    duration: number,\n    target: Float32Array | number[],\n  ): void {\n    if (this.interpolation === 'CUBICSPLINE') {\n      super.interpolate(index, nextIndex, t, duration, target);\n\n      return;\n    }\n\n    const values = this.values;\n    const a = index * 3;\n    const b = nextIndex * 3;\n    const a0 = values[a];\n    const a1 = values[a + 1];\n    const a2 = values[a + 2];\n\n    target[0] = a0 + (values[b] - a0) * t;\n    target[1] = a1 + (values[b + 1] - a1) * t;\n    target[2] = a2 + (values[b + 2] - a2) * t;\n  }\n}\n","import { checkExtension, CubeTexture, ExtensionType, path } from 'pixi.js';\nimport type { Loader, LoaderParser, ResolvedAsset, Texture } from 'pixi.js';\n\nconst FACE_KEYS = ['right', 'left', 'top', 'bottom', 'front', 'back'] as const;\n\ntype CubemapFaceKey = (typeof FACE_KEYS)[number];\ntype CubemapJson = Record<CubemapFaceKey, string>;\n\n/**\n * Loads a `.cubemap` JSON file as a {@link CubeTexture}\n *\n * The JSON names an image for each of the six faces, relative to the `.cubemap` file:\n *\n * ```json\n * {\n *   \"right\": \"specular_posx.jpg\",\n *   \"left\":  \"specular_negx.jpg\",\n *   \"top\":   \"specular_posy.jpg\",\n *   \"bottom\":\"specular_negy.jpg\",\n *   \"front\": \"specular_posz.jpg\",\n *   \"back\":  \"specular_negz.jpg\"\n * }\n * ```\n *\n * `@pixi/3d` registers it with `Assets` on import. `Assets.unload(url)` destroys the cube and\n * unloads its six images from the loader's cache, even when another loaded asset still uses one.\n * @example\n * ```ts\n * import { Assets } from 'pixi.js';\n * import '@pixi/3d';\n *\n * const env = await Assets.load<CubeTexture>('environment.cubemap');\n * view3d.environment = env;\n * ```\n * @category assets\n * @advanced\n */\nexport const loadCubemap = {\n  extension: {\n    type: ExtensionType.LoadParser,\n    name: 'loadCubemap',\n  },\n  // oxlint-disable-next-line typescript/no-deprecated -- pixi's Loader._validateParsers keys parsers by name too, and reports an id conflict for each parser after the first that leaves it out\n  name: 'loadCubemap',\n  id: 'cubemap',\n\n  test(url: string) {\n    return checkExtension(url, '.cubemap');\n  },\n\n  async load(url: string, _resolvedAsset?: ResolvedAsset, loader?: Loader) {\n    const response = await fetch(url);\n    const json: CubemapJson = await response.json();\n    const basePath = url.substring(0, url.lastIndexOf('/') + 1);\n\n    const faceEntries = await Promise.all(\n      FACE_KEYS.map(async (key) => {\n        const src = basePath + json[key];\n        const texture: Texture = await loader!.load({ src, parser: 'texture' });\n\n        return [key, texture] as const;\n      }),\n    );\n\n    const faces = Object.fromEntries(faceEntries) as Record<CubemapFaceKey, Texture>;\n\n    const filename = path.basename(url, '.cubemap');\n\n    return CubeTexture.from({ faces, label: filename });\n  },\n\n  /**\n   * Destroys the cube before unloading its faces, so it has stopped listening to them by then\n   * @param cubeTexture - The cube texture `load` returned\n   * @param _resolvedAsset - Unused\n   * @param loader - The loader that cached the face textures\n   */\n  async unload(cubeTexture: CubeTexture, _resolvedAsset?: ResolvedAsset, loader?: Loader) {\n    const faces = cubeTexture.source.faces;\n    const faceUrls = FACE_KEYS.map((key) => faces[key]._sourceOrigin);\n\n    cubeTexture.destroy(true);\n    await loader!.unload(faceUrls);\n  },\n} satisfies LoaderParser<CubeTexture>;\n","/** @internal */\nexport const GLTF_SEMANTIC_TO_ATTRIBUTE: Record<string, string> = {\n  POSITION: 'positions',\n  NORMAL: 'normals',\n  TEXCOORD_0: 'uvs',\n  JOINTS_0: 'joints',\n  WEIGHTS_0: 'weights',\n  TANGENT: 'tangents',\n  COLOR_0: 'colors',\n  COLOR_1: 'colors1',\n};\n","import type { TypedArray } from 'pixi.js';\n\n/**\n * Widens VEC3 colours to RGBA with an opaque alpha, as `Geometry3D` reads four per vertex\n * @param data - Colour data\n * @param components - Components per vertex in `data`; anything but 3 returns `data` unchanged\n * @internal\n */\nexport function widenColorToRgba(data: TypedArray, components: number): TypedArray {\n  if (components !== 3) return data;\n\n  const Ctor = data.constructor as new (len: number) => TypedArray;\n  const vertexCount = data.length / 3;\n  const out = new Ctor(vertexCount * 4);\n  const opaque = data instanceof Float32Array ? 1 : data instanceof Uint8Array ? 255 : 65535;\n\n  for (let i = 0; i < vertexCount; i++) {\n    const src = i * 3;\n    const dst = i * 4;\n    out[dst] = data[src];\n    out[dst + 1] = data[src + 1];\n    out[dst + 2] = data[src + 2];\n    out[dst + 3] = opaque;\n  }\n\n  return out;\n}\n","const code = \"(function(){let e,t;async function n(e,t){let n=new URL(e,self.location.origin).href,r=new URL(t,self.location.origin).href;importScripts(n);let i=await fetch(r).then(e=>{if(!e.ok)throw Error(`Failed to fetch Draco WASM: ${e.status} ${e.statusText}`);return e.arrayBuffer()});return await self.DracoDecoderModule({wasmBinary:i})}let r={5120:{ctor:Int8Array,bytes:1,dtKey:`DT_INT8`},5121:{ctor:Uint8Array,bytes:1,dtKey:`DT_UINT8`},5122:{ctor:Int16Array,bytes:2,dtKey:`DT_INT16`},5123:{ctor:Uint16Array,bytes:2,dtKey:`DT_UINT16`},5125:{ctor:Uint32Array,bytes:4,dtKey:`DT_UINT32`},5126:{ctor:Float32Array,bytes:4,dtKey:`DT_FLOAT32`}};async function i(n,i){if(!e)throw Error(`Draco decoder not initialized`);let a=await e;t||=new a.Decoder;let o=t,s=new a.DecoderBuffer,c=new a.Mesh,l=0;try{s.Init(new Int8Array(n),n.byteLength);let e=o.DecodeBufferToMesh(s,c);if(!e.ok())throw Error(`Draco decode failed: ${e.error_msg()}`);let t=c.num_faces()*3,u=c.num_points(),d=u<=65535,f=d?2:4;l=a._malloc(t*f),d?o.GetTrianglesUInt16Array(c,t*2,l):o.GetTrianglesUInt32Array(c,t*4,l);let p=new(d?Uint16Array:Uint32Array)(a.HEAPU8.buffer,l,t).slice();a._free(l),l=0;let m={},h=[p.buffer],g=Object.keys(i);for(let e=0;e<g.length;e++){let t=g[e],{dracoId:n,componentType:s}=i[t],d=r[s];if(!d)throw Error(`Unsupported Draco componentType: ${s}`);let f=o.GetAttributeByUniqueId(c,n);if(!f)throw Error(`Draco attribute not found for uniqueId ${n}`);let p=u*f.num_components(),_=p*d.bytes;l=a._malloc(_),o.GetAttributeDataArrayForAllPoints(c,f,a[d.dtKey],_,l);let v=new d.ctor(a.HEAPU8.buffer,l,p).slice();a._free(l),l=0,m[t]=v,h.push(v.buffer)}return{indices:p,attributes:m,transferables:h}}finally{l&&a._free(l),a.destroy(c),a.destroy(s)}}async function a(t){let r=t.data;if(r.type===`init`){e=n(r.jsUrl,r.wasmUrl);return}if(r.type===`decode`)try{let{indices:e,attributes:t,transferables:n}=await i(r.bufferViewBytes,r.attributeIds);self.postMessage({id:r.id,success:!0,indices:e,attributes:t},n)}catch(e){let t=e instanceof Error?e.message:String(e);self.postMessage({id:r.id,success:!1,error:t})}}self.onmessage=a})();\";\nlet url;\nexport default function workerUrl() {\n  return (url ??= URL.createObjectURL(new Blob([code], { type: 'text/javascript;charset=utf-8' })));\n}\n","/**\n * The URLs the Draco decoder loads from, by default Google's hosted build;\n * {@link setDracoDecoderPath} changes them\n * @category assets\n * @advanced\n */\nexport const dracoDecoderUrls = {\n  jsUrl: 'https://www.gstatic.com/draco/versioned/decoders/1.5.7/draco_wasm_wrapper.js',\n  wasmUrl: 'https://www.gstatic.com/draco/versioned/decoders/1.5.7/draco_decoder.wasm',\n};\n\n/**\n * Sets where the Draco decoder is fetched from, to self-host it\n *\n * Call it before loading the first Draco-compressed file, as the decoder loads once, on the first\n * decode. A relative URL resolves against the page's origin, not the page's path.\n * @example\n * ```ts\n * setDracoDecoderPath({\n *   jsUrl: '/draco/draco_wasm_wrapper.js',\n *   wasmUrl: '/draco/draco_decoder.wasm',\n * });\n * ```\n * @param config - Decoder JS and WASM URLs; a field left out keeps its current value\n * @category assets\n * @standard\n */\nexport function setDracoDecoderPath(config: Partial<typeof dracoDecoderUrls>): void {\n  Object.assign(dracoDecoderUrls, config);\n}\n","import { dracoDecoderUrls } from '../setDracoDecoderPath';\n\n/**\n * Mirrored by `AttributeRequest` in `draco.worker.ts`\n * @internal\n */\nexport interface DracoAttributeRequest {\n  dracoId: number;\n  componentType: number;\n}\n\ninterface DracoDecodeResult {\n  indices: Uint16Array | Uint32Array;\n  attributes: Record<string, ArrayBufferView>;\n}\n\n/** The reply `draco.worker.ts` posts for one decode */\ninterface DecodeMessage {\n  id: number;\n  success: boolean;\n  indices?: Uint16Array | Uint32Array;\n  attributes?: Record<string, ArrayBufferView>;\n  error?: string;\n}\n\n/**\n * A classic worker, as the decoder loads through `importScripts`. Keep the `new URL` form that starts\n * it: `scripts/build/inline-worker.mts` matches it to inline the worker\n */\nlet dracoWorker: Worker | undefined;\nlet nextId = 0;\nconst resolvers: Record<number, (value: DracoDecodeResult) => void> = {};\nconst rejecters: Record<number, (reason: Error) => void> = {};\n\n/** Rejects every pending decode and drops the worker, so the next decode starts a fresh one */\nfunction rejectAllInFlight(reason: string): void {\n  for (const id in rejecters) {\n    rejecters[id](new Error(`Draco worker: ${reason}`));\n    delete resolvers[id];\n    delete rejecters[id];\n  }\n  dracoWorker?.terminate();\n  dracoWorker = undefined;\n}\n\nfunction getDracoWorker(): Worker {\n  if (!dracoWorker) {\n    dracoWorker = new Worker(new URL('./draco.worker.ts', import.meta.url));\n\n    dracoWorker.onmessage = (event: MessageEvent<DecodeMessage>) => {\n      const { id, success, indices, attributes, error } = event.data;\n      if (success && indices && attributes) {\n        resolvers[id]?.({ indices, attributes });\n      } else {\n        rejecters[id]?.(new Error(error ?? 'Draco decode failed'));\n      }\n      delete resolvers[id];\n      delete rejecters[id];\n    };\n\n    dracoWorker.onerror = (event) => rejectAllInFlight(event.message || 'uncaught error');\n    dracoWorker.onmessageerror = () => rejectAllInFlight('message deserialization failed');\n\n    dracoWorker.postMessage({\n      type: 'init',\n      jsUrl: dracoDecoderUrls.jsUrl,\n      wasmUrl: dracoDecoderUrls.wasmUrl,\n    });\n  }\n\n  return dracoWorker;\n}\n\n/**\n * Transfers `bufferViewBytes` to the worker, so pass a copy to keep the bytes\n * @internal\n */\nexport function loadDracoOnWorker(\n  bufferViewBytes: ArrayBuffer,\n  attributeIds: Record<string, DracoAttributeRequest>,\n): Promise<DracoDecodeResult> {\n  const worker = getDracoWorker();\n  const id = nextId++;\n\n  return new Promise<DracoDecodeResult>((resolve, reject) => {\n    resolvers[id] = resolve;\n    rejecters[id] = reject;\n    worker.postMessage({ type: 'decode', id, bufferViewBytes, attributeIds }, [bufferViewBytes]);\n  });\n}\n","import type { TypedArray } from 'pixi.js';\n\nimport type { Geometry3DOptions } from '../../../../geometry/Geometry3D';\nimport { warnOnce } from '../../../../utils/warnOnce';\nimport type { GltfFormat } from '../GltfFormat';\nimport { GLTF_SEMANTIC_TO_ATTRIBUTE } from '../utils/gltfAttributeMap';\nimport { widenColorToRgba } from '../utils/widenColorToRgba';\nimport type { DracoAttributeRequest } from './worker/loadDracoOnWorker';\nimport { loadDracoOnWorker } from './worker/loadDracoOnWorker';\n\n/** @internal */\nexport async function decodeDracoPrimitive(\n  gltfRaw: GltfFormat,\n  buffers: ArrayBuffer[],\n  primitiveRaw: GltfFormat.MeshPrimitive,\n  dracoExt: GltfFormat.KHRDracoMeshCompression,\n): Promise<Partial<Geometry3DOptions>> {\n  const bufferView = gltfRaw.bufferViews![dracoExt.bufferView];\n  const sourceBuffer: ArrayBuffer = buffers[bufferView.buffer];\n  const start = bufferView.byteOffset ?? 0;\n  const bytes = sourceBuffer.slice(start, start + bufferView.byteLength);\n\n  const attributeIds: Record<string, DracoAttributeRequest> = {};\n  const semantics = Object.keys(dracoExt.attributes);\n  for (let i = 0; i < semantics.length; i++) {\n    const semantic = semantics[i];\n    const accessorIdx = primitiveRaw.attributes[semantic];\n    if (accessorIdx === undefined) continue;\n    const accessor = gltfRaw.accessors![accessorIdx];\n    attributeIds[semantic] = {\n      dracoId: dracoExt.attributes[semantic],\n      componentType: accessor.componentType,\n    };\n  }\n\n  const decoded = await loadDracoOnWorker(bytes, attributeIds);\n\n  const result: Record<string, unknown> = { indices: decoded.indices };\n  for (let i = 0; i < semantics.length; i++) {\n    const semantic = semantics[i];\n    if (!decoded.attributes[semantic]) continue;\n    const attributeName = GLTF_SEMANTIC_TO_ATTRIBUTE[semantic];\n    if (attributeName) {\n      const data = decoded.attributes[semantic] as TypedArray;\n      result[attributeName] =\n        attributeName === 'colors' || attributeName === 'colors1'\n          ? widenColorToRgba(data, gltfRaw.accessors![primitiveRaw.attributes[semantic]].type === 'VEC3' ? 3 : 4)\n          : data;\n    } else {\n      warnOnce(`pixijs-3d-custom-attribute-${semantic}`, `[@pixi/3d] custom attribute ${semantic} skipped`);\n    }\n  }\n\n  return result;\n}\n","import type { GltfFormat } from '../GltfFormat';\n\n// oxlint-disable-next-line typescript/consistent-type-imports\ntype MeshoptDecoder = typeof import('meshoptimizer/decoder').MeshoptDecoder;\n\nlet decoderPromise: Promise<MeshoptDecoder> | undefined;\n\n/** Imports `meshoptimizer/decoder` alone, as the package root also bundles the encoder and simplifier */\nfunction getDecoder(): Promise<MeshoptDecoder> {\n  if (!decoderPromise) {\n    decoderPromise = (async () => {\n      const { MeshoptDecoder } = await import('meshoptimizer/decoder');\n      await MeshoptDecoder.ready;\n      const poolSize = Math.max(1, Math.min((navigator.hardwareConcurrency ?? 4) - 1, 4));\n      MeshoptDecoder.useWorkers(poolSize);\n      return MeshoptDecoder;\n    })();\n  }\n\n  return decoderPromise;\n}\n\n/**\n * Keeps each view's `byteStride`, which interleaved accessors read. `normalizeMeshopt` relies on\n * this deleting each decoded view's extension entry\n * @param gltfRaw - Parsed glTF JSON, rewritten in place\n * @param buffers - By glTF buffer index; decoded views are appended\n * @internal\n */\nexport async function decodeMeshoptBufferViews(gltfRaw: GltfFormat, buffers: ArrayBuffer[]): Promise<void> {\n  const bufferViews = gltfRaw.bufferViews;\n  if (!bufferViews) return;\n\n  const decoder = await getDecoder();\n\n  await Promise.all(\n    bufferViews.map(async (bv) => {\n      const ext = bv.extensions?.EXT_meshopt_compression ?? bv.extensions?.KHR_meshopt_compression;\n      if (!ext) return;\n\n      const sourceBuffer: ArrayBuffer = buffers[ext.buffer];\n      const source = new Uint8Array(sourceBuffer, ext.byteOffset ?? 0, ext.byteLength);\n\n      const decoded = await decoder.decodeGltfBufferAsync(\n        ext.count,\n        ext.byteStride,\n        source,\n        ext.mode,\n        ext.filter ?? 'NONE',\n      );\n\n      const newIndex = buffers.length;\n      buffers.push(decoded.buffer as ArrayBuffer);\n      bv.buffer = newIndex;\n      bv.byteOffset = 0;\n      bv.byteLength = ext.count * ext.byteStride;\n\n      delete bv.extensions?.EXT_meshopt_compression;\n      delete bv.extensions?.KHR_meshopt_compression;\n    }),\n  );\n}\n","import type { GltfFormat } from '../GltfFormat';\nimport { decodeMeshoptBufferViews } from './decodeMeshoptBufferViews';\n\n/**\n * Compaction remaps only `bufferView.buffer`. That's enough while meshopt is the only extension that\n * names a buffer, as `decodeMeshoptBufferViews` deletes its entries\n * @param gltfRaw - Parsed glTF JSON, rewritten in place\n * @param buffers - By glTF buffer index; decoded and compacted in place\n * @internal\n */\nexport async function normalizeMeshopt(gltfRaw: GltfFormat, buffers: ArrayBuffer[]): Promise<void> {\n  const usesMeshopt =\n    gltfRaw.extensionsUsed?.includes('EXT_meshopt_compression') ||\n    gltfRaw.extensionsUsed?.includes('KHR_meshopt_compression');\n  if (!usesMeshopt) return;\n\n  await decodeMeshoptBufferViews(gltfRaw, buffers);\n\n  const bufferViews = gltfRaw.bufferViews;\n  if (!bufferViews) {\n    buffers.length = 0;\n    return;\n  }\n\n  const remap = new Map<number, number>();\n  const compacted: ArrayBuffer[] = [];\n  for (let i = 0; i < bufferViews.length; i++) {\n    const oldIdx = bufferViews[i].buffer;\n    if (!remap.has(oldIdx)) {\n      remap.set(oldIdx, compacted.length);\n      compacted.push(buffers[oldIdx]);\n    }\n  }\n\n  for (let i = 0; i < bufferViews.length; i++) {\n    bufferViews[i].buffer = remap.get(bufferViews[i].buffer)!;\n  }\n\n  buffers.length = 0;\n  for (let i = 0; i < compacted.length; i++) buffers.push(compacted[i]);\n}\n","import type { Texture } from 'pixi.js';\n\nimport type { Animation } from '../animation/Animation';\nimport { SHARED_DEFAULT_TEXTURES } from '../core/textures/DefaultTextures';\nimport type { Geometry3D } from '../geometry/Geometry3D';\nimport type { BaseMaterial3D } from '../materials/BaseMaterial3D';\nimport type { Scene3DDescriptor, Scene3DEntry } from './Scene3DDescriptor';\n\n/**\n * The geometries, materials, textures and animations loaded from a glTF or GLB file\n *\n * A source is a template: add `new Model3D(source)` to a view, never the source itself. Every model\n * spawned from one source shares its geometries, materials and textures, so a change to a source\n * material shows on every model that draws it. {@link Model3D#materials} gives one model materials\n * of its own.\n *\n * The plural lists (`textures`, `materials`, `geometries`) hold everything, by index in the file.\n * The singular records (`texture`, `material`, `geometry`) hold only what the file named.\n *\n * {@link loadGltf} lists the texture formats a file can use and the imports they need.\n * @example\n * ```ts\n * import { Assets } from 'pixi.js';\n * import { Model3D, Scene3DSource } from '@pixi/3d';\n *\n * const source = await Assets.load<Scene3DSource>('robot.glb');\n *\n * // Two models sharing the same geometry, materials and textures\n * const robotA = new Model3D(source);\n * const robotB = new Model3D(source);\n *\n * view3d.root.addChild(robotA, robotB);\n *\n * // Repaints both robots\n * source.material['Helmet'].baseColor = 0xff0000;\n * ```\n * @category assets\n * @standard\n */\nexport class Scene3DSource {\n  /**\n   * Every texture, by its index in the file\n   *\n   * Textures in the file that use the same image share one `Texture` and its style, so an entry can\n   * repeat. The file's samplers set the style, and glTF's defaults (repeat wrapping, linear\n   * filtering, mipmaps) fill whatever a sampler leaves out.\n   * @example\n   * ```ts\n   * for (const texture of source.textures) texture.source.style.maxAnisotropy = 8;\n   * ```\n   */\n  public readonly textures: Texture[] = [];\n\n  /**\n   * Every material, by its index in the file\n   *\n   * Unlit materials load as {@link FlatMaterial}, the rest as {@link Material3D}. When a mesh\n   * primitive names no material, the glTF default material, a white `Material3D` with `metallic` and\n   * `roughness` at 1, is added after the file's own.\n   * @example\n   * ```ts\n   * const pbrMaterials = source.materials.filter((material) => material instanceof Material3D);\n   * ```\n   */\n  public readonly materials: BaseMaterial3D[] = [];\n\n  /**\n   * Every mesh's geometries, by its index in the file: one per primitive of the mesh\n   * @example\n   * ```ts\n   * const [body, glass] = source.geometries[0];\n   * ```\n   */\n  public readonly geometries: Geometry3D[][] = [];\n\n  /**\n   * The textures the file names, keyed by name\n   * @example\n   * ```ts\n   * const logo = new Sprite(source.texture['Logo']);\n   * ```\n   */\n  public readonly texture: Record<string, Texture> = {};\n\n  /**\n   * The materials the file names, keyed by name\n   * @example\n   * ```ts\n   * source.material['Paint'].baseColor = 0x3366ff;\n   * ```\n   */\n  public readonly material: Record<string, BaseMaterial3D> = {};\n\n  /**\n   * The geometry of each mesh the file names, keyed by mesh name\n   *\n   * A mesh with several primitives maps to its first; {@link Scene3DSource#geometries} has them all.\n   * @example\n   * ```ts\n   * const rock = new Mesh3D({ geometry: source.geometry['Rock'], material: new Material3D() });\n   * ```\n   */\n  public readonly geometry: Record<string, Geometry3D> = {};\n\n  /**\n   * Animation clips keyed by name; an unnamed clip is keyed `anim_<index>`\n   * @example\n   * ```ts\n   * const walkSeconds = source.animations['Walk'].duration;\n   * ```\n   */\n  public readonly animations: Record<string, Animation> = {};\n\n  /**\n   * The scenes the file names, keyed by name\n   *\n   * Pass a name as {@link Model3DOptions#scene} to spawn that scene instead of the default one.\n   * @example\n   * ```ts\n   * const showroom = new Model3D({ source, scene: 'Showroom' });\n   * ```\n   */\n  public readonly scene: Record<string, Scene3DEntry> = {};\n\n  /**\n   * Whether {@link Scene3DSource#destroy} has run\n   * @example\n   * ```ts\n   * if (!source.destroyed) view3d.root.addChild(new Model3D(source));\n   * ```\n   */\n  public destroyed = false;\n\n  /** @internal */\n  public readonly _descriptor: Scene3DDescriptor;\n\n  /**\n   * Cache keys of the file's images, which the loader's `unload` releases\n   * @internal\n   */\n  public readonly _imageUrls: string[] = [];\n\n  /** @internal */\n  constructor(descriptor: Scene3DDescriptor) {\n    this._descriptor = descriptor;\n\n    if (descriptor.scenes) {\n      descriptor.scenes.forEach((scene) => {\n        if (scene.name) {\n          this.scene[scene.name] = scene;\n        }\n      });\n    }\n  }\n\n  /**\n   * Destroys every geometry, material and texture the source holds; a second call does nothing\n   *\n   * Every {@link Model3D} spawned from this source draws these resources, so destroy or stop\n   * rendering those models first. For a source from `Assets.load`, call `Assets.unload(url)`\n   * instead. It destroys the source and also unloads every image the file referenced from the\n   * loader's cache, even when another loaded asset still uses one.\n   * @example\n   * ```ts\n   * const source = await Assets.load<Scene3DSource>('robot.glb');\n   * const robot = new Model3D(source);\n   *\n   * // Later, once no model from it is rendered any more\n   * robot.destroy();\n   * await Assets.unload('robot.glb'); // calls source.destroy()\n   * ```\n   */\n  public destroy(): void {\n    if (this.destroyed) return;\n    this.destroyed = true;\n\n    for (const primitives of this.geometries) {\n      if (primitives) for (const geometry of primitives) geometry.destroy(true);\n    }\n\n    for (const material of this.materials) material?.destroy();\n\n    for (const texture of this.textures) {\n      if (texture && !texture.destroyed && !SHARED_DEFAULT_TEXTURES.has(texture)) texture.destroy(true);\n    }\n\n    (this.geometries as Geometry3D[][] | null) = null;\n    (this.materials as BaseMaterial3D[] | null) = null;\n    (this.textures as Texture[] | null) = null;\n    (this._imageUrls as string[] | null) = null;\n    (this.geometry as Record<string, Geometry3D> | null) = null;\n    (this.material as Record<string, BaseMaterial3D> | null) = null;\n    (this.texture as Record<string, Texture> | null) = null;\n    (this.animations as Record<string, Animation> | null) = null;\n    (this.scene as Record<string, Scene3DEntry> | null) = null;\n  }\n}\n","import type { VertexFormat } from 'pixi.js';\n\nimport type { GltfFormat } from '../GltfFormat';\n\nconst GL_BYTE = 5120;\nconst GL_UNSIGNED_BYTE = 5121;\nconst GL_SHORT = 5122;\nconst GL_UNSIGNED_SHORT = 5123;\nconst GL_FLOAT = 5126;\n\nconst TYPE_TO_COMPONENTS: Record<string, 1 | 2 | 3 | 4> = {\n  SCALAR: 1,\n  VEC2: 2,\n  VEC3: 3,\n  VEC4: 4,\n};\n\nconst COMPONENT_TYPE_TO_PREFIX: Record<number, { raw: string; normalized: string }> = {\n  [GL_FLOAT]: { raw: 'float32', normalized: 'float32' },\n  [GL_BYTE]: { raw: 'sint8', normalized: 'snorm8' },\n  [GL_UNSIGNED_BYTE]: { raw: 'uint8', normalized: 'unorm8' },\n  [GL_SHORT]: { raw: 'sint16', normalized: 'snorm16' },\n  [GL_UNSIGNED_SHORT]: { raw: 'uint16', normalized: 'unorm16' },\n};\n\n/** @internal */\nexport const NORMALIZED_SCALE: Record<number, number> = {\n  [GL_BYTE]: 1 / 127,\n  [GL_UNSIGNED_BYTE]: 1 / 255,\n  [GL_SHORT]: 1 / 32767,\n  [GL_UNSIGNED_SHORT]: 1 / 65535,\n};\n\n/**\n * Maps an integer VEC3 to `x4`, as WebGPU has no 3-component 8- or 16-bit format, so\n * `accessorToAttribute` in `processMeshes.ts` pads the data\n * @internal\n */\nexport function accessorToVertexFormat(accessor: GltfFormat.Accessor): VertexFormat {\n  const components = TYPE_TO_COMPONENTS[accessor.type];\n  if (!components || components === 1) {\n    throw new Error(`[accessorToVertexFormat] Unsupported accessor type: ${accessor.type}`);\n  }\n\n  const prefix = COMPONENT_TYPE_TO_PREFIX[accessor.componentType];\n  if (!prefix) {\n    throw new Error(`[accessorToVertexFormat] Unsupported componentType: ${accessor.componentType}`);\n  }\n\n  const isFloat = accessor.componentType === GL_FLOAT;\n  const suffix = components === 3 ? (isFloat ? 'x3' : 'x4') : `x${components}`;\n  const stem = accessor.normalized ? prefix.normalized : prefix.raw;\n\n  return `${stem}${suffix}` as VertexFormat;\n}\n","import type { GltfFormat } from '../GltfFormat';\n\ntype Component = 5120 | 5121 | 5122 | 5123 | 5125 | 5126;\n\ntype ComponentArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Uint32Array | Float32Array;\n\ninterface ComponentArrayConstructor {\n  new (length: number): ComponentArray;\n  new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): ComponentArray;\n}\n\nconst TypedMap: Record<Component, ComponentArrayConstructor> = {\n  5120: Int8Array,\n  5121: Uint8Array,\n  5122: Int16Array,\n  5123: Uint16Array,\n  5125: Uint32Array,\n  5126: Float32Array,\n};\n\nconst BYTES_PER: Record<Component, number> = {\n  5120: 1,\n  5121: 1,\n  5122: 2,\n  5123: 2,\n  5125: 4,\n  5126: 4,\n};\n\nconst NUM_COMPONENTS = {\n  SCALAR: 1,\n  VEC2: 2,\n  VEC3: 3,\n  VEC4: 4,\n  MAT2: 4,\n  MAT3: 9,\n  MAT4: 16,\n} as const;\n\n/**\n * Returns tightly packed data as a view of the file's buffer unless `copy` is set; interleaved and\n * sparse data always come back as new arrays\n * @internal\n */\nexport function getBuffer(\n  gltfRaw: GltfFormat,\n  buffers: ArrayBuffer[],\n  accessorIndex: number,\n  copy = false,\n): ArrayBufferView {\n  const accessor = gltfRaw.accessors![accessorIndex];\n\n  if (accessor.sparse) {\n    return readSparseAccessor(gltfRaw, buffers, accessorIndex);\n  }\n\n  const bufferView = gltfRaw.bufferViews![accessor.bufferView!];\n  const arrayBuffer: ArrayBuffer = buffers[bufferView.buffer];\n\n  const componentType = accessor.componentType as Component;\n  const TypeClass = TypedMap[componentType];\n  const numComponents = NUM_COMPONENTS[accessor.type as keyof typeof NUM_COMPONENTS];\n\n  const baseOffsetBytes = (bufferView.byteOffset ?? 0) + (accessor.byteOffset ?? 0);\n  const bytesPerComponent = BYTES_PER[componentType];\n  const elementSizeBytes = numComponents * bytesPerComponent;\n  const strideBytes = bufferView.byteStride ?? elementSizeBytes;\n  const count = accessor.count;\n\n  if (strideBytes === elementSizeBytes) {\n    const view = new TypeClass(arrayBuffer, baseOffsetBytes, count * numComponents);\n    return copy ? view.slice() : view;\n  }\n\n  const srcTyped = new TypeClass(arrayBuffer);\n  const srcBase = baseOffsetBytes / bytesPerComponent;\n  const strideElements = strideBytes / bytesPerComponent;\n  const out = new TypeClass(count * numComponents);\n\n  let dst = 0;\n  for (let i = 0; i < count; i++) {\n    const srcRow = srcBase + i * strideElements;\n    for (let c = 0; c < numComponents; c++) {\n      out[dst++] = srcTyped[srcRow + c];\n    }\n  }\n\n  return out;\n}\n\n/** VEC3, the usual sparse morph target, gets its own unrolled loop for speed */\nfunction readSparseAccessor(gltfRaw: GltfFormat, buffers: ArrayBuffer[], accessorIndex: number): ArrayBufferView {\n  const accessor = gltfRaw.accessors![accessorIndex];\n  const sparse = accessor.sparse!;\n  const componentType = accessor.componentType as Component;\n  const TypeClass = TypedMap[componentType];\n  const numComponents = NUM_COMPONENTS[accessor.type as keyof typeof NUM_COMPONENTS];\n  const total = accessor.count * numComponents;\n\n  const out = new TypeClass(total);\n  if (accessor.bufferView !== undefined) {\n    const bufferView = gltfRaw.bufferViews![accessor.bufferView];\n    const baseOffset = (bufferView.byteOffset ?? 0) + (accessor.byteOffset ?? 0);\n    out.set(new TypeClass(buffers[bufferView.buffer], baseOffset, total));\n  }\n\n  const indicesView = gltfRaw.bufferViews![sparse.indices.bufferView];\n  const IndexClass = TypedMap[sparse.indices.componentType as Component];\n  const indices = new IndexClass(\n    buffers[indicesView.buffer],\n    (indicesView.byteOffset ?? 0) + (sparse.indices.byteOffset ?? 0),\n    sparse.count,\n  );\n  const valuesView = gltfRaw.bufferViews![sparse.values.bufferView];\n  const values = new TypeClass(\n    buffers[valuesView.buffer],\n    (valuesView.byteOffset ?? 0) + (sparse.values.byteOffset ?? 0),\n    sparse.count * numComponents,\n  );\n\n  if (numComponents === 3) {\n    for (let i = 0; i < sparse.count; i++) {\n      const d = indices[i] * 3;\n      const s = i * 3;\n      out[d] = values[s];\n      out[d + 1] = values[s + 1];\n      out[d + 2] = values[s + 2];\n    }\n  } else {\n    for (let i = 0; i < sparse.count; i++) {\n      const dstBase = indices[i] * numComponents;\n      const srcBase = i * numComponents;\n      for (let c = 0; c < numComponents; c++) out[dstBase + c] = values[srcBase + c];\n    }\n  }\n\n  return out;\n}\n","import { Animation } from '../../../../animation/Animation';\nimport { QuaternionTrack } from '../../../../animation/tracks/QuaternionTrack';\nimport { Track } from '../../../../animation/tracks/Track';\nimport type { InterpolationMode, TrackOptions } from '../../../../animation/tracks/Track';\nimport { Vector3Track } from '../../../../animation/tracks/Vector3Track';\nimport type { Scene3DSource } from '../../../Scene3DSource';\nimport type { GltfFormat } from '../GltfFormat';\nimport { NORMALIZED_SCALE } from '../utils/accessorToVertexFormat';\nimport { getBuffer } from '../utils/getBuffer';\n\nconst trackClassMap: Record<string, new (options: TrackOptions) => Track> = {\n  translation: Vector3Track,\n  rotation: QuaternionTrack,\n  scale: Vector3Track,\n};\n\nconst trackPathMap: Record<string, string> = {\n  translation: 'position',\n  rotation: 'quaternion',\n  scale: 'scale',\n  weights: 'weights',\n};\n\n/** @internal */\nexport function processAnimations(gltfRaw: GltfFormat, buffers: ArrayBuffer[], source: Scene3DSource) {\n  if (!gltfRaw.animations) return;\n\n  gltfRaw.animations.forEach((animation, index) => {\n    const tracks: Track[] = [];\n\n    animation.channels.forEach((channel) => {\n      const sampler = animation.samplers[channel.sampler];\n      const target = channel.target;\n\n      const track = createTrack(target, sampler, gltfRaw, buffers);\n\n      if (track) tracks.push(track);\n    });\n\n    const label = animation.name || `anim_${index}`;\n\n    source.animations[label] = new Animation({\n      label,\n      tracks,\n    });\n  });\n}\n\n/** Signed normalized values clamp at -1, as glTF's decode formula does */\nfunction getBufferAsFloat32(gltfRaw: GltfFormat, buffers: ArrayBuffer[], accessorIndex: number): Float32Array {\n  const raw = getBuffer(gltfRaw, buffers, accessorIndex);\n  if (raw instanceof Float32Array) return raw;\n\n  const accessor = gltfRaw.accessors![accessorIndex];\n  const typedRaw = raw as Int16Array | Uint16Array | Int8Array | Uint8Array;\n  const out = new Float32Array(typedRaw.length);\n\n  if (accessor.normalized === true) {\n    const scale = NORMALIZED_SCALE[accessor.componentType] ?? 1;\n    const isSigned = accessor.componentType === 5120 || accessor.componentType === 5122;\n\n    if (isSigned) {\n      for (let i = 0; i < typedRaw.length; i++) {\n        const v = typedRaw[i] * scale;\n        out[i] = v < -1 ? -1 : v;\n      }\n    } else {\n      for (let i = 0; i < typedRaw.length; i++) {\n        out[i] = typedRaw[i] * scale;\n      }\n    }\n  } else {\n    out.set(typedRaw);\n  }\n  return out;\n}\n\nfunction createTrack(\n  target: GltfFormat.AnimationChannelTarget,\n  sampler: GltfFormat.AnimationSampler,\n  gltfRaw: GltfFormat,\n  buffers: ArrayBuffer[],\n) {\n  const times = getBufferAsFloat32(gltfRaw, buffers, sampler.input);\n  const values = getBufferAsFloat32(gltfRaw, buffers, sampler.output);\n\n  const targetName = target.node!.toString();\n\n  const path = trackPathMap[target.path] ?? target.path;\n  const label = `${targetName}.${path}`;\n  const interpolation = (sampler.interpolation as InterpolationMode) ?? 'LINEAR';\n\n  if (target.path === 'weights') {\n    const componentsPerKeyframe = times.length > 0 ? values.length / times.length : 1;\n    const valueSize = interpolation === 'CUBICSPLINE' ? componentsPerKeyframe / 3 : componentsPerKeyframe;\n\n    return new Track({ label, times, values, interpolation, valueSize });\n  }\n\n  const TrackClass = trackClassMap[target.path] ?? Vector3Track;\n\n  return new TrackClass({\n    label,\n    times,\n    values,\n    interpolation,\n  });\n}\n","import { RAD_TO_DEG } from 'pixi.js';\n\nimport type { Scene3DCamera, Scene3DDescriptor } from '../../../Scene3DDescriptor';\nimport type { GltfFormat } from '../GltfFormat';\n\n/**\n * Drops `ymag` and `aspectRatio`, as the view's size sets the aspect; `xmag` is half the width, as\n * `orthographicSize` is\n * @internal\n */\nexport function processCameras(gltfRaw: GltfFormat, descriptor: Scene3DDescriptor): void {\n  if (!gltfRaw.cameras) {\n    descriptor.cameras = [];\n\n    return;\n  }\n\n  descriptor.cameras = gltfRaw.cameras.map((rawCamera): Scene3DCamera => {\n    if (rawCamera.type === 'perspective') {\n      const perspectiveData = rawCamera.perspective!;\n\n      return {\n        fov: perspectiveData.yfov * RAD_TO_DEG,\n        near: perspectiveData.znear,\n        far: perspectiveData.zfar,\n        mode: 0,\n      };\n    }\n\n    const orthographicData = rawCamera.orthographic!;\n\n    return {\n      orthographicSize: orthographicData.xmag,\n      near: orthographicData.znear,\n      far: orthographicData.zfar,\n      mode: 1,\n    };\n  });\n}\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * The cutout for `alphaMode: 'mask'`: discards fragments with alpha below the material's\n * `alphaCutoff` and makes the rest fully opaque\n *\n * List it after the bit that sets `alpha` from the base colour.\n * @category rendering\n * @advanced\n */\nexport const alphaMaskBit: ShaderBit = {\n  name: 'alphaMask',\n  bindings: {\n    material: {\n      alphaCutoff: 'f32',\n    },\n  },\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  if (alpha < material.alphaCutoff) {\n    discard;\n  }\n  alpha = 1.0;\n`,\n    },\n  },\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  if (alpha < material.alphaCutoff) discard;\n  alpha = 1.0;\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * Applies the material's {@link BaseMaterial3D#uvTransform} to the mesh UVs\n *\n * List it in a custom material's bits for `uvTransform` to work there.\n * @category rendering\n * @advanced\n */\nexport const uvTransformBit: ShaderBit = {\n  name: 'uvTransform',\n\n  bindings: {\n    material: {\n      uvOffset: 'vec2<f32>',\n      uvTransformRow0: 'vec4<f32>',\n    },\n  },\n\n  gpu: {\n    vertex: {\n      end: /*wgsl*/ `\n  let m = material.uvTransformRow0;\n  uv = vec2<f32>(m.x * uv.x + m.y * uv.y,\n                 m.z * uv.x + m.w * uv.y) + material.uvOffset;\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      end: /*glsl*/ `\n  vec4 m = material.uvTransformRow0;\n  uv = vec2(m.x * uv.x + m.y * uv.y,\n            m.z * uv.x + m.w * uv.y) + material.uvOffset;\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Declares `alphaCutoff` without reading it, so the struct, fixed at construction, already holds it\n * when `'mask'` mode adds `alphaMaskBit`\n * @internal\n */\nexport const flatMaterialBit: ShaderBit = {\n  name: 'flatMaterial',\n\n  textures: ['baseColor'],\n\n  bindings: {\n    material: {\n      baseColor: 'vec4<f32>',\n      displayBaseColor: 'vec4<f32>',\n      alphaCutoff: 'f32',\n    },\n  },\n\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  var baseColor = inputTint(material.baseColor, material.displayBaseColor);\n\n  let baseTex = sampleBaseColor(input.vUV);\n  baseColor *= vec4<f32>(decodeColor(baseTex.rgb / max(baseTex.a, 0.001)), baseTex.a);\n\n  albedo *= baseColor.rgb;\n  alpha *= baseColor.a;\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  vec4 baseColor = inputTint(material.baseColor, material.displayBaseColor);\n\n  vec4 baseTex = sampleBaseColor(vUV);\n  baseColor *= vec4(decodeColor(baseTex.rgb / max(baseTex.a, 0.001)), baseTex.a);\n\n  albedo *= baseColor.rgb;\n  alpha *= baseColor.a;\n`,\n    },\n  },\n};\n","import { alphaMaskBit } from '../../core/shader/bits/alphaMaskBit';\nimport { uvTransformBit } from '../../core/shader/bits/uvTransformBit';\nimport type { ShaderBit } from '../../core/shader/ShaderBit';\nimport { ShaderDescriptor } from '../../core/shader/ShaderDescriptor';\nimport type { View3D } from '../../scene/View3D';\nimport { BaseMaterial3D } from '../BaseMaterial3D';\nimport type { BaseMaterial3DOptions, ColorSpace } from '../BaseMaterial3D';\nimport { flatMaterialBit } from './bits/flatMaterialBit';\n\n/**\n * Options for {@link FlatMaterial}, the same as {@link BaseMaterial3DOptions}\n *\n * `extraBits` run after the base colour and texture and before the `'mask'` cutoff, so they see the\n * textured `albedo` and `alpha`, and the cutoff sees any alpha they write.\n * @example\n * ```ts\n * const options: FlatMaterialOptions = { baseColorTexture: iconTexture, alphaMode: 'mask' };\n * const icon = new FlatMaterial(options);\n * ```\n * @category materials\n * @standard\n */\nexport type FlatMaterialOptions = BaseMaterial3DOptions;\n\n/**\n * An unlit material that draws its base colour and texture with no lighting\n *\n * Lights, the view's environment and shadows leave it alone, which suits UI panels, icons, debug\n * drawing and anything baked. The view's exposure, fog and tone curve still apply: under the\n * default `toneMapping: 'none'` at exposure 1 it draws its colour and texture as authored,\n * multiplied the way a pixi sprite's tint is, while a curve such as `'aces'` shifts them.\n * @example\n * ```ts\n * const panel = new Mesh3D({\n *   geometry: new PlaneGeometry({ width: 2, height: 1 }),\n *   material: new FlatMaterial({ baseColorTexture: panelTexture }),\n * });\n * ```\n * @category materials\n * @standard\n */\nexport class FlatMaterial extends BaseMaterial3D {\n  /**\n   * `'display'`, since a flat material only multiplies its colours\n   * @advanced\n   */\n  public override colorSpace: ColorSpace = 'display';\n\n  /**\n   * `false`: a flat material takes no part in lighting\n   * @advanced\n   */\n  public override lit = false;\n\n  constructor(options: FlatMaterialOptions = {}) {\n    super(options);\n    this._descriptor = new ShaderDescriptor({});\n\n    const derivationBits = [flatMaterialBit, uvTransformBit, ...this.extraBits];\n    this._deriveLayoutFromBits(derivationBits, {\n      baseColor: options.baseColorTexture,\n      ...options.textures,\n    });\n  }\n\n  /**\n   * The shader descriptor for this material, the same in every view\n   * @param _view - Unused\n   * @advanced\n   */\n  public override getPrimaryDescriptor(_view: View3D): ShaderDescriptor {\n    if (!this._variantDirty) return this._descriptor!;\n\n    const bits: ShaderBit[] = [flatMaterialBit, uvTransformBit];\n    for (let i = 0; i < this.extraBits.length; i++) bits.push(this.extraBits[i]);\n    if (this._alphaMode === 'mask') bits.push(alphaMaskBit);\n\n    this._descriptor!.update({ bitsGpu: bits, bitsGl: bits });\n    this._variantDirty = false;\n\n    return this._descriptor!;\n  }\n}\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * The bitangent points the way `v` shrinks, to match glTF tangents, and the frame's handedness is\n * worked out per fragment, since which way window y runs depends on the backend and the target\n * @internal\n */\nexport const derivativeTangentFrameBit: ShaderBit = {\n  name: 'derivativeTangentFrame',\n\n  gpu: {\n    header: /*wgsl*/ `\nfn calculateTBN(surfaceNormal: vec3<f32>, position: vec3<f32>, texCoord: vec2<f32>) -> mat3x3<f32> {\n  let dp1 = dpdx(position);\n  let dp2 = dpdy(position);\n  let duv1 = dpdx(texCoord);\n  let duv2 = dpdy(texCoord);\n\n  let dp2perp = cross(dp2, surfaceNormal);\n  let dp1perp = cross(surfaceNormal, dp1);\n  let tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n  let bitangent = -(dp2perp * duv1.y + dp1perp * duv2.y);\n\n  let invmax = inverseSqrt(max(dot(tangent, tangent), dot(bitangent, bitangent)));\n  let scale = select(invmax, -invmax, dot(dp1, dp2perp) < 0.0);\n  return mat3x3<f32>(tangent * scale, bitangent * scale, surfaceNormal);\n}\n`,\n  },\n\n  gl: {\n    fragment: {\n      header: /*glsl*/ `\nmat3 calculateTBN(highp vec3 surfaceNormal, highp vec3 position, highp vec2 texCoord) {\n  highp vec3 dp1 = dFdx(position);\n  highp vec3 dp2 = dFdy(position);\n  highp vec2 duv1 = dFdx(texCoord);\n  highp vec2 duv2 = dFdy(texCoord);\n\n  highp vec3 dp2perp = cross(dp2, surfaceNormal);\n  highp vec3 dp1perp = cross(surfaceNormal, dp1);\n  highp vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n  highp vec3 bitangent = -(dp2perp * duv1.y + dp1perp * duv2.y);\n\n  highp float invmax = inversesqrt(max(dot(tangent, tangent), dot(bitangent, bitangent)));\n  highp float scale = dot(dp1, dp2perp) < 0.0 ? -invmax : invmax;\n  return mat3(tangent * scale, bitangent * scale, surfaceNormal);\n}\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * Declares the constants `PI` and `INV_PI` for a bit that lists it in `requires`\n *\n * The lighting of {@link Material3D} and {@link PhongMaterial} requires it already, so a bit for\n * either must not declare its own `PI` or `INV_PI`: the second declaration fails the compile.\n * @example\n * ```ts\n * const ringsBit: ShaderBit = {\n *   name: 'rings',\n *   requires: [mathConstantsBit],\n *   gpu: { fragment: { material: 'albedo *= 0.75 + 0.25 * cos(input.vUV.x * 8.0 * PI);' } },\n *   gl: { fragment: { material: 'albedo *= 0.75 + 0.25 * cos(vUV.x * 8.0 * PI);' } },\n * };\n * ```\n * @category rendering\n * @advanced\n */\nexport const mathConstantsBit: ShaderBit = {\n  name: 'mathConstants',\n\n  gpu: {\n    header: /*wgsl*/ `\nconst PI: f32 = 3.14159265359;\nconst INV_PI: f32 = 0.31830988618;\n`,\n  },\n\n  gl: {\n    header: /*glsl*/ `\nconst float PI = 3.14159265359;\nconst float INV_PI = 0.31830988618;\n`,\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\nimport { derivativeTangentFrameBit } from './derivativeTangentFrameBit';\nimport { mathConstantsBit } from './mathConstantsBit';\n\n/**\n * Builds the frame on the geometric normal, since the mapped one makes the grain wobble per texel;\n * the lobes replace `pbrLightingBit`'s specular and read its locals\n */\nfunction createAnisotropyBit(withTexture: boolean, withVertexTangent: boolean): ShaderBit {\n  const name = `anisotropy${withTexture ? ':texture' : ''}${withVertexTangent ? ':tangent' : ''}`;\n\n  const gpuSource = withTexture\n    ? /*wgsl*/ `\n  let anisoSample = sampleAnisotropy(input.vUV);\n  let anisoDirRaw = anisoSample.rg * 2.0 - 1.0;\n  let anisoTexStrength = anisoSample.b;\n`\n    : /*wgsl*/ `\n  let anisoDirRaw = vec2<f32>(1.0, 0.0);\n  let anisoTexStrength = 1.0;\n`;\n\n  const glSource = withTexture\n    ? /*glsl*/ `\n  vec4 anisoSample = sampleAnisotropy(vUV);\n  vec2 anisoDirRaw = anisoSample.rg * 2.0 - 1.0;\n  float anisoTexStrength = anisoSample.b;\n`\n    : /*glsl*/ `\n  vec2 anisoDirRaw = vec2(1.0, 0.0);\n  float anisoTexStrength = 1.0;\n`;\n\n  const gpuFrame = withVertexTangent\n    ? /*wgsl*/ `\n  let anisoTw = normalize(input.vAnisoTangent);\n  let anisoBw = normalize(input.vAnisoBitangent);\n  let anisoT = normalize(anisoDir.x * anisoTw + anisoDir.y * anisoBw);\n`\n    : /*wgsl*/ `\n  let anisoTBN = calculateTBN(anisoGeoN, input.vPosition, input.vUV);\n  let anisoT = normalize(anisoTBN * vec3<f32>(anisoDir, 0.0));\n`;\n\n  const glFrame = withVertexTangent\n    ? /*glsl*/ `\n  vec3 anisoTw = normalize(vAnisoTangent);\n  vec3 anisoBw = normalize(vAnisoBitangent);\n  vec3 anisoT = normalize(anisoDir.x * anisoTw + anisoDir.y * anisoBw);\n`\n    : /*glsl*/ `\n  mat3 anisoTBN = calculateTBN(anisoGeoN, vPosition, vUV);\n  vec3 anisoT = normalize(anisoTBN * vec3(anisoDir, 0.0));\n`;\n\n  const bit: ShaderBit = {\n    name,\n\n    requires: withVertexTangent ? [mathConstantsBit] : [mathConstantsBit, derivativeTangentFrameBit],\n\n    textures: withTexture ? ['anisotropy'] : [],\n\n    bindings: {\n      material: {\n        anisotropyParams: 'vec4<f32>',\n      },\n    },\n\n    gpu: {\n      fragment: {\n        material: /*wgsl*/ `\n${gpuSource}\n  let anisoRot = material.anisotropyParams.y;\n  let anisoC = cos(anisoRot);\n  let anisoS = sin(anisoRot);\n  let anisoDir = vec2<f32>(\n    anisoDirRaw.x * anisoC - anisoDirRaw.y * anisoS,\n    anisoDirRaw.x * anisoS + anisoDirRaw.y * anisoC,\n  );\n  let anisoStrength = clamp(material.anisotropyParams.x * anisoTexStrength, 0.0, 1.0);\n\n  let anisoGeoN = normalize(select(-input.vNormal, input.vNormal, input.frontFacing));\n${gpuFrame}\n  let anisoB = normalize(cross(anisoGeoN, anisoT));\n\n  let anisoBentCross = cross(cross(anisoB, viewDir), anisoB);\n  let anisoBentLenSq = dot(anisoBentCross, anisoBentCross);\n  var anisoBentN = normal;\n  if (anisoBentLenSq > 1e-8) {\n    anisoBentN = anisoBentCross * inverseSqrt(anisoBentLenSq);\n  }\n  let anisoBend = 1.0 - anisoStrength * (1.0 - roughness);\n  let anisoBend4 = anisoBend * anisoBend * anisoBend * anisoBend;\n  specularNormal = normalize(mix(anisoBentN, normal, anisoBend4));\n`,\n        lobePreLighting: /*wgsl*/ `\n  let anisoAlphaB = a;\n  let anisoAlphaT = mix(a, 1.0, anisoStrength * anisoStrength);\n  let anisoTdotV = dot(anisoT, viewDir);\n  let anisoBdotV = dot(anisoB, viewDir);\n`,\n        lobePerLight: /*wgsl*/ `\n    {\n      let anisoTdotL = dot(anisoT, lightDir);\n      let anisoBdotL = dot(anisoB, lightDir);\n      let anisoTdotH = dot(anisoT, halfVector);\n      let anisoBdotH = dot(anisoB, halfVector);\n\n      let anisoA2 = anisoAlphaT * anisoAlphaB;\n      let anisoFv = vec3<f32>(anisoAlphaB * anisoTdotH, anisoAlphaT * anisoBdotH, anisoA2 * nDotH);\n      let anisoW2 = anisoA2 / dot(anisoFv, anisoFv);\n      let anisoD = anisoA2 * anisoW2 * anisoW2 * INV_PI;\n\n      let anisoGGXV = nDotL * length(vec3<f32>(anisoAlphaT * anisoTdotV, anisoAlphaB * anisoBdotV, nDotV));\n      let anisoGGXL = nDotV * length(vec3<f32>(anisoAlphaT * anisoTdotL, anisoAlphaB * anisoBdotL, nDotL));\n      let anisoVis = 0.5 / max(anisoGGXV + anisoGGXL, 1e-5);\n\n      let anisoSpec = anisoD * fresnel * anisoVis;\n      directLight += (anisoSpec - specular) * radiance * nDotL * shadow;\n    }\n`,\n      },\n    },\n\n    gl: {\n      fragment: {\n        material: /*glsl*/ `\n${glSource}\n  float anisoRot = material.anisotropyParams.y;\n  float anisoC = cos(anisoRot);\n  float anisoS = sin(anisoRot);\n  vec2 anisoDir = vec2(\n    anisoDirRaw.x * anisoC - anisoDirRaw.y * anisoS,\n    anisoDirRaw.x * anisoS + anisoDirRaw.y * anisoC\n  );\n  float anisoStrength = clamp(material.anisotropyParams.x * anisoTexStrength, 0.0, 1.0);\n\n  vec3 anisoGeoN = normalize(gl_FrontFacing ? vNormal : -vNormal);\n${glFrame}\n  vec3 anisoB = normalize(cross(anisoGeoN, anisoT));\n\n  vec3 anisoBentCross = cross(cross(anisoB, viewDir), anisoB);\n  float anisoBentLenSq = dot(anisoBentCross, anisoBentCross);\n  vec3 anisoBentN = anisoBentLenSq > 1e-8 ? anisoBentCross * inversesqrt(anisoBentLenSq) : normal;\n  float anisoBend = 1.0 - anisoStrength * (1.0 - roughness);\n  float anisoBend4 = anisoBend * anisoBend * anisoBend * anisoBend;\n  specularNormal = normalize(mix(anisoBentN, normal, anisoBend4));\n`,\n        lobePreLighting: /*glsl*/ `\n  float anisoAlphaB = a;\n  float anisoAlphaT = mix(a, 1.0, anisoStrength * anisoStrength);\n  float anisoTdotV = dot(anisoT, viewDir);\n  float anisoBdotV = dot(anisoB, viewDir);\n`,\n        lobePerLight: /*glsl*/ `\n    {\n      float anisoTdotL = dot(anisoT, lightDir);\n      float anisoBdotL = dot(anisoB, lightDir);\n      float anisoTdotH = dot(anisoT, halfVector);\n      float anisoBdotH = dot(anisoB, halfVector);\n\n      float anisoA2 = anisoAlphaT * anisoAlphaB;\n      vec3 anisoFv = vec3(anisoAlphaB * anisoTdotH, anisoAlphaT * anisoBdotH, anisoA2 * nDotH);\n      float anisoW2 = anisoA2 / dot(anisoFv, anisoFv);\n      float anisoD = anisoA2 * anisoW2 * anisoW2 * INV_PI;\n\n      float anisoGGXV = nDotL * length(vec3(anisoAlphaT * anisoTdotV, anisoAlphaB * anisoBdotV, nDotV));\n      float anisoGGXL = nDotV * length(vec3(anisoAlphaT * anisoTdotL, anisoAlphaB * anisoBdotL, nDotL));\n      float anisoVis = 0.5 / max(anisoGGXV + anisoGGXL, 1e-5);\n\n      vec3 anisoSpec = anisoD * fresnel * anisoVis;\n      directLight += (anisoSpec - specular) * radiance * nDotL * shadow;\n    }\n`,\n      },\n    },\n  };\n\n  if (withVertexTangent) {\n    bit.attributes = { aTangent: 'float32x4' };\n    bit.interStage = { vAnisoTangent: 'vec3<f32>', vAnisoBitangent: 'vec3<f32>' };\n    bit.gpu!.vertex = {\n      input: /*wgsl*/ `  tangent = input.aTangent.xyz;`,\n      end: /*wgsl*/ `\n  let anisoWorldT = normalize(modelMatrix3 * tangent);\n  output.vAnisoTangent = anisoWorldT;\n  output.vAnisoBitangent = cross(worldNormal, anisoWorldT) * input.aTangent.w;\n`,\n    };\n    bit.gl!.vertex = {\n      input: /*glsl*/ `  tangent = aTangent.xyz;`,\n      end: /*glsl*/ `\n  vec3 anisoWorldT = normalize(modelMatrix3 * tangent);\n  vAnisoTangent = anisoWorldT;\n  vAnisoBitangent = cross(worldNormal, anisoWorldT) * aTangent.w;\n`,\n    };\n  }\n\n  return bit;\n}\n\n/** @internal */\nexport const anisotropyBit: ShaderBit = createAnisotropyBit(false, false);\n\n/** @internal */\nexport const anisotropyTextureBit: ShaderBit = createAnisotropyBit(true, false);\n\n/** @internal */\nexport const anisotropyTangentBit: ShaderBit = createAnisotropyBit(false, true);\n\n/** @internal */\nexport const anisotropyTextureTangentBit: ShaderBit = createAnisotropyBit(true, true);\n\n/**\n * Returns an anisotropy bit's vertex-tangent variant, which keeps its `material` fields and textures so\n * the material's layout holds, and any other bit unchanged\n * @internal\n */\nexport function anisotropyTangentVariant(bit: ShaderBit): ShaderBit {\n  if (bit === anisotropyBit) return anisotropyTangentBit;\n  if (bit === anisotropyTextureBit) return anisotropyTextureTangentBit;\n  return bit;\n}\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * Field and texture names must match `EmissivePropsClass` in `materials/utils/emissiveProps.ts`\n * @internal\n */\nexport const emissiveBit: ShaderBit = {\n  name: 'emissive',\n  textures: ['emissive'],\n  bindings: {\n    material: {\n      emissive: 'vec3<f32>',\n      emissiveStrength: 'f32',\n    },\n  },\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  emissive = material.emissive * material.emissiveStrength;\n  let emissiveTex = sampleEmissive(input.vUV).rgb;\n  emissive *= pow(emissiveTex, vec3<f32>(2.2));\n`,\n    },\n  },\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  emissive = material.emissive * material.emissiveStrength;\n  vec3 emissiveTex = sampleEmissive(vUV).rgb;\n  emissive *= pow(emissiveTex, vec3(2.2));\n`,\n    },\n  },\n};\n","import { Color } from 'pixi.js';\nimport type { Texture } from 'pixi.js';\n\nimport type { BaseMaterial3D } from '../BaseMaterial3D';\nimport { linearToSrgb, writeLinearRgb } from '../BaseMaterial3D';\nimport type { MaterialData } from './createMaterialDataClass';\n\ntype FeaturePropBinding =\n  | { kind: 'lane'; field: string; lane: number }\n  | { kind: 'scalar'; field: string }\n  | { kind: 'colour'; field: string }\n  | { kind: 'texture'; slot: string; readonly?: boolean };\n\ntype FeaturePropsSchema = Record<string, FeaturePropBinding>;\n\n/**\n * Builds the class behind a feature-props object such as `material.clearcoat`; lane setters compare\n * with `Math.fround(value)`, or re-setting an inexact value like 0.3 would queue an upload each time\n * @internal\n */\nexport function createFeaturePropsClass<T>(\n  schema: Record<keyof T, FeaturePropBinding>,\n): new (material: BaseMaterial3D) => T {\n  const bindings = Object.entries(schema as FeaturePropsSchema);\n  const colourBindings = bindings.filter(([, binding]) => binding.kind === 'colour') as [\n    string,\n    { kind: 'colour'; field: string },\n  ][];\n\n  class FeatureProps {\n    public readonly _material: BaseMaterial3D;\n    public readonly _data: MaterialData;\n    public readonly _colours: Record<string, Float32Array> = Object.create(null);\n    public readonly _tints: Record<string, number> = Object.create(null);\n\n    constructor(material: BaseMaterial3D) {\n      this._material = material;\n      this._data = material.data;\n      for (const [name, binding] of colourBindings) {\n        const view = (this._data[binding.field] as Float32Array).subarray(0, 3);\n        this._colours[name] = view;\n        this._tints[name] = Color.shared\n          .setValue([linearToSrgb(view[0]), linearToSrgb(view[1]), linearToSrgb(view[2])])\n          .toNumber();\n      }\n    }\n  }\n\n  for (const [name, binding] of bindings) {\n    let descriptor: PropertyDescriptor;\n    switch (binding.kind) {\n      case 'lane': {\n        const { field, lane } = binding;\n        descriptor = {\n          get(this: FeatureProps): number {\n            return (this._data[field] as Float32Array)[lane];\n          },\n          set(this: FeatureProps, value: number) {\n            const view = this._data[field] as Float32Array;\n            if (view[lane] === Math.fround(value)) return;\n            view[lane] = value;\n            this._material.update();\n          },\n        };\n        break;\n      }\n      case 'scalar': {\n        const { field } = binding;\n        descriptor = {\n          get(this: FeatureProps): number {\n            return this._data[field] as number;\n          },\n          set(this: FeatureProps, value: number) {\n            this._data[field] = value;\n          },\n        };\n        break;\n      }\n      case 'colour':\n        descriptor = {\n          get(this: FeatureProps): number {\n            return this._tints[name];\n          },\n          set(this: FeatureProps, value: Parameters<Color['setValue']>[0]) {\n            const colour = Color.shared.setValue(value);\n            this._tints[name] = colour.toNumber();\n            writeLinearRgb(this._colours[name], 0, colour);\n            this._material.update();\n          },\n        };\n        break;\n      case 'texture': {\n        const { slot } = binding;\n        descriptor = {\n          get(this: FeatureProps): Texture | undefined {\n            return this._material.textures[slot];\n          },\n        };\n        if (!binding.readonly) {\n          descriptor.set = function (this: FeatureProps, value: Texture): void {\n            this._material.textures[slot] = value;\n          };\n        }\n        break;\n      }\n    }\n    descriptor.enumerable = true;\n    descriptor.configurable = false;\n    Object.defineProperty(FeatureProps.prototype, name, descriptor);\n  }\n\n  return FeatureProps as new (material: BaseMaterial3D) => T;\n}\n\n/**\n * Read a feature-props object back as a plain object of its props, such as the `clearcoat` options\n * `clone` passes to the copy's constructor\n *\n * The names come from the prototype, where {@link createFeaturePropsClass} defines every prop of the\n * schema as enumerable, so they can't drift from the getters. The instance's own fields\n * (`_material`, `_data`, the colour views) aren't on the prototype, so they stay out. A `readonly`\n * texture prop the group was built without reads `undefined`.\n * @param props - An instance of a class {@link createFeaturePropsClass} built\n * @returns Each prop's current value, by name\n * @internal\n */\nexport function readFeatureProps<T extends object>(props: T): T {\n  const values: Partial<T> = {};\n  for (const name of Object.keys(Object.getPrototypeOf(props)) as (keyof T)[]) values[name] = props[name];\n\n  return values as T;\n}\n","import type { ColorSource, Texture } from 'pixi.js';\n\nimport { createFeaturePropsClass } from './createFeaturePropsClass';\n\n/**\n * Options for a material's own glow, the `emissive` group of {@link Material3D} and\n * {@link PhongMaterial}\n *\n * Passing the group turns the glow on. It's added after lighting, so it shows in the dark, and\n * follows glTF's emissive colour and texture plus `KHR_materials_emissive_strength`.\n * @example\n * ```ts\n * const lamp = new Material3D({ emissive: { color: 0xffcc66, strength: 3 } });\n * ```\n * @category materials\n * @standard\n */\nexport interface EmissiveOptions {\n  /**\n   * Glow colour, multiplied by `texture` when there is one\n   * @default 0xffffff\n   * @example\n   * ```ts\n   * const ember = new Material3D({ emissive: { color: 'orange' } });\n   * ```\n   */\n  color?: ColorSource;\n  /**\n   * Multiplier on the glow; above 1 it goes past white, which bloom picks up\n   * @default 1\n   * @example\n   * ```ts\n   * const neon = new Material3D({ emissive: { color: 0x66ccff, strength: 8 } });\n   * ```\n   */\n  strength?: number;\n  /**\n   * Glow map, multiplied by `color`\n   * @example\n   * ```ts\n   * const tower = new Material3D({ emissive: { texture: litWindowsTexture } });\n   * ```\n   */\n  texture?: Texture;\n}\n\n/**\n * Runtime controls for a material's glow, as `material.emissive`\n *\n * Present only when the material was built with an `emissive` group. Changes never recompile the\n * shader.\n * @example\n * ```ts\n * const sign = new Material3D({ emissive: { color: 0xff0044 } });\n * sign.emissive!.strength = 2;\n * ```\n * @category materials\n * @standard\n */\nexport interface EmissiveProps {\n  /**\n   * Glow colour; takes any `ColorSource` and reads back a hex number, like `Container.tint`\n   * @example\n   * ```ts\n   * material.emissive!.color = 'red';\n   * ```\n   */\n  get color(): number;\n  /** Sets the glow colour from any `ColorSource` */\n  set color(value: ColorSource);\n  /**\n   * Multiplier on the glow; above 1 it goes past white, which bloom picks up\n   * @example\n   * ```ts\n   * material.emissive!.strength = 4;\n   * ```\n   */\n  strength: number;\n  /**\n   * Glow map, multiplied by `color`\n   * @example\n   * ```ts\n   * material.emissive!.texture = await Assets.load('lit-windows.png');\n   * ```\n   */\n  texture: Texture;\n}\n\n/**\n * Field and slot names here must match what `emissiveBit` declares\n * @internal\n */\nexport const EmissivePropsClass = createFeaturePropsClass<EmissiveProps>({\n  color: { kind: 'colour', field: 'emissive' },\n  strength: { kind: 'scalar', field: 'emissiveStrength' },\n  texture: { kind: 'texture', slot: 'emissive' },\n});\n","import { derivativeTangentFrameBit } from '../../../core/shader/bits/derivativeTangentFrameBit';\nimport { mathConstantsBit } from '../../../core/shader/bits/mathConstantsBit';\nimport type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * The geometric normal flipped on back faces, in both constants: the coat skips the base normal map, and\n * `doubleSidedNormalBit` flips only `normal`\n */\nconst CC_FACE_NORMAL_GPU = /*wgsl*/ `normalize(select(-input.vNormal, input.vNormal, input.frontFacing))`;\nconst CC_FACE_NORMAL_GL = /*glsl*/ `normalize(gl_FrontFacing ? vNormal : -vNormal)`;\n\n/**\n * The direct GGX floors roughness and runs only where `ccNDotL > 0`, which keeps both divides off zero;\n * the environment reads the raw roughness, so a mirror coat stays sharp\n */\nfunction createClearcoatBit(withNormalMap: boolean): ShaderBit {\n  const gpuNormal = withNormalMap\n    ? /*wgsl*/ `\n  let ccTangentNormal = sampleClearcoatNormal(input.vUV).rgb * 2.0 - 1.0;\n  let ccScaledNormal = vec3<f32>(\n    ccTangentNormal.xy * material.clearcoatParams.z,\n    ccTangentNormal.z,\n  );\n  let ccTBN = calculateTBN(${CC_FACE_NORMAL_GPU}, input.vPosition, input.vUV);\n  let ccNormal = normalize(ccTBN * ccScaledNormal);\n`\n    : /*wgsl*/ `\n  let ccNormal = ${CC_FACE_NORMAL_GPU};\n`;\n\n  const glNormal = withNormalMap\n    ? /*glsl*/ `\n  vec3 ccTangentNormal = sampleClearcoatNormal(vUV).rgb * 2.0 - 1.0;\n  vec3 ccScaledNormal = vec3(ccTangentNormal.xy * material.clearcoatParams.z, ccTangentNormal.z);\n  mat3 ccTBN = calculateTBN(${CC_FACE_NORMAL_GL}, vPosition, vUV);\n  vec3 ccNormal = normalize(ccTBN * ccScaledNormal);\n`\n    : /*glsl*/ `\n  vec3 ccNormal = ${CC_FACE_NORMAL_GL};\n`;\n\n  return {\n    name: withNormalMap ? 'clearcoat:normalMap' : 'clearcoat',\n\n    requires: withNormalMap ? [mathConstantsBit, derivativeTangentFrameBit] : [mathConstantsBit],\n\n    textures: withNormalMap\n      ? ['clearcoat', 'clearcoatRoughness', 'clearcoatNormal']\n      : ['clearcoat', 'clearcoatRoughness'],\n\n    bindings: {\n      material: {\n        clearcoatParams: 'vec4<f32>',\n      },\n    },\n\n    gpu: {\n      header: `const CLEARCOAT_F0: f32 = 0.04;\\n`,\n\n      fragment: {\n        lobePreLighting: /*wgsl*/ `\n  let ccFactor = material.clearcoatParams.x * sampleClearcoat(input.vUV).r;\n  let ccRoughnessRaw = material.clearcoatParams.y * sampleClearcoatRoughness(input.vUV).g;\n  let ccRoughnessIBL = clamp(ccRoughnessRaw, 0.0, 1.0);\n  let ccRoughness = min(max(ccRoughnessIBL, 0.04) + geometricRoughness, 1.0);\n${gpuNormal}\n  let ccA = ccRoughness * ccRoughness;\n  let ccA2 = ccA * ccA;\n  let ccA2InvPi = ccA2 * INV_PI;\n  let ccOneMinusA = 1.0 - ccA;\n  let ccNDotV = max(dot(ccNormal, viewDir), 0.0);\n  let ccVisV = ccNDotV * ccOneMinusA + ccA;\n\n  var clearcoatLight = vec3<f32>(0.0);\n`,\n        lobePerLight: /*wgsl*/ `\n    {\n      let ccHalfVector = normalize(viewDir + lightDir);\n      let ccNDotL = max(dot(ccNormal, lightDir), 0.0);\n      if (ccNDotL > 0.0) {\n        let ccNDotH = max(dot(ccNormal, ccHalfVector), 0.0);\n        let ccDDenom = (ccNDotH * ccNDotH * (ccA2 - 1.0) + 1.0);\n        let ccD = ccA2InvPi / (ccDDenom * ccDDenom);\n        let ccVis = 0.5 / (ccNDotL * ccVisV + ccNDotV * (ccNDotL * ccOneMinusA + ccA));\n        let ccHDotV = max(dot(ccHalfVector, viewDir), 0.0);\n        let ccFc5 = exp2((-5.55473 * ccHDotV - 6.98316) * ccHDotV);\n        let ccF = CLEARCOAT_F0 + (1.0 - CLEARCOAT_F0) * ccFc5;\n        clearcoatLight += ccD * ccF * ccVis * light.color * attenuation * ccNDotL * shadow;\n      }\n    }\n`,\n        lobePostLighting: /*wgsl*/ `\n  let ccFcv5 = exp2((-5.55473 * ccNDotV - 6.98316) * ccNDotV);\n\n  let ccR = reflect(-viewDir, ccNormal);\n  let ccPrefiltered = sampleEnvironment(ccR, ccRoughnessIBL);\n  let ccBrdf = textureSampleLevel(uBrdfLutTexture, uBrdfLutSampler, vec2<f32>(ccNDotV, ccRoughnessIBL), 0.0).rg;\n  let clearcoatIBL = ccPrefiltered * (CLEARCOAT_F0 * ccBrdf.x + ccBrdf.y);\n\n  let ccFv = CLEARCOAT_F0 + (1.0 - CLEARCOAT_F0) * ccFcv5;\n  let ccAttenuation = 1.0 - ccFactor * ccFv;\n  finalColor = finalColor * ccAttenuation + (clearcoatLight + clearcoatIBL) * ccFactor;\n`,\n      },\n    },\n\n    gl: {\n      fragment: {\n        header: /*glsl*/ `\n#define CLEARCOAT_F0 0.04\n`,\n        lobePreLighting: /*glsl*/ `\n  float ccFactor = material.clearcoatParams.x * sampleClearcoat(vUV).r;\n  float ccRoughnessRaw = material.clearcoatParams.y * sampleClearcoatRoughness(vUV).g;\n  float ccRoughnessIBL = clamp(ccRoughnessRaw, 0.0, 1.0);\n  float ccRoughness = min(max(ccRoughnessIBL, 0.04) + geometricRoughness, 1.0);\n${glNormal}\n  float ccA = ccRoughness * ccRoughness;\n  float ccA2 = ccA * ccA;\n  float ccA2InvPi = ccA2 * INV_PI;\n  float ccOneMinusA = 1.0 - ccA;\n  float ccNDotV = max(dot(ccNormal, viewDir), 0.0);\n  float ccVisV = ccNDotV * ccOneMinusA + ccA;\n\n  vec3 clearcoatLight = vec3(0.0);\n`,\n        lobePerLight: /*glsl*/ `\n    {\n      vec3 ccHalfVector = normalize(viewDir + lightDir);\n      float ccNDotL = max(dot(ccNormal, lightDir), 0.0);\n      if (ccNDotL > 0.0) {\n        float ccNDotH = max(dot(ccNormal, ccHalfVector), 0.0);\n        float ccDDenom = (ccNDotH * ccNDotH * (ccA2 - 1.0) + 1.0);\n        float ccD = ccA2InvPi / (ccDDenom * ccDDenom);\n        float ccVis = 0.5 / (ccNDotL * ccVisV + ccNDotV * (ccNDotL * ccOneMinusA + ccA));\n        float ccHDotV = max(dot(ccHalfVector, viewDir), 0.0);\n        float ccFc5 = exp2((-5.55473 * ccHDotV - 6.98316) * ccHDotV);\n        float ccF = CLEARCOAT_F0 + (1.0 - CLEARCOAT_F0) * ccFc5;\n        clearcoatLight += ccD * ccF * ccVis * light.color * attenuation * ccNDotL * shadow;\n      }\n    }\n`,\n        lobePostLighting: /*glsl*/ `\n  float ccFcv5 = exp2((-5.55473 * ccNDotV - 6.98316) * ccNDotV);\n\n  vec3 ccR = reflect(-viewDir, ccNormal);\n  vec3 ccPrefiltered = sampleEnvironment(ccR, ccRoughnessIBL);\n  vec2 ccBrdf = texture(uBrdfLutTexture, vec2(ccNDotV, ccRoughnessIBL)).rg;\n  vec3 clearcoatIBL = ccPrefiltered * (CLEARCOAT_F0 * ccBrdf.x + ccBrdf.y);\n\n  float ccFv = CLEARCOAT_F0 + (1.0 - CLEARCOAT_F0) * ccFcv5;\n  float ccAttenuation = 1.0 - ccFactor * ccFv;\n  finalColor = finalColor * ccAttenuation + (clearcoatLight + clearcoatIBL) * ccFactor;\n`,\n      },\n    },\n  };\n}\n\n/** @internal */\nexport const clearcoatBit: ShaderBit = createClearcoatBit(false);\n\n/** @internal */\nexport const clearcoatNormalMapBit: ShaderBit = createClearcoatBit(true);\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Every Fresnel term uses `f90` where Schlick has 1, to match `specularBit` and `pbrLightingBit`. The environment\n * sampled at roughness 1 is already about irradiance / PI, so diffuse takes no `1 / PI`\n * @internal\n */\nexport const iblBit: ShaderBit = {\n  name: 'ibl',\n\n  bindings: {\n    global: {\n      uBrdfLutTexture: 'texture_2d<f32>',\n    },\n  },\n\n  gpu: {\n    fragment: {\n      lighting: /*wgsl*/ `\n  {\n    let NdotV_ibl = max(dot(normal, viewDir), 0.0);\n    let R_ibl = reflect(-viewDir, specularNormal);\n\n    let radiance = sampleEnvironment(R_ibl, roughness);\n    let irradiance = sampleEnvironment(normal, 1.0);\n\n    let f_ab = textureSampleLevel(uBrdfLutTexture, uBrdfLutSampler, vec2<f32>(NdotV_ibl, roughness), 0.0).rg;\n\n    let Fr = max(vec3<f32>(f90 - f90 * roughness), fresnelF0) - fresnelF0;\n    let k_S = fresnelF0 + Fr * exp2((-5.55473 * NdotV_ibl - 6.98316) * NdotV_ibl);\n    let FssEss = k_S * f_ab.x + f90 * f_ab.y;\n\n    let Ems = 1.0 - (f_ab.x + f_ab.y);\n    let F_avg = fresnelF0 + (f90 - fresnelF0) / 21.0;\n    let Fms = FssEss * F_avg / (1.0 - F_avg * Ems + 1e-5);\n    let FmsEms = Fms * Ems;\n\n    let k_D = albedo * (1.0 - FssEss - FmsEms) * (1.0 - metallic);\n\n    ambient += FssEss * radiance + (FmsEms + k_D) * irradiance;\n  }\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      lighting: /*glsl*/ `\n  {\n    float NdotV_ibl = max(dot(normal, viewDir), 0.0);\n    vec3 R_ibl = reflect(-viewDir, specularNormal);\n\n    vec3 radiance = sampleEnvironment(R_ibl, roughness);\n    vec3 irradiance = sampleEnvironment(normal, 1.0);\n\n    vec2 f_ab = texture(uBrdfLutTexture, vec2(NdotV_ibl, roughness)).rg;\n\n    vec3 Fr = max(vec3(f90 - f90 * roughness), fresnelF0) - fresnelF0;\n    vec3 k_S = fresnelF0 + Fr * exp2((-5.55473 * NdotV_ibl - 6.98316) * NdotV_ibl);\n    vec3 FssEss = k_S * f_ab.x + f90 * f_ab.y;\n\n    float Ems = 1.0 - (f_ab.x + f_ab.y);\n    vec3 F_avg = fresnelF0 + (f90 - fresnelF0) / 21.0;\n    vec3 Fms = FssEss * F_avg / (1.0 - F_avg * Ems + 1e-5);\n    vec3 FmsEms = Fms * Ems;\n\n    vec3 k_D = albedo * (1.0 - FssEss - FmsEms) * (1.0 - metallic);\n\n    ambient += FssEss * radiance + (FmsEms + k_D) * irradiance;\n  }\n`,\n    },\n  },\n};\n","import { mathConstantsBit } from '../../../core/shader/bits/mathConstantsBit';\nimport type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/** @internal */\nexport const iridescenceBit: ShaderBit = {\n  name: 'iridescence',\n\n  requires: [mathConstantsBit],\n\n  textures: ['iridescence'],\n\n  bindings: {\n    material: {\n      transmissionVolume: 'vec4<f32>',\n      attenuationColorIrid: 'vec4<f32>',\n      iridescenceThickness: 'f32',\n      iridescenceThicknessMinimum: 'f32',\n    },\n  },\n\n  gpu: {\n    header: /*wgsl*/ `\nconst XYZ_TO_REC709 = mat3x3<f32>(\n   3.2404542, -0.9692660,  0.0556434,\n  -1.5371385,  1.8760108, -0.2040259,\n  -0.4985314,  0.0415560,  1.0572252,\n);\n\nfn evalSensitivity(OPD: f32, shift: vec3<f32>) -> vec3<f32> {\n  let phase = 2.0 * PI * OPD * 1e-9;\n  let val = vec3<f32>(5.4856e-13, 4.4201e-13, 5.2481e-13);\n  let pos = vec3<f32>(1.6810e+06, 1.7953e+06, 2.2084e+06);\n  let vr  = vec3<f32>(4.3278e+09, 9.3046e+09, 6.6121e+09);\n  var xyz = val * sqrt(2.0 * PI * vr) * cos(pos * phase + shift) * exp(-vr * phase * phase);\n  xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift.x) * exp(-4.5282e+09 * phase * phase);\n  xyz /= 1.0685e-7;\n  let srgb = XYZ_TO_REC709 * xyz;\n  return srgb;\n}\n\nfn IorToFresnel0(transmittedIor: f32, incidentIor: f32) -> f32 {\n  let r = (transmittedIor - incidentIor) / (transmittedIor + incidentIor);\n  return r * r;\n}\n\nfn IorToFresnel0v(transmittedIor: vec3<f32>, incidentIor: f32) -> vec3<f32> {\n  let r = (transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor));\n  return r * r;\n}\n\nfn Fresnel0ToIorV(f0: vec3<f32>) -> vec3<f32> {\n  let sqrtF0 = sqrt(clamp(f0, vec3(0.0), vec3(0.9999)));\n  return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n}\n\nfn F_Schlick_scalar(f0: f32, f90: f32, VdotH: f32) -> f32 {\n  let fc5 = exp2((-5.55473 * VdotH - 6.98316) * VdotH);\n  return f0 + (f90 - f0) * fc5;\n}\n\nfn F_Schlick_v(f0: vec3<f32>, f90: f32, VdotH: f32) -> vec3<f32> {\n  let fc5 = exp2((-5.55473 * VdotH - 6.98316) * VdotH);\n  return f0 + (vec3(f90) - f0) * fc5;\n}\n\nfn evalIridescence(outsideIor: f32, iridescenceIor: f32, cosTheta: f32,\n                    thinFilmThickness: f32, baseF0: vec3<f32>) -> vec3<f32> {\n  let iridIor = mix(outsideIor, iridescenceIor, smoothstep(0.0, 0.03, thinFilmThickness));\n\n  let sinTheta2Sq = (outsideIor * outsideIor) / (iridIor * iridIor)\n                     * (1.0 - cosTheta * cosTheta);\n  let cosTheta2Sq = 1.0 - sinTheta2Sq;\n  if (cosTheta2Sq < 0.0) { return vec3<f32>(1.0); }\n  let cosTheta2 = sqrt(cosTheta2Sq);\n\n  let R12 = IorToFresnel0(iridIor, outsideIor);\n  let R12s = F_Schlick_scalar(R12, 1.0, cosTheta);\n  let T121 = 1.0 - R12s;\n  var phi12: f32 = 0.0;\n  if (iridIor < outsideIor) { phi12 = PI; }\n  let phi21 = PI - phi12;\n\n  let baseIor = Fresnel0ToIorV(baseF0);\n  let R23 = IorToFresnel0v(baseIor, iridIor);\n  let R23s = F_Schlick_v(R23, 1.0, cosTheta2);\n  var phi23 = vec3<f32>(0.0);\n  if (baseIor.x < iridIor) { phi23.x = PI; }\n  if (baseIor.y < iridIor) { phi23.y = PI; }\n  if (baseIor.z < iridIor) { phi23.z = PI; }\n\n  let OPD = 2.0 * iridIor * thinFilmThickness * cosTheta2;\n  let phi = vec3<f32>(phi21) + phi23;\n\n  let R123 = clamp(R12s * R23s, vec3(1e-5), vec3(0.9999));\n  let r123 = sqrt(R123);\n  let Rs = (T121 * T121 * R23s) / (vec3(1.0) - R123);\n\n  var I = vec3<f32>(R12s) + Rs;\n\n  var Cm = Rs - vec3<f32>(T121);\n  for (var m: i32 = 1; m <= 2; m = m + 1) {\n    Cm *= r123;\n    let mf = f32(m);\n    let Sm = 2.0 * evalSensitivity(mf * OPD, mf * phi);\n    I = I + Cm * Sm;\n  }\n\n  return max(I, vec3(0.0));\n}\n`,\n    fragment: {\n      material: /*wgsl*/ `\n  {\n    let iridTex = sampleIridescence(input.vUV);\n    let iridescenceFactor = material.transmissionVolume.w * iridTex.r;\n    let iridescenceIor = material.attenuationColorIrid.w;\n    let iridThickness = mix(\n      material.iridescenceThicknessMinimum,\n      material.iridescenceThickness,\n      iridTex.g,\n    );\n    let iridNdotV = max(dot(normal, viewDir), 0.001);\n    let iridF = evalIridescence(1.0, iridescenceIor, iridNdotV, iridThickness, fresnelF0);\n    fresnelF0 = mix(fresnelF0, iridF, iridescenceFactor);\n  }\n`,\n    },\n  },\n\n  gl: {\n    header: /*glsl*/ `\nconst mat3 XYZ_TO_REC709 = mat3(\n   3.2404542, -0.9692660,  0.0556434,\n  -1.5371385,  1.8760108, -0.2040259,\n  -0.4985314,  0.0415560,  1.0572252\n);\n\nvec3 evalSensitivity(float OPD, vec3 shift) {\n  float phase = 2.0 * PI * OPD * 1e-9;\n  vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n  vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n  vec3 vr  = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n  vec3 xyz = val * sqrt(2.0 * PI * vr) * cos(pos * phase + shift) * exp(-vr * phase * phase);\n  xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift.x) * exp(-4.5282e+09 * phase * phase);\n  xyz /= 1.0685e-7;\n  vec3 srgb = XYZ_TO_REC709 * xyz;\n  return srgb;\n}\n\nfloat IorToFresnel0(float transmittedIor, float incidentIor) {\n  float r = (transmittedIor - incidentIor) / (transmittedIor + incidentIor);\n  return r * r;\n}\n\nvec3 IorToFresnel0v(vec3 transmittedIor, float incidentIor) {\n  vec3 r = (transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor));\n  return r * r;\n}\n\nvec3 Fresnel0ToIorV(vec3 f0) {\n  vec3 sqrtF0 = sqrt(clamp(f0, 0.0, 0.9999));\n  return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n}\n\nfloat F_Schlick_scalar(float f0, float f90, float VdotH) {\n  float fc5 = exp2((-5.55473 * VdotH - 6.98316) * VdotH);\n  return f0 + (f90 - f0) * fc5;\n}\n\nvec3 F_Schlick_v(vec3 f0, float f90, float VdotH) {\n  float fc5 = exp2((-5.55473 * VdotH - 6.98316) * VdotH);\n  return f0 + (vec3(f90) - f0) * fc5;\n}\n\nvec3 evalIridescence(float outsideIor, float iridescenceIor, float cosTheta,\n                      float thinFilmThickness, vec3 baseF0) {\n  float iridIor = mix(outsideIor, iridescenceIor, smoothstep(0.0, 0.03, thinFilmThickness));\n\n  float sinTheta2Sq = (outsideIor * outsideIor) / (iridIor * iridIor)\n                       * (1.0 - cosTheta * cosTheta);\n  float cosTheta2Sq = 1.0 - sinTheta2Sq;\n  if (cosTheta2Sq < 0.0) { return vec3(1.0); }\n  float cosTheta2 = sqrt(cosTheta2Sq);\n\n  float R12 = IorToFresnel0(iridIor, outsideIor);\n  float R12s = F_Schlick_scalar(R12, 1.0, cosTheta);\n  float T121 = 1.0 - R12s;\n  float phi12 = 0.0;\n  if (iridIor < outsideIor) { phi12 = PI; }\n  float phi21 = PI - phi12;\n\n  vec3 baseIor = Fresnel0ToIorV(baseF0);\n  vec3 R23 = IorToFresnel0v(baseIor, iridIor);\n  vec3 R23s = F_Schlick_v(R23, 1.0, cosTheta2);\n  vec3 phi23 = vec3(0.0);\n  if (baseIor.x < iridIor) phi23.x = PI;\n  if (baseIor.y < iridIor) phi23.y = PI;\n  if (baseIor.z < iridIor) phi23.z = PI;\n\n  float OPD = 2.0 * iridIor * thinFilmThickness * cosTheta2;\n  vec3 phi = vec3(phi21) + phi23;\n\n  vec3 R123 = clamp(R12s * R23s, 1e-5, 0.9999);\n  vec3 r123 = sqrt(R123);\n  vec3 Rs = (T121 * T121 * R23s) / (vec3(1.0) - R123);\n\n  vec3 I = vec3(R12s) + Rs;\n\n  vec3 Cm = Rs - vec3(T121);\n  for (int m = 1; m <= 2; m++) {\n    Cm *= r123;\n    float mf = float(m);\n    vec3 Sm = 2.0 * evalSensitivity(mf * OPD, mf * phi);\n    I += Cm * Sm;\n  }\n\n  return max(I, vec3(0.0));\n}\n`,\n    fragment: {\n      material: /*glsl*/ `\n  {\n    vec4 iridTex = sampleIridescence(vUV);\n    float iridescenceFactor = material.transmissionVolume.w * iridTex.r;\n    float iridescenceIor = material.attenuationColorIrid.w;\n    float iridThickness = mix(\n      material.iridescenceThicknessMinimum,\n      material.iridescenceThickness,\n      iridTex.g\n    );\n\n    float iridNdotV = max(dot(normal, viewDir), 0.001);\n    vec3 iridF = evalIridescence(1.0, iridescenceIor, iridNdotV, iridThickness, fresnelF0);\n    fresnelF0 = mix(fresnelF0, iridF, iridescenceFactor);\n  }\n`,\n    },\n  },\n};\n","/**\n * Most lights a view draws at once\n *\n * Ambient lights don't count. Past the limit, the visible lights last in {@link View3D#lights}\n * are left out. It can't exceed 32, the bits of the light mask in `LightTiles.ts`.\n * @category scene\n * @advanced\n */\nexport const MAX_LIGHTS = 32;\n\n/**\n * Floats per light slot in `LightDataList`: four `vec4`s, as the `MAX_LIGHTS * 4` size of `uLightData` assumes\n * @internal\n */\nexport const FLOATS_PER_LIGHT = 16;\n","import type { Matrix4 } from '../math/matrix/Matrix4';\nimport type { TypedFixedArray } from '../math/utils/misc';\nimport { FLOATS_PER_LIGHT } from './lightLimits';\nimport type { ReadonlyRect, RenderSession } from './render-passes/RenderSession';\n\n/** @internal */\nexport const LIGHT_TILES_X = 16;\n\n/** @internal */\nexport const LIGHT_TILES_Y = 9;\n\n/**\n * `vec4<i32>` lanes of tile masks, four tiles to a lane; the lighting shader reads tile `t` at `[t >> 2][t & 3]`\n * @internal\n */\nexport const LIGHT_TILE_LANES = Math.ceil((LIGHT_TILES_X * LIGHT_TILES_Y) / 4);\n\n/** @internal */\nexport const LIGHT_DEPTH_BINS = 32;\n\n/** @internal */\nexport const LIGHT_DEPTH_LANES = Math.ceil(LIGHT_DEPTH_BINS / 4);\n\nconst gridPlanes = new Float32Array((LIGHT_TILES_X + 1 + LIGHT_TILES_Y + 1) * 4);\n\nfunction writeGridPlanes(e: TypedFixedArray<16>, axis: number, lines: number, offset: number): void {\n  for (let b = 0; b < lines; b++) {\n    const k = (2 * b) / (lines - 1) - 1;\n    const nx = e[axis] - k * e[3];\n    const ny = e[axis + 4] - k * e[7];\n    const nz = e[axis + 8] - k * e[11];\n    const invLength = 1 / Math.sqrt(nx * nx + ny * ny + nz * nz);\n    const o = offset + b * 4;\n\n    gridPlanes[o] = nx * invLength;\n    gridPlanes[o + 1] = ny * invLength;\n    gridPlanes[o + 2] = nz * invLength;\n    gridPlanes[o + 3] = (e[axis + 12] - k * e[15]) * invLength;\n  }\n}\n\n/**\n * Bins lights into screen tiles and depth intervals; light `i` is bit `i`, so `MAX_LIGHTS` in `lightLimits.ts` stops at 32\n *\n * Tests every grid line, as a sphere crossing the camera plane breaks their order, and pads bins for float32 rounding.\n * @param out - Receives the tile masks, tile `(x, y)` at `y * LIGHT_TILES_X + x`.\n * @param lightData - The packed lights.\n * @param lightCount - How many lights are packed.\n * @param viewProjection - The view-projection the draws use, with the target's Y flip.\n * @param view - World to camera; depth runs along its -Z.\n * @param depthMasks - Receives one mask per depth interval.\n * @param depthPlane - Receives the coefficients that turn a world position into a depth bin.\n * @internal\n */\nexport function binLightTiles(\n  out: Int32Array,\n  lightData: Float32Array,\n  lightCount: number,\n  viewProjection: Matrix4,\n  view: Matrix4,\n  depthMasks: Int32Array,\n  depthPlane: Float32Array,\n): void {\n  const e = viewProjection.elements;\n  const rowPlanes = (LIGHT_TILES_X + 1) * 4;\n  const v = view.elements;\n  const depthRadiusScale = Math.hypot(v[2], v[6], v[10]);\n  let everywhere = 0;\n  let finiteLights = 0;\n  let minDepth = Infinity;\n  let maxDepth = -Infinity;\n\n  out.fill(0);\n\n  writeGridPlanes(e, 0, LIGHT_TILES_X + 1, 0);\n  writeGridPlanes(e, 1, LIGHT_TILES_Y + 1, rowPlanes);\n\n  const wLength = Math.sqrt(e[3] * e[3] + e[7] * e[7] + e[11] * e[11]);\n\n  for (let i = 0; i < lightCount; i++) {\n    const o = i * FLOATS_PER_LIGHT;\n    const bit = 1 << i;\n    const range = Math.sqrt(lightData[o + 7]);\n\n    if (lightData[o + 3] === 0 || range <= 0 || !Number.isFinite(range)) {\n      everywhere |= bit;\n      continue;\n    }\n\n    const px = lightData[o];\n    const py = lightData[o + 1];\n    const pz = lightData[o + 2];\n\n    if (e[3] * px + e[7] * py + e[11] * pz + e[15] <= -range * wLength) continue;\n\n    let x0 = 0;\n    let x1 = LIGHT_TILES_X - 1;\n    for (let b = 0; b <= LIGHT_TILES_X; b++) {\n      const p = b * 4;\n      const distance = gridPlanes[p] * px + gridPlanes[p + 1] * py + gridPlanes[p + 2] * pz + gridPlanes[p + 3];\n      if (distance >= range) x0 = Math.max(x0, b);\n      else if (distance <= -range) x1 = Math.min(x1, b - 1);\n    }\n    if (x0 > x1) continue;\n\n    let y0 = 0;\n    let y1 = LIGHT_TILES_Y - 1;\n    for (let b = 0; b <= LIGHT_TILES_Y; b++) {\n      const p = rowPlanes + b * 4;\n      const distance = gridPlanes[p] * px + gridPlanes[p + 1] * py + gridPlanes[p + 2] * pz + gridPlanes[p + 3];\n      if (distance >= range) y0 = Math.max(y0, b);\n      else if (distance <= -range) y1 = Math.min(y1, b - 1);\n    }\n    if (y0 > y1) continue;\n\n    finiteLights |= bit;\n    const depth = -(v[2] * px + v[6] * py + v[10] * pz + v[14]);\n    const radius = range * depthRadiusScale;\n    minDepth = Math.min(minDepth, depth - radius);\n    maxDepth = Math.max(maxDepth, depth + radius);\n\n    for (let ty = y0; ty <= y1; ty++) {\n      const row = ty * LIGHT_TILES_X;\n      for (let tx = x0; tx <= x1; tx++) out[row + tx] |= bit;\n    }\n  }\n\n  if (everywhere !== 0) {\n    const tileCount = LIGHT_TILES_X * LIGHT_TILES_Y;\n    for (let t = 0; t < tileCount; t++) out[t] |= everywhere;\n  }\n  depthMasks.fill(everywhere);\n  depthPlane.fill(0);\n  if (finiteLights === 0) return;\n\n  if (wLength > 0) minDepth = Math.max(minDepth, 0);\n\n  const scale = LIGHT_DEPTH_BINS / Math.max(maxDepth - minDepth, 1e-6);\n  depthPlane[0] = -v[2] * scale;\n  depthPlane[1] = -v[6] * scale;\n  depthPlane[2] = -v[10] * scale;\n  depthPlane[3] = (-v[14] - minDepth) * scale;\n  const radiusScale = Math.hypot(depthPlane[0], depthPlane[1], depthPlane[2]);\n\n  for (let i = 0; i < lightCount; i++) {\n    const bit = 1 << i;\n    if ((finiteLights & bit) === 0) continue;\n    const o = i * FLOATS_PER_LIGHT;\n    const x = lightData[o] * depthPlane[0];\n    const y = lightData[o + 1] * depthPlane[1];\n    const z = lightData[o + 2] * depthPlane[2];\n    const center = x + y + z + depthPlane[3];\n    const radius = Math.sqrt(lightData[o + 7]) * radiusScale;\n    const padding = (Math.abs(x) + Math.abs(y) + Math.abs(z) + Math.abs(depthPlane[3]) + radius) * 1e-6 + 1e-5;\n    const first = Math.max(0, Math.min(LIGHT_DEPTH_BINS - 1, Math.floor(center - radius - padding)));\n    const last = Math.max(0, Math.min(LIGHT_DEPTH_BINS - 1, Math.floor(center + radius + padding)));\n    for (let bin = first; bin <= last; bin++) depthMasks[bin] |= bit;\n  }\n}\n\n/** @internal */\nexport class LightTiles {\n  /** Both mask arrays start with every bit set, so nothing is rejected before the first `prepare` */\n  public readonly masks = new Int32Array(LIGHT_TILE_LANES * 4).fill(-1);\n  public readonly depthMasks = new Int32Array(LIGHT_DEPTH_LANES * 4).fill(-1);\n  public readonly depthPlane = new Float32Array(4);\n  public readonly tileTransform = new Float32Array(4);\n\n  private _session: RenderSession | null = null;\n\n  public prepare(session: RenderSession, viewProjection: Matrix4, view: Matrix4): boolean {\n    if (this._session === session) return false;\n    this._session = session;\n\n    const lights = session.view3d._lightDataList;\n    binLightTiles(this.masks, lights.data, lights.count, viewProjection, view, this.depthMasks, this.depthPlane);\n\n    return true;\n  }\n\n  public setViewport(rect: ReadonlyRect, topDown: boolean): boolean {\n    const t = this.tileTransform;\n    const scaleX = Math.fround(LIGHT_TILES_X / rect.width);\n    const scaleY = Math.fround((topDown ? -LIGHT_TILES_Y : LIGHT_TILES_Y) / rect.height);\n    const offsetX = Math.fround(-rect.x * scaleX);\n    const offsetY = Math.fround((topDown ? LIGHT_TILES_Y : 0) - rect.y * scaleY);\n\n    if (t[0] === scaleX && t[1] === scaleY && t[2] === offsetX && t[3] === offsetY) return false;\n    t[0] = scaleX;\n    t[1] = scaleY;\n    t[2] = offsetX;\n    t[3] = offsetY;\n\n    return true;\n  }\n\n  public invalidate(): void {\n    this._session = null;\n  }\n\n  /** Drops the session, which holds the view and the renderer */\n  public destroy(): void {\n    this.invalidate();\n  }\n}\n","import { MAX_LIGHTS } from '../lightLimits';\nimport { LIGHT_DEPTH_BINS, LIGHT_TILES_X, LIGHT_TILES_Y } from '../LightTiles';\nimport type { ShaderBit } from './ShaderBit';\n\n/** Unpacks a light in `LightDataList`'s layout; the include guard lets two lighting bits share a shader */\nconst GL_GET_LIGHT_HELPER = /*glsl*/ `\n#ifndef PIXIJS_3D_GET_LIGHT_DEFINED\n#define PIXIJS_3D_GET_LIGHT_DEFINED\nLight getLight(int index) {\n  int offset = index * 4;\n  vec4 d0 = uLightData[offset + 0];\n  vec4 d1 = uLightData[offset + 1];\n  vec4 d2 = uLightData[offset + 2];\n  vec4 d3 = uLightData[offset + 3];\n\n  Light l;\n  l.position = d0.xyz;\n  l.type = d0.w;\n  l.color = d1.xyz;\n  l.rangeSq = d1.w;\n  l.direction = d2.xyz;\n  l.coneCos = d2.w;\n  l.innerConeCos = d3.x;\n  l.shadowDataIndex = d3.y;\n  l.radiusPow4 = d3.w;\n  return l;\n}\n#endif\n`;\n\n/**\n * Options for {@link createLightingBit}: the shading math of a lighting model, such as toon or\n * Blinn-Phong, around a light loop the factory writes\n *\n * The generated fragment `lighting` slot runs:\n *\n * ```text\n * preLighting\n * for (each light that can reach this fragment) {\n *   work out light, lightDir, attenuation, nDotL and shadow, or skip the light\n *   perLight\n * }\n * postLighting\n * ```\n *\n * 1. In `preLighting`, declare and zero your accumulators, such as `directLight`, and work out\n *    anything that doesn't depend on the light, such as `nDotV`.\n * 2. In `perLight`, add this light's share to them. `continue;` skips the rest of this light.\n *    Lights that don't reach the fragment or that the surface faces away from never get here.\n * 3. In `postLighting`, write `finalColor` from the accumulators and whatever the material bit\n *    declared, such as `emissive`. Exposure, fog and tone mapping run after it.\n *\n * The loop sits in a block of its own, so names these snippets declare aren't visible to later\n * slots such as `end`.\n *\n * ## What `perLight` can read\n *\n * | Name          | Type    | Value                                                         |\n * |---------------|---------|---------------------------------------------------------------|\n * | `light`       | `Light` | this light                                                    |\n * | `lightDir`    | `vec3`  | normalized, from the fragment toward the light                |\n * | `attenuation` | `f32`   | distance falloff times the spot cone, above 0                 |\n * | `nDotL`       | `f32`   | `max(dot(normal, lightDir), 0)`, above 0                      |\n * | `shadow`      | `f32`   | 1 lit, 0 shadowed                                             |\n * | `normal`      | `vec3`  | the world-space surface normal, as the material bits left it  |\n * | `viewDir`     | `vec3`  | normalized, toward the camera; declared by the material bit   |\n *\n * Anything else the model needs, such as `albedo` and `roughness`, comes from the material bit\n * that runs before it. The light's kind is `light.kind` in WGSL and `light.type` in GLSL; compare\n * it with `LIGHT_DIRECTIONAL`, `LIGHT_POINT` or `LIGHT_SPOT`.\n *\n * ## Lobes\n *\n * Another bit in the descriptor can add per-light math to this loop, rather than run a second loop\n * that samples every shadow again, through the fragment slots `lobePreLighting`, `lobePerLight`\n * and `lobePostLighting`. Each runs after the matching snippet here, in the order the lobe bits are\n * listed, so `lobePostLighting` sees the assembled `finalColor` and can rewrite it.\n *\n * ## Requirements\n *\n * Use the bit in a material with {@link BaseMaterial3D#lit} on, the default. A pass's own shader\n * can't run it.\n * @category rendering\n * @advanced\n */\nexport interface CreateLightingBitOptions {\n  /** The bit's {@link ShaderBit#name}, which must be unique */\n  name: string;\n\n  /** Bindings the model needs, such as its own `material` fields */\n  bindings?: ShaderBit['bindings'];\n  /** Structs the model declares */\n  structs?: ShaderBit['structs'];\n  /** Textures the model samples, such as a lookup table */\n  textures?: string[];\n\n  /** Bits the model needs in the shader, such as {@link mathConstantsBit} for `PI` and `INV_PI` */\n  requires?: ShaderBit[];\n\n  /** Code for the `{{header}}` slot, such as helper functions and constants */\n  header?: {\n    /** WGSL source (WebGPU) */\n    gpu?: string;\n    /** GLSL source (WebGL) */\n    gl?: string;\n  };\n\n  /**\n   * Code that runs once, before the light loop\n   *\n   * Declare the accumulators here, and anything that doesn't depend on the light. What it declares\n   * stays in scope for `perLight` and `postLighting`.\n   */\n  preLighting?: {\n    /** WGSL source (WebGPU) */\n    gpu?: string;\n    /** GLSL source (WebGL) */\n    gl?: string;\n  };\n\n  /** The shading math for one light, run inside the loop; {@link CreateLightingBitOptions} lists what it reads */\n  perLight: {\n    /** WGSL source (WebGPU) */\n    gpu?: string;\n    /** GLSL source (WebGL) */\n    gl?: string;\n  };\n\n  /**\n   * Code that runs once, after the light loop\n   *\n   * It writes the template's `finalColor`, as in\n   * `finalColor = ambient * occlusion + directLight + emissive;`.\n   */\n  postLighting?: {\n    /** WGSL source (WebGPU) */\n    gpu?: string;\n    /** GLSL source (WebGL) */\n    gl?: string;\n  };\n}\n\n/**\n * Builds a lighting `ShaderBit` around the shading math in `opts`\n *\n * Call it once at module scope and list the bit in a material's `bitsGpu` and `bitsGl`.\n * {@link CreateLightingBitOptions} says what each snippet can read.\n * @example A diffuse-only Lambert model\n *\n * ```ts\n * export const lambertLightingBit = createLightingBit({\n *   name: 'lambertLighting',\n *\n *   preLighting: {\n *     gpu: 'var directLight = vec3<f32>(0.0);',\n *     gl:  'vec3 directLight = vec3(0.0);',\n *   },\n *\n *   perLight: {\n *     gpu: 'directLight += albedo * light.color * nDotL * attenuation * shadow;',\n *     gl:  'directLight += albedo * light.color * nDotL * attenuation * shadow;',\n *   },\n *\n *   postLighting: {\n *     gpu: 'finalColor = directLight;',\n *     gl:  'finalColor = directLight;',\n *   },\n * });\n * ```\n *\n * The PBR material's Cook-Torrance lighting and the toon material's `toonLightingBit` are built the\n * same way.\n * @param opts - The lighting model's snippets and metadata\n * @returns The composed lighting bit\n * @category rendering\n * @advanced\n */\nexport function createLightingBit(opts: CreateLightingBitOptions): ShaderBit {\n  const wgslLoop = /*wgsl*/ `\n{\n${opts.preLighting?.gpu ?? ''}\n{{fragmentLobePreLighting}}\n\n  let lightTile = clamp(\n    vec2<i32>(input.position.xy * camera.uLightTileTransform.xy + camera.uLightTileTransform.zw),\n    vec2<i32>(0),\n    vec2<i32>(${LIGHT_TILES_X - 1}, ${LIGHT_TILES_Y - 1})\n  );\n  let lightTileIndex = lightTile.y * ${LIGHT_TILES_X} + lightTile.x;\n  let lightDepthIndex = i32(clamp(\n    dot(camera.uLightDepthPlane, vec4<f32>(input.vPosition, 1.0)), 0.0, ${LIGHT_DEPTH_BINS - 1}.0\n  ));\n  var lightMask = u32(camera.uLightTiles[lightTileIndex >> 2][lightTileIndex & 3]) &\n    u32(camera.uLightDepthMasks[lightDepthIndex >> 2][lightDepthIndex & 3]);\n\n  for (var n: i32 = 0; n < ${MAX_LIGHTS}; n++) {\n    if (lightMask == 0u) { break; }\n    let i = i32(firstTrailingBit(lightMask));\n    lightMask &= lightMask - 1u;\n\n    let lightOffset = i * 4;\n    let light0 = global.uLightData[lightOffset];\n    let light1 = global.uLightData[lightOffset + 1];\n    let light2 = global.uLightData[lightOffset + 2];\n    let light3 = global.uLightData[lightOffset + 3];\n    let light = Light(light0.xyz, light0.w, light1.xyz, light1.w, light2.xyz, light2.w, light3.x, light3.y, light3.z, light3.w);\n\n    var lightDir: vec3<f32>;\n    var attenuation: f32 = 1.0;\n\n    if (light.kind == LIGHT_DIRECTIONAL) {\n      lightDir = -light.direction;\n    } else {\n      let toLight = light.position - input.vPosition;\n      let distanceSq = dot(toLight, toLight);\n\n      if (light.rangeSq > 0.0) {\n        if (distanceSq >= light.rangeSq) { continue; }\n\n        let distRatio = distanceSq / light.rangeSq;\n        let windowFalloff = saturate(1.0 - distRatio * distRatio);\n        attenuation = windowFalloff * windowFalloff * inverseSqrt(distanceSq * distanceSq + light.radiusPow4);\n      } else {\n        attenuation = inverseSqrt(distanceSq * distanceSq + light.radiusPow4);\n      }\n\n      lightDir = toLight * inverseSqrt(distanceSq);\n\n      if (light.kind == LIGHT_SPOT) {\n        let spotCos = dot(-lightDir, light.direction);\n        let spotAtten = saturate((spotCos - light.coneCos) / max(light.innerConeCos - light.coneCos, 1e-6));\n        attenuation *= spotAtten * spotAtten;\n      }\n    }\n\n    if (attenuation <= 0.0) { continue; }\n\n    let nDotL = max(dot(normal, lightDir), 0.0);\n    if (nDotL <= 0.0) { continue; }\n\n    let shadow = calculateShadow(light.shadowDataIndex, light.cascadeCount, input.vPosition, normal, nDotL);\n\n${opts.perLight.gpu ?? ''}\n{{fragmentLobePerLight}}\n  }\n\n${opts.postLighting?.gpu ?? ''}\n{{fragmentLobePostLighting}}\n}\n`;\n\n  /**\n   * Keeps a fixed `MAX_LIGHTS` trip count, since some GL compilers make an unbounded loop far slower,\n   * and reads the light index off the lowest bit's float exponent, as GLSL ES 3.00 has no `findLSB`\n   */\n  const glslLoop = /*glsl*/ `\n{\n${opts.preLighting?.gl ?? ''}\n{{lobePreLighting}}\n\n  ivec2 lightTile = clamp(\n    ivec2(gl_FragCoord.xy * uLightTileTransform.xy + uLightTileTransform.zw),\n    ivec2(0),\n    ivec2(${LIGHT_TILES_X - 1}, ${LIGHT_TILES_Y - 1})\n  );\n  int lightTileIndex = lightTile.y * ${LIGHT_TILES_X} + lightTile.x;\n  int lightDepthIndex = int(clamp(\n    dot(uLightDepthPlane, vec4(vPosition, 1.0)), 0.0, ${LIGHT_DEPTH_BINS - 1}.0\n  ));\n  uint lightMask = uint(uLightTiles[lightTileIndex >> 2][lightTileIndex & 3]) &\n    uint(uLightDepthMasks[lightDepthIndex >> 2][lightDepthIndex & 3]);\n\n  for (int n = 0; n < ${MAX_LIGHTS}; n++) {\n    if (lightMask == 0u) break;\n    uint lowestBit = lightMask & (0u - lightMask);\n    int i = int(floatBitsToUint(float(lowestBit)) >> 23u) - 127;\n    lightMask &= lightMask - 1u;\n\n    Light light = getLight(i);\n\n    vec3 lightDir;\n    float attenuation = 1.0;\n\n    if (light.type == LIGHT_DIRECTIONAL) {\n      lightDir = -light.direction;\n    } else {\n      vec3 toLight = light.position - vPosition;\n      float distanceSq = dot(toLight, toLight);\n\n      if (light.rangeSq > 0.0) {\n        if (distanceSq >= light.rangeSq) continue;\n\n        float distRatio = distanceSq / light.rangeSq;\n        float windowFalloff = clamp(1.0 - distRatio * distRatio, 0.0, 1.0);\n        attenuation = windowFalloff * windowFalloff * inversesqrt(distanceSq * distanceSq + light.radiusPow4);\n      } else {\n        attenuation = inversesqrt(distanceSq * distanceSq + light.radiusPow4);\n      }\n\n      lightDir = toLight * inversesqrt(distanceSq);\n\n      if (light.type == LIGHT_SPOT) {\n        float spotCos = dot(-lightDir, light.direction);\n        float spotAtten = clamp((spotCos - light.coneCos) / max(light.innerConeCos - light.coneCos, 1e-6), 0.0, 1.0);\n        attenuation *= spotAtten * spotAtten;\n      }\n    }\n\n    if (attenuation <= 0.0) continue;\n\n    float nDotL = max(dot(normal, lightDir), 0.0);\n    if (nDotL <= 0.0) continue;\n\n    float shadow = calculateShadow(light, vPosition, normal, nDotL);\n\n${opts.perLight.gl ?? ''}\n{{lobePerLight}}\n  }\n\n${opts.postLighting?.gl ?? ''}\n{{lobePostLighting}}\n}\n`;\n\n  return {\n    name: opts.name,\n    requires: opts.requires,\n    structs: opts.structs,\n    bindings: opts.bindings,\n    textures: opts.textures,\n\n    gpu: {\n      header: opts.header?.gpu,\n      fragment: { lighting: wgslLoop },\n    },\n\n    gl: {\n      header: `${GL_GET_LIGHT_HELPER}\\n${opts.header?.gl ?? ''}`,\n      fragment: { lighting: glslLoop },\n    },\n  };\n}\n","import { mathConstantsBit } from '../../../core/shader/bits/mathConstantsBit';\nimport { createLightingBit } from '../../../core/shader/createLightingBit';\n\n/**\n * The GGX divide takes no epsilon, which would flatten smooth highlights; `pbrMaterialBit` floors roughness\n * instead. The sheen and anisotropy lobes read this bit's locals, and anisotropy replaces its `specular`\n * @internal\n */\nexport const pbrLightingBit = createLightingBit({\n  name: 'pbrLighting',\n\n  requires: [mathConstantsBit],\n\n  preLighting: {\n    gpu: /*wgsl*/ `\n  directLight = vec3<f32>(0.0);\n\n  ambient += global.uGlobalLightParams.xyz * albedo * (1.0 - metallic) * INV_PI;\n\n  let nDotV = max(dot(normal, viewDir), 0.0);\n  let a = roughness * roughness;\n  let a2 = a * a;\n  let a2_inv_pi = a2 * INV_PI;\n  let oneMinusA = 1.0 - a;\n  let visV = nDotV * oneMinusA + a;\n  let albedoOverPI = albedo * INV_PI;\n`,\n    gl: /*glsl*/ `\n  directLight = vec3(0.0);\n\n  ambient += uGlobalLightParams.xyz * albedo * (1.0 - metallic) * INV_PI;\n\n  float nDotV = max(dot(normal, viewDir), 0.0);\n  float a = roughness * roughness;\n  float a2 = a * a;\n  float a2_inv_pi = a2 * INV_PI;\n  float oneMinusA = 1.0 - a;\n  float visV = nDotV * oneMinusA + a;\n  vec3 albedoOverPI = albedo * INV_PI;\n`,\n  },\n\n  perLight: {\n    gpu: /*wgsl*/ `\n    let halfVector = normalize(viewDir + lightDir);\n    let hDotV = max(dot(halfVector, viewDir), 0.0);\n\n    let nDotH = max(dot(normal, halfVector), 0.0);\n    let dDenom = (nDotH * nDotH * (a2 - 1.0) + 1.0);\n    let distribution = a2_inv_pi / (dDenom * dDenom);\n\n    let vis = 0.5 / max(nDotL * visV + nDotV * (nDotL * oneMinusA + a), 1e-6);\n\n    let fc5 = exp2((-5.55473 * hDotV - 6.98316) * hDotV);\n    let fresnel = fresnelF0 + (vec3<f32>(f90) - fresnelF0) * fc5;\n\n    let specular = distribution * fresnel * vis;\n    let diffuseWeight = (vec3<f32>(1.0) - fresnel) * (1.0 - metallic);\n\n    let radiance = light.color * attenuation;\n    directLight += (diffuseWeight * albedoOverPI + specular) * radiance * nDotL * shadow;\n`,\n    gl: /*glsl*/ `\n    vec3 halfVector = normalize(viewDir + lightDir);\n    float hDotV = max(dot(halfVector, viewDir), 0.0);\n\n    float nDotH = max(dot(normal, halfVector), 0.0);\n    float dDenom = (nDotH * nDotH * (a2 - 1.0) + 1.0);\n    float distribution = a2_inv_pi / (dDenom * dDenom);\n\n    float vis = 0.5 / max(nDotL * visV + nDotV * (nDotL * oneMinusA + a), 1e-6);\n\n    float fc5 = exp2((-5.55473 * hDotV - 6.98316) * hDotV);\n    vec3 fresnel = fresnelF0 + (vec3(f90) - fresnelF0) * fc5;\n\n    vec3 specular = distribution * fresnel * vis;\n    vec3 diffuseWeight = (vec3(1.0) - fresnel) * (1.0 - metallic);\n\n    vec3 radiance = light.color * attenuation;\n    directLight += (diffuseWeight * albedoOverPI + specular) * radiance * nDotL * shadow;\n`,\n  },\n\n  postLighting: {\n    gpu: /*wgsl*/ `\n  finalColor = (ambient * occlusion) + directLight + emissive;\n`,\n    gl: /*glsl*/ `\n  finalColor = (ambient * occlusion) + directLight + emissive;\n`,\n  },\n});\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Floors roughness at 0.045 for `pbrLightingBit`'s unguarded GGX divide. Declares the `normal` slot,\n * `normalScale` and `alphaCutoff` for normal mapping and `alphaMaskBit`, which join after the layout is fixed\n * @internal\n */\nexport const pbrMaterialBit: ShaderBit = {\n  name: 'pbrMaterial',\n\n  textures: ['baseColor', 'metallicRoughness', 'occlusion', 'normal'],\n  bindings: {\n    material: {\n      baseColor: 'vec4<f32>',\n      alphaCutoff: 'f32',\n      pbrParams: 'vec4<f32>',\n      transmissionVolume: 'vec4<f32>',\n      attenuationColorIrid: 'vec4<f32>',\n      normalScale: 'f32',\n    },\n  },\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  var viewDir: vec3<f32>;\n  var metallic: f32 = 0.0;\n  var roughness: f32 = 1.0;\n  var fresnelF0: vec3<f32>;\n  var f90: f32 = 1.0;\n  var emissive: vec3<f32> = vec3<f32>(0.0);\n  var occlusion: f32 = 1.0;\n  var directLight: vec3<f32> = vec3<f32>(0.0);\n  var ambient: vec3<f32> = vec3<f32>(0.0);\n\n  var baseColor = material.baseColor;\n  metallic = material.pbrParams.x;\n  roughness = material.pbrParams.y;\n  occlusion = material.pbrParams.z;\n\n  let ior = material.pbrParams.w;\n  let iorRatio = (ior - 1.0) / (ior + 1.0);\n  fresnelF0 = vec3<f32>(iorRatio * iorRatio);\n\n  var baseTex = sampleBaseColor(input.vUV);\n  let baseTexLinear = baseTex.rgb / max(baseTex.a, 0.001);\n  baseTex = vec4<f32>(pow(baseTexLinear, vec3<f32>(2.2)), baseTex.a);\n  baseColor *= baseTex;\n\n  let mrTex = sampleMetallicRoughness(input.vUV);\n  metallic *= mrTex.b;\n  roughness *= mrTex.g;\n\n  occlusion *= sampleOcclusion(input.vUV).r;\n\n  let dNdx = abs(dpdx(normal));\n  let dNdy = abs(dpdy(normal));\n  let dN = max(dNdx, dNdy);\n  let geometricRoughness = max(max(dN.x, dN.y), dN.z);\n  roughness = clamp(max(roughness, 0.045) + geometricRoughness, 0.0, 1.0);\n\n  albedo *= baseColor.rgb;\n  alpha *= baseColor.a;\n\n  viewDir = normalize(camera.uCameraPosition.xyz - input.vPosition);\n  fresnelF0 = mix(fresnelF0, albedo, metallic);\n\n  var specularNormal = normal;\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  vec3 viewDir;\n  float metallic = 0.0;\n  float roughness = 1.0;\n  vec3 fresnelF0;\n  float f90 = 1.0;\n  vec3 emissive = vec3(0.0);\n  float occlusion = 1.0;\n  vec3 directLight = vec3(0.0);\n  vec3 ambient = vec3(0.0);\n\n  vec4 baseColor = material.baseColor;\n  metallic = material.pbrParams.x;\n  roughness = material.pbrParams.y;\n  occlusion = material.pbrParams.z;\n\n  float ior = material.pbrParams.w;\n  float iorRatio = (ior - 1.0) / (ior + 1.0);\n  fresnelF0 = vec3(iorRatio * iorRatio);\n\n  vec4 baseTex = sampleBaseColor(vUV);\n  vec3 baseTexLinear = baseTex.rgb / max(baseTex.a, 0.001);\n  baseTex.rgb = pow(baseTexLinear, vec3(2.2));\n  baseColor *= baseTex;\n\n  vec4 mrTex = sampleMetallicRoughness(vUV);\n  metallic *= mrTex.b;\n  roughness *= mrTex.g;\n\n  occlusion *= sampleOcclusion(vUV).r;\n\n  vec3 dNdx = abs(dFdx(normal));\n  vec3 dNdy = abs(dFdy(normal));\n  vec3 dN = max(dNdx, dNdy);\n  float geometricRoughness = max(max(dN.x, dN.y), dN.z);\n  roughness = clamp(max(roughness, 0.045) + geometricRoughness, 0.0, 1.0);\n\n  albedo *= baseColor.rgb;\n  alpha *= baseColor.a;\n\n  viewDir = normalize(uCameraPosition.xyz - vPosition);\n  fresnelF0 = mix(fresnelF0, albedo, metallic);\n\n  vec3 specularNormal = normal;\n`,\n    },\n  },\n};\n","import { mathConstantsBit } from '../../../core/shader/bits/mathConstantsBit';\nimport type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Reads `pbrLightingBit`'s `nDotH` and `nDotV`. The 0.07 roughness and 0.0078125 `sin2h` floors stop `pow`\n * underflowing on mobile GPUs with 16-bit floats. The colour is divided by alpha to undo pixi's premultiplied upload\n * @internal\n */\nexport const sheenBit: ShaderBit = {\n  name: 'sheen',\n\n  requires: [mathConstantsBit],\n\n  textures: ['sheen'],\n\n  bindings: {\n    material: {\n      sheenParams: 'vec4<f32>',\n    },\n  },\n\n  gpu: {\n    header: /*wgsl*/ `\nfn charlieD(charlieScale: f32, invAlphaHalf: f32, NdotH: f32) -> f32 {\n  let cos2h = NdotH * NdotH;\n  let sin2h = max(1.0 - cos2h, 0.0078125);\n  return charlieScale * pow(sin2h, invAlphaHalf);\n}\n\nfn ashikhminV(NdotL: f32, NdotV: f32) -> f32 {\n  return 1.0 / (4.0 * (NdotL + NdotV - NdotL * NdotV) + 1e-5);\n}\n\nfn sheenE(NdotV: f32, sheenRoughness: f32) -> f32 {\n  let r = sheenRoughness;\n  let a = mix(21.5473, 25.3245, r);\n  let b = mix(3.82987, 3.32435, r);\n  let c = mix(0.19823, 0.16801, r);\n  let d = mix(-1.97760, -1.27393, r);\n  let e = mix(-4.32054, -4.85967, r);\n  return a / (1.0 + b * pow(NdotV, c)) + d * NdotV + e;\n}\n`,\n\n    fragment: {\n      lobePreLighting: /*wgsl*/ `\n  let sheenTex = sampleSheen(input.vUV);\n  let sheenTexStraight = sheenTex.rgb / max(sheenTex.a, 0.001);\n  let sheenTexColor = pow(sheenTexStraight, vec3<f32>(2.2));\n  let sheenColor = material.sheenParams.rgb * sheenTexColor;\n\n  let sheenRoughnessIBL = clamp(material.sheenParams.a * sheenTex.a, 0.0, 1.0);\n  let sheenRoughness = max(sheenRoughnessIBL, 0.07);\n  let sheenAlpha = sheenRoughness * sheenRoughness;\n  let sheenInvAlpha = 1.0 / sheenAlpha;\n  let sheenInvAlphaHalf = sheenInvAlpha * 0.5;\n  let sheenCharlieScale = (2.0 + sheenInvAlpha) * INV_PI * 0.5;\n  let sheenMax = max(sheenColor.r, max(sheenColor.g, sheenColor.b));\n\n  var sheenLight = vec3<f32>(0.0);\n`,\n      lobePerLight: /*wgsl*/ `\n    {\n      let shD = charlieD(sheenCharlieScale, sheenInvAlphaHalf, nDotH);\n      let shV = ashikhminV(nDotL, nDotV);\n      sheenLight += sheenColor * shD * shV * nDotL * light.color * attenuation * shadow;\n    }\n`,\n      lobePostLighting: /*wgsl*/ `\n  let shR = reflect(-viewDir, normal);\n  let shPref = sampleEnvironment(shR, sheenRoughnessIBL);\n  let shE = clamp(sheenE(nDotV, sheenRoughnessIBL), 0.0, 1.0);\n  let sheenIBL = sheenColor * shPref * shE;\n  let sheenAlbedoScale = 1.0 - sheenMax * shE;\n  finalColor = finalColor * sheenAlbedoScale + sheenLight + sheenIBL;\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      header: /*glsl*/ `\nfloat charlieD(float charlieScale, float invAlphaHalf, float NdotH) {\n  float cos2h = NdotH * NdotH;\n  float sin2h = max(1.0 - cos2h, 0.0078125);\n  return charlieScale * pow(sin2h, invAlphaHalf);\n}\n\nfloat ashikhminV(float NdotL, float NdotV) {\n  return 1.0 / (4.0 * (NdotL + NdotV - NdotL * NdotV) + 1e-5);\n}\n\nfloat sheenE(float NdotV, float sheenRoughness) {\n  float r = sheenRoughness;\n  float a = mix(21.5473, 25.3245, r);\n  float b = mix(3.82987, 3.32435, r);\n  float c = mix(0.19823, 0.16801, r);\n  float d = mix(-1.97760, -1.27393, r);\n  float e = mix(-4.32054, -4.85967, r);\n  return a / (1.0 + b * pow(NdotV, c)) + d * NdotV + e;\n}\n`,\n      lobePreLighting: /*glsl*/ `\n  vec4 sheenTex = sampleSheen(vUV);\n  vec3 sheenTexStraight = sheenTex.rgb / max(sheenTex.a, 0.001);\n  vec3 sheenTexColor = pow(sheenTexStraight, vec3(2.2));\n  vec3 sheenColor = material.sheenParams.rgb * sheenTexColor;\n\n  float sheenRoughnessIBL = clamp(material.sheenParams.a * sheenTex.a, 0.0, 1.0);\n  float sheenRoughness = max(sheenRoughnessIBL, 0.07);\n  float sheenAlpha = sheenRoughness * sheenRoughness;\n  float sheenInvAlpha = 1.0 / sheenAlpha;\n  float sheenInvAlphaHalf = sheenInvAlpha * 0.5;\n  float sheenCharlieScale = (2.0 + sheenInvAlpha) * INV_PI * 0.5;\n  float sheenMax = max(sheenColor.r, max(sheenColor.g, sheenColor.b));\n\n  vec3 sheenLight = vec3(0.0);\n`,\n      lobePerLight: /*glsl*/ `\n    {\n      float shD = charlieD(sheenCharlieScale, sheenInvAlphaHalf, nDotH);\n      float shV = ashikhminV(nDotL, nDotV);\n      sheenLight += sheenColor * shD * shV * nDotL * light.color * attenuation * shadow;\n    }\n`,\n      lobePostLighting: /*glsl*/ `\n  vec3 shR = reflect(-viewDir, normal);\n  vec3 shPref = sampleEnvironment(shR, sheenRoughnessIBL);\n  float shE = clamp(sheenE(nDotV, sheenRoughnessIBL), 0.0, 1.0);\n  vec3 sheenIBL = sheenColor * shPref * shE;\n  float sheenAlbedoScale = 1.0 - sheenMax * shE;\n  finalColor = finalColor * sheenAlbedoScale + sheenLight + sheenIBL;\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Rebuilds F0 from the IOR, as `pbrMaterialBit` has already mixed in the metal. The texture's alpha holds\n * the factor, so the tint is divided by it to undo pixi's premultiplied upload before decoding\n * @internal\n */\nexport const specularBit: ShaderBit = {\n  name: 'specular',\n\n  textures: ['specular'],\n\n  bindings: {\n    material: {\n      specularParams: 'vec4<f32>',\n    },\n  },\n\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  {\n    let specTex = sampleSpecular(input.vUV);\n    let specTexStraight = specTex.rgb / max(specTex.a, 0.001);\n    let specTexColor = pow(specTexStraight, vec3<f32>(2.2));\n    let specColor = material.specularParams.rgb * specTexColor;\n    let specFactor = material.specularParams.w * specTex.a;\n\n    let ior = material.pbrParams.w;\n    let iorRatio = (ior - 1.0) / (ior + 1.0);\n    let iorF0 = vec3<f32>(iorRatio * iorRatio);\n    let dielectricF0 = min(iorF0 * specColor, vec3<f32>(1.0)) * specFactor;\n\n    fresnelF0 = mix(dielectricF0, albedo, metallic);\n    f90 = mix(specFactor, 1.0, metallic);\n  }\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  {\n    vec4 specTex = sampleSpecular(vUV);\n    vec3 specTexStraight = specTex.rgb / max(specTex.a, 0.001);\n    vec3 specTexColor = pow(specTexStraight, vec3(2.2));\n    vec3 specColor = material.specularParams.rgb * specTexColor;\n    float specFactor = material.specularParams.w * specTex.a;\n\n    float ior = material.pbrParams.w;\n    float iorRatio = (ior - 1.0) / (ior + 1.0);\n    vec3 iorF0 = vec3(iorRatio * iorRatio);\n    vec3 dielectricF0 = min(iorF0 * specColor, vec3(1.0)) * specFactor;\n\n    fresnelF0 = mix(dielectricF0, albedo, metallic);\n    f90 = mix(specFactor, 1.0, metallic);\n  }\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Shader helpers that sample the opaque pass's colour or depth copy at a world position, for custom\n * material bits such as refraction or water\n *\n * List it in your bit's `requires` to get:\n *\n * - `screenUVFromWorld(worldPos)`: the UV of a world position in a screen copy, for an offset\n *   refraction tap or a depth `textureLoad`. A copy can be larger than the view, so the UV is scaled\n *   and clamped to the part the view fills.\n * - `sampleScreenCopy(tex, [sampler,] worldPos, lod)`: samples a colour copy there at mip `lod`,\n *   keeping a blurred tap inside the view's part of the copy. WGSL takes a sampler and GLSL doesn't.\n *   Colour only: load depth with `textureLoad`.\n * @category rendering\n * @advanced\n */\nexport const screenSpaceFuncsBit: ShaderBit = {\n  name: 'screenSpaceFuncs',\n  gpu: {\n    header: /*wgsl*/ `\nfn screenUVFromWorld(worldPos: vec3<f32>) -> vec2<f32> {\n  let clip = camera.uViewProjectionMatrix * vec4<f32>(worldPos, 1.0);\n  let ndc = clip.xy / clip.w;\n  let uv = vec2<f32>(ndc.x * 0.5 + 0.5, 1.0 - (ndc.y * 0.5 + 0.5)) * camera.uViewportUVScale;\n  return clamp(uv, vec2<f32>(0.0), camera.uViewportUVScale);\n}\n\nfn sampleScreenCopy(tex: texture_2d<f32>, samp: sampler, worldPos: vec3<f32>, lod: f32) -> vec4<f32> {\n  let texDims = vec2<f32>(textureDimensions(tex));\n  let inset = min(exp2(lod) * 0.5 / texDims, camera.uViewportUVScale * 0.5);\n  let uv = clamp(screenUVFromWorld(worldPos), inset, camera.uViewportUVScale - inset);\n  return textureSampleLevel(tex, samp, uv, lod);\n}\n`,\n  },\n  gl: {\n    header: /*glsl*/ `\nvec2 screenUVFromWorld(vec3 worldPos) {\n  vec4 clip = uViewProjectionMatrix * vec4(worldPos, 1.0);\n  vec2 uv = (clip.xy / clip.w * 0.5 + 0.5) * uViewportUVScale;\n  return clamp(uv, vec2(0.0), uViewportUVScale);\n}\n\nvec4 sampleScreenCopy(sampler2D tex, vec3 worldPos, float lod) {\n  vec2 texDims = vec2(textureSize(tex, 0));\n  vec2 inset = min(exp2(lod) * 0.5 / texDims, uViewportUVScale * 0.5);\n  vec2 uv = clamp(screenUVFromWorld(worldPos), inset, uViewportUVScale - inset);\n  return textureLod(tex, uv, lod);\n}\n`,\n  },\n};\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\nimport { screenSpaceFuncsBit } from './screenSpaceFuncsBit';\n\n/**\n * Adds what shows through to the unlit `emissive`, so front lights don't shade it, and takes that share\n * out of `albedo`. WebGPU samples the opaque copy with `uBrdfLutSampler`, whose linear mip filter the blur needs\n * @internal\n */\nexport const transmissionBit: ShaderBit = {\n  name: 'transmission',\n  requires: [screenSpaceFuncsBit],\n  textures: ['transmission', 'thickness'],\n\n  interStage: {\n    vModelScale: 'vec3<f32>',\n  },\n\n  bindings: {\n    material: {\n      pbrParams: 'vec4<f32>',\n      transmissionVolume: 'vec4<f32>',\n      attenuationColorIrid: 'vec4<f32>',\n    },\n  },\n\n  gpu: {\n    vertex: {\n      end: /*wgsl*/ `\n  output.vModelScale = vec3<f32>(\n    length(modelMatrix[0].xyz),\n    length(modelMatrix[1].xyz),\n    length(modelMatrix[2].xyz)\n  );\n`,\n    },\n    fragment: {\n      material: /*wgsl*/ `\n  {\n    let transmissionFactor = material.transmissionVolume.x;\n    let thicknessFactor = material.transmissionVolume.y;\n    let ior = material.pbrParams.w;\n\n    let txFactor = transmissionFactor * sampleTransmission(input.vUV).r;\n    let thickness = thicknessFactor * sampleThickness(input.vUV).g;\n\n    let colorTexDims = vec2<f32>(textureDimensions(uOpaqueColorTexture));\n\n    let refractedDir = refract(-viewDir, normal, 1.0 / ior);\n    let transmissionRay = normalize(refractedDir) * thickness * input.vModelScale;\n    let exitPoint = input.vPosition + transmissionRay;\n\n    let txRoughness = roughness * clamp(ior * 2.0 - 2.0, 0.0, 1.0);\n    let txLod = log2(colorTexDims.x) * txRoughness;\n\n    var transmittedColor = sampleScreenCopy(uOpaqueColorTexture, uBrdfLutSampler, exitPoint, txLod).rgb;\n\n    transmittedColor = decodeToLinear(transmittedColor);\n\n    let attenuationDistance = material.transmissionVolume.z;\n    if (thickness > 0.0 && attenuationDistance < 1e9) {\n      let attenuationColor = material.attenuationColorIrid.rgb;\n      let attCoeff = -log(max(attenuationColor, vec3(1e-6))) / attenuationDistance;\n      transmittedColor *= exp(-attCoeff * length(transmissionRay));\n    }\n\n    let txIorRatio = (ior - 1.0) / (ior + 1.0);\n    let txF0 = txIorRatio * txIorRatio;\n    let txNdotV = max(dot(normal, viewDir), 0.0);\n    let txFc5 = exp2((-5.55473 * txNdotV - 6.98316) * txNdotV);\n    let txF = f90 * (txF0 + (1.0 - txF0) * txFc5);\n    let effectiveTx = txFactor * (1.0 - txF);\n\n    emissive += transmittedColor * albedo * effectiveTx;\n    albedo *= (1.0 - txFactor);\n  }\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      end: /*glsl*/ `\n  vModelScale = vec3(\n    length(modelMatrix[0].xyz),\n    length(modelMatrix[1].xyz),\n    length(modelMatrix[2].xyz)\n  );\n`,\n    },\n    fragment: {\n      material: /*glsl*/ `\n  {\n    float transmissionFactor = material.transmissionVolume.x;\n    float thicknessFactor = material.transmissionVolume.y;\n    float ior = material.pbrParams.w;\n\n    float txFactor = transmissionFactor * sampleTransmission(vUV).r;\n    float thickness = thicknessFactor * sampleThickness(vUV).g;\n\n    vec2 colorTexDims = vec2(textureSize(uOpaqueColorTexture, 0));\n\n    vec3 refractedDir = refract(-viewDir, normal, 1.0 / ior);\n    vec3 transmissionRay = normalize(refractedDir) * thickness * vModelScale;\n    vec3 exitPoint = vPosition + transmissionRay;\n\n    float txRoughness = roughness * clamp(ior * 2.0 - 2.0, 0.0, 1.0);\n    float txLod = log2(colorTexDims.x) * txRoughness;\n\n    vec3 transmittedColor = sampleScreenCopy(uOpaqueColorTexture, exitPoint, txLod).rgb;\n\n    transmittedColor = decodeToLinear(transmittedColor);\n\n    float attenuationDistance = material.transmissionVolume.z;\n    if (thickness > 0.0 && attenuationDistance < 1e9) {\n      vec3 attenuationColor = material.attenuationColorIrid.rgb;\n      vec3 attCoeff = -log(max(attenuationColor, vec3(1e-6))) / attenuationDistance;\n      transmittedColor *= exp(-attCoeff * length(transmissionRay));\n    }\n\n    float txIorRatio = (ior - 1.0) / (ior + 1.0);\n    float txF0 = txIorRatio * txIorRatio;\n    float txNdotV = max(dot(normal, viewDir), 0.0);\n    float txFc5 = exp2((-5.55473 * txNdotV - 6.98316) * txNdotV);\n    float txF = f90 * (txF0 + (1.0 - txF0) * txFc5);\n    float effectiveTx = txFactor * (1.0 - txF);\n\n    emissive += transmittedColor * albedo * effectiveTx;\n    albedo *= (1.0 - txFactor);\n  }\n`,\n    },\n  },\n};\n","import { Color } from 'pixi.js';\nimport type { ColorSource, Texture, TextureDestroyOptions, TypeOrBool } from 'pixi.js';\n\nimport { RenderPassBit } from '../../core/render-passes/RenderPass';\nimport { alphaMaskBit } from '../../core/shader/bits/alphaMaskBit';\nimport { anisotropyBit, anisotropyTextureBit } from '../../core/shader/bits/anisotropyBit';\nimport { emissiveBit } from '../../core/shader/bits/emissiveBit';\nimport { uvTransformBit } from '../../core/shader/bits/uvTransformBit';\nimport type { ShaderBit } from '../../core/shader/ShaderBit';\nimport { ShaderDescriptor } from '../../core/shader/ShaderDescriptor';\nimport { NORMAL_MAP } from '../../core/textures/DefaultTextures';\nimport type { View3D } from '../../scene/View3D';\nimport { BaseMaterial3D, writeLinearRgb } from '../BaseMaterial3D';\nimport type { BaseMaterial3DOptions } from '../BaseMaterial3D';\nimport { createFeaturePropsClass, readFeatureProps } from '../utils/createFeaturePropsClass';\nimport type { MaterialData } from '../utils/createMaterialDataClass';\nimport type { MaterialTextures } from '../utils/createMaterialTexturesClass';\nimport { EmissivePropsClass } from '../utils/emissiveProps';\nimport type { EmissiveOptions, EmissiveProps } from '../utils/emissiveProps';\nimport { clearcoatBit, clearcoatNormalMapBit } from './bits/clearcoatBit';\nimport { iblBit } from './bits/iblBit';\nimport { iridescenceBit } from './bits/iridescenceBit';\nimport { pbrLightingBit } from './bits/pbrLightingBit';\nimport { pbrMaterialBit } from './bits/pbrMaterialBit';\nimport { sheenBit } from './bits/sheenBit';\nimport { specularBit } from './bits/specularBit';\nimport { transmissionBit } from './bits/transmissionBit';\n\n/**\n * Options for a {@link Material3D}'s `specular` group (`KHR_materials_specular`): the strength and\n * tint of the reflection on non-metal surfaces\n * @example\n * ```ts\n * const varnish = new Material3D({ roughness: 0.3, specular: { factor: 0.6, color: 0xfff2dd } });\n * ```\n * @category materials\n * @standard\n */\nexport interface SpecularOptions {\n  /**\n   * Strength of the non-metal reflection, from 0 (none) to 1 (standard PBR)\n   * @default 1\n   * @example\n   * ```ts\n   * const matte = new Material3D({ specular: { factor: 0 } });\n   * ```\n   */\n  factor?: number;\n  /**\n   * Tint of the non-metal reflection\n   * @default 0xffffff\n   * @example\n   * ```ts\n   * const warm = new Material3D({ specular: { color: 0xffd0a0 } });\n   * ```\n   */\n  color?: ColorSource;\n  /**\n   * Strength map, read from alpha; used only when there is no `colorTexture`\n   *\n   * The two share a slot, so its colour channels tint the reflection too: keep them white.\n   * @example\n   * ```ts\n   * const worn = new Material3D({ specular: { texture: wearMask } });\n   * ```\n   */\n  texture?: Texture;\n  /**\n   * Tint in RGB and strength in alpha, the packed image; used over `texture` when both are given\n   * @example\n   * ```ts\n   * const packed = new Material3D({ specular: { colorTexture: specularMap } });\n   * ```\n   */\n  colorTexture?: Texture;\n}\n\n/**\n * Options for a {@link Material3D}'s `iridescence` group (`KHR_materials_iridescence`): a thin film\n * whose colour shifts with the viewing angle, like a soap bubble or an oil slick\n * @example\n * ```ts\n * const beetle = new Material3D({ metallic: 1, roughness: 0.2, iridescence: { thicknessMaximum: 500 } });\n * ```\n * @category materials\n * @standard\n */\nexport interface IridescenceOptions {\n  /**\n   * Strength of the effect, from 0 (none) to 1\n   * @default 1\n   * @example\n   * ```ts\n   * const hint = new Material3D({ iridescence: { factor: 0.3 } });\n   * ```\n   */\n  factor?: number;\n  /**\n   * Index of refraction of the film\n   * @default 1.3\n   * @example\n   * ```ts\n   * const oily = new Material3D({ iridescence: { ior: 1.5 } });\n   * ```\n   */\n  ior?: number;\n  /**\n   * Film thickness in nanometres where the texture's green channel is 0\n   *\n   * glTF's default is 100, which the glTF loader passes.\n   * @default 0\n   * @example\n   * ```ts\n   * const bubble = new Material3D({ iridescence: { thicknessMinimum: 100, thicknessTexture: filmMap } });\n   * ```\n   */\n  thicknessMinimum?: number;\n  /**\n   * Film thickness in nanometres where the texture's green channel is 1, and so the thickness\n   * everywhere when there is no texture\n   * @default 400\n   * @example\n   * ```ts\n   * const thickFilm = new Material3D({ iridescence: { thicknessMaximum: 800 } });\n   * ```\n   */\n  thicknessMaximum?: number;\n  /**\n   * Factor in red and thickness in green, the packed image; used over `thicknessTexture` when both\n   * are given\n   * @example\n   * ```ts\n   * const packed = new Material3D({ iridescence: { texture: iridescenceMap } });\n   * ```\n   */\n  texture?: Texture;\n  /**\n   * Thickness map, read from green; used only when there is no `texture`\n   *\n   * The two share a slot, so its red channel scales the factor too: keep it white.\n   * @example\n   * ```ts\n   * const swirl = new Material3D({ iridescence: { thicknessTexture: swirlMap } });\n   * ```\n   */\n  thicknessTexture?: Texture;\n}\n\n/**\n * Options for a {@link Material3D}'s `transmission` group (`KHR_materials_transmission` with\n * `KHR_materials_volume`): glass and other surfaces you see through\n *\n * Through a transmissive mesh you see the background and the opaque meshes, tinted by its base colour\n * and blurred by its roughness, but not other transmissive or blended meshes. On WebGL, glass in a\n * view drawn straight onto an opaque canvas shows nothing through. Start the application with\n * `useBackBuffer: true`, or, when the scene has `doubleSided` materials, whose lighting that option\n * breaks, give the view `composite: true`.\n * @example\n * ```ts\n * const glass = new Material3D({ roughness: 0.05, transmission: { thickness: 0.5 } });\n * ```\n * @category materials\n * @standard\n */\nexport interface TransmissionOptions {\n  /**\n   * How much light passes through, from 0 (opaque surface) to 1 (clear glass)\n   * @default 1\n   * @example\n   * ```ts\n   * const frosted = new Material3D({ roughness: 0.6, transmission: { factor: 0.9 } });\n   * ```\n   */\n  factor?: number;\n  /**\n   * Map whose red channel scales `factor`\n   * @example\n   * ```ts\n   * const stainedGlass = new Material3D({ transmission: { texture: leadingMask } });\n   * ```\n   */\n  texture?: Texture;\n  /**\n   * Thickness of the volume in the mesh's own units, scaled with the mesh\n   *\n   * 0 makes a thin wall: light doesn't bend and isn't absorbed.\n   * @default 0\n   * @example\n   * ```ts\n   * const block = new Material3D({ transmission: { thickness: 1 } });\n   * ```\n   */\n  thickness?: number;\n  /**\n   * Map whose green channel scales `thickness`\n   * @example\n   * ```ts\n   * const bottle = new Material3D({ transmission: { thickness: 0.3, thicknessTexture: wallThickness } });\n   * ```\n   */\n  thicknessTexture?: Texture;\n  /**\n   * Distance in world units that light travels through the volume before it takes on\n   * `attenuationColor`\n   *\n   * Left out, light isn't absorbed. Absorption also needs `thickness` above 0.\n   * @example\n   * ```ts\n   * const wine = new Material3D({\n   *   transmission: { thickness: 1, attenuationDistance: 1, attenuationColor: 0x7a0f1e },\n   * });\n   * ```\n   */\n  attenuationDistance?: number;\n  /**\n   * Colour white light turns after travelling `attenuationDistance` through the volume\n   * @default 0xffffff\n   * @example\n   * ```ts\n   * const bottleGreen = new Material3D({\n   *   transmission: { thickness: 0.5, attenuationDistance: 1, attenuationColor: 0x2e8b57 },\n   * });\n   * ```\n   */\n  attenuationColor?: ColorSource;\n}\n\n/**\n * Options for a {@link Material3D}'s `clearcoat` group (`KHR_materials_clearcoat`): a clear lacquer\n * layer on top, as on car paint or varnished wood\n * @example\n * ```ts\n * const carPaint = new Material3D({ baseColor: 0x8c1c13, roughness: 0.5, clearcoat: { roughness: 0.03 } });\n * ```\n * @category materials\n * @standard\n */\nexport interface ClearcoatOptions {\n  /**\n   * Strength of the coat, from 0 (none) to 1\n   * @default 1\n   * @example\n   * ```ts\n   * const satinVarnish = new Material3D({ clearcoat: { factor: 0.5 } });\n   * ```\n   */\n  factor?: number;\n  /**\n   * Roughness of the coat, independent of the surface underneath\n   * @default 0\n   * @example\n   * ```ts\n   * const hazyCoat = new Material3D({ clearcoat: { roughness: 0.4 } });\n   * ```\n   */\n  roughness?: number;\n  /**\n   * Strength of the coat normal map's bumps\n   * @default 1\n   * @example\n   * ```ts\n   * const orangePeel = new Material3D({ clearcoat: { normalTexture: peelNormals, normalScale: 0.3 } });\n   * ```\n   */\n  normalScale?: number;\n  /**\n   * Map whose red channel scales `factor`\n   * @example\n   * ```ts\n   * const chipped = new Material3D({ clearcoat: { texture: chipMask } });\n   * ```\n   */\n  texture?: Texture;\n  /**\n   * Map whose green channel scales `roughness`\n   * @example\n   * ```ts\n   * const smudged = new Material3D({ clearcoat: { roughness: 1, roughnessTexture: smudgeMap } });\n   * ```\n   */\n  roughnessTexture?: Texture;\n  /**\n   * Normal map for the coat alone, green up like {@link Material3DOptions#normalTexture}\n   *\n   * Pass it here to have one; to add one later, {@link BaseMaterial3D#clone | clone} the material\n   * with it. Without it the coat follows the geometry's normals, not the base normal map, and costs\n   * less.\n   * @example\n   * ```ts\n   * const dimpled = new Material3D({ clearcoat: { normalTexture: dimpleNormals } });\n   * ```\n   */\n  normalTexture?: Texture;\n}\n\n/**\n * Options for a {@link Material3D}'s `sheen` group (`KHR_materials_sheen`): the soft glow at grazing\n * angles on velvet, satin and other cloth\n * @example\n * ```ts\n * const velvet = new Material3D({ baseColor: 0x3b0a45, roughness: 0.9, sheen: { color: 0xd8a0ff } });\n * ```\n * @category materials\n * @standard\n */\nexport interface SheenOptions {\n  /**\n   * Colour of the sheen; black turns it off\n   * @default 0xffffff\n   * @example\n   * ```ts\n   * const silk = new Material3D({ sheen: { color: 0xfff0e0 } });\n   * ```\n   */\n  color?: ColorSource;\n  /**\n   * Roughness of the sheen, from 0 to 1\n   * @default 0\n   * @example\n   * ```ts\n   * const felt = new Material3D({ sheen: { roughness: 0.8 } });\n   * ```\n   */\n  roughness?: number;\n  /**\n   * Colour in RGB and roughness in alpha, the packed image; used over `roughnessTexture` when both\n   * are given\n   * @example\n   * ```ts\n   * const fabric = new Material3D({ sheen: { texture: sheenMap } });\n   * ```\n   */\n  texture?: Texture;\n  /**\n   * Roughness map, read from alpha; used only when there is no `texture`\n   *\n   * The two share a slot, so its colour channels tint the sheen too: keep them white.\n   * @example\n   * ```ts\n   * const worn = new Material3D({ sheen: { roughnessTexture: wearMap } });\n   * ```\n   */\n  roughnessTexture?: Texture;\n}\n\n/**\n * Options for a {@link Material3D}'s `anisotropy` group (`KHR_materials_anisotropy`): highlights\n * stretched along one direction, as on brushed metal, vinyl records or carbon fibre\n * @example\n * ```ts\n * const brushed = new Material3D({ metallic: 1, roughness: 0.4, anisotropy: { strength: 0.8 } });\n * ```\n * @category materials\n * @standard\n */\nexport interface AnisotropyOptions {\n  /**\n   * How strongly highlights stretch, from 0 to 1\n   * @default 1\n   * @example\n   * ```ts\n   * const lightlyBrushed = new Material3D({ anisotropy: { strength: 0.3 } });\n   * ```\n   */\n  strength?: number;\n  /**\n   * Rotation of the stretch direction in radians, starting from the surface's tangent\n   * @default 0\n   * @example\n   * ```ts\n   * const crossGrain = new Material3D({ anisotropy: { rotation: Math.PI / 2 } });\n   * ```\n   */\n  rotation?: number;\n  /**\n   * Per-texel direction in RG (a -1 to 1 vector stored as 0 to 1) and strength in B\n   *\n   * Pass it here to have one; to add one later, {@link BaseMaterial3D#clone | clone} the material\n   * with it. Without it the direction is the tangent, turned by `rotation`, everywhere.\n   * @example\n   * ```ts\n   * const carbonFibre = new Material3D({ anisotropy: { texture: weaveDirections } });\n   * ```\n   */\n  texture?: Texture;\n}\n\n/**\n * Options for {@link Material3D}\n *\n * Each extension (`emissive`, `specular`, `iridescence`, `transmission`, `clearcoat`, `sheen`,\n * `anisotropy`) is a group that turns the feature on when passed, even empty: `clearcoat: {}` adds a\n * full-strength coat. Inside a group, each factor and strength defaults to 1 and each colour to\n * white; the glTF loader passes each extension's own defaults instead.\n * @example\n * ```ts\n * const options: Material3DOptions = { baseColor: 0x8c1c13, roughness: 0.4, clearcoat: {} };\n * const carPaint = new Material3D(options);\n * ```\n * @category materials\n * @standard\n */\nexport interface Material3DOptions extends Omit<BaseMaterial3DOptions, 'descriptor'> {\n  /**\n   * Tangent-space normal map, green up as in glTF and OpenGL\n   *\n   * Invert the green channel of a DirectX-style map, or its bumps light from the wrong side. Needs UVs\n   * on the geometry, and uses its tangents when it has them. Can be assigned later through\n   * `material.textures.normal`; a material without one pays nothing for normal mapping.\n   * @example\n   * ```ts\n   * const bricks = new Material3D({ baseColorTexture: brickColour, normalTexture: brickNormals });\n   * ```\n   */\n  normalTexture?: Texture;\n  /**\n   * Strength of the normal map's bumps\n   * @default 1\n   * @example\n   * ```ts\n   * const shallow = new Material3D({ normalTexture: brickNormals, normalScale: 0.5 });\n   * ```\n   */\n  normalScale?: number;\n\n  /**\n   * Perceptual roughness, from 0 (mirror-like) to 1 (fully rough)\n   * @default 1\n   * @example\n   * ```ts\n   * const polished = new Material3D({ roughness: 0.1 });\n   * ```\n   */\n  roughness?: number;\n  /**\n   * Metalness, from 0 (non-metal) to 1 (metal)\n   * @default 0\n   * @example\n   * ```ts\n   * const gold = new Material3D({ baseColor: 0xffc356, metallic: 1, roughness: 0.25 });\n   * ```\n   */\n  metallic?: number;\n  /**\n   * Map with roughness in green and metalness in blue, as in glTF; scales `roughness` and\n   * `metallic`\n   * @example\n   * ```ts\n   * const rusty = new Material3D({ metallic: 1, metallicRoughnessTexture: rustMap });\n   * ```\n   */\n  metallicRoughnessTexture?: Texture;\n\n  /**\n   * Ambient occlusion map, read from red; it darkens ambient and environment light only\n   * @example\n   * ```ts\n   * const crate = new Material3D({ baseColorTexture: crateColour, occlusionTexture: crateOcclusion });\n   * ```\n   */\n  occlusionTexture?: Texture;\n  /**\n   * Multiplier on the occlusion, see {@link Material3D#occlusionStrength}\n   * @default 1\n   * @example\n   * ```ts\n   * const softer = new Material3D({ occlusionTexture: crateOcclusion, occlusionStrength: 0.8 });\n   * ```\n   */\n  occlusionStrength?: number;\n\n  /**\n   * Index of refraction, see {@link Material3D#ior}\n   * @default 1.5\n   * @example\n   * ```ts\n   * const water = new Material3D({ ior: 1.33, transmission: { thickness: 1 } });\n   * ```\n   */\n  ior?: number;\n\n  /**\n   * The material's own glow; passing the group turns it on\n   * @example\n   * ```ts\n   * const lava = new Material3D({ emissive: { texture: lavaGlow, strength: 4 } });\n   * ```\n   */\n  emissive?: EmissiveOptions;\n  /**\n   * Strength and tint of non-metal reflections; passing the group turns it on\n   * @example\n   * ```ts\n   * const lacquer = new Material3D({ specular: { color: 0xfff4e0 } });\n   * ```\n   */\n  specular?: SpecularOptions;\n  /**\n   * Thin-film colour shift; passing the group turns it on\n   * @example\n   * ```ts\n   * const soapBubble = new Material3D({ iridescence: {}, transmission: {} });\n   * ```\n   */\n  iridescence?: IridescenceOptions;\n  /**\n   * Glass and other see-through surfaces; passing the group turns it on\n   * @example\n   * ```ts\n   * const pane = new Material3D({ roughness: 0, transmission: {} });\n   * ```\n   */\n  transmission?: TransmissionOptions;\n  /**\n   * Clear lacquer layer on top; passing the group turns it on\n   * @example\n   * ```ts\n   * const pianoBlack = new Material3D({ baseColor: 0x050505, clearcoat: {} });\n   * ```\n   */\n  clearcoat?: ClearcoatOptions;\n  /**\n   * Cloth sheen; passing the group turns it on\n   * @example\n   * ```ts\n   * const cushion = new Material3D({ sheen: { color: 0xffffff, roughness: 0.5 } });\n   * ```\n   */\n  sheen?: SheenOptions;\n  /**\n   * Highlights stretched along one direction; passing the group turns it on\n   * @example\n   * ```ts\n   * const pan = new Material3D({ metallic: 1, anisotropy: {} });\n   * ```\n   */\n  anisotropy?: AnisotropyOptions;\n}\n\n/**\n * Runtime controls for a material's `specular` group, as `material.specular`\n * @example\n * ```ts\n * const material = new Material3D({ specular: {} });\n * material.specular!.factor = 0.25;\n * ```\n * @category materials\n * @standard\n */\nexport interface SpecularProps {\n  /**\n   * Strength of the non-metal reflection, from 0 (none) to 1 (standard PBR)\n   * @example\n   * ```ts\n   * material.specular!.factor = 0;\n   * ```\n   */\n  factor: number;\n  /**\n   * Tint of the non-metal reflection; takes any `ColorSource` and reads back a hex number, like\n   * `Container.tint`\n   * @example\n   * ```ts\n   * material.specular!.color = 0xffe0c0;\n   * ```\n   */\n  get color(): number;\n  /** Sets the tint from any `ColorSource` */\n  set color(value: ColorSource);\n  /**\n   * The packed map, tint in RGB and strength in alpha\n   * @example\n   * ```ts\n   * material.specular!.texture = await Assets.load('specular.png');\n   * ```\n   */\n  texture: Texture;\n}\n\n/**\n * Runtime controls for a material's `iridescence` group, as `material.iridescence`\n * @example\n * ```ts\n * const material = new Material3D({ iridescence: {} });\n * material.iridescence!.thicknessMaximum = 600;\n * ```\n * @category materials\n * @standard\n */\nexport interface IridescenceProps {\n  /**\n   * Strength of the effect, from 0 (none) to 1\n   * @example\n   * ```ts\n   * material.iridescence!.factor = 0.5;\n   * ```\n   */\n  factor: number;\n  /**\n   * Index of refraction of the film\n   * @example\n   * ```ts\n   * material.iridescence!.ior = 1.4;\n   * ```\n   */\n  ior: number;\n  /**\n   * Film thickness in nanometres where the texture's green channel is 0\n   * @example\n   * ```ts\n   * material.iridescence!.thicknessMinimum = 100;\n   * ```\n   */\n  thicknessMinimum: number;\n  /**\n   * Film thickness in nanometres where the texture's green channel is 1\n   * @example\n   * ```ts\n   * material.iridescence!.thicknessMaximum = 500;\n   * ```\n   */\n  thicknessMaximum: number;\n  /**\n   * The packed map, factor in red and thickness in green\n   * @example\n   * ```ts\n   * material.iridescence!.texture = await Assets.load('film.png');\n   * ```\n   */\n  texture: Texture;\n}\n\n/**\n * Runtime controls for a material's `transmission` group, as `material.transmission`\n * @example\n * ```ts\n * const material = new Material3D({ transmission: {} });\n * material.transmission!.thickness = 0.4;\n * ```\n * @category materials\n * @standard\n */\nexport interface TransmissionProps {\n  /**\n   * How much light passes through, from 0 (opaque surface) to 1 (clear glass)\n   * @example\n   * ```ts\n   * material.transmission!.factor = 0.5;\n   * ```\n   */\n  factor: number;\n  /**\n   * Thickness of the volume in the mesh's own units; 0 makes a thin wall\n   * @example\n   * ```ts\n   * material.transmission!.thickness = 2;\n   * ```\n   */\n  thickness: number;\n  /**\n   * Distance in world units that light travels through the volume before it takes on\n   * `attenuationColor`\n   *\n   * 1e9 or more turns absorption off.\n   * @example\n   * ```ts\n   * material.transmission!.attenuationDistance = 0.5;\n   * ```\n   */\n  attenuationDistance: number;\n  /**\n   * Colour white light turns after travelling `attenuationDistance`; takes any `ColorSource` and\n   * reads back a hex number, like `Container.tint`\n   * @example\n   * ```ts\n   * material.transmission!.attenuationColor = 'teal';\n   * ```\n   */\n  get attenuationColor(): number;\n  /** Sets the attenuation colour from any `ColorSource` */\n  set attenuationColor(value: ColorSource);\n  /**\n   * Map whose red channel scales `factor`\n   * @example\n   * ```ts\n   * material.transmission!.texture = await Assets.load('frost-mask.png');\n   * ```\n   */\n  texture: Texture;\n  /**\n   * Map whose green channel scales `thickness`\n   * @example\n   * ```ts\n   * material.transmission!.thicknessTexture = await Assets.load('thickness.png');\n   * ```\n   */\n  thicknessTexture: Texture;\n}\n\n/**\n * Runtime controls for a material's `clearcoat` group, as `material.clearcoat`\n * @example\n * ```ts\n * const material = new Material3D({ clearcoat: {} });\n * material.clearcoat!.roughness = 0.2;\n * ```\n * @category materials\n * @standard\n */\nexport interface ClearcoatProps {\n  /**\n   * Strength of the coat, from 0 (none) to 1\n   * @example\n   * ```ts\n   * material.clearcoat!.factor = 0.7;\n   * ```\n   */\n  factor: number;\n  /**\n   * Roughness of the coat, independent of the surface underneath\n   * @example\n   * ```ts\n   * material.clearcoat!.roughness = 0.1;\n   * ```\n   */\n  roughness: number;\n  /**\n   * Strength of the coat normal map's bumps; no effect without a coat normal map\n   * @example\n   * ```ts\n   * material.clearcoat!.normalScale = 0.5;\n   * ```\n   */\n  normalScale: number;\n  /**\n   * Map whose red channel scales `factor`\n   * @example\n   * ```ts\n   * material.clearcoat!.texture = await Assets.load('coat-mask.png');\n   * ```\n   */\n  texture: Texture;\n  /**\n   * Map whose green channel scales `roughness`\n   * @example\n   * ```ts\n   * material.clearcoat!.roughnessTexture = await Assets.load('coat-roughness.png');\n   * ```\n   */\n  roughnessTexture: Texture;\n  /**\n   * The coat normal map, or `undefined` when the material was built without one\n   *\n   * Read-only: to add one, {@link BaseMaterial3D#clone | clone} the material with\n   * `clearcoat: { normalTexture }`; to swap it, assign `material.textures.clearcoatNormal`.\n   * @advanced\n   */\n  readonly normalTexture?: Texture;\n}\n\n/**\n * Runtime controls for a material's `sheen` group, as `material.sheen`\n * @example\n * ```ts\n * const material = new Material3D({ sheen: {} });\n * material.sheen!.color = 0xffd0e0;\n * ```\n * @category materials\n * @standard\n */\nexport interface SheenProps {\n  /**\n   * Colour of the sheen; takes any `ColorSource` and reads back a hex number, like\n   * `Container.tint`\n   * @example\n   * ```ts\n   * material.sheen!.color = 'pink';\n   * ```\n   */\n  get color(): number;\n  /** Sets the sheen colour from any `ColorSource` */\n  set color(value: ColorSource);\n  /**\n   * Roughness of the sheen, from 0 to 1\n   * @example\n   * ```ts\n   * material.sheen!.roughness = 0.6;\n   * ```\n   */\n  roughness: number;\n  /**\n   * The packed map, colour in RGB and roughness in alpha\n   * @example\n   * ```ts\n   * material.sheen!.texture = await Assets.load('sheen.png');\n   * ```\n   */\n  texture: Texture;\n}\n\n/**\n * Runtime controls for a material's `anisotropy` group, as `material.anisotropy`\n * @example\n * ```ts\n * const material = new Material3D({ metallic: 1, anisotropy: {} });\n * material.anisotropy!.rotation = Math.PI / 4;\n * ```\n * @category materials\n * @standard\n */\nexport interface AnisotropyProps {\n  /**\n   * How strongly highlights stretch, from 0 to 1\n   * @example\n   * ```ts\n   * material.anisotropy!.strength = 0.5;\n   * ```\n   */\n  strength: number;\n  /**\n   * Rotation of the stretch direction in radians, starting from the surface's tangent\n   * @example\n   * ```ts\n   * material.anisotropy!.rotation += 0.01;\n   * ```\n   */\n  rotation: number;\n  /**\n   * The direction map (direction in RG, strength in B), or `undefined` when the material was built\n   * without one\n   *\n   * Read-only: to add one, {@link BaseMaterial3D#clone | clone} the material with\n   * `anisotropy: { texture }`; to swap it, assign `material.textures.anisotropy`.\n   * @advanced\n   */\n  readonly texture?: Texture;\n}\n\nconst SpecularPropsClass = createFeaturePropsClass<SpecularProps>({\n  factor: { kind: 'lane', field: 'specularParams', lane: 3 },\n  color: { kind: 'colour', field: 'specularParams' },\n  texture: { kind: 'texture', slot: 'specular' },\n});\n\nconst IridescencePropsClass = createFeaturePropsClass<IridescenceProps>({\n  factor: { kind: 'lane', field: 'transmissionVolume', lane: 3 },\n  ior: { kind: 'lane', field: 'attenuationColorIrid', lane: 3 },\n  thicknessMinimum: { kind: 'scalar', field: 'iridescenceThicknessMinimum' },\n  thicknessMaximum: { kind: 'scalar', field: 'iridescenceThickness' },\n  texture: { kind: 'texture', slot: 'iridescence' },\n});\n\nconst TransmissionPropsClass = createFeaturePropsClass<TransmissionProps>({\n  factor: { kind: 'lane', field: 'transmissionVolume', lane: 0 },\n  thickness: { kind: 'lane', field: 'transmissionVolume', lane: 1 },\n  attenuationDistance: { kind: 'lane', field: 'transmissionVolume', lane: 2 },\n  attenuationColor: { kind: 'colour', field: 'attenuationColorIrid' },\n  texture: { kind: 'texture', slot: 'transmission' },\n  thicknessTexture: { kind: 'texture', slot: 'thickness' },\n});\n\nconst ClearcoatPropsClass = createFeaturePropsClass<ClearcoatProps>({\n  factor: { kind: 'lane', field: 'clearcoatParams', lane: 0 },\n  roughness: { kind: 'lane', field: 'clearcoatParams', lane: 1 },\n  normalScale: { kind: 'lane', field: 'clearcoatParams', lane: 2 },\n  texture: { kind: 'texture', slot: 'clearcoat' },\n  roughnessTexture: { kind: 'texture', slot: 'clearcoatRoughness' },\n  normalTexture: { kind: 'texture', slot: 'clearcoatNormal', readonly: true },\n});\n\nconst SheenPropsClass = createFeaturePropsClass<SheenProps>({\n  color: { kind: 'colour', field: 'sheenParams' },\n  roughness: { kind: 'lane', field: 'sheenParams', lane: 3 },\n  texture: { kind: 'texture', slot: 'sheen' },\n});\n\nconst AnisotropyPropsClass = createFeaturePropsClass<AnisotropyProps>({\n  strength: { kind: 'lane', field: 'anisotropyParams', lane: 0 },\n  rotation: { kind: 'lane', field: 'anisotropyParams', lane: 1 },\n  texture: { kind: 'texture', slot: 'anisotropy', readonly: true },\n});\n\n/**\n * The texture slots of a {@link Material3D}, as `material.textures`\n *\n * The four core slots always exist. The others exist only when the material was built with the\n * matching group, and `clearcoatNormal` and `anisotropy` only when that group had its texture. Each\n * option group says how its slot is packed.\n * @example\n * ```ts\n * const material = new Material3D({ baseColorTexture: bricks });\n * material.textures.baseColor = mossyBricks;\n * ```\n * @category materials\n * @standard\n */\nexport interface Material3DTextures extends MaterialTextures {\n  /**\n   * Base colour map\n   * @example\n   * ```ts\n   * material.textures.baseColor = await Assets.load('albedo.png');\n   * ```\n   */\n  baseColor: Texture;\n  /**\n   * Roughness in green, metalness in blue\n   * @example\n   * ```ts\n   * material.textures.metallicRoughness = await Assets.load('metal-rough.png');\n   * ```\n   */\n  metallicRoughness: Texture;\n  /**\n   * Ambient occlusion in red\n   * @example\n   * ```ts\n   * material.textures.occlusion = await Assets.load('occlusion.png');\n   * ```\n   */\n  occlusion: Texture;\n  /**\n   * Tangent-space normal map; holds a flat map until you assign one\n   * @example\n   * ```ts\n   * material.textures.normal = await Assets.load('normal.png');\n   * ```\n   */\n  normal: Texture;\n  /**\n   * Glow map\n   * @example\n   * ```ts\n   * material.textures.emissive = await Assets.load('glow.png');\n   * ```\n   */\n  emissive?: Texture;\n  /**\n   * Specular tint in RGB, strength in alpha\n   * @example\n   * ```ts\n   * material.textures.specular = await Assets.load('specular.png');\n   * ```\n   */\n  specular?: Texture;\n  /**\n   * Iridescence factor in red, film thickness in green\n   * @example\n   * ```ts\n   * material.textures.iridescence = await Assets.load('film.png');\n   * ```\n   */\n  iridescence?: Texture;\n  /**\n   * Transmission factor in red\n   * @example\n   * ```ts\n   * material.textures.transmission = await Assets.load('frost-mask.png');\n   * ```\n   */\n  transmission?: Texture;\n  /**\n   * Volume thickness in green\n   * @example\n   * ```ts\n   * material.textures.thickness = await Assets.load('thickness.png');\n   * ```\n   */\n  thickness?: Texture;\n  /**\n   * Clearcoat factor in red\n   * @example\n   * ```ts\n   * material.textures.clearcoat = await Assets.load('coat-mask.png');\n   * ```\n   */\n  clearcoat?: Texture;\n  /**\n   * Clearcoat roughness in green\n   * @example\n   * ```ts\n   * material.textures.clearcoatRoughness = await Assets.load('coat-roughness.png');\n   * ```\n   */\n  clearcoatRoughness?: Texture;\n  /**\n   * Clearcoat normal map\n   * @example\n   * ```ts\n   * material.textures.clearcoatNormal = await Assets.load('coat-normal.png');\n   * ```\n   */\n  clearcoatNormal?: Texture;\n  /**\n   * Sheen colour in RGB, roughness in alpha\n   * @example\n   * ```ts\n   * material.textures.sheen = await Assets.load('sheen.png');\n   * ```\n   */\n  sheen?: Texture;\n  /**\n   * Anisotropy direction in RG, strength in B\n   * @example\n   * ```ts\n   * material.textures.anisotropy = await Assets.load('brush-direction.png');\n   * ```\n   */\n  anisotropy?: Texture;\n}\n\n/**\n * The fields of {@link Material3D#data}\n *\n * The core fields always exist; the others only when the material was built with the matching\n * group.\n * @category materials\n * @advanced\n */\nexport interface Material3DData extends MaterialData {\n  /** Base colour in linear light, alpha in the last lane */\n  baseColor: Float32Array;\n  /** Lanes: metallic, roughness, occlusionStrength, ior */\n  pbrParams: Float32Array;\n  /** Strength of the normal map's bumps */\n  normalScale: number;\n  /** Lanes: transmission factor, thickness, attenuationDistance, iridescence factor */\n  transmissionVolume: Float32Array;\n  /** Lanes: attenuationColor in linear light, iridescence IOR */\n  attenuationColorIrid: Float32Array;\n  /** Glow colour in linear light */\n  emissive?: Float32Array;\n  /** Multiplier on the glow */\n  emissiveStrength?: number;\n  /** Iridescence film thickness in nanometres where the texture's green channel is 1 */\n  iridescenceThickness?: number;\n  /** Iridescence film thickness in nanometres where the texture's green channel is 0 */\n  iridescenceThicknessMinimum?: number;\n  /** Lanes: specular tint in linear light, factor */\n  specularParams?: Float32Array;\n  /** Lanes: factor, roughness, normalScale, unused */\n  clearcoatParams?: Float32Array;\n  /** Lanes: sheen colour in linear light, roughness */\n  sheenParams?: Float32Array;\n  /** Lanes: strength, rotation, unused, unused */\n  anisotropyParams?: Float32Array;\n}\n\n/**\n * The standard physically based (PBR) material\n *\n * Base colour, metalness and roughness, with normal, occlusion and emissive maps, plus the glTF\n * extensions for specular, iridescence, transmission and volume, clearcoat, sheen and anisotropy.\n * glTF materials load into it, except unlit ones, which load as {@link FlatMaterial}.\n *\n * Each extension is an option group, and passing one gives the material a runtime object of the same\n * name: `new Material3D({ clearcoat: { roughness: 0.2 } })` gives `material.clearcoat.roughness`.\n * Writing to it, or to a core value such as `roughness`, never recompiles the shader.\n *\n * The groups passed to the constructor fix the material's features for good. A group left out costs\n * nothing, while a feature turned off at runtime, such as a coat at factor 0, keeps its cost. To add\n * a feature to a material that exists, such as one the glTF loader built,\n * `material.clone({ clearcoat: { factor: 1 } })` ({@link BaseMaterial3D#clone}) makes a copy with it\n * and everything else the material has.\n *\n * Custom shader code in {@link BaseMaterial3DOptions#extraBits} runs after the features in each\n * slot, and in the `material` slot before the `'mask'` cutoff, so it sees the final `albedo` and\n * `alpha`, and alpha it writes there still reaches the cutoff. Like the groups, it's fixed when the\n * material is built, and `clone({ extraBits })` makes a copy with more.\n * @example\n * ```ts\n * const paint = new Material3D({\n *   baseColor: 0x8c1c13,\n *   metallic: 0.2,\n *   roughness: 0.5,\n *   clearcoat: { roughness: 0.05 },\n * });\n * paint.clearcoat!.factor = 0.8;\n * ```\n * @category materials\n * @standard\n */\nexport class Material3D extends BaseMaterial3D<Material3DData, Material3DTextures, Material3DOptions> {\n  /**\n   * Runtime glow controls; present only when the material was built with an `emissive` group\n   * @example\n   * ```ts\n   * if (material.emissive) material.emissive.strength = 2;\n   * ```\n   */\n  public readonly emissive?: EmissiveProps;\n  /**\n   * Runtime specular controls; present only when the material was built with a `specular` group\n   * @example\n   * ```ts\n   * if (material.specular) material.specular.factor = 0.5;\n   * ```\n   */\n  public readonly specular?: SpecularProps;\n  /**\n   * Runtime iridescence controls; present only when the material was built with an `iridescence`\n   * group\n   * @example\n   * ```ts\n   * if (material.iridescence) material.iridescence.factor = 1;\n   * ```\n   */\n  public readonly iridescence?: IridescenceProps;\n  /**\n   * Runtime transmission controls; present only when the material was built with a `transmission`\n   * group\n   * @example\n   * ```ts\n   * if (material.transmission) material.transmission.factor = 0.9;\n   * ```\n   */\n  public readonly transmission?: TransmissionProps;\n  /**\n   * Runtime clearcoat controls; present only when the material was built with a `clearcoat` group\n   * @example\n   * ```ts\n   * if (material.clearcoat) material.clearcoat.roughness = 0.1;\n   * ```\n   */\n  public readonly clearcoat?: ClearcoatProps;\n  /**\n   * Runtime sheen controls; present only when the material was built with a `sheen` group\n   * @example\n   * ```ts\n   * if (material.sheen) material.sheen.roughness = 0.4;\n   * ```\n   */\n  public readonly sheen?: SheenProps;\n  /**\n   * Runtime anisotropy controls; present only when the material was built with an `anisotropy`\n   * group\n   * @example\n   * ```ts\n   * if (material.anisotropy) material.anisotropy.rotation = Math.PI / 2;\n   * ```\n   */\n  public readonly anisotropy?: AnisotropyProps;\n\n  /**\n   * In shader order: `specularBit` sets the F0 and `f90` that `iridescenceBit` and `transmissionBit`\n   * read, and `emissiveBit` assigns the `emissive` that `transmissionBit` adds to\n   */\n  private readonly _featureBits: ShaderBit[] = [];\n\n  constructor(options: Material3DOptions = {}) {\n    const { emissive, specular, iridescence, transmission, clearcoat, sheen, anisotropy } = options;\n\n    super({\n      ...options,\n      alphaMode: options.alphaMode ?? 'opaque',\n      doubleSided: options.doubleSided ?? false,\n    });\n\n    if (transmission) {\n      this._passBit = (this._passBit & ~RenderPassBit.MATERIAL_PASS_MASK) | RenderPassBit.TRANSMISSION;\n    }\n\n    const textures: Record<string, Texture | undefined> = {\n      baseColor: options.baseColorTexture,\n      metallicRoughness: options.metallicRoughnessTexture,\n      occlusion: options.occlusionTexture,\n      normal: options.normalTexture ?? NORMAL_MAP,\n      ...options.textures,\n    };\n\n    if (emissive) {\n      textures.emissive = emissive.texture;\n      this._featureBits.push(emissiveBit);\n    }\n\n    if (specular) {\n      textures.specular = specular.colorTexture ?? specular.texture;\n      this._featureBits.push(specularBit);\n    }\n\n    if (iridescence) {\n      textures.iridescence = iridescence.texture ?? iridescence.thicknessTexture;\n      this._featureBits.push(iridescenceBit);\n    }\n\n    if (transmission) {\n      textures.transmission = transmission.texture;\n      textures.thickness = transmission.thicknessTexture;\n      this._featureBits.push(transmissionBit);\n    }\n\n    if (clearcoat) {\n      textures.clearcoat = clearcoat.texture;\n      textures.clearcoatRoughness = clearcoat.roughnessTexture;\n      if (clearcoat.normalTexture) {\n        textures.clearcoatNormal = clearcoat.normalTexture;\n        this._featureBits.push(clearcoatNormalMapBit);\n      } else {\n        this._featureBits.push(clearcoatBit);\n      }\n    }\n\n    if (sheen) {\n      textures.sheen = sheen.texture ?? sheen.roughnessTexture;\n      this._featureBits.push(sheenBit);\n    }\n\n    if (anisotropy) {\n      if (anisotropy.texture) {\n        textures.anisotropy = anisotropy.texture;\n        this._featureBits.push(anisotropyTextureBit);\n      } else {\n        this._featureBits.push(anisotropyBit);\n      }\n    }\n\n    this._deriveLayoutFromBits([pbrMaterialBit, uvTransformBit, ...this._featureBits, ...this.extraBits], textures);\n\n    const data = this.data;\n\n    data.pbrParams[0] = options.metallic ?? 0;\n    data.pbrParams[1] = options.roughness ?? 1;\n    data.pbrParams[2] = options.occlusionStrength ?? 1;\n    data.pbrParams[3] = options.ior ?? 1.5;\n    data.normalScale = options.normalScale ?? 1;\n\n    data.transmissionVolume[2] = 1e10;\n    const attenuationColorIrid = data.attenuationColorIrid;\n    writeLinearRgb(attenuationColorIrid, 0, Color.shared.setValue(0xffffff));\n    attenuationColorIrid[3] = 1.3;\n\n    if (emissive) {\n      const props = (this.emissive = new EmissivePropsClass(this));\n      props.color = emissive.color ?? 0xffffff;\n      props.strength = emissive.strength ?? 1;\n    }\n\n    if (specular) {\n      const props = (this.specular = new SpecularPropsClass(this));\n      props.color = specular.color ?? 0xffffff;\n      props.factor = specular.factor ?? 1;\n    }\n\n    if (iridescence) {\n      const props = (this.iridescence = new IridescencePropsClass(this));\n      props.factor = iridescence.factor ?? 1;\n      props.ior = iridescence.ior ?? 1.3;\n      props.thicknessMaximum = iridescence.thicknessMaximum ?? 400;\n      props.thicknessMinimum = iridescence.thicknessMinimum ?? 0;\n    }\n\n    if (transmission) {\n      const props = (this.transmission = new TransmissionPropsClass(this));\n      props.factor = transmission.factor ?? 1;\n      props.thickness = transmission.thickness ?? 0;\n      props.attenuationDistance = transmission.attenuationDistance ?? 1e10;\n      props.attenuationColor = transmission.attenuationColor ?? 0xffffff;\n    }\n\n    if (clearcoat) {\n      const props = (this.clearcoat = new ClearcoatPropsClass(this));\n      props.factor = clearcoat.factor ?? 1;\n      props.roughness = clearcoat.roughness ?? 0;\n      props.normalScale = clearcoat.normalScale ?? 1;\n    }\n\n    if (sheen) {\n      const props = (this.sheen = new SheenPropsClass(this));\n      props.color = sheen.color ?? 0xffffff;\n      props.roughness = sheen.roughness ?? 0;\n    }\n\n    if (anisotropy) {\n      const props = (this.anisotropy = new AnisotropyPropsClass(this));\n      props.strength = anisotropy.strength ?? 1;\n      props.rotation = anisotropy.rotation ?? 0;\n    }\n  }\n\n  /**\n   * `iblBit` joins only when the view has an environment, since the compiler may still run work\n   * multiplied by the zero that `envSourceDefaultBit` returns\n   */\n  private _descriptorByEnvKey: Record<string, ShaderDescriptor> = Object.create(null);\n\n  /**\n   * The shader descriptor for a view, cached per kind of environment\n   * @param view - View whose environment picks the descriptor\n   * @advanced\n   */\n  public override getPrimaryDescriptor(view: View3D): ShaderDescriptor {\n    if (this._variantDirty) {\n      this._descriptorByEnvKey = Object.create(null);\n      this._variantDirty = false;\n    }\n\n    const envBit = view._envBit;\n    const envKey = envBit.name;\n\n    let descriptor = this._descriptorByEnvKey[envKey];\n    if (descriptor) return descriptor;\n\n    const bitsGpu = [pbrMaterialBit, envBit];\n    const bitsGl = [pbrMaterialBit, envBit];\n\n    if (view.environment !== null) {\n      bitsGpu.push(iblBit);\n      bitsGl.push(iblBit);\n    }\n\n    bitsGpu.push(pbrLightingBit);\n    bitsGl.push(pbrLightingBit);\n\n    bitsGpu.push(uvTransformBit);\n    bitsGl.push(uvTransformBit);\n    bitsGpu.push(...this._featureBits);\n    bitsGl.push(...this._featureBits);\n    bitsGpu.push(...this.extraBits);\n    bitsGl.push(...this.extraBits);\n    if (this._alphaMode === 'mask') {\n      bitsGpu.push(alphaMaskBit);\n      bitsGl.push(alphaMaskBit);\n    }\n\n    descriptor = new ShaderDescriptor({});\n    descriptor.update({ bitsGpu, bitsGl });\n    this._descriptorByEnvKey[envKey] = descriptor;\n    return descriptor;\n  }\n\n  /**\n   * The base options plus the PBR values, maps and each feature group the material has\n   * @advanced\n   */\n  protected override _toOptions(): Material3DOptions {\n    const { emissive, specular, iridescence, transmission, clearcoat, sheen, anisotropy, textures } = this;\n\n    return {\n      ...super._toOptions(),\n      metallic: this.metallic,\n      roughness: this.roughness,\n      occlusionStrength: this.occlusionStrength,\n      ior: this.ior,\n      normalScale: this.normalScale,\n      normalTexture: textures.normal,\n      metallicRoughnessTexture: textures.metallicRoughness,\n      occlusionTexture: textures.occlusion,\n      emissive: emissive && readFeatureProps(emissive),\n      specular: specular && readFeatureProps(specular),\n      iridescence: iridescence && readFeatureProps(iridescence),\n      transmission: transmission && readFeatureProps(transmission),\n      clearcoat: clearcoat && readFeatureProps(clearcoat),\n      sheen: sheen && readFeatureProps(sheen),\n      anisotropy: anisotropy && readFeatureProps(anisotropy),\n    };\n  }\n\n  /**\n   * Metalness, from 0 (non-metal) to 1 (metal)\n   *\n   * Ambient lights don't light a metal, so with no environment a metal is dark except for its\n   * highlights.\n   * @default 0\n   * @example\n   * ```ts\n   * material.metallic = 1;\n   * ```\n   */\n  public get metallic(): number {\n    return this.data.pbrParams[0];\n  }\n  /**\n   * Sets the metalness\n   * @param value - Metalness, 0 to 1\n   */\n  public set metallic(value: number) {\n    if (this.data.pbrParams[0] === Math.fround(value)) return;\n    this.data.pbrParams[0] = value;\n    this.update();\n  }\n\n  /**\n   * Perceptual roughness, from 0 (mirror-like) to 1 (fully rough)\n   * @default 1\n   * @example\n   * ```ts\n   * material.roughness = 0.2;\n   * ```\n   */\n  public get roughness(): number {\n    return this.data.pbrParams[1];\n  }\n  /**\n   * Sets the perceptual roughness\n   * @param value - Roughness, 0 to 1\n   */\n  public set roughness(value: number) {\n    if (this.data.pbrParams[1] === Math.fround(value)) return;\n    this.data.pbrParams[1] = value;\n    this.update();\n  }\n\n  /**\n   * Multiplier on the occlusion\n   *\n   * Ambient and environment light are scaled by the sampled occlusion times this value, so values\n   * below 1 darken that light even where the map is white, and values above 1 brighten it.\n   * @default 1\n   * @example\n   * ```ts\n   * material.occlusionStrength = 0.8;\n   * ```\n   */\n  public get occlusionStrength(): number {\n    return this.data.pbrParams[2];\n  }\n  /**\n   * Sets the multiplier on the occlusion\n   * @param value - Multiplier on the occlusion\n   */\n  public set occlusionStrength(value: number) {\n    if (this.data.pbrParams[2] === Math.fround(value)) return;\n    this.data.pbrParams[2] = value;\n    this.update();\n  }\n\n  /**\n   * Index of refraction (`KHR_materials_ior`); sets how strongly non-metals reflect, and how far\n   * transmission bends light\n   * @default 1.5\n   * @example\n   * ```ts\n   * material.ior = 1.33;\n   * ```\n   */\n  public get ior(): number {\n    return this.data.pbrParams[3];\n  }\n  /**\n   * Sets the index of refraction\n   * @param value - Refractive index; 1.5 suits most glass and plastic\n   */\n  public set ior(value: number) {\n    if (this.data.pbrParams[3] === Math.fround(value)) return;\n    this.data.pbrParams[3] = value;\n    this.update();\n  }\n\n  /**\n   * Strength of the normal map's bumps; 1 leaves the map as authored\n   * @default 1\n   * @example\n   * ```ts\n   * material.normalScale = 2;\n   * ```\n   */\n  public get normalScale(): number {\n    return this.data.normalScale;\n  }\n  /**\n   * Sets the strength of the normal map's bumps\n   * @param value - Bump strength\n   */\n  public set normalScale(value: number) {\n    this.data.normalScale = value;\n  }\n\n  /**\n   * Frees the material for good\n   *\n   * Its textures stay alive unless `options` asks for them. Calling it again does nothing.\n   * @param options - Whether to destroy the textures too, as {@link BaseMaterial3D#destroy} takes them\n   * @example\n   * ```ts\n   * mesh.material.destroy();\n   * ```\n   */\n  public override destroy(options?: TypeOrBool<TextureDestroyOptions>): void {\n    if (this.destroyed) return;\n    super.destroy(options);\n\n    (this._descriptorByEnvKey as Record<string, ShaderDescriptor> | null) = null;\n    (this._featureBits as ShaderBit[] | null) = null;\n\n    /** @internal */\n    const features = this as {\n      emissive?: EmissiveProps;\n      specular?: SpecularProps;\n      iridescence?: IridescenceProps;\n      transmission?: TransmissionProps;\n      clearcoat?: ClearcoatProps;\n      sheen?: SheenProps;\n      anisotropy?: AnisotropyProps;\n    };\n    features.emissive = undefined;\n    features.specular = undefined;\n    features.iridescence = undefined;\n    features.transmission = undefined;\n    features.clearcoat = undefined;\n    features.sheen = undefined;\n    features.anisotropy = undefined;\n  }\n}\n","import { Matrix, warn } from 'pixi.js';\n\nimport { linearToSrgb } from '../../../../materials/BaseMaterial3D';\nimport type { BaseMaterial3D, BaseMaterial3DOptions } from '../../../../materials/BaseMaterial3D';\nimport { FlatMaterial } from '../../../../materials/flat/FlatMaterial';\nimport { Material3D } from '../../../../materials/pbr/Material3D';\nimport type {\n  AnisotropyOptions,\n  ClearcoatOptions,\n  IridescenceOptions,\n  Material3DOptions,\n  SheenOptions,\n  SpecularOptions,\n  TransmissionOptions,\n} from '../../../../materials/pbr/Material3D';\nimport type { EmissiveOptions } from '../../../../materials/utils/emissiveProps';\nimport type { Scene3DSource } from '../../../Scene3DSource';\nimport type { GltfFormat } from '../GltfFormat';\n\n/**\n * A material has one UV transform for all its textures, so this takes the first on any texture\n * `processPbrMaterial` sets; keep this list in step with it\n */\nfunction extractUvTransform(rawMaterial: GltfFormat.Material): GltfFormat.KHRTextureTransform | undefined {\n  const pbr = rawMaterial.pbrMetallicRoughness;\n  const ext = rawMaterial.extensions;\n  const candidates = [\n    pbr?.baseColorTexture,\n    pbr?.metallicRoughnessTexture,\n    rawMaterial.normalTexture,\n    rawMaterial.occlusionTexture,\n    rawMaterial.emissiveTexture,\n    ext?.KHR_materials_transmission?.transmissionTexture,\n    ext?.KHR_materials_volume?.thicknessTexture,\n    ext?.KHR_materials_clearcoat?.clearcoatTexture,\n    ext?.KHR_materials_clearcoat?.clearcoatRoughnessTexture,\n    ext?.KHR_materials_clearcoat?.clearcoatNormalTexture,\n    ext?.KHR_materials_sheen?.sheenColorTexture,\n    ext?.KHR_materials_sheen?.sheenRoughnessTexture,\n    ext?.KHR_materials_specular?.specularTexture,\n    ext?.KHR_materials_specular?.specularColorTexture,\n    ext?.KHR_materials_iridescence?.iridescenceTexture,\n    ext?.KHR_materials_iridescence?.iridescenceThicknessTexture,\n    ext?.KHR_materials_anisotropy?.anisotropyTexture,\n  ];\n  for (const info of candidates) {\n    const ktt = info?.extensions?.KHR_texture_transform;\n    if (ktt) return ktt;\n  }\n  return undefined;\n}\n\nconst warnedTexCoords = new Set<string>();\n\ninterface TextureBindingLike {\n  texCoord?: number;\n  extensions?: { KHR_texture_transform?: { texCoord?: number } };\n}\n\nfunction warnUnsupportedTexCoord(\n  bindingName: string,\n  info: TextureBindingLike | undefined,\n  materialName: string,\n): void {\n  if (!info) return;\n\n  const bindingTexCoord = info.texCoord ?? 0;\n  if (bindingTexCoord !== 0) {\n    const key = `binding:${bindingName}:${bindingTexCoord}`;\n    if (!warnedTexCoords.has(key)) {\n      warnedTexCoords.add(key);\n      warn(\n        `[@pixi/3d] ${bindingName} on material \"${materialName}\" uses texCoord=${bindingTexCoord}; ` +\n          `multi-UV-set support is not yet implemented and the texture will sample from UV0 ` +\n          `(may apply to other materials in this asset).`,\n      );\n    }\n  }\n\n  const transformTexCoord = info.extensions?.KHR_texture_transform?.texCoord;\n  if (transformTexCoord !== undefined && transformTexCoord !== bindingTexCoord) {\n    const key = `transform:${bindingName}:${transformTexCoord}`;\n    if (!warnedTexCoords.has(key)) {\n      warnedTexCoords.add(key);\n      warn(\n        `[@pixi/3d] KHR_texture_transform on ${bindingName} (material \"${materialName}\") overrides ` +\n          `texCoord (binding=${bindingTexCoord}, transform=${transformTexCoord}); per-binding ` +\n          `texCoord overrides are not supported and the binding's texCoord will be used instead.`,\n      );\n    }\n  }\n}\n\nfunction warnUnsupportedPbrTexCoords(rawMaterial: GltfFormat.Material): void {\n  const name = rawMaterial.name ?? '<unnamed>';\n  const pbr = rawMaterial.pbrMetallicRoughness;\n  warnUnsupportedTexCoord('baseColorTexture', pbr?.baseColorTexture, name);\n  warnUnsupportedTexCoord('metallicRoughnessTexture', pbr?.metallicRoughnessTexture, name);\n  warnUnsupportedTexCoord('normalTexture', rawMaterial.normalTexture, name);\n  warnUnsupportedTexCoord('occlusionTexture', rawMaterial.occlusionTexture, name);\n  warnUnsupportedTexCoord('emissiveTexture', rawMaterial.emissiveTexture, name);\n  warnUnsupportedTexCoord(\n    'transmissionTexture',\n    rawMaterial.extensions?.KHR_materials_transmission?.transmissionTexture,\n    name,\n  );\n  warnUnsupportedTexCoord('thicknessTexture', rawMaterial.extensions?.KHR_materials_volume?.thicknessTexture, name);\n  warnUnsupportedTexCoord('clearcoatTexture', rawMaterial.extensions?.KHR_materials_clearcoat?.clearcoatTexture, name);\n  warnUnsupportedTexCoord(\n    'clearcoatRoughnessTexture',\n    rawMaterial.extensions?.KHR_materials_clearcoat?.clearcoatRoughnessTexture,\n    name,\n  );\n  warnUnsupportedTexCoord(\n    'clearcoatNormalTexture',\n    rawMaterial.extensions?.KHR_materials_clearcoat?.clearcoatNormalTexture,\n    name,\n  );\n  warnUnsupportedTexCoord('sheenColorTexture', rawMaterial.extensions?.KHR_materials_sheen?.sheenColorTexture, name);\n  warnUnsupportedTexCoord(\n    'sheenRoughnessTexture',\n    rawMaterial.extensions?.KHR_materials_sheen?.sheenRoughnessTexture,\n    name,\n  );\n  warnUnsupportedTexCoord('specularTexture', rawMaterial.extensions?.KHR_materials_specular?.specularTexture, name);\n  warnUnsupportedTexCoord(\n    'specularColorTexture',\n    rawMaterial.extensions?.KHR_materials_specular?.specularColorTexture,\n    name,\n  );\n  warnUnsupportedTexCoord(\n    'anisotropyTexture',\n    rawMaterial.extensions?.KHR_materials_anisotropy?.anisotropyTexture,\n    name,\n  );\n}\n\nfunction warnUnsupportedUnlitTexCoords(rawMaterial: GltfFormat.Material): void {\n  const name = rawMaterial.name ?? '<unnamed>';\n  warnUnsupportedTexCoord('baseColorTexture', rawMaterial.pbrMetallicRoughness?.baseColorTexture, name);\n}\n\n/**\n * The `KHR_texture_transform` matrix in the form `BaseMaterial3D.uvTransform` documents. It rotates as\n * the Khronos sample renderer does, the opposite of the GLSL in the extension's README\n */\nfunction buildUvTransformMatrix(ktt: GltfFormat.KHRTextureTransform): Matrix {\n  const [ox, oy] = ktt.offset ?? [0, 0];\n  const [sx, sy] = ktt.scale ?? [1, 1];\n  const rot = ktt.rotation ?? 0;\n  const cos = Math.cos(rot);\n  const sin = Math.sin(rot);\n  return new Matrix(sx * cos, sx * sin, -sy * sin, sy * cos, ox, oy);\n}\n\nfunction gltfAlphaMode(rawMaterial: GltfFormat.Material): BaseMaterial3DOptions['alphaMode'] {\n  return rawMaterial.alphaMode === 'BLEND' ? 'blend' : rawMaterial.alphaMode === 'MASK' ? 'mask' : 'opaque';\n}\n\n/**\n * Encodes glTF's linear colours to the sRGB that material and light colours decode, as floats, so\n * nothing rounds to 8 bits\n * @internal\n */\nexport function linearRgbToSrgb(rgb: number[]): [number, number, number] {\n  return [linearToSrgb(rgb[0]), linearToSrgb(rgb[1]), linearToSrgb(rgb[2])];\n}\n\nfunction processUnlitMaterial(rawMaterial: GltfFormat.Material, source: Scene3DSource): FlatMaterial {\n  warnUnsupportedUnlitTexCoords(rawMaterial);\n\n  const options: BaseMaterial3DOptions = {\n    alphaMode: gltfAlphaMode(rawMaterial),\n    alphaCutoff: rawMaterial.alphaCutoff,\n    doubleSided: rawMaterial.doubleSided ?? false,\n    vertexColors: true,\n  };\n\n  const pbr = rawMaterial.pbrMetallicRoughness;\n  if (pbr?.baseColorFactor !== undefined) {\n    options.baseColor = linearRgbToSrgb(pbr.baseColorFactor);\n    options.alpha = pbr.baseColorFactor[3];\n  }\n  if (pbr?.baseColorTexture !== undefined) {\n    options.baseColorTexture = source.textures[pbr.baseColorTexture.index];\n  }\n\n  const ktt = pbr?.baseColorTexture?.extensions?.KHR_texture_transform;\n  if (ktt) options.uvTransform = buildUvTransformMatrix(ktt);\n\n  return new FlatMaterial(options);\n}\n\n/**\n * Passes every glTF default explicitly, as `Material3D`'s differ: metallic 0, and an extension group\n * switching on at factor 1\n */\nfunction processPbrMaterial(rawMaterial: GltfFormat.Material, source: Scene3DSource): Material3D {\n  warnUnsupportedPbrTexCoords(rawMaterial);\n\n  const options: Partial<Material3DOptions> = {\n    alphaMode: gltfAlphaMode(rawMaterial),\n    alphaCutoff: rawMaterial.alphaCutoff,\n    doubleSided: rawMaterial.doubleSided ?? false,\n    metallic: 1,\n    roughness: 1,\n    vertexColors: true,\n  };\n\n  if (rawMaterial.normalTexture !== undefined) {\n    options.normalTexture = source.textures[rawMaterial.normalTexture.index];\n    if (rawMaterial.normalTexture.scale !== undefined) {\n      options.normalScale = rawMaterial.normalTexture.scale;\n    }\n  }\n\n  if (rawMaterial.emissiveFactor || rawMaterial.emissiveTexture) {\n    const emissive: EmissiveOptions = {\n      color: linearRgbToSrgb(rawMaterial.emissiveFactor ?? [0, 0, 0]),\n      strength: rawMaterial.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? 1,\n    };\n    if (rawMaterial.emissiveTexture) {\n      emissive.texture = source.textures[rawMaterial.emissiveTexture.index];\n    }\n    options.emissive = emissive;\n  }\n\n  if (rawMaterial.occlusionTexture) {\n    options.occlusionTexture = source.textures[rawMaterial.occlusionTexture.index];\n    if (rawMaterial.occlusionTexture.strength !== undefined) {\n      options.occlusionStrength = rawMaterial.occlusionTexture.strength;\n    }\n  }\n\n  if (rawMaterial.pbrMetallicRoughness) {\n    const pbr = rawMaterial.pbrMetallicRoughness;\n\n    if (pbr.baseColorFactor !== undefined) {\n      options.baseColor = linearRgbToSrgb(pbr.baseColorFactor);\n      options.alpha = pbr.baseColorFactor[3];\n    }\n    if (pbr.metallicFactor !== undefined) options.metallic = pbr.metallicFactor;\n    if (pbr.roughnessFactor !== undefined) options.roughness = pbr.roughnessFactor;\n\n    if (pbr.baseColorTexture !== undefined) {\n      options.baseColorTexture = source.textures[pbr.baseColorTexture.index];\n    }\n\n    if (pbr.metallicRoughnessTexture !== undefined)\n      options.metallicRoughnessTexture = source.textures[pbr.metallicRoughnessTexture.index];\n  }\n\n  const ktt = extractUvTransform(rawMaterial);\n  if (ktt) options.uvTransform = buildUvTransformMatrix(ktt);\n\n  const transmissionExt = rawMaterial.extensions?.KHR_materials_transmission;\n  if (transmissionExt) {\n    const transmission: TransmissionOptions = { factor: transmissionExt.transmissionFactor ?? 0 };\n    if (transmissionExt.transmissionTexture) {\n      transmission.texture = source.textures[transmissionExt.transmissionTexture.index];\n    }\n\n    const volume = rawMaterial.extensions?.KHR_materials_volume;\n    if (volume) {\n      transmission.thickness = volume.thicknessFactor ?? 0;\n      transmission.attenuationDistance = volume.attenuationDistance ?? Infinity;\n      transmission.attenuationColor = linearRgbToSrgb(volume.attenuationColor ?? [1, 1, 1]);\n      if (volume.thicknessTexture) {\n        transmission.thicknessTexture = source.textures[volume.thicknessTexture.index];\n      }\n    }\n\n    options.transmission = transmission;\n\n    const hasTransmission = (transmission.factor ?? 0) > 0 || transmission.texture !== undefined;\n    if (hasTransmission && options.alphaMode !== 'opaque') {\n      warn(\n        `[@pixi/3d] Material \"${rawMaterial.name ?? '<unnamed>'}\" combines KHR_materials_transmission ` +\n          `with alphaMode=\"${rawMaterial.alphaMode ?? 'OPAQUE'}\"; the glTF spec leaves this undefined. ` +\n          `Coercing alphaMode to OPAQUE so the transmission pass handles transparency.`,\n      );\n      options.alphaMode = 'opaque';\n    }\n  }\n\n  const iorExt = rawMaterial.extensions?.KHR_materials_ior;\n  if (iorExt) {\n    options.ior = iorExt.ior ?? 1.5;\n  }\n\n  const iridescence = rawMaterial.extensions?.KHR_materials_iridescence;\n  if (iridescence) {\n    const irid: IridescenceOptions = {\n      factor: iridescence.iridescenceFactor ?? 0,\n      ior: iridescence.iridescenceIor ?? 1.3,\n      thicknessMinimum: iridescence.iridescenceThicknessMinimum ?? 100,\n      thicknessMaximum: iridescence.iridescenceThicknessMaximum ?? 400,\n    };\n    const factorIdx = iridescence.iridescenceTexture?.index;\n    const thickIdx = iridescence.iridescenceThicknessTexture?.index;\n    if (factorIdx !== undefined) irid.texture = source.textures[factorIdx];\n    if (thickIdx !== undefined) irid.thicknessTexture = source.textures[thickIdx];\n    options.iridescence = irid;\n    if (factorIdx !== undefined && thickIdx !== undefined && factorIdx !== thickIdx) {\n      warn(\n        `[@pixi/3d] KHR_materials_iridescence on material \"${rawMaterial.name ?? '<unnamed>'}\" references ` +\n          `two different textures for iridescenceTexture (R=factor) and iridescenceThicknessTexture ` +\n          `(G=thickness); PixiJS 3D packs both into one slot (R+G). The factor texture will be used and ` +\n          `iridescence thickness will be sampled from its G channel. Repack into a single image with ` +\n          `factor in R and thickness in G for the intended look.`,\n      );\n    }\n  }\n\n  const clearcoat = rawMaterial.extensions?.KHR_materials_clearcoat;\n  if (clearcoat) {\n    const cc: ClearcoatOptions = {\n      factor: clearcoat.clearcoatFactor ?? 0,\n      roughness: clearcoat.clearcoatRoughnessFactor ?? 0,\n    };\n    if (clearcoat.clearcoatTexture) {\n      cc.texture = source.textures[clearcoat.clearcoatTexture.index];\n    }\n    if (clearcoat.clearcoatRoughnessTexture) {\n      cc.roughnessTexture = source.textures[clearcoat.clearcoatRoughnessTexture.index];\n    }\n    if (clearcoat.clearcoatNormalTexture) {\n      cc.normalTexture = source.textures[clearcoat.clearcoatNormalTexture.index];\n      if (clearcoat.clearcoatNormalTexture.scale !== undefined) {\n        cc.normalScale = clearcoat.clearcoatNormalTexture.scale;\n      }\n    }\n    options.clearcoat = cc;\n  }\n\n  const sheen = rawMaterial.extensions?.KHR_materials_sheen;\n  if (sheen) {\n    const sh: SheenOptions = {\n      color: linearRgbToSrgb(sheen.sheenColorFactor ?? [0, 0, 0]),\n      roughness: sheen.sheenRoughnessFactor ?? 0,\n    };\n    const colorIdx = sheen.sheenColorTexture?.index;\n    const roughIdx = sheen.sheenRoughnessTexture?.index;\n    if (colorIdx !== undefined) sh.texture = source.textures[colorIdx];\n    if (roughIdx !== undefined) sh.roughnessTexture = source.textures[roughIdx];\n    options.sheen = sh;\n    if (colorIdx !== undefined && roughIdx !== undefined && colorIdx !== roughIdx) {\n      warn(\n        `[@pixi/3d] KHR_materials_sheen on material \"${rawMaterial.name ?? '<unnamed>'}\" references two ` +\n          `different textures for sheenColor and sheenRoughness; PixiJS 3D packs both into one slot (RGB+A). ` +\n          `The colour texture will be used and sheen roughness will be sampled from its alpha channel ` +\n          `(usually 1.0 on an sRGB colour texture, effectively giving factor-only roughness). Repack into ` +\n          `a single RGBA image with roughness in alpha for the intended look.`,\n      );\n    }\n  }\n\n  const specular = rawMaterial.extensions?.KHR_materials_specular;\n  if (specular) {\n    const spec: SpecularOptions = {\n      factor: specular.specularFactor ?? 1,\n      color: linearRgbToSrgb(specular.specularColorFactor ?? [1, 1, 1]),\n    };\n    const colorIdx = specular.specularColorTexture?.index;\n    const factorIdx = specular.specularTexture?.index;\n    if (colorIdx !== undefined) spec.colorTexture = source.textures[colorIdx];\n    if (factorIdx !== undefined) spec.texture = source.textures[factorIdx];\n    options.specular = spec;\n    if (colorIdx !== undefined && factorIdx !== undefined && colorIdx !== factorIdx) {\n      warn(\n        `[@pixi/3d] KHR_materials_specular on material \"${rawMaterial.name ?? '<unnamed>'}\" references two ` +\n          `different textures for specularColor (RGB) and specular (A); PixiJS 3D packs both into one slot ` +\n          `(RGB+A). The colour texture will be used and specular factor will be sampled from its alpha ` +\n          `channel (usually 1.0 on an sRGB colour texture, effectively giving factor-only strength). ` +\n          `Repack into a single RGBA image with factor in alpha for the intended look.`,\n      );\n    }\n  }\n\n  const anisotropy = rawMaterial.extensions?.KHR_materials_anisotropy;\n  if (anisotropy) {\n    const aniso: AnisotropyOptions = {\n      strength: anisotropy.anisotropyStrength ?? 0,\n      rotation: anisotropy.anisotropyRotation ?? 0,\n    };\n    const texIdx = anisotropy.anisotropyTexture?.index;\n    if (texIdx !== undefined) aniso.texture = source.textures[texIdx];\n    options.anisotropy = aniso;\n  }\n\n  return new Material3D(options);\n}\n\n/** @internal */\nexport function processMaterial(rawMaterial: GltfFormat.Material, source: Scene3DSource): BaseMaterial3D {\n  if (rawMaterial.extensions?.KHR_materials_unlit) {\n    return processUnlitMaterial(rawMaterial, source);\n  }\n  return processPbrMaterial(rawMaterial, source);\n}\n\n/**\n * Adds the glTF default material after the file's own, at the index `processNodes` gives a\n * primitive with none\n * @internal\n */\nexport function processMaterials(gltfRaw: GltfFormat, source: Scene3DSource): void {\n  const rawMaterials = gltfRaw.materials ?? [];\n\n  rawMaterials.forEach((rawMaterial, index) => {\n    const material = processMaterial(rawMaterial, source);\n\n    material.label = rawMaterial.name;\n    source.materials[index] = material;\n\n    if (rawMaterial.name) {\n      source.material[rawMaterial.name] = material;\n    }\n  });\n\n  if (gltfRaw.meshes?.some((mesh) => mesh.primitives.some((p) => p.material === undefined))) {\n    source.materials[rawMaterials.length] = new Material3D({ metallic: 1, roughness: 1 });\n  }\n}\n","import { RAD_TO_DEG } from 'pixi.js';\n\nimport type { Scene3DDescriptor } from '../../../Scene3DDescriptor';\nimport type { GltfFormat } from '../GltfFormat';\nimport { linearRgbToSrgb } from './processMaterials';\n\nconst lightMap: Record<string, number> = {\n  directional: 0,\n  point: 1,\n  spot: 2,\n};\n\n/** @internal */\nexport function processLights(gltfRaw: GltfFormat, descriptor: Scene3DDescriptor): void {\n  if (gltfRaw.extensions?.KHR_lights_punctual?.lights) {\n    const lights = gltfRaw.extensions.KHR_lights_punctual.lights;\n\n    descriptor.lights = lights.map((rawLight) => {\n      const outerConeAngle = rawLight.spot?.outerConeAngle ?? Math.PI / 4;\n      const innerConeAngle = rawLight.spot?.innerConeAngle ?? 0;\n\n      return {\n        name: rawLight.name,\n        color: linearRgbToSrgb(rawLight.color ?? [1, 1, 1]),\n        intensity: rawLight.intensity,\n        type: lightMap[rawLight.type],\n        range: rawLight.range ?? 0,\n        coneAngle: outerConeAngle * RAD_TO_DEG,\n        penumbra: outerConeAngle > 0 ? Math.max(0, Math.min(1, 1.0 - innerConeAngle / outerConeAngle)) : 0,\n      };\n    });\n  }\n}\n","import { Buffer, BufferUsage, warn } from 'pixi.js';\nimport type { Attribute, Topology, TypedArray } from 'pixi.js';\n\nimport { Geometry3D } from '../../../../geometry/Geometry3D';\nimport type { Geometry3DOptions } from '../../../../geometry/Geometry3D';\nimport { padTo4Components } from '../../../../geometry/utils/Geometry3DUtils';\nimport { Box } from '../../../../math/shapes/Box';\nimport { Vector3 } from '../../../../math/vector/Vector3';\nimport { warnOnce } from '../../../../utils/warnOnce';\nimport type { Scene3DSource } from '../../../Scene3DSource';\nimport { decodeDracoPrimitive } from '../draco/decodeDracoPrimitive';\nimport type { GltfFormat } from '../GltfFormat';\nimport { accessorToVertexFormat, NORMALIZED_SCALE } from '../utils/accessorToVertexFormat';\nimport { getBuffer } from '../utils/getBuffer';\nimport { GLTF_SEMANTIC_TO_ATTRIBUTE } from '../utils/gltfAttributeMap';\nimport { widenColorToRgba } from '../utils/widenColorToRgba';\n\nconst GL_FLOAT = 5126;\n\n/**\n * Pixi's `Topology` has no line loop (2) or triangle fan (6), as WebGPU lacks them: a loop loses its\n * closing segment, and a fan draws wrong\n */\nconst topologyMap: Record<number, Topology> = {\n  0: 'point-list',\n  1: 'line-list',\n  2: 'line-strip',\n  3: 'line-strip',\n  4: 'triangle-list',\n  5: 'triangle-strip',\n  6: 'triangle-list',\n};\n\nasync function processPrimitive(\n  gltfRaw: GltfFormat,\n  buffers: ArrayBuffer[],\n  primitiveRaw: GltfFormat.MeshPrimitive,\n): Promise<Geometry3D> {\n  const options: Geometry3DOptions = {};\n  const dracoExt = primitiveRaw.extensions?.KHR_draco_mesh_compression;\n\n  if (dracoExt) {\n    Object.assign(options, await decodeDracoPrimitive(gltfRaw, buffers, primitiveRaw, dracoExt));\n  } else {\n    if (primitiveRaw.indices !== undefined) {\n      const raw = getBuffer(gltfRaw, buffers, primitiveRaw.indices);\n      options.indices = raw instanceof Uint8Array ? new Uint16Array(raw) : (raw as Uint16Array | Uint32Array);\n    }\n\n    for (const i in primitiveRaw.attributes) {\n      const attributeName = GLTF_SEMANTIC_TO_ATTRIBUTE[i];\n      if (attributeName) {\n        const accessorIndex = primitiveRaw.attributes[i];\n        const data = getBuffer(gltfRaw, buffers, accessorIndex);\n        const accessor = gltfRaw.accessors?.[accessorIndex];\n\n        if ((attributeName === 'colors' || attributeName === 'colors1') && accessor) {\n          (options as Record<string, unknown>)[attributeName] = widenColorToRgba(\n            data as TypedArray,\n            accessor.type === 'VEC3' ? 3 : 4,\n          );\n          continue;\n        }\n\n        (options as Record<string, unknown>)[attributeName] = data;\n      } else {\n        warnOnce(`pixijs-3d-custom-attribute-${i}`, `[@pixi/3d] custom attribute ${i} skipped`);\n      }\n    }\n\n    if (primitiveRaw.targets) {\n      const morphTargets = decodeMorphTargets(gltfRaw, buffers, primitiveRaw.targets);\n      if (morphTargets) options.morphTargets = morphTargets;\n    }\n  }\n\n  const uvAccessorIndex = primitiveRaw.attributes.TEXCOORD_0;\n  if (uvAccessorIndex !== undefined && gltfRaw.accessors) {\n    options.uvs = accessorToAttribute(options.uvs, gltfRaw.accessors[uvAccessorIndex]);\n  }\n\n  const positionAccessorIndex = primitiveRaw.attributes.POSITION;\n  if (positionAccessorIndex !== undefined && gltfRaw.accessors) {\n    const positionAccessor = gltfRaw.accessors[positionAccessorIndex];\n    options.positions = accessorToAttribute(options.positions, positionAccessor);\n\n    const { min, max } = positionAccessor;\n    if (min && max) {\n      const scale = positionAccessor.normalized ? NORMALIZED_SCALE[positionAccessor.componentType] : 1;\n      options.bounds3D = new Box(\n        new Vector3(min[0] * scale, min[1] * scale, min[2] * scale),\n        new Vector3(max[0] * scale, max[1] * scale, max[2] * scale),\n      );\n    } else if (positionAccessor.componentType !== GL_FLOAT) {\n      throw new Error(\n        `[@pixi/3d] POSITION accessor ${positionAccessorIndex} stores integers but has no min and max, ` +\n          'which glTF requires and the bounds come from.',\n      );\n    }\n  }\n\n  options.topology = topologyMap[primitiveRaw.mode ?? 4];\n\n  return new Geometry3D(options);\n}\n\n/**\n * Pads integer VEC3 data to the `x4` format `accessorToVertexFormat` gives it. Draco data comes\n * through here too, as `draco.worker.ts` decodes into the accessor's component type\n */\nfunction accessorToAttribute(\n  data: Float32Array | Attribute | undefined,\n  accessor: GltfFormat.Accessor,\n): Float32Array | Attribute | undefined {\n  if (accessor.componentType === GL_FLOAT || !ArrayBuffer.isView(data)) return data;\n\n  return {\n    buffer: new Buffer({\n      data: accessor.type === 'VEC3' ? padTo4Components(data) : data,\n      usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,\n    }),\n    format: accessorToVertexFormat(accessor),\n  };\n}\n\nfunction decodeMorphTargets(\n  gltfRaw: GltfFormat,\n  buffers: ArrayBuffer[],\n  targets: { [k: string]: number }[],\n): { positions: Float32Array; normals?: Float32Array }[] | undefined {\n  const morphTargets: { positions: Float32Array; normals?: Float32Array }[] = [];\n  let normalCount = 0;\n\n  for (let t = 0; t < targets.length; t++) {\n    const accessorIndex = targets[t].POSITION;\n    if (accessorIndex === undefined) {\n      warn(`[@pixi/3d] morph target ${t} has no POSITION deltas; rendering base pose.`);\n      return undefined;\n    }\n\n    const accessor = gltfRaw.accessors?.[accessorIndex];\n    if (accessor && accessor.componentType !== GL_FLOAT) {\n      warn(\n        `[@pixi/3d] morph target ${t} uses non-float POSITION deltas, which are not supported; rendering base pose.`,\n      );\n      return undefined;\n    }\n\n    const entry: { positions: Float32Array; normals?: Float32Array } = {\n      positions: getBuffer(gltfRaw, buffers, accessorIndex, true) as Float32Array,\n    };\n\n    const normalIndex = targets[t].NORMAL;\n    if (normalIndex !== undefined) {\n      const normalAccessor = gltfRaw.accessors?.[normalIndex];\n      if (normalAccessor && normalAccessor.componentType !== GL_FLOAT) {\n        warn(`[@pixi/3d] morph target ${t} has non-float NORMAL deltas; morphing positions only.`);\n      } else {\n        entry.normals = getBuffer(gltfRaw, buffers, normalIndex, true) as Float32Array;\n        normalCount++;\n      }\n    }\n\n    morphTargets.push(entry);\n  }\n\n  if (normalCount > 0 && normalCount < morphTargets.length) {\n    warn(`[@pixi/3d] morph targets mix NORMAL deltas; morphing positions only.`);\n    for (const target of morphTargets) target.normals = undefined;\n  }\n\n  return morphTargets.length > 0 ? morphTargets : undefined;\n}\n\n/** @internal */\nexport async function processMeshes(gltfRaw: GltfFormat, buffers: ArrayBuffer[], source: Scene3DSource): Promise<void> {\n  if (!gltfRaw.meshes) return;\n\n  await Promise.all(\n    gltfRaw.meshes.map(async (meshRaw, i) => {\n      const geometries = await Promise.all(\n        meshRaw.primitives.map((primitiveRaw) => processPrimitive(gltfRaw, buffers, primitiveRaw)),\n      );\n\n      const targetCount = geometries[0]?.morphTargetCount ?? 0;\n      for (let p = 1; p < geometries.length; p++) {\n        if (geometries[p].morphTargetCount !== targetCount) {\n          warn(\n            `[@pixi/3d] mesh ${i} primitive ${p} has ${geometries[p].morphTargetCount} morph targets, ` +\n              `expected ${targetCount} (all primitives of a mesh must match).`,\n          );\n        }\n      }\n\n      source.geometries[i] = geometries;\n\n      if (meshRaw.name && geometries.length > 0) {\n        source.geometry[meshRaw.name] = geometries[0];\n      }\n    }),\n  );\n}\n","import type { Scene3DDescriptor, Scene3DNode } from '../../../Scene3DDescriptor';\nimport type { GltfFormat } from '../GltfFormat';\n\n/**\n * Gives a primitive with no material the index after the file's materials, where\n * `processMaterials` adds the default one\n * @internal\n */\nexport function processNodes(gltfRaw: GltfFormat, descriptor: Scene3DDescriptor): void {\n  if (!gltfRaw.nodes) return;\n\n  descriptor.nodes = gltfRaw.nodes.map((nodeRaw, index) => {\n    const children = nodeRaw.children ?? [];\n\n    const node: Scene3DNode = {\n      label: nodeRaw.name || `node_${index}`,\n      children,\n    };\n\n    if (nodeRaw.matrix && nodeRaw.matrix.length === 16) {\n      node.position = new Float32Array(3);\n      node.rotation = new Float32Array(4);\n      node.scale = new Float32Array(3);\n\n      decomposeMatrix(nodeRaw.matrix, node.position, node.rotation, node.scale);\n    } else {\n      if (nodeRaw.translation) {\n        node.position = new Float32Array(nodeRaw.translation);\n      }\n\n      if (nodeRaw.scale) {\n        node.scale = new Float32Array(nodeRaw.scale);\n      }\n\n      if (nodeRaw.rotation) {\n        node.rotation = new Float32Array(nodeRaw.rotation);\n      }\n    }\n\n    if (nodeRaw.camera !== undefined) {\n      node.camera = nodeRaw.camera;\n    }\n\n    if (nodeRaw.mesh !== undefined) {\n      node.geometry = nodeRaw.mesh;\n\n      const mesh = gltfRaw.meshes?.[nodeRaw.mesh];\n      if (mesh) {\n        const defaultMaterial = gltfRaw.materials?.length ?? 0;\n\n        node.materials = mesh.primitives.map((p) => p.material ?? defaultMaterial);\n\n        const weights = nodeRaw.weights ?? mesh.weights;\n        if (weights) node.weights = weights;\n      }\n    }\n\n    if (nodeRaw.extensions) {\n      if (nodeRaw.extensions.KHR_lights_punctual) {\n        node.light = nodeRaw.extensions.KHR_lights_punctual.light;\n      }\n\n      if (nodeRaw.extensions.KHR_node_visibility?.visible === false) {\n        node.visible = false;\n      }\n    }\n\n    if (nodeRaw.skin !== undefined) {\n      node.skin = nodeRaw.skin;\n    }\n\n    return node;\n  });\n}\n\nfunction decomposeMatrix(\n  matrix: Float32Array | number[],\n  position: Float32Array,\n  quaternion: Float32Array,\n  scale: Float32Array,\n): void {\n  const te = matrix;\n\n  let sx = Math.sqrt(te[0] * te[0] + te[1] * te[1] + te[2] * te[2]);\n  const sy = Math.sqrt(te[4] * te[4] + te[5] * te[5] + te[6] * te[6]);\n  const sz = Math.sqrt(te[8] * te[8] + te[9] * te[9] + te[10] * te[10]);\n\n  const det =\n    te[0] * (te[5] * te[10] - te[9] * te[6]) -\n    te[4] * (te[1] * te[10] - te[9] * te[2]) +\n    te[8] * (te[1] * te[6] - te[5] * te[2]);\n\n  if (det < 0) sx = -sx;\n\n  position[0] = te[12];\n  position[1] = te[13];\n  position[2] = te[14];\n\n  const invSX = 1 / sx;\n  const invSY = 1 / sy;\n  const invSZ = 1 / sz;\n\n  const m11 = te[0] * invSX;\n  const m21 = te[1] * invSX;\n  const m31 = te[2] * invSX;\n\n  const m12 = te[4] * invSY;\n  const m22 = te[5] * invSY;\n  const m32 = te[6] * invSY;\n\n  const m13 = te[8] * invSZ;\n  const m23 = te[9] * invSZ;\n  const m33 = te[10] * invSZ;\n\n  const trace = m11 + m22 + m33;\n\n  if (trace > 0) {\n    const s = 0.5 / Math.sqrt(trace + 1.0);\n\n    quaternion[3] = 0.25 / s;\n    quaternion[0] = (m32 - m23) * s;\n    quaternion[1] = (m13 - m31) * s;\n    quaternion[2] = (m21 - m12) * s;\n  } else if (m11 > m22 && m11 > m33) {\n    const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);\n\n    quaternion[3] = (m32 - m23) / s;\n    quaternion[0] = 0.25 * s;\n    quaternion[1] = (m12 + m21) / s;\n    quaternion[2] = (m13 + m31) / s;\n  } else if (m22 > m33) {\n    const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);\n\n    quaternion[3] = (m13 - m31) / s;\n    quaternion[0] = (m12 + m21) / s;\n    quaternion[1] = 0.25 * s;\n    quaternion[2] = (m23 + m32) / s;\n  } else {\n    const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);\n\n    quaternion[3] = (m21 - m12) / s;\n    quaternion[0] = (m13 + m31) / s;\n    quaternion[1] = (m23 + m32) / s;\n    quaternion[2] = 0.25 * s;\n  }\n\n  scale[0] = sx;\n  scale[1] = sy;\n  scale[2] = sz;\n}\n","import type { Scene3DDescriptor } from '../../../Scene3DDescriptor';\nimport type { GltfFormat } from '../GltfFormat';\n\n/** @internal */\nexport function processScenes(gltfRaw: GltfFormat, descriptor: Scene3DDescriptor): void {\n  if (!gltfRaw.scenes) return;\n\n  descriptor.scenes = gltfRaw.scenes.map((sceneRaw) => ({\n    children: sceneRaw.nodes,\n    name: sceneRaw.name,\n  }));\n\n  if (gltfRaw.scene !== undefined && gltfRaw.scene < descriptor.scenes.length) {\n    descriptor.defaultScene = gltfRaw.scene;\n  }\n}\n","import { Matrix4 } from '../../../../math/matrix/Matrix4';\nimport { Quaternion } from '../../../../math/rotation/Quaternion';\nimport { Vector3 } from '../../../../math/vector/Vector3';\nimport type { Scene3DDescriptor, Scene3DNode, Scene3DSkin } from '../../../Scene3DDescriptor';\nimport type { GltfFormat } from '../GltfFormat';\nimport { getBuffer } from '../utils/getBuffer';\n\nconst _jointRest = new Matrix4();\nconst _nodeLocal = new Matrix4();\nconst _inverseBind = new Matrix4();\nconst _position = new Vector3();\nconst _quaternion = new Quaternion();\nconst _scale = new Vector3();\nconst _unitScale = new Vector3(1, 1, 1);\n\n/** Composing a rest pose with inverse binds that cancel it leaves float noise near 1e-7 */\nconst BIND_SHAPE_TOLERANCE = 1e-6;\n\n/**\n * Ignores each skin's `skeleton` property, which glTF says skinning doesn't need (§3.7.3.1). Skins with\n * the same nodes and inverse binds merge, so a node's `skin` indexes the descriptor's skins, not the file's\n * @param gltfRaw - Parsed glTF JSON\n * @param buffers - By glTF buffer index\n * @param descriptor - Receives the skins; its joint nodes get marked and its skin indices remapped\n * @internal\n */\nexport function processSkins(gltfRaw: GltfFormat, buffers: ArrayBuffer[], descriptor: Scene3DDescriptor): void {\n  if (!gltfRaw.skins) {\n    descriptor.skins = [];\n\n    return;\n  }\n\n  const parentMap = buildParentMap(gltfRaw.nodes);\n\n  const meshSubtreeCache = new Map<number, boolean>();\n\n  const skins: Scene3DSkin[] = [];\n\n  const skinIndices: number[] = [];\n\n  const entries = gltfRaw.skins.map((skinRaw) => ({\n    skinRaw,\n    parentNode: findParentNode(skinRaw.joints, parentMap),\n    nodes: [] as number[],\n  }));\n\n  const collect = (entry: (typeof entries)[number]): void => {\n    entry.nodes = collectSkeletonNodes(entry.skinRaw.joints, entry.parentNode, parentMap);\n\n    if (!descriptor.nodes) return;\n\n    for (const globalIdx of entry.nodes) {\n      if (subtreeHasMesh(gltfRaw.nodes, globalIdx, meshSubtreeCache)) continue;\n\n      const node = descriptor.nodes[globalIdx];\n\n      if (node) node.isJoint = true;\n    }\n  };\n\n  entries.forEach(collect);\n\n  /** A lift marks new joints, which can sit above another skin's parent node, so loop until none moves */\n  let moved = true;\n\n  while (moved) {\n    moved = false;\n\n    for (const entry of entries) {\n      const parentNode = liftParentNode(entry.parentNode, parentMap, gltfRaw.nodes, descriptor.nodes);\n\n      if (parentNode === entry.parentNode) continue;\n\n      entry.parentNode = parentNode;\n      collect(entry);\n      moved = true;\n    }\n  }\n\n  for (const { skinRaw, parentNode, nodes } of entries) {\n    const inverseBindMatrices = getBuffer(gltfRaw, buffers, skinRaw.inverseBindMatrices!) as Float32Array;\n    const joints = skinRaw.joints;\n\n    const globalToLocal = new Map<number, number>();\n\n    nodes.forEach((globalIdx, localIdx) => globalToLocal.set(globalIdx, localIdx));\n\n    const nodeCount = nodes.length;\n    const skeletonParent = new Int16Array(nodeCount);\n    const skeletonNodes = new Int32Array(nodeCount);\n\n    for (let i = 0; i < nodeCount; i++) {\n      const globalIdx = nodes[i];\n      const globalParent = parentMap[globalIdx];\n\n      skeletonNodes[i] = globalIdx;\n      const localParent = globalToLocal.get(globalParent);\n\n      skeletonParent[i] = localParent !== undefined ? localParent : -1;\n    }\n\n    const skeletonJoints = new Int16Array(joints.length);\n\n    for (let i = 0; i < joints.length; i++) {\n      skeletonJoints[i] = globalToLocal.get(joints[i])!;\n    }\n\n    const skeletonLabels = nodes.map((idx) => gltfRaw.nodes?.[idx]?.name || `node_${idx}`);\n\n    const duplicateOf = skins.findIndex(\n      (other) =>\n        sameValues(other.skeletonNodes, skeletonNodes) && sameValues(other.inverseBindMatrices, inverseBindMatrices),\n    );\n\n    if (duplicateOf !== -1) {\n      skinIndices.push(duplicateOf);\n\n      continue;\n    }\n\n    skinIndices.push(skins.length);\n    skins.push({\n      name: skinRaw.name,\n      inverseBindMatrices,\n      skeletonParent,\n      skeletonNodes,\n      skeletonJoints,\n      skeletonLabels,\n      parentNode,\n      bindShapeMatrix: readBindShapeMatrix(joints[0], parentNode, parentMap, descriptor.nodes, inverseBindMatrices),\n    });\n  }\n\n  descriptor.skins = skins;\n\n  if (descriptor.nodes) {\n    for (const node of descriptor.nodes) {\n      if (node.skin !== undefined) node.skin = skinIndices[node.skin];\n    }\n  }\n}\n\n/**\n * `undefined` near the identity or for a matrix with no inverse. Any other is rebuilt from its\n * position, rotation and scale, dropping shear, so a mesh given those three has exactly this matrix\n * @param joint - The skin's first joint\n * @param parentNode - Where the walk up from the joint stops\n * @param parentMap - Parent node index per node, `-1` for none\n * @param nodes - The descriptor's nodes, which hold the rest pose\n * @param inverseBindMatrices - The skin's inverse bind matrices\n */\nfunction readBindShapeMatrix(\n  joint: number | undefined,\n  parentNode: number,\n  parentMap: Int32Array,\n  nodes: Scene3DNode[] | undefined,\n  inverseBindMatrices: Float32Array,\n): Float32Array | undefined {\n  if (joint === undefined || !nodes) return undefined;\n\n  _jointRest.identity();\n\n  for (let curr = joint; curr !== -1 && curr !== parentNode; curr = parentMap[curr]) {\n    const node = nodes[curr];\n\n    if (!node) continue;\n\n    if (node.position) _position.fromArray(node.position);\n    else _position.set(0, 0, 0);\n\n    if (node.rotation) _quaternion.fromArray(node.rotation);\n    else _quaternion.set(0, 0, 0, 1);\n\n    _jointRest.premultiply(\n      _nodeLocal.compose(_position, _quaternion, node.scale ? _scale.fromArray(node.scale) : _unitScale),\n    );\n  }\n\n  _jointRest.multiply(_inverseBind.fromArray(inverseBindMatrices));\n\n  const elements = _jointRest.elements;\n  let isIdentity = true;\n\n  for (let i = 0; i < 16 && isIdentity; i++) {\n    isIdentity = Math.abs(elements[i] - (i % 5 === 0 ? 1 : 0)) < BIND_SHAPE_TOLERANCE;\n  }\n\n  if (isIdentity) return undefined;\n\n  const determinant = _jointRest.determinant();\n\n  if (determinant === 0 || !Number.isFinite(determinant)) return undefined;\n\n  _jointRest.decompose(_position, _quaternion, _scale);\n  _jointRest.compose(_position, _quaternion, _scale);\n\n  return new Float32Array(_jointRest.elements);\n}\n\nfunction sameValues(a: ArrayLike<number>, b: ArrayLike<number>): boolean {\n  if (a === b) return true;\n  if (a.length !== b.length) return false;\n\n  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n\n  return true;\n}\n\nfunction buildParentMap(nodes?: { children?: number[] }[]): Int32Array {\n  const map = new Int32Array(nodes?.length || 0).fill(-1);\n\n  nodes?.forEach((node, parentIndex) => {\n    node.children?.forEach((childIndex) => {\n      map[childIndex] = parentIndex;\n    });\n  });\n\n  return map;\n}\n\n/**\n * Seeds the cache with `false` before recursing, so a cyclic hierarchy terminates\n * @param nodes - The glTF node list\n * @param index - The subtree's root node\n * @param cache - Results by node index, shared across skins\n */\nfunction subtreeHasMesh(nodes: GltfFormat['nodes'], index: number, cache: Map<number, boolean>): boolean {\n  const cached = cache.get(index);\n  if (cached !== undefined) return cached;\n\n  cache.set(index, false);\n\n  const node = nodes?.[index];\n  let result = node?.mesh !== undefined;\n\n  if (!result && node?.children) {\n    for (const child of node.children) {\n      if (subtreeHasMesh(nodes, child, cache)) {\n        result = true;\n        break;\n      }\n    }\n  }\n\n  cache.set(index, result);\n\n  return result;\n}\n\n/**\n * The lowest node above every joint, or `-1` for none\n * @param joints - The skin's joint node indices\n * @param parentMap - Parent node index per node, `-1` for none\n */\nfunction findParentNode(joints: number[], parentMap: Int32Array): number {\n  const jointSet = new Set(joints);\n\n  let common: number[] | undefined;\n\n  for (const joint of joints) {\n    const parent = parentMap[joint];\n\n    if (jointSet.has(parent)) continue;\n\n    const chain: number[] = [];\n\n    for (let curr = parent; curr !== -1; curr = parentMap[curr]) chain.push(curr);\n\n    common = common ? common.filter((node) => chain.includes(node)) : chain;\n\n    if (!common.length) return -1;\n  }\n\n  return common?.[0] ?? -1;\n}\n\n/**\n * Moves a skin's parent node above every joint and skinned mesh on its way to the root, as\n * `Model3D` builds neither in place\n * @param parentNode - The skin's parent node, `-1` for the root\n * @param parentMap - Parent node index per node, `-1` for none\n * @param gltfNodes - The glTF node list\n * @param nodes - The descriptor's nodes, with the joints found so far marked\n */\nfunction liftParentNode(\n  parentNode: number,\n  parentMap: Int32Array,\n  gltfNodes: GltfFormat['nodes'],\n  nodes: Scene3DNode[] | undefined,\n): number {\n  let lifted = parentNode;\n\n  for (let curr = parentNode; curr !== -1; curr = parentMap[curr]) {\n    const nodeRaw = gltfNodes?.[curr];\n    const isSkinnedMesh = nodeRaw?.mesh !== undefined && nodeRaw.skin !== undefined;\n\n    if (isSkinnedMesh || nodes?.[curr]?.isJoint) lifted = parentMap[curr];\n  }\n\n  return lifted;\n}\n\n/**\n * The joints plus their ancestors below `parentNode`, parents first, as `Skeleton` requires\n * @param joints - The skin's joint node indices\n * @param parentNode - The skin's parent node, `-1` for the root\n * @param parentMap - Parent node index per node, `-1` for none\n */\nfunction collectSkeletonNodes(joints: number[], parentNode: number, parentMap: Int32Array): number[] {\n  const nodeSet = new Set<number>();\n\n  for (const joint of joints) {\n    let curr = joint;\n\n    while (curr !== -1 && curr !== parentNode && !nodeSet.has(curr)) {\n      nodeSet.add(curr);\n      curr = parentMap[curr];\n    }\n  }\n\n  const depthCache = new Map<number, number>();\n  const getDepth = (idx: number): number => {\n    if (depthCache.has(idx)) return depthCache.get(idx)!;\n    let d = 0,\n      p = idx;\n\n    while (p !== -1) {\n      d++;\n      p = parentMap[p];\n    }\n    depthCache.set(idx, d);\n\n    return d;\n  };\n\n  return Array.from(nodeSet).sort((a, b) => getDepth(a) - getDepth(b));\n}\n","import { CompressedSource } from 'pixi.js';\nimport type { SCALE_MODE, Texture, WRAP_MODE } from 'pixi.js';\n\nimport type { Scene3DSource } from '../../../Scene3DSource';\nimport type { GltfFormat } from '../GltfFormat';\n\n/** The glTF default sampler, written to every texture, since pixi's own default clamps to the edge */\nconst DEFAULT_SAMPLER: Required<Pick<GltfFormat.Sampler, 'wrapS' | 'wrapT' | 'magFilter' | 'minFilter'>> = {\n  wrapS: 10497,\n  wrapT: 10497,\n  magFilter: 9729,\n  minFilter: 9987,\n};\n\n/**\n * A `CompressedSource` keeps the mips it shipped with, as the GPU can't generate them\n * @internal\n */\nexport function processTextures(gltfRaw: GltfFormat, images: Texture[], source: Scene3DSource): void {\n  if (gltfRaw.textures) {\n    gltfRaw.textures.forEach((rawTexture, index) => {\n      const texture = images[rawTexture.source!];\n\n      const sampler = { ...DEFAULT_SAMPLER, ...gltfRaw.samplers?.[rawTexture.sampler!] };\n\n      const style = texture.source.style;\n\n      style.addressModeU = getWrapMode(sampler.wrapS);\n      style.addressModeV = getWrapMode(sampler.wrapT);\n      style.magFilter = getMagFilter(sampler.magFilter);\n      style.minFilter = getMinFilter(sampler.minFilter);\n\n      texture.source.autoGenerateMipmaps =\n        !(texture.source instanceof CompressedSource) && wantsMipmaps(sampler.minFilter);\n\n      source.textures[index] = texture;\n\n      if (rawTexture.name) {\n        source.texture[rawTexture.name] = texture;\n      }\n    });\n  }\n}\n\nfunction getWrapMode(mode: number): WRAP_MODE {\n  switch (mode) {\n    case 33071:\n      return 'clamp-to-edge';\n    case 33648:\n      return 'mirror-repeat';\n    case 10497:\n      return 'repeat';\n    default:\n      return 'repeat';\n  }\n}\n\nfunction getMagFilter(mode: number): SCALE_MODE {\n  return mode === 9728 ? 'nearest' : 'linear';\n}\n\nfunction getMinFilter(mode: number): SCALE_MODE {\n  if (mode === 9728 || mode === 9984 || mode === 9986) {\n    return 'nearest';\n  }\n  return 'linear';\n}\n\nfunction wantsMipmaps(minFilter: number): boolean {\n  return minFilter !== 9728 && minFilter !== 9729;\n}\n","import type { Texture } from 'pixi.js';\n\nimport type { Scene3DDescriptor } from '../../Scene3DDescriptor';\nimport { Scene3DSource } from '../../Scene3DSource';\nimport type { GltfFormat } from './GltfFormat';\nimport { processAnimations } from './process/processAnimations';\nimport { processCameras } from './process/processCameras';\nimport { processLights } from './process/processLights';\nimport { processMaterials } from './process/processMaterials';\nimport { processMeshes } from './process/processMeshes';\nimport { processNodes } from './process/processNodes';\nimport { processScenes } from './process/processScenes';\nimport { processSkins } from './process/processSkins';\nimport { processTextures } from './process/processTextures';\n\n/**\n * Skins read the nodes and materials read the textures, so each runs after what it reads\n * @internal\n */\nexport async function parseGltf(\n  gltfRaw: GltfFormat,\n  buffers: ArrayBuffer[] = [],\n  images: Texture[] = [],\n): Promise<Scene3DSource> {\n  const descriptor: Scene3DDescriptor = {};\n\n  processNodes(gltfRaw, descriptor);\n  processScenes(gltfRaw, descriptor);\n  processLights(gltfRaw, descriptor);\n  processCameras(gltfRaw, descriptor);\n\n  const source = new Scene3DSource(descriptor);\n\n  processAnimations(gltfRaw, buffers, source);\n  processSkins(gltfRaw, buffers, descriptor);\n  processTextures(gltfRaw, images, source);\n  await processMeshes(gltfRaw, buffers, source);\n  processMaterials(gltfRaw, source);\n\n  return source;\n}\n","import type { GltfFormat } from '../GltfFormat';\n\nconst GLB_CHUNK_TYPE_JSON = 0x4e4f534a;\nconst GLB_CHUNK_TYPE_BIN = 0x004e4942;\n/** `glTF` in ASCII, read as a little-endian uint32 */\nconst GLB_MAGIC = 0x46546c67;\n/** The GLB header: magic, version and total length, a uint32 each */\nconst GLB_HEADER_BYTES = 12;\n\n/**\n * `buffers` holds the BIN chunk as buffer 0, or is empty when the file has none\n * @internal\n */\nexport function glbToGltf(arrayBuffer: ArrayBuffer): {\n  json: GltfFormat;\n  buffers: ArrayBuffer[];\n} {\n  const dataView = new DataView(arrayBuffer);\n\n  const magic = dataView.getUint32(0, true);\n  const version = dataView.getUint32(4, true);\n  const length = dataView.getUint32(8, true);\n\n  if (magic !== GLB_MAGIC) {\n    throw new Error(`Invalid GLB magic: ${magic.toString(16)}`);\n  }\n\n  if (version < 2) {\n    throw new Error(`Unsupported GLB version: ${version}`);\n  }\n\n  let json: GltfFormat | undefined;\n  const buffers: ArrayBuffer[] = [];\n\n  let offset = GLB_HEADER_BYTES;\n\n  while (offset < length) {\n    const chunkLength = dataView.getUint32(offset, true);\n    const chunkType = dataView.getUint32(offset + 4, true);\n\n    offset += 8;\n\n    if (chunkType === GLB_CHUNK_TYPE_JSON) {\n      const jsonText = new TextDecoder().decode(new Uint8Array(arrayBuffer, offset, chunkLength));\n\n      json = JSON.parse(jsonText);\n    } else if (chunkType === GLB_CHUNK_TYPE_BIN) {\n      const buffer = arrayBuffer.slice(offset, offset + chunkLength);\n\n      buffers.push(buffer);\n    }\n\n    offset += chunkLength;\n  }\n\n  if (!json) {\n    throw new Error('GLB file contains no JSON chunk');\n  }\n\n  return { json, buffers };\n}\n","import { detectAvif, GlobalResourceRegistry } from 'pixi.js';\nimport type { Loader, Texture } from 'pixi.js';\n\nimport type { GltfFormat } from '../GltfFormat';\n\n/** Cached per page; clearing the global resource registry resets it, so tests can fake it */\nlet avifSupport: Promise<boolean> | undefined;\n\nGlobalResourceRegistry.register({\n  clear: () => {\n    avifSupport = undefined;\n  },\n});\n\ninterface LoadedImages {\n  textures: Texture[];\n  urls: string[];\n}\n\n/**\n * Lists each blob URL in `urls` though it's revoked, as it stays its texture's cache key. On a\n * failure it unloads what loaded, since the caller never receives those keys\n * @param json - Parsed glTF JSON; each texture's `source` is rewritten to the image it uses\n * @param basePath - URL prefix for relative image URIs\n * @param buffers - Holds embedded image bytes; a promise lets URI images load while it settles\n * @param loader - Loads each image as a texture\n * @internal\n */\nexport async function loadImages(\n  json: GltfFormat,\n  basePath: string,\n  buffers: ArrayBuffer[] | Promise<ArrayBuffer[]>,\n  loader: Loader,\n): Promise<LoadedImages> {\n  const images = json.images ?? [];\n  const urls: string[] = [];\n  const textures: Texture[] = [];\n\n  const imagePromises = Array.from(await pickImages(json, loader), async ([index, parser]) => {\n    const image = images[index];\n\n    if (image.uri) {\n      const src = image.uri.startsWith('data:') ? image.uri : basePath + image.uri;\n\n      urls.push(src);\n\n      textures[index] = await loader.load({ src, parser });\n    } else if (image.bufferView !== undefined) {\n      const src = await getBlobUrlForImage(image.bufferView, image.mimeType, json, await buffers);\n\n      urls.push(src);\n\n      try {\n        textures[index] = await loader.load({ src, parser });\n      } finally {\n        URL.revokeObjectURL(src);\n      }\n    }\n  });\n\n  const results = await Promise.allSettled([...imagePromises, buffers]);\n  const failure = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');\n\n  if (failure) {\n    await loader.unload(urls);\n    throw failure.reason;\n  }\n\n  return { textures, urls };\n}\n\n/** Most preferred first; the KTX2 parser goes by id, as a data or blob URL has no `.ktx2` to match */\nconst IMAGE_EXTENSIONS = [\n  { name: 'KHR_texture_basisu', parser: 'ktx2' },\n  { name: 'EXT_texture_avif', parser: 'texture' },\n  { name: 'EXT_texture_webp', parser: 'texture' },\n] as const;\n\nasync function pickImages(json: GltfFormat, loader: Loader): Promise<Map<number, 'ktx2' | 'texture'>> {\n  const parsers = new Map<number, 'ktx2' | 'texture'>();\n  const textures = json.textures ?? [];\n  const usable: Record<(typeof IMAGE_EXTENSIONS)[number]['name'], boolean> = {\n    KHR_texture_basisu: loader.parsers.some((parser) => parser.id === 'ktx2'),\n    EXT_texture_avif:\n      textures.some((texture) => texture.extensions?.EXT_texture_avif) && (await (avifSupport ??= detectAvif.test())),\n    EXT_texture_webp: true,\n  };\n\n  textures.forEach((texture, index) => {\n    const extensions: NonNullable<GltfFormat.Texture['extensions']> = texture.extensions ?? {};\n    const preferred = IMAGE_EXTENSIONS.find(({ name }) => usable[name] && extensions[name]);\n\n    if (preferred) {\n      texture.source = extensions[preferred.name]!.source;\n      parsers.set(texture.source, preferred.parser);\n    } else if (texture.source !== undefined) {\n      parsers.set(texture.source, 'texture');\n    } else if (extensions.KHR_texture_basisu) {\n      throw new Error(\n        `[@pixi/3d] glTF texture ${index} has only a KHR_texture_basisu (KTX2) image, which needs pixi's ` +\n          `KTX2 loader: import 'pixi.js/ktx2' before loading the model`,\n      );\n    } else if (extensions.EXT_texture_avif) {\n      throw new Error(\n        `[@pixi/3d] glTF texture ${index} has only an EXT_texture_avif image, and this browser can't decode AVIF`,\n      );\n    } else {\n      throw new Error(`[@pixi/3d] glTF texture ${index} has no PNG, JPEG, WebP, AVIF or KTX2 image`);\n    }\n  });\n\n  return parsers;\n}\n\nasync function getBlobUrlForImage(\n  bufferViewIndex: number,\n  mimeType: string | undefined,\n  json: GltfFormat,\n  buffers: ArrayBuffer[],\n) {\n  const bufferView = json.bufferViews![bufferViewIndex];\n  const buffer = buffers[bufferView.buffer];\n\n  const blob = new Blob([new Uint8Array(buffer, bufferView.byteOffset || 0, bufferView.byteLength)], {\n    type: mimeType || 'image/png',\n  });\n\n  // oxlint-disable-next-line no-restricted-properties -- embedded GLB images are binary; the data: URL from pixijs#11599 would copy each texture through a base64 string\n  return URL.createObjectURL(blob);\n}\n","import { checkDataUrl, checkExtension, ExtensionType, warn } from 'pixi.js';\nimport type { Loader, LoaderParser, ResolvedAsset } from 'pixi.js';\n\nimport type { Scene3DSource } from '../../Scene3DSource';\nimport type { GltfFormat } from './GltfFormat';\nimport { normalizeMeshopt } from './meshopt/normalizeMeshopt';\nimport { parseGltf } from './parseGltf';\nimport { glbToGltf } from './utils/glbToGltf';\nimport { loadImages } from './utils/loadImages';\n\n/**\n * Loads a binary glTF (`.glb`) file as a {@link Scene3DSource}\n *\n * `@pixi/3d` registers it with `Assets` on import, and `Assets.unload(url)` frees the source as\n * {@link Scene3DSource#destroy} describes. Compressed data and texture formats load as\n * {@link loadGltf} describes.\n *\n * Only the buffer packed in the file loads: a buffer kept outside it isn't fetched, and the loader\n * warns. Images kept outside it resolve relative to the `.glb` URL.\n * @example\n * ```ts\n * import 'pixi.js/ktx2'; // only needed for models with KTX2 textures\n * import { Assets } from 'pixi.js';\n * import { Model3D, type Scene3DSource } from '@pixi/3d';\n *\n * const source = await Assets.load<Scene3DSource>('robot.glb');\n * view3d.root.addChild(new Model3D(source));\n * ```\n * @category assets\n * @advanced\n */\nexport const loadGlb = {\n  extension: {\n    type: ExtensionType.LoadParser,\n    name: 'loadGlb',\n  },\n  // oxlint-disable-next-line typescript/no-deprecated -- pixi's Loader._validateParsers keys parsers by name too, and reports an id conflict for each parser after the first that leaves it out\n  name: 'loadGlb',\n  id: 'glb',\n  test(url: string) {\n    return checkDataUrl(url, 'model/gltf-binary') || checkExtension(url, '.glb');\n  },\n  async load(url: string, _resolvedAsset?: ResolvedAsset, loader?: Loader) {\n    const response = await fetch(url);\n    const arrayBuffer = await response.arrayBuffer();\n\n    const basePath = url.substring(0, url.lastIndexOf('/') + 1);\n\n    const { json, buffers } = glbToGltf(arrayBuffer);\n\n    padContainerBuffers(json.buffers ?? [], buffers);\n\n    await normalizeMeshopt(json, buffers);\n\n    const images = await loadImages(json, basePath, buffers, loader!);\n\n    const source = await parseGltf(json, buffers, images.textures);\n\n    source._imageUrls.push(...images.urls);\n\n    return source;\n  },\n  /**\n   * Keeps the order of `loadGltf.unload`, which says why\n   * @param source - The source `load` returned\n   * @param _resolvedAsset - Unused\n   * @param loader - The loader that cached the images\n   */\n  async unload(source: Scene3DSource, _resolvedAsset?: ResolvedAsset, loader?: Loader) {\n    for (const material of source.materials) material.destroy();\n    await loader!.unload(source._imageUrls);\n    source.destroy();\n  },\n} satisfies LoaderParser<Scene3DSource>;\n\nfunction padContainerBuffers(declared: NonNullable<GltfFormat['buffers']>, buffers: ArrayBuffer[]): void {\n  for (let i = buffers.length; i < declared.length; i++) {\n    const isMeshoptFallback =\n      declared[i].extensions?.EXT_meshopt_compression?.fallback === true ||\n      declared[i].extensions?.KHR_meshopt_compression?.fallback === true;\n\n    if (!isMeshoptFallback) {\n      warn(\n        `[@pixi/3d] GLB buffer ${i} (\"${declared[i].uri ?? 'no uri'}\") lives outside the container; ` +\n          `external GLB buffers are not loaded, so anything reading it will come back empty.`,\n      );\n    }\n\n    buffers.push(new ArrayBuffer(0));\n  }\n}\n","import { checkDataUrl, checkExtension, ExtensionType } from 'pixi.js';\nimport type { Loader, LoaderParser, ResolvedAsset } from 'pixi.js';\n\nimport type { Scene3DSource } from '../../Scene3DSource';\nimport type { GltfFormat } from './GltfFormat';\nimport { normalizeMeshopt } from './meshopt/normalizeMeshopt';\nimport { parseGltf } from './parseGltf';\nimport { loadImages } from './utils/loadImages';\n\n/**\n * Loads a `.gltf` file, with its external buffers and images, as a {@link Scene3DSource}\n *\n * `@pixi/3d` registers it with `Assets` on import, and `Assets.unload(url)` frees the source as\n * {@link Scene3DSource#destroy} describes. {@link loadGlb} loads the binary `.glb` form.\n *\n * Meshopt-compressed buffers (`EXT_meshopt_compression`, `KHR_meshopt_compression`) and\n * Draco-compressed meshes (`KHR_draco_mesh_compression`) decode as they load. Draco fetches its\n * decoder from the URLs {@link setDracoDecoderPath} sets.\n *\n * Each texture loads the first of its images the app supports, in this order:\n * - KTX2 (`KHR_texture_basisu`), once `import 'pixi.js/ktx2'` registers pixi's KTX2 loader. That\n *   loader fetches its transcoder from jsDelivr unless pixi's `setKTXTranscoderPath` sets other URLs.\n * - AVIF (`EXT_texture_avif`), in a browser that decodes it.\n * - WebP (`EXT_texture_webp`).\n * - The PNG or JPEG in its `source`.\n *\n * A texture with no image the app supports fails the load, with an error that says why.\n *\n * Two glTF texture features work with limits:\n * - Every texture samples the first UV set. One that asks for another, as some baked occlusion maps\n *   do, samples the first instead, and the loader warns.\n * - A material applies the first `KHR_texture_transform` it finds on its textures to all of them.\n * @example\n * ```ts\n * import 'pixi.js/ktx2'; // only needed for models with KTX2 textures\n * import { Assets } from 'pixi.js';\n * import { Model3D, type Scene3DSource } from '@pixi/3d';\n *\n * const source = await Assets.load<Scene3DSource>('robot.gltf');\n * view3d.root.addChild(new Model3D(source));\n * ```\n * @category assets\n * @advanced\n */\nexport const loadGltf = {\n  extension: {\n    type: ExtensionType.LoadParser,\n    name: 'loadGltf',\n  },\n  // oxlint-disable-next-line typescript/no-deprecated -- pixi's Loader._validateParsers keys parsers by name too, and reports an id conflict for each parser after the first that leaves it out\n  name: 'loadGltf',\n  id: 'gltf',\n  test(url: string) {\n    return checkDataUrl(url, 'model/gltf+json') || checkExtension(url, '.gltf');\n  },\n  async load(url: string, _resolvedAsset?: ResolvedAsset, loader?: Loader) {\n    const response = await fetch(url);\n    const json: GltfFormat = await response.json();\n    const basePath = url.substring(0, url.lastIndexOf('/') + 1);\n\n    const bufferPromises = (json.buffers || []).map(async (buffer) => {\n      if (buffer.uri) {\n        if (buffer.uri.startsWith('data:')) {\n          const response = await fetch(buffer.uri);\n\n          return await response.arrayBuffer();\n        }\n\n        const bufferUrl = basePath + buffer.uri;\n        const bufferResponse = await fetch(bufferUrl);\n\n        return await bufferResponse.arrayBuffer();\n      }\n\n      const isMeshoptFallback =\n        buffer.extensions?.EXT_meshopt_compression?.fallback === true ||\n        buffer.extensions?.KHR_meshopt_compression?.fallback === true;\n\n      if (isMeshoptFallback) {\n        return new ArrayBuffer(0);\n      }\n\n      throw new Error('GLTF buffer has no URI');\n    });\n\n    const buffersReady = Promise.all(bufferPromises).then(async (buffers) => {\n      await normalizeMeshopt(json, buffers);\n\n      return buffers;\n    });\n\n    const images = await loadImages(json, basePath, buffersReady, loader!);\n    const source = await parseGltf(json, await buffersReady, images.textures);\n\n    source._imageUrls.push(...images.urls);\n\n    return source;\n  },\n  /**\n   * Destroys the materials first, as pixi warns when a bound texture source is destroyed, then unloads\n   * the images through the loader, as pixi also warns when a source `Assets` manages is destroyed directly\n   * @param source - The source `load` returned\n   * @param _resolvedAsset - Unused\n   * @param loader - The loader that cached the images\n   */\n  async unload(source: Scene3DSource, _resolvedAsset?: ResolvedAsset, loader?: Loader) {\n    for (const material of source.materials) material.destroy();\n    await loader!.unload(source._imageUrls);\n    source.destroy();\n  },\n} satisfies LoaderParser<Scene3DSource>;\n","import { Geometry, GlobalResourceRegistry } from 'pixi.js';\n\nlet triangle: Geometry | undefined;\n\nGlobalResourceRegistry.register({\n  clear: () => {\n    triangle?.destroy(true);\n    triangle = undefined;\n  },\n});\n\n/**\n * The oversized clip-space triangle every fullscreen draw shares; it outlives every draw, since WebGPU submits draws\n * later and a buffer destroyed first voids the frame, and only `releaseGlobalResources` on a renderer destroy frees it\n * @internal\n */\nexport function fullscreenTriangleGeometry(): Geometry {\n  triangle ??= new Geometry({\n    attributes: {\n      aPosition: new Float32Array([-1, -1, 3, -1, -1, 3]),\n    },\n  });\n  return triangle;\n}\n","import type { TEXTURE_FORMATS } from 'pixi.js';\n\nimport type { ShaderBit } from '../ShaderBit';\n\nconst srgbDecodeBit: ShaderBit = {\n  name: 'decodeToLinearSrgb',\n  gpu: { header: /*wgsl*/ 'fn decodeToLinear(c: vec3<f32>) -> vec3<f32> { return pow(c, vec3<f32>(2.2)); }' },\n  gl: { header: /*glsl*/ 'vec3 decodeToLinear(vec3 c) { return pow(c, vec3(2.2)); }' },\n};\n\nconst linearDecodeBit: ShaderBit = {\n  name: 'decodeToLinearNone',\n  gpu: { header: /*wgsl*/ 'fn decodeToLinear(c: vec3<f32>) -> vec3<f32> { return c; }' },\n  gl: { header: /*glsl*/ 'vec3 decodeToLinear(vec3 c) { return c; }' },\n};\n\n/**\n * For the opaque copy, pass whether the materials tone-map, since its format can't tell under\n * `toneMapping: 'custom'`\n * @internal\n */\nexport function decodeToLinearBit(encoded: boolean): ShaderBit {\n  return encoded ? srgbDecodeBit : linearDecodeBit;\n}\n\n/** @internal */\nexport function isLinearFormat(format: TEXTURE_FORMATS): boolean {\n  return format.includes('float') || format.endsWith('-srgb');\n}\n","import type { ShaderBit } from '../ShaderBit';\nimport { mathConstantsBit } from './mathConstantsBit';\n\n/** @internal */\nexport const iblSamplingFuncsBit: ShaderBit = {\n  name: 'iblSamplingFuncs',\n  requires: [mathConstantsBit],\n  gpu: {\n    header: /*wgsl*/ `\nfn radicalInverseVdC(bits_in: u32) -> f32 {\n  var bits = bits_in;\n  bits = (bits << 16u) | (bits >> 16u);\n  bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\n  bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\n  bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\n  bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\n  return f32(bits) * 2.3283064365386963e-10;\n}\n\nfn hammersley(i: u32, N: u32) -> vec2<f32> {\n  return vec2<f32>(f32(i) / f32(N), radicalInverseVdC(i));\n}\n\nfn importanceSampleGGX(Xi: vec2<f32>, N: vec3<f32>, roughness: f32) -> vec3<f32> {\n  let a = roughness * roughness;\n\n  let phi = 2.0 * PI * Xi.x;\n  let cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));\n  let sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\n  let H = vec3<f32>(\n    cos(phi) * sinTheta,\n    sin(phi) * sinTheta,\n    cosTheta\n  );\n\n  var up: vec3<f32>;\n  if abs(N.z) < 0.999 {\n    up = vec3<f32>(0.0, 0.0, 1.0);\n  } else {\n    up = vec3<f32>(1.0, 0.0, 0.0);\n  }\n\n  let tangent = normalize(cross(up, N));\n  let bitangent = cross(N, tangent);\n\n  let sampleVec = tangent * H.x + bitangent * H.y + N * H.z;\n  return normalize(sampleVec);\n}\n`,\n  },\n  gl: {\n    header: /*glsl*/ `\nfloat radicalInverseVdC(uint bits) {\n    bits = (bits << 16u) | (bits >> 16u);\n    bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\n    bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\n    bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\n    bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\n    return float(bits) * 2.3283064365386963e-10;\n}\n\nvec2 hammersley(uint i, uint N) {\n    return vec2(float(i) / float(N), radicalInverseVdC(i));\n}\n\nvec3 importanceSampleGGX(vec2 Xi, vec3 N, float roughness) {\n    float a = roughness * roughness;\n\n    float phi = 2.0 * PI * Xi.x;\n    float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));\n    float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\n    vec3 H = vec3(\n        cos(phi) * sinTheta,\n        sin(phi) * sinTheta,\n        cosTheta\n    );\n\n    vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\n    vec3 tangent = normalize(cross(up, N));\n    vec3 bitangent = cross(N, tangent);\n\n    vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;\n    return normalize(sampleVec);\n}\n`,\n  },\n};\n","import { RendererType } from 'pixi.js';\nimport type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\n/**\n * WebGL 2 draws into a float texture only with `EXT_color_buffer_float`; WebGPU always can\n * @internal\n */\nexport function assertFloatRenderable(renderer: WebGLRenderer | WebGPURenderer, what: string): void {\n  if (renderer.type !== RendererType.WEBGL || (renderer as WebGLRenderer).context.extensions.colorBufferFloat) return;\n  throw new Error(\n    `${what}: this WebGL 2 device has no EXT_color_buffer_float, so it cannot draw into a float texture.`,\n  );\n}\n\n/**\n * Picks `rg11b10ufloat`, which has no alpha, or `rgba16float` on a WebGPU device without\n * `rg11b10ufloat-renderable`; WebGL 2 needs what {@link assertFloatRenderable} checks\n * @internal\n */\nexport function floatRgbFormat(renderer: WebGLRenderer | WebGPURenderer): 'rg11b10ufloat' | 'rgba16float' {\n  if (renderer.type !== RendererType.WEBGPU) return 'rg11b10ufloat';\n  return (renderer as WebGPURenderer).gpu.device.features.has('rg11b10ufloat-renderable')\n    ? 'rg11b10ufloat'\n    : 'rgba16float';\n}\n","import { BindGroup, CubeTexture, RenderTarget, State, TextureSource, UniformGroup } from 'pixi.js';\nimport type { CubeTextureSource, WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport { fullscreenTriangleGeometry } from '../fullscreenTriangleGeometry';\nimport { decodeToLinearBit, isLinearFormat } from '../shader/bits/decodeToLinearBit';\nimport { iblSamplingFuncsBit } from '../shader/bits/iblSamplingFuncsBit';\nimport type { ShaderBit } from '../shader/ShaderBit';\nimport type { ShaderBitTemplate } from '../shader/ShaderBitTemplate';\nimport { assertFloatRenderable, floatRgbFormat } from '../textures/floatRenderTargets';\n\ninterface GenerateIblSpecialCubemapOptions {\n  renderer: WebGPURenderer | WebGLRenderer;\n  sourceTexture: CubeTexture;\n  size?: number;\n  sampleCount?: number;\n  mipLevelCount?: number;\n  label?: string;\n}\n\n/**\n * Largest value every `rg11b10ufloat` channel holds; this prefilter and `equirectToCube.ts` cap radiance at it,\n * so no texel becomes infinity\n * @internal\n */\nexport const RG11B10_MAX = 64512;\n\n/** The source's mip count once uploaded, since pixi raises it for `autoGenerateMipmaps` only at upload */\nfunction sourceMipLevelCount(source: CubeTextureSource): number {\n  return source.autoGenerateMipmaps\n    ? Math.floor(Math.log2(Math.max(source.pixelWidth, source.pixelHeight))) + 1\n    : source.mipLevelCount;\n}\n\n/**\n * Prefilters an environment cube into the specular cube IBL reads, restoring the bind as `generateBrdfLut` does\n *\n * Writes `floatRgbFormat`, since every lit fragment samples the cube and 4 bytes a texel halve `rgba16float`'s\n * bandwidth. Floors the weight sum at 1e-4, as a 0 / 0 NaN would stay in the mip. Only the WGSL face mapping\n * negates y, as WebGPU puts texture row 0 at clip y = +1.\n * @throws On WebGL 2 without `EXT_color_buffer_float`.\n * @internal\n */\nexport function generateIblSpecialCubemap(options: GenerateIblSpecialCubemapOptions): CubeTexture {\n  const { renderer, sourceTexture } = options;\n\n  const size = options.size ?? Math.min(256, Math.max(128, sourceTexture.source.pixelWidth));\n  const sampleCount = options.sampleCount ?? 1024;\n  const label = options.label ?? 'ibl-specular';\n  assertFloatRenderable(renderer, 'View3D environment, for the cube a cubemap environment is prefiltered into');\n  const format = floatRgbFormat(renderer);\n  const mipLevelCount = options.mipLevelCount ?? 5;\n\n  const gpuTemplate = /* wgsl */ `\n     {{header}}\n\n     fn getDirection(face: i32, pos: vec2<f32>) -> vec3<f32> {\n        let u = pos.x;\n        let v = -pos.y;\n        \n        var dir = vec3<f32>(0.0);\n        \n        switch face {\n            case 0: { dir = vec3<f32>(1.0, -v, -u); }\n            case 1: { dir = vec3<f32>(-1.0, -v, u); }\n            case 2: { dir = vec3<f32>(u, 1.0, v); }\n            case 3: { dir = vec3<f32>(u, -1.0, -v); }\n            case 4: { dir = vec3<f32>(u, -v, 1.0); }\n            default: { dir = vec3<f32>(-u, -v, -1.0); }\n        }\n\n        return dir;\n     }\n\n     fn sourceLod(NdotH: f32, roughness: f32, solidAnglePerTexel: f32) -> f32 {\n        let a2 = roughness * roughness * roughness * roughness;\n        let d = NdotH * NdotH * (a2 - 1.0) + 1.0;\n        let pdf = a2 / (PI * d * d) * 0.25;\n        let solidAnglePerSample = 1.0 / (local.sampleCount * pdf + 1e-4);\n        return clamp(0.5 * log2(solidAnglePerSample / solidAnglePerTexel) + 1.0, 0.0, local.sourceMaxMip);\n     }\n\n     @vertex\n     fn mainVertex(input: VertexInput) -> VertexOutput {\n       var output: VertexOutput;\n       output.position = vec4<f32>(input.aPosition, 0.0, 1.0);\n       output.vDir = getDirection(i32(local.layer + 0.5), input.aPosition);\n       return output;\n     }\n\n     @fragment\n     fn mainFragment(input: FragmentInput) -> @location(0) vec4<f32> {\n        let N = normalize(input.vDir);\n        let R = N;\n        let V = R;\n        \n        let maxMipLevel = f32(local.mipLevelCount) - 1.0;\n        let roughness = local.mipLevel / maxMipLevel;\n        \n        if roughness < 0.01 {\n            let s = textureSampleLevel(uSourceTexture, uSampler, N, 0.0).rgb;\n            return vec4<f32>(min(decodeToLinear(s), vec3<f32>(${RG11B10_MAX}.0)), 1.0);\n        }\n        \n        var prefilteredColor = vec3<f32>(0.0);\n        var totalWeight = 0.0;\n        \n        let sampleCount = u32(local.sampleCount);\n        let solidAnglePerTexel = 4.0 * PI / (6.0 * local.sourceSize * local.sourceSize);\n        \n        for (var i = 0u; i < sampleCount; i++) {\n            let Xi = hammersley(i, sampleCount);\n            let H = importanceSampleGGX(Xi, N, roughness);\n            let L = normalize(2.0 * dot(V, H) * H - V);\n            \n            let NdotL = max(dot(N, L), 0.0);\n            let lod = sourceLod(dot(N, H), roughness, solidAnglePerTexel);\n            let sampleColor = decodeToLinear(textureSampleLevel(uSourceTexture, uSampler, L, lod).rgb);\n            \n            let weight = NdotL * step(0.0001, NdotL);\n            prefilteredColor += sampleColor * weight;\n            totalWeight += weight;\n        }\n        \n        prefilteredColor = prefilteredColor / max(totalWeight, 1e-4);\n        \n        return vec4<f32>(min(prefilteredColor, vec3<f32>(${RG11B10_MAX}.0)), 1.0);\n     }\n  `;\n\n  const glTemplate = {\n    vertex: /* glsl */ `#version 300 es\n        {{header}}\n\n        vec3 getDirection(int face, vec2 pos) {\n            float u = pos.x;\n            float v = pos.y;\n            \n            vec3 dir = vec3(0.0);\n            \n            switch(face) {\n                case 0: dir = vec3(1.0, -v, -u); break;\n                case 1: dir = vec3(-1.0, -v, u); break;\n                case 2: dir = vec3(u, 1.0, v); break;\n                case 3: dir = vec3(u, -1.0, -v); break;\n                case 4: dir = vec3(u, -v, 1.0); break;\n                default: dir = vec3(-u, -v, -1.0); break;\n            }\n\n            return dir;\n        }\n\n        void main() {\n            gl_Position = vec4(aPosition, 0.0, 1.0);\n            vDir = getDirection(int(layer + 0.5), aPosition);\n        }\n      `,\n    fragment: /* glsl */ `#version 300 es\n        {{header}}\n\n        out vec4 fragColor;\n\n        float sourceLod(float NdotH, float roughness, float solidAnglePerTexel) {\n            float a2 = roughness * roughness * roughness * roughness;\n            float d = NdotH * NdotH * (a2 - 1.0) + 1.0;\n            float pdf = a2 / (PI * d * d) * 0.25;\n            float solidAnglePerSample = 1.0 / (sampleCount * pdf + 1e-4);\n            return clamp(0.5 * log2(solidAnglePerSample / solidAnglePerTexel) + 1.0, 0.0, sourceMaxMip);\n        }\n\n        void main() {\n            vec3 N = normalize(vDir);\n            vec3 R = N;\n            vec3 V = R;\n            \n            float maxMipLevel = mipLevelCount - 1.0;\n            float roughness = mipLevel / maxMipLevel;\n            \n            if (roughness < 0.01) {\n                vec3 s = textureLod(uSourceTexture, N, 0.0).rgb;\n                fragColor = vec4(min(decodeToLinear(s), vec3(${RG11B10_MAX}.0)), 1.0);\n                return;\n            }\n            \n            vec3 prefilteredColor = vec3(0.0);\n            float totalWeight = 0.0;\n            \n            uint sampleCountUint = uint(sampleCount);\n            float solidAnglePerTexel = 4.0 * PI / (6.0 * sourceSize * sourceSize);\n            \n            for (uint i = 0u; i < sampleCountUint; i++) {\n                vec2 Xi = hammersley(i, sampleCountUint);\n                vec3 H = importanceSampleGGX(Xi, N, roughness);\n                vec3 L = normalize(2.0 * dot(V, H) * H - V);\n                \n                float NdotL = max(dot(N, L), 0.0);\n                float lod = sourceLod(dot(N, H), roughness, solidAnglePerTexel);\n                vec3 sampleColor = decodeToLinear(textureLod(uSourceTexture, L, lod).rgb);\n                \n                float weight = NdotL * step(0.0001, NdotL);\n                prefilteredColor += sampleColor * weight;\n                totalWeight += weight;\n            }\n            \n            prefilteredColor = prefilteredColor / max(totalWeight, 1e-4);\n            fragColor = vec4(min(prefilteredColor, vec3(${RG11B10_MAX}.0)), 1.0);\n        }\n      `,\n  };\n\n  const template: ShaderBitTemplate = {\n    bindGroups: ['local'],\n    gpu: gpuTemplate,\n    gl: glTemplate,\n  };\n\n  const localBit: ShaderBit = {\n    name: 'iblPrefilter',\n    requires: [iblSamplingFuncsBit, decodeToLinearBit(!isLinearFormat(sourceTexture.source.format))],\n    attributes: {\n      aPosition: 'float32x2',\n    },\n    interStage: {\n      vDir: 'vec3<f32>',\n    },\n    bindings: {\n      local: {\n        uSourceTexture: 'texture_cube<f32>',\n        uSampler: 'sampler',\n        layer: 'f32',\n        mipLevel: 'f32',\n        mipLevelCount: 'f32',\n        sampleCount: 'f32',\n        sourceSize: 'f32',\n        sourceMaxMip: 'f32',\n      },\n    },\n  };\n\n  const cubeTextureSource = new TextureSource({\n    label,\n    width: size,\n    height: size,\n    viewDimension: 'cube',\n    arrayLayerCount: 6,\n    mipLevelCount,\n    format,\n  }) as CubeTextureSource;\n\n  const localUniforms = new UniformGroup({\n    layer: { value: 0, type: 'f32' },\n    mipLevel: { value: 0, type: 'f32' },\n    mipLevelCount: { value: mipLevelCount, type: 'f32' },\n    sampleCount: { value: sampleCount, type: 'f32' },\n    sourceSize: { value: sourceTexture.source.pixelWidth, type: 'f32' },\n    sourceMaxMip: { value: sourceMipLevelCount(sourceTexture.source) - 1, type: 'f32' },\n  });\n\n  const localBindGroup = new BindGroup({\n    local: localUniforms,\n    uSourceTexture: sourceTexture.source,\n    uSampler: sourceTexture.source.style,\n  });\n\n  const shader = renderer.material3d.compileIsolatedShader([localBit], template, {\n    0: localBindGroup,\n  });\n\n  const geometry = fullscreenTriangleGeometry();\n\n  const renderTarget = new RenderTarget({\n    colorTextures: [cubeTextureSource],\n  });\n\n  const localUbo = shader.resources.local;\n\n  const savedBind = renderer.renderTarget.renderTarget ? renderer.renderTarget.getBindState() : null;\n\n  for (let i = 0; i < 6; i++) {\n    for (let j = 0; j < mipLevelCount; j++) {\n      localUbo.uniforms.layer = i;\n      localUbo.uniforms.mipLevel = j;\n\n      const batchedUbo =\n        'uniformBatch' in renderer.renderPipes ? renderer.renderPipes.uniformBatch.getUboResource(localUbo) : localUbo;\n\n      localBindGroup.setResource(batchedUbo, 'local');\n\n      renderer.renderTarget.bind({ target: renderTarget, clear: true, mipLevel: j, layer: i });\n\n      renderer.encoder.draw({\n        geometry,\n        shader,\n        state: State.default2d,\n      });\n    }\n  }\n\n  if (savedBind) renderer.renderTarget.bind(savedBind);\n\n  localBindGroup.destroy();\n  shader.destroy();\n  renderTarget.destroy();\n\n  return new CubeTexture({\n    source: cubeTextureSource,\n  });\n}\n","import { CompressedSource, CubeTexture } from 'pixi.js';\n\nimport { RG11B10_MAX } from '../../../core/ibl/generateIblSpecialCubemap';\nimport type { RadianceImage } from './parseRadianceHdr';\n\nconst f32 = new Float32Array(1);\nconst u32 = new Uint32Array(f32.buffer);\n\n/** Negative values and NaN give 0, values past `RG11B10_MAX` clamp, and values under 2⁻¹⁴ flush to 0 */\nfunction toUfloat(value: number, mantissaBits: number): number {\n  if (!(value > 0)) return 0;\n  f32[0] = Math.min(value, RG11B10_MAX);\n  const bits = u32[0];\n  const exponent = ((bits >>> 23) & 0xff) - 112;\n  if (exponent <= 0) return 0;\n  const shift = 23 - mantissaBits;\n  return ((exponent << mantissaBits) | ((bits >>> shift) & ((1 << mantissaBits) - 1))) + ((bits >>> (shift - 1)) & 1);\n}\n\n/**\n * Follows the cube-map face table GPU APIs share, `s` and `t` running -1 to 1 from the top-left\n * @param face - In pixi's order: +X, -X, +Y, -Y, +Z, -Z\n * @param s - Across the face\n * @param t - Down the face\n * @param out - Receives the unnormalised direction\n */\nfunction faceDirection(face: number, s: number, t: number, out: Float64Array): void {\n  switch (face) {\n    case 0:\n      out[0] = 1;\n      out[1] = -t;\n      out[2] = -s;\n      break;\n    case 1:\n      out[0] = -1;\n      out[1] = -t;\n      out[2] = s;\n      break;\n    case 2:\n      out[0] = s;\n      out[1] = 1;\n      out[2] = t;\n      break;\n    case 3:\n      out[0] = s;\n      out[1] = -1;\n      out[2] = -t;\n      break;\n    case 4:\n      out[0] = s;\n      out[1] = -t;\n      out[2] = 1;\n      break;\n    default:\n      out[0] = -s;\n      out[1] = -t;\n      out[2] = -1;\n  }\n}\n\n/**\n * Works in place: blocks go in row order, so a write never lands on a texel a later block reads\n * @param rgb - The face's RGB floats at its front, replaced there by the halved face\n * @param size - The face's width, a power of two above 1\n */\nfunction halveFace(rgb: Float32Array, size: number): void {\n  const half = size >> 1;\n  for (let y = 0; y < half; y++) {\n    for (let x = 0; x < half; x++) {\n      const a = (y * 2 * size + x * 2) * 3;\n      const b = a + size * 3;\n      const o = (y * half + x) * 3;\n      for (let c = 0; c < 3; c++) rgb[o + c] = 0.25 * (rgb[a + c] + rgb[a + 3 + c] + rgb[b + c] + rgb[b + 3 + c]);\n    }\n  }\n}\n\nfunction packRg11b10(rgb: Float32Array, texels: number): Uint32Array {\n  const out = new Uint32Array(texels);\n  for (let i = 0; i < texels; i++) {\n    out[i] =\n      (toUfloat(rgb[i * 3], 6) | (toUfloat(rgb[i * 3 + 1], 6) << 11) | (toUfloat(rgb[i * 3 + 2], 5) << 22)) >>> 0;\n  }\n  return out;\n}\n\n/**\n * `rg11b10ufloat` holds light above 1 in half the memory of `rgba16float`, and filters with no\n * extension. Each mip averages the one above, for the prefilter in `generateIblSpecialCubemap.ts`\n * @internal\n */\nexport function equirectToCube(image: RadianceImage, faceSize: number, label: string): CubeTexture {\n  const { width, height, data } = image;\n  const dir = new Float64Array(3);\n  const rgb = new Float32Array(faceSize * faceSize * 3);\n  const sources: CompressedSource[] = [];\n\n  for (let face = 0; face < 6; face++) {\n    for (let y = 0; y < faceSize; y++) {\n      const t = ((y + 0.5) / faceSize) * 2 - 1;\n      for (let x = 0; x < faceSize; x++) {\n        const s = ((x + 0.5) / faceSize) * 2 - 1;\n        faceDirection(face, s, t, dir);\n        const length = Math.sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]);\n        const u = (Math.atan2(dir[2], dir[0]) / (2 * Math.PI) + 0.5) * width - 0.5;\n        const v = (0.5 - Math.asin(dir[1] / length) / Math.PI) * height - 0.5;\n\n        const x0 = Math.floor(u);\n        const y0 = Math.max(0, Math.floor(v));\n        const fx = u - x0;\n        const fy = Math.min(1, Math.max(0, v - y0));\n        const left = ((x0 % width) + width) % width;\n        const right = (left + 1) % width;\n        const top = Math.min(y0, height - 1) * width;\n        const bottom = Math.min(y0 + 1, height - 1) * width;\n\n        const o = (y * faceSize + x) * 3;\n        for (let c = 0; c < 3; c++) {\n          const upper = data[(top + left) * 3 + c] * (1 - fx) + data[(top + right) * 3 + c] * fx;\n          const lower = data[(bottom + left) * 3 + c] * (1 - fx) + data[(bottom + right) * 3 + c] * fx;\n          rgb[o + c] = upper * (1 - fy) + lower * fy;\n        }\n      }\n    }\n\n    const levels: Uint32Array[] = [packRg11b10(rgb, faceSize * faceSize)];\n    for (let size = faceSize; size > 1; size >>= 1) {\n      halveFace(rgb, size);\n      levels.push(packRg11b10(rgb, (size >> 1) ** 2));\n    }\n    sources.push(\n      new CompressedSource({ resource: levels, format: 'rg11b10ufloat', width: faceSize, height: faceSize, label }),\n    );\n  }\n\n  const [right, left, top, bottom, front, back] = sources;\n\n  return CubeTexture.from({\n    faces: { right, left, top, bottom, front, back },\n    label,\n    mipLevelCount: right.mipLevelCount,\n  });\n}\n","/**\n * Linear RGB floats, row 0 at the top\n * @internal\n */\nexport interface RadianceImage {\n  width: number;\n  height: number;\n  data: Float32Array;\n}\n\nconst latin1 = new TextDecoder('latin1');\n\n/**\n * Adds 0.5 to each mantissa before scaling it by `2^(e - 136)`, as Radiance's own decoder does\n * @throws If the file isn't `32-bit_rle_rgbe` in the standard `-Y <height> +X <width>` layout, or ends early\n * @internal\n */\nexport function parseRadianceHdr(buffer: ArrayBuffer): RadianceImage {\n  const bytes = new Uint8Array(buffer);\n  let pos = 0;\n\n  const readLine = (): string => {\n    const start = pos;\n    while (pos < bytes.length && bytes[pos] !== 0x0a) pos++;\n    const line = latin1.decode(bytes.subarray(start, pos));\n    pos++;\n    return line;\n  };\n\n  for (let line = readLine(); line !== ''; line = readLine()) {\n    if (line.startsWith('FORMAT=') && line !== 'FORMAT=32-bit_rle_rgbe') {\n      throw new Error(`parseRadianceHdr: unsupported pixel format \"${line.slice(7)}\"; only 32-bit_rle_rgbe is read.`);\n    }\n  }\n\n  const size = /^-Y (\\d+) \\+X (\\d+)$/.exec(readLine().trim());\n  if (!size) throw new Error('parseRadianceHdr: only the standard \"-Y <height> +X <width>\" orientation is read.');\n  const height = Number(size[1]);\n  const width = Number(size[2]);\n\n  const data = new Float32Array(width * height * 3);\n  const scanline = new Uint8Array(width * 4);\n  const runLength = width >= 8 && width < 0x8000;\n  const exponentScale = new Float64Array(256);\n  for (let e = 1; e < 256; e++) exponentScale[e] = 2 ** (e - 136);\n\n  for (let y = 0; y < height; y++) {\n    if (runLength && bytes[pos] === 2 && bytes[pos + 1] === 2 && ((bytes[pos + 2] << 8) | bytes[pos + 3]) === width) {\n      pos += 4;\n      for (let channel = 0; channel < 4; channel++) {\n        let x = 0;\n        while (x < width) {\n          if (pos >= bytes.length) throw new Error('parseRadianceHdr: the file ends inside a scanline.');\n          let count = bytes[pos++];\n          if (count > 128) {\n            count -= 128;\n            const value = bytes[pos++];\n            for (let i = 0; i < count; i++) scanline[x++ * 4 + channel] = value;\n          } else {\n            for (let i = 0; i < count; i++) scanline[x++ * 4 + channel] = bytes[pos++];\n          }\n        }\n      }\n    } else {\n      if (pos + width * 4 > bytes.length) throw new Error('parseRadianceHdr: the file ends inside a scanline.');\n      scanline.set(bytes.subarray(pos, pos + width * 4));\n      pos += width * 4;\n    }\n\n    let out = y * width * 3;\n    for (let x = 0; x < width; x++) {\n      const scale = exponentScale[scanline[x * 4 + 3]];\n      data[out] = (scanline[x * 4] + 0.5) * scale;\n      data[out + 1] = (scanline[x * 4 + 1] + 0.5) * scale;\n      data[out + 2] = (scanline[x * 4 + 2] + 0.5) * scale;\n      out += 3;\n    }\n  }\n\n  return { width, height, data };\n}\n","import { checkExtension, ExtensionType, path } from 'pixi.js';\nimport type { CubeTexture, LoaderParser, ResolvedAsset } from 'pixi.js';\n\nimport { equirectToCube } from './equirectToCube';\nimport { parseRadianceHdr } from './parseRadianceHdr';\n\n/**\n * Options read from an `.hdr` asset's `data`\n * @category assets\n * @advanced\n */\nexport interface HdrAssetData {\n  /**\n   * Width of each cube face in texels, a power of two\n   *\n   * Defaults to a quarter of the panorama's width, rounded down to a power of two, from 16 to 512.\n   * A 512 cube with its mips takes about 8.4 MB on the GPU and the same again in main memory, and\n   * each doubling takes four times that. Raise it only where a sharper sky is worth the memory.\n   */\n  faceSize?: number;\n}\n\nfunction defaultFaceSize(width: number): number {\n  return Math.min(512, Math.max(16, 2 ** Math.floor(Math.log2(width / 4))));\n}\n\n/**\n * Loads an equirectangular Radiance `.hdr` image as an HDR {@link CubeTexture}\n *\n * Use the cube as {@link View3D#environment}, {@link View3D#background}, or both. It keeps light\n * brighter than white, such as the sun, bright in reflections and in the sky.\n *\n * The conversion runs on the main thread while the asset loads: about 50 ms for a 1k panorama and\n * 150 ms for a 2k one on a fast desktop, longer on a phone. {@link HdrAssetData#faceSize} trades\n * memory for a sharper sky.\n *\n * The centre of the panorama faces +X, so a camera looking down -Z, as the default camera does, is\n * centred a quarter of the way in from the panorama's left edge. HDR panoramas are commonly shown\n * this way on the web.\n *\n * `@pixi/3d` registers it with `Assets` on import, and `Assets.unload(url)` destroys the cube and\n * its faces.\n * @example\n * ```ts\n * import { Assets } from 'pixi.js';\n * import type { CubeTexture } from 'pixi.js';\n * import '@pixi/3d';\n *\n * const sky = await Assets.load<CubeTexture>('studio_2k.hdr');\n * view3d.environment = sky;\n * view3d.background = sky;\n *\n * const sharp = await Assets.load<CubeTexture>({ src: 'sunset_4k.hdr', data: { faceSize: 1024 } });\n * ```\n * @category assets\n * @advanced\n */\nexport const loadHdr = {\n  extension: {\n    type: ExtensionType.LoadParser,\n    name: 'loadHdr',\n  },\n  // oxlint-disable-next-line typescript/no-deprecated -- pixi's Loader._validateParsers keys parsers by name too, and reports an id conflict for each parser after the first that leaves it out\n  name: 'loadHdr',\n  id: 'hdr',\n\n  test(url: string) {\n    return checkExtension(url, '.hdr');\n  },\n\n  async load(url: string, resolvedAsset?: ResolvedAsset<HdrAssetData>) {\n    const response = await fetch(url);\n    if (!response.ok) throw new Error(`loadHdr: fetching ${url} failed with status ${response.status}.`);\n    const image = parseRadianceHdr(await response.arrayBuffer());\n    const faceSize = resolvedAsset?.data?.faceSize ?? defaultFaceSize(image.width);\n\n    return equirectToCube(image, faceSize, path.basename(url, '.hdr'));\n  },\n\n  /**\n   * Destroys the faces too, as destroying a cube's source only detaches them\n   * @param cubeTexture - The cube texture `load` returned\n   */\n  unload(cubeTexture: CubeTexture) {\n    const faces = Object.values(cubeTexture.source.faces);\n    cubeTexture.destroy(true);\n    for (const face of faces) face.destroy();\n  },\n} satisfies LoaderParser<CubeTexture>;\n","/**\n * Most direct commands a run of one pipeline, texture set and geometry records on WebGPU before it\n * merges; lower values cost frame time in distance-sorted passes (`bench/transparency.bench.ts`)\n * @internal\n */\nexport const MERGE_THRESHOLD = 16;\n","import type { InstanceDataStoreBuffer } from '../buffers/InstanceDataStoreBuffer';\n\n/**\n * The instance data of a {@link BatchedMesh3D} as one float array, for rewriting many slots a frame\n *\n * Field `name` of slot `i` is the four numbers from `offset + i * stride + fields[name]`. Call\n * {@link BatchInstanceData.update | update} once you're done, or the writes may never be uploaded:\n *\n * ```ts\n * const { data, stride, offset, fields } = batched.instanceData;\n *\n * for (let i = 0, o = offset + fields.look; i < batched.size; i++, o += stride) {\n *   data[o + 3] = glow[i];\n * }\n *\n * batched.instanceData.update();\n * ```\n *\n * Write `vec4<u32>` and `vec4<i32>` fields through {@link BatchInstanceData.u32Data | u32Data}, which\n * views the same memory at the same indices. The matrices are a separate array,\n * {@link BatchedMesh3D.matrices}, with their own `stride` and `offset`, and `update()` here uploads\n * none of them. Read `stride`, `offset` and `fields` rather than hard-coding them, since the layout\n * can change between releases.\n * @category scene\n * @advanced\n */\nexport class BatchInstanceData {\n  /** Floats from one slot's row to the next in {@link BatchInstanceData.data | data} */\n  public readonly stride: number = 0;\n  /** Float index of slot 0's row in {@link BatchInstanceData.data | data} */\n  public readonly offset: number = 0;\n  /** Each field's first float within a slot's row */\n  public readonly fields: Readonly<Record<string, number>>;\n\n  private readonly _store: InstanceDataStoreBuffer;\n  private readonly _baseIndex: number = 0;\n  private readonly _size: number = 0;\n\n  /** @internal */\n  constructor(store: InstanceDataStoreBuffer, baseIndex: number, size: number) {\n    const { layout } = store;\n\n    this._store = store;\n    this._baseIndex = baseIndex;\n    this._size = size;\n    this.stride = layout.stride;\n    this.offset = baseIndex * layout.stride;\n    this.fields = layout.offsets;\n  }\n\n  /** The instance data as floats; it stays valid across `unload()`, but not past `destroy()` */\n  public get data(): Float32Array {\n    return this._store.data;\n  }\n\n  /**\n   * The same memory as {@link BatchInstanceData.data | data}, as unsigned integers\n   *\n   * A negative number written here keeps its bits, so it reads back negative from a `vec4<i32>`\n   * field.\n   */\n  public get u32Data(): Uint32Array {\n    return this._store.u32Data;\n  }\n\n  /**\n   * Uploads the instance data written in place on the next render\n   *\n   * Pass the range that changed to upload only those slots. Throws a `RangeError` for a range outside\n   * the batch. Once it's called, every slot marked before the next render uploads as one span, from\n   * the lowest to the highest, so for a few scattered slots use\n   * {@link BatchedMesh3D.setInstanceDataAt | setInstanceDataAt} alone.\n   * @param first - The first slot that changed\n   * @param count - How many slots changed; defaults to every slot from `first` on\n   */\n  public update(first = 0, count = this._size - first): void {\n    const size = this._size;\n    if (!(first >= 0 && count >= 0 && first + count <= size)) {\n      throw new RangeError(`update: slots ${first} to ${first + count - 1} are outside the batch (${size} slots).`);\n    }\n    if (count === 0) return;\n\n    const base = this._baseIndex + first;\n    this._store.markDirtyRange(base, base + count - 1);\n  }\n\n  /** @internal */\n  public destroy(): void {\n    (this._store as InstanceDataStoreBuffer | null) = null;\n  }\n}\n","import { Buffer } from 'pixi.js';\nimport type { BufferOptions } from 'pixi.js';\n\n/**\n * A pixi `Buffer` the GC never frees, since recorded bundles, bind groups and VAOs replay it without\n * a lookup; only its owner's `unload` or `destroy` frees it\n * @internal\n */\nexport class Buffer3D extends Buffer {\n  constructor(options: BufferOptions) {\n    super(options);\n    this.autoGarbageCollect = false;\n  }\n}\n","import { isMobile } from 'pixi.js';\n\n/**\n * Bytes one storage-buffer upload call costs, counted as bytes it could have moved instead; set for\n * phones, since a value tuned on desktop costs a phone over 1.5 ms a frame\n * @internal\n */\nexport const BUFFER_CALL_BYTES = 8192;\n\n/**\n * {@link BUFFER_CALL_BYTES} for a data texture, whose upload calls cost more\n * @internal\n */\nexport const TEXTURE_CALL_BYTES = 16384;\n\n/**\n * Smallest span a storage buffer splits into runs on Android, where Chrome writes a smaller span\n * cheaply and runs cost Mali phones more\n * @internal\n */\nexport const BUFFER_SPAN_FLOOR_BYTES = isMobile.android.device ? 4 * 1024 * 1024 : 0;\n\nconst MERGE_GAP_BYTES = 768;\n\nconst FULL_WORD = 0xffffffff;\n\n/** @internal */\nexport class DirtySlots {\n  /** Lowest changed slot, or `Infinity` when nothing changed */\n  public min = Infinity;\n\n  /** Highest changed slot, or `-Infinity` when nothing changed */\n  public max = -Infinity;\n\n  public spanOnly = false;\n\n  /** Start and end slot of each run, end exclusive */\n  public runs = new Int32Array(64);\n\n  public runCount = 0;\n  public runSlots = 0;\n  private _bits: Uint32Array;\n  private readonly _slotBytes: number = 0;\n  private _hasBits = false;\n  private _collected = false;\n\n  constructor(capacity: number, slotBytes: number) {\n    this._bits = new Uint32Array((capacity + 31) >>> 5);\n    this._slotBytes = slotBytes;\n  }\n\n  public get isEmpty(): boolean {\n    return this.min > this.max;\n  }\n\n  public mark(slot: number): void {\n    if (slot < this.min) this.min = slot;\n    if (slot > this.max) this.max = slot;\n    if (this.spanOnly) return;\n\n    const word = slot >>> 5;\n    const bit = 1 << (slot & 31);\n    const bits = this._bits[word];\n    if ((bits & bit) !== 0) return;\n    this._bits[word] = bits | bit;\n    this._hasBits = true;\n  }\n\n  public markRange(from: number, to: number): void {\n    if (from < this.min) this.min = from;\n    if (to > this.max) this.max = to;\n    this.spanOnly = true;\n  }\n\n  /** Takes a full word 32 slots at a time, so a frame that moves every slot costs a step per word */\n  public planRuns(): void {\n    if (this.spanOnly || this.isEmpty) return;\n\n    const bits = this._bits;\n    const gapSlots = Math.floor(MERGE_GAP_BYTES / this._slotBytes);\n    const last = this.max >>> 5;\n    let runCount = 0;\n    let runSlots = 0;\n    let start = -1;\n    let end = -1;\n\n    for (let w = this.min >>> 5; w <= last; w++) {\n      let word = bits[w];\n      if (word === 0) continue;\n      bits[w] = 0;\n\n      if (word === FULL_WORD) {\n        const first = w << 5;\n        if (end >= 0 && first - end <= gapSlots) {\n          end = first + 32;\n        } else {\n          if (end >= 0) {\n            runSlots += end - start;\n            runCount = this._pushRun(runCount, start, end);\n          }\n          start = first;\n          end = first + 32;\n        }\n        continue;\n      }\n\n      while (word !== 0) {\n        const slot = (w << 5) | (31 - Math.clz32(word & -word));\n        word &= word - 1;\n\n        if (end >= 0 && slot - end <= gapSlots) {\n          end = slot + 1;\n        } else {\n          if (end >= 0) {\n            runSlots += end - start;\n            runCount = this._pushRun(runCount, start, end);\n          }\n          start = slot;\n          end = slot + 1;\n        }\n      }\n    }\n\n    if (end >= 0) {\n      runSlots += end - start;\n      runCount = this._pushRun(runCount, start, end);\n    }\n\n    this.runCount = runCount;\n    this.runSlots = runSlots;\n    this._collected = true;\n  }\n\n  public runsBeatSpan(callBytes: number, spanFloorBytes = 0): boolean {\n    if (this.spanOnly || !this._collected) return false;\n    const slotBytes = this._slotBytes;\n    const spanBytes = (this.max - this.min + 1) * slotBytes;\n    return spanBytes >= spanFloorBytes && this.runCount * callBytes + this.runSlots * slotBytes < spanBytes;\n  }\n\n  /**\n   * Forgets every change, clearing the bits `planRuns` left, as when a bulk range claimed the upload or\n   * no GPU view needed a plan\n   */\n  public clear(): void {\n    if (!this._collected && this._hasBits) {\n      this._bits.fill(0, this.min >>> 5, (this.max >>> 5) + 1);\n    }\n    this.min = Infinity;\n    this.max = -Infinity;\n    this.spanOnly = false;\n    this.runCount = 0;\n    this.runSlots = 0;\n    this._hasBits = false;\n    this._collected = false;\n  }\n\n  public grow(capacity: number): void {\n    const words = (capacity + 31) >>> 5;\n    if (words <= this._bits.length) return;\n    const bits = new Uint32Array(words);\n    bits.set(this._bits);\n    this._bits = bits;\n  }\n\n  private _pushRun(runCount: number, start: number, end: number): number {\n    if (runCount * 2 + 2 > this.runs.length) {\n      const runs = new Int32Array(this.runs.length * 2);\n      runs.set(this.runs);\n      this.runs = runs;\n    }\n    this.runs[runCount * 2] = start;\n    this.runs[runCount * 2 + 1] = end;\n    return runCount + 1;\n  }\n}\n","import { Texture, BufferResource, BufferUsage, warn } from 'pixi.js';\nimport type { BufferImageSource } from 'pixi.js';\n\nimport { Buffer3D } from './Buffer3D';\nimport { alignToDataTextureRows, createDataTextureSource, uploadFloatRange } from './dataTextureLayout';\nimport { BUFFER_CALL_BYTES, BUFFER_SPAN_FLOOR_BYTES, DirtySlots, TEXTURE_CALL_BYTES } from './DirtySlots';\n\ninterface RenderDataBufferOptions<T extends object> {\n  stride: number;\n  initialSize?: number;\n  indexKey: string;\n  copier: (\n    data: T,\n    buffer: Float32Array,\n    u32Buffer: Uint32Array,\n    fl64Buffer: Float64Array,\n    offset: number,\n    stride: number,\n  ) => void;\n}\n\n/** Holds its slot index under the store's `indexKey`, which must start at -1 or `allocate` never gives it a slot */\ntype SlotOwner = Record<string, number>;\n\n/** @internal */\nexport class DataStoreBuffer<T extends object = object> {\n  public data: Float32Array;\n  public u32Data: Uint32Array;\n  public fl64Data: Float64Array;\n\n  private _buffer: Buffer3D | null = null;\n  private _bufferResource: BufferResource | null = null;\n\n  private readonly _retiredBuffers: Buffer3D[] = [];\n  private readonly _retiredTextures: Texture[] = [];\n\n  private _texture: Texture | null = null;\n  private _textureSource: BufferImageSource | null = null;\n\n  private _indexKey: string;\n  private _freeList!: Uint32Array;\n  private _freeCount: number = 0;\n  private readonly _stride: number = 0;\n  private _count: number = 0;\n  private readonly _copier: (\n    data: T,\n    buffer: Float32Array,\n    u32Buffer: Uint32Array,\n    fl64Buffer: Float64Array,\n    offset: number,\n    stride: number,\n  ) => void;\n\n  private readonly _dirty: DirtySlots;\n\n  /** Bumped when growth replaces the GPU views, so whatever bound the old ones must bind again */\n  public bufferVersion = 0;\n\n  constructor(options: RenderDataBufferOptions<T>) {\n    this._stride = options.stride;\n    this._indexKey = options.indexKey;\n\n    const initialSize = options.initialSize || 100;\n    let size = initialSize * this._stride;\n    if (size % 4 !== 0) size += 4 - (size % 4);\n    size = alignToDataTextureRows(size);\n\n    this.data = new Float32Array(size);\n    this.u32Data = new Uint32Array(this.data.buffer);\n    this.fl64Data = new Float64Array(this.data.buffer);\n    this._freeList = new Uint32Array(initialSize);\n    this._dirty = new DirtySlots(Math.floor(size / this._stride), this._stride * 4);\n\n    this._copier = options.copier;\n  }\n\n  /**\n   * WebGPU only: pixi's WebGL buffer system keeps only the last range `update` sends before a bind,\n   * so WebGL code reads {@link DataStoreBuffer#texture} and never binds this\n   */\n  public get buffer(): Buffer3D {\n    return (this._buffer ??= new Buffer3D({\n      data: this.data,\n      usage: BufferUsage.STORAGE | BufferUsage.COPY_DST | BufferUsage.COPY_SRC,\n      label: 'RenderDataBuffer',\n    }));\n  }\n\n  public get bufferResource(): BufferResource {\n    return (this._bufferResource ??= new BufferResource({ buffer: this.buffer }));\n  }\n\n  /** Growth replaces it, so read it each frame rather than holding it */\n  public get texture(): Texture {\n    return this._texture || this._initTexture();\n  }\n\n  private _initTexture(): Texture {\n    if (this._stride % 4 !== 0) {\n      warn(\n        `DataStoreBuffer: Stride (${this._stride}) is not a multiple of 4. This will cause issues when sampling from a texture.`,\n      );\n    }\n\n    this._textureSource = createDataTextureSource(this.data);\n    this._texture = new Texture({ source: this._textureSource });\n\n    return this._texture;\n  }\n\n  public update(): void {\n    const dirty = this._dirty;\n    if (dirty.isEmpty) return;\n\n    const buffer = this._buffer;\n    const source = this._textureSource;\n\n    if (buffer || source) {\n      dirty.planRuns();\n\n      const stride = this._stride;\n      const runs = dirty.runs;\n\n      if (buffer) {\n        if (dirty.runsBeatSpan(BUFFER_CALL_BYTES, BUFFER_SPAN_FLOOR_BYTES)) {\n          for (let r = 0; r < dirty.runCount; r++) {\n            const start = runs[r * 2] * stride;\n            buffer.update((runs[r * 2 + 1] * stride - start) * 4, start * 4);\n          }\n        } else {\n          const start = dirty.min * stride;\n          buffer.update(((dirty.max + 1) * stride - start) * 4, start * 4);\n        }\n      }\n\n      if (source) {\n        if (dirty.runsBeatSpan(TEXTURE_CALL_BYTES)) {\n          for (let r = 0; r < dirty.runCount; r++) {\n            uploadFloatRange(source, runs[r * 2] * stride, runs[r * 2 + 1] * stride);\n          }\n        } else {\n          uploadFloatRange(source, dirty.min * stride, (dirty.max + 1) * stride);\n        }\n      }\n    }\n\n    dirty.clear();\n  }\n\n  /** Checks the new slot's end against the array, which is sized in texture rows and can end partway through a slot */\n  public allocate(item: T): number {\n    const slotOwner = item as SlotOwner;\n    let index = slotOwner[this._indexKey];\n\n    if (index < 0) {\n      if (this._freeCount > 0) {\n        index = this._freeList[--this._freeCount];\n      } else {\n        if ((this._count + 1) * this._stride > this.data.length) {\n          this._expand();\n        }\n        index = this._count++;\n      }\n\n      slotOwner[this._indexKey] = index;\n    }\n\n    return index;\n  }\n\n  /**\n   * Too slow for per-frame use at scale, since the `indexKey` read is megamorphic; writes nothing\n   * once the store is destroyed, since items outlive their renderer\n   */\n  public set(item: T): number {\n    if (!this.data) return -1;\n\n    const index = this.allocate(item);\n    const stride = this._stride;\n\n    this._copier(item, this.data, this.u32Data, this.fl64Data, index * stride, stride);\n    this._dirty.mark(index);\n\n    return index;\n  }\n\n  /** Resets the index even once the store is destroyed, so the item can take a slot in the next renderer's store */\n  public remove(item: T): void {\n    const slotOwner = item as SlotOwner;\n    const index = slotOwner[this._indexKey];\n\n    if (index < 0) return;\n\n    slotOwner[this._indexKey] = -1;\n\n    if (!this.data) return;\n\n    if (this._freeCount >= this._freeList.length) {\n      const newFreeList = new Uint32Array(this._freeList.length * 2);\n      newFreeList.set(this._freeList);\n      this._freeList = newFreeList;\n    }\n\n    this._freeList[this._freeCount++] = index;\n  }\n\n  get stride(): number {\n    return this._stride;\n  }\n\n  /**\n   * Reserves `count` slots for a caller that writes them itself; the block is never freed\n   * @param owner - Receives the block's first index under `indexKey`.\n   * @param count - Slots to reserve.\n   */\n  public allocateBlock(owner: SlotOwner, count: number): number {\n    const existing = owner[this._indexKey];\n    if (existing >= 0) return existing;\n\n    const requiredSize = (this._count + count) * this._stride;\n    if (requiredSize > this.data.length) {\n      this._expand(requiredSize);\n    }\n\n    const baseIndex = this._count;\n\n    owner[this._indexKey] = baseIndex;\n    this._count += count;\n    this._dirty.markRange(baseIndex, baseIndex + count - 1);\n\n    return baseIndex;\n  }\n\n  public markDirty(index: number): void {\n    this._dirty.mark(index);\n  }\n\n  /** Makes the whole next upload one span, single marks included, so mark scattered slots with {@link markDirty} */\n  public markDirtyRange(fromIndex: number, toIndex: number): void {\n    this._dirty.markRange(fromIndex, toIndex);\n  }\n\n  private _freeRetired(): void {\n    for (let i = 0; i < this._retiredBuffers.length; i++) this._retiredBuffers[i].destroy();\n    this._retiredBuffers.length = 0;\n\n    for (let i = 0; i < this._retiredTextures.length; i++) this._retiredTextures[i].destroy(true);\n    this._retiredTextures.length = 0;\n  }\n\n  public unload(): void {\n    if (!this.data) return;\n\n    this._buffer?.unload();\n    this._textureSource?.unload();\n    this._freeRetired();\n  }\n\n  public destroy(): void {\n    if (!this.data) return;\n\n    this._bufferResource?.destroy(false);\n    this._buffer?.destroy();\n\n    this._freeRetired();\n\n    this._texture?.destroy(true);\n\n    (this.data as Float32Array | null) = null;\n    (this.u32Data as Uint32Array | null) = null;\n    (this.fl64Data as Float64Array | null) = null;\n    this._buffer = null;\n    this._bufferResource = null;\n\n    (this._freeList as Uint32Array | null) = null;\n    this._texture = null;\n    this._textureSource = null;\n  }\n\n  /**\n   * Retires the GPU views rather than destroying them, since a view that drew earlier this frame\n   * still binds them; `_freeRetired` frees them\n   */\n  protected _expand(minSize?: number): void {\n    let newSize = this.data.length * 2;\n    if (minSize !== undefined && newSize < minSize) newSize = minSize;\n\n    newSize = alignToDataTextureRows(newSize);\n\n    const newData = new Float32Array(newSize);\n    newData.set(this.data);\n    this.data = newData;\n    this.u32Data = new Uint32Array(this.data.buffer);\n    this.fl64Data = new Float64Array(this.data.buffer);\n\n    const newSlotCapacity = newSize / this._stride;\n    this._dirty.grow(Math.floor(newSlotCapacity));\n    if (newSlotCapacity > this._freeList.length) {\n      const newFreeList = new Uint32Array(newSlotCapacity);\n      newFreeList.set(this._freeList);\n      this._freeList = newFreeList;\n    }\n\n    if (this._buffer) {\n      this._retiredBuffers.push(this._buffer);\n      this._buffer = null;\n      this._bufferResource = null;\n    }\n\n    if (this._texture) {\n      this._retiredTextures.push(this._texture);\n      this._texture = null;\n      this._textureSource = null;\n    }\n\n    this.bufferVersion++;\n  }\n}\n","import type { Geometry3D } from '../../geometry/Geometry3D';\nimport type { Mesh3D } from '../../scene/Mesh3D';\nimport { DataStoreBuffer } from './DataStoreBuffer';\n\n/**\n * 32-bit lanes per mesh store row, 24 as WGSL pads `RenderableStruct` to its `mat4x4` alignment. Its\n * fields must stay in lane order, and lanes 16 to 18 in one texel, which `instanceFetchBitGl` fetches once\n * @internal\n */\nexport const MESH3D_STORE_STRIDE = 24;\n/**\n * Written for skinned meshes only, since only skinned shaders read it\n * @internal\n */\nexport const MESH3D_LANE_BONES = 16;\n/** @internal */\nexport const MESH3D_LANE_MATERIAL = 17;\n/**\n * Holds -1 as a `u32`, the cull kernel's `NO_BOUNDS`, until the geometry has a row\n * @internal\n */\nexport const MESH3D_LANE_GEOMETRY = 18;\n/**\n * 0 when hidden; {@link Mesh3DDataStoreBuffer.visible} holds the copy the CPU reads\n * @internal\n */\nexport const MESH3D_LANE_VISIBILITY = 19;\n/**\n * 0 means no weights, since real offsets start past the delta arena; always written, so a reused row\n * never keeps the last owner's offset\n * @internal\n */\nexport const MESH3D_LANE_MORPH_WEIGHT = 20;\n\n/** @internal */\nexport const MESH3D_SPHERE_STRIDE = 4;\n\n/** Moves the 16 floats as 8 f64s, which alias them, to halve the copies */\nconst copyWorldTransform = (fl64Buffer: Float64Array, offset64: number, elements64: Float64Array) => {\n  fl64Buffer[offset64] = elements64[0];\n  fl64Buffer[offset64 + 1] = elements64[1];\n  fl64Buffer[offset64 + 2] = elements64[2];\n  fl64Buffer[offset64 + 3] = elements64[3];\n  fl64Buffer[offset64 + 4] = elements64[4];\n  fl64Buffer[offset64 + 5] = elements64[5];\n  fl64Buffer[offset64 + 6] = elements64[6];\n  fl64Buffer[offset64 + 7] = elements64[7];\n};\n\nconst copyMeshData = (\n  renderable: Mesh3D,\n  _buffer: Float32Array,\n  u32Buffer: Uint32Array,\n  fl64Buffer: Float64Array,\n  offset: number,\n) => {\n  copyWorldTransform(fl64Buffer, offset / 2, renderable.worldTransform.elements64);\n\n  if (renderable.skeleton) {\n    u32Buffer[offset + MESH3D_LANE_BONES] = renderable.skeleton._bonePitIndex;\n  }\n\n  u32Buffer[offset + MESH3D_LANE_MATERIAL] = renderable.material._materialIndex;\n  u32Buffer[offset + MESH3D_LANE_GEOMETRY] = renderable.geometry._geometryDataIndex;\n\n  u32Buffer[offset + MESH3D_LANE_MORPH_WEIGHT] = renderable._morph ? renderable._morph._weightIndex : 0;\n};\n\n/**\n * Writes radius -1, which the cull always keeps, for dynamic geometry or an empty sphere\n * @internal\n */\nexport function transformBoundingSphere(\n  out: Float32Array,\n  o: number,\n  matrix: ArrayLike<number>,\n  matrixOffset: number,\n  geometry: Geometry3D,\n  radiusGrowth: number,\n): void {\n  const local = geometry.boundsSphere;\n  const radius = local.radius;\n\n  if (geometry.dynamic || radius < 0) {\n    out[o] = 0;\n    out[o + 1] = 0;\n    out[o + 2] = 0;\n    out[o + 3] = -1;\n\n    return;\n  }\n\n  const center = local.center;\n  const cx = center.x;\n  const cy = center.y;\n  const cz = center.z;\n  const m00 = matrix[matrixOffset];\n  const m01 = matrix[matrixOffset + 1];\n  const m02 = matrix[matrixOffset + 2];\n  const m10 = matrix[matrixOffset + 4];\n  const m11 = matrix[matrixOffset + 5];\n  const m12 = matrix[matrixOffset + 6];\n  const m20 = matrix[matrixOffset + 8];\n  const m21 = matrix[matrixOffset + 9];\n  const m22 = matrix[matrixOffset + 10];\n\n  out[o] = m00 * cx + m10 * cy + m20 * cz + matrix[matrixOffset + 12];\n  out[o + 1] = m01 * cx + m11 * cy + m21 * cz + matrix[matrixOffset + 13];\n  out[o + 2] = m02 * cx + m12 * cy + m22 * cz + matrix[matrixOffset + 14];\n\n  const sx = m00 * m00 + m01 * m01 + m02 * m02;\n  const sy = m10 * m10 + m11 * m11 + m12 * m12;\n  const sz = m20 * m20 + m21 * m21 + m22 * m22;\n  out[o + 3] = (radius + radiusGrowth) * Math.sqrt(Math.max(sx, sy, sz));\n}\n\n/** @internal */\nexport class Mesh3DDataStoreBuffer extends DataStoreBuffer<Mesh3D> {\n  /**\n   * Each row's sphere for the CPU cull, in its matrix's space; `null` until {@link writesSpheres} first\n   * turns on, and never uploaded\n   */\n  public boundingSpheres: Float32Array | null = null;\n\n  /** While off, {@link boundingSpheres} go stale, so the batch sweeps every row when it turns this on */\n  public writesSpheres = false;\n\n  /** Each row's visibility lane as a byte, so a CPU walk reads 1 byte a row; write both through `_storeVisibility` */\n  public visible: Uint8Array;\n\n  constructor(initialSize = 100) {\n    super({\n      stride: MESH3D_STORE_STRIDE,\n      initialSize,\n      indexKey: '_storeIndex',\n      copier: copyMeshData,\n    });\n\n    this.visible = new Uint8Array(Math.floor(this.data.length / MESH3D_STORE_STRIDE));\n  }\n\n  public enableSphereWrites(value: boolean): void {\n    this.writesSpheres = value;\n    if (value && this.boundingSpheres === null && this.data) {\n      this.boundingSpheres = new Float32Array(\n        Math.floor(this.data.length / MESH3D_STORE_STRIDE) * MESH3D_SPHERE_STRIDE,\n      );\n    }\n  }\n\n  public override set(item: Mesh3D): number {\n    const index = super.set(item);\n    if (index >= 0) {\n      this._storeVisibility(index, item._worldVisible);\n      const geometry = item.geometry;\n      this.writeBoundingSphere(\n        index,\n        this.data,\n        index * MESH3D_STORE_STRIDE,\n        geometry,\n        item._morph ? geometry._morphBoundsExpansion : 0,\n      );\n    }\n\n    return index;\n  }\n\n  public writeBoundingSphere(\n    index: number,\n    matrix: ArrayLike<number>,\n    matrixOffset: number,\n    geometry: Geometry3D,\n    radiusGrowth: number,\n  ): void {\n    if (!this.writesSpheres) return;\n    transformBoundingSphere(\n      this.boundingSpheres!,\n      index * MESH3D_SPHERE_STRIDE,\n      matrix,\n      matrixOffset,\n      geometry,\n      radiusGrowth,\n    );\n  }\n\n  /** Called as the transform pass computes the matrix, while it's still in the CPU cache */\n  public writeWorldTransform(index: number, elements64: Float64Array): void {\n    copyWorldTransform(this.fl64Data, index * (MESH3D_STORE_STRIDE >> 1), elements64);\n    this.markDirty(index);\n  }\n\n  public writeVisibility(index: number, worldVisible: number): void {\n    this._storeVisibility(index, worldVisible);\n    this.markDirty(index);\n  }\n\n  /** Marks nothing for upload, since the block's allocation already did */\n  public writeVisibilityRange(first: number, count: number, worldVisible: number): void {\n    for (let i = first, end = first + count; i < end; i++) this._storeVisibility(i, worldVisible);\n  }\n\n  private _storeVisibility(index: number, worldVisible: number): void {\n    this.u32Data[index * MESH3D_STORE_STRIDE + MESH3D_LANE_VISIBILITY] = worldVisible;\n    this.visible[index] = worldVisible;\n  }\n\n  public override destroy(): void {\n    super.destroy();\n    (this.visible as Uint8Array | null) = null;\n    this.boundingSpheres = null;\n  }\n\n  protected override _expand(minSize?: number): void {\n    super._expand(minSize);\n\n    const visible = new Uint8Array(Math.floor(this.data.length / MESH3D_STORE_STRIDE));\n    visible.set(this.visible);\n    this.visible = visible;\n    if (this.boundingSpheres === null) return;\n\n    const spheres = new Float32Array(Math.floor(this.data.length / MESH3D_STORE_STRIDE) * MESH3D_SPHERE_STRIDE);\n    spheres.set(this.boundingSpheres);\n    this.boundingSpheres = spheres;\n  }\n}\n","import { MESH3D_STORE_STRIDE } from '../buffers/Mesh3DDataStoreBuffer';\nimport type { Mesh3DBatch } from './Mesh3DBatch';\n\n/**\n * The slot matrices of a {@link BatchedMesh3D} as one float array, for rewriting many slots a frame\n *\n * Slot `i`'s matrix is the 16 floats from `offset + i * stride`, column-major and affine, as\n * {@link BatchedMesh3D.setMatrixAt | setMatrixAt} takes it. Call {@link BatchMatrices.update | update}\n * once you're done, or the writes may never be uploaded:\n *\n * ```ts\n * const { data, stride, offset } = batched.matrices;\n *\n * for (let i = 0, o = offset; i < batched.size; i++, o += stride) {\n *   // Rotation and scale live in 0-2, 4-6 and 8-10; translation in 12-14.\n *   data[o + 12] = x[i];\n *   data[o + 13] = y[i];\n *   data[o + 14] = z[i];\n * }\n *\n * batched.matrices.update();\n * ```\n *\n * A new slot's matrix is all zeros, so set each full matrix once before writing only the lanes that\n * move. Write only a slot's 16 floats: the floats between matrices hold engine data, such as the\n * slot's material and visibility. Read `stride` and `offset` rather than hard-coding them, since the\n * layout can change between releases.\n * @category scene\n * @advanced\n */\nexport class BatchMatrices {\n  /** Floats from one slot's matrix to the next in {@link BatchMatrices.data | data} */\n  public readonly stride: number = MESH3D_STORE_STRIDE;\n  /** Float index of slot 0's matrix in {@link BatchMatrices.data | data} */\n  public readonly offset: number = 0;\n\n  private readonly _batch: Mesh3DBatch;\n  private readonly _baseIndex: number = 0;\n\n  /** @internal */\n  constructor(batch: Mesh3DBatch, baseIndex: number) {\n    this._batch = batch;\n    this._baseIndex = baseIndex;\n    this.offset = baseIndex * MESH3D_STORE_STRIDE;\n  }\n\n  /** The float array holding every slot's matrix; it stays valid across `unload()`, but not past `destroy()` */\n  public get data(): Float32Array {\n    return this._batch.storeBuffer.data;\n  }\n\n  /**\n   * Uploads the matrices written through {@link BatchMatrices.data | data} on the next render, for\n   * drawing, culling and shadows alike\n   *\n   * Pass the range that changed, or nothing for every slot. Throws a `RangeError` for a range outside\n   * the batch. The next render then uploads every matrix from slot 0 to the end of the range in one\n   * go, so for a few scattered slots use `setMatrixAt` alone.\n   * @param first - The first slot that changed\n   * @param count - How many slots changed; defaults to every slot from `first` on\n   */\n  public update(first = 0, count = this._batch.items.length - first): void {\n    const batch = this._batch;\n    const items = batch.items;\n    if (!(first >= 0 && count >= 0 && first + count <= items.length)) {\n      throw new RangeError(\n        `update: slots ${first} to ${first + count - 1} are outside the batch (${items.length} slots).`,\n      );\n    }\n    if (count === 0) return;\n\n    const base = this._baseIndex + first;\n    batch.storeBuffer.markDirtyRange(base, base + count - 1);\n\n    if (batch.storeBuffer.writesSpheres) {\n      for (let i = first, end = first + count; i < end; i++) batch._writeSlotSphere(i);\n    }\n  }\n\n  /** @internal */\n  public destroy(): void {\n    (this._batch as Mesh3DBatch | null) = null;\n  }\n}\n","import type { BindGroup, Geometry, Shader, State, Topology } from 'pixi.js';\n\nimport type { DrawCommandCapture } from './DrawCommandCapture';\n\n/** @internal */\nexport class DrawCommand {\n  public geometry: Geometry = null!;\n  public shader: Shader = null!;\n  public globalBindGroup: BindGroup = null!;\n  /** The group bound at 2: a material's own, a merged run's, or `undefined` for a pass that binds no material */\n  public batchBindGroup: BindGroup | undefined = undefined;\n  public state: State = null!;\n  public topology: Topology = null!;\n  /** Held here, since the members may be re-keyed or destroyed before a draw list edits the command */\n  public batchKey = 0;\n  /** The id of the texture set {@link batchBindGroup} binds, or 0 for a pass that binds no material */\n  public textureSetId = 0;\n  public merged = false;\n  /**\n   * Whether every member has left; the command keeps its slot so no other command's args move, and\n   * a bundle recorded since skips it, as its material may be destroyed\n   */\n  public dead = false;\n  /** Whether a bundle recorded while the command was dead skipped it, so reviving it re-records the bundles */\n  public leftOut = false;\n  /** The captures a tail command holds while it has members; empty on a command the build recorded */\n  public readonly captures: DrawCommandCapture[] = [];\n}\n","import type { Buffer, Geometry, TextureSource } from 'pixi.js';\n\n/** @internal */\nexport type CapturedResource = Buffer | TextureSource;\n\n/** @internal */\nexport class DrawCommandCapture {\n  /** The `captureTick` of the build that last recorded the resource, or -1 when no build has */\n  public generation = 0;\n  public tailOwners = 0;\n  /** Geometries whose GPU layouts bake the buffer, dropped when it's lost; `null` marks a texture source */\n  public readonly geometries: Geometry[] | null;\n\n  constructor(\n    public readonly resource: CapturedResource,\n    generation: number,\n    geometry: Geometry | null,\n  ) {\n    this.generation = generation;\n    this.geometries = geometry ? [geometry] : null;\n  }\n}\n","import { Geometry } from 'pixi.js';\nimport type { Buffer, Shader, State, TextureSource, Topology } from 'pixi.js';\n\nimport type { BaseMaterial3D } from '../../materials/BaseMaterial3D';\nimport { Buffer3D } from '../buffers/Buffer3D';\nimport type { IndirectDrawData } from '../buffers/IndirectDrawData';\nimport type { CameraData } from '../CameraData';\nimport { SHARED_DEFAULT_TEXTURES } from '../textures/DefaultTextures';\nimport { DrawCommand } from './DrawCommand';\nimport { DrawCommandCapture } from './DrawCommandCapture';\nimport type { CapturedResource } from './DrawCommandCapture';\n\ninterface CaptureTicked {\n  _captureTick?: number;\n}\n\ninterface CaptureStamped {\n  _capturedResourceId?: number;\n  _capturedStyleId?: number;\n}\n\n/**\n * Bumped when a captured texture source or its style changes; material bind groups don't watch their\n * sources, so they refresh when it moves (`refreshMaterialBindings`)\n */\nlet textureDirtyId = 0;\n\n/** Stamps a texture source with its own and its style's `_resourceId`; true when an earlier stamp differs */\nfunction recordTextureIds(source: TextureSource & CaptureStamped): boolean {\n  const id = source._resourceId;\n  const styleId = source.style ? source.style._resourceId : -1;\n  const moved =\n    source._capturedResourceId !== undefined &&\n    (source._capturedResourceId !== id || source._capturedStyleId !== styleId);\n  source._capturedResourceId = id;\n  source._capturedStyleId = styleId;\n  return moved;\n}\n\ninterface DrawOptions {\n  geometry: Geometry;\n  shader: Shader;\n  state: State;\n  topology: Topology;\n  size: number;\n  instanceCount: number;\n  start: number;\n  baseVertex: number;\n  firstInstance: number;\n}\n\ninterface DrawEncoder {\n  draw(options: DrawOptions): void;\n}\n\n/** Refilled per draw so a replay allocates nothing, and emptied after so it pins no resource */\nconst _drawOptions: DrawOptions = {\n  geometry: null!,\n  shader: null!,\n  state: null!,\n  topology: 'triangle-list',\n  size: 0,\n  instanceCount: 0,\n  start: 0,\n  baseVertex: 0,\n  firstInstance: 0,\n};\n\ninterface DrawIndirectEncoder {\n  drawIndirect(options: {\n    geometry: Geometry;\n    shader: Shader;\n    state: State;\n    topology: Topology;\n    indirectBuffer: GPUBuffer;\n    indirectOffset: number;\n  }): void;\n}\n\ninterface DrawCallsResolver {\n  getGPUBuffer(buffer: Buffer): GPUBuffer;\n}\n\ninterface CaptureLifecycleEvents {\n  on(event: 'change' | 'styleChange', fn: (resource: CapturedResource) => void): unknown;\n  off(event: 'change' | 'styleChange', fn: (resource: CapturedResource) => void): unknown;\n}\n\nlet lastCaptureTick = 0;\n\n/**\n * An ordered list of draw commands that every frustum drawing it replays against its own numeric args\n *\n * It listens to every buffer and texture source its build or a tail command bakes, and reports one\n * whose GPU copy goes, or whose style changes, through `onCaptureLost`.\n * @internal\n */\nexport class DrawCommandList {\n  /** Pooled commands; the first `count` are in use */\n  public commands: DrawCommand[] = [];\n  public count = 0;\n\n  /** Commands the last build recorded; those from here to `count` are tail commands, which no bundle holds */\n  public bodyCount = 0;\n\n  /** Bumped once per rebuild, by `clear`; a draw list's edits leave it alone (`DrawList.rangesDirtyId`) */\n  public dirtyId = 0;\n\n  public onCaptureLost?: () => void;\n\n  private readonly _captures = new Map<CapturedResource, DrawCommandCapture>();\n\n  private _destroyed = false;\n\n  /** This build's tick, unique across lists, since geometries and materials keep the last tick that captured them */\n  public captureTick: number = ++lastCaptureTick;\n\n  /**\n   * Drops the GPU layouts that bake a lost buffer through the base `Geometry.unload`, since\n   * `Geometry3D.unload` would also vacate the atlas range; for a texture source it bumps `textureDirtyId`\n   */\n  private readonly _onCaptureResourceLost = (resource: CapturedResource): void => {\n    const geometries = this._captures.get(resource)?.geometries;\n    if (geometries) {\n      for (const geometry of geometries) Geometry.prototype.unload.call(geometry);\n    } else {\n      recordTextureIds(resource as TextureSource);\n      textureDirtyId++;\n    }\n    this.onCaptureLost?.();\n  };\n\n  /**\n   * Hands out the pooled command at `count`, so a builder may lower `count` to drop the commands after it\n   * @returns The command to fill in\n   */\n  public next(): DrawCommand {\n    const i = this.count;\n    const cmd = (this.commands[i] ??= new DrawCommand());\n    cmd.dead = false;\n    cmd.leftOut = false;\n    this.count = i + 1;\n    return cmd;\n  }\n\n  /** Captures each of `geometry`'s buffers for the current build */\n  public captureGeometry(geometry: Geometry): void {\n    const ticked = geometry as Geometry & CaptureTicked;\n    if (ticked._captureTick === this.captureTick) return;\n    ticked._captureTick = this.captureTick;\n\n    const buffers = geometry.buffers;\n    for (let i = 0; i < buffers.length; i++) {\n      this._capture(buffers[i], geometry);\n    }\n  }\n\n  /**\n   * Captures a material's texture sources for the current build and refreshes its bind groups; skips the\n   * shared default textures, which are never destroyed or collected\n   */\n  public captureMaterialTextures(material: BaseMaterial3D): void {\n    if (material._captureTick === this.captureTick) return;\n    material._captureTick = this.captureTick;\n\n    const textures = material._textures;\n    for (let t = 0; t < textures.length; t++) {\n      if (!SHARED_DEFAULT_TEXTURES.has(textures[t])) this._capture(textures[t].source, null);\n    }\n\n    this.refreshMaterialBindings(material);\n  }\n\n  /**\n   * Captures a tail command's buffers and textures while it has members, counting the command as an\n   * owner even of resources the build or another tail command holds\n   */\n  public captureTail(command: DrawCommand, geometry: Geometry, material: BaseMaterial3D | null): void {\n    const held = command.captures;\n\n    const buffers = geometry.buffers;\n    for (let i = 0; i < buffers.length; i++) {\n      const capture = this._capture(buffers[i], geometry, true);\n      if (capture) held.push(capture);\n    }\n    if (!material) return;\n\n    const textures = material._textures;\n    for (let t = 0; t < textures.length; t++) {\n      if (SHARED_DEFAULT_TEXTURES.has(textures[t])) continue;\n      const capture = this._capture(textures[t].source, null, true);\n      if (capture) held.push(capture);\n    }\n\n    this.refreshMaterialBindings(material);\n  }\n\n  /**\n   * Gives back a tail command's captures once its last member leaves; a buffer capture that stays\n   * forgets the command's geometry unless something else still draws it\n   */\n  public releaseTail(command: DrawCommand): void {\n    const held = command.captures;\n    const geometry = command.geometry;\n    let tailDraws = false;\n    for (let i = this.bodyCount; i < this.count && !tailDraws; i++) {\n      const other = this.commands[i];\n      tailDraws = other !== command && other.geometry === geometry && other.captures.length > 0;\n    }\n    const drawn = tailDraws || (geometry as Geometry & CaptureTicked)._captureTick === this.captureTick;\n\n    for (let i = 0; i < held.length; i++) {\n      const capture = held[i];\n      if (--capture.tailOwners > 0 || capture.generation === this.captureTick) {\n        if (!drawn && capture.geometries) {\n          const at = capture.geometries.indexOf(geometry);\n          if (at >= 0) capture.geometries.splice(at, 1);\n        }\n        continue;\n      }\n      this._unwatch(capture);\n      this._captures.delete(capture.resource);\n    }\n    held.length = 0;\n  }\n\n  /** Refreshes a material's bind groups if a texture changed since their last refresh */\n  public refreshMaterialBindings(material: BaseMaterial3D): void {\n    if (material._lastTextureDirtyId === textureDirtyId) return;\n    material._lastTextureDirtyId = textureDirtyId;\n    material._refreshTextureBindings();\n  }\n\n  /**\n   * Captures a resource for the current build, or for a tail command, watching it if nothing did\n   * @returns The capture, or `undefined` for an engine-owned `Buffer3D`, which pixi's GC never frees\n   */\n  private _capture(\n    resource: CapturedResource,\n    geometry: Geometry | null,\n    tail = false,\n  ): DrawCommandCapture | undefined {\n    if (resource instanceof Buffer3D) return undefined;\n\n    const generation = tail ? -1 : this.captureTick;\n    let capture = this._captures.get(resource);\n    if (capture === undefined) {\n      capture = new DrawCommandCapture(resource, generation, geometry);\n      this._captures.set(resource, capture);\n      (resource as unknown as CaptureLifecycleEvents).on('change', this._onCaptureResourceLost);\n      if (geometry === null) this._watchTexture(resource as TextureSource);\n    } else {\n      if (!tail && capture.generation !== generation) {\n        capture.generation = generation;\n        if (capture.geometries) capture.geometries.length = 0;\n      }\n      if (geometry && capture.geometries && !capture.geometries.includes(geometry)) capture.geometries.push(geometry);\n    }\n    if (tail) capture.tailOwners++;\n\n    return capture;\n  }\n\n  /**\n   * Watches `styleChange` as well as `change`, since a WebGPU bundle replays the sampler it recorded, and\n   * bumps `textureDirtyId` if the source changed while no list watched it\n   */\n  private _watchTexture(source: TextureSource): void {\n    (source as unknown as CaptureLifecycleEvents).on('styleChange', this._onCaptureResourceLost);\n    if (recordTextureIds(source)) textureDirtyId++;\n  }\n\n  private _unwatch(capture: DrawCommandCapture): void {\n    const events = capture.resource as unknown as CaptureLifecycleEvents;\n    events.off('change', this._onCaptureResourceLost);\n    if (capture.geometries === null) events.off('styleChange', this._onCaptureResourceLost);\n  }\n\n  private _dropCaptures(): void {\n    for (const capture of this._captures.values()) this._unwatch(capture);\n    this._captures.clear();\n  }\n\n  /** Resets the list for a rebuild; the old captures stay until `endBuild` sweeps those not recorded again */\n  public clear(): void {\n    for (let i = this.bodyCount; i < this.count; i++) {\n      const held = this.commands[i].captures;\n      for (let c = 0; c < held.length; c++) held[c].tailOwners = 0;\n      held.length = 0;\n    }\n    this.captureTick = ++lastCaptureTick;\n    this.count = 0;\n    this.bodyCount = 0;\n    this.dirtyId++;\n  }\n\n  /** Finishes a rebuild: sweeps the captures it didn't record again, and makes every command the body's */\n  public endBuild(): void {\n    this.bodyCount = this.count;\n    const generation = this.captureTick;\n    for (const capture of this._captures.values()) {\n      if (capture.generation === generation) continue;\n      this._unwatch(capture);\n      this._captures.delete(capture.resource);\n    }\n  }\n\n  /**\n   * Stamps every captured resource as used; call it on frames that replay a bundle, since a replay binds\n   * nothing for pixi's GC to see\n   */\n  public touch(now: number): void {\n    for (const resource of this._captures.keys()) resource._gcLastUsed = now;\n  }\n\n  /** Drops the commands and every capture, for a build that isn't coming back; `clear` keeps the captures */\n  public releaseCaptures(): void {\n    this.clear();\n    this._dropCaptures();\n  }\n\n  /**\n   * Draws each command from the CPU-side counts in `data`, skipping a size of 0, which pixi takes as the whole buffer\n   *\n   * A bundle that records these draws bakes the counts, so it re-records on `CullResult.countsDirtyId`.\n   */\n  public replayDirect(encoder: DrawEncoder, data: IndirectDrawData, camera: CameraData): void {\n    const args = data.drawCalls;\n    const { bindGroup } = camera;\n    const options = _drawOptions;\n    for (let i = 0; i < this.count; i++) {\n      const o = i * 5;\n      const instanceCount = args[o + 1];\n      if (instanceCount === 0 || args[o] === 0) continue;\n      const cmd = this.commands[i];\n      cmd.shader.groups[0] = cmd.globalBindGroup;\n      cmd.shader.groups[1] = bindGroup;\n      if (cmd.batchBindGroup) cmd.shader.groups[2] = cmd.batchBindGroup;\n      options.geometry = cmd.geometry;\n      options.shader = cmd.shader;\n      options.state = cmd.state;\n      options.topology = cmd.topology;\n      options.size = args[o];\n      options.instanceCount = instanceCount;\n      options.start = args[o + 2];\n      options.baseVertex = args[o + 3];\n      options.firstInstance = args[o + 4];\n      encoder.draw(options);\n    }\n    options.geometry = null!;\n    options.shader = null!;\n    options.state = null!;\n  }\n\n  /** Records one `drawIndirect` per live command (WebGPU), reading command `i`'s five `u32` args at byte `i * 20` */\n  public replay(\n    encoder: DrawIndirectEncoder,\n    resolver: DrawCallsResolver,\n    data: IndirectDrawData,\n    camera: CameraData,\n    from = 0,\n    to = this.count,\n  ): void {\n    const indirectBuffer = resolver.getGPUBuffer(data.drawCallsBuffer);\n    const { bindGroup } = camera;\n    for (let i = from; i < to; i++) {\n      const cmd = this.commands[i];\n      if (cmd.dead) {\n        cmd.leftOut = true;\n        continue;\n      }\n      cmd.shader.groups[0] = cmd.globalBindGroup;\n      cmd.shader.groups[1] = bindGroup;\n      if (cmd.batchBindGroup) cmd.shader.groups[2] = cmd.batchBindGroup;\n      encoder.drawIndirect({\n        geometry: cmd.geometry,\n        shader: cmd.shader,\n        state: cmd.state,\n        topology: cmd.topology,\n        indirectBuffer,\n        indirectOffset: i * 20,\n      });\n    }\n  }\n\n  /** Drops the recorded commands and releases every capture; the numeric args aren't this list's to free */\n  public destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n\n    this._dropCaptures();\n    this.onCaptureLost = undefined;\n    this.count = 0;\n    (this.commands as DrawCommand[] | null) = null;\n  }\n}\n","import { createStructLayout } from '../shader/codegen/structLayout';\nimport type { StructDefinition } from '../shader/ShaderBit';\n\n/**\n * The types a {@link BatchedMesh3D} instance-data field can have\n * @category scene\n * @advanced\n */\nexport type InstanceDataType = 'vec4<f32>' | 'vec4<u32>' | 'vec4<i32>';\n\n/**\n * One instance-data field of a {@link BatchedMesh3D}: its type and the value every slot starts with\n * @category scene\n * @advanced\n */\nexport interface InstanceDataField {\n  /** The four numbers every slot starts with */\n  value: ArrayLike<number>;\n  /** What a shader bit reads `instance.<name>` as */\n  type: InstanceDataType;\n}\n\n/**\n * The instance-data fields of a {@link BatchedMesh3D}, keyed by the name shader bits read them by\n * @category scene\n * @advanced\n */\nexport type InstanceDataOptions = Record<string, InstanceDataField>;\n\n/** @internal */\nexport interface InstanceDataLayout {\n  readonly struct: StructDefinition;\n  readonly offsets: Readonly<Record<string, number>>;\n  readonly stride: number;\n  readonly defaults: Uint32Array;\n  /** Part of the shader cache key; equal for batches that declare the same fields in the same order */\n  readonly key: string;\n}\n\nconst FIELD_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;\nconst FIELD_TYPES: readonly InstanceDataType[] = ['vec4<f32>', 'vec4<u32>', 'vec4<i32>'];\n\n/**\n * Lays a batch's instance-data fields out over one row; refuses `__` in a name, which GLSL reserves\n * @internal\n */\nexport function createInstanceDataLayout(fields: InstanceDataOptions): InstanceDataLayout {\n  const names = Object.keys(fields);\n  if (names.length === 0) {\n    throw new Error('instanceData: no fields declared. Declare at least one, or leave the option out.');\n  }\n\n  const struct: StructDefinition = {};\n\n  for (const name of names) {\n    const field = fields[name];\n\n    if (!FIELD_NAME.test(name) || name.includes('__')) {\n      throw new Error(\n        `instanceData: \"${name}\" is not a usable field name. Use letters, digits and single underscores, starting with a letter.`,\n      );\n    }\n    if (!FIELD_TYPES.includes(field.type)) {\n      throw new Error(`instanceData: field \"${name}\" is \"${field.type}\". Use ${FIELD_TYPES.join(', ')}.`);\n    }\n    if (field.value?.length !== 4) {\n      throw new Error(`instanceData: field \"${name}\" needs a value of four numbers.`);\n    }\n\n    struct[name] = field.type;\n  }\n\n  const layout = createStructLayout(struct);\n  const defaults = new Uint32Array(layout.size / 4);\n  const floats = new Float32Array(defaults.buffer);\n  const offsets: Record<string, number> = {};\n\n  for (const element of layout.elements) {\n    const word = element.offset / 4;\n    const { type, value } = fields[element.name];\n    const target = type === 'vec4<f32>' ? floats : defaults;\n\n    offsets[element.name] = word;\n    for (let i = 0; i < 4; i++) target[word + i] = value[i];\n  }\n\n  return {\n    struct,\n    offsets,\n    stride: defaults.length,\n    defaults,\n    key: names.map((name) => `${name}:${fields[name].type}`).join(','),\n  };\n}\n","import { createInstanceDataLayout } from '../batcher/instanceDataLayout';\nimport type { InstanceDataLayout, InstanceDataOptions } from '../batcher/instanceDataLayout';\nimport { DataStoreBuffer } from './DataStoreBuffer';\n\nconst noCopy = (): void => {};\n\n/**\n * A slot's row has its mesh store index, which the shaders already hold, so rows before the batch's\n * first slot go unused\n * @internal\n */\nexport class InstanceDataStoreBuffer extends DataStoreBuffer {\n  public readonly layout: InstanceDataLayout;\n\n  constructor(fields: InstanceDataOptions, firstRow: number, slotCount: number) {\n    const layout = createInstanceDataLayout(fields);\n    const rowCount = firstRow + slotCount;\n\n    super({ stride: layout.stride, initialSize: rowCount, indexKey: '_instanceStoreIndex', copier: noCopy });\n\n    this.layout = layout;\n    this.allocateBlock({ _instanceStoreIndex: -1 }, rowCount);\n\n    const { defaults, stride } = layout;\n    const u32 = this.u32Data;\n    for (let row = firstRow; row < rowCount; row++) u32.set(defaults, row * stride);\n  }\n}\n","import type { Mesh3DData } from './Mesh3DData';\n\n/** Change flag: the item's entry in the last order is stale, since it left or re-keyed */\nconst REMOVED = 1;\n\n/** Change flag: the item needs a place in the next order, since it arrived or re-keyed */\nconst PENDING = 2;\n\nconst INSERTION_SHIFT_BUDGET = 32;\n\nconst MAX_INSERTION_BACKOFF = 64;\n\n/**\n * One pass's sorted view of a batch's items: after a sort, `items[indices[i]]` is the i-th in draw order\n *\n * Both sorts start from the last order, so a frame with few changes costs close to one pass over it.\n * @internal\n */\nexport class SortedMesh3DView<T extends Mesh3DData> {\n  /** The batch's item array, shared with its other views, so never copied */\n  public items: T[];\n\n  public count = 0;\n\n  /** Whether `indices` needs a sort */\n  public dirty = true;\n\n  /**\n   * Bumped when a sort may have changed the order; the insertion sort in `sortForced` bumps it only\n   * when an entry moved, since each bump rebuilds a distance-sorted pass's draws\n   */\n  public orderDirtyId = 0;\n\n  public indices: Uint32Array;\n\n  /** Item indices in add order, each removal filled by the last entry; current between sorts, unlike `indices` */\n  public renderableIndices: Uint32Array;\n\n  /** Float64, so a 53-bit key stays exact */\n  private _sortKeys: Float64Array;\n\n  private _localIndices: Uint32Array;\n\n  private readonly _uidToLocal = new Map<number, number>();\n\n  /** Entries of `indices` the last sort left in order, or -1 when there's no order to start from */\n  private _sortedCount = -1;\n\n  private _sortedKeys: Float64Array;\n\n  private _mergeIndices: Uint32Array;\n\n  private _mergeKeys: Float64Array;\n\n  private _changes = new Uint8Array(0);\n\n  private _hasChanges = false;\n\n  /**\n   * Uids flagged {@link PENDING} since the last sort, the first `_pendingCount` of them; counted rather\n   * than truncated, so it keeps its storage\n   */\n  private readonly _pending: number[] = [];\n\n  private _pendingCount = 0;\n\n  private _orderForced = false;\n\n  private _insertionSkip = 0;\n\n  private _insertionBackoff = 0;\n\n  constructor(items: T[], initialCapacity = 32) {\n    this.items = items;\n    this.renderableIndices = new Uint32Array(initialCapacity);\n    this._sortKeys = new Float64Array(initialCapacity);\n    this._localIndices = new Uint32Array(initialCapacity);\n    this.indices = new Uint32Array(initialCapacity);\n    this._sortedKeys = new Float64Array(initialCapacity);\n    this._mergeIndices = new Uint32Array(initialCapacity);\n    this._mergeKeys = new Float64Array(initialCapacity);\n  }\n\n  /** Whether the last order came from `sortForced`, so it holds no key order to merge into or keep commands against */\n  public get orderForced(): boolean {\n    return this._orderForced;\n  }\n\n  /** The item index of a member, or -1 when the view doesn't hold it */\n  public indexOf(uid: number): number {\n    const local = this._uidToLocal.get(uid);\n\n    return local === undefined ? -1 : this.renderableIndices[local];\n  }\n\n  public add(uid: number, renderableIndex: number, sortKey: number): void {\n    const local = this.count++;\n\n    if (local >= this.renderableIndices.length) {\n      this._grow(Math.max(this.renderableIndices.length * 2, 256));\n    }\n\n    this.renderableIndices[local] = renderableIndex;\n    this._sortKeys[local] = sortKey;\n    this._uidToLocal.set(uid, local);\n    this.dirty = true;\n\n    if (this._sortedCount >= 0) this._markPending(uid, renderableIndex);\n  }\n\n  public remove(uid: number): void {\n    const local = this._uidToLocal.get(uid);\n\n    if (local === undefined) return;\n\n    const renderableIndex = this.renderableIndices[local];\n    const lastLocal = --this.count;\n\n    if (local !== lastLocal) {\n      const lastRenderableIdx = this.renderableIndices[lastLocal];\n      const lastKey = this._sortKeys[lastLocal];\n      const lastUid = this._getUidAtLocal(lastLocal);\n\n      this.renderableIndices[local] = lastRenderableIdx;\n      this._sortKeys[local] = lastKey;\n      this._uidToLocal.set(lastUid, local);\n    }\n\n    this._uidToLocal.delete(uid);\n    this.dirty = true;\n\n    if (this._sortedCount >= 0) {\n      this._setChange(renderableIndex, REMOVED);\n      this._changes[renderableIndex] &= ~PENDING;\n    }\n  }\n\n  /** Updates an item's sort key, leaving the view clean when the key is unchanged, as it is after most material swaps */\n  public updateKey(uid: number, key: number): void {\n    const local = this._uidToLocal.get(uid);\n    if (local === undefined) return;\n    if (this._sortKeys[local] === key) return;\n    this._sortKeys[local] = key;\n    this.dirty = true;\n\n    if (this._sortedCount >= 0) {\n      const renderableIndex = this.renderableIndices[local];\n      this._setChange(renderableIndex, REMOVED);\n      this._markPending(uid, renderableIndex);\n    }\n  }\n\n  /** Sorts by key into `indices` if anything changed, patching the last order when few items moved */\n  public sort(): void {\n    const count = this.count;\n    if (count === 0) {\n      this._resetOrder(0);\n      return;\n    }\n    if (!this.dirty) return;\n\n    if (this._sortedCount < 0 || this._orderForced || this._pendingCount > count >> 1 || !this._patchOrder()) {\n      this._sortFull();\n    }\n    this.orderDirtyId++;\n\n    this._orderForced = false;\n    this.dirty = false;\n  }\n\n  /**\n   * Re-reads every key and sorts, dirty or not, trying an insertion sort of the last order first while the items are\n   * unchanged; it backs off after a failure, since a view two cameras take turns sorting fails it every time\n   */\n  public sortForced(getKey: (item: T) => number): void {\n    const count = this.count;\n    if (count === 0) {\n      this._resetOrder(0);\n      this.orderDirtyId++;\n      return;\n    }\n\n    let sorted = false;\n    if (this._orderForced && this._sortedCount === count && !this._hasChanges) {\n      if (this._insertionSkip > 0) this._insertionSkip--;\n      else sorted = this._insertionSort(getKey);\n    }\n\n    if (!sorted) {\n      const items = this.items;\n      const keys = this._sortKeys;\n      const renderableIndices = this.renderableIndices;\n\n      for (let i = 0; i < count; i++) {\n        keys[i] = getKey(items[renderableIndices[i]]);\n      }\n\n      this._sortFull();\n    }\n\n    this._orderForced = true;\n    this.dirty = false;\n  }\n\n  public clear(): void {\n    this.orderDirtyId++;\n    this.count = 0;\n    this._uidToLocal.clear();\n    this.dirty = true;\n    this._resetOrder(-1);\n    this._orderForced = false;\n    this._insertionSkip = 0;\n    this._insertionBackoff = 0;\n  }\n\n  private _sortFull(): void {\n    const count = this.count;\n    const keys = this._sortKeys;\n    const localIndices = this._localIndices;\n    const renderableIndices = this.renderableIndices;\n    const indices = this.indices;\n    const sortedKeys = this._sortedKeys;\n\n    for (let i = 0; i < count; i++) {\n      localIndices[i] = i;\n    }\n\n    localIndices.subarray(0, count).sort((a, b) => keys[a] - keys[b]);\n\n    for (let i = 0; i < count; i++) {\n      const local = localIndices[i];\n      indices[i] = renderableIndices[local];\n      sortedKeys[i] = keys[local];\n    }\n    this.orderDirtyId++;\n\n    this._resetOrder(count);\n  }\n\n  /**\n   * Re-sorts the last order by fresh keys with an insertion sort\n   * @returns `false` when it ran out of budget, so the caller sorts in full\n   */\n  private _insertionSort(getKey: (item: T) => number): boolean {\n    const count = this.count;\n    const items = this.items;\n    const indices = this.indices;\n    const keys = this._sortedKeys;\n\n    for (let i = 0; i < count; i++) {\n      keys[i] = getKey(items[indices[i]]);\n    }\n\n    const budget = count * INSERTION_SHIFT_BUDGET;\n    let shifts = 0;\n\n    for (let i = 1; i < count; i++) {\n      const key = keys[i];\n      if (keys[i - 1] <= key) continue;\n\n      const index = indices[i];\n      let j = i - 1;\n      do {\n        keys[j + 1] = keys[j];\n        indices[j + 1] = indices[j];\n        j--;\n      } while (j >= 0 && keys[j] > key);\n      keys[j + 1] = key;\n      indices[j + 1] = index;\n\n      shifts += i - 1 - j;\n      if (shifts > budget) {\n        this._insertionBackoff = Math.min(MAX_INSERTION_BACKOFF, Math.max(1, this._insertionBackoff * 2));\n        this._insertionSkip = this._insertionBackoff;\n        return false;\n      }\n    }\n\n    this._insertionBackoff = 0;\n    if (shifts > 0) this.orderDirtyId++;\n    return true;\n  }\n\n  /**\n   * Merges the sorted pending items into the last order; equal keys keep the last order, newcomers after\n   * @returns `false` when the patched order doesn't account for every item, so the caller sorts in full\n   */\n  private _patchOrder(): boolean {\n    const count = this.count;\n    const keys = this._sortKeys;\n    const renderableIndices = this.renderableIndices;\n    if (this._changes.length < this.items.length) this._growChanges(this.items.length);\n    const changes = this._changes;\n\n    const arriving = this._localIndices;\n    let arrivingCount = 0;\n    for (let p = 0; p < this._pendingCount; p++) {\n      const local = this._uidToLocal.get(this._pending[p]);\n      if (local === undefined) continue;\n      const renderableIndex = renderableIndices[local];\n      if ((changes[renderableIndex] & PENDING) === 0) continue;\n      changes[renderableIndex] &= ~PENDING;\n      arriving[arrivingCount++] = local;\n    }\n    if (arrivingCount > 1) arriving.subarray(0, arrivingCount).sort((a, b) => keys[a] - keys[b]);\n\n    const previous = this.indices;\n    const previousKeys = this._sortedKeys;\n    const previousCount = this._sortedCount;\n    const merged = this._mergeIndices;\n    const mergedKeys = this._mergeKeys;\n    let i = 0;\n    let j = 0;\n    let o = 0;\n\n    for (;;) {\n      while (i < previousCount && (changes[previous[i]] & REMOVED) !== 0) i++;\n      if (i < previousCount && (j === arrivingCount || previousKeys[i] <= keys[arriving[j]])) {\n        merged[o] = previous[i];\n        mergedKeys[o++] = previousKeys[i++];\n      } else if (j < arrivingCount) {\n        const local = arriving[j++];\n        merged[o] = renderableIndices[local];\n        mergedKeys[o++] = keys[local];\n      } else break;\n    }\n    if (o !== count) return false;\n\n    this.indices = merged;\n    this._mergeIndices = previous;\n    this._sortedKeys = mergedKeys;\n    this._mergeKeys = previousKeys;\n    this._resetOrder(count);\n    return true;\n  }\n\n  /**\n   * Flags an item for a place in the next order, dropping the order once the pending list outgrows\n   * the view, so a view that never sorts doesn't grow it forever\n   */\n  private _markPending(uid: number, renderableIndex: number): void {\n    if (!this._setChange(renderableIndex, PENDING)) return;\n    this._pending[this._pendingCount++] = uid;\n    if (this._pendingCount > this.renderableIndices.length) this._resetOrder(-1);\n  }\n\n  /** Sets a change flag on an item index; returns whether it was newly set */\n  private _setChange(renderableIndex: number, flag: number): boolean {\n    if (renderableIndex >= this._changes.length) this._growChanges(renderableIndex + 1);\n    const changes = this._changes;\n    const flags = changes[renderableIndex];\n    if ((flags & flag) !== 0) return false;\n    changes[renderableIndex] = flags | flag;\n    this._hasChanges = true;\n    return true;\n  }\n\n  /** Grows `_changes`; a patch grows it to the item array's length first, since the merge reading past its end is slow */\n  private _growChanges(minLength: number): void {\n    const grown = new Uint8Array(Math.max(minLength, this._changes.length * 2, 256));\n    grown.set(this._changes);\n    this._changes = grown;\n  }\n\n  private _resetOrder(sortedCount: number): void {\n    if (this._hasChanges) {\n      this._changes.fill(0);\n      this._hasChanges = false;\n      this._pendingCount = 0;\n    }\n    this._sortedCount = sortedCount;\n  }\n\n  private _getUidAtLocal(local: number): number {\n    const renderableIdx = this.renderableIndices[local];\n    return this.items[renderableIdx].uid;\n  }\n\n  private _grow(newCapacity: number): void {\n    const oldRI = this.renderableIndices;\n    const oldKeys = this._sortKeys;\n\n    this.renderableIndices = new Uint32Array(newCapacity);\n    this._sortKeys = new Float64Array(newCapacity);\n    this._localIndices = new Uint32Array(newCapacity);\n    this.indices = new Uint32Array(newCapacity);\n    this._sortedKeys = new Float64Array(newCapacity);\n    this._mergeIndices = new Uint32Array(newCapacity);\n    this._mergeKeys = new Float64Array(newCapacity);\n\n    this.renderableIndices.set(oldRI);\n    this._sortKeys.set(oldKeys);\n\n    this._resetOrder(-1);\n  }\n}\n","/**\n * `u32`s per command, in `drawIndexedIndirect` order\n * @internal\n */\nexport const ARGS_PER_COMMAND = 5;\n\n/** @internal */\nexport class DrawArgs {\n  /** {@link ensureCapacity} may replace the array, so read it rather than holding it */\n  public drawCalls: Uint32Array;\n\n  constructor(initialCommands = 128) {\n    this.drawCalls = new Uint32Array(initialCommands * ARGS_PER_COMMAND);\n  }\n\n  /** Growth keeps the contents, since the batcher grows the array mid-build */\n  public ensureCapacity(commandCount: number): Uint32Array {\n    const needed = commandCount * ARGS_PER_COMMAND;\n    if (this.drawCalls.length < needed) {\n      const grown = new Uint32Array(Math.ceil(commandCount * 1.5) * ARGS_PER_COMMAND);\n      grown.set(this.drawCalls);\n      this.drawCalls = grown;\n    }\n    return this.drawCalls;\n  }\n\n  public destroy(): void {\n    (this.drawCalls as Uint32Array | null) = null;\n  }\n}\n","import { BufferResource, BufferUsage } from 'pixi.js';\n\nimport type { Mesh3DData } from '../batcher/Mesh3DData';\nimport type { SortedMesh3DView } from '../batcher/SortedMesh3DView';\nimport { Buffer3D } from './Buffer3D';\n\n/** @internal */\nexport class RenderInstanceBuffer {\n  public readonly bufferResource: BufferResource;\n  private readonly _buffer: Buffer3D;\n\n  /** One mesh store index per instance, in draw order */\n  public data: Uint32Array;\n\n  constructor(label: string, initialInstances = 128) {\n    this.data = new Uint32Array(initialInstances);\n\n    this._buffer = new Buffer3D({\n      data: this.data,\n      usage: BufferUsage.STORAGE | BufferUsage.COPY_DST | BufferUsage.COPY_SRC,\n      label,\n      shrinkToFit: false,\n    });\n\n    this.bufferResource = new BufferResource({ buffer: this._buffer });\n  }\n\n  public get buffer(): Buffer3D {\n    return this._buffer;\n  }\n\n  /**\n   * Growth drops the contents, since `populateIds` rewrites every record and a draw list's edit copies\n   * the ones it keeps\n   */\n  public ensureSize(count: number): Uint32Array {\n    if (this.data.length < count) {\n      this.data = new Uint32Array(Math.ceil(count * 1.5));\n      this._buffer.data = this.data;\n    }\n    return this.data;\n  }\n\n  public populateIds(view: SortedMesh3DView<Mesh3DData>): void {\n    const count = view.count;\n    const data = this.ensureSize(count);\n    const sortedIndices = view.indices;\n    const items = view.items;\n\n    for (let i = 0; i < count; i++) {\n      data[i] = items[sortedIndices[i]]._storeIndex;\n    }\n  }\n\n  public upload(count: number, first = 0): void {\n    this._buffer.update((count - first) * 4, first * 4);\n  }\n\n  public unload(): void {\n    this._buffer?.unload();\n  }\n\n  public destroy(): void {\n    if (!this._buffer) return;\n\n    this.bufferResource.destroy(false);\n    this._buffer.destroy();\n\n    (this._buffer as Buffer3D | null) = null;\n    (this.bufferResource as BufferResource | null) = null;\n    (this.data as Uint32Array | null) = null;\n  }\n}\n","import { DrawCommandList } from '../batcher/DrawCommandList';\nimport type { Mesh3DData, MeshPassCache } from '../batcher/Mesh3DData';\nimport { SortedMesh3DView } from '../batcher/SortedMesh3DView';\nimport { pipelineState } from '../batcher/updateMesh3DKeys';\nimport { DrawArgs } from '../buffers/DrawArgs';\nimport { RenderInstanceBuffer } from '../buffers/RenderInstanceBuffer';\nimport type { RenderInstanceTexture } from '../buffers/RenderInstanceTexture';\n\ninterface DrawListOptions {\n  items: Mesh3DData[];\n  label: string;\n  bit: number;\n  initialCapacity?: number;\n}\n\ninterface GlData {\n  indexTexture: RenderInstanceTexture | null;\n  /** The records before culling, kept apart from `indexTexture` so every draw compacts from them afresh */\n  indexStaging: Uint32Array | null;\n  lastVisibilityDirtyId: number;\n}\n\ninterface GpuData {\n  /** The records before culling; each pass's `CullResult` writes its survivors elsewhere */\n  instanceBuffer: RenderInstanceBuffer;\n  /** Bumped when a bundle must re-record while the draw commands stay valid; each pass keeps its own watermark */\n  bundleDirtyId: number;\n}\n\n/** Scratch every list's {@link DrawList.applyEdits} shares, since no two edits run at once */\nlet editRecords = new Uint32Array(0);\nlet editCursors = new Uint32Array(0);\n\nconst NO_COMMAND = -1;\n\n/** `_rowCommand` holds `JOINING_BASE - k` for a row joining command `k`, so it isn't taken for one that stayed */\nconst JOINING_BASE = -2;\n\n/** Tail commands a list holds before it rebuilds; each is a live draw outside the bundle on indirect WebGPU */\nconst TAIL_COMMAND_CAP = 64;\n\n/** Scene updates a tail may stand with no new command before the list rebuilds it into the body */\nconst TAIL_QUIET_FRAMES = 60;\n\nfunction kindHash(batchKey: number, textureSetId: number): number {\n  const h =\n    Math.imul(batchKey >>> 0, 0x9e3779b1) ^\n    Math.imul((batchKey / 0x1_0000_0000) >>> 0, 0x85ebca6b) ^\n    Math.imul(textureSetId, 0xc2b2ae35);\n\n  return h ^ (h >>> 15);\n}\n\n/**\n * The meshes of one pass bit on one batch, the commands that draw them, and one record per mesh grouped by command\n *\n * Every pass on the bit shares it; what a camera's cull decides lives in each pass's `CullResult` on WebGPU.\n * @internal\n */\nexport class DrawList {\n  /** Between rebuilds only its members are current: `view.indices` keeps the last rebuild's order */\n  public view: SortedMesh3DView<Mesh3DData>;\n\n  /** Bumped when a change needs a rebuild rather than an {@link applyEdits} */\n  public drawDirtyId = 0;\n\n  public lastDrawDirtyId = -1;\n  public lastOrderDirtyId = -1;\n\n  /**\n   * Bumped when {@link applyEdits} moves the commands' ranges or adds a tail command; each `CullResult`\n   * re-copies its args on it\n   */\n  public rangesDirtyId = 0;\n\n  public readonly bit: number = 0;\n  public commandList = new DrawCommandList();\n\n  /** The draw args; WebGL's draws rewrite its instance counts in place, and each WebGPU `CullResult` culls a copy */\n  public drawData = new DrawArgs();\n\n  public gpuData: GpuData;\n  public glData: GlData;\n\n  /** The command drawing each store row, or `NO_COMMAND`; sized by the batch's store, not by every mesh ever met */\n  private _rowCommand: Int32Array = new Int32Array(0);\n\n  /** Members each command holds; the instance-count lane can't serve, since WebGL's draws rewrite it */\n  private _memberCounts = new Uint32Array(0);\n\n  /** 1 for each command a member left since the last {@link applyEdits} */\n  private _left = new Uint8Array(0);\n\n  /** Body commands with no member; the list rebuilds once they outnumber the rest */\n  private _deadCount = 0;\n\n  private _recordCount = 0;\n\n  /** Item indices of the members waiting for a command; indices, so a mesh destroyed meanwhile isn't kept */\n  private _joining = new Uint32Array(64);\n\n  private _joiningCount = 0;\n  private _firstEdited = Infinity;\n  private _readDirtyId = -1;\n\n  /** Set under `cache: 'never'`, whose list rebuilds every frame and takes no edits */\n  private _alwaysRebuilt = false;\n\n  /** The commands by kind: an open-addressed table of command index plus one, probed from `kindHash` */\n  private _kinds = new Int32Array(0);\n\n  /** Places of {@link _kinds} in use, or -1 when the table is stale */\n  private _kindsUsed = -1;\n\n  private _edited = false;\n  private _quietFrames = 0;\n  private _lastQuietTick = -1;\n  private _destroyed = false;\n\n  constructor(options: DrawListOptions) {\n    this.view = new SortedMesh3DView<Mesh3DData>(options.items, options.initialCapacity);\n    this.bit = options.bit;\n\n    this.glData = {\n      indexTexture: null,\n      indexStaging: null,\n      lastVisibilityDirtyId: -1,\n    };\n\n    this.gpuData = {\n      instanceBuffer: new RenderInstanceBuffer(options.label),\n      bundleDirtyId: 0,\n    };\n\n    this.commandList.onCaptureLost = () => {\n      this.drawDirtyId++;\n    };\n  }\n\n  public get records(): Uint32Array {\n    return this.glData.indexStaging ?? this.gpuData.instanceBuffer.data;\n  }\n\n  /** Whether the commands must rebuild; pure, so any phase may ask, and {@link claimDrawBuilt} claims */\n  public isDrawStale(): boolean {\n    return this.drawDirtyId !== this.lastDrawDirtyId || this._edited;\n  }\n\n  /**\n   * Whether a pass sorted by key must rebuild the list before it draws, sorting the view when it must\n   * @param updateTick - The view's `_updateTick`, so a standing tail counts each scene update once\n   * @param alwaysRebuild - Whether the pass rebuilds every frame (`cache: 'never'`)\n   */\n  public nextBuild(updateTick: number, alwaysRebuild = false): boolean {\n    this._alwaysRebuilt = alwaysRebuild;\n    if (!alwaysRebuild && !this.isDrawStale()) {\n      const commandList = this.commandList;\n      if (commandList.count === commandList.bodyCount || updateTick === this._lastQuietTick) return false;\n      this._lastQuietTick = updateTick;\n      if (++this._quietFrames < TAIL_QUIET_FRAMES) return false;\n      this.drawDirtyId++;\n    }\n\n    this._quietFrames = 0;\n    this._edited = false;\n    this.view.sort();\n    return true;\n  }\n\n  public isOrderStale(): boolean {\n    return this.view.orderDirtyId !== this.lastOrderDirtyId;\n  }\n\n  /** Claims the draw watermarks; call only where the build ran, after the sort it used */\n  public claimDrawBuilt(): void {\n    this.lastDrawDirtyId = this.drawDirtyId;\n    this.lastOrderDirtyId = this.view.orderDirtyId;\n  }\n\n  /** Claims the draw watermark for a list that built nothing because it has no members */\n  public claimDrawEmpty(): void {\n    this.lastDrawDirtyId = this.drawDirtyId;\n  }\n\n  /** Adds a mesh; {@link applyEdits} gives it a command */\n  public add(item: Mesh3DData, index: number): void {\n    const editable = this._editable();\n    this.view.add(item.uid, index, item._sortKey);\n    if (editable) this._queueJoin(index);\n    this._edited = true;\n  }\n\n  /** Removes a mesh; call while it still holds its store row */\n  public remove(item: Mesh3DData): void {\n    if (this._editable()) this._dropFromCommand(item._storeIndex);\n    this.view.remove(item.uid);\n    this._edited = true;\n  }\n\n  /** Takes a member whose kind may have changed out of its command, for {@link applyEdits} to place again */\n  public move(item: Mesh3DData): void {\n    if (this._editable() && this._dropFromCommand(item._storeIndex)) this._queueJoin(this.view.indexOf(item.uid));\n    this._edited = true;\n  }\n\n  /**\n   * Brings the commands up to the view's members without a rebuild, or bumps {@link drawDirtyId}\n   * when they can't take the edit; runs once a frame, at the end of the scene update\n   */\n  public applyEdits(): void {\n    if (!this._edited) return;\n    this._edited = false;\n    if (this.lastDrawDirtyId < 0) return;\n\n    if (!this._editable() || !this._repack()) {\n      this._joiningCount = 0;\n      this.drawDirtyId++;\n    }\n  }\n\n  /** Whether the commands can take an edit; ask before changing the view, so the records still match it */\n  private _editable(): boolean {\n    const commandList = this.commandList;\n    if (\n      this.drawDirtyId !== this.lastDrawDirtyId ||\n      commandList.count === 0 ||\n      this._alwaysRebuilt ||\n      this.view.orderForced\n    ) {\n      return false;\n    }\n    if (this._readDirtyId !== commandList.dirtyId) this._readBuild();\n    return true;\n  }\n\n  private _readBuild(): void {\n    const commandList = this.commandList;\n    const commandCount = commandList.count;\n    const drawCalls = this.drawData.drawCalls;\n    const records = this.records;\n    const total = this.view.count;\n\n    const capacity = commandCount + TAIL_COMMAND_CAP;\n    if (this._memberCounts.length < capacity) {\n      this._memberCounts = new Uint32Array(capacity * 2);\n      this._left = new Uint8Array(capacity * 2);\n    }\n    const counts = this._memberCounts;\n    this._left.fill(0);\n    let rowCommand = this._rowCommand.fill(NO_COMMAND);\n\n    for (let k = 0; k < commandCount; k++) {\n      const start = drawCalls[k * 5 + 4];\n      const end = k + 1 < commandCount ? drawCalls[(k + 1) * 5 + 4] : total;\n      counts[k] = end - start;\n      for (let i = start; i < end; i++) {\n        const row = records[i];\n        if (row >= rowCommand.length) rowCommand = this._growRows(row + 1);\n        rowCommand[row] = k;\n      }\n    }\n\n    this._recordCount = total;\n    this._deadCount = 0;\n    this._joiningCount = 0;\n    this._firstEdited = Infinity;\n    this._kindsUsed = -1;\n    this._readDirtyId = commandList.dirtyId;\n  }\n\n  /** Grows {@link _rowCommand}; it doubles, but past 256 rows never beyond what the batch's store can hold */\n  private _growRows(minLength: number): Int32Array {\n    const doubled = Math.min(this._rowCommand.length * 2, this.view.items.length + 1);\n    const grown = new Int32Array(Math.max(minLength, doubled, 256)).fill(NO_COMMAND);\n    grown.set(this._rowCommand);\n\n    return (this._rowCommand = grown);\n  }\n\n  private _queueJoin(index: number): void {\n    if (this._joiningCount === this._joining.length) {\n      if (this._joiningCount >= this.view.items.length) {\n        this._joiningCount = 0;\n        this.drawDirtyId++;\n        return;\n      }\n      const grown = new Uint32Array(this._joining.length * 2);\n      grown.set(this._joining);\n      this._joining = grown;\n    }\n    this._joining[this._joiningCount++] = index;\n  }\n\n  /**\n   * Drops a store row from its command; once dead body commands outnumber live ones the list\n   * rebuilds, since each costs a zero-instance draw in every bundle replay\n   * @returns Whether a command drew the row\n   */\n  private _dropFromCommand(row: number): boolean {\n    const rowCommand = this._rowCommand;\n    if (row < 0 || row >= rowCommand.length) return false;\n    const k = rowCommand[row];\n    if (k < 0) return false;\n\n    rowCommand[row] = NO_COMMAND;\n    this._left[k] = 1;\n    if (k < this._firstEdited) this._firstEdited = k;\n    if (--this._memberCounts[k] > 0) return true;\n\n    const commandList = this.commandList;\n    if (k >= commandList.bodyCount) commandList.releaseTail(commandList.commands[k]);\n    else if (++this._deadCount * 2 > commandList.bodyCount) this.drawDirtyId++;\n    return true;\n  }\n\n  /**\n   * Places the waiting members and lays the records out again; the body of {@link applyEdits}\n   * @returns `false` when the list must rebuild instead\n   */\n  private _repack(): boolean {\n    const view = this.view;\n    const items = view.items;\n    const bit = this.bit;\n    const joining = this._joining;\n    let rowCommand = this._rowCommand;\n    let first = this._firstEdited;\n    let joined = 0;\n\n    for (let p = 0; p < this._joiningCount; p++) {\n      const item = items[joining[p]] as Mesh3DData | null;\n      if (!item || (item._lastRenderPass & bit) === 0) continue;\n      const row = item._storeIndex;\n      if (row >= rowCommand.length) rowCommand = this._growRows(row + 1);\n      if (rowCommand[row] !== NO_COMMAND) continue;\n\n      const cache = item._passCache[bit];\n      if (!cache) return false;\n      let k = this._find(item, cache);\n      if (k < 0) {\n        k = this._record(item, cache);\n        if (k < 0) return false;\n      }\n      if (this._memberCounts[k]++ === 0 && k < this.commandList.bodyCount) this._deadCount--;\n      rowCommand[row] = JOINING_BASE - k;\n      joining[joined++] = row;\n      if (k < first) first = k;\n    }\n    this._joiningCount = 0;\n    this._firstEdited = Infinity;\n\n    const commandList = this.commandList;\n    const bodyCount = commandList.bodyCount;\n    const counts = this._memberCounts;\n    const builtCount = commandList.count;\n    while (commandList.count > bodyCount && counts[commandList.count - 1] === 0) commandList.count--;\n    const commandCount = commandList.count;\n    if (first === Infinity) return true;\n    if (first > commandCount) first = commandCount;\n\n    const count = view.count;\n    if (editRecords.length < count) editRecords = new Uint32Array(Math.ceil(count * 1.5));\n    if (editCursors.length < commandCount) editCursors = new Uint32Array(commandCount * 2);\n    const out = editRecords;\n    const cursors = editCursors;\n    const records = this.records;\n    const recordCount = this._recordCount;\n    const commands = commandList.commands;\n    const drawCalls = this.drawData.drawCalls;\n    const left = this._left;\n    const base = drawCalls[first * 5 + 4];\n    let at = base;\n    let revived = false;\n\n    for (let k = first; k < commandCount; k++) {\n      const command = commands[k];\n      const members = counts[k];\n      const start = drawCalls[k * 5 + 4];\n      const end = k + 1 < builtCount ? drawCalls[(k + 1) * 5 + 4] : recordCount;\n      drawCalls[k * 5 + 4] = at;\n      drawCalls[k * 5 + 1] = members;\n      if (left[k] === 0) {\n        for (let i = start; i < end; i++) out[at++] = records[i];\n      } else {\n        left[k] = 0;\n        for (let i = start; i < end; i++) {\n          const row = records[i];\n          if (rowCommand[row] >= 0) out[at++] = row;\n        }\n      }\n      cursors[k] = at;\n      at = drawCalls[k * 5 + 4] + members;\n      if (command.leftOut && members > 0 && k < bodyCount) {\n        revived = true;\n        command.leftOut = false;\n      }\n      command.dead = members === 0;\n    }\n    if (at !== count) return false;\n\n    for (let p = 0; p < joined; p++) {\n      const row = joining[p];\n      const k = JOINING_BASE - rowCommand[row];\n      rowCommand[row] = k;\n      out[cursors[k]++] = row;\n    }\n\n    const moved = out.subarray(base, count);\n    const glData = this.glData;\n    if (glData.indexStaging) {\n      const indexTexture = glData.indexTexture!;\n      indexTexture.ensureCapacity(count);\n      if (records.length < indexTexture.data.length) {\n        glData.indexStaging = new Uint32Array(indexTexture.data.length);\n        glData.indexStaging.set(records.subarray(0, base));\n      }\n      glData.indexStaging.set(moved, base);\n      glData.lastVisibilityDirtyId = -1;\n    } else {\n      if (count > base) {\n        const instanceBuffer = this.gpuData.instanceBuffer;\n        const grown = instanceBuffer.ensureSize(count);\n        if (grown !== records) grown.set(records.subarray(0, base));\n        grown.set(moved, base);\n        instanceBuffer.upload(count, grown !== records ? 0 : base);\n      }\n      if (revived) this.gpuData.bundleDirtyId++;\n    }\n\n    this._recordCount = count;\n    this.rangesDirtyId++;\n\n    return true;\n  }\n\n  /** The command that draws a member's kind, or -1 */\n  private _find(item: Mesh3DData, cache: MeshPassCache): number {\n    if (this._kindsUsed < 0) this._indexKinds();\n\n    const kinds = this._kinds;\n    const mask = kinds.length - 1;\n    const bound = this.commandList.commands[0].batchBindGroup ? item.material._textureSetId : 0;\n\n    for (let h = kindHash(cache.batchKey, bound) & mask; ; h = (h + 1) & mask) {\n      const entry = kinds[h];\n      if (entry === 0) return -1;\n      if (this._fits(entry - 1, item, cache)) return entry - 1;\n    }\n  }\n\n  /** Fills {@link _kinds} with every command, sized so at most half its places are in use */\n  private _indexKinds(): void {\n    const commandList = this.commandList;\n    const commandCount = commandList.count;\n    let size = 256;\n    while (size < (commandCount + TAIL_COMMAND_CAP) * 2) size *= 2;\n\n    if (this._kinds.length === size) this._kinds.fill(0);\n    else this._kinds = new Int32Array(size);\n\n    this._kindsUsed = 0;\n    for (let k = 0; k < commandCount; k++) this._indexKind(k);\n  }\n\n  /** Enters a command in {@link _kinds}; once half full it is refilled on the next {@link _find} */\n  private _indexKind(k: number): void {\n    const kinds = this._kinds;\n    const mask = kinds.length - 1;\n    const command = this.commandList.commands[k];\n    let h = kindHash(command.batchKey, command.textureSetId) & mask;\n    while (kinds[h] !== 0) h = (h + 1) & mask;\n    kinds[h] = k + 1;\n    if (++this._kindsUsed * 2 > kinds.length) this._kindsUsed = -1;\n  }\n\n  /**\n   * Whether command `k` draws `item`'s kind, compared exactly; an empty tail command has released its\n   * captures (`DrawCommandList.releaseTail`), and the atlas range keeps a mesh out of a command drawing\n   * the range its geometry left\n   */\n  private _fits(k: number, item: Mesh3DData, cache: MeshPassCache): boolean {\n    const commandList = this.commandList;\n    const command = commandList.commands[k];\n    if (cache.batchKey !== command.batchKey) return false;\n    if (k >= commandList.bodyCount && this._memberCounts[k] === 0) return false;\n\n    const alloc = item.geometry._geometryAtlasAllocation;\n    if (command.geometry !== (alloc ? alloc.atlas.geometry : item.geometry)) return false;\n    if (alloc) {\n      const drawCalls = this.drawData.drawCalls;\n      if (drawCalls[k * 5] !== alloc.indexCount || drawCalls[k * 5 + 2] !== alloc.firstIndex) return false;\n    }\n\n    const group = command.batchBindGroup;\n    if (!group) return true;\n\n    return command.merged\n      ? command.textureSetId === item.material._textureSetId\n      : group === item.material._getBindGroup();\n  }\n\n  /**\n   * Records a tail command for a kind no command draws; a list's commands all carry a material\n   * group or none do, as the batchers build them, so the first says which\n   * @returns The command's index, or -1 when the tail is full\n   */\n  private _record(item: Mesh3DData, cache: MeshPassCache): number {\n    const commandList = this.commandList;\n    const commands = commandList.commands;\n    let k = commandList.bodyCount;\n    while (k < commandList.count && this._memberCounts[k] > 0) k++;\n\n    if (k === commandList.count) {\n      if (k - commandList.bodyCount === TAIL_COMMAND_CAP) return -1;\n      commandList.next();\n      this._memberCounts[k] = 0;\n      this.drawData.ensureCapacity(k + 1)[k * 5 + 4] = this._recordCount;\n    }\n\n    const webgl = this.glData.indexStaging !== null;\n    const bindsMaterial = commands[0].batchBindGroup !== undefined;\n    const material = item.material;\n    const alloc = item.geometry._geometryAtlasAllocation;\n    const geometry = alloc ? alloc.atlas.geometry : item.geometry;\n    const command = commands[k];\n\n    commandList.captureTail(command, geometry, bindsMaterial ? material : null);\n    command.geometry = geometry;\n    command.shader = cache.shader;\n    command.globalBindGroup = commands[0].globalBindGroup;\n    command.batchBindGroup = bindsMaterial\n      ? webgl\n        ? material._getMergedBindGroup()\n        : material._getBindGroup()\n      : undefined;\n    command.state = pipelineState(cache.batchKey, cache.state);\n    command.topology = cache.topology;\n    command.batchKey = cache.batchKey;\n    command.textureSetId = bindsMaterial ? material._textureSetId : 0;\n    command.merged = bindsMaterial && webgl;\n    command.dead = false;\n    command.leftOut = false;\n\n    const drawCalls = this.drawData.drawCalls;\n    drawCalls[k * 5] = alloc ? alloc.indexCount : geometry.indexCount || geometry.indexBuffer.data.length;\n    drawCalls[k * 5 + 2] = alloc ? alloc.firstIndex : 0;\n    drawCalls[k * 5 + 3] = alloc && !webgl ? alloc.baseVertex : 0;\n\n    if (this._kindsUsed >= 0) this._indexKind(k);\n    this._quietFrames = 0;\n\n    return k;\n  }\n\n  /** Frees the GPU memory and the captures of the build, keeping the CPU state; the next frame rebuilds */\n  public unload(): void {\n    if (this._destroyed) return;\n\n    this.commandList.releaseCaptures();\n    this.drawDirtyId++;\n\n    this.gpuData.bundleDirtyId++;\n    this.gpuData.instanceBuffer.unload();\n    this.glData.indexTexture?.unload();\n  }\n\n  /** Releases what this list owns alone; the shaders, geometry and bind groups its commands use are shared */\n  public destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n\n    this.gpuData.instanceBuffer.destroy();\n\n    this.glData.indexTexture?.destroy();\n    this.glData.indexTexture = null;\n    this.glData.indexStaging = null;\n\n    (this.view as SortedMesh3DView<Mesh3DData> | null) = null;\n    this.commandList.destroy();\n    this.drawData.destroy();\n  }\n}\n","import type { Geometry3D } from '../../geometry/Geometry3D';\nimport type { BaseMaterial3D } from '../../materials/BaseMaterial3D';\nimport { Sphere } from '../../math/shapes/Sphere';\nimport type { BillboardMode } from '../../scene/Mesh3D';\nimport { MESH3D_SPHERE_STRIDE, MESH3D_STORE_STRIDE, transformBoundingSphere } from '../buffers/Mesh3DDataStoreBuffer';\nimport type { Mesh3DBatch } from './Mesh3DBatch';\nimport type { Mesh3DData, MeshPassCache } from './Mesh3DData';\n\nconst _sphereScratch = new Float32Array(MESH3D_SPHERE_STRIDE);\n\n/** @internal */\nexport class Mesh3DSlot implements Mesh3DData {\n  public uid = 0;\n  public _sortKey = 0;\n  public _storeIndex = 0;\n  public _batchDirty = true;\n  public _lastRenderPass = 0;\n  public _lastDescriptorDirtyId = -1;\n  public readonly skeleton = undefined;\n  public _passCache: Record<number, MeshPassCache> = {};\n  public geometry!: Geometry3D;\n  public material!: BaseMaterial3D;\n\n  public receiveShadow = true;\n  public billboardMode: BillboardMode = 'none';\n  public _worldVisible = 1;\n\n  private readonly _batch: Mesh3DBatch;\n  private _boundingSphere: Sphere | null = null;\n\n  constructor(uid: number, storeIndex: number, batch: Mesh3DBatch) {\n    this.uid = uid;\n    this._storeIndex = storeIndex;\n    this._batch = batch;\n  }\n\n  public get boundingSphere(): Sphere {\n    const sphere = (this._boundingSphere ||= new Sphere());\n    const store = this._batch.storeBuffer;\n    let spheres = store.boundingSpheres;\n    let o = this._storeIndex * MESH3D_SPHERE_STRIDE;\n    if (!store.writesSpheres || spheres === null) {\n      const geometry = this.geometry as Geometry3D | undefined;\n      if (geometry === undefined) return sphere.makeEmpty();\n      spheres = _sphereScratch;\n      o = 0;\n      transformBoundingSphere(spheres, 0, store.data, this._storeIndex * MESH3D_STORE_STRIDE, geometry, 0);\n    }\n    sphere.center.set(spheres[o], spheres[o + 1], spheres[o + 2]);\n    sphere.radius = spheres[o + 3];\n\n    return sphere;\n  }\n\n  public destroy(): void {\n    (this._batch as Mesh3DBatch | null) = null;\n  }\n}\n","import type { Geometry3D } from '../../geometry/Geometry3D';\nimport type { BaseMaterial3D } from '../../materials/BaseMaterial3D';\nimport { Matrix4 } from '../../math/matrix/Matrix4';\nimport type { CullMode } from '../../scene/View3D';\nimport { InstanceDataStoreBuffer } from '../buffers/InstanceDataStoreBuffer';\nimport { MESH3D_LANE_MATERIAL, MESH3D_STORE_STRIDE, Mesh3DDataStoreBuffer } from '../buffers/Mesh3DDataStoreBuffer';\nimport { DrawList } from '../render-passes/DrawList';\nimport { BatchInstanceData } from './BatchInstanceData';\nimport { BatchMatrices } from './BatchMatrices';\nimport type { InstanceDataOptions } from './instanceDataLayout';\nimport type { Mesh3DData } from './Mesh3DData';\nimport { Mesh3DSlot } from './Mesh3DSlot';\n\nlet _meshBatchUid = 0;\nconst _identityMatrix = new Matrix4();\n\ninterface BatchRenderData {\n  worldTransform: Matrix4;\n  _worldVisible: number;\n  label?: string | null;\n}\n\nconst SCENE_BATCH_RENDER_DATA: BatchRenderData = {\n  worldTransform: _identityMatrix,\n  _worldVisible: 1,\n};\n\ntype Mesh3DBatchSizeOrItems = { size: number; items?: never } | { items: Mesh3DData[]; size?: never };\n\ntype Mesh3DBatchOptions = Mesh3DBatchSizeOrItems & {\n  renderData?: BatchRenderData;\n  instanceData?: InstanceDataOptions;\n};\n\n/**\n * A set of meshes drawn together, with its own store and per-pass draw lists: the slots of a\n * {@link BatchedMesh3D}, or a view's scene meshes\n * @internal\n */\nexport class Mesh3DBatch {\n  public readonly uid = ++_meshBatchUid;\n  public readonly items: Mesh3DData[];\n  public readonly storeBuffer: Mesh3DDataStoreBuffer;\n  public readonly drawLists: Record<number, DrawList> = Object.create(null);\n\n  /** Rows share their index with `storeBuffer`'s; `null` without instance data */\n  public instanceStoreBuffer: InstanceDataStoreBuffer | null = null;\n\n  /** Row 0, allocated first, since the WebGPU shaders read the batch matrix from `uRenderableStorage[0]` */\n  private readonly _batchWorldMatrixIndex: number = 0;\n\n  public readonly renderData: BatchRenderData;\n\n  public readonly isUserBatch: boolean;\n\n  /** Slots waiting for a rebuild, listed once while `_batchDirty` is set; `null` for a scene batch */\n  public _dirtyIndices: Uint32Array | null = null;\n  public _dirtyCount = 0;\n\n  public _editsPending = false;\n\n  public destroyed = false;\n\n  /** Bumped when an item's visibility or `cull` changes; a draw without culling compacts only when it moves */\n  public _visibilityDirtyId = 0;\n\n  private _cull: CullMode = 'off';\n\n  public _lastStoreBufferVersion = 0;\n\n  private readonly _baseIndex: number = 0;\n  private _matrices: BatchMatrices | null = null;\n  private _instanceData: BatchInstanceData | null = null;\n\n  /** Writes every user slot visible, since the store's visibility starts at 0 and a compaction would drop them all */\n  constructor(options: Mesh3DBatchOptions) {\n    this.renderData = options.renderData ?? SCENE_BATCH_RENDER_DATA;\n    this.storeBuffer = new Mesh3DDataStoreBuffer();\n\n    const matrixSlotOwner = { _storeIndex: -1 };\n    this._batchWorldMatrixIndex = this.storeBuffer.allocateBlock(matrixSlotOwner, 1);\n\n    if (options.items !== undefined) {\n      this.items = options.items;\n      this._baseIndex = 0;\n      this.isUserBatch = false;\n    } else {\n      const size = options.size;\n      const blockOwner = { _storeIndex: -1 };\n      this._baseIndex = this.storeBuffer.allocateBlock(blockOwner, size);\n      const items: Mesh3DSlot[] = [];\n      const dirtyIndices = new Uint32Array(size);\n      for (let i = 0; i < size; i++) {\n        items.push(new Mesh3DSlot(i, this._baseIndex + i, this));\n        dirtyIndices[i] = i;\n      }\n      this.storeBuffer.writeVisibilityRange(this._baseIndex, size, 1);\n      this.items = items;\n      this._dirtyIndices = dirtyIndices;\n      this._dirtyCount = size;\n      this.isUserBatch = true;\n\n      if (options.instanceData) {\n        this.instanceStoreBuffer = new InstanceDataStoreBuffer(options.instanceData, this._baseIndex, size);\n      }\n    }\n\n    this.writeBatchWorldMatrix(_identityMatrix);\n  }\n\n  /** Writes the batch matrix row, copying the 16 floats as 8 f64s; a store row is 12 f64s wide */\n  public writeBatchWorldMatrix(matrix: Matrix4): void {\n    const idx = this._batchWorldMatrixIndex;\n    const fl64 = this.storeBuffer.fl64Data;\n    const wm64 = matrix.elements64;\n    const o = idx * 12;\n    fl64[o] = wm64[0];\n    fl64[o + 1] = wm64[1];\n    fl64[o + 2] = wm64[2];\n    fl64[o + 3] = wm64[3];\n    fl64[o + 4] = wm64[4];\n    fl64[o + 5] = wm64[5];\n    fl64[o + 6] = wm64[6];\n    fl64[o + 7] = wm64[7];\n    this.storeBuffer.markDirty(idx);\n  }\n\n  public setMatrixAt(index: number, matrix: Matrix4): void {\n    const storeIndex = this._baseIndex + index;\n    const fl64 = this.storeBuffer.fl64Data;\n    const wm64 = matrix.elements64;\n    const o = storeIndex * 12;\n    fl64[o] = wm64[0];\n    fl64[o + 1] = wm64[1];\n    fl64[o + 2] = wm64[2];\n    fl64[o + 3] = wm64[3];\n    fl64[o + 4] = wm64[4];\n    fl64[o + 5] = wm64[5];\n    fl64[o + 6] = wm64[6];\n    fl64[o + 7] = wm64[7];\n    this.storeBuffer.markDirty(storeIndex);\n\n    this._writeSlotSphere(index);\n  }\n\n  public _writeSlotSphere(index: number): void {\n    const store = this.storeBuffer;\n    if (!store.writesSpheres) return;\n    const geometry = this.items[index].geometry as Geometry3D | undefined;\n    if (geometry === undefined) return;\n    const storeIndex = this._baseIndex + index;\n    store.writeBoundingSphere(storeIndex, store.data, storeIndex * MESH3D_STORE_STRIDE, geometry, 0);\n  }\n\n  public get matrices(): BatchMatrices {\n    return (this._matrices ??= new BatchMatrices(this, this._baseIndex));\n  }\n\n  public get instanceData(): BatchInstanceData {\n    if (this._instanceData) return this._instanceData;\n\n    const store = this.instanceStoreBuffer;\n    if (!store) {\n      throw new Error('instanceData: this batch has no instance data. Declare the fields in the instanceData option.');\n    }\n\n    return (this._instanceData = new BatchInstanceData(store, this._baseIndex, this.items.length));\n  }\n\n  public setInstanceDataAt(index: number, name: string, x: number, y: number, z: number, w: number): void {\n    const store = this.instanceStoreBuffer;\n    const offset = store?.layout.offsets[name];\n    if (!store || offset === undefined) {\n      const declared = store ? `It declares: ${Object.keys(store.layout.offsets).join(', ')}.` : 'It declares none.';\n\n      throw new Error(`setInstanceDataAt: this batch has no instanceData field \"${name}\". ${declared}`);\n    }\n\n    const { layout } = store;\n    const storeIndex = this._baseIndex + index;\n    const o = storeIndex * layout.stride + offset;\n    const target = layout.struct[name] === 'vec4<f32>' ? store.data : store.u32Data;\n    target[o] = x;\n    target[o + 1] = y;\n    target[o + 2] = z;\n    target[o + 3] = w;\n    store.markDirty(storeIndex);\n  }\n\n  public setGeometryAt(index: number, geometry: Geometry3D): void {\n    const item = this.items[index] as Mesh3DSlot;\n    item.geometry = geometry;\n    this._writeSlotSphere(index);\n    if (!item._batchDirty) {\n      item._batchDirty = true;\n      this._dirtyIndices![this._dirtyCount++] = index;\n    }\n  }\n\n  public setMaterialAt(index: number, material: BaseMaterial3D): void {\n    const item = this.items[index] as Mesh3DSlot;\n    item.material = material;\n    item._lastDescriptorDirtyId = -1;\n    if (!item._batchDirty) {\n      item._batchDirty = true;\n      this._dirtyIndices![this._dirtyCount++] = index;\n    }\n\n    if (material._materialIndex !== -1) {\n      const storeIndex = this._baseIndex + index;\n      this.storeBuffer.u32Data[storeIndex * MESH3D_STORE_STRIDE + MESH3D_LANE_MATERIAL] = material._materialIndex;\n      this.storeBuffer.markDirty(storeIndex);\n    }\n  }\n\n  public invalidate(index: number): void {\n    const item = this.items[index] as Mesh3DSlot;\n    if (!item._batchDirty) {\n      item._batchDirty = true;\n      if (this._dirtyIndices) {\n        this._dirtyIndices[this._dirtyCount++] = index;\n      }\n    }\n  }\n\n  public setVisibleAt(index: number, visible: boolean): void {\n    const item = this.items[index] as Mesh3DSlot;\n    const value = visible ? 1 : 0;\n    if (item._worldVisible === value) return;\n    item._worldVisible = value;\n    this.storeBuffer.writeVisibility(this._baseIndex + index, value);\n    this._visibilityDirtyId++;\n  }\n\n  public getVisibleAt(index: number): boolean {\n    return this.items[index]._worldVisible === 1;\n  }\n\n  /**\n   * Sets which passes draw a slot\n   *\n   * A pass's captures go when its last slot leaves, since an empty pass never rebuilds. A joining slot\n   * is marked dirty, since the batchers read its pass cache without checking it exists.\n   */\n  public setPassesAt(index: number, passMask: number): void {\n    const item = this.items[index] as Mesh3DSlot;\n    const prev = item._lastRenderPass;\n    const added = passMask & ~prev;\n    const removed = prev & ~passMask;\n\n    let bits = removed;\n    while (bits) {\n      const bit = bits & -bits;\n      const pd = this.drawLists[bit];\n      pd.remove(item);\n      if (pd.view.count === 0) {\n        pd.drawDirtyId++;\n        pd.commandList.releaseCaptures();\n      }\n      bits ^= bit;\n    }\n\n    bits = added;\n    while (bits) {\n      const bit = bits & -bits;\n      let pd = this.drawLists[bit];\n      if (!pd)\n        pd = this.drawLists[bit] = new DrawList({\n          items: this.items,\n          label: `pass_${bit}`,\n          bit,\n        });\n      pd.add(item, index);\n      bits ^= bit;\n    }\n\n    item._lastRenderPass = passMask;\n    if (added | removed) this._editsPending = true;\n\n    if (added && !item._batchDirty) {\n      item._batchDirty = true;\n      if (this._dirtyIndices) this._dirtyIndices[this._dirtyCount++] = index;\n    }\n  }\n\n  public get cull(): CullMode {\n    return this._cull;\n  }\n\n  /** Sets the culling mode; a change turns the store's sphere writes off until a CPU cull asks again */\n  public set cull(value: CullMode) {\n    if (value === this._cull) return;\n    this._cull = value;\n    this._visibilityDirtyId++;\n    if (this.storeBuffer.writesSpheres) this.storeBuffer.enableSphereWrites(false);\n  }\n\n  /** Turns sphere writes on and sweeps every row when a CPU cull first asks; a batch never CPU-culled pays nothing */\n  public _ensureSpheres(): void {\n    const store = this.storeBuffer;\n    if (store.writesSpheres) return;\n    store.enableSphereWrites(true);\n    this._sweepSpheres();\n  }\n\n  /** Grows a row's sphere by the morph reach only when its item has a morph, as `Mesh3D.boundingSphere` does */\n  private _sweepSpheres(): void {\n    if (this.destroyed) return;\n    const store = this.storeBuffer;\n    const data = store.data;\n    const items = this.items;\n    for (let i = 0; i < items.length; i++) {\n      const item = items[i] as Mesh3DData | null;\n      if (item === null) continue;\n      const row = item._storeIndex;\n      const geometry = item.geometry as Geometry3D | undefined;\n      if (row < 0 || geometry === undefined) continue;\n      store.writeBoundingSphere(\n        row,\n        data,\n        row * MESH3D_STORE_STRIDE,\n        geometry,\n        item._morph ? geometry._morphBoundsExpansion : 0,\n      );\n    }\n  }\n\n  /**\n   * Applies every draw list's membership edits, once, at the end of the scene update, when every\n   * joining item has its keys and pass cache to match a command by\n   */\n  public applyEdits(): void {\n    if (!this._editsPending) return;\n    this._editsPending = false;\n    for (const bit in this.drawLists) this.drawLists[bit].applyEdits();\n  }\n\n  public invalidateDrawCaches(): void {\n    for (const bit in this.drawLists) this.drawLists[bit].drawDirtyId++;\n  }\n\n  public invalidateBundleCaches(): void {\n    for (const bit in this.drawLists) this.drawLists[bit].gpuData.bundleDirtyId++;\n  }\n\n  public unload(): void {\n    if (this.destroyed) return;\n\n    this.storeBuffer.unload();\n    this.instanceStoreBuffer?.unload();\n    for (const bit in this.drawLists) this.drawLists[bit].unload();\n  }\n\n  /** Destroys no geometry, material or scene mesh: the view owns the scene batch's meshes */\n  public destroy(): void {\n    if (this.destroyed) return;\n    this.destroyed = true;\n\n    this.storeBuffer.destroy();\n    this.instanceStoreBuffer?.destroy();\n    this.instanceStoreBuffer = null;\n\n    for (const bit in this.drawLists) this.drawLists[bit].destroy();\n    (this.drawLists as Record<number, DrawList> | null) = null;\n\n    if (this.isUserBatch) {\n      for (const item of this.items) (item as Mesh3DSlot).destroy();\n    }\n\n    this._dirtyIndices = null;\n    this._matrices?.destroy();\n    this._matrices = null;\n    this._instanceData?.destroy();\n    this._instanceData = null;\n  }\n}\n","import type { BindGroup } from 'pixi.js';\n\nimport type { View3D } from '../../scene/View3D';\nimport type { DrawArgs } from '../buffers/DrawArgs';\nimport type { MaterialSystemGpu } from '../gpu/shader/MaterialSystemGpu';\nimport { MERGE_THRESHOLD } from './batchConstants';\nimport type { DrawCommandList } from './DrawCommandList';\nimport type { Mesh3DBatch } from './Mesh3DBatch';\nimport type { Mesh3DData } from './Mesh3DData';\nimport type { SortedMesh3DView } from './SortedMesh3DView';\nimport { pipelineState } from './updateMesh3DKeys';\n\ninterface BatcherRenderOptions {\n  renderables: SortedMesh3DView<Mesh3DData>;\n  globalBindGroup: BindGroup;\n  commandList: DrawCommandList;\n  drawData: DrawArgs;\n  passBit: number;\n  bindsMaterial: boolean;\n  batch: Mesh3DBatch;\n  view3d: View3D;\n}\n\n/**\n * Stands in for an unatlased geometry's allocation, so the walk reads one shape without a branch; a\n * real allocation's index count of 0 is kept, so an empty atlased geometry draws nothing\n */\nconst noAlloc = {\n  atlas: null,\n  indexCount: undefined,\n  firstIndex: undefined,\n  baseVertex: undefined,\n};\n\n/**\n * Turns a pass's sorted renderables into instanced WebGPU draw commands, one run at a time\n *\n * A run is a stretch of rows with one batch key and one texture set. In a pass that binds materials it\n * records a command per change of material, and draws merged once it needs more than `MERGE_THRESHOLD`.\n * @internal\n */\nexport class Mesh3DBatcher {\n  private readonly _materialSystem: MaterialSystemGpu;\n\n  constructor(materialSystem: MaterialSystemGpu) {\n    this._materialSystem = materialSystem;\n  }\n\n  /**\n   * Rebuilds `commandList` from the sorted renderables\n   *\n   * Each later material of a direct run refreshes its own bind group, since the capture at a run's\n   * start refreshes only the first material's.\n   */\n  public render(options: BatcherRenderOptions): void {\n    const { renderables, globalBindGroup, commandList, drawData, passBit, bindsMaterial, batch, view3d } = options;\n    const len = renderables.count;\n    if (len === 0) return;\n\n    commandList.clear();\n\n    const indices = renderables.indices;\n    const items = renderables.items;\n    const materialSystem = this._materialSystem;\n\n    let r = items[indices[0]];\n    let cache = r._passCache[passBit];\n    let currentAlloc = r.geometry._geometryAtlasAllocation || noAlloc;\n    let currentBatchKey = cache.batchKey;\n    let currentGeometry = currentAlloc.atlas ? currentAlloc.atlas.geometry : r.geometry;\n    let currentShader = cache.shader;\n    let currentState = pipelineState(currentBatchKey, cache.state);\n    let currentTopology = cache.topology;\n    let currentMaterial = r.material;\n\n    let batchStart = 0;\n    let runStart = 0;\n    let runCommandStart = 0;\n    let runFirstMaterial = currentMaterial;\n    let merged = false;\n\n    if (bindsMaterial) commandList.captureMaterialTextures(currentMaterial);\n\n    for (let i = 1; i < len; i++) {\n      r = items[indices[i]];\n      cache = r._passCache[passBit];\n\n      const rBatchKey = cache.batchKey;\n      const m = r.material;\n      const keyChanged = rBatchKey !== currentBatchKey;\n\n      if (!keyChanged && (!bindsMaterial || m === currentMaterial)) continue;\n\n      const sameRun = !keyChanged && currentMaterial._textureSetId === m._textureSetId;\n      if (sameRun) {\n        if (merged) {\n          currentMaterial = m;\n          continue;\n        }\n        const commandsWithNewMaterial = commandList.count - runCommandStart + 2;\n        if (commandsWithNewMaterial > MERGE_THRESHOLD) {\n          commandList.count = runCommandStart;\n          batchStart = runStart;\n          merged = true;\n          currentShader = materialSystem.ensureMergedShader(items[indices[runStart]], batch, view3d);\n          currentMaterial = m;\n          continue;\n        }\n      }\n\n      const cmd = commandList.next();\n      cmd.geometry = currentGeometry;\n      cmd.shader = currentShader;\n      cmd.globalBindGroup = globalBindGroup;\n      cmd.batchBindGroup = bindsMaterial\n        ? merged\n          ? runFirstMaterial._getMergedBindGroup()\n          : currentMaterial._getBindGroup()\n        : undefined;\n      cmd.state = currentState;\n      cmd.topology = currentTopology;\n      cmd.batchKey = currentBatchKey;\n      cmd.textureSetId = bindsMaterial ? runFirstMaterial._textureSetId : 0;\n      cmd.merged = bindsMaterial && merged;\n      commandList.captureGeometry(currentGeometry);\n      const offset = (commandList.count - 1) * 5;\n      const drawCalls = drawData.ensureCapacity(commandList.count);\n      drawCalls[offset] =\n        currentAlloc.indexCount ?? (currentGeometry.indexCount || currentGeometry.indexBuffer.data.length);\n      drawCalls[offset + 1] = i - batchStart;\n      drawCalls[offset + 2] = currentAlloc.firstIndex || 0;\n      drawCalls[offset + 3] = currentAlloc.baseVertex || 0;\n      drawCalls[offset + 4] = batchStart;\n\n      batchStart = i;\n      const materialChanged = m !== currentMaterial;\n      currentMaterial = m;\n\n      if (!sameRun) {\n        if (keyChanged) {\n          currentAlloc = r.geometry._geometryAtlasAllocation || noAlloc;\n          currentBatchKey = rBatchKey;\n          currentGeometry = currentAlloc.atlas ? currentAlloc.atlas.geometry : r.geometry;\n          currentState = pipelineState(rBatchKey, cache.state);\n          currentTopology = cache.topology;\n        }\n        currentShader = cache.shader;\n        runStart = i;\n        runCommandStart = commandList.count;\n        runFirstMaterial = m;\n        merged = false;\n      }\n\n      if (bindsMaterial && materialChanged) {\n        if (sameRun) commandList.refreshMaterialBindings(m);\n        else commandList.captureMaterialTextures(m);\n      }\n    }\n\n    {\n      const cmd = commandList.next();\n      cmd.geometry = currentGeometry;\n      cmd.shader = currentShader;\n      cmd.globalBindGroup = globalBindGroup;\n      cmd.batchBindGroup = bindsMaterial\n        ? merged\n          ? runFirstMaterial._getMergedBindGroup()\n          : currentMaterial._getBindGroup()\n        : undefined;\n      cmd.state = currentState;\n      cmd.topology = currentTopology;\n      cmd.batchKey = currentBatchKey;\n      cmd.textureSetId = bindsMaterial ? runFirstMaterial._textureSetId : 0;\n      cmd.merged = bindsMaterial && merged;\n      commandList.captureGeometry(currentGeometry);\n      const offset = (commandList.count - 1) * 5;\n      const drawCalls = drawData.ensureCapacity(commandList.count);\n      drawCalls[offset] =\n        currentAlloc.indexCount ?? (currentGeometry.indexCount || currentGeometry.indexBuffer.data.length);\n      drawCalls[offset + 1] = len - batchStart;\n      drawCalls[offset + 2] = currentAlloc.firstIndex || 0;\n      drawCalls[offset + 3] = currentAlloc.baseVertex || 0;\n      drawCalls[offset + 4] = batchStart;\n    }\n\n    commandList.endBuild();\n  }\n}\n","import { BufferImageSource, BufferResource, BufferUsage, Texture } from 'pixi.js';\n\nimport type { Skeleton } from '../../scene/Skeleton';\nimport { Buffer3D } from './Buffer3D';\nimport { alignToDataTextureRows, dataTextureSize, uploadFloatRange } from './dataTextureLayout';\n\n/**\n * Floats per bone matrix: the three rows {@link Matrix4.multiplyAffineTo3x4} writes, since the fourth\n * is always `(0, 0, 0, 1)`\n * @internal\n */\nexport const BONE_MATRIX_FLOATS = 12;\n\ninterface BonePitOptions {\n  initialBoneCapacity?: number;\n}\n\n/**\n * Call `clear`, then `add` for each skeleton drawn, then `update` once, every frame\n * @internal\n */\nexport class BonePit {\n  public data: Float32Array;\n\n  private _buffer: Buffer3D | null = null;\n  private _bufferResource: BufferResource | null = null;\n\n  private _boneCount = 0;\n  private _tick = 0;\n\n  /** Bumped when growth replaces the buffer, so whatever bound the old one must bind again */\n  public bufferVersion = 0;\n\n  private _texture: Texture | null = null;\n  private _textureSource: BufferImageSource | null = null;\n\n  private readonly _retiredBuffers: Buffer3D[] = [];\n\n  /**\n   * The `Skeleton._worldId` each `add` slot last copied. A match skips the copy only while no earlier\n   * slot changed, and `update` trims it to the frame's adds, since later slots may lie under moved bones\n   */\n  private readonly _slotWorldIds: number[] = [];\n  private _addCount = 0;\n  private _changed = false;\n\n  constructor(options: BonePitOptions = {}) {\n    const initialBones = options.initialBoneCapacity ?? 256;\n    this.data = new Float32Array(alignToDataTextureRows(initialBones * BONE_MATRIX_FLOATS));\n  }\n\n  public get buffer(): Buffer3D {\n    return (this._buffer ??= new Buffer3D({\n      data: this.data,\n      usage: BufferUsage.STORAGE | BufferUsage.COPY_DST | BufferUsage.COPY_SRC,\n      label: 'BonePit',\n      shrinkToFit: false,\n    }));\n  }\n\n  public get bufferResource(): BufferResource {\n    return (this._bufferResource ??= new BufferResource({ buffer: this.buffer }));\n  }\n\n  public get texture(): Texture {\n    return this._texture || this._initTexture();\n  }\n\n  private _initTexture(): Texture {\n    const { width, height } = dataTextureSize(this.data.length);\n\n    this._textureSource = new BufferImageSource({\n      resource: this.data,\n      width,\n      height,\n      format: 'rgba32float',\n      scaleMode: 'nearest',\n      alphaMode: 'no-premultiply-alpha',\n    });\n\n    this._texture = new Texture({ source: this._textureSource });\n    return this._texture;\n  }\n\n  public clear(): void {\n    this._boneCount = 0;\n    this._addCount = 0;\n    this._tick++;\n  }\n\n  public add(skeleton: Skeleton): number {\n    if (skeleton._bonePitTick === this._tick) {\n      return skeleton._bonePitIndex;\n    }\n\n    skeleton._bonePitTick = this._tick;\n\n    const baseIndex = this._boneCount;\n    const slot = this._addCount++;\n\n    this._boneCount += skeleton.jointCount;\n    skeleton._bonePitIndex = baseIndex;\n\n    if (!this._changed && this._slotWorldIds[slot] === skeleton._worldId) return baseIndex;\n\n    this._changed = true;\n    this._slotWorldIds[slot] = skeleton._worldId;\n    this._ensureCapacity(this._boneCount);\n    this.data.set(skeleton.worldMatrix, baseIndex * BONE_MATRIX_FLOATS);\n\n    return baseIndex;\n  }\n\n  public update(): void {\n    if (this._slotWorldIds.length !== this._addCount) this._slotWorldIds.length = this._addCount;\n    if (!this._changed) return;\n\n    this._changed = false;\n    if (this._boneCount === 0) return;\n\n    const floats = this._boneCount * BONE_MATRIX_FLOATS;\n\n    this._buffer?.update(floats * 4, 0);\n    if (this._textureSource) uploadFloatRange(this._textureSource, 0, floats);\n  }\n\n  /** Retires the buffer rather than destroying it, since draws recorded earlier still bind it; `_freeRetired` frees it */\n  private _ensureCapacity(requiredBoneCount: number): void {\n    const requiredFloats = requiredBoneCount * BONE_MATRIX_FLOATS;\n    if (requiredFloats <= this.data.length) return;\n\n    let newFloatCapacity = this.data.length;\n    while (newFloatCapacity < requiredFloats) newFloatCapacity *= 2;\n    newFloatCapacity = alignToDataTextureRows(newFloatCapacity);\n\n    const newData = new Float32Array(newFloatCapacity);\n    newData.set(this.data);\n    this.data = newData;\n\n    if (this._buffer) {\n      this._retiredBuffers.push(this._buffer);\n      this._buffer = null;\n      this._bufferResource = null;\n    }\n    this.bufferVersion++;\n\n    if (this._textureSource) {\n      const { width, height } = dataTextureSize(this.data.length);\n\n      this._textureSource.resource = this.data;\n\n      if (this._textureSource.width !== width || this._textureSource.height !== height) {\n        this._textureSource.resize(width, height);\n      }\n      this._textureSource.update();\n    }\n  }\n\n  private _freeRetired(): void {\n    for (let i = 0; i < this._retiredBuffers.length; i++) this._retiredBuffers[i].destroy();\n    this._retiredBuffers.length = 0;\n  }\n\n  public unload(): void {\n    if (!this.data) return;\n\n    this._buffer?.unload();\n    this._textureSource?.unload();\n    this._freeRetired();\n  }\n\n  public destroy(): void {\n    if (!this.data) return;\n\n    this._bufferResource?.destroy(false);\n    this._buffer?.destroy();\n\n    this._freeRetired();\n\n    this._texture?.destroy(true);\n\n    (this.data as Float32Array | null) = null;\n    (this._slotWorldIds as number[] | null) = null;\n    this._buffer = null;\n    this._bufferResource = null;\n\n    this._texture = null;\n    this._textureSource = null;\n  }\n}\n","import { BufferUsage, BufferResource } from 'pixi.js';\n\nimport { Buffer3D } from './Buffer3D';\n\n/** @internal */\nexport const EMPTY_BUFFER_RESOURCE = new BufferResource({\n  buffer: new Buffer3D({\n    data: new Int32Array(1),\n    usage: BufferUsage.STORAGE | BufferUsage.COPY_DST | BufferUsage.COPY_SRC,\n    label: 'EmptyBufferResource',\n    shrinkToFit: false,\n  }),\n});\n","import type { Geometry3D } from '../../geometry/Geometry3D';\nimport { DataStoreBuffer } from './DataStoreBuffer';\n\n/**\n * Floats per geometry row; must match the WGSL `GeometryData` struct\n * @internal\n */\nexport const GEOMETRY_DATA_STRIDE = 8;\n\n/**\n * Writes 0 targets for a geometry whose deltas went with a destroyed renderer, so it draws unmorphed\n * rather than reading a stale offset\n */\nconst copyGeometryData = (\n  geometry: Geometry3D,\n  buffer: Float32Array,\n  u32Buffer: Uint32Array,\n  _fl64Buffer: Float64Array,\n  offset: number,\n) => {\n  const { center, radius } = geometry.boundsSphere;\n\n  buffer[offset] = center.x;\n  buffer[offset + 1] = center.y;\n  buffer[offset + 2] = center.z;\n  buffer[offset + 3] = geometry.dynamic ? -1 : radius + geometry._morphBoundsExpansion;\n\n  if (geometry.morphTargetCount > 0) {\n    const packed = geometry._morphDeltaBase >= 0;\n    u32Buffer[offset + 4] = packed ? geometry._morphDeltaBase : 0;\n    u32Buffer[offset + 5] = packed ? geometry.morphTargetCount : 0;\n    u32Buffer[offset + 6] = packed ? geometry._geometryAtlasAllocation?.baseVertex || 0 : 0;\n  }\n};\n\n/**\n * `Geometry3D.destroy` frees a geometry's row through its `_geometryDataStore`\n * @internal\n */\nexport class GeometryDataStoreBuffer extends DataStoreBuffer<Geometry3D> {\n  constructor(initialSize = 100) {\n    super({\n      stride: GEOMETRY_DATA_STRIDE,\n      indexKey: '_geometryDataIndex',\n      copier: copyGeometryData,\n      initialSize,\n    });\n  }\n\n  /**\n   * Never adopts another store's row, whose index may name a row here, but frees it there and takes a\n   * new one, so two live renderers drawing one geometry swap its row every frame\n   */\n  public override set(geometry: Geometry3D): number {\n    const old = geometry._geometryDataStore;\n    if (old !== this) {\n      old?.remove(geometry);\n      geometry._geometryDataStore = this;\n    }\n    return super.set(geometry);\n  }\n}\n","import { BufferUsage } from 'pixi.js';\n\nimport { Buffer3D } from './Buffer3D';\nimport { ARGS_PER_COMMAND, DrawArgs } from './DrawArgs';\n\n/** @internal */\nexport class IndirectDrawData extends DrawArgs {\n  public drawCallsBuffer: Buffer3D;\n\n  constructor(label = 'DrawCalls', initialCommands = 128) {\n    super(initialCommands);\n\n    this.drawCallsBuffer = new Buffer3D({\n      data: this.drawCalls,\n      usage: BufferUsage.INDIRECT | BufferUsage.STORAGE | BufferUsage.COPY_DST | BufferUsage.COPY_SRC,\n      label,\n      shrinkToFit: false,\n    });\n  }\n\n  /** Growth gives pixi a new `GPUBuffer`, and `CullResult.sync` drops the bundle that baked the old one */\n  public override ensureCapacity(commandCount: number): Uint32Array {\n    const before = this.drawCalls;\n    const after = super.ensureCapacity(commandCount);\n    if (after !== before) this.drawCallsBuffer.data = after;\n    return after;\n  }\n\n  public upload(commandCount: number): void {\n    this.drawCallsBuffer.update(commandCount * ARGS_PER_COMMAND * 4);\n  }\n\n  /** Copies all five lanes, not just the counts, since the indirect draw reads its offsets from here too */\n  public copyCommandsFrom(source: DrawArgs, commandCount: number): void {\n    const dst = this.ensureCapacity(commandCount);\n    dst.set(source.drawCalls.subarray(0, commandCount * ARGS_PER_COMMAND));\n    this.upload(commandCount);\n  }\n\n  public unload(): void {\n    this.drawCallsBuffer?.unload();\n  }\n\n  public override destroy(): void {\n    if (!this.drawCallsBuffer) return;\n\n    this.drawCallsBuffer.destroy();\n    (this.drawCallsBuffer as Buffer3D | null) = null;\n\n    super.destroy();\n  }\n}\n","import { BufferResource } from 'pixi.js';\n\n/**\n * Drops the buffer listener every material would add, which each destroy would walk the whole list\n * to remove; `MaterialDataStoreBuffer.uniformResource` replaces the resource when the buffer goes\n * @internal\n */\nexport class MaterialRowResource extends BufferResource {\n  constructor(options: ConstructorParameters<typeof BufferResource>[0]) {\n    super(options);\n    // oxlint-disable-next-line typescript/unbound-method -- the emitter matches a listener by function and context, and this passes both\n    this.buffer.off('change', this.onBufferChange, this);\n  }\n}\n","import { BufferUsage, RendererType, Texture } from 'pixi.js';\nimport type { BufferImageSource, BufferResource } from 'pixi.js';\n\nimport type { BaseMaterial3D, MaterialUploadQueue } from '../../materials/BaseMaterial3D';\nimport { Buffer3D } from './Buffer3D';\nimport {\n  alignToDataTextureRows,\n  createDataTextureSource,\n  uploadFloatRange,\n  WORDS_PER_TEXEL,\n} from './dataTextureLayout';\nimport { BUFFER_CALL_BYTES, BUFFER_SPAN_FLOOR_BYTES, TEXTURE_CALL_BYTES } from './DirtySlots';\nimport { MaterialRowResource } from './MaterialRowResource';\n\nconst INITIAL_TEXELS = 1024;\nconst BYTES_PER_TEXEL = WORDS_PER_TEXEL * 4;\n\nfunction leastCommonMultiple(a: number, b: number): number {\n  let x = a;\n  let y = b;\n  while (y) [x, y] = [y, x % y];\n\n  return (a / x) * b;\n}\n\ninterface MaterialDataStoreBufferOptions {\n  alignment: number;\n  rendererType: RendererType;\n}\n\n/**\n * Places start on the device's uniform offset alignment rather than the next texel, since a direct\n * draw binds its material's place as a uniform range\n * @internal\n */\nexport class MaterialDataStoreBuffer implements MaterialUploadQueue {\n  public data: Float32Array;\n  private readonly _retiredTextures: Texture[] = [];\n\n  /** Growth replaces it, so read it each frame rather than holding it */\n  public texture: Texture<BufferImageSource>;\n\n  /** The uniform view, `null` until a {@link uniformResource} call and again after growth retires it */\n  private _buffer: Buffer3D | null = null;\n\n  private readonly _retiredBuffers: Buffer3D[] = [];\n  private readonly _alignment: number = 0;\n  private readonly _texelsPerUnit: number = 0;\n  private _end = 0;\n  private readonly _freePlaces = new Map<number, number[]>();\n\n  /** Live in the first `_dirtyCount` entries; the drain nulls each, so a queued material can be collected */\n  private readonly _dirtyQueue: (BaseMaterial3D | null)[] = [];\n  private _dirtyCount = 0;\n  private _ranges = new Uint32Array(64);\n\n  /** Bumped when growth replaces the GPU views, so whatever bound the old ones must bind again */\n  public bufferVersion = 0;\n\n  /** Per-call fee for uniform writes; `Infinity` on WebGL, where pixi uploads only the last range set before a bind */\n  private readonly _bufferCallBytes: number = 0;\n\n  constructor(options: MaterialDataStoreBufferOptions) {\n    const { alignment, rendererType } = options;\n    if (!(alignment > 0)) {\n      throw new Error(\n        `MaterialDataStoreBuffer: renderer.limits.minUniformBufferOffsetAlignment is ${alignment}; ` +\n          'the limits system fills it in after the renderer has a context',\n      );\n    }\n\n    this._alignment = leastCommonMultiple(alignment, BYTES_PER_TEXEL);\n    this._texelsPerUnit = this._alignment / BYTES_PER_TEXEL;\n    this._bufferCallBytes = rendererType === RendererType.WEBGPU ? BUFFER_CALL_BYTES : Infinity;\n    this.data = new Float32Array(alignToDataTextureRows(INITIAL_TEXELS * WORDS_PER_TEXEL));\n    this.texture = new Texture({ source: createDataTextureSource(this.data) });\n  }\n\n  /**\n   * Does nothing once the store is destroyed, so a late `material.update()` can't leave the material\n   * flagged as queued on a store that never drains\n   */\n  public enqueueDirty(material: BaseMaterial3D): void {\n    if (!this.data || material._storeQueued) return;\n    material._storeQueued = true;\n    this._dirtyQueue[this._dirtyCount++] = material;\n  }\n\n  /**\n   * Places the material at once, since callers write its index into mesh rows in the same walk;\n   * another store's place is handed back, as in `GeometryDataStoreBuffer.set`\n   */\n  public register(material: BaseMaterial3D): void {\n    const old = material._uploadQueue;\n    if (old === this && material._materialIndex !== -1) return;\n\n    if (old && old !== this) old.remove(material);\n    material._uploadQueue = this;\n    material._storeQueued = false;\n    this._allocate(material);\n    this.enqueueDirty(material);\n  }\n\n  /**\n   * Reads the material's data for the place's length, so call it before the data is dropped; once the\n   * store is destroyed it only resets the index\n   */\n  public remove(material: BaseMaterial3D): void {\n    const index = material._materialIndex;\n    if (index < 0) return;\n\n    material._materialIndex = -1;\n\n    if (!this.data) return;\n\n    const units = this._units(material);\n    let free = this._freePlaces.get(units);\n    if (!free) this._freePlaces.set(units, (free = []));\n    free.push(index);\n  }\n\n  /** Cached on the material, and replaced once growth or a re-registration moves its place */\n  public uniformResource(material: BaseMaterial3D): BufferResource {\n    const buffer = (this._buffer ??= new Buffer3D({\n      data: this.data,\n      usage: BufferUsage.UNIFORM | BufferUsage.COPY_DST,\n      label: 'MaterialStore',\n    }));\n    const offset = material._materialIndex * BYTES_PER_TEXEL;\n\n    let resource = material._uniformResource;\n    if (resource && resource.buffer === buffer && resource.offset === offset) return resource;\n\n    resource?.destroy(false);\n    resource = material._uniformResource = new MaterialRowResource({\n      buffer,\n      offset,\n      size: this._units(material) * this._alignment,\n    });\n\n    return resource;\n  }\n\n  /**\n   * Resets the count before the drain, so a throw can't leave it counting nulled entries; skips a\n   * material whose `_uploadQueue` is no longer this store\n   */\n  public update(): void {\n    const queue = this._dirtyQueue;\n    const count = this._dirtyCount;\n    if (count === 0) return;\n\n    this._dirtyCount = 0;\n\n    const data = this.data;\n    let rangeCount = 0;\n    let floats = 0;\n    let min = Infinity;\n    let max = -Infinity;\n\n    for (let i = 0; i < count; i++) {\n      const material = queue[i]!;\n      queue[i] = null;\n      if (material._uploadQueue !== this) continue;\n      material._storeQueued = false;\n\n      const f32 = material.data._f32;\n      const start = material._materialIndex * WORDS_PER_TEXEL;\n      const end = start + f32.length;\n      data.set(f32, start);\n\n      if (rangeCount * 2 + 2 > this._ranges.length) {\n        const ranges = new Uint32Array(this._ranges.length * 2);\n        ranges.set(this._ranges);\n        this._ranges = ranges;\n      }\n      this._ranges[rangeCount * 2] = start;\n      this._ranges[rangeCount * 2 + 1] = end;\n      rangeCount++;\n      floats += end - start;\n      if (start < min) min = start;\n      if (end > max) max = end;\n    }\n\n    if (rangeCount === 0) return;\n\n    const ranges = this._ranges;\n    const spanBytes = (max - min) * 4;\n    const rangeBytes = floats * 4;\n\n    const source = this.texture.source;\n    if (rangeCount * TEXTURE_CALL_BYTES + rangeBytes < spanBytes) {\n      for (let r = 0; r < rangeCount; r++) {\n        uploadFloatRange(source, ranges[r * 2], ranges[r * 2 + 1]);\n      }\n    } else {\n      uploadFloatRange(source, min, max);\n    }\n\n    const buffer = this._buffer;\n    if (!buffer) return;\n\n    if (spanBytes >= BUFFER_SPAN_FLOOR_BYTES && rangeCount * this._bufferCallBytes + rangeBytes < spanBytes) {\n      for (let r = 0; r < rangeCount; r++) {\n        const start = ranges[r * 2];\n        buffer.update((ranges[r * 2 + 1] - start) * 4, start * 4);\n      }\n    } else {\n      buffer.update(spanBytes, min * 4);\n    }\n  }\n\n  public destroy(): void {\n    if (!this.data) return;\n\n    this._buffer?.destroy();\n    for (let i = 0; i < this._retiredBuffers.length; i++) this._retiredBuffers[i].destroy();\n\n    for (let i = 0; i < this._retiredTextures.length; i++) this._retiredTextures[i].destroy(true);\n\n    this.texture.destroy(true);\n\n    (this.data as Float32Array | null) = null;\n    this._buffer = null;\n    (this._retiredBuffers as Buffer3D[] | null) = null;\n    (this._retiredTextures as Texture[] | null) = null;\n    (this.texture as Texture<BufferImageSource> | null) = null;\n\n    (this._freePlaces as Map<number, number[]> | null) = null;\n    (this._dirtyQueue as (BaseMaterial3D | null)[] | null) = null;\n    this._dirtyCount = 0;\n    (this._ranges as Uint32Array | null) = null;\n  }\n\n  private _units(material: BaseMaterial3D): number {\n    return Math.ceil(material.data._f32.byteLength / this._alignment);\n  }\n\n  private _allocate(material: BaseMaterial3D): void {\n    if (material._materialIndex >= 0) return;\n\n    const units = this._units(material);\n    let index = this._freePlaces.get(units)?.pop();\n\n    if (index === undefined) {\n      const endBytes = (this._end + units) * this._alignment;\n      if (endBytes > this.data.byteLength) this._expand(endBytes / 4);\n\n      index = this._end * this._texelsPerUnit;\n      this._end += units;\n    }\n\n    material._materialIndex = index;\n  }\n\n  /**\n   * Retires the GPU views rather than destroying them, since a view that drew earlier this frame\n   * still binds them; `destroy` frees them\n   */\n  private _expand(minSize: number): void {\n    let newSize = this.data.length * 2;\n    if (newSize < minSize) newSize = minSize;\n\n    newSize = alignToDataTextureRows(newSize);\n\n    const newData = new Float32Array(newSize);\n    newData.set(this.data);\n    this.data = newData;\n\n    this._retiredTextures.push(this.texture);\n    this.texture = new Texture({ source: createDataTextureSource(this.data) });\n\n    if (this._buffer) {\n      this._retiredBuffers.push(this._buffer);\n      this._buffer = null;\n    }\n\n    this.bufferVersion++;\n  }\n}\n","import { BufferImageSource, BufferResource, BufferUsage, Texture, warn } from 'pixi.js';\n\nimport type { Geometry3D } from '../../geometry/Geometry3D';\nimport type { Mesh3D } from '../../scene/Mesh3D';\nimport type { Morph } from '../../scene/Morph';\nimport { Buffer3D } from './Buffer3D';\nimport { alignToDataTextureRows, dataTextureSize, uploadFloatRange } from './dataTextureLayout';\n\nconst FLOATS_PER_DELTA = 4;\n\ninterface MorphStoreBufferOptions {\n  deltaCapacity?: number;\n  weightCapacity?: number;\n}\n\n/**\n * Geometries' morph deltas, then meshes' weights, in one array so morphing takes one binding\n * @internal\n */\nexport class MorphStoreBuffer {\n  public data: Float32Array;\n\n  private _buffer: Buffer3D | null = null;\n  private _bufferResource: BufferResource | null = null;\n\n  /** Bumped when growth replaces the buffer, so whatever bound the old one must bind again */\n  public bufferVersion = 0;\n\n  private _deltaCursor = 0;\n\n  /** The arena's capacity, which is also the weights base; weight slots are relative to it */\n  private _deltaCapacity = 0;\n\n  private _weightCursor = 0;\n  private readonly _freeSlots = new Map<number, number[]>();\n  private readonly _freeDeltaBlocks = new Map<number, number[]>();\n  private _minDirty = Infinity;\n  private _maxDirty = -Infinity;\n  private readonly _retiredBuffers: Buffer3D[] = [];\n\n  private _texture: Texture | null = null;\n  private _textureSource: BufferImageSource | null = null;\n\n  constructor(options: MorphStoreBufferOptions = {}) {\n    this._deltaCapacity = options.deltaCapacity ?? 4096;\n    const weightCapacity = alignWeightCapacity(this._deltaCapacity, options.weightCapacity ?? 1024);\n\n    this.data = new Float32Array(this._deltaCapacity + weightCapacity);\n  }\n\n  public get buffer(): Buffer3D {\n    return (this._buffer ??= new Buffer3D({\n      data: this.data,\n      usage: BufferUsage.STORAGE | BufferUsage.COPY_DST | BufferUsage.COPY_SRC,\n      label: 'MorphStoreBuffer',\n      shrinkToFit: false,\n    }));\n  }\n\n  public get bufferResource(): BufferResource {\n    return (this._bufferResource ??= new BufferResource({ buffer: this.buffer }));\n  }\n\n  public get texture(): Texture {\n    return this._texture || this._initTexture();\n  }\n\n  /**\n   * Target `i`'s delta for vertex `vid` sits at `base + (vid * targetCount + i) * stride`, as the morph\n   * bits read it. Releases the raw targets, so a geometry another store packed draws unmorphed here\n   */\n  public uploadDeltas(geometry: Geometry3D): void {\n    const old = geometry._morphStore;\n    if (old === this) return;\n\n    if (old) {\n      old.freeDeltas(geometry);\n      warn(`MorphStoreBuffer: geometry #${geometry.uid} was packed by another renderer and draws unmorphed here`);\n      return;\n    }\n\n    const targets = geometry._morphTargets;\n    if (!targets || targets.length === 0) return;\n\n    const withNormals = geometry.hasMorphNormals;\n    const stride = withNormals ? FLOATS_PER_DELTA * 2 : FLOATS_PER_DELTA;\n    const targetCount = targets.length;\n    const vertexCount = targets[0].positions.length / 3;\n    const floats = vertexCount * targetCount * stride;\n\n    const recycled = this._freeDeltaBlocks.get(floats);\n    let base: number;\n    if (recycled && recycled.length > 0) {\n      base = recycled.pop()!;\n    } else {\n      base = this._deltaCursor;\n      if (base + floats > this._deltaCapacity) this._growArena(base + floats);\n      this._deltaCursor += floats;\n    }\n\n    const maxDeltaSq = new Float64Array(targetCount);\n\n    const data = this.data;\n    for (let vid = 0; vid < vertexCount; vid++) {\n      const src = vid * 3;\n      for (let i = 0; i < targetCount; i++) {\n        const dst = base + (vid * targetCount + i) * stride;\n        const p = targets[i].positions;\n        const dx = p[src];\n        const dy = p[src + 1];\n        const dz = p[src + 2];\n        data[dst] = dx;\n        data[dst + 1] = dy;\n        data[dst + 2] = dz;\n        data[dst + 3] = 0;\n\n        const lengthSq = dx * dx + dy * dy + dz * dz;\n        if (lengthSq > maxDeltaSq[i]) maxDeltaSq[i] = lengthSq;\n\n        if (withNormals) {\n          const n = targets[i].normals!;\n          data[dst + 4] = n[src];\n          data[dst + 5] = n[src + 1];\n          data[dst + 6] = n[src + 2];\n          data[dst + 7] = 0;\n        }\n      }\n    }\n\n    let expansion = 0;\n    for (let i = 0; i < targetCount; i++) expansion += Math.sqrt(maxDeltaSq[i]);\n    geometry._morphBoundsExpansion = expansion;\n\n    geometry._morphDeltaBase = base;\n    geometry._morphDeltaFloats = floats;\n    geometry._morphStore = this;\n    geometry._morphTargets = null;\n    this._markDirty(base, base + floats - 1);\n  }\n\n  /** The release for `uploadDeltas`, from `Geometry3D.destroy`; once the store is destroyed it only resets the geometry */\n  public freeDeltas(geometry: Geometry3D): void {\n    const base = geometry._morphDeltaBase;\n    if (base < 0) return;\n\n    const floats = geometry._morphDeltaFloats;\n    geometry._morphDeltaBase = -1;\n    geometry._morphDeltaFloats = 0;\n    geometry._morphStore = null;\n\n    if (!this.data) return;\n\n    recycle(this._freeDeltaBlocks, floats, base);\n  }\n\n  /** Packs every geometry before placing any weights, since arena growth moves the weights base */\n  public sync(morphedMeshes: Mesh3D[]): void {\n    for (let i = 0; i < morphedMeshes.length; i++) {\n      this.uploadDeltas(morphedMeshes[i].geometry);\n    }\n\n    const weightsBase = this._deltaCapacity;\n    for (let i = 0; i < morphedMeshes.length; i++) {\n      const mesh = morphedMeshes[i];\n      const morph = mesh._morph!;\n      if (morph._store !== this) {\n        morph._store?.freeSlot(morph);\n        this.allocSlot(morph);\n      }\n      const absolute = weightsBase + morph._slot;\n      if (morph._weightIndex !== absolute) {\n        morph._weightIndex = absolute;\n        mesh._markStoreDirty();\n      }\n      this.writeWeights(morph);\n    }\n\n    this.update();\n  }\n\n  public allocSlot(morph: Morph): void {\n    let size = 1;\n    while (size < morph.weights.length) size <<= 1;\n\n    const free = this._freeSlots.get(size);\n    let slot: number;\n\n    if (free && free.length > 0) {\n      slot = free.pop()!;\n    } else {\n      slot = this._weightCursor;\n      if (this._deltaCapacity + slot + size > this.data.length) {\n        this._growWeights(slot + size);\n      }\n      this._weightCursor += size;\n    }\n\n    morph._slot = slot;\n    morph._slotSize = size;\n    morph._store = this;\n  }\n\n  /** Once the store is destroyed it only resets the morph */\n  public freeSlot(morph: Morph): void {\n    const slot = morph._slot;\n    if (slot < 0) return;\n\n    const size = morph._slotSize;\n    morph._slot = -1;\n    morph._slotSize = 0;\n    morph._store = null;\n\n    if (!this.data) return;\n\n    recycle(this._freeSlots, size, slot);\n  }\n\n  /**\n   * Marks the slot for upload only when a copied value differs, the only change tracking weights have;\n   * the copy stops at the slot's size, in case `weights` grew\n   */\n  public writeWeights(morph: Morph): void {\n    const weights = morph.weights;\n    const data = this.data;\n    const base = this._deltaCapacity + morph._slot;\n    const count = Math.min(weights.length, morph._slotSize);\n\n    let changed = false;\n    for (let i = 0; i < count; i++) {\n      const value = weights[i];\n      if (data[base + i] !== value) {\n        data[base + i] = value;\n        changed = true;\n      }\n    }\n    if (changed) this._markDirty(base, base + count - 1);\n  }\n\n  public update(): void {\n    if (this._minDirty > this._maxDirty) return;\n\n    this._buffer?.update((this._maxDirty - this._minDirty + 1) * 4, this._minDirty * 4);\n\n    if (this._textureSource) uploadFloatRange(this._textureSource, this._minDirty, this._maxDirty + 1);\n\n    this._minDirty = Infinity;\n    this._maxDirty = -Infinity;\n  }\n\n  private _freeRetired(): void {\n    for (let i = 0; i < this._retiredBuffers.length; i++) this._retiredBuffers[i].destroy();\n    this._retiredBuffers.length = 0;\n  }\n\n  public destroy(): void {\n    if (!this.data) return;\n\n    this._bufferResource?.destroy(false);\n    this._buffer?.destroy();\n\n    this._freeRetired();\n\n    this._texture?.destroy(true);\n    this._texture = null;\n    this._textureSource = null;\n\n    (this.data as Float32Array | null) = null;\n    this._buffer = null;\n    this._bufferResource = null;\n  }\n\n  private _markDirty(from: number, to: number): void {\n    if (from < this._minDirty) this._minDirty = from;\n    if (to > this._maxDirty) this._maxDirty = to;\n  }\n\n  private _growArena(requiredFloats: number): void {\n    let capacity = this._deltaCapacity;\n    while (capacity < requiredFloats) capacity *= 2;\n    this._reallocate(capacity, this.data.length - this._deltaCapacity);\n  }\n\n  private _growWeights(requiredFloats: number): void {\n    let capacity = this.data.length - this._deltaCapacity;\n    while (capacity < requiredFloats) capacity *= 2;\n    this._reallocate(this._deltaCapacity, capacity);\n  }\n\n  /** Retires the buffer rather than destroying it, since draws recorded earlier still bind it; `destroy` frees it */\n  private _reallocate(newDeltaCapacity: number, newWeightCapacity: number): void {\n    newWeightCapacity = alignWeightCapacity(newDeltaCapacity, newWeightCapacity);\n    const newData = new Float32Array(newDeltaCapacity + newWeightCapacity);\n\n    newData.set(this.data.subarray(0, this._deltaCursor), 0);\n    newData.set(this.data.subarray(this._deltaCapacity, this._deltaCapacity + this._weightCursor), newDeltaCapacity);\n\n    this.data = newData;\n    this._deltaCapacity = newDeltaCapacity;\n\n    if (this._buffer) {\n      this._retiredBuffers.push(this._buffer);\n      this._buffer = null;\n      this._bufferResource = null;\n    }\n    this.bufferVersion++;\n\n    if (this._textureSource) {\n      const { width, height } = dataTextureSize(this.data.length);\n\n      this._textureSource.resource = this.data;\n      if (this._textureSource.width !== width || this._textureSource.height !== height) {\n        this._textureSource.resize(width, height);\n      }\n      this._textureSource.update();\n    }\n  }\n\n  private _initTexture(): Texture {\n    const { width, height } = dataTextureSize(this.data.length);\n\n    this._textureSource = new BufferImageSource({\n      resource: this.data,\n      width,\n      height,\n      format: 'rgba32float',\n      scaleMode: 'nearest',\n      alphaMode: 'no-premultiply-alpha',\n    });\n\n    this._texture = new Texture({ source: this._textureSource });\n\n    return this._texture;\n  }\n}\n\nfunction recycle(lists: Map<number, number[]>, size: number, offset: number): void {\n  let free = lists.get(size);\n  if (!free) {\n    free = [];\n    lists.set(size, free);\n  }\n  free.push(offset);\n}\n\nfunction alignWeightCapacity(deltaCapacity: number, weightCapacity: number): number {\n  const total = deltaCapacity + weightCapacity;\n\n  return weightCapacity + (alignToDataTextureRows(total) - total);\n}\n","import { BufferImageSource, Texture } from 'pixi.js';\n\nimport { DATA_TEXTURE_WIDTH, uploadTexelRange } from './dataTextureLayout';\n\nconst WORDS_PER_INSTANCE = 1;\n\n/** Fills a new array, so the compaction, which writes only changed texels, finds every survivor changed */\nconst NO_ROW = 0xffffffff;\n\n/**\n * WebGL2 has no `baseInstance`, so `instanceFetchBitGl` reads texel `uInstanceBase + gl_InstanceID`\n * for the store row; an integer format, since a float one could rewrite the bits\n * @internal\n */\nexport class RenderInstanceTexture {\n  /** Matches the GPU copy, which lets the compaction skip unchanged texels, so upload every texel you change */\n  public data!: Uint32Array;\n\n  private _source!: BufferImageSource;\n  private _texture!: Texture;\n  private _capacity = 0;\n\n  constructor(initialCapacity = 256) {\n    this.ensureCapacity(initialCapacity);\n  }\n\n  public get texture(): Texture {\n    return this._texture;\n  }\n\n  public get capacity(): number {\n    return this._capacity;\n  }\n\n  public ensureCapacity(instances: number): void {\n    if (instances <= this._capacity) return;\n\n    let capacity = Math.max(256, this._capacity);\n    while (capacity < instances) capacity *= 2;\n    this._capacity = capacity;\n\n    const width = Math.min(capacity, DATA_TEXTURE_WIDTH);\n    const height = Math.ceil(capacity / width);\n\n    this.data = new Uint32Array(width * height * WORDS_PER_INSTANCE).fill(NO_ROW);\n\n    if (!this._source) {\n      this._source = new BufferImageSource({\n        resource: this.data,\n        width,\n        height,\n        format: 'r32uint',\n        scaleMode: 'nearest',\n        alphaMode: 'no-premultiply-alpha',\n        label: 'InstanceIndex',\n      });\n      this._texture = new Texture({ source: this._source });\n      return;\n    }\n\n    this._source.resource = this.data;\n    if (this._source.width !== width || this._source.height !== height) {\n      this._source.resize(width, height);\n    }\n  }\n\n  public upload(start: number, end: number): void {\n    if (start < end) uploadTexelRange(this._source, start, end);\n  }\n\n  public unload(): void {\n    this._source?.unload();\n  }\n\n  public destroy(): void {\n    if (!this._texture) return;\n    this._texture.destroy(true);\n    (this._texture as Texture | null) = null;\n    (this._source as BufferImageSource | null) = null;\n    (this.data as Uint32Array | null) = null;\n  }\n}\n","import type { Matrix4 } from '../matrix/Matrix4';\nimport type { SHAPE_PRIMITIVE_3D } from '../misc/const';\nimport type { PointData3D } from '../vector/PointData3D';\nimport { Vector3 } from '../vector/Vector3';\nimport type { Box } from './Box';\nimport type { Ray } from './Ray';\nimport type { Sphere } from './Sphere';\n\n/**\n * An infinite flat plane: the points `p` where `normal · p + constant = 0`\n *\n * The ground `y = 0` is `new Plane(new Vector3(0, 1, 0), 0)`, and the upward-facing plane `y = 2`\n * has a constant of `-2`. Keep `normal` unit length, or distances come out scaled;\n * {@link Plane#normalize} fixes one that isn't.\n * @example\n * ```ts\n * const water = new Plane(new Vector3(0, 1, 0), -waterLevel);\n *\n * app.ticker.add(() => {\n *   underwaterFilter.enabled = water.distanceToPoint(camera.position) < 0;\n * });\n * ```\n * @see {@link Ray#intersectPlane} For the point where a ray hits the plane\n * @category maths\n * @standard\n */\nexport class Plane {\n  /**\n   * The unit-length direction the plane faces; its positive side\n   * @example\n   * ```ts\n   * const facingUp = slope.normal.y > 0.7;\n   * ```\n   */\n  public readonly normal: Vector3;\n  /**\n   * The origin's signed distance from the plane, negative when the origin is behind it\n   * @example\n   * ```ts\n   * water.constant = -waterLevel;\n   * ```\n   */\n  public constant = 0;\n\n  /**\n   * Names the shape without an `instanceof` check, like the `type` on pixi's 2D shapes\n   * @readonly\n   * @default 'plane'\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type: SHAPE_PRIMITIVE_3D = 'plane';\n\n  /**\n   * Creates a new `Plane`\n   *\n   * Left out, the plane is `x = 0` facing +X. A normal passed in becomes the plane's own; it is\n   * not copied.\n   * @param normal - The unit-length normal of the plane\n   * @param constant - The origin's signed distance from the plane\n   */\n  constructor(normal?: Vector3, constant = 0) {\n    this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);\n    this.constant = constant;\n  }\n\n  /**\n   * Sets the normal and constant of this plane, copying the normal\n   * @example\n   * ```ts\n   * ceiling.set({ x: 0, y: -1, z: 0 }, roomHeight);\n   * ```\n   * @param normal - The unit-length normal\n   * @param constant - The origin's signed distance from the plane\n   * @returns This plane for chaining\n   */\n  public set(normal: PointData3D, constant: number): this {\n    this.normal.copyFrom(normal);\n    this.constant = constant;\n\n    return this;\n  }\n\n  /**\n   * Sets the normal to `(x, y, z)` and the constant to `w`, the four numbers of a plane equation\n   *\n   * Equations from elsewhere, such as rows of a projection matrix, rarely have a unit-length\n   * normal, so call {@link Plane#normalize} after.\n   * @example\n   * ```ts\n   * clipPlane.setComponents(equation[0], equation[1], equation[2], equation[3]).normalize();\n   * ```\n   * @param x - The x component of the normal\n   * @param y - The y component of the normal\n   * @param z - The z component of the normal\n   * @param w - The plane constant\n   * @returns This plane for chaining\n   */\n  public setComponents(x: number, y: number, z: number, w: number): this {\n    this.normal.set(x, y, z);\n    this.constant = w;\n\n    return this;\n  }\n\n  /**\n   * Sets this plane from a unit-length `normal` and a coplanar `point`\n   * @example\n   * ```ts\n   * mirrorPlane.setFromNormalAndCoplanarPoint({ x: 0, y: 0, z: 1 }, mirror.position);\n   * ```\n   * @param normal - The unit-length normal\n   * @param point - A point on the plane\n   * @returns This plane for chaining\n   */\n  public setFromNormalAndCoplanarPoint(normal: PointData3D, point: PointData3D): this {\n    this.normal.copyFrom(normal);\n    this.constant = -(point.x * this.normal.x + point.y * this.normal.y + point.z * this.normal.z);\n\n    return this;\n  }\n\n  /**\n   * Copies `plane` into this plane\n   * @example\n   * ```ts\n   * reflectionPlane.copyFrom(water);\n   * ```\n   * @param plane - The plane to copy from\n   * @returns This plane for chaining\n   */\n  public copyFrom(plane: Plane): this {\n    this.normal.copyFrom(plane.normal);\n    this.constant = plane.constant;\n\n    return this;\n  }\n\n  /**\n   * Copies this plane into `target` and returns it\n   * @example\n   * ```ts\n   * water.copyTo(reflectionPlane);\n   * ```\n   * @param target - The plane to copy into\n   * @returns The given `target`\n   */\n  public copyTo<T extends Plane>(target: T): T {\n    target.normal.copyFrom(this.normal);\n    target.constant = this.constant;\n\n    return target;\n  }\n\n  /**\n   * Creates a new `Plane` with the same normal and constant\n   * @example\n   * ```ts\n   * const worldPlane = localPlane.clone().applyMatrix4(portal.worldTransform);\n   * ```\n   * @returns The new plane\n   */\n  public clone(): Plane {\n    return new Plane().copyFrom(this);\n  }\n\n  /**\n   * Returns true when `normal` and `constant` match `plane` exactly (no epsilon tolerance)\n   * @example\n   * ```ts\n   * if (!clipPlane.equals(lastClipPlane)) rebuildClipping(clipPlane);\n   * ```\n   * @param plane - The plane to compare with\n   * @returns Whether the normal and constant match\n   */\n  public equals(plane: Plane): boolean {\n    return plane.normal.equals(this.normal) && plane.constant === this.constant;\n  }\n\n  /**\n   * Scales the plane so `normal` has unit length\n   *\n   * The constant scales with it, so the plane stays in place. A zero-length normal gives `NaN`.\n   * @example\n   * ```ts\n   * const slope = new Plane(new Vector3(0, 2, 1), 0).normalize();\n   * ```\n   * @param out - Target to write the result into instead of mutating this plane\n   * @returns The result plane for chaining\n   */\n  public normalize(out: Plane = this): this {\n    if (out !== this) out.copyFrom(this);\n    const inverseNormalLength = 1.0 / out.normal.magnitude();\n    out.normal.multiplyScalar(inverseNormalLength);\n    out.constant *= inverseNormalLength;\n\n    return out as this;\n  }\n\n  /**\n   * Returns the signed distance from `point` to this plane (positive on the side of `normal`)\n   * @example\n   * ```ts\n   * const depth = -water.distanceToPoint(diver.position);\n   * ```\n   * @param point - The point to measure from\n   * @returns The signed distance to the plane\n   */\n  public distanceToPoint(point: PointData3D): number {\n    return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.constant;\n  }\n\n  /**\n   * Writes the closest point on this plane to `point` into `out` (or a new `Vector3`)\n   * @example\n   * ```ts\n   * const footprint = new Vector3();\n   *\n   * ground.projectPoint(ball.position, footprint);\n   * blobShadow.position.copyFrom(footprint);\n   * ```\n   * @param point - The point to project\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The projected point\n   */\n  public projectPoint(point: PointData3D, out?: Vector3): Vector3 {\n    out ||= new Vector3();\n\n    return out.copyFrom(point).addScaledVector(this.normal, -this.distanceToPoint(point));\n  }\n\n  /**\n   * Returns true when this plane passes through `box` or touches it; same as {@link Box#intersectsPlane}\n   * @example\n   * ```ts\n   * const halfSubmerged = water.intersectsBox(boatBounds);\n   * ```\n   * @param box - The box to test\n   * @returns Whether the plane passes through or touches the box\n   */\n  public intersectsBox(box: Box): boolean {\n    return box.intersectsPlane(this);\n  }\n\n  /**\n   * Returns true when this plane passes through `sphere` or touches it; never for an empty sphere\n   * @example\n   * ```ts\n   * const splashing = water.intersectsSphere(ball.boundingSphere);\n   * ```\n   * @param sphere - The sphere to test\n   * @returns Whether the plane passes through or touches the sphere\n   */\n  public intersectsSphere(sphere: Sphere): boolean {\n    return sphere.intersectsPlane(this);\n  }\n\n  /**\n   * Returns true when `ray` hits this plane; same as {@link Ray#intersectsPlane}\n   * @example\n   * ```ts\n   * cursor.visible = ground.intersectsRay(pointerRay);\n   * ```\n   * @param ray - The ray to test\n   * @returns Whether the ray intersects this plane\n   */\n  public intersectsRay(ray: Ray): boolean {\n    return ray.intersectsPlane(this);\n  }\n\n  /**\n   * Transforms this plane by an affine `matrix`, so points on it stay on it\n   *\n   * Non-uniform scale is fine, and the normal comes out unit length. A mirroring matrix swaps\n   * which side of the plane is positive. Needs a unit-length `normal`, and `matrix` must be affine\n   * (bottom row `[0, 0, 0, 1]`), as a {@link Container3D#worldTransform} always is.\n   * @example\n   * ```ts\n   * const worldMirror = new Plane();\n   *\n   * localMirror.applyMatrix4(mirror.worldTransform, worldMirror);\n   * ```\n   * @param matrix - The affine matrix to transform by\n   * @param out - Target to write the result into instead of mutating this plane\n   * @returns The result plane for chaining\n   */\n  public applyMatrix4(matrix: Matrix4, out: Plane = this): this {\n    if (out !== this) out.copyFrom(this);\n\n    const e = matrix.elements;\n    const e0 = e[0];\n    const e1 = e[1];\n    const e2 = e[2];\n    const e4 = e[4];\n    const e5 = e[5];\n    const e6 = e[6];\n    const e8 = e[8];\n    const e9 = e[9];\n    const e10 = e[10];\n\n    const nx0 = out.normal.x;\n    const ny0 = out.normal.y;\n    const nz0 = out.normal.z;\n    const nx = (e5 * e10 - e6 * e9) * nx0 + (e2 * e9 - e1 * e10) * ny0 + (e1 * e6 - e2 * e5) * nz0;\n    const ny = (e6 * e8 - e4 * e10) * nx0 + (e0 * e10 - e2 * e8) * ny0 + (e2 * e4 - e0 * e6) * nz0;\n    const nz = (e4 * e9 - e5 * e8) * nx0 + (e1 * e8 - e0 * e9) * ny0 + (e0 * e5 - e1 * e4) * nz0;\n\n    const len = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1;\n    const invLen = 1 / len;\n    const newNx = nx * invLen;\n    const newNy = ny * invLen;\n    const newNz = nz * invLen;\n\n    const px = -out.constant * nx0;\n    const py = -out.constant * ny0;\n    const pz = -out.constant * nz0;\n    const tpx = e0 * px + e4 * py + e8 * pz + e[12];\n    const tpy = e1 * px + e5 * py + e9 * pz + e[13];\n    const tpz = e2 * px + e6 * py + e10 * pz + e[14];\n\n    out.normal.set(newNx, newNy, newNz);\n    out.constant = -(tpx * newNx + tpy * newNy + tpz * newNz);\n\n    return out as this;\n  }\n\n  /**\n   * Returns a string representation of this plane\n   * @returns A string in the form `[@pixi/3d/math:Plane normal=(1, 0, 0) constant=0]`\n   * @advanced\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Plane normal=(${this.normal.x}, ${this.normal.y}, ${this.normal.z}) constant=${this.constant}]`;\n  }\n}\n","import type { Matrix4 } from '../matrix/Matrix4';\nimport type { Box } from '../shapes/Box';\nimport { Plane } from '../shapes/Plane';\nimport type { Sphere } from '../shapes/Sphere';\nimport type { PointData3D } from '../vector/PointData3D';\n\n/**\n * A volume bounded by six planes that face inward, most often the volume a camera sees\n *\n * Each {@link Camera3D} has one as {@link Camera3D#frustum}. Test against it to skip work for\n * things the camera can't see, or build your own from a matrix or from planes to cull against\n * another volume.\n * @example\n * ```ts\n * const onScreen = enemies.filter((enemy: Mesh3D) =>\n *   camera.frustum.intersectsSphere(enemy.boundingSphere),\n * );\n * ```\n * @category maths\n * @standard\n */\nexport class Frustum {\n  private readonly _planes: Float32Array;\n\n  /**\n   * Creates a new `Frustum`\n   *\n   * A plane left out defaults to `new Plane()`: normal `(1, 0, 0)`, constant `0`.\n   * @param p0 - The first plane\n   * @param p1 - The second plane\n   * @param p2 - The third plane\n   * @param p3 - The fourth plane\n   * @param p4 - The fifth plane\n   * @param p5 - The sixth plane\n   */\n  constructor(p0?: Plane, p1?: Plane, p2?: Plane, p3?: Plane, p4?: Plane, p5?: Plane) {\n    this._planes = new Float32Array(24);\n    for (let i = 0; i < 24; i += 4) this._planes[i] = 1;\n\n    if (p0 !== undefined) this._writePlane(0, p0);\n    if (p1 !== undefined) this._writePlane(1, p1);\n    if (p2 !== undefined) this._writePlane(2, p2);\n    if (p3 !== undefined) this._writePlane(3, p3);\n    if (p4 !== undefined) this._writePlane(4, p4);\n    if (p5 !== undefined) this._writePlane(5, p5);\n  }\n\n  /**\n   * The six planes as 24 floats, `[nx, ny, nz, c]` per plane in {@link Frustum#getPlane} order\n   *\n   * This is the frustum's own storage, not a copy: writing to it changes the frustum. Pass it to\n   * your own shader to cull on the GPU.\n   * @example\n   * ```ts\n   * device.queue.writeBuffer(frustumBuffer, 0, camera.frustum.planesData);\n   * ```\n   * @advanced\n   */\n  public get planesData(): Float32Array {\n    return this._planes;\n  }\n\n  /**\n   * Sets the six planes of this frustum\n   *\n   * Each plane's normal must be unit length and point into the volume.\n   * @example\n   * ```ts\n   * camera.cullFrustum = new Frustum().set(\n   *   new Plane(new Vector3(1, 0, 0), 20),\n   *   new Plane(new Vector3(-1, 0, 0), 20),\n   *   new Plane(new Vector3(0, 1, 0), 0),\n   *   new Plane(new Vector3(0, -1, 0), 10),\n   *   new Plane(new Vector3(0, 0, 1), 20),\n   *   new Plane(new Vector3(0, 0, -1), 20),\n   * );\n   * ```\n   * @param p0 - The first plane\n   * @param p1 - The second plane\n   * @param p2 - The third plane\n   * @param p3 - The fourth plane\n   * @param p4 - The fifth plane\n   * @param p5 - The sixth plane\n   * @returns This frustum for chaining\n   */\n  public set(p0: Plane, p1: Plane, p2: Plane, p3: Plane, p4: Plane, p5: Plane): this {\n    this._writePlane(0, p0);\n    this._writePlane(1, p1);\n    this._writePlane(2, p2);\n    this._writePlane(3, p3);\n    this._writePlane(4, p4);\n    this._writePlane(5, p5);\n\n    return this;\n  }\n\n  /**\n   * Sets the six planes to the volume that `matrix` maps onto the screen\n   *\n   * The planes come out in the space the matrix maps from: world space for a view-projection\n   * matrix, view space for a projection matrix alone. They are normalized, so distances to them are\n   * in that space's units. The matrix must map depth to `[-1, 1]`, as\n   * {@link Matrix4#makePerspective} and {@link Matrix4#makeOrthographic} do.\n   * @example\n   * ```ts\n   * const spotlightView = new Frustum().setFromProjectionMatrix(securityCamera.viewProjection);\n   * const spotted = spotlightView.containsPoint(player.position);\n   * ```\n   * @param matrix - The matrix to extract clipping planes from\n   * @returns This frustum for chaining\n   */\n  public setFromProjectionMatrix(matrix: Matrix4): this {\n    const me = matrix.elements;\n    const me0 = me[0];\n    const me1 = me[1];\n    const me2 = me[2];\n    const me3 = me[3];\n    const me4 = me[4];\n    const me5 = me[5];\n    const me6 = me[6];\n    const me7 = me[7];\n    const me8 = me[8];\n    const me9 = me[9];\n    const me10 = me[10];\n    const me11 = me[11];\n    const me12 = me[12];\n    const me13 = me[13];\n    const me14 = me[14];\n    const me15 = me[15];\n\n    const planes = this._planes;\n    _writeNormalized(planes, 0, me3 - me0, me7 - me4, me11 - me8, me15 - me12);\n    _writeNormalized(planes, 4, me3 + me0, me7 + me4, me11 + me8, me15 + me12);\n    _writeNormalized(planes, 8, me3 + me1, me7 + me5, me11 + me9, me15 + me13);\n    _writeNormalized(planes, 12, me3 - me1, me7 - me5, me11 - me9, me15 - me13);\n    _writeNormalized(planes, 16, me3 - me2, me7 - me6, me11 - me10, me15 - me14);\n    _writeNormalized(planes, 20, me3 + me2, me7 + me6, me11 + me10, me15 + me14);\n\n    return this;\n  }\n\n  /**\n   * Copies `frustum` into this frustum\n   * @example\n   * ```ts\n   * frozenFrustum.copyFrom(camera.frustum);\n   * camera.cullFrustum = frozenFrustum;\n   * ```\n   * @param frustum - The frustum to copy from\n   * @returns This frustum for chaining\n   */\n  public copyFrom(frustum: Frustum): this {\n    this._planes.set(frustum._planes);\n\n    return this;\n  }\n\n  /**\n   * Copies this frustum into `target` and returns it\n   * @example\n   * ```ts\n   * camera.frustum.copyTo(debugFrustum);\n   * ```\n   * @param target - The frustum to copy into\n   * @returns The given `target`\n   */\n  public copyTo<T extends Frustum>(target: T): T {\n    target._planes.set(this._planes);\n\n    return target;\n  }\n\n  /**\n   * Creates a new `Frustum` with the same planes\n   * @example\n   * ```ts\n   * camera.cullFrustum = camera.frustum.clone();\n   * ```\n   * @returns The new frustum\n   */\n  public clone(): Frustum {\n    return new Frustum().copyFrom(this);\n  }\n\n  /**\n   * Returns true when all six planes match `frustum` exactly, with no tolerance\n   * @example\n   * ```ts\n   * if (!camera.frustum.equals(lastFrustum)) {\n   *   lastFrustum.copyFrom(camera.frustum);\n   *   refreshVisibleList();\n   * }\n   * ```\n   * @param frustum - The frustum to compare with\n   * @returns Whether all six planes match\n   */\n  public equals(frustum: Frustum): boolean {\n    const a = this._planes;\n    const b = frustum._planes;\n    for (let i = 0; i < 24; i++) {\n      if (a[i] !== b[i]) return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Writes plane `index` into `out` and returns it\n   *\n   * After {@link Frustum#setFromProjectionMatrix} the planes are ordered right, left, bottom, top,\n   * far, near.\n   * @example\n   * ```ts\n   * const near = camera.frustum.getPlane(5, new Plane());\n   * const distanceInFront = near.distanceToPoint(pickup.position);\n   * ```\n   * @param index - The plane index, `0` to `5`\n   * @param out - Optional plane to write into; a new `Plane` when omitted\n   * @returns The written plane\n   */\n  public getPlane(index: number, out?: Plane): Plane {\n    out ||= new Plane();\n    const offset = index * 4;\n    out.normal.set(this._planes[offset], this._planes[offset + 1], this._planes[offset + 2]);\n    out.constant = this._planes[offset + 3];\n\n    return out;\n  }\n\n  /**\n   * Returns true when `point` lies inside this frustum (boundary is inclusive)\n   * @example\n   * ```ts\n   * marker.visible = !camera.frustum.containsPoint(objective.position);\n   * ```\n   * @param point - The point to test\n   * @returns Whether the point is inside this frustum\n   */\n  public containsPoint(point: PointData3D): boolean {\n    const planes = this._planes;\n    const px = point.x;\n    const py = point.y;\n    const pz = point.z;\n\n    for (let i = 0; i < 24; i += 4) {\n      if (planes[i] * px + planes[i + 1] * py + planes[i + 2] * pz + planes[i + 3] < 0) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  /**\n   * Returns true when `box` and this frustum overlap\n   *\n   * Like most culling tests it errs towards true: a box just outside a corner of the frustum can\n   * pass, but a box that overlaps it never fails.\n   * @example\n   * ```ts\n   * building.getLocalBounds(bounds).applyMatrix4(building.worldTransform);\n   * if (camera.frustum.intersectsBox(bounds)) updateWindowLights(building);\n   * ```\n   * @param box - The box to test\n   * @returns Whether the box and this frustum overlap\n   */\n  public intersectsBox(box: Box): boolean {\n    const planes = this._planes;\n    const minX = box.min.x;\n    const minY = box.min.y;\n    const minZ = box.min.z;\n    const maxX = box.max.x;\n    const maxY = box.max.y;\n    const maxZ = box.max.z;\n\n    for (let i = 0; i < 24; i += 4) {\n      const nx = planes[i];\n      const ny = planes[i + 1];\n      const nz = planes[i + 2];\n      const px = nx > 0 ? maxX : minX;\n      const py = ny > 0 ? maxY : minY;\n      const pz = nz > 0 ? maxZ : minZ;\n\n      if (nx * px + ny * py + nz * pz + planes[i + 3] < 0) return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Returns true when `sphere` and this frustum overlap\n   *\n   * Like {@link Frustum#intersectsBox} it errs towards true near the frustum's corners. Empty\n   * spheres (`radius < 0`) never intersect.\n   * @example\n   * ```ts\n   * if (camera.frustum.intersectsSphere(enemy.boundingSphere)) enemy.updateAnimation(dt);\n   * ```\n   * @param sphere - The sphere to test\n   * @returns Whether the sphere and this frustum overlap\n   */\n  public intersectsSphere(sphere: Sphere): boolean {\n    if (sphere.radius < 0) return false;\n    const planes = this._planes;\n    const cx = sphere.center.x;\n    const cy = sphere.center.y;\n    const cz = sphere.center.z;\n    const negRadius = -sphere.radius;\n\n    for (let i = 0; i < 24; i += 4) {\n      if (planes[i] * cx + planes[i + 1] * cy + planes[i + 2] * cz + planes[i + 3] < negRadius) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  /**\n   * Returns a string representation of this frustum\n   * @example\n   * ```ts\n   * console.log(`${camera.frustum}`);\n   * ```\n   * @returns The string `[@pixi/3d/math:Frustum]`\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Frustum]`;\n  }\n\n  private _writePlane(index: number, plane: Plane): void {\n    const offset = index * 4;\n    this._planes[offset] = plane.normal.x;\n    this._planes[offset + 1] = plane.normal.y;\n    this._planes[offset + 2] = plane.normal.z;\n    this._planes[offset + 3] = plane.constant;\n  }\n}\n\nfunction _writeNormalized(planes: Float32Array, offset: number, x: number, y: number, z: number, w: number): void {\n  const inv = 1 / Math.sqrt(x * x + y * y + z * z);\n  planes[offset] = x * inv;\n  planes[offset + 1] = y * inv;\n  planes[offset + 2] = z * inv;\n  planes[offset + 3] = w * inv;\n}\n","import { BindGroup, Point, Rectangle, UniformGroup } from 'pixi.js';\nimport type { PointData } from 'pixi.js';\n\nimport { Matrix4 } from '../math/matrix/Matrix4';\nimport { Frustum } from '../math/misc/Frustum';\nimport { Vector3 } from '../math/vector/Vector3';\nimport type { Camera3D } from '../scene/cameras/Camera3D';\nimport { LIGHT_DEPTH_LANES, LIGHT_TILE_LANES, LightTiles } from './LightTiles';\nimport type { ReadonlyRect, RenderSession } from './render-passes/RenderSession';\n\nconst scratchCameraPosition = new Vector3();\nconst scratchJitter = new Point();\nconst NO_JITTER: PointData = { x: 0, y: 0 };\n\nfunction flipProjectionY(projection: Matrix4): void {\n  const e = projection.elements;\n  e[1] = -e[1];\n  e[5] = -e[5];\n  e[9] = -e[9];\n  e[13] = -e[13];\n}\n\nfunction jitterProjection(projection: Matrix4, x: number, y: number): void {\n  const e = projection.elements;\n  e[0] += x * e[3];\n  e[4] += x * e[7];\n  e[8] += x * e[11];\n  e[12] += x * e[15];\n  e[1] += y * e[3];\n  e[5] += y * e[7];\n  e[9] += y * e[11];\n  e[13] += y * e[15];\n}\n\n/** `linearDepth` in `fxhBit` relies on this storing depth as `(ndc + 1) / 2`, as WebGL does */\nfunction remapProjectionZeroToOne(projection: Matrix4): void {\n  const e = projection.elements;\n  e[2] = 0.5 * (e[2] + e[3]);\n  e[6] = 0.5 * (e[6] + e[7]);\n  e[10] = 0.5 * (e[10] + e[11]);\n  e[14] = 0.5 * (e[14] + e[15]);\n}\n\n/**\n * Turns a GL-convention matrix into the GPU's: jitter, then Y flip, so the jitter keeps its direction on screen,\n * then depth remap; all are row operations, so a view-projection works as well as a projection\n * @param matrix - A projection or view-projection, edited in place.\n * @param jitter - NDC offset, Y up.\n * @param flipY - Whether the target's front face is inverted.\n * @param zeroToOneDepth - Whether to remap clip z to `[0, w]`, for WebGPU.\n */\nfunction toGpuMatrix(matrix: Matrix4, jitter: PointData, flipY: boolean, zeroToOneDepth: boolean): void {\n  jitterProjection(matrix, jitter.x, jitter.y);\n  if (flipY) flipProjectionY(matrix);\n  if (zeroToOneDepth) remapProjectionZeroToOne(matrix);\n}\n\n/** @internal */\nexport class CameraData {\n  /** Fields and order must match `cameraBit` */\n  public readonly uniformGroup: UniformGroup;\n  public readonly bindGroup: BindGroup;\n  public readonly position = new Vector3();\n  public readonly view = new Matrix4();\n  /** The GPU form `set` builds, jittered, Y-flipped and depth-remapped as asked, unlike the camera's own */\n  public readonly projection = new Matrix4();\n  public readonly viewProjection = new Matrix4();\n  /**\n   * The camera's view-projection at its last render, in this render's GPU form, jitter included, so the jitter\n   * cancels out of the motion a shader measures\n   */\n  public readonly previousViewProjection = new Matrix4();\n  public readonly viewportUvScale = new Point(1, 1);\n  public readonly lightTiles = new LightTiles();\n  /**\n   * Built from unflipped matrices, as `buildProjection` in `prepareCamera.ts` builds a camera's, since a Y flip\n   * on a lens-shifted projection would mirror the volume\n   */\n  public readonly frustum: Frustum;\n\n  /**\n   * Where the camera's image lands, clipped to its target, in logical pixels on screen or texels in a render\n   * texture; empty when it lands nowhere\n   */\n  public readonly frame = new Rectangle();\n\n  /** The session this was last built for; identity is enough, since each frame makes a new session */\n  public _currentSession: RenderSession | null = null;\n\n  /** `Camera3D.viewProjection` at the last render, as built, so `syncFromCamera` can give it this render's GPU form */\n  private readonly _lastViewProjection = new Matrix4();\n  /** Whether `_lastViewProjection` holds an earlier render */\n  public _hasHistory = false;\n\n  constructor(frustum: Frustum = new Frustum()) {\n    this.frustum = frustum;\n    this.uniformGroup = new UniformGroup({\n      uCameraPosition: { value: this.position, type: 'vec3<f32>' },\n      uViewMatrix: { value: this.view, type: 'mat4x4<f32>' },\n      uProjectionMatrix: { value: this.projection, type: 'mat4x4<f32>' },\n      uViewProjectionMatrix: { value: this.viewProjection, type: 'mat4x4<f32>' },\n      uPreviousViewProjectionMatrix: { value: this.previousViewProjection, type: 'mat4x4<f32>' },\n      uViewportUVScale: { value: this.viewportUvScale, type: 'vec2<f32>' },\n      uLightTileTransform: { value: this.lightTiles.tileTransform, type: 'vec4<f32>' },\n      uLightTiles: { value: this.lightTiles.masks, type: 'vec4<i32>', size: LIGHT_TILE_LANES },\n      uLightDepthMasks: { value: this.lightTiles.depthMasks, type: 'vec4<i32>', size: LIGHT_DEPTH_LANES },\n      uLightDepthPlane: { value: this.lightTiles.depthPlane, type: 'vec4<f32>' },\n    });\n    this.uniformGroup.isStatic = true;\n    this.uniformGroup.ubo = false;\n    this.bindGroup = new BindGroup({ camera: this.uniformGroup });\n  }\n\n  /**\n   * Writes the lanes from copies, so callers may pass scratch matrices, and builds the projection's GPU form\n   * @param position - Eye position in world space.\n   * @param view - World to view.\n   * @param projection - As built, in the GL convention.\n   * @param flipY - Whether the target's front face is inverted.\n   * @param zeroToOneDepth - Whether to remap clip z to `[0, w]`, for WebGPU.\n   * @param jitter - In NDC with Y up, not the pixels `Camera3D.jitter` holds.\n   */\n  public set(\n    position: Vector3,\n    view: Matrix4,\n    projection: Matrix4,\n    flipY = false,\n    zeroToOneDepth = false,\n    jitter: PointData = NO_JITTER,\n  ): this {\n    this.position.copyFrom(position);\n    this.view.copyFrom(view);\n    this.projection.copyFrom(projection);\n    toGpuMatrix(this.projection, jitter, flipY, zeroToOneDepth);\n    this.viewProjection.multiplyMatrices(this.projection, view);\n    this.lightTiles.invalidate();\n    this.uniformGroup.update();\n\n    return this;\n  }\n\n  public setViewportUvScale(x: number, y: number): this {\n    this.viewportUvScale.set(x, y);\n    this.uniformGroup.update();\n\n    return this;\n  }\n\n  public setViewport(rect: ReadonlyRect, topDown = false): this {\n    if (this.lightTiles.setViewport(rect, topDown)) this.uniformGroup.update();\n\n    return this;\n  }\n\n  public prepareLightTiles(session: RenderSession): void {\n    if (this.lightTiles.prepare(session, this.viewProjection, this.view)) this.uniformGroup.update();\n  }\n\n  /**\n   * Writes the camera's lanes and rolls `previousViewProjection` forward; a camera drawn twice in one frame reads\n   * no motion the second time\n   * @param camera - The camera, with its matrices built for this render.\n   * @param flipY - Whether the target's front face is inverted.\n   * @param zeroToOneDepth - Whether to remap clip z to `[0, w]`, for WebGPU.\n   * @param viewport - The GPU viewport, which turns the camera's pixel jitter into NDC; no jitter without one.\n   */\n  public syncFromCamera(camera: Camera3D, flipY = false, zeroToOneDepth = false, viewport?: ReadonlyRect | null): this {\n    camera.worldTransform.extractPosition(scratchCameraPosition);\n\n    const { x, y } = camera.jitter;\n    const valid = viewport && viewport.width > 0 && viewport.height > 0;\n    scratchJitter.set(valid ? (2 * x) / viewport.width : 0, valid ? (-2 * y) / viewport.height : 0);\n\n    this.set(scratchCameraPosition, camera.view, camera.projection, flipY, zeroToOneDepth, scratchJitter);\n\n    const previous = this.previousViewProjection;\n    previous.copyFrom(this._hasHistory ? this._lastViewProjection : camera.viewProjection);\n    toGpuMatrix(previous, scratchJitter, flipY, zeroToOneDepth);\n    this._lastViewProjection.copyFrom(camera.viewProjection);\n    this._hasHistory = true;\n\n    return this;\n  }\n\n  /**\n   * Destroys the bind group before the buffer it binds; nothing else frees a cascade's buffer, which\n   * `ShadowRenderPassGpu` takes out of the renderer GC\n   */\n  public destroy(): void {\n    this.lightTiles.destroy();\n    this._currentSession = null;\n    this.bindGroup.destroy();\n    this.uniformGroup.buffer?.destroy();\n  }\n}\n\n/**\n * A camera's data, made on first use and sharing the camera's `frustum`\n * @internal\n */\nexport function getCameraData(camera: Camera3D): CameraData {\n  return (camera._cameraData ??= new CameraData(camera.frustum));\n}\n","import { isMobile, isSafari } from 'pixi.js';\n\nimport type { CullMode } from '../scene/View3D';\n\n/**\n * A batch's cull mode in one pass: `'gpu'` falls back to `'cpu'` where the pass can't compact on the GPU\n * @internal\n */\nexport function resolveCullProducer(mode: CullMode, gpuCompaction: boolean): CullMode {\n  return mode === 'gpu' && !gpuCompaction ? 'cpu' : mode;\n}\n\n/**\n * Per pass, the largest batch in instances that culls on the CPU and draws direct, rather than on the GPU and\n * indirect; it works around WebKit's GPU cost per indirect draw, and an unset entry takes the browser's default\n * @internal\n */\nexport const cpuSubmission: {\n  forward?: number;\n  shadow?: number;\n} = {};\n\nconst CPU_SUBMISSION_WEBKIT = { forward: 50_000, shadow: 20_000 } as const;\n\nlet _webKit: boolean | undefined;\n\n/**\n * The pass's {@link cpuSubmission} cap: its override, or the browser's default, `0` outside WebKit\n * @internal\n */\nexport function cpuSubmissionLimit(pass: 'forward' | 'shadow'): number {\n  const set = cpuSubmission[pass];\n  if (set !== undefined) return set;\n  _webKit ??= isMobile.apple.device || isSafari();\n  return _webKit ? CPU_SUBMISSION_WEBKIT[pass] : 0;\n}\n\nconst _batchPlanes = new Float32Array(24);\n\n/**\n * The six world-space frustum planes in a batch's local frame, renormalized to compare with local sphere radii;\n * `planes` itself for an identity batch, or else a shared scratch that the next call overwrites\n * @internal\n */\nexport function transformFrustumToBatch(planes: Float32Array, f32: Float32Array): Float32Array {\n  const b00 = f32[0];\n  const b01 = f32[1];\n  const b02 = f32[2];\n  const b10 = f32[4];\n  const b11 = f32[5];\n  const b12 = f32[6];\n  const b20 = f32[8];\n  const b21 = f32[9];\n  const b22 = f32[10];\n  const btx = f32[12];\n  const bty = f32[13];\n  const btz = f32[14];\n  if (\n    b00 === 1 &&\n    b11 === 1 &&\n    b22 === 1 &&\n    b01 === 0 &&\n    b02 === 0 &&\n    b10 === 0 &&\n    b12 === 0 &&\n    b20 === 0 &&\n    b21 === 0 &&\n    btx === 0 &&\n    bty === 0 &&\n    btz === 0\n  ) {\n    return planes;\n  }\n\n  for (let p = 0; p < 6; p++) {\n    const o = p * 4;\n    const nx = planes[o];\n    const ny = planes[o + 1];\n    const nz = planes[o + 2];\n    const tx = b00 * nx + b01 * ny + b02 * nz;\n    const ty = b10 * nx + b11 * ny + b12 * nz;\n    const tz = b20 * nx + b21 * ny + b22 * nz;\n    const inv = 1 / Math.sqrt(tx * tx + ty * ty + tz * tz);\n    _batchPlanes[o] = tx * inv;\n    _batchPlanes[o + 1] = ty * inv;\n    _batchPlanes[o + 2] = tz * inv;\n    _batchPlanes[o + 3] = (btx * nx + bty * ny + btz * nz + planes[o + 3]) * inv;\n  }\n  return _batchPlanes;\n}\n","import type { GeometryAtlasPool } from '../geometry/GeometryAtlasPool';\nimport type { View3DGlobalData } from '../scene/View3DGlobalData';\nimport type { GeometryDataStoreBuffer } from './buffers/GeometryDataStoreBuffer';\nimport type { MaterialDataStoreBuffer } from './buffers/MaterialDataStoreBuffer';\nimport type { MorphStoreBuffer } from './buffers/MorphStoreBuffer';\n\n/**\n * Whether a shared buffer the view's cached draws baked has been reallocated since it last rendered; records the\n * new versions in `data`, so each change reports once\n * @internal\n */\nexport function detectSharedCacheInvalidation(\n  atlases: GeometryAtlasPool,\n  materialStore: MaterialDataStoreBuffer,\n  data: View3DGlobalData,\n  morphStore: MorphStoreBuffer,\n  geometryStore?: GeometryDataStoreBuffer,\n): boolean {\n  let invalidated = false;\n\n  if (data.lastAtlasBufferVersion !== atlases.bufferVersion) {\n    data.lastAtlasBufferVersion = atlases.bufferVersion;\n    invalidated = true;\n  }\n\n  if (data.lastMaterialStoreBufferVersion !== materialStore.bufferVersion) {\n    data.lastMaterialStoreBufferVersion = materialStore.bufferVersion;\n    invalidated = true;\n  }\n\n  if (data.lastMorphStoreBufferVersion !== morphStore.bufferVersion) {\n    data.lastMorphStoreBufferVersion = morphStore.bufferVersion;\n    invalidated = true;\n  }\n\n  if (geometryStore && data.lastGeometryStoreBufferVersion !== geometryStore.bufferVersion) {\n    data.lastGeometryStoreBufferVersion = geometryStore.bufferVersion;\n    invalidated = true;\n  }\n\n  return invalidated;\n}\n","import { Matrix4 } from '../../../math/matrix/Matrix4';\nimport { Box } from '../../../math/shapes/Box';\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\n\n/**\n * Most cascades a directional light can have, which `LightShadow.cascades` in `Light.ts` states\n * @internal\n */\nexport const MAX_CASCADES = 4;\n\n/**\n * Fraction of each cascade's depth range spent fading into the next; both shadow bits read it\n * @internal\n */\nexport const CASCADE_BLEND_FRACTION = 0.1;\n\nconst _invViewProj = new Matrix4();\nconst _lightSpaceFromClip = new Matrix4();\n\n/**\n * `getFrustumSliceBoundsInLightSpace`'s min and max depth and centroid x and y; a typed array, so\n * a write doesn't box a fresh heap number\n */\nconst _sliceBounds = new Float64Array(4);\n\n/**\n * Cascade split depths, by the practical split scheme of GPU Gems 3, chapter 10\n * @param near - Camera near plane distance\n * @param far - Max shadow distance\n * @param count - Number of cascades, 1 to 4\n * @param lambda - Blend factor: 0 uniform, 1 logarithmic\n * @param out - Filled in place; the last split is `far`\n * @internal\n */\nexport function computeCascadeSplits(\n  near: number,\n  far: number,\n  count: number,\n  lambda: number,\n  out: number[],\n): number[] {\n  out.length = count;\n\n  for (let i = 1; i <= count; i++) {\n    const t = i / count;\n    const log = near * Math.pow(far / near, t);\n    const uniform = near + (far - near) * t;\n    out[i - 1] = lambda * log + (1 - lambda) * uniform;\n  }\n\n  return out;\n}\n\n/**\n * Stages the clip-to-light-space transform {@link computeCascadeMatrix} reads; call it once per light first\n * @internal\n */\nexport function prepareLightSpaceTransform(camera: Camera3D, inverseLightMatrix: Matrix4): void {\n  _invViewProj.getInverse(camera.viewProjection);\n  _lightSpaceFromClip.multiplyMatrices(inverseLightMatrix, _invViewProj);\n}\n\nfunction getFrustumSliceBoundsInLightSpace(nearZ: number, farZ: number): void {\n  const e = _lightSpaceFromClip.elements;\n  let minZ = Infinity;\n  let maxZ = -Infinity;\n  let sumX = 0;\n  let sumY = 0;\n\n  for (let k = 0; k < 2; k++) {\n    const nz = k === 0 ? nearZ : farZ;\n\n    for (let iy = -1; iy <= 1; iy += 2) {\n      for (let ix = -1; ix <= 1; ix += 2) {\n        const x = e[0] * ix + e[4] * iy + e[8] * nz + e[12];\n        const y = e[1] * ix + e[5] * iy + e[9] * nz + e[13];\n        const z = e[2] * ix + e[6] * iy + e[10] * nz + e[14];\n        const w = e[3] * ix + e[7] * iy + e[11] * nz + e[15];\n        const lz = z / w;\n\n        sumX += x / w;\n        sumY += y / w;\n        if (lz < minZ) minZ = lz;\n        if (lz > maxZ) maxZ = lz;\n      }\n    }\n  }\n\n  _sliceBounds[0] = minZ;\n  _sliceBounds[1] = maxZ;\n  _sliceBounds[2] = sumX * 0.125;\n  _sliceBounds[3] = sumY * 0.125;\n}\n\nfunction distanceToNdcZ(camera: Camera3D, distance: number): number {\n  const proj = camera.projection.elements;\n  const clipZ = proj[10] * -distance + proj[14];\n  const clipW = proj[11] * -distance + proj[15];\n\n  return clipZ / clipW;\n}\n\nfunction applyOrthoZRange01(projection: Matrix4, near: number, far: number): void {\n  const te = projection.elements;\n  const zScale = 1 / (near - far);\n  te[10] = zScale;\n  te[14] = near * zScale;\n}\n\n/**\n * Snaps a window centre down to whole shadow-map texels so shadow edges don't swim; both arguments\n * are light-space world units, never the projection's normalised translation\n */\nfunction snapCentreToTexel(centre: number, halfExtent: number, mapSize: number): number {\n  const texelWorld = (2 * halfExtent) / mapSize;\n  return Math.floor(centre / texelWorld) * texelWorld;\n}\n\n/**\n * The ortho projection of one cascade: a square around the slice's bounding sphere, which keeps its\n * size from frame to frame while texel snapping keeps its position, so edges don't shimmer\n * @param camera - Scene camera\n * @param splitNear - Near split distance from the camera\n * @param splitFar - Far split distance from the camera, within its far plane, as\n *   `ShadowRenderPassBase.updateLightShadowData` clamps it\n * @param outProjection - Receives the projection\n * @param mapSize - Shadow map size in texels\n * @param applyWebGPUZRangeFix - Map depth to 0 to 1 for WebGPU; `false` keeps WebGL's -1 to 1\n * @internal\n */\nexport function computeCascadeMatrix(\n  camera: Camera3D,\n  splitNear: number,\n  splitFar: number,\n  outProjection: Matrix4,\n  mapSize: number,\n  applyWebGPUZRangeFix = true,\n): void {\n  const nearZ = distanceToNdcZ(camera, splitNear);\n  const farZ = distanceToNdcZ(camera, splitFar);\n\n  getFrustumSliceBoundsInLightSpace(nearZ, farZ);\n\n  const pe = camera.projection.elements;\n  const spread = camera.mode === 'orthographic' ? 1 : splitFar;\n  const halfFarH = spread / pe[5];\n  const halfFarW = spread / pe[0];\n  const halfDepth = (splitFar - splitNear) * 0.5;\n  const r = Math.sqrt(halfFarW * halfFarW + halfFarH * halfFarH + halfDepth * halfDepth);\n\n  const near = -_sliceBounds[1] - r * DEPTH_EXTENSION;\n  const far = -_sliceBounds[0];\n\n  const centreX = snapCentreToTexel(_sliceBounds[2], r, mapSize);\n  const centreY = snapCentreToTexel(_sliceBounds[3], r, mapSize);\n\n  outProjection.makeOrthographic(centreX - r, centreX + r, centreY + r, centreY - r, near, far);\n\n  if (applyWebGPUZRangeFix) applyOrthoZRange01(outProjection, near, far);\n}\n\nconst _lightSpaceBox = new Box();\n\n/** Footprint margin, as a fraction of the fitted box, so an edge caster's shadow still lands inside */\nconst FIXED_BOX_PAD = 0.05;\n\n/**\n * How far a shadow frustum reaches toward the light, in multiples of its half-width, so the depth\n * range scales with the scene; the `bias` option is a fraction of that range\n */\nconst DEPTH_EXTENSION = 4;\n\n/**\n * The ortho projection of a directional light's fixed shadow box, padded and texel-snapped\n * @internal\n */\nexport function computeFixedBoxMatrix(\n  boundsWorld: Box,\n  inverseLightMatrix: Matrix4,\n  outProjection: Matrix4,\n  mapSize: number,\n  applyWebGPUZRangeFix = true,\n): void {\n  boundsWorld.applyMatrix4(inverseLightMatrix, _lightSpaceBox);\n\n  const { min, max } = _lightSpaceBox;\n  const halfX = (max.x - min.x) * 0.5 * (1 + 2 * FIXED_BOX_PAD);\n  const halfY = (max.y - min.y) * 0.5 * (1 + 2 * FIXED_BOX_PAD);\n\n  const centreX = snapCentreToTexel((min.x + max.x) * 0.5, halfX, mapSize);\n  const centreY = snapCentreToTexel((min.y + max.y) * 0.5, halfY, mapSize);\n\n  const near = -max.z - Math.max(halfX, halfY) * DEPTH_EXTENSION;\n  const far = -min.z;\n\n  outProjection.makeOrthographic(centreX - halfX, centreX + halfX, centreY + halfY, centreY - halfY, near, far);\n\n  if (applyWebGPUZRangeFix) applyOrthoZRange01(outProjection, near, far);\n}\n","import { DEG_TO_RAD, TextureSource, RenderTarget } from 'pixi.js';\n\nimport type { Matrix4 } from '../../../math/matrix/Matrix4';\nimport type { Light } from '../../../scene/lights/Light';\nimport type { SpotLight } from '../../../scene/lights/SpotLight';\nimport type { CameraData } from '../../CameraData';\nimport type { ShadowDataGpu } from '../../gpu/ShadowRenderPassGpu';\nimport { MAX_CASCADES } from './csmUtils';\n\nconst MAX_SHADOW_LIGHTS = 4;\n\n/**\n * Shadow map resolution preset\n *\n * The width and height in texels of each shadow map: `'low'` 512, `'medium'` 1024, `'high'` 2048,\n * `'ultra'` 4096. Each map takes 4 MB of GPU memory at `'medium'`, and each step up takes four\n * times as much. Set per view through\n * {@link View3D#shadowQuality}.\n * @example\n * ```ts\n * const view = new View3D({ width: 800, height: 600, shadowQuality: 'high' });\n * ```\n * @category rendering\n * @standard\n */\nexport type ShadowQuality = 'low' | 'medium' | 'high' | 'ultra';\n\n/**\n * Shadow map size per side for each preset, which {@link ShadowQuality} lists\n * @internal\n */\nexport const SHADOW_QUALITY_SIZE: Record<ShadowQuality, number> = {\n  low: 512,\n  medium: 1024,\n  high: 2048,\n  ultra: 4096,\n};\n\n/**\n * How soft shadow edges are\n *\n * A wider filter softens the edges and costs more texture reads per shadowed pixel:\n * - `'hard'`: one read; the crispest, cheapest edge, and the friendliest to mobile.\n * - `'pcf'`: four reads; smooth edges at low cost. The default.\n * - `'pcf-high'`: nine reads; the widest, softest edge, for higher-end devices.\n *\n * On most GPUs each read blends four neighbouring texels, so even `'hard'` has a slightly soft\n * edge. Set per view through {@link View3D#shadowFilter}.\n * @example\n * ```ts\n * view3d.shadowFilter = 'pcf-high';\n * ```\n * @category rendering\n * @standard\n */\nexport type ShadowFilter = 'hard' | 'pcf' | 'pcf-high';\n\n/**\n * One cascade of a light's shadow: its camera, and the fields `ShadowDataList.ts` packs into its `uShadowData` slot\n * @internal\n */\nexport interface CascadeSlot {\n  cameraData: CameraData;\n  bias: number;\n  normalBias: number;\n  mapSize: number;\n  /**\n   * The light's cascade count on cascade 0 of a light with more than one; `0` elsewhere, which the\n   * shadow bits read as a plain shadow\n   */\n  cascadeCount: number;\n  /** Where each cascade ends, on cascade 0 of a cascaded light, refilled in place; `null` elsewhere */\n  splits: number[] | null;\n  needsRender: boolean;\n}\n\n/**\n * Whether a light draws its shadow this frame; the WebGPU pass asks in both prepare and render, so\n * render finds the cull results prepare staged\n * @internal\n */\nexport function castsShadowThisFrame(light: Light): boolean {\n  return !!(light.castShadow && light._gpuShadowData && light._worldVisible && light._shadowDataIndex >= 0);\n}\n\n/**\n * Frees a light's cascade camera buffers, which pixi's GC skips on WebGPU, and pools its cull results;\n * `Light._releaseShadowState` drops the data after, so no result goes back to the pool twice\n * @internal\n */\nexport function releaseShadowCascades(data: ShadowDataGpu): void {\n  const cascades = data.cascades;\n  if (cascades) {\n    for (let i = 0; i < cascades.length; i++) cascades[i]?.cameraData.destroy();\n  }\n\n  data.cullResults?.release();\n}\n\n/**\n * Whether a cascade skips re-rendering this frame at its update rate\n * @param updateRate - The cascade's update rate: 1 every frame, N every Nth, 0 only on a refresh\n * @param frameCount - The shadow pass's frame counter\n * @param forceUpdate - Whether a refresh was requested\n * @internal\n */\nexport function cascadeRenderSkip(updateRate: number, frameCount: number, forceUpdate: boolean): boolean {\n  return !forceUpdate && (updateRate === 0 || (updateRate > 1 && frameCount % updateRate !== 0));\n}\n\n/**\n * A cascade's update rate from `shadow.update`: `'manual'` is 0, and a missing array entry is 1\n * @internal\n */\nexport function updateRateFor(update: number | number[] | 'manual', cascadeIndex: number): number {\n  if (update === 'manual') return 0;\n  if (typeof update === 'number') return update;\n  return update[cascadeIndex] ?? 1;\n}\n\n/** @internal */\nexport const MAX_SHADOW_SLOTS = MAX_SHADOW_LIGHTS * MAX_CASCADES;\n\n/**\n * Cascade slots a light fills: its clamped cascade count, or 1 for a fixed box or a spot light\n * @internal\n */\nexport function cascadeCountFor(light: Light): number {\n  if (light.type !== 'directional' || light.shadow.cascades === undefined) return 1;\n  return Math.min(Math.max(light.shadow.cascades, 1), MAX_CASCADES);\n}\n\n/**\n * A shadow map render target; the caller destroys the depth texture, since destroying the target leaves it\n * @internal\n */\nexport function createShadowRenderTarget(quality: ShadowQuality, layers: number): RenderTarget {\n  const size = SHADOW_QUALITY_SIZE[quality];\n\n  const shadowMap = new TextureSource({\n    width: size,\n    height: size,\n    format: 'depth32float',\n    scaleMode: 'linear',\n    viewDimension: '2d-array',\n    autoGenerateMipmaps: false,\n    arrayLayerCount: layers,\n    compare: 'less',\n  });\n\n  return new RenderTarget({\n    colorTextures: 0,\n    depthStencilTexture: shadowMap,\n  });\n}\n\n/**\n * A spot light's shadow view and projection: twice its cone angle wide, from 1 world unit to its\n * `range`, or 1000 without one (issue #473)\n * @internal\n */\nexport function updateSpotShadowMatrices(\n  spotLight: SpotLight,\n  inverseLightMatrix: Matrix4,\n  lightProjectionMatrix: Matrix4,\n  applyWebGPUZRangeFix: boolean,\n): void {\n  inverseLightMatrix.getInverse(spotLight.worldTransform);\n\n  const range = spotLight.range || 1000;\n  const near = 1;\n  const far = range;\n\n  lightProjectionMatrix.makePerspective(spotLight.coneAngle * 2 * DEG_TO_RAD, 1, near, far);\n\n  if (applyWebGPUZRangeFix) {\n    const te = lightProjectionMatrix.elements;\n    te[10] = far / (near - far);\n    te[14] = (far * near) / (near - far);\n  }\n}\n","import { UniformGroup } from 'pixi.js';\nimport type { UniformData } from 'pixi.js';\n\nimport { MAX_LIGHTS } from './lightLimits';\nimport { MAX_SHADOW_SLOTS } from './render-passes/shadow/shadowPassUtils';\n\n/**\n * Builds the uniform group every 3D shader reads as `global`, its keys in the order `globalBitGpu` and\n * `globalBitGl` declare them, since pixi lays the buffer out in key order. It's static, so packed lights and\n * shadows upload only when each pipe's `_updateGlobalUniforms` calls `update()`, every frame.\n * @param lightData - `LightDataList.data`, held as `uLightData`, so packing a light writes the uniform.\n * @param shadowData - `ShadowDataList.data`, held as `uShadowData`.\n * @param extra - A backend's own uniforms, laid out before the light data.\n * @internal\n */\nexport function createGlobalUniformGroup<TExtra extends Record<string, UniformData> = Record<never, UniformData>>(\n  lightData: Float32Array,\n  shadowData: Float32Array,\n  extra?: TExtra,\n) {\n  return new UniformGroup(\n    {\n      uGlobalLightParams: { value: new Float32Array([0, 0, 0, 0]), type: 'vec4<f32>' },\n      uTime: { value: 0, type: 'f32' },\n      uFogColor: { value: new Float32Array([0, 0, 0]), type: 'vec3<f32>' },\n      uDisplayExposure: { value: 1, type: 'f32' },\n      uFogParams: { value: new Float32Array([0, 0, 0]), type: 'vec3<f32>' },\n      uExposure: { value: 1, type: 'f32' },\n      uHemisphereSky: { value: new Float32Array([0, 0, 0]), type: 'vec3<f32>' },\n      uHemisphereGround: { value: new Float32Array([0, 0, 0]), type: 'vec3<f32>' },\n      uHemisphereUp: { value: new Float32Array([0, 1, 0]), type: 'vec3<f32>' },\n      ...(extra as TExtra),\n      uLightData: { value: lightData, type: 'vec4<f32>', size: MAX_LIGHTS * 4 },\n      uShadowData: { value: shadowData, type: 'vec4<f32>', size: MAX_SHADOW_SLOTS * 6 },\n    },\n    { isStatic: true, ubo: true },\n  );\n}\n\n/** @internal */\nexport type GlobalUniformGroup<TExtra extends Record<string, UniformData> = Record<never, UniformData>> = ReturnType<\n  typeof createGlobalUniformGroup<TExtra>\n>;\n","import type { ShaderBitTemplate } from '../shader/ShaderBitTemplate';\n\n/**\n * The GLSL version of `brdfLutWgslTemplate`, without its y flip, since WebGL puts texture row 0 at clip y = -1\n * @internal\n */\nexport const brdfLutGlslTemplate: ShaderBitTemplate = {\n  bindGroups: ['local'],\n  gl: {\n    vertex: /* glsl */ `#version 300 es\n      {{header}}\n      void main() {\n          gl_Position = vec4(aPosition, 0.0, 1.0);\n          vUv = aPosition * 0.5 + 0.5;\n      }\n    `,\n    fragment: /* glsl */ `#version 300 es\n      {{header}}\n\n      float geometrySchlickGGX(float NdotV, float roughness) {\n          float a = roughness;\n          float k = (a * a) / 2.0;\n          return NdotV / (NdotV * (1.0 - k) + k);\n      }\n\n      float geometrySmith(vec3 N, vec3 V, vec3 L, float roughness) {\n          float NdotV = max(dot(N, V), 0.0);\n          float NdotL = max(dot(N, L), 0.0);\n          float ggx1 = geometrySchlickGGX(NdotV, roughness);\n          float ggx2 = geometrySchlickGGX(NdotL, roughness);\n          return ggx1 * ggx2;\n      }\n\n      vec2 integrateBRDF(float NdotV, float roughness, uint sampleCount) {\n          vec3 V = vec3(sqrt(1.0 - NdotV * NdotV), 0.0, NdotV);\n          vec3 N = vec3(0.0, 0.0, 1.0);\n\n          float A = 0.0;\n          float B = 0.0;\n\n          for(uint i = 0u; i < sampleCount; i++) {\n              vec2 Xi = hammersley(i, sampleCount);\n              vec3 H = importanceSampleGGX(Xi, N, roughness);\n              vec3 L = normalize(2.0 * dot(V, H) * H - V);\n\n              float NdotL = max(L.z, 0.0);\n              float NdotH = max(H.z, 0.0);\n              float VdotH = max(dot(V, H), 0.0);\n\n              if(NdotL > 0.0) {\n                  float G = geometrySmith(N, V, L, roughness);\n                  float G_Vis = (G * VdotH) / (NdotH * NdotV);\n                  float Fc = pow(1.0 - VdotH, 5.0);\n\n                  A += (1.0 - Fc) * G_Vis;\n                  B += Fc * G_Vis;\n              }\n          }\n\n          return vec2(A / float(sampleCount), B / float(sampleCount));\n      }\n\n      out vec4 fragColor;\n\n      void main() {\n          float NdotV = vUv.x;\n          float roughness = vUv.y;\n          float clampedNdotV = max(NdotV, 0.001);\n          float clampedRoughness = max(roughness, 0.01);\n          \n          vec2 result = integrateBRDF(clampedNdotV, clampedRoughness, uint(sampleCount));\n          fragColor = vec4(result.x, result.y, 0.0, 1.0);\n      }\n    `,\n  },\n};\n","import type { ShaderBitTemplate } from '../shader/ShaderBitTemplate';\n\n/**\n * WGSL shader for the BRDF table; `k = roughness² / 2` is Karis's choice for IBL, not the one for direct light\n *\n * The vertex stage flips y, since WebGPU puts texture row 0 at clip y = +1; without it the table flips in roughness.\n * @internal\n */\nexport const brdfLutWgslTemplate: ShaderBitTemplate = {\n  bindGroups: ['local'],\n  gpu: /* wgsl */ `\n{{header}}\n\nfn geometrySchlickGGX(NdotV: f32, roughness: f32) -> f32 {\n   let a = roughness;\n   let k = (a * a) / 2.0;\n   \n   return NdotV / (NdotV * (1.0 - k) + k);\n}\n\nfn geometrySmith(N: vec3<f32>, V: vec3<f32>, L: vec3<f32>, roughness: f32) -> f32 {\n   let NdotV = max(dot(N, V), 0.0);\n   let NdotL = max(dot(N, L), 0.0);\n   let ggx1 = geometrySchlickGGX(NdotV, roughness);\n   let ggx2 = geometrySchlickGGX(NdotL, roughness);\n   \n   return ggx1 * ggx2;\n}\n\nfn integrateBRDF(NdotV: f32, roughness: f32, sampleCount: u32) -> vec2<f32> {\n   let V = vec3<f32>(sqrt(1.0 - NdotV * NdotV), 0.0, NdotV);\n   let N = vec3<f32>(0.0, 0.0, 1.0);\n   \n   var A = 0.0;\n   var B = 0.0;\n   \n   for (var i = 0u; i < sampleCount; i++) {\n       let Xi = hammersley(i, sampleCount);\n       let H = importanceSampleGGX(Xi, N, roughness);\n       let L = normalize(2.0 * dot(V, H) * H - V);\n       \n       let NdotL = max(L.z, 0.0);\n       let NdotH = max(H.z, 0.0);\n       let VdotH = max(dot(V, H), 0.0);\n       \n       if NdotL > 0.0 {\n           let G = geometrySmith(N, V, L, roughness);\n           let G_Vis = (G * VdotH) / (NdotH * NdotV);\n           let Fc = pow(1.0 - VdotH, 5.0);\n           \n           A += (1.0 - Fc) * G_Vis;\n           B += Fc * G_Vis;\n       }\n   }\n   \n   A = A / f32(sampleCount);\n   B = B / f32(sampleCount);\n   \n   return vec2<f32>(A, B);\n}\n\n@vertex\nfn mainVertex(input: VertexInput) -> VertexOutput {\n  var output: VertexOutput;\n  output.position = vec4<f32>(input.aPosition, 0.0, 1.0);\n  output.vUv = vec2<f32>(input.aPosition.x * 0.5 + 0.5, -input.aPosition.y * 0.5 + 0.5);\n  return output;\n}\n\n@fragment\nfn mainFragment(input: FragmentInput) -> @location(0) vec4<f32> {\n   let NdotV = input.vUv.x;\n   let roughness = input.vUv.y;\n   \n   let clampedNdotV = max(NdotV, 0.001);\n   \n   let clampedRoughness = max(roughness, 0.01);\n   \n   let result = integrateBRDF(clampedNdotV, clampedRoughness, u32(local.sampleCount));\n   \n   return vec4<f32>(result.x, result.y, 0.0, 1.0);\n}\n`,\n};\n","import { BindGroup, RenderTexture, State, Texture, UniformGroup } from 'pixi.js';\nimport type { WebGPURenderer, WebGLRenderer } from 'pixi.js';\n\nimport { fullscreenTriangleGeometry } from '../fullscreenTriangleGeometry';\nimport { iblSamplingFuncsBit } from '../shader/bits/iblSamplingFuncsBit';\nimport type { ShaderBit } from '../shader/ShaderBit';\nimport type { ShaderBitTemplate } from '../shader/ShaderBitTemplate';\nimport { brdfLutGlslTemplate } from './brdfLutGlslTemplate';\nimport { brdfLutWgslTemplate } from './brdfLutWgslTemplate';\n\nconst brdfLutTemplate: ShaderBitTemplate = {\n  bindGroups: ['local'],\n  gpu: brdfLutWgslTemplate.gpu,\n  gl: brdfLutGlslTemplate.gl,\n};\n\ninterface GenerateBrdfLutOptions {\n  renderer: WebGPURenderer | WebGLRenderer;\n  size?: number;\n  sampleCount?: number;\n}\n\n/**\n * Renders the split-sum BRDF table IBL reads, in `rg16float` since 8 bits band visibly once tone-mapped; it restores\n * the caller's bind with `getBindState`, not `pop`, which inside a 2D filter would land on the screen\n * @internal\n */\nexport function generateBrdfLut(options: GenerateBrdfLutOptions): Texture {\n  const { renderer } = options;\n\n  const size = options.size ?? 256;\n  const sampleCount = options.sampleCount ?? 1024;\n\n  const localBit: ShaderBit = {\n    name: 'brdfLut',\n    requires: [iblSamplingFuncsBit],\n    attributes: {\n      aPosition: 'float32x2',\n    },\n    interStage: {\n      vUv: 'vec2<f32>',\n    },\n    bindings: {\n      local: {\n        sampleCount: 'f32',\n      },\n    },\n  };\n\n  const local = new BindGroup({\n    local: new UniformGroup({\n      sampleCount: { value: sampleCount, type: 'f32' },\n    }),\n  });\n  const shader = renderer.material3d.compileIsolatedShader([localBit], brdfLutTemplate, {\n    0: local,\n  });\n\n  const textureSource = RenderTexture.create({\n    width: size,\n    height: size,\n    format: 'rg16float',\n  }).source;\n\n  const texture = new Texture({\n    source: textureSource,\n  });\n\n  const geometry = fullscreenTriangleGeometry();\n\n  const savedBind = renderer.renderTarget.renderTarget ? renderer.renderTarget.getBindState() : null;\n\n  renderer.renderTarget.bind({ target: textureSource, clear: true });\n\n  renderer.encoder.draw({\n    geometry,\n    shader,\n    state: State.default2d,\n  });\n\n  if (savedBind) renderer.renderTarget.bind(savedBind);\n\n  local.destroy();\n  shader.destroy();\n\n  return texture;\n}\n","import { DEG_TO_RAD } from 'pixi.js';\n\nimport { writeLinearRgb } from '../materials/BaseMaterial3D';\nimport type { TypedFixedArray } from '../math/utils/misc';\nimport type { Light } from '../scene/lights/Light';\nimport type { PointLight } from '../scene/lights/PointLight';\nimport type { SpotLight } from '../scene/lights/SpotLight';\nimport { FLOATS_PER_LIGHT, MAX_LIGHTS } from './lightLimits';\nimport { cascadeCountFor } from './render-passes/shadow/shadowPassUtils';\n\n/** Smallest radius a light packs, which `PointLight.radius` in `PointLight.ts` states */\nconst MIN_LIGHT_RADIUS = 0.01;\n\nconst rangeSquared = (range: number): number => (range > 0 ? range * range : 0);\n\nconst radiusToFourth = (radius: number): number => {\n  const r = radius > MIN_LIGHT_RADIUS ? radius : MIN_LIGHT_RADIUS;\n  const rSq = r * r;\n  return rSq * rSq;\n};\n\n/** Writes the light's unit forward direction, which the shader reads without normalizing */\nconst writeNormalizedDirection = (buffer: Float32Array, offset: number, elements: TypedFixedArray<16>) => {\n  const dx = -elements[8];\n  const dy = -elements[9];\n  const dz = -elements[10];\n  const invLen = 1 / Math.sqrt(dx * dx + dy * dy + dz * dz);\n  buffer[offset + 8] = dx * invLen;\n  buffer[offset + 9] = dy * invLen;\n  buffer[offset + 10] = dz * invLen;\n};\n\n/**\n * Packs one light at `offset`, in the layout `LightStructGpu` and `LightStructGl` in `shaderStructs.ts` mirror,\n * with the shadow slots `prepareShadow` claimed for it, so that must run first\n * @internal\n */\nexport const writeLight = (light: Light, buffer: Float32Array, offset: number) => {\n  const worldTransform = light.worldTransform;\n  const elements = worldTransform.elements;\n\n  buffer[offset] = elements[12];\n  buffer[offset + 1] = elements[13];\n  buffer[offset + 2] = elements[14];\n\n  writeLinearRgb(buffer, offset + 4, light.color, light.intensity);\n\n  if (light.type === 'directional') {\n    buffer[offset + 3] = 0;\n    buffer[offset + 7] = 0;\n\n    writeNormalizedDirection(buffer, offset, elements);\n  } else if (light.type === 'point') {\n    buffer[offset + 3] = 1;\n    const point = light as PointLight;\n    buffer[offset + 7] = rangeSquared(point.range);\n    buffer[offset + 15] = radiusToFourth(point.radius);\n  } else if (light.type === 'spot') {\n    buffer[offset + 3] = 2;\n    const spot = light as SpotLight;\n    buffer[offset + 7] = rangeSquared(spot.range);\n    buffer[offset + 15] = radiusToFourth(spot.radius);\n\n    writeNormalizedDirection(buffer, offset, elements);\n\n    const coneAngle = spot.coneAngle * DEG_TO_RAD;\n\n    buffer[offset + 11] = Math.cos(coneAngle);\n    buffer[offset + 12] = Math.cos(coneAngle * (1 - spot.penumbra));\n  }\n\n  buffer[offset + 13] = light._shadowDataIndex;\n  buffer[offset + 14] = cascadeCountFor(light);\n};\n\n/**\n * The view's non-ambient lights, `FLOATS_PER_LIGHT` floats each as `writeLight` packs them; `data` is `uLightData`'s\n * value on both backends, so it never reallocates, and `add` doesn't bounds-check: callers stop at `MAX_LIGHTS`\n * @internal\n */\nexport class LightDataList {\n  /** Entries at and above `count` are stale */\n  public readonly data = new Float32Array(MAX_LIGHTS * FLOATS_PER_LIGHT);\n  private _count = 0;\n\n  get count(): number {\n    return this._count;\n  }\n\n  public reset(): void {\n    this._count = 0;\n  }\n\n  public add(light: Light): void {\n    writeLight(light, this.data, this._count * FLOATS_PER_LIGHT);\n    this._count++;\n  }\n}\n","import { Rectangle, RendererType } from 'pixi.js';\nimport type { Renderer, RenderTarget } from 'pixi.js';\n\nimport type { Camera3D } from '../../scene/cameras/Camera3D';\nimport { getCameraData } from '../CameraData';\nimport type { ReadonlyRect, RenderSession } from '../render-passes/RenderSession';\n\nconst _tempRect = new Rectangle();\n\nconst _sourceBounds = { x: 0, y: 0, width: 0, height: 0 };\n\n/**\n * Pixi's rounding in `RenderTargetSystem.bind()`, which truncates toward zero; `Math.round` differs on\n * the negative frame of a view scrolled off the left or top edge, and leaves a one-pixel seam\n */\nfunction roundLikePixi(value: number): number {\n  return (value + 0.5) | 0;\n}\n\nfunction placeViewport(\n  frame: Rectangle,\n  scale: number,\n  originX: number,\n  originY: number,\n  bounds: ReadonlyRect,\n  flipY: boolean,\n  out: Rectangle,\n): Rectangle {\n  let x = roundLikePixi((frame.x - originX) * scale);\n  let y = roundLikePixi((frame.y - originY) * scale);\n  let w = roundLikePixi(frame.width * scale);\n  let h = roundLikePixi(frame.height * scale);\n\n  if (x < 0) {\n    w += x;\n    x = 0;\n  }\n  if (y < 0) {\n    h += y;\n    y = 0;\n  }\n  if (x > bounds.width - 1) x = bounds.width - 1;\n  if (y > bounds.height - 1) y = bounds.height - 1;\n  if (w > bounds.width - x) w = bounds.width - x;\n  if (h > bounds.height - y) h = bounds.height - y;\n  if (w < 1) w = 1;\n  if (h < 1) h = 1;\n\n  if (flipY) y = bounds.height - h - y;\n\n  out.x = bounds.x + x;\n  out.y = bounds.y + y;\n  out.width = w;\n  out.height = h;\n  return out;\n}\n\n/**\n * Matches pixi's `RenderTargetSystem.bind()` viewport, so the graph can narrow with `setViewport` and skip a rebind,\n * which on WebGPU ends the render pass; adds the WebGL canvas's y flip, which a bind applies and `setViewport` skips\n * @param frame - In logical pixels.\n * @param target - The target the viewport applies to.\n * @param renderer - The renderer.\n * @param out - Receives the viewport, in physical pixels.\n * @internal\n */\nexport function frameToPhysicalViewport(\n  frame: Rectangle,\n  target: RenderTarget,\n  renderer: Renderer,\n  out: Rectangle,\n): Rectangle {\n  const source = target.colorTexture.source;\n\n  _sourceBounds.width = source.pixelWidth;\n  _sourceBounds.height = source.pixelHeight;\n\n  const flipY = renderer.type === RendererType.WEBGL && target.isRoot;\n\n  return placeViewport(frame, source.resolution, 0, 0, _sourceBounds, flipY, out);\n}\n\n/**\n * `null` when the camera's frame is empty; flips y on the WebGL canvas as `frameToPhysicalViewport` does\n * @param camera - The pass's camera.\n * @param session - The frame's render session.\n * @param bounds - The target's content rect, in its texels.\n * @param sceneResolution - `RenderGraph.resolution`.\n * @internal\n */\nexport function cameraFrameToPhysicalViewport(\n  camera: Camera3D,\n  session: RenderSession,\n  bounds: ReadonlyRect,\n  sceneResolution: number,\n): Rectangle | null {\n  const frame = getCameraData(camera).frame;\n  if (frame.width <= 0 || frame.height <= 0) return null;\n\n  const inTexture = camera.renderTexture !== null;\n  const scale = inTexture ? 1 : sceneResolution;\n  const viewFrame = getCameraData(session.view3d.camera).frame;\n  const originX = inTexture ? 0 : viewFrame.x;\n  const originY = inTexture ? 0 : viewFrame.y;\n  const flipY = !inTexture && session.renderer.type === RendererType.WEBGL && session.defaultTarget.isRoot;\n\n  return placeViewport(frame, scale, originX, originY, bounds, flipY, _tempRect);\n}\n","import { Bounds, Matrix, Point, Rectangle, RendererType } from 'pixi.js';\nimport type { PointData, WebGPURenderer } from 'pixi.js';\n\nimport { Matrix4 } from '../math/matrix/Matrix4';\nimport type { Camera3D } from '../scene/cameras/Camera3D';\nimport type { View3D } from '../scene/View3D';\nimport { getCameraData } from './CameraData';\nimport { cameraFrameToPhysicalViewport, frameToPhysicalViewport } from './render-graph/frameToPhysicalViewport';\nimport type { RenderSession } from './render-passes/RenderSession';\n\nconst _ndcToLocal = new Matrix4();\nconst _localToTarget = new Matrix4();\nconst _targetToFrame = new Matrix4();\nconst _screenBounds = new Rectangle();\nconst _targetBounds = new Rectangle();\nconst _uvScale = new Point();\nconst _local = new Rectangle();\nconst _placement = new Matrix();\nconst _bounds = new Bounds();\n\nfunction placeCameraInView(view3d: View3D, camera: Camera3D, rendererOffset: PointData): void {\n  const { width, height } = view3d;\n  const { x: ax, y: ay } = view3d.anchor;\n  const { x: vx, y: vy, width: vw, height: vh } = camera.viewport;\n\n  _local.set((vx - ax) * width, (vy - ay) * height, vw * width, vh * height);\n\n  _placement.copyFrom(view3d.worldTransform);\n  _placement.tx -= rendererOffset.x;\n  _placement.ty -= rendererOffset.y;\n}\n\nfunction fitFrame(local: Rectangle, placement: Matrix, bounds: Rectangle, out: Rectangle): Rectangle {\n  _bounds.clear();\n  _bounds.addFrame(local.x, local.y, local.x + local.width, local.y + local.height, placement);\n\n  out.x = _bounds.minX;\n  out.y = _bounds.minY;\n  out.width = _bounds.maxX - _bounds.minX;\n  out.height = _bounds.maxY - _bounds.minY;\n\n  return out.fit(bounds);\n}\n\n/**\n * Makes the camera's `clippingPlane` its near plane (Lengyel's oblique frustum), in GL clip space; assumes a\n * perspective projection whose X and Y rows don't mix, which an orthographic camera or a rotated View breaks\n */\nfunction applyClippingPlane(camera: Camera3D): void {\n  const plane = camera.clippingPlane;\n  if (!plane) return;\n\n  const e = camera.projection.elements;\n  const { x: nx, y: ny, z: nz } = plane.normal;\n  const nw = plane.constant;\n\n  const qx = (Math.sign(nx) + e[8]) / e[0];\n  const qy = (Math.sign(ny) + e[9]) / e[5];\n  const qz = -1;\n  const qw = (1 + e[10]) / e[14];\n\n  const s = 2 / (nx * qx + ny * qy + nz * qz + nw * qw);\n\n  e[2] = nx * s;\n  e[6] = ny * s;\n  e[10] = nz * s + 1;\n  e[14] = nw * s;\n}\n\n/**\n * Builds a camera's matrices for `local`, then maps them onto the clipped `frame` so no pixel moves when clipped;\n * they stay unflipped, as the frustum needs, and `CameraData` flips its GPU copy\n * @param camera - The camera whose matrices are rebuilt.\n * @param local - The rect the camera's `viewport` marks out.\n * @param placement - Takes `local` into the target.\n * @param frame - The clipped rect drawn, in the target's pixels.\n */\nfunction buildProjection(camera: Camera3D, local: Rectangle, placement: Matrix, frame: Rectangle): void {\n  camera.view.getInverse(camera.worldTransform);\n  camera.computeProjection(local.width / local.height, camera.projection);\n\n  const { x, y, width, height } = local;\n  const { a, b, c, d, tx, ty } = placement;\n  const { x: fx, y: fy, width: fw, height: fh } = frame;\n\n  _ndcToLocal.set(width / 2, 0, 0, x + width / 2, 0, -height / 2, 0, y + height / 2, 0, 0, 1, 0, 0, 0, 0, 1);\n  _localToTarget.set(a, c, 0, tx, b, d, 0, ty, 0, 0, 1, 0, 0, 0, 0, 1);\n  _targetToFrame.set(2 / fw, 0, 0, -(2 * fx) / fw - 1, 0, -2 / fh, 0, (2 * fy) / fh + 1, 0, 0, 1, 0, 0, 0, 0, 1);\n\n  camera.projection.premultiply(_targetToFrame.multiply(_localToTarget).multiply(_ndcToLocal));\n\n  applyClippingPlane(camera);\n  camera.viewProjection.multiplyMatrices(camera.projection, camera.view);\n  camera.frustum.setFromProjectionMatrix(camera.viewProjection);\n}\n\n/**\n * Rebuilds a camera's matrices for its place on the view's target; returns its frame, or `undefined` off-screen\n * @param view3d - The view.\n * @param camera - The camera.\n * @param screenBounds - The target's bounds.\n * @param rendererOffset - The renderer's global offset, nonzero inside a filter.\n * @internal\n */\nexport function updateCameraProjectionForView(\n  view3d: View3D,\n  camera: Camera3D,\n  screenBounds: Rectangle,\n  rendererOffset: PointData,\n): Rectangle | undefined {\n  placeCameraInView(view3d, camera, rendererOffset);\n\n  const frame = fitFrame(_local, _placement, screenBounds, getCameraData(camera).frame);\n  if (frame.width <= 0 || frame.height <= 0) return;\n\n  buildProjection(camera, _local, _placement, frame);\n\n  return frame;\n}\n\n/**\n * Rebuilds a camera's matrices for its render texture; returns its frame in texels, or `undefined` if it lands nowhere\n * @internal\n */\nexport function updateCameraProjectionForTarget(\n  camera: Camera3D,\n  targetWidth: number,\n  targetHeight: number,\n): Rectangle | undefined {\n  const { x: vx, y: vy, width: vw, height: vh } = camera.viewport;\n\n  _local.set(vx * targetWidth, vy * targetHeight, vw * targetWidth, vh * targetHeight);\n  _placement.identity();\n  _targetBounds.set(0, 0, targetWidth, targetHeight);\n\n  const frame = fitFrame(_local, _placement, _targetBounds, getCameraData(camera).frame);\n  if (frame.width <= 0 || frame.height <= 0) return;\n\n  buildProjection(camera, _local, _placement, frame);\n\n  return frame;\n}\n\n/**\n * Builds a camera's matrices and CPU-side lanes, once per session however many passes name it. The view camera\n * must go first: it fills the `session.viewport` that `sceneViewport` reads. Any other camera drawing into the\n * view takes the view's UV scale, since the pooled textures it samples are sized to the scene.\n * @internal\n */\nexport function prepareCamera(camera: Camera3D, session: RenderSession): void {\n  const cameraData = getCameraData(camera);\n  if (cameraData._currentSession === session) return;\n  cameraData._currentSession = session;\n\n  const { view3d, renderer } = session;\n\n  if (camera.view3d !== view3d) {\n    throw new Error(\n      'A render pass camera must live in the View3D it draws from. Add it to the view first, ' +\n        'e.g. `view.root.addChild(camera)`.',\n    );\n  }\n\n  const isWebGPU = renderer.type === RendererType.WEBGPU;\n  const texture = camera.renderTexture;\n\n  if (texture) {\n    const { frame, source } = texture;\n    const targetWidth = Math.round(frame.width * source.resolution);\n    const targetHeight = Math.round(frame.height * source.resolution);\n    updateCameraProjectionForTarget(camera, targetWidth, targetHeight);\n    cameraData.setViewportUvScale(1, 1);\n    _targetBounds.set(0, 0, targetWidth, targetHeight);\n  } else {\n    _screenBounds.x = 0;\n    _screenBounds.y = 0;\n    _screenBounds.width = session.defaultTarget.width;\n    _screenBounds.height = session.defaultTarget.height;\n    updateCameraProjectionForView(view3d, camera, _screenBounds, renderer.globalUniforms.globalUniformData.offset);\n\n    if (camera === view3d.camera) {\n      frameToPhysicalViewport(cameraData.frame, session.defaultTarget, renderer, session.viewport);\n    }\n\n    view3d._graph.sceneViewport(session, _targetBounds);\n    view3d._graph.setViewportUvScale(_targetBounds.width, _targetBounds.height, _uvScale);\n    cameraData.setViewportUvScale(_uvScale.x, _uvScale.y);\n  }\n\n  const viewport =\n    camera === view3d.camera\n      ? _targetBounds\n      : cameraFrameToPhysicalViewport(camera, session, _targetBounds, view3d._graph.resolution);\n\n  if (isWebGPU && viewport) cameraData.setViewport(viewport, true);\n\n  const target = texture ? renderer.renderTarget.getRenderTarget(texture) : session.defaultTarget;\n  const frontFaceInverted = renderer.renderTarget.isFrontFaceInverted(target, session.defaultTarget.flipY);\n\n  cameraData.syncFromCamera(camera, frontFaceInverted, isWebGPU, viewport);\n}\n\n/**\n * Bins the packed lights into a prepared camera's tiles, then on WebGPU uploads its uniforms, which bundles don't\n * sync; separate from `prepareCamera` because the view camera is built before the lights are packed\n * @internal\n */\nexport function uploadCamera(camera: Camera3D, session: RenderSession): void {\n  const cameraData = getCameraData(camera);\n  cameraData.prepareLightTiles(session);\n\n  const { renderer } = session;\n  if (renderer.type === RendererType.WEBGPU) {\n    (renderer as WebGPURenderer).ubo.updateUniformGroup(cameraData.uniformGroup);\n  }\n}\n","import { RendererType } from 'pixi.js';\nimport type { TEXTURE_FORMATS, WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\n/**\n * The WebGPU spec's render target pixel byte cost and component alignment, which isn't the texel\n * size: `rgba8unorm` costs 8\n */\nconst BYTE_COST: Partial<Record<TEXTURE_FORMATS, readonly [cost: number, alignment: number]>> = {\n  r8unorm: [1, 1],\n  r8uint: [1, 1],\n  r8sint: [1, 1],\n  rg8unorm: [2, 1],\n  rg8uint: [2, 1],\n  rg8sint: [2, 1],\n  rgba8unorm: [8, 1],\n  'rgba8unorm-srgb': [8, 1],\n  rgba8uint: [4, 1],\n  rgba8sint: [4, 1],\n  bgra8unorm: [8, 1],\n  'bgra8unorm-srgb': [8, 1],\n  r16uint: [2, 2],\n  r16sint: [2, 2],\n  r16float: [2, 2],\n  rg16uint: [4, 2],\n  rg16sint: [4, 2],\n  rg16float: [4, 2],\n  rgba16uint: [8, 2],\n  rgba16sint: [8, 2],\n  rgba16float: [8, 2],\n  r32uint: [4, 4],\n  r32sint: [4, 4],\n  r32float: [4, 4],\n  rg32uint: [8, 4],\n  rg32sint: [8, 4],\n  rg32float: [8, 4],\n  rgba32uint: [16, 4],\n  rgba32sint: [16, 4],\n  rgba32float: [16, 4],\n  rgb10a2unorm: [8, 4],\n  rg11b10ufloat: [8, 4],\n};\n\n/** @internal */\nexport interface ColorAttachmentFormat {\n  format: TEXTURE_FORMATS;\n  label?: string;\n}\n\n/** @internal */\nexport function assertColorAttachmentLimits(\n  passName: string,\n  colors: readonly ColorAttachmentFormat[],\n  renderer: WebGLRenderer | WebGPURenderer,\n): void {\n  let maxCount: number;\n  let maxBytes = Infinity;\n\n  if (renderer.type === RendererType.WEBGPU) {\n    const limits = (renderer as WebGPURenderer).gpu.device.limits;\n    maxCount = limits.maxColorAttachments;\n    maxBytes = limits.maxColorAttachmentBytesPerSample;\n  } else {\n    const gl = (renderer as WebGLRenderer).gl;\n    maxCount = Math.min(gl.getParameter(gl.MAX_DRAW_BUFFERS), gl.getParameter(gl.MAX_COLOR_ATTACHMENTS));\n  }\n\n  if (colors.length > maxCount) {\n    throw new Error(\n      `RenderGraph: pass \"${passName}\" attaches ${colors.length} colour textures, over this GPU's limit of ` +\n        `${maxCount}: ${colors.map((c, i) => c.label ?? `attachment ${i}`).join(', ')}. Each scene ` +\n        'output adds one to the scene passes, so list fewer.',\n    );\n  }\n\n  let bytes = 0;\n  for (let i = 0; i < colors.length; i++) {\n    const cost = BYTE_COST[colors[i].format];\n    if (!cost) continue;\n    bytes = Math.ceil(bytes / cost[1]) * cost[1] + cost[0];\n  }\n\n  if (bytes > maxBytes) {\n    const listed = colors.map((c, i) => {\n      const { label, format } = c;\n      return `${label ?? `attachment ${i}`} (${format}, ${BYTE_COST[format]?.[0] ?? '?'} bytes)`;\n    });\n    throw new Error(\n      `RenderGraph: pass \"${passName}\" needs ${bytes} bytes per pixel for its colour textures, over WebGPU's ` +\n        `limit of ${maxBytes}: ${listed.join(', ')}. Give scene outputs smaller formats or list fewer. ` +\n        'rgba8unorm counts 8 bytes, the same as rgba16float; rg16float counts 4, rg8unorm 2 and r8unorm 1.',\n    );\n  }\n}\n","import type { Camera3D } from '../../scene/cameras/Camera3D';\nimport type { RenderGraph } from './RenderGraph';\nimport type { ColorHandle, DepthHandle, ResourceHandle, TransientTextureOptions } from './ResourceHandle';\nimport type { SceneOutput } from './SceneOutput';\nimport type { GlobalTextureBindings, TextureBinding } from './TextureBinding';\n\n/**\n * How a pass uses a texture, as declared with a {@link PassBuilder} method\n *\n * - `write_attachment`: drawn into as a render target, from `writeColor` or `writeDepth`\n * - `read_attachment`: a depth attached read-only, from `readDepthAttachment`\n * - `sample`: bound for a shader to sample, from `sample`\n * - `read`: read some other way, such as a copy, from `read`\n * - `produce`: written some other way, such as a copy or compute work, from `produce`\n * @category rendering\n * @advanced\n */\nexport type AccessMode = 'write_attachment' | 'read_attachment' | 'sample' | 'read' | 'produce';\n\n/**\n * One resource access declared by a pass during `setup()`\n * @category rendering\n * @advanced\n */\nexport interface ResourceAccess {\n  /** The texture the pass uses */\n  handle: ResourceHandle;\n  /** How the pass touches it */\n  mode: AccessMode;\n  /** Where the texture is bound; set only for `'sample'` */\n  binding?: TextureBinding;\n}\n\n/** @internal */\nexport interface PassRecord {\n  accesses: ResourceAccess[];\n  hasSideEffect: boolean;\n}\n\n/**\n * Declares what a pass reads and writes; {@link GraphRenderPass#setup} receives one\n *\n * Each declaration returns its handle, so `const color = b.writeColor(b.targetColor)` captures it\n * inline.\n * @category rendering\n * @advanced\n */\nexport class PassBuilder {\n  private _current: PassRecord | null = null;\n  private _targetColor!: ColorHandle;\n  private _targetDepth!: DepthHandle;\n\n  constructor(private readonly _graph: RenderGraph) {}\n\n  /**\n   * The colour this pass draws into: {@link RenderGraph#sceneColor}, or for a pass whose camera has a\n   * render texture, that camera's own target\n   *\n   * A pass that presents the finished picture writes {@link PassBuilder#defaultColor} instead.\n   */\n  public get targetColor(): ColorHandle {\n    this._mustBeInSetup('targetColor');\n    return this._targetColor;\n  }\n\n  /** Depth paired with {@link PassBuilder#targetColor} */\n  public get targetDepth(): DepthHandle {\n    this._mustBeInSetup('targetDepth');\n    return this._targetDepth;\n  }\n\n  /** The colour of the view's own target; see {@link RenderGraph#defaultColor} */\n  public get defaultColor(): ColorHandle {\n    return this._graph.defaultColor;\n  }\n\n  /** Depth paired with {@link PassBuilder#defaultColor} */\n  public get defaultDepth(): DepthHandle {\n    return this._graph.defaultDepth;\n  }\n\n  /**\n   * The texture of a scene output the graph attaches, for this pass to write or read; see\n   * {@link RenderGraph#getSceneOutput}\n   * @param output - An output in the graph's `sceneOutputs`\n   * @returns The output's texture handle\n   */\n  public getSceneOutput(output: SceneOutput): ColorHandle {\n    return this._graph.getSceneOutput(output);\n  }\n\n  /**\n   * Declares that this pass draws into `handle` as a render target\n   *\n   * The first pass each frame to write a texture the graph allocated clears it, unless that pass\n   * writes it with {@link PassBuilder#produce} instead; a texture you import with\n   * {@link RenderGraph#importColor} keeps its content. Later writers draw over earlier ones, and a pass that writes several colours\n   * attaches them in the order it declares them.\n   *\n   * A pass's target is exactly the attachments it declares, so to draw into this pass's target,\n   * declare both `writeColor(b.targetColor)` and `writeDepth(b.targetDepth)`. Declared alone, the\n   * colour gets a target of its own: over the screen that isn't pixi's target, and inside a 2D\n   * filter it loses the view's place on the filter's texture.\n   * @param handle - The colour resource this pass writes as an attachment.\n   * @returns The same handle, for inline capture.\n   */\n  public writeColor(handle: ColorHandle): ColorHandle {\n    const record = this._mustBeInSetup('writeColor');\n    record.accesses.push({ handle, mode: 'write_attachment' });\n    return handle;\n  }\n\n  /**\n   * Declares that this pass draws into the depth `handle`; see {@link PassBuilder#writeColor}\n   * @param handle - The depth resource this pass writes as an attachment.\n   * @returns The same handle, for inline capture.\n   */\n  public writeDepth(handle: DepthHandle): DepthHandle {\n    const record = this._mustBeInSetup('writeDepth');\n    record.accesses.push({ handle, mode: 'write_attachment' });\n    return handle;\n  }\n\n  /**\n   * Declares that this pass writes `handle` itself, with a copy, compute work or targets it binds\n   *\n   * The graph counts `handle` as written, as for {@link PassBuilder#writeColor}, but binds and clears\n   * nothing for it; get the texture in `render` with {@link RenderGraph#getTexture}.\n   * @param handle - The resource this pass produces.\n   * @returns The same handle, for inline capture.\n   */\n  public produce<H extends ResourceHandle>(handle: H): H {\n    const record = this._mustBeInSetup('produce');\n    record.accesses.push({ handle, mode: 'produce' });\n    return handle;\n  }\n\n  /**\n   * Declares a read-only depth attachment: the pass depth-tests against `handle` without\n   * writing it\n   * @param handle - The depth resource attached read-only.\n   * @returns The same handle, for inline capture.\n   */\n  public readDepthAttachment(handle: DepthHandle): DepthHandle {\n    const record = this._mustBeInSetup('readDepthAttachment');\n    record.accesses.push({ handle, mode: 'read_attachment' });\n    return handle;\n  }\n\n  /**\n   * The view's global texture bindings, to pass to {@link PassBuilder#sample}\n   * @example\n   * ```ts\n   * b.sample(opaqueDepth, b.globalTextureBindings.opaqueDepth);\n   * ```\n   */\n  public get globalTextureBindings(): GlobalTextureBindings {\n    return this._graph.globalTextureBindings;\n  }\n\n  /**\n   * Declares that this pass samples `handle` through `binding`\n   *\n   * The graph puts the frame's texture in the binding before the pass renders. A texture the graph\n   * allocated that another pass attaches as a render target needs a bind group this pass owns;\n   * {@link RenderGraph#compile} throws for a global binding.\n   * @param handle - The resource this pass samples.\n   * @param binding - Where the texture goes.\n   * @returns The same handle, for inline capture.\n   */\n  public sample<H extends ResourceHandle>(handle: H, binding: TextureBinding): H {\n    const record = this._mustBeInSetup('sample');\n    if (binding.styleSlot !== undefined && handle._kind === 'depth') {\n      throw new Error(\n        'PassBuilder.sample: a depth handle binds as a depth view, which has no sampler to bind beside it',\n      );\n    }\n    record.accesses.push({ handle, mode: 'sample', binding });\n    return handle;\n  }\n\n  /**\n   * Declares a read the graph doesn't bind, for a copy or a pass that builds its own bindings\n   *\n   * It keeps the earlier passes that write the texture running; get the texture in `render` with\n   * {@link RenderGraph#getTexture}.\n   * @param handle - The resource this pass reads.\n   * @returns The same handle, for inline capture.\n   */\n  public read<H extends ResourceHandle>(handle: H): H {\n    const record = this._mustBeInSetup('read');\n    record.accesses.push({ handle, mode: 'read' });\n    return handle;\n  }\n\n  /**\n   * Keeps this pass running when no other pass reads what it writes, for work that leaves the graph,\n   * such as a readback to the CPU\n   *\n   * The graph runs a pass only when a later pass uses what it writes, or when it writes the screen,\n   * an imported texture or a camera's target. A pass that calls this in `setup` runs too, and so do\n   * the passes it reads from.\n   *\n   * It doesn't override the pass's `condition`: on a frame the condition skips this pass, any pass\n   * that only feeds it is skipped too. The scene still writes every scene output a pass requires,\n   * every frame.\n   * @example\n   * ```ts\n   * graph.addPass({\n   *   name: 'pickReadback',\n   *   bit: RenderPassBit.NONE,\n   *   setup: (b) => {\n   *     b.read(objectIds);\n   *     b.sideEffect();\n   *   },\n   *   render: (session) => readPixelUnderPointer(graph.getTexture(objectIds, session)),\n   * });\n   * ```\n   */\n  public sideEffect(): void {\n    this._mustBeInSetup('sideEffect').hasSideEffect = true;\n  }\n\n  /**\n   * Creates a colour texture the graph allocates; see {@link RenderGraph#createColor}\n   * @param options - Size, resolution, format and label; see {@link TransientTextureOptions}.\n   * @returns The handle for the new transient colour resource.\n   */\n  public createColor(options: TransientTextureOptions = {}): ColorHandle {\n    this._mustBeInSetup('createColor');\n    return this._graph.createColor(options);\n  }\n\n  /**\n   * Creates a depth texture the graph allocates; see {@link RenderGraph#createColor}\n   * @param options - Size, resolution, format and label; see {@link TransientTextureOptions}.\n   * @returns The handle for the new transient depth resource.\n   */\n  public createDepth(options: TransientTextureOptions = {}): DepthHandle {\n    this._mustBeInSetup('createDepth');\n    return this._graph.createDepth(options);\n  }\n\n  /** @internal */\n  public _beginPass(record: PassRecord, camera?: Camera3D | null): void {\n    this._current = record;\n    if (camera?.renderTexture) {\n      const target = this._graph._cameraTarget(camera);\n      this._targetColor = target.color;\n      this._targetDepth = target.depth;\n    } else {\n      this._targetColor = this._graph.sceneColor;\n      this._targetDepth = this._graph.sceneDepth;\n    }\n  }\n\n  /** @internal */\n  public _endPass(): void {\n    this._current = null;\n  }\n\n  private _mustBeInSetup(label: string): PassRecord {\n    if (!this._current) {\n      throw new Error(`PassBuilder.${label}: called outside a pass.setup()`);\n    }\n    return this._current;\n  }\n}\n","import { RenderTarget } from 'pixi.js';\nimport type { RenderTargetDescriptor, TextureSource } from 'pixi.js';\n\n/** @internal */\nexport interface PassAttachments {\n  colors?: { texture: TextureSource }[];\n  depth?: { texture: TextureSource };\n  depthReadOnly?: boolean;\n}\n\n/** @internal */\nexport class RenderTargetCache {\n  private readonly _targets: Record<string, RenderTarget> = Object.create(null);\n\n  /** Keys of the targets this cache made; a target given to `addToCache` is pixi's, and never destroyed here */\n  private readonly _ownedKeys: Set<string> = new Set();\n\n  public get(attachments: PassAttachments): RenderTarget {\n    const key = this._renderTargetKey(attachments);\n    if (!this._targets[key]) {\n      this._targets[key] = this._createRenderTarget(attachments);\n      this._ownedKeys.add(key);\n    }\n    return this._targets[key];\n  }\n\n  public addToCache(attachments: PassAttachments, renderTarget: RenderTarget): void {\n    const key = this._renderTargetKey(attachments);\n    this._targets[key] = renderTarget;\n    this._ownedKeys.delete(key);\n  }\n\n  /**\n   * Destroys the targets it made rather than dropping them, since each listens on a source that can\n   * outlive the reset; `RenderGraph._invalidatePerPassTargets` drops the graph's references to them\n   */\n  public reset(): void {\n    this._releaseOwned();\n    for (const key in this._targets) delete this._targets[key];\n  }\n\n  public destroy(): void {\n    this.reset();\n  }\n\n  private _releaseOwned(): void {\n    for (const key of this._ownedKeys) this._targets[key].destroy();\n    this._ownedKeys.clear();\n  }\n\n  private _createRenderTarget(attachments: PassAttachments): RenderTarget {\n    const descriptor: RenderTargetDescriptor = { colorAttachments: [] };\n\n    if (attachments.colors) {\n      for (let i = 0; i < attachments.colors.length; i++) {\n        descriptor.colorAttachments[i] = {\n          texture: attachments.colors[i].texture,\n          storeOp: 'store',\n        };\n      }\n    }\n\n    if (descriptor.colorAttachments.length === 0 && !attachments.depth) {\n      throw new Error('RenderTargetCache: cannot build a render target with no color or depth attachment');\n    }\n\n    if (attachments.depth) {\n      descriptor.depthStencilAttachment = {\n        texture: attachments.depth.texture,\n        depthReadOnly: attachments.depthReadOnly,\n      };\n    }\n\n    return new RenderTarget(descriptor);\n  }\n\n  /** Load ops and clear values stay out of the key: `RenderGraph._setColorAttachments` sets them on every bind */\n  private _renderTargetKey(attachments: PassAttachments): string {\n    const parts: (string | number)[] = [];\n\n    if (attachments.colors) {\n      for (let i = 0; i < attachments.colors.length; i++) {\n        parts.push(attachments.colors[i].texture.uid);\n      }\n    }\n\n    if (attachments.depth) {\n      parts.push(`depth${attachments.depth.texture.uid}${attachments.depthReadOnly ? '_ro' : ''}`);\n    }\n\n    return parts.join('_');\n  }\n}\n","import { CLEAR, Rectangle, RendererType, Texture, TexturePool, TextureView } from 'pixi.js';\nimport type {\n  BindResource,\n  BindableTexture,\n  BindOptions,\n  PointData,\n  RenderTarget,\n  RgbaArray,\n  TEXTURE_FORMATS,\n  WebGLRenderer,\n  WebGPURenderer,\n  TextureSource,\n} from 'pixi.js';\n\nimport type { Camera3D } from '../../scene/cameras/Camera3D';\nimport { getCameraData } from '../CameraData';\nimport { prepareCamera, uploadCamera } from '../prepareCamera';\nimport type { RenderSession } from '../render-passes/RenderSession';\nimport { isLinearFormat } from '../shader/bits/decodeToLinearBit';\nimport { DEPTH_VIEW_PLACEHOLDER } from '../textures/DefaultTextures';\nimport type { View3DPipe } from '../View3DPipe';\nimport { assertColorAttachmentLimits } from './assertColorAttachmentLimits';\nimport type { ColorAttachmentFormat } from './assertColorAttachmentLimits';\nimport { cameraFrameToPhysicalViewport } from './frameToPhysicalViewport';\nimport type { GraphRenderPass } from './GraphRenderPass';\nimport { PassBuilder } from './PassBuilder';\nimport type { PassRecord, ResourceAccess } from './PassBuilder';\nimport { RenderTargetCache } from './RenderTargetCache';\nimport type { PassAttachments } from './RenderTargetCache';\nimport type {\n  ColorHandle,\n  DepthHandle,\n  ResourceDescriptor,\n  ResourceHandle,\n  ResourceKind,\n  TransientTextureOptions,\n} from './ResourceHandle';\nimport { assertSceneOutput, sameSceneOutput } from './SceneOutput';\nimport type { SceneOutput } from './SceneOutput';\nimport type { GlobalTextureBindings } from './TextureBinding';\n\nconst DEPTH_FORMAT = 'depth24plus-stencil8';\n\ninterface ResolvedTarget {\n  target: RenderTarget | null;\n  flipY: boolean;\n  frame: Rectangle | null;\n}\n\n/** @internal */\nexport interface DrawTarget {\n  target: RenderTarget;\n  /** Content rect in physical pixels */\n  readonly viewport: Rectangle;\n  /** Source `target` was looked up under; `null` once it's back in the pool, and `target` leaves it out */\n  colorSource: TextureSource | null;\n  /** As `colorSource`, for the depth */\n  depthSource: TextureSource | null;\n}\n\nconst _activeViewport = new Rectangle();\ninterface SceneOutputEntry {\n  output: SceneOutput;\n  color: ColorHandle;\n}\n\nconst _resolvedTarget: ResolvedTarget = { target: null, flipY: false, frame: null };\n/** `_drawTarget` puts `Texture.EMPTY` back after each lookup, so this module-level key never holds a source alive */\nconst _drawTargetKey: PassAttachments = {};\nconst _drawTargetColors = [{ texture: Texture.EMPTY.source }];\nconst _drawTargetDepth = { texture: Texture.EMPTY.source };\n/** `_resolveDepth` nulls `target` after each copy, so this module-level scratch never holds a target alive */\nconst _depthResolveSource: DrawTarget = {\n  target: null!,\n  viewport: new Rectangle(),\n  colorSource: null,\n  depthSource: null,\n};\n\nfunction toPhysicalRect(frame: Rectangle, resolution: number, out: Rectangle): Rectangle {\n  out.x = Math.round(frame.x * resolution);\n  out.y = Math.round(frame.y * resolution);\n  out.width = Math.max(1, Math.round(frame.width * resolution));\n  out.height = Math.max(1, Math.round(frame.height * resolution));\n  return out;\n}\n\n/**\n * The passes draw into `color`, never `texture`, so a mesh sampling the texture reads last frame's picture,\n * as Camera3D promises\n */\ninterface CameraTarget {\n  color: ColorHandle;\n  depth: DepthHandle;\n  texture: ColorHandle;\n  draw: DrawTarget | null;\n}\n\n/**\n * `cachedTexture` and `cachedDepthView` are destroyed, not dropped, when their source changes, since each listens\n * on a source that outlives it; a transient keeps its depth view across frames, so the steady state allocates nothing\n */\ntype ResourceEntry =\n  | {\n      kind: 'imported';\n      type: ResourceKind;\n      getter: (session: RenderSession) => BindableTexture;\n      cachedTexture: Texture | null;\n      cachedDepthView: TextureView | null;\n      cachedDepthViewSource: TextureSource | null;\n    }\n  | {\n      kind: 'transient';\n      type: ResourceKind;\n      describe: (session: RenderSession) => ResourceDescriptor;\n      /** `null` outside the passes that use it this frame */\n      texture: Texture | null;\n      cachedTexture: Texture | null;\n      cachedDepthView: TextureView | null;\n      cachedDepthViewSource: TextureSource | null;\n    };\n\ninterface AddedPass {\n  pass: GraphRenderPass;\n  record: PassRecord;\n  /** A reader gets every earlier writer, not just the last, since the last one's `condition` can skip it */\n  dependsOn: AddedPass[];\n  isAnchored: boolean;\n  /** Cameras copied into their textures before `finishedColors` are processed, since those can include the textures */\n  copyCameras: Camera3D[];\n  /** Resolved, then mipmapped, in that order, so the mips come from the resolved picture */\n  finishedColors: ColorHandle[];\n  /** Resolved from the target this pass drew into, once per run of writers before a sampler */\n  depthResolves: DepthHandle[];\n  /** Also set on a colour's last writer; `execute()`'s `colorResolved` keeps it to one resolve beside `finishedColors` */\n  resolvesColor: boolean;\n  /** Built once by `compile()` and patched each frame, so the lookup allocates nothing; `null` with no attachments */\n  attachments: PassAttachments | null;\n  /** Parallel to `attachments.colors` */\n  colorHandles: ColorHandle[];\n  depthHandle: DepthHandle | null;\n  sampleAccesses: ResourceAccess[];\n  /** Source uid last bound per sample access, `-1` before the first; a change re-records the WebGPU bundles */\n  lastSampleSourceUids: number[];\n  cachedTarget: RenderTarget | null;\n  /**\n   * Equals `_resolveTick` once the pass passes its `condition` this frame, as `neededTick` does once it\n   * survives the cull; ticks in place of Sets, so the cull allocates nothing\n   */\n  candidateTick: number;\n  neededTick: number;\n}\n\n/**\n * Options for a {@link RenderGraph}\n * @category rendering\n * @advanced\n */\nexport interface RenderGraphOptions {\n  /** The view's global texture bindings: pass on {@link DefaultGraph3DOptions#globalTextureBindings} */\n  globalTextureBindings: GlobalTextureBindings;\n  /** Returns, each frame, the colour of the target the view draws into: usually `session.defaultTarget.colorTexture` */\n  defaultColor: (session: RenderSession) => BindableTexture;\n  /**\n   * Returns, each frame, the depth of the target the view draws into: usually\n   * `session.defaultTarget.depthStencilTexture!`\n   */\n  defaultDepth: (session: RenderSession) => BindableTexture;\n  /**\n   * A texture for the scene to draw into, sized at {@link RenderGraph#resolution}\n   *\n   * A pass must then draw it onto {@link RenderGraph#defaultColor}, as an {@link OutputPass} does.\n   * Leave it and `sceneDepth` out to draw the scene straight into the view's target.\n   */\n  sceneColor?: Omit<TransientTextureOptions, 'resolution'>;\n  /** Depth for {@link RenderGraphOptions#sceneColor}; give both or neither, with the same size and `antialias` */\n  sceneDepth?: Omit<TransientTextureOptions, 'resolution'>;\n  /**\n   * Scene outputs the scene passes write beside the scene colour, at its size; passes reach them\n   * with {@link RenderGraph#getSceneOutput}. Needs `sceneColor`, or the constructor throws. With a\n   * multisampled scene colour, each output's format must be one the GPU can average: not an integer\n   * format, a 32-bit float one, or `rgba8unorm` on WebGL. Fixed for the graph's lifetime.\n   */\n  sceneOutputs?: readonly SceneOutput[];\n}\n\n/**\n * The ordered passes a {@link View3D} renders, and the textures they read and write\n *\n * Each pass declares in `setup` what it reads and writes. From that the graph lends the passes\n * pooled textures for as long as they're used, binds each pass's target, and each frame skips any\n * pass whose output nothing uses. A view builds one with {@link createDefaultGraph3D}, or with its\n * `graph` option, then compiles and runs it.\n * @category rendering\n * @advanced\n */\nexport class RenderGraph {\n  private readonly _resources: ResourceEntry[] = [];\n  private readonly _passes: AddedPass[] = [];\n\n  private readonly _builder: PassBuilder;\n\n  private readonly _renderTargetCache: RenderTargetCache = new RenderTargetCache();\n\n  private readonly _defaultCacheKey: PassAttachments = {\n    colors: [{ texture: Texture.EMPTY.source }],\n    depth: { texture: Texture.EMPTY.source },\n  };\n\n  /** Shares `_defaultCacheKey`'s attachment objects, so patching that key's sources patches this one too */\n  private readonly _defaultCacheKeyReadOnlyDepth: PassAttachments = {\n    colors: this._defaultCacheKey.colors,\n    depth: this._defaultCacheKey.depth,\n    depthReadOnly: true,\n  };\n\n  private readonly _cameraTargets = new Map<Camera3D, CameraTarget>();\n\n  private _sceneDrawTarget: DrawTarget | null = null;\n\n  private readonly _camerasSeen = new Set<Camera3D>();\n\n  /**\n   * Camera target colours, whose writers are anchored like an imported texture's, and which bind with\n   * the outer `flipY` so the copy lands upright\n   */\n  private readonly _cameraTargetColors = new Set<number>();\n\n  /**\n   * The colour the scene draws into: the texture made from {@link RenderGraphOptions#sceneColor}, or\n   * {@link RenderGraph#defaultColor} without one\n   */\n  public readonly sceneColor: ColorHandle;\n\n  /**\n   * Whether {@link RenderGraph#sceneColor} holds linear light, from a float or `-srgb` format in\n   * {@link RenderGraphOptions#sceneColor}\n   *\n   * If so, the view leaves the tone curve out of its materials and sky, and a pass in the graph must\n   * apply it, as an {@link OutputPass} does; see {@link View3D#toneMapping}.\n   */\n  public get sceneIsLinear(): boolean {\n    const format = this._sceneColorOptions?.format;\n    return format !== undefined && isLinearFormat(format);\n  }\n\n  /** Depth paired with {@link RenderGraph#sceneColor} */\n  public readonly sceneDepth: DepthHandle;\n  /** The scene outputs this graph attaches, as given in {@link RenderGraphOptions#sceneOutputs} */\n  public readonly sceneOutputs: readonly SceneOutput[];\n  /**\n   * Texels per logical pixel of the scene, which every texture with `resolution: 'inherit'` follows\n   *\n   * The view sets it before each frame: its target's resolution when the scene draws straight to the\n   * target, otherwise {@link View3D#resolution}.\n   */\n  public resolution = 1;\n  private readonly _sceneOutputsByName = new Map<string, SceneOutputEntry>();\n  private readonly _clearValueById: Record<number, RgbaArray> = Object.create(null);\n  /** `null` when the scene draws straight into the view's target */\n  private readonly _sceneColorOptions: Omit<TransientTextureOptions, 'resolution'> | null;\n  /** The colour of the target the view draws into, such as the canvas: where the final picture goes */\n  public readonly defaultColor: ColorHandle;\n  /** Depth paired with {@link RenderGraph#defaultColor} */\n  public readonly defaultDepth: DepthHandle;\n\n  private _lastColorUid = -1;\n  private _lastDepthUid = -1;\n  /** The default colour's size last frame, in physical pixels */\n  private _lastWidth = -1;\n  private _lastHeight = -1;\n\n  private readonly _activePasses: AddedPass[] = [];\n\n  private readonly _acquireAt: number[][] = [];\n  private readonly _releaseAt: number[][] = [];\n\n  /** Active-pass index by resource id, `-1` when unused this frame; refilled in place, so nothing is allocated */\n  private _firstUseByResId: Int32Array = new Int32Array(0);\n  private _lastUseByResId: Int32Array = new Int32Array(0);\n  private _firstWriterByResId: Int32Array = new Int32Array(0);\n  private _lastWriterByResId: Int32Array = new Int32Array(0);\n  private readonly _lastWrittenHandleByResId: (ColorHandle | undefined)[] = [];\n\n  /** The single-sample copy each sampled transient depth resolves into, by `handle._id`; used only while it's multisampled */\n  private readonly _depthResolveByResId: (DepthHandle | undefined)[] = [];\n  /** The pass a multisampled depth last resolved after, by `handle._id`, or `-1`; written again after a sampler, it resolves again */\n  private _depthResolvedAtByResId: Int32Array = new Int32Array(0);\n\n  private _resolveTick = 0;\n  private _limitsChecked = false;\n\n  private readonly _resolveCandidates: AddedPass[] = [];\n  private readonly _resolveStack: AddedPass[] = [];\n\n  /** The binding live when `execute` starts, bound again at its end so later 2D content lands where it would have */\n  private _savedBind?: BindOptions;\n\n  /** Refilled per bind, since pixi copies it; `execute` clears its target and frame before returning */\n  private readonly _bindOptions: BindOptions = { target: null!, clear: CLEAR.NONE, frame: undefined, flipY: false };\n\n  private _destroyed = false;\n\n  /** The view's global texture bindings; passes reach them through {@link PassBuilder#globalTextureBindings} */\n  public readonly globalTextureBindings: GlobalTextureBindings;\n\n  constructor(opts: RenderGraphOptions) {\n    this.globalTextureBindings = opts.globalTextureBindings;\n    this.defaultColor = this.importColor(opts.defaultColor);\n    this.defaultDepth = this.importDepth(opts.defaultDepth);\n    const sceneColor = opts.sceneColor;\n    this.sceneColor = sceneColor ? this.createColor(sceneColor) : this.defaultColor;\n    this.sceneDepth = opts.sceneDepth ? this.createDepth(opts.sceneDepth) : this.defaultDepth;\n    this._sceneColorOptions = sceneColor ?? null;\n\n    this.sceneOutputs = opts.sceneOutputs ?? [];\n    if (this.sceneOutputs.length > 0) {\n      if (!sceneColor) {\n        throw new Error(\n          'RenderGraph: sceneOutputs need a sceneColor. The scene passes attach each output beside the scene ' +\n            \"colour, and the screen can't hold extra attachments, so give the graph a `sceneColor` and \" +\n            '`sceneDepth`, as createDefaultGraph3D does whenever a pass requires an output.',\n        );\n      }\n      for (const output of this.sceneOutputs) {\n        assertSceneOutput(output);\n        const color = this.createColor({\n          width: sceneColor.width,\n          height: sceneColor.height,\n          antialias: sceneColor.antialias,\n          format: output.format,\n          scaleMode: output.format.includes('int') ? 'nearest' : undefined,\n          label: output.name,\n        });\n        this._sceneOutputsByName.set(output.name, { output, color });\n        if (output.clearValue) this._clearValueById[color._id] = output.clearValue;\n      }\n    }\n\n    this._builder = new PassBuilder(this);\n  }\n\n  /**\n   * The texture of a scene output this graph attaches, for a pass to read or draw into\n   *\n   * Declare the access in the pass's `setup`, as for any graph texture. A `'beforeOpaque'` pass runs\n   * before the scene writes it, and an `'afterOpaque'` pass runs before transparent and glass\n   * surfaces do.\n   * @example\n   * ```ts\n   * const normals = graph.getSceneOutput(normalOutput);\n   * ```\n   * @param output - An output in {@link RenderGraph#sceneOutputs}, which a pass's\n   *   {@link Pass3D#requiredOutputs} puts there.\n   * @returns The output's texture handle.\n   * @throws If the graph doesn't attach an output with this name.\n   */\n  public getSceneOutput(output: SceneOutput): ColorHandle {\n    const entry = this._sceneOutputsByName.get(output.name);\n    if (!entry) {\n      throw new Error(\n        `RenderGraph.getSceneOutput: this graph doesn't attach '${output.name}'. List it in the ` +\n          \"pass's `requiredOutputs`, so the view attaches it. A custom graph builder forwards `options.passes` \" +\n          \"to createDefaultGraph3D, or gives the output to its RenderGraph's `sceneOutputs` option.\",\n      );\n    }\n    return entry.color;\n  }\n\n  /**\n   * Whether this graph attaches `output`, for a pass that uses it when the view has it and works\n   * without it otherwise\n   *\n   * It matches by name and content, so a different output that shares the name doesn't count.\n   * @example\n   * ```ts\n   * const normals = graph.hasSceneOutput(normalOutput) ? graph.getSceneOutput(normalOutput) : null;\n   * ```\n   * @param output - The output to look for.\n   * @returns Whether the graph attaches this output, by name and content.\n   */\n  public hasSceneOutput(output: SceneOutput): boolean {\n    const entry = this._sceneOutputsByName.get(output.name);\n    return entry !== undefined && sameSceneOutput(entry.output, output);\n  }\n\n  /**\n   * Adds a colour texture you own, such as a render texture, for passes to draw into\n   *\n   * `getter` runs each frame, so the graph follows a resized or swapped texture. A pass that writes\n   * it runs even when no pass reads it, and the graph never clears it.\n   * @param getter - Resolves the live texture for the frame.\n   * @returns The handle for the imported colour resource.\n   */\n  public importColor(getter: (s: RenderSession) => BindableTexture): ColorHandle {\n    return this._importResource('color', getter) as ColorHandle;\n  }\n\n  /**\n   * Adds a depth texture you own; see {@link RenderGraph#importColor}\n   * @param getter - Resolves the live texture for the frame.\n   * @returns The handle for the imported depth resource.\n   */\n  public importDepth(getter: (s: RenderSession) => BindableTexture): DepthHandle {\n    return this._importResource('depth', getter) as DepthHandle;\n  }\n\n  /**\n   * Creates a colour texture the graph allocates; {@link TransientTextureOptions} sets its size and format\n   *\n   * The graph takes it from pixi's `TexturePool` before the first pass that uses it each frame and\n   * gives it back after the last, so don't count on its content in the next frame.\n   * @param options - Size, resolution, format and label; see {@link TransientTextureOptions}.\n   * @returns The handle for the transient colour resource.\n   */\n  public createColor(options: TransientTextureOptions = {}): ColorHandle {\n    const format = options.format ?? this._sceneColorOptions?.format;\n    return this._createTransient('color', this._describe('color', { ...options, format })) as ColorHandle;\n  }\n\n  /**\n   * Creates a depth texture the graph allocates; see {@link RenderGraph#createColor}\n   * @param options - Size, resolution, format and label; see {@link TransientTextureOptions}.\n   * @returns The handle for the transient depth resource.\n   */\n  public createDepth(options: TransientTextureOptions = {}): DepthHandle {\n    return this._createTransient('depth', this._describe('depth', options)) as DepthHandle;\n  }\n\n  /** @internal */\n  public _cameraTarget(camera: Camera3D): CameraTarget {\n    if (!camera.renderTexture) {\n      throw new Error('RenderGraph._cameraTarget: this camera has no renderTexture.');\n    }\n\n    let target = this._cameraTargets.get(camera);\n\n    if (target) return target;\n\n    const colorDescriptor: ResourceDescriptor = {\n      width: 0,\n      height: 0,\n      format: this._cameraTargetFormat(camera),\n      label: 'cameraTarget',\n    };\n    const depthDescriptor: ResourceDescriptor = {\n      width: 0,\n      height: 0,\n      format: DEPTH_FORMAT,\n      label: 'cameraTargetDepth',\n    };\n    const describeTextureSize = (out: ResourceDescriptor): ResourceDescriptor => {\n      const { frame, source } = camera.renderTexture!;\n      out.width = Math.max(1, Math.round(frame.width * source.resolution));\n      out.height = Math.max(1, Math.round(frame.height * source.resolution));\n      return out;\n    };\n\n    target = {\n      color: this._createTransient('color', () => {\n        colorDescriptor.format = this._cameraTargetFormat(camera);\n        colorDescriptor.antialias = camera.renderTexture!.source.antialias;\n        return describeTextureSize(colorDescriptor);\n      }) as ColorHandle,\n      depth: this._createTransient('depth', () => {\n        depthDescriptor.antialias = camera.renderTexture!.source.antialias;\n        return describeTextureSize(depthDescriptor);\n      }) as DepthHandle,\n      texture: this._importResource('color', () => camera.renderTexture!) as ColorHandle,\n      draw: null,\n    };\n    this._cameraTargetColors.add(target.color._id);\n\n    this._cameraTargets.set(camera, target);\n\n    return target;\n  }\n\n  /** The scene's format in a linear scene, since `CopyOpaquePass` copies the camera's target into a scene-format one */\n  private _cameraTargetFormat(camera: Camera3D): TEXTURE_FORMATS {\n    return this.sceneIsLinear ? this._sceneColorOptions!.format! : camera.renderTexture!.source.format;\n  }\n\n  /**\n   * From the render-target cache, so over the screen it's pixi's own target, not a second one over\n   * the same textures; the rect is refreshed every call, since a pooled source can return with another content size\n   * @internal\n   */\n  public _drawTarget(camera: Camera3D | null, session: RenderSession): DrawTarget {\n    const cameraTarget = camera?.renderTexture ? this._cameraTarget(camera) : null;\n    const colorEntry = this._resources[(cameraTarget?.color ?? this.sceneColor)._id];\n    const depthEntry = this._resources[(cameraTarget?.depth ?? this.sceneDepth)._id];\n    const colorSource = this._liveSource(colorEntry, session);\n    const depthSource = this._liveSource(depthEntry, session);\n\n    let draw = cameraTarget ? cameraTarget.draw : this._sceneDrawTarget;\n\n    if (draw === null || draw.colorSource !== colorSource || draw.depthSource !== depthSource) {\n      if (colorSource) _drawTargetColors[0].texture = colorSource;\n      if (depthSource) _drawTargetDepth.texture = depthSource;\n      _drawTargetKey.colors = colorSource ? _drawTargetColors : undefined;\n      _drawTargetKey.depth = depthSource ? _drawTargetDepth : undefined;\n      const target = this._renderTargetCache.get(_drawTargetKey);\n      _drawTargetColors[0].texture = Texture.EMPTY.source;\n      _drawTargetDepth.texture = Texture.EMPTY.source;\n\n      if (draw === null) {\n        draw = { target, viewport: new Rectangle(), colorSource, depthSource };\n        if (cameraTarget) cameraTarget.draw = draw;\n        else this._sceneDrawTarget = draw;\n      } else {\n        draw.target = target;\n        draw.colorSource = colorSource;\n        draw.depthSource = depthSource;\n      }\n    }\n\n    const colorTexture = colorEntry.kind === 'transient' ? colorEntry.texture : null;\n    const content = colorTexture ?? (depthEntry.kind === 'transient' ? depthEntry.texture : null);\n\n    if (content) toPhysicalRect(content.frame, content.source.resolution, draw.viewport);\n    else draw.viewport.copyFrom(session.viewport);\n\n    return draw;\n  }\n\n  /** The passes in the order they run, in a new array each call */\n  public get passes(): GraphRenderPass[] {\n    const out: GraphRenderPass[] = [];\n    for (let i = 0; i < this._passes.length; i++) out.push(this._passes[i].pass);\n    return out;\n  }\n\n  /**\n   * Writes the scale from view UVs, 0 to 1, to the content of a scene-sized graph texture, which the\n   * pool can make larger than its content\n   * @param pixelWidth - Scene width in texels, from {@link RenderGraph#sceneViewport}.\n   * @param pixelHeight - Scene height in texels.\n   * @param out - Destination for the scale.\n   */\n  public setViewportUvScale(pixelWidth: number, pixelHeight: number, out: PointData): void {\n    const size = TexturePool.getOptimalSize(pixelWidth, pixelHeight);\n    out.x = pixelWidth / size.width;\n    out.y = pixelHeight / size.height;\n  }\n\n  /**\n   * The scene's content rect in its own texels, available before any target is bound\n   *\n   * When the scene draws straight into the view's target, it's the view's place there. Otherwise it\n   * starts at the origin of the scene texture and is sized at {@link RenderGraph#resolution}.\n   * @param session - The frame's render session, with `viewport` filled.\n   * @param out - Receives the rect.\n   * @returns `out`, for inline use.\n   */\n  public sceneViewport(session: RenderSession, out: Rectangle): Rectangle {\n    const options = this._sceneColorOptions;\n\n    if (!options) return out.copyFrom(session.viewport);\n\n    out.x = 0;\n    out.y = 0;\n    return this._contentSize(options, this.resolution, session, out);\n  }\n\n  private _contentSize<T extends Pick<Rectangle, 'width' | 'height'>>(\n    options: TransientTextureOptions,\n    resolution: number,\n    s: RenderSession,\n    out: T,\n  ): T {\n    const targetResolution = s.defaultTarget.colorTexture.source.resolution;\n    const width = options.width ?? s.viewport.width / targetResolution;\n    const height = options.height ?? s.viewport.height / targetResolution;\n    out.width = Math.max(1, Math.round(width * resolution));\n    out.height = Math.max(1, Math.round(height * resolution));\n    return out;\n  }\n\n  /** The returned function refills one descriptor per call, which is safe because the pool only reads it */\n  private _describe(type: ResourceKind, options: TransientTextureOptions): (s: RenderSession) => ResourceDescriptor {\n    const depth = type === 'depth';\n    const scaleMode = options.scaleMode ?? (depth ? 'nearest' : undefined);\n    const descriptor: ResourceDescriptor = {\n      width: 0,\n      height: 0,\n      format: DEPTH_FORMAT,\n      autoGenerateMipmaps: options.autoGenerateMipmaps ?? false,\n      label: options.label ?? (depth ? 'depthTransient' : 'colorTransient'),\n    };\n    if (scaleMode) descriptor.scaleMode = scaleMode;\n    if (options.antialias) descriptor.antialias = true;\n    return (s: RenderSession) => {\n      const resolution = typeof options.resolution === 'number' ? options.resolution : this.resolution;\n      this._contentSize(options, resolution, s, descriptor);\n      descriptor.format =\n        options.format ?? (depth ? DEPTH_FORMAT : (s.defaultTarget.colorTexture.source.format ?? 'bgra8unorm'));\n      return descriptor;\n    };\n  }\n\n  /**\n   * Adds a pass after those already added, and runs its `setup` now\n   *\n   * Passes run in the order they're added. Keep the handles `setup` declares for `render`.\n   * @param pass - The pass to register.\n   * @returns The same pass, for inline capture.\n   */\n  public addPass<T extends GraphRenderPass>(pass: T): T {\n    const record: PassRecord = { accesses: [], hasSideEffect: false };\n    this._passes.push({\n      pass,\n      record,\n      dependsOn: [],\n      isAnchored: false,\n      attachments: null,\n      colorHandles: [],\n      depthHandle: null,\n      sampleAccesses: [],\n      lastSampleSourceUids: [],\n      cachedTarget: null,\n      candidateTick: 0,\n      neededTick: 0,\n      copyCameras: [],\n      finishedColors: [],\n      depthResolves: [],\n      resolvesColor: false,\n    });\n\n    this._builder._beginPass(record, pass.camera);\n    try {\n      pass.setup(this._builder);\n    } finally {\n      this._builder._endPass();\n    }\n\n    return pass;\n  }\n\n  /**\n   * Works out what each pass depends on and which target it binds; the view calls it once the graph\n   * is built\n   *\n   * It can run again, and starts afresh each time. It throws when a pass both writes and reads one\n   * texture, or samples, through a global binding, a texture {@link PassBuilder#sample} says needs\n   * the pass's own bind group.\n   */\n  public compile(): void {\n    this._limitsChecked = false;\n    for (let i = 0; i < this._passes.length; i++) {\n      const ap = this._passes[i];\n      ap.dependsOn.length = 0;\n      ap.isAnchored = ap.record.hasSideEffect;\n      ap.attachments = null;\n      ap.colorHandles.length = 0;\n      ap.depthHandle = null;\n      ap.sampleAccesses.length = 0;\n      ap.lastSampleSourceUids.length = 0;\n      ap.cachedTarget = null;\n    }\n\n    const writersById: Record<number, AddedPass[]> = Object.create(null);\n    const attachedBy: Record<number, AddedPass> = Object.create(null);\n\n    for (let i = 0; i < this._passes.length; i++) {\n      const ap = this._passes[i];\n      const accesses = ap.record.accesses;\n\n      let hasAttachment = false;\n      let depthReadOnly = false;\n\n      for (let j = 0; j < accesses.length; j++) {\n        const a = accesses[j];\n        const id = a.handle._id;\n\n        if (a.mode === 'write_attachment' || a.mode === 'produce') {\n          const writers = writersById[id] ?? (writersById[id] = []);\n          const prev = writers[writers.length - 1];\n          if (prev && prev !== ap && !ap.dependsOn.includes(prev)) {\n            ap.dependsOn.push(prev);\n          }\n          writers.push(ap);\n\n          if (this._resources[id].kind === 'imported' || this._cameraTargetColors.has(id)) ap.isAnchored = true;\n        } else {\n          for (let k = 0; k < accesses.length; k++) {\n            const b = accesses[k];\n            if (k === j) continue;\n            if ((b.mode === 'write_attachment' || b.mode === 'produce') && b.handle._id === id) {\n              throw new Error(\n                `RenderGraph.compile: pass \"${ap.pass.name}\" both writes and reads (mode=${a.mode}) the same resource (id ${id}). ` +\n                  'A texture can only be one of (writable attachment) or (sampled / read-only) within a single pass.',\n              );\n            }\n          }\n\n          const writers = writersById[id];\n          if (writers) {\n            for (let w = 0; w < writers.length; w++) {\n              const writer = writers[w];\n              if (writer !== ap && !ap.dependsOn.includes(writer)) ap.dependsOn.push(writer);\n            }\n          }\n\n          if (a.mode === 'sample') {\n            ap.sampleAccesses.push(a);\n            ap.lastSampleSourceUids.push(-1);\n            if (a.handle._kind === 'depth' && this._resources[id].kind === 'transient') {\n              this._ensureDepthResolve(a.handle as DepthHandle);\n            }\n          }\n        }\n\n        if (a.mode === 'write_attachment') {\n          hasAttachment = true;\n          if (a.handle._kind === 'color') {\n            ap.colorHandles.push(a.handle as ColorHandle);\n          } else {\n            ap.depthHandle = a.handle as DepthHandle;\n          }\n        } else if (a.mode === 'read_attachment') {\n          hasAttachment = true;\n          ap.depthHandle = a.handle as DepthHandle;\n          depthReadOnly = true;\n        } else {\n          continue;\n        }\n        if (this._resources[id].kind === 'transient') attachedBy[id] ??= ap;\n      }\n\n      if (!hasAttachment) continue;\n\n      const attachments: PassAttachments = {};\n      if (ap.colorHandles.length > 0) {\n        const colors: {\n          /** Patched to the live source each frame */\n          texture: TextureSource;\n        }[] = [];\n        for (let k = 0; k < ap.colorHandles.length; k++) {\n          colors.push({ texture: Texture.EMPTY.source });\n        }\n        attachments.colors = colors;\n      }\n      if (ap.depthHandle !== null) {\n        attachments.depth = { texture: Texture.EMPTY.source };\n        if (depthReadOnly) attachments.depthReadOnly = true;\n      }\n      ap.attachments = attachments;\n    }\n\n    const globalGroup = this.globalTextureBindings.opaqueDepth.group;\n    for (let i = 0; i < this._passes.length; i++) {\n      const ap = this._passes[i];\n      for (let j = 0; j < ap.sampleAccesses.length; j++) {\n        const a = ap.sampleAccesses[j];\n        const attacher = attachedBy[a.handle._id];\n        if (a.binding!.group === globalGroup && attacher) {\n          throw new Error(\n            `RenderGraph.compile: pass \"${ap.pass.name}\" samples resource ${a.handle._id} through the view's global ` +\n              `bind group, and pass \"${attacher.pass.name}\" attaches it. The global group stays bound while every pass ` +\n              'draws, so a texture it holds cannot also be a render target. Sample it through a bind group the pass owns.',\n          );\n        }\n      }\n    }\n  }\n\n  /** @internal */\n  public run(session: RenderSession): void {\n    this.resolve(session);\n    this.prepareCameras(session);\n    this.execute(session);\n  }\n\n  /**\n   * Places a camera's copy after the last pass that writes its colour, the last point the colour is still allocated\n   * @internal\n   */\n  public resolve(session: RenderSession): void {\n    this._activePasses.length = 0;\n    if (!this._limitsChecked) this._assertAttachmentLimits(session);\n\n    const tick = ++this._resolveTick;\n\n    const candidates = this._resolveCandidates;\n    candidates.length = 0;\n    for (let i = 0; i < this._passes.length; i++) {\n      const ap = this._passes[i];\n      if (ap.pass.condition?.(session) ?? true) {\n        ap.candidateTick = tick;\n        candidates.push(ap);\n      }\n    }\n    if (candidates.length === 0) return;\n\n    const stack = this._resolveStack;\n    stack.length = 0;\n    for (let i = 0; i < candidates.length; i++) {\n      const ap = candidates[i];\n      if (ap.isAnchored) {\n        ap.neededTick = tick;\n        stack.push(ap);\n      }\n    }\n    while (stack.length > 0) {\n      const ap = stack.pop()!;\n      const deps = ap.dependsOn;\n      for (let i = 0; i < deps.length; i++) {\n        const dep = deps[i];\n        if (dep.candidateTick !== tick || dep.neededTick === tick) continue;\n        dep.neededTick = tick;\n        stack.push(dep);\n      }\n    }\n\n    for (let i = 0; i < this._passes.length; i++) {\n      const ap = this._passes[i];\n      if (ap.neededTick === tick) this._activePasses.push(ap);\n    }\n\n    const n = this._activePasses.length;\n    while (this._acquireAt.length < n) {\n      this._acquireAt.push([]);\n      this._releaseAt.push([]);\n    }\n    for (let i = 0; i < n; i++) {\n      this._acquireAt[i].length = 0;\n      this._releaseAt[i].length = 0;\n      this._activePasses[i].copyCameras.length = 0;\n      this._activePasses[i].finishedColors.length = 0;\n      this._activePasses[i].depthResolves.length = 0;\n      this._activePasses[i].resolvesColor = false;\n    }\n\n    const resCount = this._resources.length;\n    if (this._firstUseByResId.length < resCount) {\n      this._firstUseByResId = new Int32Array(resCount);\n      this._lastUseByResId = new Int32Array(resCount);\n      this._firstWriterByResId = new Int32Array(resCount);\n      this._lastWriterByResId = new Int32Array(resCount);\n      this._lastWrittenHandleByResId.length = resCount;\n      this._depthResolvedAtByResId = new Int32Array(resCount);\n    }\n    const firstUse = this._firstUseByResId;\n    const lastUse = this._lastUseByResId;\n    const firstWriter = this._firstWriterByResId;\n    const lastWriter = this._lastWriterByResId;\n    const lastWrittenHandle = this._lastWrittenHandleByResId;\n    const resolvedAt = this._depthResolvedAtByResId;\n    firstUse.fill(-1, 0, resCount);\n    lastUse.fill(-1, 0, resCount);\n    firstWriter.fill(-1, 0, resCount);\n    lastWriter.fill(-1, 0, resCount);\n    resolvedAt.fill(-1, 0, resCount);\n\n    for (let i = 0; i < n; i++) {\n      const accesses = this._activePasses[i].record.accesses;\n      for (let j = 0; j < accesses.length; j++) {\n        const a = accesses[j];\n        const id = a.handle._id;\n        const entry = this._resources[id];\n        if (entry.kind === 'transient') {\n          if (firstUse[id] === -1) firstUse[id] = i;\n          lastUse[id] = i;\n        }\n        if (a.mode === 'write_attachment' || a.mode === 'produce') {\n          if (firstWriter[id] === -1) firstWriter[id] = i;\n          lastWriter[id] = i;\n          if (entry.type === 'color') lastWrittenHandle[id] = a.handle as ColorHandle;\n        } else if (\n          a.mode === 'sample' &&\n          a.handle._kind === 'depth' &&\n          entry.kind === 'transient' &&\n          lastWriter[id] !== -1 &&\n          entry.describe(session).antialias\n        ) {\n          const at = lastWriter[id];\n          const copyId = this._depthResolveByResId[id]!._id;\n          if (resolvedAt[id] !== at) {\n            resolvedAt[id] = at;\n            this._activePasses[at].depthResolves.push(a.handle as DepthHandle);\n            if (firstUse[copyId] === -1) firstUse[copyId] = at;\n          }\n          lastUse[copyId] = i;\n        } else if (\n          a.mode === 'sample' &&\n          a.handle._kind === 'color' &&\n          entry.kind === 'transient' &&\n          lastWriter[id] !== -1 &&\n          !this._activePasses[lastWriter[id]].resolvesColor &&\n          entry.describe(session).antialias\n        ) {\n          this._activePasses[lastWriter[id]].resolvesColor = true;\n        }\n      }\n    }\n\n    for (let id = 0; id < resCount; id++) {\n      const first = firstUse[id];\n      if (first !== -1) {\n        this._acquireAt[first].push(id);\n        this._releaseAt[lastUse[id]].push(id);\n      }\n      const last = lastWriter[id];\n      if (last !== -1 && this._resources[id].type === 'color') {\n        this._activePasses[last].finishedColors.push(lastWrittenHandle[id]!);\n      }\n    }\n\n    const seen = this._camerasSeen;\n    seen.clear();\n    for (let i = n - 1; i >= 0; i--) {\n      const ap = this._activePasses[i];\n      const camera = ap.pass.camera;\n      if (!camera?.renderTexture || seen.has(camera)) continue;\n      const cameraTarget = this._cameraTarget(camera);\n      if (lastWriter[cameraTarget.color._id] !== i) continue;\n      seen.add(camera);\n      ap.copyCameras.push(camera);\n      ap.finishedColors.push(cameraTarget.texture);\n    }\n  }\n\n  /**\n   * Runs after the view packs its lights, which `uploadCamera` bins, and before any target is bound, so every\n   * camera reads its front-face winding off the same binding\n   * @internal\n   */\n  public prepareCameras(session: RenderSession): void {\n    uploadCamera(session.view3d.camera, session);\n\n    for (let i = 0; i < this._activePasses.length; i++) {\n      const camera = this._activePasses[i].pass.camera;\n      if (!camera) continue;\n\n      prepareCamera(camera, session);\n      uploadCamera(camera, session);\n    }\n  }\n\n  /**\n   * Never clears the view's own target, which holds the 2D content beneath, and a clear would stop views sharing\n   * pixi's open WebGPU pass; a transient binds with the `flipY` that matches the outer target's winding\n   * @internal\n   */\n  public execute(session: RenderSession): void {\n    this._maybeResetRenderTargetCache(session);\n    this._prepareDefaultTarget(session);\n    const renderer = session.renderer as WebGLRenderer | WebGPURenderer;\n    const pipe = renderer.renderPipes.view3d;\n\n    const savedBind = (this._savedBind = renderer.renderTarget.getBindState(this._savedBind));\n    const defaultSurface = savedBind.target;\n    const defaultFlipY = !!savedBind.flipY;\n    const bindOptions = this._bindOptions;\n\n    const outerInverted = renderer.renderTarget.isFrontFaceInverted(session.defaultTarget, defaultFlipY);\n    const transientFlipY = outerInverted !== (renderer.type === RendererType.WEBGL);\n    session.defaultFrontFaceInverted = outerInverted;\n\n    for (let i = 0; i < this._activePasses.length; i++) {\n      this._activePasses[i].pass.prepare?.(session);\n    }\n\n    for (let i = 0; i < this._activePasses.length; i++) {\n      const ap = this._activePasses[i];\n      const { pass } = ap;\n\n      const toAcquire = this._acquireAt[i];\n      for (let k = 0; k < toAcquire.length; k++) {\n        const entry = this._resources[toAcquire[k]] as Extract<ResourceEntry, { kind: 'transient' }>;\n        const desc = entry.describe(session);\n        const texture = TexturePool.getOptimalTexture(desc);\n        if (desc.label) texture.source.label = desc.label;\n        entry.texture = texture;\n      }\n\n      const { target, flipY, frame } = this._resolveTarget(ap, i, session, transientFlipY, defaultFlipY);\n\n      if (target === session.defaultTarget) {\n        if (session.activeTarget !== target) {\n          bindOptions.target = defaultSurface;\n          bindOptions.clear = CLEAR.NONE;\n          bindOptions.frame = getCameraData(session.view3d.camera).frame;\n          bindOptions.flipY = defaultFlipY;\n          renderer.renderTarget.bind(bindOptions);\n          session.activeTarget = target;\n          session.activeViewport = session.viewport;\n        }\n      } else if (target !== null && target !== session.activeTarget) {\n        const clear = this._resolveClear(ap, i);\n        bindOptions.target = target;\n        bindOptions.clear = clear;\n        bindOptions.frame = frame ?? undefined;\n        bindOptions.flipY = flipY;\n        renderer.renderTarget.bind(bindOptions);\n        if ((clear & CLEAR.DEPTH) !== 0 && ap.depthHandle !== null && ap.depthHandle._id === this.sceneDepth._id) {\n          session.needsDepthClear = false;\n        }\n        session.activeTarget = target;\n        if (frame) {\n          const resolution = (target.colorTexture?.source ?? target.depthStencilTexture!.source).resolution;\n          session.activeViewport = toPhysicalRect(frame, resolution, _activeViewport);\n        }\n      }\n\n      const sampleAccesses = ap.sampleAccesses;\n      const lastSampleSourceUids = ap.lastSampleSourceUids;\n      for (let j = 0; j < sampleAccesses.length; j++) {\n        const a = sampleAccesses[j];\n        const binding = a.binding!;\n        let handle = a.handle;\n        if (handle._kind === 'depth' && this._depthResolvedAtByResId[handle._id] !== -1) {\n          handle = this._depthResolveByResId[handle._id]!;\n        }\n        const resolved = this._bindResource(handle, session);\n        binding.group.setResource(resolved, binding.slot);\n        if (binding.styleSlot !== undefined)\n          binding.group.setResource((resolved as TextureSource).style, binding.styleSlot);\n        const r = resolved as {\n          source?: {\n            uid?: number;\n          };\n          uid?: number;\n        } | null;\n        const sourceUid = r?.source?.uid ?? r?.uid ?? -1;\n        if (sourceUid !== lastSampleSourceUids[j]) {\n          lastSampleSourceUids[j] = sourceUid;\n          if (renderer.type === RendererType.WEBGPU && pass.bit !== undefined) {\n            const batches = session.view3d._meshBatches;\n            for (let b = 0; b < batches.length; b++) {\n              const list = batches[b].drawLists[pass.bit];\n              if (list) list.gpuData.bundleDirtyId++;\n            }\n          }\n        }\n      }\n\n      const passCamera = target !== null && pass.camera && pass.camera !== session.view3d.camera ? pass.camera : null;\n      const passViewport =\n        passCamera && cameraFrameToPhysicalViewport(passCamera, session, session.activeViewport, this.resolution);\n\n      if (passCamera === null) {\n        pass.render(session);\n      } else if (passViewport) {\n        const restore = session.activeViewport;\n\n        pipe.setViewport(passViewport);\n        session.activeViewport = passViewport;\n\n        pass.render(session);\n\n        session.activeViewport = restore;\n        pipe.setViewport(restore);\n      }\n\n      const depthResolves = ap.depthResolves;\n      for (let k = 0; k < depthResolves.length; k++) {\n        this._resolveDepth(ap, depthResolves[k], target, pipe, session);\n      }\n\n      let colorResolved = depthResolves.length > 0;\n      if (!colorResolved && ap.resolvesColor) {\n        pipe.resolveColor();\n        colorResolved = true;\n      }\n      const copyCameras = ap.copyCameras;\n      for (let k = 0; k < copyCameras.length; k++) {\n        const camera = copyCameras[k];\n        const renderTexture = camera.renderTexture!;\n        const drawTarget = this._drawTarget(camera, session);\n        const format = renderTexture.source.format;\n        if (this._cameraTargetFormat(camera) === format) {\n          pipe.copyColor(drawTarget, renderTexture, session);\n        } else {\n          if (!colorResolved && drawTarget.target.colorTexture.source.antialias) {\n            pipe.resolveColor();\n            colorResolved = true;\n          }\n          pipe.outputColor(\n            drawTarget,\n            renderTexture,\n            session,\n            isLinearFormat(format) ? null : session.view3d.toneMapping,\n          );\n        }\n      }\n\n      const finishedColors = ap.finishedColors;\n      for (let k = 0; k < finishedColors.length; k++) {\n        const handle = finishedColors[k];\n        const source = this.getTexture(handle, session).source;\n        if (\n          !colorResolved &&\n          source.antialias &&\n          this._resources[handle._id].kind === 'transient' &&\n          !this._cameraTargetColors.has(handle._id)\n        ) {\n          pipe.resolveColor();\n          colorResolved = true;\n        }\n        if (source.autoGenerateMipmaps) pipe.generateMips(handle, session);\n      }\n\n      const toRelease = this._releaseAt[i];\n      for (let k = 0; k < toRelease.length; k++) {\n        const entry = this._resources[toRelease[k]] as Extract<ResourceEntry, { kind: 'transient' }>;\n        TexturePool.returnTexture(entry.texture!);\n        entry.texture = null;\n      }\n    }\n\n    renderer.renderTarget.bind(savedBind);\n    session.activeTarget = null;\n    bindOptions.target = null!;\n    bindOptions.frame = undefined;\n  }\n\n  /**\n   * Frees the GPU memory each pass can rebuild, such as the shadow map, through its\n   * {@link GraphRenderPass#unload}; the graph keeps rendering\n   *\n   * Textures the graph allocates are back in pixi's `TexturePool` between frames, and stay there.\n   */\n  public unload(): void {\n    if (this._destroyed) return;\n\n    for (let i = 0; i < this._passes.length; i++) {\n      this._passes[i].pass.unload?.();\n    }\n  }\n\n  /**\n   * Destroys the graph and its passes; imported textures are left alone, and pixi's `TexturePool`\n   * keeps the textures the graph used\n   */\n  public destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n\n    this._releaseTransients();\n\n    for (let i = 0; i < this._passes.length; i++) {\n      this._passes[i].pass.destroy?.();\n    }\n\n    this._renderTargetCache.destroy();\n\n    for (let i = 0; i < this._resources.length; i++) {\n      const entry = this._resources[i];\n      if (entry.cachedTexture) {\n        entry.cachedTexture.destroy(false);\n        entry.cachedTexture = null;\n      }\n      if (entry.cachedDepthView) {\n        entry.cachedDepthView.destroy();\n        entry.cachedDepthView = null;\n        entry.cachedDepthViewSource = null;\n      }\n    }\n\n    (this._resources as ResourceEntry[] | null) = null;\n    (this._passes as AddedPass[] | null) = null;\n    (this._activePasses as AddedPass[] | null) = null;\n    (this._cameraTargets as Map<Camera3D, CameraTarget> | null) = null;\n    (this._cameraTargetColors as Set<number> | null) = null;\n    this._sceneDrawTarget = null;\n  }\n\n  /** A depth handle binds as a depth-only view, since WebGPU's `texture_depth_2d` rejects a depth-stencil source */\n  private _bindResource(handle: ResourceHandle, session: RenderSession): BindResource {\n    const source = this.getTexture(handle, session).source;\n    if (handle._kind !== 'depth') return source;\n    const entry = this._resources[handle._id];\n    if (entry.cachedDepthViewSource !== source) {\n      entry.cachedDepthView?.destroy();\n      entry.cachedDepthView = new TextureView(source, { aspect: 'depth-only' });\n      entry.cachedDepthViewSource = source;\n    }\n    return entry.cachedDepthView!;\n  }\n\n  /**\n   * The texture behind a handle, for a pass that binds it itself, such as raw WebGPU compute\n   *\n   * Call it in the pass's `render`, for a handle the pass declared in `setup`;\n   * {@link PassBuilder#sample} binds a texture for you instead. A texture the graph allocated lives\n   * from the first pass that uses it to the last, and then the pool can hand it to another pass, so\n   * don't keep it past `render`. Outside that span this throws.\n   *\n   * On WebGPU, record on `renderer.encoder.commandEncoder`: work on an encoder of your own runs\n   * before this frame's earlier passes, and reads what the texture held before this frame. A render\n   * pass can still be open, so call `renderer.renderTarget.finishRenderPass()` first, and set\n   * {@link RenderSession#activeTarget} to `null` so the next pass binds its target again.\n   * `renderer.texture.getGpuSource(texture.source)` gives the `GPUTexture`, and\n   * `renderer.texture.getTextureView` gives a view it caches on the source, so a bind group made from\n   * that view can be kept while the view stays the same.\n   *\n   * A pooled texture can be larger than its content: `texture.frame` times\n   * `texture.source.resolution` is the content rect in texels. A depth-stencil texture binds to a\n   * WebGPU shader through a depth-only view, as in the example.\n   * @example\n   * ```ts\n   * const depth = graph.getTexture(depthHandle, session);\n   * const depthView = renderer.texture.getTextureView(depth, { aspect: 'depth-only' });\n   *\n   * renderer.renderTarget.finishRenderPass();\n   * session.activeTarget = null;\n   * const compute = renderer.encoder.commandEncoder.beginComputePass();\n   * // bind depthView, dispatch\n   * compute.end();\n   * ```\n   * @param handle - A resource the calling pass declared.\n   * @param session - The frame's render session.\n   * @returns The texture, valid until the pass's `render` returns.\n   */\n  public getTexture(handle: ResourceHandle, session: RenderSession): Texture {\n    const entry = this._resources[handle._id];\n    if (entry.kind === 'transient') {\n      if (entry.texture === null) {\n        throw new Error(\n          `RenderGraph.getTexture: '${entry.describe(session).label}' isn't alive here. A graph ` +\n            'texture only exists inside the render of a pass that declared it, with b.read, b.sample ' +\n            'or a write, so resolve it there and use it before render returns.',\n        );\n      }\n      return entry.texture;\n    }\n    const imported = entry.getter(session);\n    if (imported instanceof Texture) return imported;\n    const source = imported.source;\n    if (!entry.cachedTexture || entry.cachedTexture.source !== source) {\n      entry.cachedTexture?.destroy(false);\n      entry.cachedTexture = new Texture({ source });\n    }\n    return entry.cachedTexture;\n  }\n\n  /** Runs before the frame takes any pooled texture, so a view over the limit throws holding nothing */\n  private _assertAttachmentLimits(session: RenderSession): void {\n    const renderer = session.renderer as WebGLRenderer | WebGPURenderer;\n    for (let i = 0; i < this._passes.length; i++) {\n      const ap = this._passes[i];\n      if (ap.colorHandles.length < 2) continue;\n      const colors: ColorAttachmentFormat[] = [];\n      for (let j = 0; j < ap.colorHandles.length; j++) {\n        const entry = this._resources[ap.colorHandles[j]._id];\n        colors.push(entry.kind === 'transient' ? entry.describe(session) : entry.getter(session).source);\n      }\n      assertColorAttachmentLimits(ap.pass.name, colors, renderer);\n    }\n    this._limitsChecked = true;\n  }\n\n  private _attachmentSource(entry: ResourceEntry, session: RenderSession): TextureSource {\n    if (entry.kind === 'imported') return entry.getter(session).source;\n    if (entry.texture === null) {\n      throw new Error('RenderGraph._resolveTarget: a transient attachment has not been allocated');\n    }\n    return entry.texture.source;\n  }\n\n  private _liveSource(entry: ResourceEntry, session: RenderSession): TextureSource | null {\n    if (entry.kind === 'transient' && entry.texture === null) return null;\n    return this._attachmentSource(entry, session);\n  }\n\n  private _importResource(type: ResourceKind, getter: (s: RenderSession) => BindableTexture): ResourceHandle {\n    const id = this._resources.length;\n    this._resources.push({\n      kind: 'imported',\n      type,\n      getter,\n      cachedTexture: null,\n      cachedDepthView: null,\n      cachedDepthViewSource: null,\n    });\n    return { _kind: type, _id: id };\n  }\n\n  /** The copy has a descriptor of its own, refreshed from the depth's each frame, since the depth's is multisampled */\n  private _ensureDepthResolve(handle: DepthHandle): void {\n    const id = handle._id;\n    if (this._depthResolveByResId[id]) return;\n    const entry = this._resources[id] as Extract<ResourceEntry, { /** @internal */ kind: 'transient' }>;\n    const descriptor: ResourceDescriptor = { width: 0, height: 0, format: DEPTH_FORMAT, scaleMode: 'nearest' };\n    this._depthResolveByResId[id] = this._createTransient('depth', (s: RenderSession) => {\n      const from = entry.describe(s);\n      descriptor.width = from.width;\n      descriptor.height = from.height;\n      descriptor.format = from.format;\n      descriptor.label ??= `${from.label ?? 'depthTransient'}Resolve`;\n      return descriptor;\n    }) as DepthHandle;\n  }\n\n  /** The copy ends the pass's render pass, which resolves the target's colour too; `execute`'s `colorResolved` counts on it */\n  private _resolveDepth(\n    ap: AddedPass,\n    handle: DepthHandle,\n    target: RenderTarget | null,\n    pipe: View3DPipe,\n    session: RenderSession,\n  ): void {\n    if (target === null || ap.depthHandle === null || ap.depthHandle._id !== handle._id) {\n      throw new Error(\n        `RenderGraph: pass \"${ap.pass.name}\" is the last writer of a multisampled depth before a pass samples it, ` +\n          \"but doesn't attach it; a multisampled depth is resolved from the target that drew it.\",\n      );\n    }\n    const { frame, source } = this.getTexture(handle, session);\n    const copy = this.getTexture(this._depthResolveByResId[handle._id]!, session);\n    _depthResolveSource.target = target;\n    toPhysicalRect(frame, source.resolution, _depthResolveSource.viewport);\n    pipe.copyDepth(_depthResolveSource, copy, session);\n    _depthResolveSource.target = null!;\n  }\n\n  private _createTransient(type: ResourceKind, describe: (s: RenderSession) => ResourceDescriptor): ResourceHandle {\n    const id = this._resources.length;\n    this._resources.push({\n      kind: 'transient',\n      type,\n      describe,\n      texture: null,\n      cachedTexture: null,\n      cachedDepthView: null,\n      cachedDepthViewSource: null,\n    });\n    return { _kind: type, _id: id };\n  }\n\n  /**\n   * Fills every field of the shared result, so no pass inherits the last one's; reuses `ap.cachedTarget` while\n   * the sources match, which misses a cache reset, so `_invalidatePerPassTargets` drops it then\n   */\n  private _resolveTarget(\n    ap: AddedPass,\n    passIdx: number,\n    session: RenderSession,\n    transientFlipY: boolean,\n    defaultFlipY: boolean,\n  ): ResolvedTarget {\n    const out = _resolvedTarget;\n    const attachments = ap.attachments;\n    if (attachments === null) {\n      out.target = null;\n      out.flipY = defaultFlipY;\n      out.frame = null;\n      return out;\n    }\n\n    const colorHandles = ap.colorHandles;\n    let changed = false;\n    let frame: Rectangle | null = null;\n    let flipY = defaultFlipY;\n\n    if (attachments.colors) {\n      for (let i = 0; i < colorHandles.length; i++) {\n        const id = colorHandles[i]._id;\n        const entry = this._resources[id];\n        const source = this._attachmentSource(entry, session);\n        if (frame === null && entry.kind === 'transient') {\n          frame = entry.texture!.frame;\n          flipY = this._cameraTargetColors.has(id) ? defaultFlipY : transientFlipY;\n        }\n        if (attachments.colors[i].texture !== source) {\n          attachments.colors[i].texture = source;\n          changed = true;\n        }\n      }\n    }\n\n    if (ap.depthHandle !== null) {\n      const entry = this._resources[ap.depthHandle._id];\n      const source = this._attachmentSource(entry, session);\n      if (frame === null && entry.kind === 'transient') {\n        frame = entry.texture!.frame;\n        flipY = transientFlipY;\n      }\n      if (attachments.depth!.texture !== source) {\n        attachments.depth!.texture = source;\n        changed = true;\n      }\n    }\n\n    out.flipY = flipY;\n    if (changed || ap.cachedTarget === null) {\n      ap.cachedTarget = this._renderTargetCache.get(attachments);\n    }\n    out.target = ap.cachedTarget;\n    if (attachments.colors && out.target !== session.defaultTarget) this._setColorAttachments(out.target, ap, passIdx);\n    out.frame = frame;\n    return out;\n  }\n\n  /**\n   * Content UV `(min, max)`, inset half a texel, so `min + max` is the content's extent; `fullscreenEffectShader`\n   * relies on both\n   * @internal\n   */\n  public _inputClamp(handle: ResourceHandle, session: RenderSession, out: Float32Array): void {\n    if (this._resources[handle._id].kind !== 'transient') {\n      throw new Error(`RenderGraph._inputClamp: resource ${handle._id} is imported, not a transient`);\n    }\n    const { frame, source } = this.getTexture(handle, session);\n    const halfX = 0.5 / source.pixelWidth;\n    const halfY = 0.5 / source.pixelHeight;\n    out[0] = halfX;\n    out[1] = halfY;\n    out[2] = frame.width / source.pixelWidth - halfX;\n    out[3] = frame.height / source.pixelHeight - halfY;\n  }\n\n  /**\n   * `RenderTargetCache.reset` destroys its targets while pooled sources keep their identity, so a\n   * source check alone would keep a destroyed target\n   */\n  private _invalidatePerPassTargets(): void {\n    for (let i = 0; i < this._passes.length; i++) this._passes[i].cachedTarget = null;\n    for (const cameraTarget of this._cameraTargets.values()) cameraTarget.draw = null;\n    this._sceneDrawTarget = null;\n  }\n\n  /**\n   * Seeds pixi's own target, since on WebGPU a second target over the canvas reconfigures it and destroys the\n   * frame's swap-chain texture; re-seeds only when the key's sources differ, which a cache reset forces\n   */\n  private _prepareDefaultTarget(session: RenderSession): void {\n    session.defaultTarget.ensureDepthStencilTexture();\n\n    const color = session.defaultTarget.colorTexture.source;\n    const depth = session.defaultTarget.depthStencilTexture!.source;\n    const key = this._defaultCacheKey;\n    if (key.colors![0].texture === color && key.depth!.texture === depth) return;\n\n    key.colors![0].texture = color;\n    key.depth!.texture = depth;\n    this._renderTargetCache.addToCache(key, session.defaultTarget);\n    this._renderTargetCache.addToCache(this._defaultCacheKeyReadOnlyDepth, session.defaultTarget);\n  }\n\n  /**\n   * Runs on every bind, since one cached target can back different handles within a frame; never on the view's\n   * own target, whose attachments belong to the app or pixi\n   */\n  private _setColorAttachments(target: RenderTarget, ap: AddedPass, passIdx: number): void {\n    const colors = target.colorAttachments;\n    const several = colors.length > 1;\n    for (let i = 0; i < colors.length; i++) {\n      const attachment = colors[i];\n      const id = ap.colorHandles[i]._id;\n      const value = this._clearValueById[id];\n      if (attachment.clearValue !== value) attachment.clearValue = value;\n      if (several) {\n        const loadOp = this._effectiveLoadOp(id, passIdx);\n        if (attachment.loadOp !== loadOp) attachment.loadOp = loadOp;\n      }\n    }\n  }\n\n  private _resolveClear(ap: AddedPass, passIdx: number): CLEAR {\n    const accesses = ap.record.accesses;\n    let clearColor = false;\n    let clearDepth = false;\n    for (let i = 0; i < accesses.length; i++) {\n      const access = accesses[i];\n      if (access.mode !== 'write_attachment') continue;\n      if (this._effectiveLoadOp(access.handle._id, passIdx) !== 'clear') continue;\n      if (access.handle._kind === 'color') clearColor = true;\n      else if (access.handle._kind === 'depth') clearDepth = true;\n    }\n\n    if (clearColor && clearDepth) return CLEAR.ALL;\n    if (clearColor) return CLEAR.COLOR;\n    if (clearDepth) return CLEAR.DEPTH;\n    return CLEAR.NONE;\n  }\n\n  private _effectiveLoadOp(id: number, passIdx: number): 'load' | 'clear' {\n    if (this._firstWriterByResId[id] !== passIdx) return 'load';\n    const entry = this._resources[id];\n    if (entry.kind === 'transient') return 'clear';\n    if (id === this.defaultDepth._id) return 'clear';\n    return 'load';\n  }\n\n  /**\n   * `-1` is not seen yet, so the default depth `_prepareDefaultTarget` creates later doesn't read as a swap. A resize\n   * resets the cache too, since targets at the old size would never bind again.\n   * Each reset puts `Texture.EMPTY` back in the default key, or `_prepareDefaultTarget` wouldn't re-seed pixi's target.\n   */\n  private _maybeResetRenderTargetCache(session: RenderSession): void {\n    const colorTex = session.defaultTarget.colorTexture.source;\n    const depthTex = session.defaultTarget.depthStencilTexture?.source;\n    const colorUid = colorTex.uid;\n    const depthUid = depthTex ? depthTex.uid : -1;\n    const colorChanged = this._lastColorUid !== -1 && colorUid !== this._lastColorUid;\n    const depthChanged = this._lastDepthUid !== -1 && depthUid !== this._lastDepthUid;\n    const resized =\n      this._lastWidth !== -1 && (colorTex.pixelWidth !== this._lastWidth || colorTex.pixelHeight !== this._lastHeight);\n    if (colorChanged || depthChanged || resized) {\n      this._renderTargetCache.reset();\n      this._invalidatePerPassTargets();\n      this._defaultCacheKey.colors![0].texture = Texture.EMPTY.source;\n      this._defaultCacheKey.depth!.texture = Texture.EMPTY.source;\n    }\n    this._lastColorUid = colorUid;\n    this._lastDepthUid = depthUid;\n    this._lastWidth = colorTex.pixelWidth;\n    this._lastHeight = colorTex.pixelHeight;\n  }\n\n  /**\n   * Puts placeholders back in every transient sample binding, so none holds a texture the pool destroys; `destroy`\n   * runs it too, since the view's global bind group outlives the graph\n   * @internal\n   */\n  public _releaseTransients(): void {\n    for (let i = 0; i < this._passes.length; i++) {\n      const sampleAccesses = this._passes[i].sampleAccesses;\n      for (let j = 0; j < sampleAccesses.length; j++) {\n        const a = sampleAccesses[j];\n        if (this._resources[a.handle._id].kind !== 'transient') continue;\n        const binding = a.binding!;\n        const placeholder = a.handle._kind === 'depth' ? DEPTH_VIEW_PLACEHOLDER : Texture.EMPTY.source;\n        binding.group.setResource(placeholder, binding.slot);\n        if (binding.styleSlot !== undefined) binding.group.setResource(Texture.EMPTY.source.style, binding.styleSlot);\n      }\n    }\n  }\n}\n","import type { ColorSource } from 'pixi.js';\n\nimport type { PointData3D } from '../../../math/vector/PointData3D';\n\n/** @internal */\nexport const HEMISPHERE_DEFAULT_UP = { x: 0, y: 1, z: 0 } as const;\n\n/**\n * Sky and ground colours that light the scene in place of an environment map, or fill the\n * background behind it\n *\n * Assign one to {@link View3D.environment}. A surface facing `up` takes the sky colour, one facing\n * the other way takes the ground colour, and anything between blends the two. Reflections read the\n * same gradient. It needs no cube map, so it's cheaper than one, especially on mobile. It casts no\n * shadows.\n *\n * Assigned to {@link View3D#background}, it draws the same gradient behind the scene. Use one\n * object for both and the sky matches the light the scene receives.\n *\n * It's a plain object: pass an object literal. The view reads its fields every frame, so a\n * colour can be animated, for a sunset say.\n * @example\n * ```ts\n * new View3D({\n *   width,\n *   height,\n *   environment: { skyColor: 0x88ccff, groundColor: 0x553311 },\n * });\n *\n * // Change a colour at any time:\n * (view.environment as Hemisphere).skyColor = 0xff8800; // sunset\n *\n * // The same object as a procedural sky behind the scene\n * const sky: Hemisphere = { skyColor: 0x88ccff, groundColor: 0x553311 };\n * new View3D({ width, height, environment: sky, background: sky });\n * ```\n * @category environment\n * @standard\n */\nexport interface Hemisphere {\n  /**\n   * Colour in the direction of `up`: what a surface facing `up` receives, and the sky drawn there\n   * as a background\n   * @example\n   * ```ts\n   * hemisphere.skyColor = 0x88ccff;\n   * ```\n   */\n  skyColor: ColorSource;\n  /**\n   * Colour in the direction opposite `up`: what a surface facing away from `up` receives\n   * @example\n   * ```ts\n   * hemisphere.groundColor = 0x553311;\n   * ```\n   */\n  groundColor: ColorSource;\n  /**\n   * Direction the sky is in; it doesn't need to be normalised\n   * @default { x: 0, y: 1, z: 0 }\n   * @example\n   * ```ts\n   * const zUpWorld: Hemisphere = { skyColor: 0x88ccff, groundColor: 0x553311, up: { x: 0, y: 0, z: 1 } };\n   * ```\n   */\n  up?: PointData3D;\n  /**\n   * Brightness, multiplied into both colours, as a light and as a background\n   * @default 1\n   * @example\n   * ```ts\n   * hemisphere.intensity = isNight ? 0.2 : 1;\n   * ```\n   */\n  intensity?: number;\n}\n","import { Color } from 'pixi.js';\n\nimport { writeLinearRgb } from '../materials/BaseMaterial3D';\nimport { HEMISPHERE_DEFAULT_UP } from '../scene/lights/environment/Hemisphere';\nimport type { Hemisphere } from '../scene/lights/environment/Hemisphere';\n\n/** One scratch per colour, since `Color` skips the parse when its source repeats */\nconst skyScratch = new Color();\nconst groundScratch = new Color();\n\n/**\n * Writes a hemisphere's linear sky and ground colours, scaled by its intensity, and its unit up axis; every\n * reader goes through this, so the lighting and the background agree\n * @param hemisphere - The hemisphere.\n * @param sky - Receives the sky colour.\n * @param ground - Receives the ground colour.\n * @param up - Receives the up axis, zeros when it has no length.\n * @internal\n */\nexport function writeHemisphere(\n  hemisphere: Hemisphere,\n  sky: Float32Array,\n  ground: Float32Array,\n  up: Float32Array,\n): void {\n  const intensity = hemisphere.intensity ?? 1;\n  writeLinearRgb(sky, 0, skyScratch.setValue(hemisphere.skyColor), intensity);\n  writeLinearRgb(ground, 0, groundScratch.setValue(hemisphere.groundColor), intensity);\n\n  const axis = hemisphere.up ?? HEMISPHERE_DEFAULT_UP;\n  const lenSq = axis.x * axis.x + axis.y * axis.y + axis.z * axis.z;\n  const invLen = lenSq > 0 ? 1 / Math.sqrt(lenSq) : 0;\n  up[0] = axis.x * invLen;\n  up[1] = axis.y * invLen;\n  up[2] = axis.z * invLen;\n}\n","import { Geometry, State } from 'pixi.js';\n\nimport type { ShaderBit } from '../../shader/ShaderBit';\n\n/**\n * The cube sky's shader bit, the same on both backends\n * @internal\n */\nexport const backgroundBit: ShaderBit = {\n  name: 'background',\n  attributes: {\n    aPosition: 'float32x3',\n  },\n  interStage: {\n    vDir: 'vec3<f32>',\n  },\n  bindings: {\n    background: {\n      uCube: 'texture_cube<f32>',\n      uCubeSampler: 'sampler',\n    },\n  },\n};\n\n/**\n * The gradient sky's shader bit; its own uniforms, since the global `uHemisphere*` ones hold valid\n * data only while the view's environment is a hemisphere\n * @internal\n */\nexport const backgroundGradientBit: ShaderBit = {\n  name: 'backgroundGradient',\n  attributes: {\n    aPosition: 'float32x3',\n  },\n  interStage: {\n    vDir: 'vec3<f32>',\n  },\n  bindings: {\n    background: {\n      uSkyColor: 'vec3<f32>',\n      uGroundColor: 'vec3<f32>',\n      uUp: 'vec3<f32>',\n    },\n  },\n};\n\n/** GLSL twin of `backgroundVertexWgsl` in `BackgroundPass.ts` */\nconst backgroundVertexGl = /* glsl */ `#version 300 es\n\n{{header}}\n\nvoid main() {\n  vDir = aPosition;\n\n  mat4 view = uViewMatrix;\n  view[3].xyz = vec3(0.0);\n\n  vec4 clip = uProjectionMatrix * view * vec4(aPosition, 1.0);\n  gl_Position = clip.xyww;\n}\n`;\n\n/**\n * GLSL half of `backgroundTemplate` in `BackgroundPass.ts`\n * @internal\n */\nexport const backgroundGlTemplate = {\n  vertex: backgroundVertexGl,\n  fragment: /* glsl */ `#version 300 es\n\n{{header}}\n\nout vec4 fragColor;\n\nvoid main() {\n  vec4 sampleColor = texture(uCube, normalize(vDir));\n  vec3 sampleLinear = decodeToLinear(sampleColor.rgb);\n  vec3 finalColor = sampleLinear * uExposure;\n  {{end}}\n  fragColor = vec4(finalColor, sampleColor.a);\n}\n`,\n};\n\n/**\n * GLSL half of `backgroundGradientTemplate` in `BackgroundPass.ts`\n * @internal\n */\nexport const backgroundGradientGlTemplate = {\n  vertex: backgroundVertexGl,\n  fragment: /* glsl */ `#version 300 es\n\n{{header}}\n\nout vec4 fragColor;\n\nvoid main() {\n  float t = dot(normalize(vDir), uUp) * 0.5 + 0.5;\n  vec3 finalColor = mix(uGroundColor, uSkyColor, t) * uExposure;\n  {{end}}\n  fragColor = vec4(finalColor, 1.0);\n}\n`,\n};\n\n/**\n * The sky cube, whose vertex positions are the directions the shader looks the cubemap up in\n * @internal\n */\nexport function createBackgroundGeometry(): Geometry {\n  const s = 1;\n\n  const positions: number[] = [];\n\n  const pushFace = (corners: number[][]) => {\n    const idx = [0, 1, 2, 0, 2, 3];\n    for (let i = 0; i < idx.length; i++) {\n      const c = corners[idx[i]];\n      positions.push(c[0], c[1], c[2]);\n    }\n  };\n\n  pushFace([\n    [s, -s, -s],\n    [s, -s, s],\n    [s, s, s],\n    [s, s, -s],\n  ]);\n  pushFace([\n    [-s, -s, s],\n    [-s, -s, -s],\n    [-s, s, -s],\n    [-s, s, s],\n  ]);\n  pushFace([\n    [-s, s, -s],\n    [s, s, -s],\n    [s, s, s],\n    [-s, s, s],\n  ]);\n  pushFace([\n    [-s, -s, s],\n    [s, -s, s],\n    [s, -s, -s],\n    [-s, -s, -s],\n  ]);\n  pushFace([\n    [-s, -s, s],\n    [-s, s, s],\n    [s, s, s],\n    [s, -s, s],\n  ]);\n  pushFace([\n    [s, -s, -s],\n    [s, s, -s],\n    [-s, s, -s],\n    [-s, -s, -s],\n  ]);\n\n  return new Geometry({\n    attributes: {\n      aPosition: positions,\n    },\n  });\n}\n\n/** @internal */\nexport function createBackgroundState(): State {\n  const state = new State();\n\n  state.depthTest = false;\n  state.depthMask = false;\n  state.culling = false;\n  state.blend = false;\n\n  return state;\n}\n","import { BindGroup, Color, CubeTexture, UniformGroup } from 'pixi.js';\nimport type { Geometry, Shader, State, WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport { writeLinearRgb } from '../../../materials/BaseMaterial3D';\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\nimport { getCameraData } from '../../CameraData';\nimport type { PassBuilder } from '../../render-graph/PassBuilder';\nimport type { SceneOutput } from '../../render-graph/SceneOutput';\nimport { decodeToLinearBit, isLinearFormat } from '../../shader/bits/decodeToLinearBit';\nimport type { ShaderBit } from '../../shader/ShaderBit';\nimport type { ShaderBitTemplate } from '../../shader/ShaderBitTemplate';\nimport { CUBETEXTURE_EMPTY } from '../../textures/DefaultTextures';\nimport { writeHemisphere } from '../../writeHemisphere';\nimport { RenderPass, RenderPassBit } from '../RenderPass';\nimport type { RenderSession } from '../RenderSession';\nimport {\n  backgroundBit,\n  backgroundGlTemplate,\n  backgroundGradientBit,\n  backgroundGradientGlTemplate,\n  createBackgroundGeometry,\n  createBackgroundState,\n} from './backgroundPassUtils';\n\n/** Vertex stage of both sky templates; `backgroundVertexGl` in `backgroundPassUtils.ts` is its GLSL twin */\nconst backgroundVertexWgsl = /* wgsl */ `\n@vertex\nfn mainVertex(input: VertexInput) -> VertexOutput {\n  var output: VertexOutput;\n\n  output.vDir = input.aPosition;\n\n  var view = camera.uViewMatrix;\n  view[3] = vec4<f32>(0.0, 0.0, 0.0, view[3].w);\n\n  let clip = camera.uProjectionMatrix * view * vec4<f32>(input.aPosition, 1.0);\n  output.position = vec4<f32>(clip.x, clip.y, clip.w, clip.w);\n\n  return output;\n}\n`;\n\n/** The cube sky's template; `backgroundGlTemplate` in `backgroundPassUtils.ts` is its GLSL half */\nconst backgroundTemplate: ShaderBitTemplate = {\n  bindGroups: [{ name: 'global', ubo: true }, 'camera', 'background'],\n  gpu: /* wgsl */ `\n{{header}}\n${backgroundVertexWgsl}\n@fragment\nfn mainFragment(input: FragmentInput) -> @location(0) vec4<f32> {\n  let sample = textureSample(uCube, uCubeSampler, normalize(input.vDir));\n  let sampleLinear = decodeToLinear(sample.rgb);\n  var finalColor = sampleLinear * global.uExposure;\n  {{fragmentEnd}}\n  return vec4<f32>(finalColor, sample.a);\n}\n`,\n  gl: backgroundGlTemplate,\n};\n\n/** The gradient sky's template; `backgroundGradientGlTemplate` in `backgroundPassUtils.ts` is its GLSL half */\nconst backgroundGradientTemplate: ShaderBitTemplate = {\n  bindGroups: [{ name: 'global', ubo: true }, 'camera', 'background'],\n  gpu: /* wgsl */ `\n{{header}}\n${backgroundVertexWgsl}\n@fragment\nfn mainFragment(input: FragmentInput) -> @location(0) vec4<f32> {\n  let t = dot(normalize(input.vDir), background.uUp) * 0.5 + 0.5;\n  var finalColor = mix(background.uGroundColor, background.uSkyColor, t) * global.uExposure;\n  {{fragmentEnd}}\n  return vec4<f32>(finalColor, 1.0);\n}\n`,\n  gl: backgroundGradientGlTemplate,\n};\n\n/**\n * Options for constructing a {@link BackgroundPass}\n * @category rendering\n * @advanced\n */\nexport interface BackgroundPassOptions {\n  /** Renderer the pass draws with: the {@link PassContext#renderer} a {@link Pass3D#build} call receives */\n  renderer: WebGLRenderer | WebGPURenderer;\n  /** Camera to draw the sky from, or the view's own when omitted; see {@link RenderPassOptions#camera} */\n  camera?: Camera3D;\n  /** The scene outputs attached after the target colour; see {@link RenderPassOptions#attachedOutputs} */\n  attachedOutputs?: readonly SceneOutput[];\n}\n\n/**\n * Draws the view's {@link View3D#background} behind the scene: a cubemap, a {@link Hemisphere}\n * sky/ground gradient, or a plain colour\n *\n * The sky stays at infinity however the camera moves, and takes the view's {@link View3D#exposure}\n * and {@link View3D#toneMapping}, so it matches materials that reflect the same environment. Fog in\n * the same colour as a plain colour background blends into it exactly. Switching between a cubemap\n * and a hemisphere or colour recompiles the pass's shader. The pass holds the old cubemap until a\n * frame draws another background, which a `null` background never does; destroying the cubemap\n * before then makes pixi warn.\n *\n * It paints colour over whatever its target holds, with no depth test, so add it before its\n * camera's opaque draw. The default graph draws one for the view's camera; any other camera draws\n * no sky unless you add a `BackgroundPass` with that `camera` from a {@link Pass3D#build}.\n * @category rendering\n * @advanced\n */\nexport class BackgroundPass extends RenderPass {\n  private readonly _geometry: Geometry;\n  private readonly _state: State;\n  private readonly _cubeBindGroup: BindGroup;\n  private readonly _skyColor = new Float32Array(3);\n  private readonly _groundColor = new Float32Array(3);\n  private readonly _up = new Float32Array(3);\n  private readonly _gradientUniforms: UniformGroup;\n  private readonly _gradientBindGroup: BindGroup;\n  private _shader: Shader | null = null;\n  private _cachedToneBit: ShaderBit | null = null;\n  private _cachedBackgroundBit: ShaderBit | null = null;\n  private _cachedDecodeBit: ShaderBit | null = null;\n  private _destroyed = false;\n\n  constructor(options: BackgroundPassOptions) {\n    super({\n      renderer: options.renderer,\n      name: 'background',\n      description: 'Draws the View3D cubemap, hemisphere or colour background behind scene geometry.',\n      bit: RenderPassBit.BACKGROUND,\n      camera: options.camera,\n      attachedOutputs: options.attachedOutputs,\n    });\n    this._geometry = createBackgroundGeometry();\n    this._state = createBackgroundState();\n    this._cubeBindGroup = new BindGroup({\n      uCube: CUBETEXTURE_EMPTY.source,\n      uCubeSampler: CUBETEXTURE_EMPTY.source.style,\n    });\n    this._gradientUniforms = new UniformGroup({\n      uSkyColor: { value: this._skyColor, type: 'vec3<f32>' },\n      uGroundColor: { value: this._groundColor, type: 'vec3<f32>' },\n      uUp: { value: this._up, type: 'vec3<f32>' },\n    });\n    this._gradientBindGroup = new BindGroup({ background: this._gradientUniforms });\n  }\n\n  /**\n   * Declares colour and depth writes on its camera's target, or on the scene's\n   * @param b - The builder recording this pass's resource accesses\n   */\n  public override setup(b: PassBuilder): void {\n    this._writeTarget(b);\n  }\n\n  /**\n   * Skips the frame when the view has no background\n   * @param session - The current frame's render session\n   * @returns Whether the view has a background to draw\n   */\n  public override condition(session: RenderSession): boolean {\n    return session.view3d.background !== null;\n  }\n\n  /**\n   * Draws the sky with the view's current background\n   * @param session - The current frame's render session\n   */\n  public override render(session: RenderSession): void {\n    const { view3d } = session;\n    const background = view3d.background;\n    if (background === null) return;\n\n    let bit: ShaderBit;\n    let template: ShaderBitTemplate;\n    let backgroundGroup: BindGroup;\n    let decodeBit: ShaderBit | null = null;\n    if (background instanceof CubeTexture) {\n      bit = backgroundBit;\n      decodeBit = decodeToLinearBit(!isLinearFormat(background.source.format));\n      template = backgroundTemplate;\n      this._cubeBindGroup.setResource(background.source, 'uCube');\n      this._cubeBindGroup.setResource(background.source.style, 'uCubeSampler');\n      backgroundGroup = this._cubeBindGroup;\n    } else {\n      bit = backgroundGradientBit;\n      template = backgroundGradientTemplate;\n      if (typeof background === 'number') {\n        writeLinearRgb(this._skyColor, 0, Color.shared.setValue(background));\n        this._groundColor.set(this._skyColor);\n        this._up.fill(0);\n      } else {\n        writeHemisphere(background, this._skyColor, this._groundColor, this._up);\n      }\n      backgroundGroup = this._gradientBindGroup;\n    }\n\n    const toneBit = view3d._toneMappingBit;\n    if (\n      this._shader &&\n      (this._cachedToneBit !== toneBit || this._cachedBackgroundBit !== bit || this._cachedDecodeBit !== decodeBit)\n    ) {\n      this._shader.destroy();\n      this._shader = null;\n    }\n    if (!this._shader) {\n      const bits: ShaderBit[] = [bit];\n      if (decodeBit) bits.push(decodeBit);\n      if (toneBit) bits.push(toneBit);\n      this._shader = this.pipe.renderer.material3d.compilePassShader(bits, template);\n      this._cachedToneBit = toneBit;\n      this._cachedBackgroundBit = bit;\n      this._cachedDecodeBit = decodeBit;\n      if (bit === backgroundGradientBit) {\n        this._cubeBindGroup.setResource(CUBETEXTURE_EMPTY.source, 'uCube');\n        this._cubeBindGroup.setResource(CUBETEXTURE_EMPTY.source.style, 'uCubeSampler');\n      }\n    }\n\n    this._shader.groups[0] = session.globalBindGroup;\n    this._shader.groups[1] = getCameraData(this.camera ?? view3d.camera).bindGroup;\n    this._shader.groups[2] = backgroundGroup;\n\n    this.pipe.renderGeometry(this._geometry, this._shader, this._state);\n  }\n\n  /** Frees the gradient's uniform buffer on the GPU; the next frame drawing a hemisphere or colour uploads it again */\n  public unload(): void {\n    this._gradientUniforms.buffer?.unload();\n  }\n\n  /** Releases the pass's shader, sky cube, bind groups and uniform buffer; the view's background texture stays alive */\n  public override destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n\n    this._shader?.destroy();\n    this._shader = null;\n    this._geometry.destroy(true);\n    this._cubeBindGroup.destroy();\n    this._gradientBindGroup.destroy();\n    this._gradientUniforms.buffer?.destroy();\n  }\n}\n","import type { BindGroup, RenderBundle } from 'pixi.js';\n\nimport { IndirectDrawData } from '../buffers/IndirectDrawData';\nimport { RenderInstanceBuffer } from '../buffers/RenderInstanceBuffer';\nimport type { DrawList } from './DrawList';\n\n/**\n * What one camera's cull decides about one {@link DrawList} on WebGPU, and the bundle recorded against it\n * @internal\n */\nexport class CullResult {\n  public readonly survivors = new RenderInstanceBuffer('survivors');\n\n  /** A copy of the list's `drawData`, re-taken on {@link sync}; the cull writes its instance counts */\n  public readonly indirectDrawData = new IndirectDrawData('survivorDrawCalls');\n\n  public bundle: RenderBundle | null = null;\n\n  /** Whether the pass issues direct draws from CPU-side counts rather than indirect ones; set by {@link sync} */\n  public direct = false;\n\n  /** Bumped by the CPU walk in `gpu/cull.ts` when a count changes; a bundle of direct draws bakes the counts */\n  public countsDirtyId = 0;\n\n  public lastBundleCountsDirtyId = -1;\n  public lastCommandListDirtyId = -1;\n  public lastRangesDirtyId = -1;\n  public lastBundleDirtyId = -1;\n  public lastCameraBindGroup: BindGroup | null = null;\n\n  /** `-1` makes `gpu/cull.ts` run the visibility compaction again */\n  public lastVisibilityDirtyId = -1;\n\n  /**\n   * Re-syncs to the list's commands after a rebuild or an edit, and to `direct`\n   *\n   * An edit keeps an indirect bundle, which holds the body's commands by their place in the args.\n   * @returns Whether it re-synced\n   */\n  public sync(list: DrawList, direct: boolean): boolean {\n    if (this.direct !== direct) {\n      this.direct = direct;\n      this.bundle = null;\n      this.lastVisibilityDirtyId = -1;\n    }\n\n    const dirtyId = list.commandList.dirtyId;\n    const rangesDirtyId = list.rangesDirtyId;\n    if (this.lastCommandListDirtyId === dirtyId && this.lastRangesDirtyId === rangesDirtyId) return false;\n\n    const editedOnly = this.lastCommandListDirtyId === dirtyId;\n    const args = this.indirectDrawData.drawCalls;\n    const survivors = this.survivors.data;\n    this.indirectDrawData.copyCommandsFrom(list.drawData, list.commandList.count);\n    this.survivors.ensureSize(list.view.count);\n    if (!editedOnly || this.direct || args !== this.indirectDrawData.drawCalls || survivors !== this.survivors.data) {\n      this.bundle = null;\n    }\n    this.lastCommandListDirtyId = dirtyId;\n    this.lastRangesDirtyId = rangesDirtyId;\n    this.lastVisibilityDirtyId = -1;\n    return true;\n  }\n\n  /** Whether the recorded bundle must re-record */\n  public isBundleStale(list: DrawList, cameraBindGroup: BindGroup): boolean {\n    return (\n      this.lastBundleDirtyId !== list.gpuData.bundleDirtyId ||\n      this.lastCameraBindGroup !== cameraBindGroup ||\n      (this.direct && this.lastBundleCountsDirtyId !== this.countsDirtyId)\n    );\n  }\n\n  /** Claims the bundle watermarks after recording this result's bundle */\n  public claimBundleRecorded(list: DrawList, cameraBindGroup: BindGroup): void {\n    this.lastBundleDirtyId = list.gpuData.bundleDirtyId;\n    this.lastCameraBindGroup = cameraBindGroup;\n    this.lastBundleCountsDirtyId = this.countsDirtyId;\n  }\n\n  /** Frees the bundle and the buffers' GPU copies, keeping the CPU arrays; the next use re-syncs */\n  public unload(): void {\n    this.bundle = null;\n    this.lastCommandListDirtyId = -1;\n    this.lastRangesDirtyId = -1;\n    this.lastBundleDirtyId = -1;\n    this.lastCameraBindGroup = null;\n    this.lastBundleCountsDirtyId = -1;\n    this.lastVisibilityDirtyId = -1;\n    this.survivors.unload();\n    this.indirectDrawData.unload();\n  }\n\n  /** `BigPool` return hook: a pooled result holds no GPU memory */\n  public reset(): void {\n    this.unload();\n  }\n\n  /** `BigPool.clear` hook */\n  public destroy(): void {\n    this.bundle = null;\n    this.survivors.destroy();\n    this.indirectDrawData.destroy();\n  }\n}\n","import { BigPool } from 'pixi.js';\n\nimport type { View3D } from '../../scene/View3D';\nimport type { Mesh3DBatch } from '../batcher/Mesh3DBatch';\nimport { CullResult } from './CullResult';\n\n/**\n * Pooled {@link CullResult}s by batch uid, any number per batch. The owner hands them back with\n * {@link CullResults.release} when it goes, so no bundle outlives it bound to a freed survivor buffer.\n * @internal\n */\nexport class CullResults {\n  private readonly _byBatch: Record<number, (CullResult | undefined)[]> = Object.create(null);\n  private _lastMeshBatchesDirtyId = -1;\n\n  public ensure(batch: Mesh3DBatch, index = 0): CullResult {\n    const results = (this._byBatch[batch.uid] ??= []);\n    return (results[index] ??= BigPool.get(CullResult));\n  }\n\n  /** Never mints; `undefined` means prepare never minted one, so there is nothing to draw */\n  public get(batch: Mesh3DBatch, index = 0): CullResult | undefined {\n    return this._byBatch[batch.uid]?.[index];\n  }\n\n  public remove(batch: Mesh3DBatch, index: number): void {\n    const results = this._byBatch[batch.uid];\n    const result = results?.[index];\n    if (!results || !result) return;\n    BigPool.return(result);\n    results[index] = undefined;\n    while (results.length > 0 && !results[results.length - 1]) results.pop();\n  }\n\n  /** Sweeps only when `View3D._meshBatchesDirtyId` has moved, so a steady frame costs one compare */\n  public removeDetached(view3d: View3D): void {\n    const dirtyId = view3d._meshBatchesDirtyId;\n    if (this._lastMeshBatchesDirtyId === dirtyId) return;\n    this._lastMeshBatchesDirtyId = dirtyId;\n\n    const batches = view3d._meshBatches;\n    for (const key in this._byBatch) {\n      const uid = +key;\n      let present = false;\n      for (let i = 0; i < batches.length; i++) {\n        if (batches[i].uid === uid) {\n          present = true;\n          break;\n        }\n      }\n      if (present) continue;\n      for (const result of this._byBatch[uid]) if (result) BigPool.return(result);\n      delete this._byBatch[uid];\n    }\n  }\n\n  public unload(): void {\n    for (const key in this._byBatch) {\n      for (const result of this._byBatch[key]) result?.unload();\n    }\n  }\n\n  public release(): void {\n    for (const key in this._byBatch) {\n      for (const result of this._byBatch[key]) if (result) BigPool.return(result);\n      delete this._byBatch[key];\n    }\n    this._lastMeshBatchesDirtyId = -1;\n  }\n}\n","import type { PassBuilder } from '../render-graph/PassBuilder';\nimport { CullResults } from './CullResults';\nimport type { RenderForwardDescriptor } from './RenderForwardDescriptor';\nimport { RenderPass, RenderPassBit } from './RenderPass';\nimport type { RenderPassOptions } from './RenderPass';\nimport type { RenderSession } from './RenderSession';\n\n/**\n * Options for constructing a {@link ForwardRenderPass}\n * @category rendering\n * @advanced\n */\nexport interface ForwardRenderPassOptions extends RenderPassOptions {\n  /**\n   * Draw order\n   *\n   * - `'key'`: stable batch and pipeline order, so the draw work can be cached between frames.\n   *   Right for opaque surfaces.\n   * - `'distance'`: back to front by distance from the camera, re-sorted every frame. Right for\n   *   alpha blending.\n   */\n  sort: 'key' | 'distance';\n  /**\n   * Whether the pass may reuse its draws across frames where nothing changed\n   *\n   * Defaults to `'auto'` on a `'key'` pass, where `'never'` makes it rebuild its draws every frame,\n   * and to `'never'` on a `'distance'` pass. Leave it out there: `'auto'` makes WebGPU draw a\n   * `'distance'` pass in key order, not back to front.\n   */\n  cache?: 'auto' | 'never';\n}\n\n/**\n * Draws the scene meshes in one pass membership from one camera\n *\n * The default graph's opaque, transparent and glass passes are forward passes, and a\n * {@link MeshPass} builds one. It draws every mesh whose material belongs to its `name`, a\n * built-in membership such as `'opaque'` or a name materials join through their `passes` option.\n *\n * Construct one in a {@link Pass3D#build} to draw a membership again from another camera, as\n * {@link PortalPass} does for `'opaque'` and `'transparent'`. It writes colour and depth on its\n * camera's target, or the scene's when it has no camera.\n * @category rendering\n * @advanced\n */\nexport class ForwardRenderPass extends RenderPass {\n  /** Declarative draw description handed to the pipe every frame */\n  protected readonly _forward: RenderForwardDescriptor;\n\n  /** @internal */\n  public readonly cullResults = new CullResults();\n\n  constructor(options: ForwardRenderPassOptions) {\n    super(options);\n    this._forward = {\n      bit: this.bit,\n      bindsMaterial: !this.descriptor?.shaderDescriptor && (this.bit & RenderPassBit.MATERIAL_PASS_MASK) !== 0,\n      cullResults: this.cullResults,\n      camera: this.camera,\n      sort: options.sort,\n      cache: options.cache,\n    };\n    this._updatesViewKey = options.sort === 'key';\n  }\n\n  /**\n   * Declares writes of its camera's target colour, attached outputs and depth; a subclass that also\n   * samples a texture, such as an opaque copy, overrides it\n   * @param b - The builder recording this pass's resource accesses\n   */\n  public override setup(b: PassBuilder): void {\n    this._writeTarget(b);\n  }\n\n  /**\n   * Skips the frame when no mesh in the view's scene belongs to this pass\n   *\n   * Membership decides, not visibility: a pass whose meshes are all hidden still runs and draws\n   * nothing.\n   * @param session - The current frame's render session\n   * @returns Whether the pass should run this frame\n   */\n  public override condition(session: RenderSession): boolean {\n    const batches = session.view3d._meshBatches;\n    for (let i = 0; i < batches.length; i++) {\n      const pd = batches[i].drawLists[this.bit];\n      if (pd && pd.view.count > 0) return true;\n    }\n    return false;\n  }\n\n  /**\n   * Builds and culls this pass's draws before any render target is bound, on WebGPU with `cache: 'auto'`\n   * @param session - The current frame's render session\n   */\n  public override prepare(session: RenderSession): void {\n    this.pipe.prepareForward(this._forward, session);\n  }\n\n  /**\n   * Draws this pass's meshes from its camera\n   * @param session - The current frame's render session\n   */\n  public override render(session: RenderSession): void {\n    this.pipe.renderForward(this._forward, session);\n  }\n\n  /** Gives back the GPU memory this pass recorded for its draws; the next render rebuilds it */\n  public unload(): void {\n    this.cullResults.unload();\n  }\n\n  /** Releases what this pass recorded for its draws */\n  public override destroy(): void {\n    this.cullResults.release();\n    super.destroy();\n  }\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\nimport type { PassBuilder } from '../../render-graph/PassBuilder';\nimport type { ColorHandle, DepthHandle } from '../../render-graph/ResourceHandle';\nimport { ForwardRenderPass } from '../ForwardRenderPass';\nimport { RenderPassBit } from '../RenderPass';\n\n/**\n * Options for constructing a {@link BlendedRefractionPass}\n * @category rendering\n * @advanced\n */\nexport interface BlendedRefractionPassOptions {\n  /** Renderer the pass draws with: the {@link PassContext#renderer} a {@link Pass3D#build} call receives */\n  renderer: WebGLRenderer | WebGPURenderer;\n  /** Camera to draw from, or the view's own when omitted; see {@link RenderPassOptions#camera} */\n  camera?: Camera3D;\n  /**\n   * Opaque colour copy the materials refract, from a {@link CopyOpaquePass}: {@link PassContext#opaqueColor}\n   * for the view's own camera\n   */\n  opaqueColorHandle: ColorHandle;\n  /**\n   * Opaque depth copy the materials read, from a {@link CopyDepthPass}: {@link PassContext#opaqueDepth}\n   * for the view's own camera\n   */\n  opaqueDepthHandle: DepthHandle;\n}\n\n/**\n * Draws blended refractive materials, such as water, over copies of the opaque colour and depth\n *\n * Draws the meshes in {@link RenderPassBit.BLENDED_REFRACTION}, back to front from the camera and\n * re-sorted every frame. They test against the scene's depth.\n *\n * A {@link CopyOpaquePass} and a {@link CopyDepthPass} on the same camera must run earlier in the\n * graph. {@link createDefaultGraph3D} adds this pass and both copies for the view's camera.\n * @category rendering\n * @advanced\n */\nexport class BlendedRefractionPass extends ForwardRenderPass {\n  /** Opaque colour copy the materials refract, as given in {@link BlendedRefractionPassOptions#opaqueColorHandle} */\n  public readonly opaqueColorHandle: ColorHandle;\n  /** Opaque depth copy the materials sample, as given in {@link BlendedRefractionPassOptions#opaqueDepthHandle} */\n  public readonly opaqueDepthHandle: DepthHandle;\n\n  constructor(options: BlendedRefractionPassOptions) {\n    super({\n      renderer: options.renderer,\n      name: 'blendedRefraction',\n      description: 'Draws distance-sorted refractive materials using opaque color and depth copies.',\n      bit: RenderPassBit.BLENDED_REFRACTION,\n      sort: 'distance',\n      camera: options.camera,\n    });\n    this.opaqueColorHandle = options.opaqueColorHandle;\n    this.opaqueDepthHandle = options.opaqueDepthHandle;\n  }\n\n  /**\n   * Writes its camera's colour, declares its depth read-only, and samples both opaque copies\n   * @param b - The builder recording this pass's resource accesses\n   */\n  public override setup(b: PassBuilder): void {\n    b.writeColor(b.targetColor);\n    b.readDepthAttachment(b.targetDepth);\n    b.sample(this.opaqueColorHandle, b.globalTextureBindings.opaqueColor);\n    b.sample(this.opaqueDepthHandle, b.globalTextureBindings.opaqueDepth);\n  }\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\nimport type { PassBuilder } from '../../render-graph/PassBuilder';\nimport type { DepthHandle } from '../../render-graph/ResourceHandle';\nimport { RenderPass, RenderPassBit } from '../RenderPass';\nimport type { RenderSession } from '../RenderSession';\n\n/**\n * Options for constructing a {@link CopyDepthPass}\n * @category rendering\n * @advanced\n */\nexport interface CopyDepthPassOptions {\n  /** Renderer the pass copies with: the {@link PassContext#renderer} a {@link Pass3D#build} call receives */\n  renderer: WebGLRenderer | WebGPURenderer;\n  /** Camera whose depth is copied, or the view's own when omitted; see {@link RenderPassOptions#camera} */\n  camera?: Camera3D;\n  /**\n   * Depth texture the copy lands in; hand the same handle to the passes that sample it\n   *\n   * For another camera, create it with {@link RenderGraph#createDepth}.\n   */\n  opaqueDepthHandle: DepthHandle;\n}\n\n/**\n * Copies a camera's opaque depth into a texture for refractive materials to sample\n *\n * Effects that read the depth beneath them, such as a water shoreline or refraction that fades with\n * depth, draw over the opaque scene and so sample a copy of its depth. {@link createDefaultGraph3D}\n * copies the view's camera into {@link PassContext#opaqueDepth}. For another camera, add one after\n * the draws it copies and before the passes that sample it; passes on other targets can run in\n * between.\n *\n * The graph skips the copy on frames where nothing samples it. {@link BlendedRefractionPass} does,\n * but {@link TransmissionRenderPass} doesn't, so glass alone costs no depth copy.\n * @category rendering\n * @advanced\n */\nexport class CopyDepthPass extends RenderPass {\n  /** Depth texture the copy lands in, as given in {@link CopyDepthPassOptions#opaqueDepthHandle} */\n  public readonly opaqueDepthHandle: DepthHandle;\n\n  constructor(options: CopyDepthPassOptions) {\n    super({\n      renderer: options.renderer,\n      name: 'copyDepth',\n      description: 'Copies opaque depth into a texture for later screen-space sampling.',\n      bit: RenderPassBit.NONE,\n      camera: options.camera,\n    });\n    this.opaqueDepthHandle = options.opaqueDepthHandle;\n  }\n\n  /**\n   * Reads its camera's depth target and produces {@link CopyDepthPass#opaqueDepthHandle}\n   * @param b - The builder recording this pass's resource accesses\n   */\n  public override setup(b: PassBuilder): void {\n    b.read(b.targetDepth);\n    b.produce(this.opaqueDepthHandle);\n  }\n\n  /**\n   * Copies its camera's depth target into {@link CopyDepthPass#opaqueDepthHandle}\n   * @param session - The current frame's render session\n   */\n  public override render(session: RenderSession): void {\n    const graph = session.view3d._graph;\n    this.pipe.copyDepth(\n      graph._drawTarget(this.camera, session),\n      graph.getTexture(this.opaqueDepthHandle, session),\n      session,\n    );\n  }\n}\n","import { RendererType } from 'pixi.js';\nimport type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\nimport { warnOnce } from '../../../utils/warnOnce';\nimport type { PassBuilder } from '../../render-graph/PassBuilder';\nimport type { ColorHandle } from '../../render-graph/ResourceHandle';\nimport { RenderPass, RenderPassBit } from '../RenderPass';\nimport type { RenderSession } from '../RenderSession';\n\n/**\n * Options for constructing a {@link CopyOpaquePass}\n * @category rendering\n * @advanced\n */\nexport interface CopyOpaquePassOptions {\n  /** Renderer the pass copies with: the {@link PassContext#renderer} a {@link Pass3D#build} call receives */\n  renderer: WebGLRenderer | WebGPURenderer;\n  /** Camera whose picture is copied, or the view's own when omitted; see {@link RenderPassOptions#camera} */\n  camera?: Camera3D;\n  /**\n   * Colour texture the copy lands in; hand the same handle to the passes that sample it\n   *\n   * For another camera, create it with {@link RenderGraph#createColor} and `autoGenerateMipmaps: true`,\n   * or rough glass refracts it unblurred.\n   */\n  opaqueColorHandle: ColorHandle;\n}\n\n/**\n * Copies a camera's opaque picture into a texture for glass to sample\n *\n * Glass can't sample the target it draws into, so transmissive and blended refractive materials\n * refract a copy taken after the opaque draw. {@link createDefaultGraph3D} copies the view's camera\n * into {@link PassContext#opaqueColor}. For another camera, add one after the draws it copies and\n * before the passes that sample it; passes on other targets can run in between. The graph skips the\n * copy on frames where nothing samples it.\n *\n * On WebGL, give the renderer `useBackBuffer: true` when a view draws glass. Without it, a view\n * drawn straight to an opaque canvas (the default `backgroundAlpha: 1`) gets an empty copy, so its\n * glass refracts nothing. The pass warns once when it copies the view's picture with the setting off.\n * @category rendering\n * @advanced\n */\nexport class CopyOpaquePass extends RenderPass {\n  /** Colour texture the copy lands in, as given in {@link CopyOpaquePassOptions#opaqueColorHandle} */\n  public readonly opaqueColorHandle: ColorHandle;\n\n  /** Set by the first copy of the view's picture, so later frames skip the check and build no warning key */\n  private _backBufferWarned = false;\n\n  constructor(options: CopyOpaquePassOptions) {\n    super({\n      renderer: options.renderer,\n      name: 'copyOpaque',\n      description: 'Copies opaque color for transmission and refraction passes to sample.',\n      bit: RenderPassBit.NONE,\n      camera: options.camera,\n    });\n    this.opaqueColorHandle = options.opaqueColorHandle;\n  }\n\n  /**\n   * Reads its camera's colour target and produces {@link CopyOpaquePass#opaqueColorHandle}\n   * @param b - The builder recording this pass's resource accesses\n   */\n  public override setup(b: PassBuilder): void {\n    b.read(b.targetColor);\n    b.produce(this.opaqueColorHandle);\n  }\n\n  /**\n   * Copies its camera's colour target into {@link CopyOpaquePass#opaqueColorHandle}\n   * @param session - The current frame's render session\n   */\n  public override render(session: RenderSession): void {\n    if (!this.camera && !this._backBufferWarned) {\n      this._backBufferWarned = true;\n      const renderer = this.pipe.renderer;\n      if (renderer.type === RendererType.WEBGL && !(renderer as WebGLRenderer).backBuffer.useBackBuffer) {\n        warnOnce(\n          `pixijs-3d-copy-opaque-backbuffer-${renderer.uid}`,\n          '[@pixi/3d] Glass is drawing with useBackBuffer off, so a View3D drawn straight to an opaque canvas ' +\n            'refracts nothing. Pass useBackBuffer: true when you create the Application or renderer.',\n        );\n      }\n    }\n\n    const graph = session.view3d._graph;\n    this.pipe.copyColor(\n      graph._drawTarget(this.camera, session),\n      graph.getTexture(this.opaqueColorHandle, session),\n      session,\n    );\n  }\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\nimport type { PassBuilder } from '../../render-graph/PassBuilder';\nimport type { SceneOutput } from '../../render-graph/SceneOutput';\nimport { RenderPass, RenderPassBit } from '../RenderPass';\nimport type { RenderSession } from '../RenderSession';\n\ninterface DepthClearPassOptions {\n  renderer: WebGLRenderer | WebGPURenderer;\n  camera?: Camera3D;\n  attachedOutputs?: readonly SceneOutput[];\n}\n\n/**\n * Clears depth over `session.activeViewport` only, so other views and 2D content sharing the depth\n * buffer keep theirs\n * @internal\n */\nexport class DepthClearPass extends RenderPass {\n  constructor(options: DepthClearPassOptions) {\n    super({\n      renderer: options.renderer,\n      name: 'depthClear',\n      description: 'Clears this View3D depth region before scene geometry renders.',\n      bit: RenderPassBit.NONE,\n      camera: options.camera,\n      attachedOutputs: options.attachedOutputs,\n    });\n  }\n\n  /**\n   * Writes colour and the scene outputs as well as depth, to share the scene passes' target; on an\n   * offscreen target, its bind as first writer does the clear\n   */\n  public override setup(b: PassBuilder): void {\n    this._writeTarget(b);\n  }\n\n  /** Always clears for a camera, since `session.needsDepthClear` tracks only the view's own clear */\n  public override render(session: RenderSession): void {\n    if (!this.camera) {\n      if (!session.needsDepthClear) return;\n      session.needsDepthClear = false;\n    }\n    this.pipe.clearDepth(session);\n  }\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\nimport type { SceneOutput } from '../../render-graph/SceneOutput';\nimport { ForwardRenderPass } from '../ForwardRenderPass';\nimport { RenderPassBit } from '../RenderPass';\n\ninterface OpaqueRenderPassOptions {\n  renderer: WebGLRenderer | WebGPURenderer;\n  camera?: Camera3D;\n  attachedOutputs?: readonly SceneOutput[];\n}\n\n/** @internal */\nexport class OpaqueRenderPass extends ForwardRenderPass {\n  constructor(options: OpaqueRenderPassOptions) {\n    super({\n      renderer: options.renderer,\n      name: 'opaque',\n      description: 'Draws opaque scene geometry into scene color and depth.',\n      bit: RenderPassBit.OPAQUE,\n      sort: 'key',\n      camera: options.camera,\n      attachedOutputs: options.attachedOutputs,\n    });\n  }\n}\n","import type { ShaderBit } from '../../ShaderBit';\n\n/**\n * Stephen Hill's ACES fit, with the input scaled by 1/0.6 as Narkowicz pre-exposes his, so an input\n * of 1 lands near 0.76; then the display encode, which must match `srgbEncodeBit`\n * @internal\n */\nexport const acesToneMappingBit: ShaderBit = {\n  name: 'acesToneMapping',\n\n  gpu: {\n    header: `\nfn acesTonemap(linearColor: vec3<f32>) -> vec3<f32> {\n  let inMat = mat3x3<f32>(\n    vec3<f32>(0.59719, 0.07600, 0.02840),\n    vec3<f32>(0.35458, 0.90834, 0.13383),\n    vec3<f32>(0.04823, 0.01566, 0.83777),\n  );\n  let outMat = mat3x3<f32>(\n    vec3<f32>(1.60475, -0.10208, -0.00327),\n    vec3<f32>(-0.53108, 1.10813, -0.07276),\n    vec3<f32>(-0.07367, -0.00605, 1.07602),\n  );\n\n  var color = inMat * (linearColor * (1.0 / 0.6));\n\n  let a = color * (color + vec3<f32>(0.0245786)) - vec3<f32>(0.000090537);\n  let b = color * (0.983729 * color + vec3<f32>(0.4329510)) + vec3<f32>(0.238081);\n  color = a / b;\n\n  return clamp(outMat * color, vec3<f32>(0.0), vec3<f32>(1.0));\n}\n`,\n    fragment: {\n      end: `\n  finalColor = acesTonemap(finalColor);\n  finalColor = pow(finalColor, vec3<f32>(1.0 / 2.2));\n`,\n    },\n  },\n\n  gl: {\n    header: `\nvec3 acesTonemap(vec3 linearColor) {\n  const mat3 inMat = mat3(\n    vec3(0.59719, 0.07600, 0.02840),\n    vec3(0.35458, 0.90834, 0.13383),\n    vec3(0.04823, 0.01566, 0.83777)\n  );\n  const mat3 outMat = mat3(\n    vec3(1.60475, -0.10208, -0.00327),\n    vec3(-0.53108, 1.10813, -0.07276),\n    vec3(-0.07367, -0.00605, 1.07602)\n  );\n\n  vec3 color = inMat * (linearColor * (1.0 / 0.6));\n\n  vec3 a = color * (color + 0.0245786) - 0.000090537;\n  vec3 b = color * (0.983729 * color + 0.4329510) + 0.238081;\n  color = a / b;\n\n  return clamp(outMat * color, 0.0, 1.0);\n}\n`,\n    fragment: {\n      end: `\n  finalColor = acesTonemap(finalColor);\n  finalColor = pow(finalColor, vec3(1.0 / 2.2));\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../ShaderBit';\n\n/**\n * Ends with the display encode, which must match `srgbEncodeBit`\n * @internal\n */\nexport const reinhardToneMappingBit: ShaderBit = {\n  name: 'reinhardToneMapping',\n\n  gpu: {\n    fragment: {\n      end: `\n  finalColor = finalColor / (finalColor + vec3<f32>(1.0));\n\n  finalColor = pow(finalColor, vec3<f32>(1.0 / 2.2));\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      end: `\n  finalColor = finalColor / (finalColor + vec3(1.0));\n\n  finalColor = pow(finalColor, vec3(1.0 / 2.2));\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../ShaderBit';\n\n/**\n * Every curve bit ends with this `pow(x, 1 / 2.2)`, and every 2.2 decode, on the GPU or the CPU,\n * inverts it, so change them together\n * @internal\n */\nexport const srgbEncodeBit: ShaderBit = {\n  name: 'srgbEncode',\n\n  gpu: {\n    fragment: {\n      end: `\n  finalColor = pow(finalColor, vec3<f32>(1.0 / 2.2));\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      end: `\n  finalColor = pow(finalColor, vec3(1.0 / 2.2));\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../ShaderBit';\n\n/**\n * John Hable's Uncharted 2 curve (Hable 2010, \"Filmic Tonemapping Operators\"), then the display\n * encode, which must match `srgbEncodeBit`\n * @internal\n */\nexport const uncharted2ToneMappingBit: ShaderBit = {\n  name: 'uncharted2ToneMapping',\n\n  gpu: {\n    header: `\nfn uncharted2Curve(x: vec3<f32>) -> vec3<f32> {\n  let A = 0.15;\n  let B = 0.50;\n  let C = 0.10;\n  let D = 0.20;\n  let E = 0.02;\n  let F = 0.30;\n  return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\n}\n\nfn uncharted2Tonemap(color: vec3<f32>) -> vec3<f32> {\n  let exposureBias = 2.0;\n  let W = vec3<f32>(11.2);\n  let curr = uncharted2Curve(color * exposureBias);\n  let whiteScale = vec3<f32>(1.0) / uncharted2Curve(W);\n  return curr * whiteScale;\n}\n`,\n    fragment: {\n      end: `\n  finalColor = uncharted2Tonemap(finalColor);\n\n  finalColor = pow(finalColor, vec3<f32>(1.0 / 2.2));\n`,\n    },\n  },\n\n  gl: {\n    header: `\nvec3 uncharted2Curve(vec3 x) {\n  float A = 0.15;\n  float B = 0.50;\n  float C = 0.10;\n  float D = 0.20;\n  float E = 0.02;\n  float F = 0.30;\n  return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\n}\n\nvec3 uncharted2Tonemap(vec3 color) {\n  float exposureBias = 2.0;\n  vec3 W = vec3(11.2);\n  vec3 curr = uncharted2Curve(color * exposureBias);\n  vec3 whiteScale = vec3(1.0) / uncharted2Curve(W);\n  return curr * whiteScale;\n}\n`,\n    fragment: {\n      end: `\n  finalColor = uncharted2Tonemap(finalColor);\n\n  finalColor = pow(finalColor, vec3(1.0 / 2.2));\n`,\n    },\n  },\n};\n","import type { ToneMapping } from '../../../../scene/View3D';\nimport type { ShaderBit } from '../../ShaderBit';\nimport { acesToneMappingBit } from './acesToneMappingBit';\nimport { reinhardToneMappingBit } from './reinhardToneMappingBit';\nimport { srgbEncodeBit } from './srgbEncodeBit';\nimport { uncharted2ToneMappingBit } from './uncharted2ToneMappingBit';\n\n/**\n * `null` for `'custom'`, which leaves the output linear\n * @internal\n */\nexport const TONE_MAPPING_BITS: Record<ToneMapping, ShaderBit | null> = {\n  aces: acesToneMappingBit,\n  reinhard: reinhardToneMappingBit,\n  uncharted2: uncharted2ToneMappingBit,\n  none: srgbEncodeBit,\n  custom: null,\n};\n\n/** Leaves an alpha near 0 alone: additive light has no coverage and is already straight */\nconst straightColorBit: ShaderBit = {\n  name: 'outputStraightColor',\n  gpu: { fragment: { end: 'finalColor = select(finalColor, finalColor / fxColor.a, fxColor.a > 0.0001);' } },\n  gl: { fragment: { end: 'finalColor = fxColor.a > 0.0001 ? finalColor / fxColor.a : finalColor;' } },\n};\n\nconst premultiplyColorBit: ShaderBit = {\n  name: 'outputPremultiplyColor',\n  gpu: { fragment: { end: 'finalColor = select(finalColor, finalColor * fxColor.a, fxColor.a > 0.0001);' } },\n  gl: { fragment: { end: 'finalColor = fxColor.a > 0.0001 ? finalColor * fxColor.a : finalColor;' } },\n};\n\n/** Fixed per pixel so a still image doesn't shimmer, and scaled by alpha so clear pixels stay clear */\nconst ditherBit: ShaderBit = {\n  name: 'outputDither',\n  gpu: {\n    fragment: {\n      end: 'finalColor += (fract(52.9829189 * fract(dot(input.position.xy, vec2<f32>(0.06711056, 0.00583715)))) - 0.5) / 255.0 * fxColor.a;',\n    },\n  },\n  gl: {\n    fragment: {\n      end: 'finalColor += (fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5) / 255.0 * fxColor.a;',\n    },\n  },\n};\n\n/**\n * Needs the source colour in `fxColor`, the result in `finalColor` and, in WGSL, `input.position`\n * @internal\n */\nexport function toneOutputBits(toneMapping: ToneMapping | null | undefined): ShaderBit[] {\n  const curve = toneMapping ? TONE_MAPPING_BITS[toneMapping] : null;\n  return curve ? [straightColorBit, curve, premultiplyColorBit, ditherBit] : [];\n}\n","import { BindGroup, CLEAR, Rectangle, State, Texture, UniformGroup } from 'pixi.js';\nimport type { BindOptions, Shader, WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { ToneMapping } from '../../../scene/View3D';\nimport { fullscreenTriangleGeometry } from '../../fullscreenTriangleGeometry';\nimport type { DrawTarget } from '../../render-graph/RenderGraph';\nimport { toneOutputBits } from '../../shader/bits/tonemapping/toneMappingBits';\nimport type { ShaderBit } from '../../shader/ShaderBit';\nimport type { ShaderBitTemplate } from '../../shader/ShaderBitTemplate';\nimport type { View3DPipe } from '../../View3DPipe';\n\nconst scratchBind: BindOptions = { target: null!, clear: CLEAR.NONE };\nconst scratchViewport = new Rectangle();\n\nconst colorOutputBit: ShaderBit = {\n  name: 'colorOutputDraw',\n  attributes: {\n    aPosition: 'float32x2',\n  },\n  bindings: {\n    local: {\n      uSource: 'texture_2d<f32>',\n      uOffset: 'vec2<f32>',\n    },\n  },\n};\n\n/**\n * Reads by pixel position, not UV, so each texel lands where `copyColor` would put it on both\n * backends, as `View3DPipe.outputColor` promises\n */\nconst colorOutputTemplate: ShaderBitTemplate = {\n  bindGroups: ['local'],\n  gpu: /* wgsl */ `\n{{header}}\n\n@vertex\nfn mainVertex(input: VertexInput) -> VertexOutput {\n  var output: VertexOutput;\n  output.position = vec4<f32>(input.aPosition, 0.0, 1.0);\n  return output;\n}\n\n@fragment\nfn mainFragment(input: FragmentInput) -> @location(0) vec4<f32> {\n  let fxColor = textureLoad(uSource, vec2<i32>(input.position.xy + local.uOffset), 0);\n  var finalColor = fxColor.rgb;\n  {{fragmentEnd}}\n  return vec4<f32>(finalColor, fxColor.a);\n}\n`,\n  gl: {\n    vertex: /* glsl */ `#version 300 es\n\n{{header}}\n\nvoid main() {\n  gl_Position = vec4(aPosition, 0.0, 1.0);\n}\n`,\n    fragment: /* glsl */ `#version 300 es\n\n{{header}}\n\nout vec4 fragColor;\n\nvoid main() {\n  vec4 fxColor = texelFetch(uSource, ivec2(gl_FragCoord.xy + uOffset), 0);\n  vec3 finalColor = fxColor.rgb;\n  {{end}}\n  fragColor = vec4(finalColor, fxColor.a);\n}\n`,\n  },\n};\n\n/** @internal */\nexport class ColorOutputDraw {\n  private readonly _renderer: WebGPURenderer | WebGLRenderer;\n  private readonly _uniforms = new UniformGroup({ uOffset: { value: new Float32Array(2), type: 'vec2<f32>' } });\n  private readonly _bindGroup: BindGroup;\n  private readonly _shaders = new Map<ToneMapping | null, Shader>();\n  private readonly _state: State;\n\n  constructor(renderer: WebGPURenderer | WebGLRenderer) {\n    this._renderer = renderer;\n    this._bindGroup = new BindGroup({ local: this._uniforms, uSource: Texture.WHITE.source });\n    const state = new State();\n    state.blend = false;\n    state.depthTest = false;\n    state.depthMask = false;\n    state.culling = false;\n    this._state = state;\n  }\n\n  /**\n   * Clears only a `noFrame` dest, sparing tile GPUs a read-back; a clear would wipe the rest of a framed one's texture\n   *\n   * Puts the placeholder back after, so the bind group never keeps a pooled texture the pool may destroy.\n   * @param pipe - The pipe drawing it\n   * @param source - The camera's draw target and its content rect, in physical pixels\n   * @param dest - The texture to fill\n   * @param toneMapping - The tone mapping to apply, or `null` to change the format only\n   */\n  public draw(pipe: View3DPipe, source: DrawTarget, dest: Texture, toneMapping: ToneMapping | null): void {\n    const renderer = this._renderer;\n    const { viewport } = source;\n    const frame = dest.frame;\n    const resolution = dest.source.resolution;\n    const x = Math.round(frame.x * resolution);\n    const y = Math.round(frame.y * resolution);\n\n    const offset = this._uniforms.uniforms.uOffset as Float32Array;\n    offset[0] = viewport.x - x;\n    offset[1] = viewport.y - y;\n    this._uniforms.update();\n    const ubo =\n      'uniformBatch' in renderer.renderPipes\n        ? renderer.renderPipes.uniformBatch.getUboResource(this._uniforms)\n        : this._uniforms;\n    this._bindGroup.setResource(ubo, 'local');\n    this._bindGroup.setResource(source.target.colorTexture, 'uSource');\n\n    let shader = this._shaders.get(toneMapping);\n    if (!shader) {\n      shader = renderer.material3d.compileIsolatedShader(\n        [colorOutputBit, ...toneOutputBits(toneMapping)],\n        colorOutputTemplate,\n        {\n          0: this._bindGroup,\n        },\n      );\n      this._shaders.set(toneMapping, shader);\n    }\n\n    scratchBind.target = dest;\n    scratchBind.clear = dest.noFrame ? CLEAR.COLOR : CLEAR.NONE;\n    renderer.renderTarget.bind(scratchBind);\n    scratchBind.target = null!;\n    pipe.setViewport(scratchViewport.set(x, y, viewport.width, viewport.height));\n    pipe.renderGeometry(fullscreenTriangleGeometry(), shader, this._state);\n    this._bindGroup.setResource(Texture.WHITE.source, 'uSource');\n  }\n\n  public destroy(): void {\n    for (const shader of this._shaders.values()) shader.destroy();\n    (this._shaders as Map<ToneMapping | null, Shader> | null) = null;\n    this._bindGroup.destroy();\n  }\n}\n","import type { Camera3D } from '../../scene/cameras/Camera3D';\nimport type { CullResults } from './CullResults';\n\n/** @internal */\nexport interface RenderForwardDescriptor {\n  readonly bit: number;\n\n  readonly bindsMaterial: boolean;\n\n  /** Per pass, since passes on one bit share each batch's draw list but can each have their own camera */\n  readonly cullResults: CullResults;\n\n  /** `null` for the view's own camera */\n  readonly camera: Camera3D | null;\n\n  readonly sort: 'key' | 'distance';\n\n  /** Unset follows `sort`: a `'key'` pass caches and a `'distance'` pass doesn't */\n  readonly cache?: 'auto' | 'never';\n}\n\n/** @internal */\nexport function cachesDrawWork(desc: RenderForwardDescriptor): boolean {\n  return (desc.cache ?? (desc.sort === 'key' ? 'auto' : 'never')) === 'auto';\n}\n","import type { RenderTarget, TextureSource } from 'pixi.js';\n\nimport { Matrix4 } from '../../../math/matrix/Matrix4';\nimport { Box } from '../../../math/shapes/Box';\nimport { Sphere } from '../../../math/shapes/Sphere';\nimport { Vector3 } from '../../../math/vector/Vector3';\nimport type { Light, ShadowData } from '../../../scene/lights/Light';\nimport type { SpotLight } from '../../../scene/lights/SpotLight';\nimport type { View3D } from '../../../scene/View3D';\nimport { warnOnce } from '../../../utils/warnOnce';\nimport { CameraData } from '../../CameraData';\nimport type { PassBuilder } from '../../render-graph/PassBuilder';\nimport type { DepthHandle } from '../../render-graph/ResourceHandle';\nimport { DEPTH_EMPTY } from '../../textures/DefaultTextures';\nimport type { View3DPipe } from '../../View3DPipe';\nimport { RenderPass } from '../RenderPass';\nimport type { RenderPassOptions } from '../RenderPass';\nimport type { RenderSession } from '../RenderSession';\nimport {\n  computeCascadeMatrix,\n  computeCascadeSplits,\n  computeFixedBoxMatrix,\n  prepareLightSpaceTransform,\n} from './csmUtils';\nimport {\n  MAX_SHADOW_SLOTS,\n  SHADOW_QUALITY_SIZE,\n  cascadeCountFor,\n  cascadeRenderSkip,\n  createShadowRenderTarget,\n  updateRateFor,\n  updateSpotShadowMatrices,\n} from './shadowPassUtils';\nimport type { CascadeSlot, ShadowQuality } from './shadowPassUtils';\n\nconst tempEyeMatrix = new Matrix4();\nconst tempEye = new Vector3();\n\nconst _scratchSphere = new Sphere();\nconst _scratchBox = new Box();\nconst _scratchVec = new Vector3();\n\nconst DEFAULT_SHADOW_BIAS = 0.001;\n/** Default `shadow.normalBias` of a spot light, which `LightShadow.normalBias` in `Light.ts` states */\nconst SPOT_SHADOW_NORMAL_BIAS = 0.15;\n/**\n * Default `shadow.normalBias` of a directional light in shadow-map texels, which `LightShadow.normalBias`\n * in `Light.ts` states; the shadow bits taper it by `1 - N·L`, so this is the grazing-incidence offset\n */\nconst SHADOW_NORMAL_BIAS_TEXELS = 3;\n/** Default `shadow.maxDistance`, which `LightShadow.maxDistance` in `Light.ts` states */\nconst DEFAULT_CASCADE_MAX_DISTANCE = 50;\n/** World units per shadow-map texel above which the auto-fit box warns that shadows look soft */\nconst SHADOW_SOFT_TEXEL_THRESHOLD = 0.15;\n/** Casters up to which the auto-fit box re-measures every frame, which `LightShadow.bounds` in `Light.ts` states */\nconst MAX_AUTO_FIT_CASTERS = 256;\n\n/** The warnings built once, since their triggers hold frame after frame and the check must not allocate */\nconst WARN_BOUNDS_WITH_CASCADES =\n  'Shadow: shadow.bounds and shadow.cascades are both set — cascades take precedence and the bounds ' +\n  'box is ignored. Use bounds for a fixed region or cascades for a camera-following shadow, not both.';\nconst WARN_SHADOW_BOX_LARGE =\n  'Shadow auto-fit box spans a large scene, so shadows may look soft. Raise view3d.shadowQuality, set ' +\n  'light.shadow.bounds to the area that needs shadows, or, for a scene the camera roams across, enable ' +\n  'cascades: light.shadow.cascades = 3.';\nconst WARN_SHADOW_BUDGET =\n  `Too many shadow maps for the shadow budget of ${MAX_SHADOW_SLOTS}: each shadow-casting light takes one, ` +\n  `or one per cascade. Lights past the budget render without shadows.`;\n\ninterface ShadowRenderPassBaseOptions extends RenderPassOptions {\n  shadowMapHandle: DepthHandle;\n}\n\n/**\n * The shadow pass work both backends share; `ShadowRenderPassGpu` and `ShadowRenderPassGl` add the draws\n * @internal\n */\nexport abstract class ShadowRenderPassBase<\n  P extends View3DPipe = View3DPipe,\n  S extends ShadowData = ShadowData,\n> extends RenderPass<P> {\n  protected _renderTarget: RenderTarget | null = null;\n\n  /** Layers the shadow map holds: the most slots claimed, never shrinking, since each growth re-records every bundle */\n  private _layerCount = 0;\n\n  protected _quality: ShadowQuality = 'medium';\n  protected _frameCount = 0;\n  private _hasCastersValue = false;\n  private _hasCastersFrame = -1;\n  private readonly _sceneCasterBounds = new Box();\n  private _sceneBoundsFrame = -1;\n  private _destroyed = false;\n\n  /**\n   * Bumped when the map's contents are discarded; each light's `ShadowData.targetVersion` records the\n   * one its layers hold\n   */\n  public targetVersion = 0;\n\n  /** Kept so `unload`, which runs outside a frame, can unbind the map it frees */\n  private _view3d: View3D | null = null;\n\n  /** The graph's handle on the shadow map, imported in `createDefaultGraph3D` */\n  public readonly shadowMapHandle: DepthHandle;\n\n  constructor(options: ShadowRenderPassBaseOptions) {\n    super(options);\n    this.shadowMapHandle = options.shadowMapHandle;\n  }\n\n  /** The shadow map's render target, created on first use */\n  get renderTarget(): RenderTarget {\n    if (this._renderTarget === null) {\n      this._renderTarget = createShadowRenderTarget(this._quality, Math.max(this._layerCount, 1));\n    }\n\n    return this._renderTarget;\n  }\n\n  /**\n   * Grows the shadow map to cover `slots` layers; called as slots are claimed, before the graph\n   * runs, so the frame that needs more layers gets them\n   */\n  private _growAtlas(slots: number): void {\n    if (slots <= this._layerCount) return;\n\n    this._layerCount = Math.min(slots, MAX_SHADOW_SLOTS);\n    this._releaseTarget();\n  }\n\n  /** The shadow quality tier; a change frees the map, and the next access makes one at the new size */\n  set quality(value: ShadowQuality) {\n    if (value === this._quality) return;\n    this._quality = value;\n    this._releaseTarget();\n  }\n\n  get quality(): ShadowQuality {\n    return this._quality;\n  }\n\n  /**\n   * Start-of-frame bookkeeping; the lighting system calls it every frame, even when the pass is\n   * skipped, and nothing is bound yet, so a new `shadowQuality` can free the map here\n   */\n  public beginFrame(view3d: View3D): void {\n    this._view3d = view3d;\n    this.quality = view3d.shadowQuality;\n\n    this._frameCount++;\n    view3d._shadowDataList.reset();\n  }\n\n  /** Frees the shadow map; the next frame that needs shadows makes it again and every light re-renders */\n  public unload(): void {\n    this._releaseTarget();\n  }\n\n  /**\n   * Unbinds the map before destroying it, so no bundle replays the freed view; pixi's\n   * `RenderTarget.destroy` leaves a depth texture it was handed\n   */\n  private _releaseTarget(): void {\n    const target = this._renderTarget;\n    if (!target) return;\n\n    this._renderTarget = null;\n    this.targetVersion++;\n\n    if (this._view3d) this._bindShadowSource(this._view3d, DEPTH_EMPTY.source);\n\n    const shadowMap = target.depthStencilTexture!;\n    target.destroy();\n    shadowMap.destroy();\n  }\n\n  /**\n   * Points the view's global shadow-map slot at `source`, re-recording every bundle in the view on a\n   * change; it compares with the slot itself, since the view can re-create its global group\n   */\n  protected _bindShadowSource(view3d: View3D, source: TextureSource): void {\n    const { group, slot } = view3d._graph.globalTextureBindings.shadowMap;\n    if (group.getResource(slot) === source) return;\n\n    group.setResource(source, slot);\n    view3d._invalidateBundleCaches();\n  }\n\n  /** Declares the shadow map as a produce, so the graph binds no target and the pass binds its own layers */\n  public override setup(b: PassBuilder): void {\n    b.produce(this.shadowMapHandle);\n  }\n\n  /**\n   * Skips the frame when no light can cast or no mesh is in the shadow pass; hidden casters count,\n   * so the WebGPU pass still releases a hidden light's cull results for batches that left the view\n   */\n  public override condition(session: RenderSession): boolean {\n    const lights = session.lights;\n\n    for (let i = 0; i < lights.length; i++) {\n      if (lights[i].canCastShadow) return this._hasCasters(session.view3d);\n    }\n\n    return false;\n  }\n\n  /** Whether any mesh is in the shadow pass this frame, hidden ones included; read once per frame */\n  private _hasCasters(view3d: View3D): boolean {\n    if (this._hasCastersFrame === this._frameCount) return this._hasCastersValue;\n    this._hasCastersFrame = this._frameCount;\n\n    const batches = view3d._meshBatches;\n    let hasCasters = false;\n\n    for (let i = 0; i < batches.length && !hasCasters; i++) {\n      hasCasters = (batches[i].drawLists[this.bit]?.view.count ?? 0) > 0;\n    }\n\n    this._hasCastersValue = hasCasters;\n\n    return hasCasters;\n  }\n\n  /** `true` remaps shadow depth to 0 to 1 for WebGPU; `false` keeps WebGL's -1 to 1 */\n  protected abstract readonly _applyZRangeFix: boolean;\n\n  /** The light's shadow data, created on first use */\n  public getShadowGPUData(light: Light): S {\n    return (light._gpuShadowData ??= {\n      inverseLightMatrix: new Matrix4(),\n      lightProjectionMatrix: new Matrix4(),\n      /** Current from the start; a new light's first layers come from `_shadowRefreshRequested` */\n      targetVersion: this.targetVersion,\n    }) as S;\n  }\n\n  /**\n   * The light's cascade slot, created on first use with a camera group of its own: WebGPU's\n   * `writeBuffer` calls all land before the bundles run, so a shared group would draw every cascade alike\n   */\n  protected _cascadeSlot(light: Light, cascadeIndex: number): CascadeSlot {\n    const cascades = (this.getShadowGPUData(light).cascades ??= []);\n\n    return (cascades[cascadeIndex] ??= {\n      cameraData: new CameraData(),\n      bias: 0,\n      normalBias: 0,\n      mapSize: 0,\n      cascadeCount: 0,\n      splits: null,\n      needsRender: true,\n    });\n  }\n\n  /**\n   * Writes a fitted cascade's matrices and cull volume into its camera data, so a cascade throttled\n   * off later frames keeps a frustum that matches its frozen matrices\n   */\n  protected _commitCascadeCamera(slot: CascadeSlot, view: Matrix4, projection: Matrix4): void {\n    tempEyeMatrix.getInverse(view);\n    tempEyeMatrix.extractPosition(tempEye);\n\n    const cameraData = slot.cameraData;\n\n    cameraData.set(tempEye, view, projection);\n    cameraData.frustum.setFromProjectionMatrix(cameraData.viewProjection);\n  }\n\n  /**\n   * Fits a light's shadow and fills its cascade slots for `uShadowData`; a cascade its update rate\n   * skips keeps its matrices, and re-renders only when the map was discarded since\n   */\n  public updateLightShadowData(light: Light, view3d: View3D): void {\n    if (!light.canCastShadow) return;\n\n    const camera = view3d.camera;\n    const shadowData = this.getShadowGPUData(light);\n    const { inverseLightMatrix, lightProjectionMatrix } = shadowData;\n    const targetStale = shadowData.targetVersion !== this.targetVersion;\n    const mapSize = SHADOW_QUALITY_SIZE[this._quality];\n    const forceUpdate = light._shadowRefreshRequested;\n    const update = light.shadow.update;\n    const bias = light.shadow.bias ?? DEFAULT_SHADOW_BIAS;\n\n    if (light.type === 'spot' || light.shadow.cascades === undefined) {\n      const slot = this._cascadeSlot(light, 0);\n      const renderSkip = cascadeRenderSkip(updateRateFor(update, 0), this._frameCount, forceUpdate);\n\n      if (!renderSkip) {\n        if (light.type === 'spot') {\n          updateSpotShadowMatrices(light as SpotLight, inverseLightMatrix, lightProjectionMatrix, this._applyZRangeFix);\n          this._commitCascadeCamera(slot, inverseLightMatrix, lightProjectionMatrix);\n          slot.normalBias = light.shadow.normalBias ?? SPOT_SHADOW_NORMAL_BIAS;\n        } else {\n          const bounds = light.shadow.bounds ?? this._resolveAutoShadowBounds(light, view3d, mapSize);\n          if (bounds !== undefined && !bounds.isEmpty()) {\n            inverseLightMatrix.getInverse(light.worldTransform);\n            computeFixedBoxMatrix(bounds, inverseLightMatrix, lightProjectionMatrix, mapSize, this._applyZRangeFix);\n            this._commitCascadeCamera(slot, inverseLightMatrix, lightProjectionMatrix);\n            slot.normalBias = this._resolveNormalBias(light, lightProjectionMatrix, mapSize);\n          }\n        }\n      }\n\n      slot.bias = bias;\n      slot.mapSize = mapSize;\n      slot.cascadeCount = 0;\n      slot.splits = null;\n      slot.needsRender = targetStale || !renderSkip;\n      return;\n    }\n\n    if (light.shadow.bounds !== undefined) warnOnce('pixijs-3d-shadow-bounds-cascades', WARN_BOUNDS_WITH_CASCADES);\n    inverseLightMatrix.getInverse(light.worldTransform);\n\n    const cascadeCount = cascadeCountFor(light);\n    const lambda = light.shadow.lambda;\n\n    const maxDist = Math.min(light.shadow.maxDistance ?? DEFAULT_CASCADE_MAX_DISTANCE, camera.far);\n\n    const cascade0 = this._cascadeSlot(light, 0);\n    const splits = (cascade0.splits ??= []);\n    computeCascadeSplits(camera.near, maxDist, cascadeCount, lambda, splits);\n\n    prepareLightSpaceTransform(camera, inverseLightMatrix);\n\n    for (let c = 0; c < cascadeCount; c++) {\n      const slot = c === 0 ? cascade0 : this._cascadeSlot(light, c);\n      const renderSkip = cascadeRenderSkip(updateRateFor(update, c), this._frameCount, forceUpdate);\n\n      if (!renderSkip) {\n        const splitNear = c === 0 ? camera.near : splits[c - 1];\n        computeCascadeMatrix(camera, splitNear, splits[c], lightProjectionMatrix, mapSize, this._applyZRangeFix);\n        this._commitCascadeCamera(slot, inverseLightMatrix, lightProjectionMatrix);\n        slot.normalBias = this._resolveNormalBias(light, lightProjectionMatrix, mapSize);\n      }\n\n      slot.bias = bias;\n      slot.mapSize = mapSize;\n      slot.cascadeCount = c === 0 && cascadeCount > 1 ? cascadeCount : 0;\n      if (c > 0) slot.splits = null;\n      slot.needsRender = targetStale || !renderSkip;\n    }\n  }\n\n  /**\n   * Marks a light's layers current; the backends call it once the draws ran, so a refresh is marked\n   * done only on a frame that drew the light\n   */\n  protected _completeShadowUpdate(light: Light): void {\n    if (light._gpuShadowData) light._gpuShadowData.targetVersion = this.targetVersion;\n    light._shadowRefreshRequested = false;\n  }\n\n  /** The auto-fit box of a directional light with no `shadow.bounds`, or `undefined` before any caster */\n  private _resolveAutoShadowBounds(light: Light, view3d: View3D, mapSize: number): Box | undefined {\n    const casterCount = this._countSceneCasters(view3d);\n    const prev = light._autoShadowBounds;\n\n    if (casterCount > MAX_AUTO_FIT_CASTERS && light._autoShadowBoundsFrozen) return prev ?? undefined;\n\n    const gathered = this._ensureSceneCasterBounds(view3d);\n    if (gathered.isEmpty()) return prev ?? undefined;\n\n    const box = prev ?? (light._autoShadowBounds = new Box());\n    box.copyFrom(gathered);\n\n    if (casterCount <= MAX_AUTO_FIT_CASTERS) {\n      light._autoShadowBoundsFrozen = false;\n    } else {\n      light._autoShadowBoundsFrozen = true;\n      warnOnce(\n        'pixijs-3d-shadow-autofit-cap',\n        `Shadow auto-fit: ${casterCount} shadow casters is over the auto-measure cap (${MAX_AUTO_FIT_CASTERS}), ` +\n          `so the shadow box was fitted once and frozen. If casters move or spawn outside it, set shadow.bounds, ` +\n          `enable shadow.cascades, or call light.fitShadowBounds() after changes.`,\n      );\n    }\n\n    this._warnIfShadowBoxLarge(box, mapSize);\n    return box;\n  }\n\n  private _countSceneCasters(view3d: View3D): number {\n    let count = 0;\n    const batches = view3d._meshBatches;\n\n    for (let b = 0; b < batches.length; b++) {\n      const batch = batches[b];\n      if (!batch.renderData._worldVisible) continue;\n      const pd = batch.drawLists[this.bit];\n      if (pd) count += pd.view.count;\n    }\n\n    return count;\n  }\n\n  /**\n   * World-space box around every visible shadow caster, gathered once per frame; the scene batch,\n   * always first, holds world-space spheres, and a {@link BatchedMesh3D}'s are batch-local\n   */\n  private _ensureSceneCasterBounds(view3d: View3D): Box {\n    if (this._sceneBoundsFrame === this._frameCount) return this._sceneCasterBounds;\n    this._sceneBoundsFrame = this._frameCount;\n\n    const box = this._sceneCasterBounds.makeEmpty();\n    const batches = view3d._meshBatches;\n\n    for (let b = 0; b < batches.length; b++) {\n      const batch = batches[b];\n      if (!batch.renderData._worldVisible) continue;\n      const list = batch.drawLists[this.bit];\n      if (!list || list.view.count === 0) continue;\n\n      const batchMatrix = b === 0 ? null : batch.renderData.worldTransform;\n      const items = list.view.items;\n      const renderableIndices = list.view.renderableIndices;\n\n      for (let i = 0; i < list.view.count; i++) {\n        const item = items[renderableIndices[i]];\n        if (item._worldVisible === 0) continue;\n        const sphere = item.boundingSphere;\n        if (sphere.radius < 0) continue;\n\n        const world = batchMatrix ? sphere.applyMatrix4(batchMatrix, _scratchSphere) : sphere;\n        box.union(world.getBounds(_scratchBox));\n      }\n    }\n\n    return box;\n  }\n\n  private _warnIfShadowBoxLarge(bounds: Box, mapSize: number): void {\n    if (bounds.isEmpty()) return;\n\n    const size = bounds.getSize(_scratchVec);\n    if (Math.max(size.x, size.y, size.z) / mapSize > SHADOW_SOFT_TEXEL_THRESHOLD) {\n      warnOnce('pixijs-3d-shadow-autofit-large', WARN_SHADOW_BOX_LARGE);\n    }\n  }\n\n  /** The light's `shadow.normalBias`, else {@link SHADOW_NORMAL_BIAS_TEXELS} at the projection's texel size */\n  private _resolveNormalBias(light: Light, orthoProjection: Matrix4, mapSize: number): number {\n    if (light.shadow.normalBias !== undefined) return light.shadow.normalBias;\n    const texelWorld = 2 / (orthoProjection.elements[0] * mapSize);\n    return SHADOW_NORMAL_BIAS_TEXELS * texelWorld;\n  }\n\n  /**\n   * Claims a light's shadow slots, fits it, and adds its slots to the view's shadow list; the\n   * lighting systems' one entry point, so they never track shadow state\n   */\n  public prepareShadow(light: Light, view3d: View3D): void {\n    const list = view3d._shadowDataList;\n    const slots = this._claimShadowSlots(light, view3d, list.count);\n    if (slots === 0) return;\n\n    this._growAtlas(list.count + slots);\n    this.updateLightShadowData(light, view3d);\n\n    const cascades = this.getShadowGPUData(light).cascades!;\n    for (let c = 0; c < slots; c++) list.add(cascades[c]);\n  }\n\n  /**\n   * Claims this frame's slots for a light and sets its `_shadowDataIndex`, or sets -1 and returns 0\n   * when it can't cast, nothing casts, or the budget is full\n   */\n  private _claimShadowSlots(light: Light, view3d: View3D, claimed: number): number {\n    const castsShadow = light.canCastShadow && this._hasCasters(view3d);\n    const cascadeCount = cascadeCountFor(light);\n\n    if (castsShadow && claimed + cascadeCount <= MAX_SHADOW_SLOTS) {\n      light._shadowDataIndex = claimed;\n      return cascadeCount;\n    }\n\n    if (castsShadow) warnOnce('pixijs-3d-shadow-budget', WARN_SHADOW_BUDGET);\n\n    light._shadowDataIndex = -1;\n    return 0;\n  }\n\n  /**\n   * Releases the shadow map without unbinding it, since the view tears its global bind group down\n   * before it destroys the graph\n   */\n  public override destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n\n    this._view3d = null;\n    this._releaseTarget();\n\n    super.destroy();\n  }\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\nimport type { PassBuilder } from '../../render-graph/PassBuilder';\nimport type { ColorHandle } from '../../render-graph/ResourceHandle';\nimport type { SceneOutput } from '../../render-graph/SceneOutput';\nimport { ForwardRenderPass } from '../ForwardRenderPass';\nimport { RenderPassBit } from '../RenderPass';\n\n/**\n * Options for constructing a {@link TransmissionRenderPass}\n * @category rendering\n * @advanced\n */\nexport interface TransmissionRenderPassOptions {\n  /** Renderer the pass draws with: the {@link PassContext#renderer} a {@link Pass3D#build} call receives */\n  renderer: WebGLRenderer | WebGPURenderer;\n  /** Camera to draw from, or the view's own when omitted; see {@link RenderPassOptions#camera} */\n  camera?: Camera3D;\n  /**\n   * Opaque colour copy the glass refracts, from a {@link CopyOpaquePass}: {@link PassContext#opaqueColor}\n   * for the view's own camera\n   */\n  opaqueColorHandle: ColorHandle;\n  /** The scene outputs attached after the target colour; see {@link RenderPassOptions#attachedOutputs} */\n  attachedOutputs?: readonly SceneOutput[];\n}\n\n/**\n * Draws transmissive (glass) materials over a copy of the opaque picture behind them\n *\n * Draws the meshes whose material sets {@link Material3DOptions#transmission}. Each fragment\n * refracts the opaque colour copy, rough glass through the copy's blurred mip levels, so a\n * {@link CopyOpaquePass} on the same camera must run earlier in the graph.\n * {@link createDefaultGraph3D} adds this pass and its copy for the view's camera.\n *\n * The copy is taken before any glass draws, so glass behind glass doesn't show through it. Glass\n * writes depth by default, so it hides particles and anything else drawn behind it later. A frame\n * with no glass in the scene skips the copy, unless something else samples it.\n * @category rendering\n * @advanced\n */\nexport class TransmissionRenderPass extends ForwardRenderPass {\n  /** Opaque colour copy the glass refracts, as given in {@link TransmissionRenderPassOptions#opaqueColorHandle} */\n  public readonly opaqueColorHandle: ColorHandle;\n\n  constructor(options: TransmissionRenderPassOptions) {\n    super({\n      renderer: options.renderer,\n      name: 'transmission',\n      description: 'Draws transmissive materials using the opaque scene color behind them.',\n      bit: RenderPassBit.TRANSMISSION,\n      sort: 'key',\n      camera: options.camera,\n      attachedOutputs: options.attachedOutputs,\n    });\n    this.opaqueColorHandle = options.opaqueColorHandle;\n  }\n\n  /**\n   * Writes its camera's colour and depth, and samples the opaque colour copy\n   * @param b - The builder recording this pass's resource accesses\n   */\n  public override setup(b: PassBuilder): void {\n    super.setup(b);\n    b.sample(this.opaqueColorHandle, b.globalTextureBindings.opaqueColor);\n  }\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { Camera3D } from '../../../scene/cameras/Camera3D';\nimport type { SceneOutput } from '../../render-graph/SceneOutput';\nimport { ForwardRenderPass } from '../ForwardRenderPass';\nimport { RenderPassBit } from '../RenderPass';\n\ninterface TransparentRenderPassOptions {\n  renderer: WebGLRenderer | WebGPURenderer;\n  camera?: Camera3D;\n  attachedOutputs?: readonly SceneOutput[];\n}\n\n/** @internal */\nexport class TransparentRenderPass extends ForwardRenderPass {\n  constructor(options: TransparentRenderPassOptions) {\n    super({\n      renderer: options.renderer,\n      name: 'transparent',\n      description: 'Draws distance-sorted transparent scene geometry after opaque and refractive content.',\n      bit: RenderPassBit.TRANSPARENT,\n      sort: 'distance',\n      camera: options.camera,\n      attachedOutputs: options.attachedOutputs,\n    });\n  }\n}\n","import type { Matrix4 } from '../../../math/matrix/Matrix4';\nimport type { Vector3 } from '../../../math/vector/Vector3';\nimport type { Mesh3DData } from '../../batcher/Mesh3DData';\nimport type { SortedMesh3DView } from '../../batcher/SortedMesh3DView';\nimport { MESH3D_STORE_STRIDE } from '../../buffers/Mesh3DDataStoreBuffer';\n\n/**\n * Sorts back to front: keys are negated squared distances, so the ascending sort puts the farthest first\n *\n * Positions are store-row lanes 12 to 14: world space in the scene batch, batch-local in a {@link BatchedMesh3D}'s.\n * @internal\n */\nexport function calculateTransparentDistances(\n  renderables: SortedMesh3DView<Mesh3DData>,\n  transformData: Float32Array,\n  cameraPos: Vector3,\n): void {\n  const camX = cameraPos.x;\n  const camY = cameraPos.y;\n  const camZ = cameraPos.z;\n\n  const items = renderables.items;\n  const renderableIndices = renderables.renderableIndices;\n  const count = renderables.count;\n\n  for (let i = 0; i < count; i++) {\n    const renderable = items[renderableIndices[i]];\n\n    const matrixOffset = renderable._storeIndex * MESH3D_STORE_STRIDE;\n\n    const dx = transformData[matrixOffset + 12] - camX;\n    const dy = transformData[matrixOffset + 13] - camY;\n    const dz = transformData[matrixOffset + 14] - camZ;\n\n    const distSq = dx * dx + dy * dy + dz * dz;\n\n    renderable._sortKey = -distSq;\n  }\n\n  renderables.sortForced((m) => m._sortKey);\n}\n\n/**\n * Sorts back to front, keyed as {@link calculateTransparentDistances}\n * @internal\n */\nexport function calculateDistancesFromWorldMatrix(renderables: SortedMesh3DView<Mesh3DData>, cameraPos: Vector3): void {\n  const camX = cameraPos.x;\n  const camY = cameraPos.y;\n  const camZ = cameraPos.z;\n\n  const items = renderables.items;\n  const renderableIndices = renderables.renderableIndices;\n  const count = renderables.count;\n\n  for (let i = 0; i < count; i++) {\n    const renderable = items[renderableIndices[i]] as Mesh3DData & { worldTransform: Matrix4 };\n    const e = renderable.worldTransform.elements;\n\n    const dx = e[12] - camX;\n    const dy = e[13] - camY;\n    const dz = e[14] - camZ;\n\n    renderable._sortKey = -(dx * dx + dy * dy + dz * dz);\n  }\n\n  renderables.sortForced((m) => m._sortKey);\n}\n\n/**\n * Sorts back to front, keyed as {@link calculateTransparentDistances}\n * @internal\n */\nexport function calculateDistancesFromStore(\n  renderables: SortedMesh3DView<Mesh3DData>,\n  cameraPos: Vector3,\n  storeF32: Float32Array,\n  batchMatrix: Matrix4,\n): void {\n  const camX = cameraPos.x;\n  const camY = cameraPos.y;\n  const camZ = cameraPos.z;\n  const bm = batchMatrix.elements;\n\n  const items = renderables.items;\n  const renderableIndices = renderables.renderableIndices;\n  const count = renderables.count;\n\n  for (let i = 0; i < count; i++) {\n    const renderable = items[renderableIndices[i]];\n    const s = renderable._storeIndex * MESH3D_STORE_STRIDE;\n    const tx = storeF32[s + 12];\n    const ty = storeF32[s + 13];\n    const tz = storeF32[s + 14];\n\n    const wx = bm[0] * tx + bm[4] * ty + bm[8] * tz + bm[12];\n    const wy = bm[1] * tx + bm[5] * ty + bm[9] * tz + bm[13];\n    const wz = bm[2] * tx + bm[6] * ty + bm[10] * tz + bm[14];\n\n    const dx = wx - camX;\n    const dy = wy - camY;\n    const dz = wz - camZ;\n\n    renderable._sortKey = -(dx * dx + dy * dy + dz * dz);\n  }\n\n  renderables.sortForced((m) => m._sortKey);\n}\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * Must follow the material's bits, so its `end` code overrides any alpha they write\n * @internal\n */\nexport const alphaOpaqueBit: ShaderBit = {\n  name: 'alphaOpaque',\n  gpu: {\n    fragment: {\n      end: /*wgsl*/ `\n  alpha = 1.0;\n`,\n    },\n  },\n  gl: {\n    fragment: {\n      end: /*glsl*/ `\n  alpha = 1.0;\n`,\n    },\n  },\n};\n","import { LIGHT_DEPTH_LANES, LIGHT_TILE_LANES } from '../../LightTiles';\nimport type { ShaderBit } from '../ShaderBit';\n\n/**\n * Must match the uniform group `CameraData` builds, field for field and in order\n * @internal\n */\nexport const cameraBit: ShaderBit = {\n  name: 'camera',\n  bindings: {\n    camera: {\n      uCameraPosition: 'vec3<f32>',\n      uViewMatrix: 'mat4x4<f32>',\n      uProjectionMatrix: 'mat4x4<f32>',\n      uViewProjectionMatrix: 'mat4x4<f32>',\n      uPreviousViewProjectionMatrix: 'mat4x4<f32>',\n      uViewportUVScale: 'vec2<f32>',\n      uLightTileTransform: 'vec4<f32>',\n      uLightTiles: `array<vec4<i32>, ${LIGHT_TILE_LANES}>`,\n      uLightDepthMasks: `array<vec4<i32>, ${LIGHT_DEPTH_LANES}>`,\n      uLightDepthPlane: 'vec4<f32>',\n    },\n  },\n};\n","import type { BaseMaterial3D } from '../../../materials/BaseMaterial3D';\nimport type { ShaderBit } from '../ShaderBit';\nimport { srgbEncodeBit } from './tonemapping/srgbEncodeBit';\n\nfunction helpers(name: string, color: string, input: 'linear' | 'display', frame: string): ShaderBit {\n  const wgsl = /*wgsl*/ `\nfn decodeColor(c: vec3<f32>) -> vec3<f32> { return ${color.replace('VEC3', 'vec3<f32>')}; }\nfn inputTint(linearTint: vec4<f32>, displayTint: vec4<f32>) -> vec4<f32> { return ${input}Tint; }\nfn inputExposure(linearExposure: f32, displayExposure: f32) -> f32 { return ${input}Exposure; }\nfn decodeFrame(c: vec3<f32>) -> vec3<f32> { return ${frame.replace('VEC3', 'vec3<f32>')}; }\n`;\n  const glsl = /*glsl*/ `\nvec3 decodeColor(vec3 c) { return ${color.replace('VEC3', 'vec3')}; }\nvec4 inputTint(vec4 linearTint, vec4 displayTint) { return ${input}Tint; }\nfloat inputExposure(float linearExposure, float displayExposure) { return ${input}Exposure; }\nvec3 decodeFrame(vec3 c) { return ${frame.replace('VEC3', 'vec3')}; }\n`;\n\n  return {\n    name,\n    gpu: { header: wgsl },\n    gl: { header: glsl },\n  };\n}\n\nconst linearColorSpaceBit: ShaderBit = helpers('colorSpaceLinear', 'pow(c, VEC3(2.2))', 'linear', 'pow(c, VEC3(2.2))');\n\nconst linearFramesColorSpaceBit: ShaderBit = helpers('colorSpaceLinearFrames', 'pow(c, VEC3(2.2))', 'linear', 'c');\n\n/**\n * Gives the same bytes as linear light only while the encode is a pure 2.2 gamma, which the\n * decode then cancels\n * @internal\n */\nexport const displayColorSpaceBit: ShaderBit = helpers('colorSpaceDisplay', 'c', 'display', 'c');\n\n/**\n * Picks display space only for a `colorSpace: 'display'` material where it gives the same bytes as\n * linear light: unlit, ending in the encode alone, with nothing mixed in linear light\n * @internal\n */\nexport function selectColorSpaceBit(\n  material: BaseMaterial3D,\n  toneBit: ShaderBit | null,\n  linearInputs: boolean,\n): ShaderBit {\n  if (!toneBit) return linearFramesColorSpaceBit;\n\n  const encodeOnly = material._skipsToneCurve || toneBit === srgbEncodeBit;\n  const display = material.colorSpace === 'display' && !material.lit && encodeOnly && !linearInputs;\n\n  return display ? displayColorSpaceBit : linearColorSpaceBit;\n}\n","import type { ShaderBit } from '../ShaderBit';\n\n/** @internal */\nexport const doubleSidedNormalBit: ShaderBit = {\n  name: 'doubleSidedNormal',\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  normal = select(-normal, normal, input.frontFacing);\n`,\n    },\n  },\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  if (!gl_FrontFacing) {\n    normal = -normal;\n  }\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\n\n/** @internal */\nexport const envSourceCubeBit: ShaderBit = {\n  name: 'envSourceCube',\n\n  gpu: {\n    header: /*wgsl*/ `\nfn sampleEnvironment(dir: vec3<f32>, roughness: f32) -> vec3<f32> {\n  let maxMip = f32(textureNumLevels(uEnvironmentTexture) - 1u);\n  return textureSampleLevel(uEnvironmentTexture, uSampler, dir, roughness * maxMip).rgb;\n}\n`,\n  },\n\n  gl: {\n    header: /*glsl*/ `\nvec3 sampleEnvironment(vec3 dir, float roughness) {\n  return textureLod(uEnvironmentTexture, dir, roughness * uEnvironmentMaxMipLevel).rgb;\n}\n`,\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\n\n/** @internal */\nexport const envSourceDefaultBit: ShaderBit = {\n  name: 'envSourceDefault',\n\n  gpu: {\n    header: /*wgsl*/ `\nfn sampleEnvironment(dir: vec3<f32>, roughness: f32) -> vec3<f32> {\n  return vec3<f32>(0.0);\n}\n`,\n  },\n\n  gl: {\n    header: /*glsl*/ `\nvec3 sampleEnvironment(vec3 dir, float roughness) {\n  return vec3(0.0);\n}\n`,\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\n\n/** @internal */\nexport const envSourceHemisphereBit: ShaderBit = {\n  name: 'envSourceHemisphere',\n\n  gpu: {\n    header: /*wgsl*/ `\nfn sampleEnvironment(dir: vec3<f32>, roughness: f32) -> vec3<f32> {\n  let t = dot(dir, global.uHemisphereUp) * 0.5 + 0.5;\n  return mix(global.uHemisphereGround, global.uHemisphereSky, t);\n}\n`,\n  },\n\n  gl: {\n    header: /*glsl*/ `\nvec3 sampleEnvironment(vec3 dir, float roughness) {\n  float t = dot(dir, uHemisphereUp) * 0.5 + 0.5;\n  return mix(uHemisphereGround, uHemisphereSky, t);\n}\n`,\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * The derivative normal's sign follows screen handedness, so it's flipped to agree with `normal`\n * @internal\n */\nexport const flatShadingBit: ShaderBit = {\n  name: 'flatShading',\n\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  let flatNormal = normalize(cross(dpdx(input.vPosition), dpdy(input.vPosition)));\n  normal = select(-flatNormal, flatNormal, dot(flatNormal, normal) >= 0.0);\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  vec3 flatNormal = normalize(cross(dFdx(vPosition), dFdy(vPosition)));\n  normal = dot(flatNormal, normal) >= 0.0 ? flatNormal : -flatNormal;\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../ShaderBit';\n\n/** @internal */\nexport const exp2FogBit: ShaderBit = {\n  name: 'exp2Fog',\n\n  interStage: {\n    vFogDepth: 'f32',\n  },\n\n  gpu: {\n    vertex: {\n      afterTransform: /*wgsl*/ `\n  output.vFogDepth = -(camera.uViewMatrix * worldPosition).z;\n`,\n    },\n    fragment: {\n      end: /*wgsl*/ `\n  let fogD = global.uFogParams.z * input.vFogDepth;\n  let fogFactor = 1.0 - exp(-fogD * fogD);\n  finalColor = mix(finalColor, global.uFogColor, fogFactor);\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      afterTransform: /*glsl*/ `\n  vFogDepth = -(uViewMatrix * worldPosition).z;\n`,\n    },\n    fragment: {\n      end: /*glsl*/ `\n  float fogD = uFogParams.z * vFogDepth;\n  float fogFactor = 1.0 - exp(-fogD * fogD);\n  finalColor = mix(finalColor, uFogColor, fogFactor);\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../ShaderBit';\n\n/** @internal */\nexport const exponentialFogBit: ShaderBit = {\n  name: 'exponentialFog',\n\n  interStage: {\n    vFogDepth: 'f32',\n  },\n\n  gpu: {\n    vertex: {\n      afterTransform: /*wgsl*/ `\n  output.vFogDepth = -(camera.uViewMatrix * worldPosition).z;\n`,\n    },\n    fragment: {\n      end: /*wgsl*/ `\n  let fogFactor = 1.0 - exp(-global.uFogParams.z * input.vFogDepth);\n  finalColor = mix(finalColor, global.uFogColor, fogFactor);\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      afterTransform: /*glsl*/ `\n  vFogDepth = -(uViewMatrix * worldPosition).z;\n`,\n    },\n    fragment: {\n      end: /*glsl*/ `\n  float fogFactor = 1.0 - exp(-uFogParams.z * vFogDepth);\n  finalColor = mix(finalColor, uFogColor, fogFactor);\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../ShaderBit';\n\n/** @internal */\nexport const linearFogBit: ShaderBit = {\n  name: 'linearFog',\n\n  interStage: {\n    vFogDepth: 'f32',\n  },\n\n  gpu: {\n    vertex: {\n      afterTransform: /*wgsl*/ `\n  output.vFogDepth = -(camera.uViewMatrix * worldPosition).z;\n`,\n    },\n    fragment: {\n      end: /*wgsl*/ `\n  let fogFactor = smoothstep(global.uFogParams.x, global.uFogParams.y, input.vFogDepth);\n  finalColor = mix(finalColor, global.uFogColor, fogFactor);\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      afterTransform: /*glsl*/ `\n  vFogDepth = -(uViewMatrix * worldPosition).z;\n`,\n    },\n    fragment: {\n      end: /*glsl*/ `\n  float fogFactor = smoothstep(uFogParams.x, uFogParams.y, vFogDepth);\n  finalColor = mix(finalColor, uFogColor, fogFactor);\n`,\n    },\n  },\n};\n","import { glTexelAddress } from '../../buffers/dataTextureLayout';\nimport {\n  MESH3D_LANE_BONES,\n  MESH3D_LANE_GEOMETRY,\n  MESH3D_LANE_MATERIAL,\n  MESH3D_LANE_MORPH_WEIGHT,\n  MESH3D_STORE_STRIDE,\n} from '../../buffers/Mesh3DDataStoreBuffer';\nimport type { ShaderBit } from '../ShaderBit';\n\nconst TEXELS_PER_ROW = MESH3D_STORE_STRIDE / 4;\n\nconst COMPONENT = ['x', 'y', 'z', 'w'];\nconst at = (lane: number) => ({ texel: lane >> 2, component: COMPONENT[lane & 3] });\n\nconst BONES = at(MESH3D_LANE_BONES);\nconst GEOMETRY = at(MESH3D_LANE_GEOMETRY);\nconst MORPH = at(MESH3D_LANE_MORPH_WEIGHT);\nconst MATERIAL = at(MESH3D_LANE_MATERIAL);\n\n/**\n * One fetch reads three lanes, which `Mesh3DDataStoreBuffer` keeps in one texel. `batchTransform`\n * stays out of the once-a-frame global block, since `Mesh3DBatcherGl` sets it per batch.\n */\nfunction createInstanceFetchBitGl(material: boolean): ShaderBit {\n  return {\n    name: material ? 'instanceFetchMaterial' : 'instanceFetch',\n    bindings: {\n      global: {\n        uMeshStoreTexture: 'texture_2d<u32>',\n        uRenderInstanceTexture: 'texture_2d<u32>',\n        batchTransform: {\n          uBatchWorldMatrix: 'mat4x4<f32>',\n        },\n      },\n    },\n    gl: {\n      vertex: {\n        header: /* glsl */ `\n      uniform int uInstanceBase;\n\n      uvec4 fetchStoreTexel(int texel) {\n        return texelFetch(uMeshStoreTexture, ${glTexelAddress('texel')}, 0);\n      }\n      `,\n        input: /* glsl */ `\n      int instanceSlot = uInstanceBase + gl_InstanceID;\n      uvec4 renderInstance = texelFetch(uRenderInstanceTexture, ${glTexelAddress('instanceSlot')}, 0);\n\n      int storeTexel = int(renderInstance.x) * ${TEXELS_PER_ROW};\n\n      modelMatrix = uBatchWorldMatrix * mat4(\n        uintBitsToFloat(fetchStoreTexel(storeTexel)),\n        uintBitsToFloat(fetchStoreTexel(storeTexel + 1)),\n        uintBitsToFloat(fetchStoreTexel(storeTexel + 2)),\n        uintBitsToFloat(fetchStoreTexel(storeTexel + 3)));\n\n      uvec4 indexLanes = fetchStoreTexel(storeTexel + ${BONES.texel});\n      float bonePitIndex = float(indexLanes.${BONES.component});\n      vec2 morphData = vec2(\n        float(fetchStoreTexel(storeTexel + ${MORPH.texel}).${MORPH.component}),\n        float(int(indexLanes.${GEOMETRY.component})));\n      ${material ? `vMaterialIndex = indexLanes.${MATERIAL.component};` : ''}\n      `,\n      },\n    },\n  };\n}\n\n/**\n * Sets each instance's `modelMatrix` on WebGL, for a pass's own template that draws meshes\n *\n * List it in the pass descriptor's `bitsGl`. A material's shader fetches the same data already, so\n * listing it in a material's `descriptor` fails the compile. It fills the vertex template's\n * `{{input}}` slot with the matrix and the indices skinning and morphing read. WebGPU templates\n * read the same data themselves, so `bitsGpu` needs no counterpart.\n * @example\n * ```ts\n * const shaderDescriptor = {\n *   bitsGpu: [maskBit],\n *   bitsGl: [instanceFetchBitGl, maskBit],\n *   template: maskTemplate,\n * };\n * ```\n * @category rendering\n * @advanced\n */\nexport const instanceFetchBitGl: ShaderBit = createInstanceFetchBitGl(false);\n\n/** @internal */\nexport const instanceFetchMaterialBitGl: ShaderBit = createInstanceFetchBitGl(true);\n","import { collectTextureNames } from '../../../materials/utils/validateMaterialTextureSlots';\nimport { mergeMaterialStruct } from '../codegen/materialStruct';\nimport type { BindingGroup, ShaderBit } from '../ShaderBit';\n\n/**\n * `'direct'` draws one material, reading its row as a uniform; `'merged'` instances a run of\n * materials, each reading its row from the material store's texture\n * @internal\n */\nexport type MaterialShaderForm = 'direct' | 'merged';\n\n/** Keyed as the bit's name is, so each name stands for one bit, as `assertBitIdentity` requires */\nconst materialBits = new Map<string, ShaderBit>();\n\n/**\n * Texture `t` at binding `2t` and its sampler at `2t + 1`, then the direct form's `material` row:\n * the shape `BaseMaterial3D` binds. `textureGetters` in `texturesPluginGpu.ts` numbers textures the same way\n * @internal\n */\nexport function materialBindingsBit(bits: readonly ShaderBit[], form: MaterialShaderForm): ShaderBit {\n  const count = collectTextureNames(bits).length;\n  const hasRow = form === 'direct' && Object.keys(mergeMaterialStruct(bits)).length > 0;\n  const key = `${count}|${form}|${hasRow}`;\n  let bit = materialBits.get(key);\n  if (bit) return bit;\n\n  const batch: BindingGroup = Object.fromEntries(\n    Array.from({ length: count }, (_, t) => t).flatMap((t) => [\n      [`uMaterialTexture${t}`, 'texture_2d<f32>'] as const,\n      [`uMaterialSampler${t}`, 'sampler'] as const,\n    ]),\n  );\n  if (hasRow) batch.material = 'uniform<Material>';\n  bit = {\n    name: `materialBindings:${count}:${form}${hasRow ? ':material' : ''}`,\n    bindings: { batch },\n  };\n  materialBits.set(key, bit);\n\n  return bit;\n}\n","import type { BillboardMode } from '../../../scene/Mesh3D';\nimport type { ShaderBit } from '../ShaderBit';\n\n/** Lit only: unlit shaders still write `vNormal`, so the compiler wouldn't drop the work */\nconst NORMAL_GPU = /*wgsl*/ `\n  worldNormal = bbRight * normal.x + bbUp * normal.y + bbNormal * normal.z;\n`;\n\nconst NORMAL_GL = /*glsl*/ `\n  worldNormal = bbRight * normal.x + bbUp * normal.y + bbNormal * normal.z;\n`;\n\nfunction sphericalGpu(lit: boolean): string {\n  return /*wgsl*/ `\n  let bbRight = vec3<f32>(camera.uViewMatrix[0][0], camera.uViewMatrix[1][0], camera.uViewMatrix[2][0]);\n  let bbUp    = vec3<f32>(camera.uViewMatrix[0][1], camera.uViewMatrix[1][1], camera.uViewMatrix[2][1]);\n  let bbNormal = cross(bbRight, bbUp);\n\n  let bbScaleX = length(modelMatrix[0].xyz);\n  let bbScaleY = length(modelMatrix[1].xyz);\n  let bbScaleZ = length(modelMatrix[2].xyz);\n\n  worldPosition = vec4<f32>(\n    modelMatrix[3].xyz\n      + bbRight * (position.x * bbScaleX)\n      + bbUp * (position.y * bbScaleY)\n      + bbNormal * (position.z * bbScaleZ),\n    1.0\n  );\n  clipPosition = camera.uViewProjectionMatrix * worldPosition;\n${lit ? NORMAL_GPU : ''}`;\n}\n\nfunction sphericalGl(lit: boolean): string {\n  return /*glsl*/ `\n  vec3 bbRight = vec3(uViewMatrix[0][0], uViewMatrix[1][0], uViewMatrix[2][0]);\n  vec3 bbUp    = vec3(uViewMatrix[0][1], uViewMatrix[1][1], uViewMatrix[2][1]);\n  vec3 bbNormal = cross(bbRight, bbUp);\n\n  float bbScaleX = length(modelMatrix[0].xyz);\n  float bbScaleY = length(modelMatrix[1].xyz);\n  float bbScaleZ = length(modelMatrix[2].xyz);\n\n  worldPosition = vec4(\n    modelMatrix[3].xyz\n      + bbRight * (position.x * bbScaleX)\n      + bbUp * (position.y * bbScaleY)\n      + bbNormal * (position.z * bbScaleZ),\n    1.0\n  );\n  gl_Position = uViewProjectionMatrix * worldPosition;\n${lit ? NORMAL_GL : ''}`;\n}\n\nfunction cylindricalGpu(lit: boolean): string {\n  return /*wgsl*/ `\n  let bbColX = modelMatrix[0].xyz;\n  let bbColY = modelMatrix[1].xyz;\n  let bbScaleX = length(bbColX);\n  let bbScaleY = length(bbColY);\n  let bbScaleZ = length(modelMatrix[2].xyz);\n  let bbCentre = modelMatrix[3].xyz;\n\n  var bbUp = vec3<f32>(0.0, 1.0, 0.0);\n  if (bbScaleY > 1e-8) { bbUp = bbColY / bbScaleY; }\n\n  let bbToCam = camera.uCameraPosition - bbCentre;\n  let bbFlat = bbToCam - bbUp * dot(bbToCam, bbUp);\n  let bbFlatLenSq = dot(bbFlat, bbFlat);\n\n  var bbRight = vec3<f32>(1.0, 0.0, 0.0);\n  if (bbFlatLenSq > 1e-8) {\n    bbRight = cross(bbUp, bbFlat) * inverseSqrt(bbFlatLenSq);\n  } else if (bbScaleX > 1e-8) {\n    bbRight = bbColX / bbScaleX;\n  }\n\n  let bbNormal = cross(bbRight, bbUp);\n\n  worldPosition = vec4<f32>(\n    bbCentre\n      + bbRight * (position.x * bbScaleX)\n      + bbUp * (position.y * bbScaleY)\n      + bbNormal * (position.z * bbScaleZ),\n    1.0\n  );\n  clipPosition = camera.uViewProjectionMatrix * worldPosition;\n${lit ? NORMAL_GPU : ''}`;\n}\n\nfunction cylindricalGl(lit: boolean): string {\n  return /*glsl*/ `\n  vec3 bbColX = modelMatrix[0].xyz;\n  vec3 bbColY = modelMatrix[1].xyz;\n  float bbScaleX = length(bbColX);\n  float bbScaleY = length(bbColY);\n  float bbScaleZ = length(modelMatrix[2].xyz);\n  vec3 bbCentre = modelMatrix[3].xyz;\n\n  vec3 bbUp = vec3(0.0, 1.0, 0.0);\n  if (bbScaleY > 1e-8) { bbUp = bbColY / bbScaleY; }\n\n  vec3 bbToCam = uCameraPosition - bbCentre;\n  vec3 bbFlat = bbToCam - bbUp * dot(bbToCam, bbUp);\n  float bbFlatLenSq = dot(bbFlat, bbFlat);\n\n  vec3 bbRight = vec3(1.0, 0.0, 0.0);\n  if (bbFlatLenSq > 1e-8) {\n    bbRight = cross(bbUp, bbFlat) * inversesqrt(bbFlatLenSq);\n  } else if (bbScaleX > 1e-8) {\n    bbRight = bbColX / bbScaleX;\n  }\n\n  vec3 bbNormal = cross(bbRight, bbUp);\n\n  worldPosition = vec4(\n    bbCentre\n      + bbRight * (position.x * bbScaleX)\n      + bbUp * (position.y * bbScaleY)\n      + bbNormal * (position.z * bbScaleZ),\n    1.0\n  );\n  gl_Position = uViewProjectionMatrix * worldPosition;\n${lit ? NORMAL_GL : ''}`;\n}\n\nconst cache: Partial<Record<string, ShaderBit>> = Object.create(null);\n\n/**\n * Rewrites `worldPosition` and the clip position in the vertex `afterTransform` slot, so it goes ahead of any bit that\n * reads them there\n * @internal\n */\nexport function getMeshBillboardBit(mode: BillboardMode, lit: boolean): ShaderBit {\n  const key = `${mode}:${lit}`;\n  const existing = cache[key];\n  if (existing) return existing;\n\n  if (mode === 'none') {\n    throw new Error(\"[meshBillboardBits] billboardMode 'none' has no bit — the caller must skip injection.\");\n  }\n\n  const spherical = mode === 'spherical';\n  const bit: ShaderBit = {\n    name: `meshBillboard${spherical ? 'Spherical' : 'Cylindrical'}${lit ? 'Lit' : ''}`,\n    gpu: { vertex: { afterTransform: spherical ? sphericalGpu(lit) : cylindricalGpu(lit) } },\n    gl: { vertex: { afterTransform: spherical ? sphericalGl(lit) : cylindricalGl(lit) } },\n  };\n\n  cache[key] = bit;\n  return bit;\n}\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * Declared `float32x3` for any buffer format: quantized normals arrive normalized, and both\n * backends read the first three components\n * @internal\n */\nexport const normalBit: ShaderBit = {\n  name: 'normal',\n\n  attributes: {\n    aNormal: 'float32x3',\n  },\n\n  gpu: {\n    vertex: {\n      input: 'normal = input.aNormal;',\n    },\n  },\n\n  gl: {\n    vertex: {\n      input: 'normal = aNormal;',\n    },\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\nimport { derivativeTangentFrameBit } from './derivativeTangentFrameBit';\n\n/**\n * Declares no `material` fields or textures: it's picked per mesh, after the material's layout is\n * fixed, so `normalScale` and the `normal` texture come from the material bit\n * @internal\n */\nexport const normalMappingBit: ShaderBit = {\n  name: 'normalMapping',\n\n  requires: [derivativeTangentFrameBit],\n\n  gpu: {\n    fragment: {\n      material: `\n  let normalMapSample = sampleNormal(input.vUV).rgb;\n  var tangentNormal = normalMapSample * 2.0 - 1.0;\n  tangentNormal = vec3<f32>(tangentNormal.xy * material.normalScale, tangentNormal.z);\n  let tbnMatrix = calculateTBN(normal, input.vPosition, input.vUV);\n  normal = normalize(tbnMatrix * tangentNormal);\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      material: `\n  {\n  vec3 normalMapSample = sampleNormal(vUV).rgb;\n  vec3 tangentNormal = normalMapSample * 2.0 - 1.0;\n  tangentNormal.xy *= material.normalScale;\n  mat3 tbnMatrix = calculateTBN(normal, vPosition, vUV);\n  normal = normalize(tbnMatrix * tangentNormal);\n  }\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * `calculateShadow` here must match the shadow bits' signature and the call in `createLightingBit`,\n * on each backend\n * @internal\n */\nexport const noShadowBit: ShaderBit = {\n  name: 'no-shadow',\n  gpu: {\n    header: /*wgsl*/ `\n    fn calculateShadow(\n      shadowDataIndex: f32,\n      cascadeCount: f32,\n      worldPos: vec3<f32>,\n      normal: vec3<f32>,\n      NdotL: f32\n    ) -> f32 {\n      return 1.0;\n    }\n    `,\n  },\n  gl: {\n    header: `\n    float calculateShadow(\n      Light light,\n      vec3 worldPos,\n      vec3 normal,\n      float NdotL\n    ) {\n      return 1.0;\n    }\n    `,\n  },\n};\n","import { getAttributeInfoFromFormat } from 'pixi.js';\nimport type { VertexFormat } from 'pixi.js';\n\nimport type { ShaderBit } from '../ShaderBit';\n\nconst cache: Partial<Record<VertexFormat, ShaderBit>> = Object.create(null);\n\n/**\n * The `vec3<f32>(…)` converts a raw integer format, which `KHR_mesh_quantization` allows\n * @internal\n */\nexport function getPositionBit(format: VertexFormat): ShaderBit {\n  const existing = cache[format];\n  if (existing) return existing;\n\n  if (getAttributeInfoFromFormat(format).size < 3) {\n    throw new Error(`[positionBit] aPosition needs three components, got ${format}`);\n  }\n\n  const xyz = format === 'float32x3' ? 'aPosition' : 'aPosition.xyz';\n\n  const bit: ShaderBit = {\n    name: `position:${format}`,\n    attributes: {\n      aPosition: format,\n    },\n    gpu: {\n      vertex: {\n        input: `position = vec4<f32>(vec3<f32>(input.${xyz}), 1.0);`,\n      },\n    },\n    gl: {\n      vertex: {\n        input: `position = vec4(vec3(${xyz}), 1.0);`,\n      },\n    },\n  };\n\n  cache[format] = bit;\n  return bit;\n}\n","/**\n * Fields stay in the order of `Mesh3DDataStoreBuffer`'s `MESH3D_LANE_*` constants\n * @internal\n */\nexport const RenderableStruct = {\n  transform: 'mat4x4<f32>',\n  bonePitIndex: 'u32',\n  materialIndex: 'u32',\n  geometryDataIndex: 'u32',\n  visibility: 'u32',\n  morphWeightIndex: 'u32',\n} as const;\n\n/**\n * Must match `GEOMETRY_DATA_STRIDE`; a `boundsRadius` below 0 marks dynamic geometry, never culled\n * @internal\n */\nexport const GeometryDataStruct = {\n  boundsCenter: 'vec3<f32>',\n  boundsRadius: 'f32',\n  morphDeltaBase: 'u32',\n  morphTargetCount: 'u32',\n  baseVertex: 'u32',\n  _pad: 'u32',\n} as const;\n\n/** @internal */\nexport const RenderableInstanceStruct = {\n  id: 'u32',\n} as const;\n\n/**\n * The top three rows, so indexing gives a row; a `mat3x4` takes 48 bytes where `mat4x3` pads to 64\n * @internal\n */\nexport const BoneMatrixStruct = {\n  rows: 'mat3x4<f32>',\n} as const;\n\n/**\n * Must match `LightDataList`'s layout\n * @internal\n */\nexport const LightStructGpu = {\n  position: 'vec3<f32>',\n  kind: 'f32',\n  color: 'vec3<f32>',\n  rangeSq: 'f32',\n  direction: 'vec3<f32>',\n  coneCos: 'f32',\n  innerConeCos: 'f32',\n  shadowDataIndex: 'f32',\n  cascadeCount: 'f32',\n  radiusPow4: 'f32',\n} as const;\n\n/**\n * `LightDataList`'s layout as `getLight` in `createLightingBit` unpacks it, without the cascade count\n * @internal\n */\nexport const LightStructGl = {\n  position: 'vec3<f32>',\n  type: 'f32',\n  color: 'vec3<f32>',\n  rangeSq: 'f32',\n  direction: 'vec3<f32>',\n  coneCos: 'f32',\n  innerConeCos: 'f32',\n  shadowDataIndex: 'f32',\n  radiusPow4: 'f32',\n} as const;\n\n/**\n * Must match `ShadowDataList`'s layout\n * @internal\n */\nexport const ShadowDataStructGl = {\n  lightSpaceMatrix: 'mat4x4<f32>',\n  shadowParams: 'vec4<f32>',\n  cascadeSplits: 'vec4<f32>',\n} as const;\n","import type { ShadowFilter } from '../../render-passes/shadow/shadowPassUtils';\n\n/** @internal */\nexport type ShadowTap = readonly [number, number];\n\nconst CENTER: readonly ShadowTap[] = [[0, 0]];\n\nconst GRID_2X2: readonly ShadowTap[] = [\n  [-1, -1],\n  [1, -1],\n  [-1, 1],\n  [1, 1],\n];\n\nconst GRID_3X3: readonly ShadowTap[] = [\n  [-2, -2],\n  [0, -2],\n  [2, -2],\n  [-2, 0],\n  [0, 0],\n  [2, 0],\n  [-2, 2],\n  [0, 2],\n  [2, 2],\n];\n\n/**\n * Offsets in texels, which the shadow bits scale by `1 / mapSize`\n * @internal\n */\nexport const SHADOW_TAPS: Record<ShadowFilter, readonly ShadowTap[]> = {\n  hard: CENTER,\n  pcf: GRID_2X2,\n  'pcf-high': GRID_3X3,\n};\n","import type { ShaderBit } from '../ShaderBit';\n\n/**\n * Reads `worldNormal`, since the template writes `vNormal` after this slot. Declares no `material`\n * fields or textures, for the reason `normalMappingBit` gives.\n * @internal\n */\nexport const tangentNormalMappingBit: ShaderBit = {\n  name: 'tangentNormalMapping',\n\n  attributes: {\n    aTangent: 'float32x4',\n  },\n\n  interStage: {\n    vTangent: 'vec3<f32>',\n    vBitangent: 'vec3<f32>',\n  },\n\n  gpu: {\n    vertex: {\n      input: `\n    tangent = input.aTangent.xyz;\n  `,\n      end: /*wgsl*/ `\n  let worldTangent = normalize(modelMatrix3 * tangent);\n  let worldBitangent = cross(worldNormal, worldTangent) * input.aTangent.w;\n  output.vTangent = worldTangent;\n  output.vBitangent = worldBitangent;\n`,\n    },\n    fragment: {\n      material: `\n  let normalMapSample = sampleNormal(input.vUV).rgb;\n  var tangentNormal = normalMapSample * 2.0 - 1.0;\n  tangentNormal = vec3<f32>(tangentNormal.xy * material.normalScale, tangentNormal.z);\n  let tbnMatrix = mat3x3<f32>(\n    normalize(input.vTangent),\n    normalize(input.vBitangent),\n    normal\n  );\n  normal = normalize(tbnMatrix * tangentNormal);\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      input: `\n    tangent = aTangent.xyz;\n  `,\n      end: `\n  vec3 worldTangent = normalize(modelMatrix3 * tangent);\n  vec3 worldBitangent = cross(worldNormal, worldTangent) * aTangent.w;\n  vTangent = worldTangent;\n  vBitangent = worldBitangent;\n`,\n    },\n    fragment: {\n      material: `\n  vec3 normalMapSample = sampleNormal(vUV).rgb;\n  vec3 tangentNormal = normalMapSample * 2.0 - 1.0;\n  tangentNormal.xy *= material.normalScale;\n  mat3 tbnMatrix = mat3(\n    normalize(vTangent),\n    normalize(vBitangent),\n    normal\n  );\n  normal = normalize(tbnMatrix * tangentNormal);\n`,\n    },\n  },\n};\n","import type { VertexFormat } from 'pixi.js';\n\nimport type { ShaderBit } from '../ShaderBit';\n\nconst cache: Partial<Record<VertexFormat, ShaderBit>> = Object.create(null);\n\n/**\n * The `vec2<f32>(…)` converts a raw integer format, which `KHR_mesh_quantization` allows\n * @internal\n */\nexport function getUvsBit(format: VertexFormat): ShaderBit {\n  const existing = cache[format];\n  if (existing) return existing;\n\n  const bit: ShaderBit = {\n    name: `uvs:${format}`,\n    overrideDefs: {\n      HAS_UVS: { type: 'u32', required: true },\n    },\n    attributes: {\n      aUV: format,\n    },\n    gpu: {\n      vertex: {\n        input: 'uv = vec2<f32>(input.aUV);',\n      },\n    },\n    gl: {\n      vertex: {\n        input: 'uv = vec2(aUV);',\n      },\n    },\n  };\n\n  cache[format] = bit;\n  return bit;\n}\n","import type { ShaderBit } from '../ShaderBit';\n\n/** @internal */\nexport const vertexColorBit: ShaderBit = {\n  name: 'vertexColor',\n  attributes: {\n    aColor: 'float32x4',\n  },\n  interStage: {\n    vColor: 'vec4<f32>',\n  },\n  gpu: {\n    vertex: {\n      end: `output.vColor = input.aColor;`,\n    },\n    fragment: {\n      material: `albedo *= input.vColor.rgb;\n  alpha *= input.vColor.a;`,\n    },\n  },\n  gl: {\n    vertex: {\n      end: `vColor = aColor;`,\n    },\n    fragment: {\n      material: `albedo *= vColor.rgb;\n  alpha *= vColor.a;`,\n    },\n  },\n};\n","import { warn } from 'pixi.js';\nimport type { VertexFormat } from 'pixi.js';\n\nimport type { ShaderBit } from '../ShaderBit';\n\nfunction warnAttributeConflict(name: string, newFormat: string, existingFormat: string): void {\n  warn(\n    `[collectAttributes] Attribute \"${name}\" redefined with different format: ` +\n      `\"${existingFormat}\" → \"${newFormat}\". Keeping original.`,\n  );\n}\n\n/** @internal */\nexport function collectAttributes(bits: ShaderBit[]): Record<string, VertexFormat> {\n  const attributes: Record<string, VertexFormat> = Object.create(null);\n\n  for (const bit of bits) {\n    if (!bit.attributes) continue;\n\n    for (const [name, format] of Object.entries(bit.attributes)) {\n      if (!(name in attributes)) {\n        attributes[name] = format;\n      } else if (attributes[name] !== format) {\n        warnAttributeConflict(name, format, attributes[name]);\n      }\n    }\n  }\n\n  return attributes;\n}\n","import type { ShaderBit } from '../ShaderBit';\n\n/** @internal */\nexport function collectSlotCode(\n  bits: ShaderBit[],\n  platform: 'gl' | 'gpu',\n  stage: 'vertex' | 'fragment',\n): Record<string, string[]> {\n  const slotCode: Record<string, string[]> = {};\n\n  for (const bit of bits) {\n    const stageData = bit[platform]?.[stage];\n    if (!stageData) continue;\n\n    for (const [slotName, code] of Object.entries(stageData)) {\n      if (!code) continue;\n      slotCode[slotName] ??= [];\n      slotCode[slotName].push(code);\n    }\n  }\n\n  return slotCode;\n}\n","const SLOT_PATTERN = /\\{\\{(.*?)\\}\\}/g;\n\n/** Two passes suffice today, the second for markers inside slot code; more than eight is a cycle */\nconst MAX_PASSES = 8;\n\n/**\n * Throws on markers left after `MAX_PASSES`, rather than strip them and compile a shader missing that code\n * @internal\n */\nexport function fillTemplateSlots(templateSource: string, slotCode: Record<string, string[]>): string {\n  let result = templateSource;\n\n  for (let pass = 0; pass < MAX_PASSES; pass++) {\n    const next = result.replace(SLOT_PATTERN, (_match, slotName: string) => {\n      const code = slotCode[slotName];\n      return code ? code.join('\\n') : '';\n    });\n    if (next === result) break;\n    result = next;\n  }\n\n  const survivors = result.match(SLOT_PATTERN);\n  if (survivors) {\n    const names = [...new Set(survivors)].join(', ');\n    throw new Error(\n      `[fillTemplateSlots] Slot markers still present after ${MAX_PASSES} substitution passes: ${names}. ` +\n        `A slot's code reintroduces its own marker (directly or via another slot) — break the cycle.`,\n    );\n  }\n\n  return result;\n}\n","import type { ShaderBit } from '../ShaderBit';\nimport { resolveBindGroups } from '../ShaderBitTemplate';\nimport type { ShaderBitTemplate } from '../ShaderBitTemplate';\nimport { bindingFields, bindingType, isStorageType, isUniformBufferType, RESOURCE_TYPES } from './parseBindingType';\n\ninterface GroupData {\n  resources: Record<string, boolean>;\n  storages: Record<string, boolean>;\n  uniformBuffers: Record<string, boolean>;\n  uniformGroups: Record<string, boolean>;\n}\n\n/**\n * Must assign the indices `buildWgslBindingMap` does, as `bindingParity.test.ts` checks\n * @internal\n */\nexport function generateGroupMap(\n  bits: ShaderBit[],\n  template: ShaderBitTemplate,\n): Record<number, Record<number, string>> {\n  const groupData: Record<string, GroupData> = Object.create(null);\n\n  const groups = resolveBindGroups(template);\n\n  for (const { name } of groups) {\n    groupData[name] = {\n      resources: Object.create(null),\n      storages: Object.create(null),\n      uniformBuffers: Object.create(null),\n      uniformGroups: Object.create(null),\n    };\n  }\n\n  for (const bit of bits) {\n    if (!bit.bindings) continue;\n\n    for (const [groupName, bindings] of Object.entries(bit.bindings)) {\n      const group = groupData[groupName];\n      if (!group) continue;\n\n      for (const { name, spec, uniformGroup } of bindingFields(bindings!, groupName)) {\n        const type = bindingType(spec);\n        if (RESOURCE_TYPES.has(type)) {\n          group.resources[name] = true;\n        } else if (isStorageType(type)) {\n          group.storages[name] = true;\n        } else if (isUniformBufferType(type)) {\n          group.uniformBuffers[name] = true;\n        } else {\n          group.uniformGroups[uniformGroup] = true;\n        }\n      }\n    }\n  }\n\n  const result: Record<number, Record<number, string>> = {};\n\n  groups.forEach(({ name: groupName }, groupIndex) => {\n    const group = groupData[groupName];\n    const map: Record<number, string> = {};\n    let bindingIndex = 0;\n\n    if (group.uniformGroups[groupName]) map[bindingIndex++] = groupName;\n\n    for (const name in group.resources) map[bindingIndex++] = name;\n\n    for (const name in group.storages) map[bindingIndex++] = name;\n\n    for (const name in group.uniformBuffers) map[bindingIndex++] = name;\n\n    for (const name in group.uniformGroups) if (name !== groupName) map[bindingIndex++] = name;\n\n    result[groupIndex] = map;\n  });\n\n  return result;\n}\n","const findSlotsRx = /\\{\\{(.*?)\\}\\}/g;\n\nfunction getTemplateSlots(programSrc: string): Record<string, string[]> {\n  const slots: Record<string, string[]> = {};\n\n  const slotMatches = programSrc.match(findSlotsRx)?.map((slot) => slot.replace(/[{()}]/g, '')) ?? [];\n\n  slotMatches.forEach((slot) => {\n    slots[slot] = [];\n  });\n\n  return slots;\n}\n\nconst templateSlotCache = new Map<string, Set<string>>();\n\n/** @internal */\nexport function getCachedTemplateSlots(templateSource: string): Set<string> {\n  let slots = templateSlotCache.get(templateSource);\n  if (!slots) {\n    slots = new Set(Object.keys(getTemplateSlots(templateSource)));\n    templateSlotCache.set(templateSource, slots);\n  }\n  return slots;\n}\n","import type { InstanceDataLayout } from '../../batcher/instanceDataLayout';\nimport type { ShaderBit, StructDefinition } from '../ShaderBit';\nimport type { ShaderBitTemplate } from '../ShaderBitTemplate';\nimport { bindingFields, bindingType } from './parseBindingType';\n\n/** @internal */\nexport interface InstanceAccess {\n  layout: InstanceDataLayout;\n  /** Every field either stage reads, all loaded in the vertex stage */\n  loaded: ReadonlySet<string>;\n  /** The fields the fragment stage reads, handed over as flat varyings */\n  varyings: readonly string[];\n}\n\n/** @internal */\nexport function readsInstanceData(bits: readonly ShaderBit[]): boolean {\n  for (let i = 0; i < bits.length; i++) {\n    if (bits[i].bindings?.instance) return true;\n  }\n\n  return false;\n}\n\n/** @internal */\nexport function instanceVaryingName(field: string): string {\n  return `vInstance_${field}`;\n}\n\nconst INSTANCE_READ = /\\binstance\\b(?:\\s*\\.\\s*([A-Za-z]\\w*))?/g;\nconst COMMENT = /\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\//g;\n\nfunction collectStageReads(\n  bits: readonly ShaderBit[],\n  platform: 'gl' | 'gpu',\n  stage: 'vertex' | 'fragment',\n  declared: StructDefinition,\n  into: Set<string>,\n): void {\n  for (const bit of bits) {\n    const slots = bit[platform]?.[stage];\n    if (!slots) continue;\n\n    for (const slot in slots) {\n      const code = slots[slot];\n      if (!code) continue;\n\n      for (const match of code.replace(COMMENT, '').matchAll(INSTANCE_READ)) {\n        if (match[1] === undefined) {\n          for (const name in declared) into.add(name);\n        } else if (match[1] in declared) {\n          into.add(match[1]);\n        }\n      }\n    }\n  }\n}\n\n/** @internal */\nexport function resolveInstanceAccess(\n  bits: readonly ShaderBit[],\n  platform: 'gl' | 'gpu',\n  layout: InstanceDataLayout | undefined,\n  template: ShaderBitTemplate,\n): InstanceAccess {\n  if (!layout) {\n    const reader = bits.find((bit) => bit.bindings?.instance);\n\n    throw new Error(\n      `[instanceData] Bit \"${reader?.name}\" reads instance data, but the mesh it draws has none. ` +\n        `Draw it as a BatchedMesh3D slot and declare the fields in the batch's instanceData option.`,\n    );\n  }\n\n  const declared: StructDefinition = {};\n\n  for (const bit of bits) {\n    const fields = bit.bindings?.instance;\n    if (!fields) continue;\n\n    for (const { name, spec } of bindingFields(fields, 'instance')) {\n      const type = bindingType(spec);\n      const inBatch = layout.struct[name];\n\n      if (inBatch !== type) {\n        throw new Error(\n          `[instanceData] Bit \"${bit.name}\" reads instance.${name} as ${type}, but the batch ` +\n            (inBatch ? `declares it as ${inBatch}.` : `has no such field. Its instanceData is: ${layout.key}.`),\n        );\n      }\n\n      declared[name] = inBatch;\n    }\n  }\n\n  const fragment = new Set<string>();\n  collectStageReads(bits, platform, 'fragment', declared, fragment);\n\n  const loaded = new Set(fragment);\n  collectStageReads(bits, platform, 'vertex', declared, loaded);\n\n  const access: InstanceAccess = { layout, loaded, varyings: [...fragment] };\n  assertInstanceSlots(template, platform, access);\n\n  return access;\n}\n\n/**\n * Without this check, a missing slot drops the access code and the compile fails at the first\n * `instance.<field>` with no hint why\n */\nfunction assertInstanceSlots(template: ShaderBitTemplate, platform: 'gl' | 'gpu', access: InstanceAccess): void {\n  const fragmentReads = access.varyings.length > 0;\n  let missing: string | null = null;\n\n  if (platform === 'gpu') {\n    const source = template.gpu ?? '';\n    if (!source.includes('{{vertexStoreAccess}}')) missing = '{{vertexStoreAccess}}';\n    else if (fragmentReads && !source.includes('{{fragmentStoreAccess}}')) missing = '{{fragmentStoreAccess}}';\n  } else if (!template.gl?.vertex.includes('{{storeAccess}}')) {\n    missing = '{{storeAccess}} in its vertex source';\n  } else if (fragmentReads && !template.gl.fragment.includes('{{storeAccess}}')) {\n    missing = '{{storeAccess}} in its fragment source';\n  }\n\n  if (missing) {\n    throw new Error(\n      `[instanceData] A bit reads instance data, but the shader template has no ${missing}. ` +\n        `Add the slot where the draw's store row is in scope, or use the material's own template.`,\n    );\n  }\n}\n","import type { ShaderCompilerPlugin } from '../ShaderCompilerPlugin';\nimport { mergeMaterialStruct } from './materialStruct';\n\n/**\n * Repacks only `Material`, since other structs' CPU writers use fixed offsets. GLSL runs it once per\n * stage over the same `data`, so it must give the same result twice.\n * @internal\n */\nexport const materialStructPackPlugin: ShaderCompilerPlugin = {\n  preCompile(context) {\n    const structs = context.data.structs;\n\n    if (!structs?.Material) return;\n\n    structs.Material = mergeMaterialStruct(context.bits);\n  },\n};\n","import { WORDS_PER_TEXEL } from '../../buffers/dataTextureLayout';\nimport type { StructDefinition } from '../ShaderBit';\nimport { createStructLayout } from './structLayout';\n\ntype TexelScalar = 'f32' | 'i32' | 'u32';\n\nfunction texelScalar(type: string): TexelScalar {\n  if (type.includes('u32')) return 'u32';\n  if (type.includes('i32')) return 'i32';\n\n  return 'f32';\n}\n\n/** @internal */\nexport interface TexelField {\n  name: string;\n  type: string;\n  /** A texel holds exact `u32` bits; any other scalar is those bits reinterpreted */\n  scalar: TexelScalar;\n  /** `''` for a whole texel, otherwise a swizzle such as `.zw` */\n  swizzle: string;\n}\n\n/**\n * No field may straddle a texel; `mergeMaterialStruct`'s types and instance data's `vec4`s never do\n * @param fields - The struct, in declaration order\n * @param read - The fields to keep; the rest still take their place. Defaults to every field.\n * @internal\n */\nexport function layoutStructTexels(fields: StructDefinition, read?: ReadonlySet<string>): Map<number, TexelField[]> {\n  const layout = createStructLayout(fields);\n  const texels = new Map<number, TexelField[]>();\n\n  for (const elem of layout.elements) {\n    if (read && !read.has(elem.name)) continue;\n\n    const wordOffset = elem.offset / 4;\n    const texelIndex = Math.floor(wordOffset / WORDS_PER_TEXEL);\n    const componentStart = wordOffset % WORDS_PER_TEXEL;\n    const swizzle =\n      elem.components === WORDS_PER_TEXEL ? '' : `.${'xyzw'.slice(componentStart, componentStart + elem.components)}`;\n\n    let entries = texels.get(texelIndex);\n    if (!entries) texels.set(texelIndex, (entries = []));\n\n    entries.push({ name: elem.name, type: elem.type, scalar: texelScalar(elem.type), swizzle });\n  }\n\n  return texels;\n}\n","import type { ShaderBit, ShaderOverrideDef, ShaderOverrideType } from './ShaderBit';\n\n/** @internal */\nexport type NormalizedShaderOverrideDef =\n  | { type: ShaderOverrideType; default: number; required: false }\n  | { type: ShaderOverrideType; default?: never; required: true };\n\nfunction normalizeDef(bitName: string, key: string, def: ShaderOverrideDef): NormalizedShaderOverrideDef {\n  const anyDef = def as unknown as {\n    type?: ShaderOverrideType;\n    default?: unknown;\n    required?: unknown;\n  };\n\n  if (!anyDef?.type) {\n    throw new Error(`[ShaderBit:${bitName}] overrideDefs.${key} missing 'type'.`);\n  }\n\n  const hasDefault = Object.prototype.hasOwnProperty.call(anyDef, 'default');\n  const isRequired = anyDef.required === true;\n\n  if (hasDefault && isRequired) {\n    throw new Error(`[ShaderBit:${bitName}] overrideDefs.${key} cannot specify both 'default' and 'required: true'.`);\n  }\n\n  if (!hasDefault && !isRequired) {\n    throw new Error(`[ShaderBit:${bitName}] overrideDefs.${key} must specify either 'default' or 'required: true'.`);\n  }\n\n  if (isRequired) {\n    return { type: anyDef.type, required: true };\n  }\n\n  if (typeof anyDef.default !== 'number' || !Number.isFinite(anyDef.default)) {\n    throw new Error(`[ShaderBit:${bitName}] overrideDefs.${key}.default must be a finite number.`);\n  }\n\n  return {\n    type: anyDef.type,\n    default: anyDef.default,\n    required: false,\n  };\n}\n\n/** @internal */\nexport function collectOverrideDefs(bits: ShaderBit[]): Record<string, NormalizedShaderOverrideDef> {\n  const defs: Record<string, NormalizedShaderOverrideDef> = Object.create(null);\n\n  for (const bit of bits) {\n    if (!bit.overrideDefs) continue;\n\n    for (const [key, rawDef] of Object.entries(bit.overrideDefs)) {\n      const normalized = normalizeDef(bit.name, key, rawDef);\n\n      const existing = defs[key];\n\n      if (\n        existing &&\n        (existing.type !== normalized.type ||\n          existing.required !== normalized.required ||\n          (!existing.required && existing.default !== normalized.default))\n      ) {\n        throw new Error(\n          `[ShaderBit overrides] Duplicate override '${key}' has conflicting definitions.\\n` +\n            `Existing: ${JSON.stringify(existing)}\\n` +\n            `New (from '${bit.name}'): ${JSON.stringify(normalized)}`,\n        );\n      }\n\n      defs[key] = existing ?? normalized;\n    }\n  }\n\n  return defs;\n}\n\nfunction formatWgslLiteral(type: ShaderOverrideType, value: number): string {\n  if (type === 'u32') {\n    const intValue = Math.trunc(value);\n    return `${intValue}u`;\n  }\n  if (type === 'i32') {\n    return `${Math.trunc(value)}`;\n  }\n  if (Number.isInteger(value)) return `${value}.0`;\n  return `${value}`;\n}\n\n/** @internal */\nexport function emitOverridesWgsl(defs: Record<string, NormalizedShaderOverrideDef>): string {\n  const lines: string[] = [];\n\n  for (const key of Object.keys(defs).sort()) {\n    const def = defs[key];\n\n    if (def.required) {\n      lines.push(`override ${key}: ${def.type};`);\n    } else {\n      const lit = formatWgslLiteral(def.type, def.default);\n      lines.push(`override ${key}: ${def.type} = ${lit};`);\n    }\n  }\n\n  return lines.length ? lines.join('\\n') : '';\n}\n\n/**\n * Gives an integral `f32` a `.0`, or GLSL reads an `int`, and a `u32` no `u` suffix, so shader code\n * compares it with a bare int in both languages, as `toonMaterialBit` does with `HAS_UVS == 1`\n */\nfunction formatGlslLiteral(type: ShaderOverrideType, value: number): string {\n  if (type === 'u32') {\n    return `${Math.trunc(value)}`;\n  }\n  if (type === 'i32') {\n    return `${Math.trunc(value)}`;\n  }\n  if (Number.isInteger(value)) return `${value}.0`;\n  return `${value}`;\n}\n\n/** @internal */\nexport function emitOverridesGlsl(\n  defs: Record<string, NormalizedShaderOverrideDef>,\n  values: Record<string, number>,\n): string {\n  const lines: string[] = [];\n\n  for (const key of Object.keys(defs).sort()) {\n    const def = defs[key];\n    const provided = values[key];\n    const hasProvided = provided !== undefined;\n\n    if (def.required && !hasProvided) {\n      throw new Error(`[glslOverrides] required override '${key}' has no value supplied via descriptor.overrides.`);\n    }\n\n    const value = hasProvided ? provided : (def as { default: number }).default;\n    lines.push(`#define ${key} ${formatGlslLiteral(def.type, value)}`);\n  }\n\n  return lines.length ? lines.join('\\n') : '';\n}\n","import { fillTemplateSlots } from './codegen/fillTemplateSlots';\nimport type { ShaderCompilerContext, ShaderCompilerPlugin } from './ShaderCompilerPlugin';\n\n/** @internal */\nexport function compileShader(context: ShaderCompilerContext, plugins: ShaderCompilerPlugin[]): string {\n  for (const plugin of plugins) {\n    plugin.collectData?.(context);\n  }\n\n  for (const plugin of plugins) {\n    plugin.preCompile?.(context);\n  }\n\n  const slotCode: Record<string, string[]> = {};\n\n  for (const plugin of plugins) {\n    const injected = plugin.injectCode?.(context);\n    if (injected) {\n      for (const [slot, code] of Object.entries(injected)) {\n        if (!code || !/\\S/.test(code)) continue;\n        slotCode[slot] ??= [];\n        slotCode[slot].push(code);\n      }\n    }\n  }\n\n  return fillTemplateSlots(context.templateString, slotCode);\n}\n","import type { ShaderBit } from './ShaderBit';\n\n/** Marks `bit` seen before walking its requirements, so two bits that require each other land once */\nfunction addWithRequired(bit: ShaderBit, resolved: ShaderBit[], seen: Set<ShaderBit>): void {\n  if (seen.has(bit)) return;\n  seen.add(bit);\n\n  const requires = bit.requires;\n\n  if (requires) {\n    for (let i = 0; i < requires.length; i++) addWithRequired(requires[i], resolved, seen);\n  }\n\n  resolved.push(bit);\n}\n\n/** @internal */\nexport function resolveShaderBits(bits: ShaderBit[]): ShaderBit[] {\n  const resolved: ShaderBit[] = [];\n  const seen = new Set<ShaderBit>();\n\n  for (let i = 0; i < bits.length; i++) addWithRequired(bits[i], resolved, seen);\n\n  return resolved;\n}\n","import { MAX_SHADOW_SLOTS } from './render-passes/shadow/shadowPassUtils';\nimport type { CascadeSlot } from './render-passes/shadow/shadowPassUtils';\n\nconst FLOATS_PER_SHADOW_SLOT = 24;\n\n/**\n * Packs one slot at `offset`, in the layout `ShadowDataStructGl` and `shadowBitsGpu` read; an unused split is 1e30,\n * not 0, so the shaders' `step(splits, viewDepth)` never counts it as crossed\n */\nfunction writeCascadeSlot(slot: CascadeSlot, buffer: Float32Array, offset: number): void {\n  buffer.set(slot.cameraData.viewProjection.elements, offset);\n\n  buffer[offset + 16] = slot.bias;\n  buffer[offset + 17] = slot.normalBias;\n  buffer[offset + 18] = slot.mapSize;\n  buffer[offset + 19] = slot.cascadeCount;\n\n  const splits = slot.splits;\n  buffer[offset + 20] = splits?.[0] ?? 1e30;\n  buffer[offset + 21] = splits?.[1] ?? 1e30;\n  buffer[offset + 22] = splits?.[2] ?? 1e30;\n  buffer[offset + 23] = splits?.[3] ?? 1e30;\n}\n\n/**\n * The view's shadow slots, one per light and cascade, with a light's cascade `c` at `light._shadowDataIndex + c`;\n * `data` is `uShadowData`'s value on both backends, so it never reallocates, and `add` doesn't bounds-check:\n * `_claimShadowSlots` stops at `MAX_SHADOW_SLOTS`\n * @internal\n */\nexport class ShadowDataList {\n  /** Entries at and above `count` are stale */\n  public readonly data = new Float32Array(MAX_SHADOW_SLOTS * FLOATS_PER_SHADOW_SLOT);\n  private _count = 0;\n\n  get count(): number {\n    return this._count;\n  }\n\n  public reset(): void {\n    this._count = 0;\n  }\n\n  public add(slot: CascadeSlot): void {\n    writeCascadeSlot(slot, this.data, this._count * FLOATS_PER_SHADOW_SLOT);\n    this._count++;\n  }\n}\n","import { BufferImageSource, CubeTexture, Texture } from 'pixi.js';\n\n/**\n * Makes {@link CubeTexture}s of one solid colour, for a flat environment\n *\n * Channels are display (sRGB) values, as in an image. For a plain background, set\n * {@link View3D#background} to the colour itself, which needs no texture.\n * @example\n * ```ts\n * view3d.environment = ColorCubeTexture.fromRGB(40, 44, 60);\n * ```\n * @category rendering\n * @standard\n */\nexport class ColorCubeTexture {\n  /**\n   * Creates a cube texture of one colour, given as a hex number\n   * @example\n   * ```ts\n   * view3d.environment = ColorCubeTexture.from(0x202830, 255, 'night-sky');\n   * ```\n   * @param color - Colour as `0xRRGGBB`\n   * @param alpha - Alpha, from 0 to 255\n   * @param label - Label for the cube; each face adds its side, as in `night-sky-left`\n   * @returns A cube texture with every face set to the colour\n   */\n  public static from(color: number, alpha = 255, label?: string): CubeTexture {\n    const r = (color >> 16) & 0xff;\n    const g = (color >> 8) & 0xff;\n    const b = color & 0xff;\n\n    return this.fromRGB(r, g, b, alpha, label);\n  }\n\n  /**\n   * Creates a cube texture of one colour, given as channels from 0 to 255\n   * @example\n   * ```ts\n   * view3d.environment = ColorCubeTexture.fromRGB(255, 240, 220);\n   * ```\n   * @param r - Red, from 0 to 255\n   * @param g - Green, from 0 to 255\n   * @param b - Blue, from 0 to 255\n   * @param a - Alpha, from 0 to 255\n   * @param label - Label for the cube; each face adds its side, as in `night-sky-left`\n   * @returns A cube texture with every face set to the colour\n   */\n  public static fromRGB(r: number, g: number, b: number, a = 255, label?: string): CubeTexture {\n    const createFaceTexture = (faceName: string): Texture => {\n      return new Texture({\n        source: new BufferImageSource({\n          resource: new Uint8Array([r, g, b, a]),\n          format: 'rgba8unorm',\n          width: 1,\n          height: 1,\n          alphaMode: 'premultiply-alpha-on-upload',\n          label: label ? `${label}-${faceName}` : `color-cube-${faceName}`,\n        }),\n        label: label ? `${label}-${faceName}` : `color-cube-${faceName}`,\n      });\n    };\n\n    return CubeTexture.from({\n      faces: {\n        left: createFaceTexture('left'),\n        right: createFaceTexture('right'),\n        top: createFaceTexture('top'),\n        bottom: createFaceTexture('bottom'),\n        front: createFaceTexture('front'),\n        back: createFaceTexture('back'),\n      },\n      label: label ?? 'color-cube-texture',\n    });\n  }\n}\n","import { Color, Container, Matrix, TextureSource, Ticker, UPDATE_PRIORITY, warn } from 'pixi.js';\nimport type { ColorSource, Renderer, RgbaArray } from 'pixi.js';\n\n/**\n * Options for {@link ContainerTexture} and {@link ContainerSource}\n * @example\n * ```ts\n * const screen = new ContainerTexture({ container: gameUi, width: 512, height: 512, renderer: app.renderer });\n * ```\n * @category rendering\n * @standard\n */\nexport interface ContainerSourceOptions {\n  /**\n   * The 2D {@link Container} to draw; it moves out of its current parent, so it stops drawing on the stage\n   * @example\n   * ```ts\n   * const badge = new ContainerTexture({ container: badgeGraphics, renderer: app.renderer });\n   * ```\n   */\n  container: Container;\n  /**\n   * Width of the capture in logical pixels; omitted, it's measured once from the container's local bounds\n   *\n   * {@link ContainerSourceOptions#transform} says where the container sits in the capture.\n   * @example\n   * ```ts\n   * const banner = new ContainerTexture({ container: bannerText, width: 1024, height: 256 });\n   * ```\n   */\n  width?: number;\n  /**\n   * Height of the capture in logical pixels, measured when omitted as\n   * {@link ContainerSourceOptions#width} describes\n   * @example\n   * ```ts\n   * const banner = new ContainerTexture({ container: bannerText, width: 1024, height: 256 });\n   * ```\n   */\n  height?: number;\n  /**\n   * Texels per logical pixel; `2` gives a sharper texture for four times the memory\n   * @example\n   * ```ts\n   * const label = new ContainerTexture({ container: labelText, resolution: 2 });\n   * ```\n   * @default 1\n   */\n  resolution?: number;\n  /**\n   * Whether to multisample the render target, which smooths the edges of shapes drawn into it\n   * @example\n   * ```ts\n   * const chart = new ContainerTexture({ container: pieChart, antialias: true });\n   * ```\n   * @default false\n   */\n  antialias?: boolean;\n  /**\n   * Matrix applied to the container when it's captured, to move or scale it into the capture\n   *\n   * Omitted, when you give neither `width` nor `height`, it moves the top-left corner of the\n   * container's contents, measured once at construction, to the origin; otherwise the capture is\n   * the window from (0, 0) to (`width`, `height`). The container's own position, pivot, scale and\n   * rotation still apply inside the capture, but the measurement leaves them out, so leave them at\n   * their defaults or pass `width`, `height` and `transform` yourself.\n   * `new Matrix().translate(128, 128)` centres a 256 × 256 capture on the origin of a container left\n   * at its defaults; change it later through the texture's `transform` property.\n   * @example\n   * ```ts\n   * const radar = new ContainerTexture({\n   *   container: radarDisc,\n   *   width: 256,\n   *   height: 256,\n   *   transform: new Matrix().translate(128, 128),\n   * });\n   * ```\n   */\n  transform?: Matrix;\n  /**\n   * Colour the capture fills the texture with before it draws the container\n   *\n   * Transparent keeps the container's alpha, so the parts it leaves empty show what's behind a\n   * material in `alphaMode: 'blend'` or `'mask'`, a {@link Sprite3D} or a 2D `Sprite`. A material in\n   * the default `alphaMode: 'opaque'` draws those parts black, and the anti-aliased edges next to them\n   * turn hard; pass `'black'` there to keep them smooth. Change it later through the texture's\n   * `clearColor` property.\n   * @example\n   * ```ts\n   * const screen = new ContainerTexture({ container: scoreText, clearColor: 'black', renderer: app.renderer });\n   * monitor.material = new FlatMaterial({ baseColorTexture: screen });\n   * ```\n   * @default 'transparent'\n   */\n  clearColor?: ColorSource;\n  /**\n   * Renderer to keep for `render()` calls with no argument; {@link ContainerSourceOptions#firstRender}\n   * and {@link ContainerSourceOptions#autoUpdate} need it\n   * @example\n   * ```ts\n   * const screen = new ContainerTexture({ container: gameUi, renderer: app.renderer });\n   *\n   * screen.render();\n   * ```\n   */\n  renderer?: Renderer;\n  /**\n   * Whether to render once during construction, so the texture has a picture before anything samples it\n   *\n   * Needs {@link ContainerSourceOptions#renderer}; without one, an explicit `true` warns.\n   * @example\n   * ```ts\n   * const screen = new ContainerTexture({ container: gameUi, renderer: app.renderer, firstRender: false });\n   * ```\n   * @default true\n   */\n  firstRender?: boolean;\n  /**\n   * Whether to re-render the container every frame, for animated content\n   *\n   * Needs a {@link ContainerSourceOptions#renderer}; without one it warns and waits until one is set.\n   * It renders from `Ticker.shared` just before an application that renders from it\n   * (`sharedTicker: true`); a default application has its own ticker and shows the previous frame's\n   * capture. While it's on, `Ticker.shared` holds the source, so turn it off or destroy the source\n   * when you're done.\n   * @example\n   * ```ts\n   * const screen = new ContainerTexture({ container: gameUi, renderer: app.renderer, autoUpdate: true });\n   * ```\n   * @default false\n   */\n  autoUpdate?: boolean;\n}\n\n/**\n * A {@link TextureSource} whose pixels are a live 2D PixiJS {@link Container}\n *\n * The source behind {@link ContainerTexture}, whose docs cover when to render and which way up the\n * picture is. Build one yourself to make several `Texture`s, each with its own frame, over one\n * container that renders once for all of them. {@link TextureSource#resize} changes its size.\n * @example\n * ```ts\n * import { Rectangle, Texture } from 'pixi.js';\n *\n * const sheet = new ContainerSource({ container: icons, width: 256, height: 128, renderer: app.renderer });\n * const play = new Texture({ source: sheet, frame: new Rectangle(0, 0, 128, 128) });\n * const pause = new Texture({ source: sheet, frame: new Rectangle(128, 0, 128, 128) });\n * ```\n * @category rendering\n * @advanced\n */\nexport class ContainerSource extends TextureSource {\n  private _container: Container;\n  private readonly _root: Container;\n  private readonly _transform = new Matrix();\n  private readonly _clearColor: Color;\n\n  /** {@link ContainerSource#clearColor} premultiplied by its alpha, since the target holds premultiplied colour */\n  private readonly _clearRgba: RgbaArray = [0, 0, 0, 1];\n\n  private _renderer: Renderer | null = null;\n  private _autoUpdate = false;\n  private _isConnectedToTicker = false;\n\n  private readonly _onTick = (): void => {\n    this.render();\n  };\n\n  /**\n   * Sets `_renderer` directly, not through `_setRenderer`, since the runner calls it mid-emit and a\n   * remove then would skip the next hook\n   */\n  private readonly _onRendererDestroy = {\n    destroy: (): void => {\n      this._renderer = null;\n      this._configureAutoUpdate();\n    },\n  };\n\n  constructor(options: ContainerSourceOptions) {\n    const { container } = options;\n    const bounds = options.width === undefined || options.height === undefined ? container.getLocalBounds() : undefined;\n    const width = Math.max(1, Math.ceil(options.width ?? bounds!.width));\n    const height = Math.max(1, Math.ceil(options.height ?? bounds!.height));\n\n    if (options.width === undefined && bounds!.width === 0) {\n      warn('ContainerSource: container has zero width bounds and no explicit width; defaulting to 1.');\n    }\n    if (options.height === undefined && bounds!.height === 0) {\n      warn('ContainerSource: container has zero height bounds and no explicit height; defaulting to 1.');\n    }\n\n    super({\n      width,\n      height,\n      resolution: options.resolution ?? 1,\n      antialias: options.antialias ?? false,\n    });\n\n    this._root = new Container();\n    this._root.addChild(container);\n    this._container = container;\n    if (options.transform) {\n      this._transform.copyFrom(options.transform);\n    } else if (options.width === undefined && options.height === undefined) {\n      this._transform.translate(-bounds!.minX, -bounds!.minY);\n    }\n    this._clearColor = new Color(options.clearColor ?? 'transparent');\n\n    if (options.renderer) {\n      this._setRenderer(options.renderer);\n    }\n\n    if (options.firstRender ?? true) {\n      if (this._renderer) {\n        this.render();\n      } else if (options.firstRender) {\n        warn('ContainerSource: `firstRender` was set without a `renderer`; nothing was rendered.');\n      }\n    }\n    if (options.autoUpdate) {\n      this.autoUpdate = true;\n    }\n  }\n\n  /** The 2D {@link Container} drawn into this source */\n  public get container(): Container {\n    return this._container;\n  }\n\n  /** The renderer kept for {@link ContainerSource#render} calls with no argument, or `null` */\n  public get renderer(): Renderer | null {\n    return this._renderer;\n  }\n\n  /**\n   * Sets the kept renderer\n   * @param value - A renderer, or `null` to release it.\n   */\n  public set renderer(value: Renderer | null) {\n    this._setRenderer(value);\n  }\n\n  /** Whether the source re-renders every frame; {@link ContainerSourceOptions#autoUpdate} has the details */\n  public get autoUpdate(): boolean {\n    return this._autoUpdate;\n  }\n\n  /**\n   * Sets whether the source re-renders every frame\n   * @param value - `true` to re-render every frame.\n   */\n  public set autoUpdate(value: boolean) {\n    if (value === this._autoUpdate) return;\n    this._autoUpdate = value;\n    if (value && !this._renderer) {\n      warn('ContainerSource: `autoUpdate` was enabled without a `renderer`; set one to drive it.');\n    }\n    this._configureAutoUpdate();\n  }\n\n  /**\n   * The capture matrix {@link ContainerSourceOptions#transform} describes; change it or assign a new\n   * one, then render again\n   */\n  public get transform(): Matrix {\n    return this._transform;\n  }\n\n  /**\n   * Sets the capture matrix, copying `value`\n   * @param value - The new capture matrix.\n   */\n  public set transform(value: Matrix) {\n    this._transform.copyFrom(value);\n  }\n\n  /**\n   * The colour {@link ContainerSourceOptions#clearColor} describes; set it or change this one in place,\n   * then render again\n   */\n  public get clearColor(): Color {\n    return this._clearColor;\n  }\n\n  /**\n   * Sets the colour the next render clears to\n   * @param value - Any {@link ColorSource}, such as `'black'`.\n   */\n  public set clearColor(value: ColorSource) {\n    this._clearColor.setValue(value);\n  }\n\n  /**\n   * Swaps the {@link Container} this source renders, as {@link ContainerTexture#setContainer} describes\n   * @param container - The new container to render.\n   */\n  public setContainer(container: Container): void {\n    if (container === this._container) return;\n    this._root.removeChildren();\n    this._root.addChild(container);\n    this._container = container;\n  }\n\n  /**\n   * Renders the container into this source, as {@link ContainerTexture#render} describes\n   * @param renderer - Renderer to draw with, kept for later calls; omit to use the kept one.\n   */\n  public render(renderer?: Renderer): void {\n    const r = renderer ?? this._renderer;\n    if (!r) {\n      warn('ContainerSource.render: no renderer passed and none retained; nothing was rendered.');\n      return;\n    }\n    this._setRenderer(r);\n    const clearColor = this._clearColor.toArray(this._clearRgba);\n    const alpha = clearColor[3];\n    clearColor[0] *= alpha;\n    clearColor[1] *= alpha;\n    clearColor[2] *= alpha;\n    r.render({ container: this._root, target: this, clear: true, clearColor, transform: this._transform, flipY: true });\n  }\n\n  /**\n   * Frees the render target and stops {@link ContainerSource#autoUpdate}, leaving the container\n   * detached but intact unless you pass `true`\n   * @param destroyContainer - Also destroy the container and its children.\n   */\n  public override destroy(destroyContainer = false): void {\n    this._autoUpdate = false;\n    this._setRenderer(null);\n    this._root.removeChildren();\n    if (destroyContainer) {\n      this._container.destroy({ children: true });\n    }\n    this._root.destroy();\n    super.destroy();\n  }\n\n  private _setRenderer(value: Renderer | null): void {\n    if (value === this._renderer) return;\n    this._renderer?.runners.destroy.remove(this._onRendererDestroy);\n    this._renderer = value;\n    value?.runners.destroy.add(this._onRendererDestroy);\n    this._configureAutoUpdate();\n  }\n\n  /** Ticks one step above an application's render, as {@link ContainerSourceOptions#autoUpdate} states */\n  private _configureAutoUpdate(): void {\n    const shouldTick = this._autoUpdate && this._renderer !== null;\n    if (shouldTick === this._isConnectedToTicker) return;\n    if (shouldTick) {\n      Ticker.shared.add(this._onTick, this, UPDATE_PRIORITY.LOW + 1);\n    } else {\n      Ticker.shared.remove(this._onTick, this);\n    }\n    this._isConnectedToTicker = shouldTick;\n  }\n}\n","import { Texture } from 'pixi.js';\nimport type { Color, ColorSource, Container, Matrix, Renderer } from 'pixi.js';\n\nimport { ContainerSource } from './ContainerSource';\nimport type { ContainerSourceOptions } from './ContainerSource';\n\n/**\n * Options for {@link ContainerTexture}, the same as {@link ContainerSourceOptions}\n * @example\n * ```ts\n * const options: ContainerTextureOptions = { container: gameUi, width: 512, height: 256 };\n * const screen = new ContainerTexture({ ...options, renderer: app.renderer });\n * ```\n * @category rendering\n * @standard\n */\nexport type ContainerTextureOptions = ContainerSourceOptions;\n\n/**\n * A {@link Texture} that shows a live 2D PixiJS {@link Container}\n *\n * Use it in any material texture slot, on any geometry. To make several textures over one\n * container, build a {@link ContainerSource} and create `Texture`s from it.\n *\n * Unless {@link ContainerTexture#autoUpdate | autoUpdate} is on, nothing redraws it. Call\n * {@link ContainerTexture#render} after setup and after each change, before you render your scene,\n * or keep a renderer and set `autoUpdate` for animated content. Until its first render it's\n * transparent black; a `renderer` option renders it once as it's made, unless\n * {@link ContainerSourceOptions#firstRender | firstRender} is `false`.\n *\n * In an opaque material, the parts the container leaves empty draw black;\n * {@link ContainerSourceOptions#clearColor | clearColor} says how to keep their edges smooth.\n *\n * The picture is stored the other way up from an image texture. It shows upright where `v` grows\n * upward, as on a default {@link PlaneGeometry} or a {@link CubeGeometry}'s sides, and upside down\n * where an image shows upright, as on a {@link SphereGeometry}, a plane with `flipV`, a loaded\n * model or a 2D `Sprite`. On a sprite, `sprite.scale.y = -1` with `sprite.anchor.y = 1` turns it\n * over in place.\n * @example\n * ```ts\n * const label = new ContainerTexture({ container: labelText, resolution: 2 });\n * sign.material = new FlatMaterial({ baseColorTexture: label });\n * label.render(app.renderer);\n *\n * const screen = new ContainerTexture({ container: gameUi, renderer: app.renderer, autoUpdate: true });\n * monitor.material = new FlatMaterial({ baseColorTexture: screen });\n * ```\n * @category rendering\n * @standard\n */\nexport class ContainerTexture extends Texture {\n  constructor(options: ContainerTextureOptions) {\n    super({ source: new ContainerSource(options) });\n  }\n\n  /**\n   * The {@link ContainerSource} behind this texture\n   * @example\n   * ```ts\n   * import { Rectangle, Texture } from 'pixi.js';\n   *\n   * const corner = new Texture({ source: screen.containerSource, frame: new Rectangle(0, 0, 64, 64) });\n   * ```\n   */\n  public get containerSource(): ContainerSource {\n    return this.source as ContainerSource;\n  }\n\n  /**\n   * The 2D {@link Container} drawn into this texture\n   * @example\n   * ```ts\n   * screen.container.addChild(scoreText);\n   * screen.render();\n   * ```\n   */\n  public get container(): Container {\n    return this.containerSource.container;\n  }\n\n  /**\n   * The renderer kept for {@link ContainerTexture#render} calls with no argument, or `null`\n   * @example\n   * ```ts\n   * screen.renderer = app.renderer;\n   * screen.render();\n   * ```\n   */\n  public get renderer(): Renderer | null {\n    return this.containerSource.renderer;\n  }\n\n  /**\n   * Sets the kept renderer\n   * @param value - A renderer, or `null` to release it.\n   */\n  public set renderer(value: Renderer | null) {\n    this.containerSource.renderer = value;\n  }\n\n  /**\n   * Whether the texture re-renders every frame; {@link ContainerSourceOptions#autoUpdate} has the details\n   * @example\n   * ```ts\n   * screen.autoUpdate = !paused;\n   * ```\n   */\n  public get autoUpdate(): boolean {\n    return this.containerSource.autoUpdate;\n  }\n\n  /**\n   * Sets whether the texture re-renders every frame\n   * @param value - `true` to re-render every frame.\n   */\n  public set autoUpdate(value: boolean) {\n    this.containerSource.autoUpdate = value;\n  }\n\n  /**\n   * The capture matrix {@link ContainerSourceOptions#transform} describes; change it or assign a new\n   * one, then render again\n   * @example\n   * ```ts\n   * screen.transform = new Matrix().translate(-scrollX, 0);\n   * screen.render();\n   * ```\n   */\n  public get transform(): Matrix {\n    return this.containerSource.transform;\n  }\n\n  /**\n   * Sets the capture matrix, copying `value`\n   * @param value - The new capture matrix.\n   */\n  public set transform(value: Matrix) {\n    this.containerSource.transform = value;\n  }\n\n  /**\n   * The colour {@link ContainerSourceOptions#clearColor} describes; set it or change this one in place,\n   * then render again\n   * @example\n   * ```ts\n   * screen.clearColor = 'black';\n   * screen.render();\n   * ```\n   */\n  public get clearColor(): Color {\n    return this.containerSource.clearColor;\n  }\n\n  /**\n   * Sets the colour the next render clears to\n   * @param value - Any {@link ColorSource}, such as `'black'`.\n   */\n  public set clearColor(value: ColorSource) {\n    this.containerSource.clearColor = value;\n  }\n\n  /**\n   * Swaps the {@link Container} this texture renders, keeping its render target and size\n   *\n   * A container other than the current one leaves its parent, the old one is left detached, and the\n   * old picture stays until the next {@link ContainerTexture#render}.\n   * @example\n   * ```ts\n   * screen.setContainer(pauseMenu);\n   * screen.render();\n   * ```\n   * @param container - The new container to render.\n   */\n  public setContainer(container: Container): void {\n    this.containerSource.setContainer(container);\n  }\n\n  /**\n   * Draws the container into this texture\n   *\n   * Call it before you render your scene, never from code that runs during a render. A renderer\n   * passed here is kept for later calls with no argument; with none passed or kept, it warns and\n   * draws nothing.\n   * @example\n   * ```ts\n   * scoreText.text = `${score}`;\n   * scoreboard.render(app.renderer);\n   * ```\n   * @param renderer - Renderer to draw with, kept for later calls; omit to use the kept one.\n   */\n  public render(renderer?: Renderer): void {\n    this.containerSource.render(renderer);\n  }\n\n  /**\n   * Destroys this texture, and optionally its source and its container\n   *\n   * As with pixi's {@link Texture#destroy}, `destroy()` leaves the {@link ContainerSource} alive,\n   * since other textures may share it, and with {@link ContainerTexture#autoUpdate} on, still\n   * rendering every frame. `destroy(true)` frees the source too. The container is yours unless you\n   * pass `{ container: true }`, which destroys it with its children and frees the source.\n   * @example\n   * ```ts\n   * screen.destroy(true);\n   * ```\n   * @param options - `true` also frees the source; an object picks `source` and `container` separately.\n   */\n  public override destroy(\n    options:\n      | boolean\n      | {\n          /**\n           * Also free the {@link ContainerSource} and its render target\n           * @example\n           * ```ts\n           * screen.destroy({ source: true });\n           * ```\n           */\n          source?: boolean;\n          /**\n           * Also destroy the 2D container and its children, which frees the source too\n           * @example\n           * ```ts\n           * screen.destroy({ container: true });\n           * ```\n           */\n          container?: boolean;\n        } = false,\n  ): void {\n    const destroySource = typeof options === 'boolean' ? options : (options.source ?? false);\n    const destroyContainer = typeof options === 'boolean' ? false : (options.container ?? false);\n\n    if (destroySource || destroyContainer) {\n      this.containerSource.destroy(destroyContainer);\n    }\n\n    super.destroy(false);\n  }\n}\n","import { RendererType } from 'pixi.js';\nimport type { TEXTURE_FORMATS, WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\n/** Integer and 32-bit float formats stay out: neither backend resolves integers, and WebGPU can't resolve 32-bit floats */\nconst RESOLVABLE_FORMATS: ReadonlySet<TEXTURE_FORMATS> = new Set<TEXTURE_FORMATS>([\n  'r8unorm',\n  'rg8unorm',\n  'rgba8unorm',\n  'rgba8unorm-srgb',\n  'bgra8unorm',\n  'rgb10a2unorm',\n  'r16float',\n  'rg16float',\n  'rgba16float',\n  'rg11b10ufloat',\n]);\n\n/**\n * `rgba8unorm` is out on WebGL: pixi gives it the unsized internal format `RGBA`, which a multisampled\n * renderbuffer rejects, so its target draws nothing\n * @internal\n */\nexport function isResolvableFormat(renderer: WebGLRenderer | WebGPURenderer, format: TEXTURE_FORMATS): boolean {\n  if (format === 'rgba8unorm' && renderer.type === RendererType.WEBGL) return false;\n  return RESOLVABLE_FORMATS.has(format);\n}\n","import type { View3D } from '../scene/View3D';\n\n/**\n * Throws when the view's camera can't render; call it after the transform walk, so `_worldVisible` is this frame's\n * @internal\n */\nexport function validateCamera(view3d: View3D): void {\n  const { camera } = view3d;\n\n  if (camera._view3d !== view3d) {\n    throw new Error(\n      'Camera3D is no longer in the View3D scene graph. ' +\n        \"Don't remove an assigned camera from its parent without reassigning view3d.camera.\",\n    );\n  }\n  if (camera.renderTexture) {\n    throw new Error(\n      \"The View3D's own camera draws the view, not a texture. Put the render texture on a second \" +\n        'camera and draw from it with a pass that names that camera.',\n    );\n  }\n  if (!camera.visible || camera._worldVisible === 0) {\n    throw new Error('Camera3D is hidden (visible=false or an ancestor is hidden). Cannot render with a hidden camera.');\n  }\n}\n","import { GCManagedHash, TexturePool } from 'pixi.js';\nimport type { Renderer } from 'pixi.js';\n\nimport type { View3D } from '../scene/View3D';\n\n/**\n * Enrols a renderer's Views in pixi's GC and is their one texture pool `evict` listener, so the global pool holds\n * no View once the renderer is destroyed; pixi's internal `GCManagedHash` nulls dropped entries, whatever its type says\n * @internal\n */\nexport class View3DGCRegistry {\n  private readonly _managedViews: GCManagedHash<View3D>;\n\n  constructor(renderer: Renderer) {\n    this._managedViews = new GCManagedHash<View3D>({ renderer, type: 'renderable', name: 'view3d' });\n    TexturePool.on('evict', this._releasePooledTextures);\n  }\n\n  /** Reads `items` on each call, since pixi's GC sweep replaces the object */\n  private readonly _releasePooledTextures = (): void => {\n    const views = this._managedViews.items;\n    for (const uid in views) {\n      const view = views[uid];\n      if (view) view._releasePooledTextures();\n    }\n  };\n\n  /** Enrols the View; does nothing for one already enrolled */\n  public track(view3d: View3D): void {\n    this._managedViews.add(view3d);\n  }\n\n  /** Unloads every enrolled View; the pipe must call it before freeing the stores their draws bind */\n  public destroy(): void {\n    TexturePool.off('evict', this._releasePooledTextures);\n    const views = Object.values(this._managedViews.items);\n    for (let i = 0; i < views.length; i++) views[i]?.unload();\n    this._managedViews.destroy();\n  }\n}\n","import type { Matrix4 } from '../matrix/Matrix4';\nimport type { SHAPE_PRIMITIVE_3D } from '../misc/const';\nimport type { PointData3D } from '../vector/PointData3D';\nimport { Vector3 } from '../vector/Vector3';\nimport type { Box } from './Box';\nimport type { Plane } from './Plane';\nimport type { Sphere } from './Sphere';\n\n/**\n * A half-line that starts at `origin` and runs along `direction`, for picking and line-of-sight\n * tests\n *\n * {@link View3D#screenToRay} builds one through a pointer position, in world space. Test a ray\n * against shapes in its own space; {@link Ray#applyMatrix4} moves it into a mesh's local space.\n * Keep `direction` unit length, and call `direction.normalize()` after changing it by hand; the\n * distance, closest-point and sphere methods give wrong results otherwise.\n * @example\n * ```ts\n * const hit = new Vector3();\n *\n * view3d.on('pointertap', (e) => {\n *   const ray = view3d.screenToRay(e.global);\n *\n *   if (ray.intersectPlane(ground, hit)) unit.moveTo(hit);\n * });\n * ```\n * @category maths\n * @standard\n */\nexport class Ray {\n  /**\n   * The point the ray starts from\n   * @example\n   * ```ts\n   * muzzle.getGlobalPosition(shotRay.origin);\n   * ```\n   */\n  public readonly origin: Vector3;\n  /**\n   * The unit-length direction the ray runs in\n   * @example\n   * ```ts\n   * sightLine.direction.copyFrom(target.position).subtract(sightLine.origin).normalize();\n   * ```\n   */\n  public readonly direction: Vector3;\n\n  /**\n   * Names the shape without an `instanceof` check, like the `type` on pixi's 2D shapes\n   * @readonly\n   * @default 'ray'\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type: SHAPE_PRIMITIVE_3D = 'ray';\n\n  /**\n   * Creates a new `Ray`\n   *\n   * Left out, the ray starts at the origin and points down -Z. Vectors passed in become the ray's\n   * own; they are not copied.\n   * @param origin - The origin of the ray\n   * @param direction - The unit-length direction of the ray\n   */\n  constructor(origin?: Vector3, direction?: Vector3) {\n    this.origin = origin !== undefined ? origin : new Vector3();\n    this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);\n  }\n\n  /**\n   * Sets the origin and direction of this ray, copying their values\n   * @example\n   * ```ts\n   * camera.worldTransform.extractForward(forward);\n   * aimRay.set(camera.getGlobalPosition(eye), forward);\n   * ```\n   * @param origin - The origin of the ray\n   * @param direction - The unit-length direction of the ray\n   * @returns This ray for chaining\n   */\n  public set(origin: PointData3D, direction: PointData3D): this {\n    this.origin.copyFrom(origin);\n    this.direction.copyFrom(direction);\n\n    return this;\n  }\n\n  /**\n   * Copies `ray` into this ray\n   * @example\n   * ```ts\n   * lastPointerRay.copyFrom(pointerRay);\n   * ```\n   * @param ray - The ray to copy from\n   * @returns This ray for chaining\n   */\n  public copyFrom(ray: Ray): this {\n    this.origin.copyFrom(ray.origin);\n    this.direction.copyFrom(ray.direction);\n\n    return this;\n  }\n\n  /**\n   * Copies this ray into `target` and returns it\n   * @example\n   * ```ts\n   * pointerRay.copyTo(lastPointerRay);\n   * ```\n   * @param target - The ray to copy into\n   * @returns The given `target`\n   */\n  public copyTo<T extends Ray>(target: T): T {\n    target.origin.copyFrom(this.origin);\n    target.direction.copyFrom(this.direction);\n\n    return target;\n  }\n\n  /**\n   * Creates a new `Ray` with the same origin and direction\n   * @example\n   * ```ts\n   * const reflected = incoming.clone();\n   * ```\n   * @returns The new ray\n   */\n  public clone(): Ray {\n    return new Ray().copyFrom(this);\n  }\n\n  /**\n   * Returns true when `origin` and `direction` match `ray` exactly (no epsilon tolerance)\n   * @example\n   * ```ts\n   * if (!pointerRay.equals(lastPointerRay)) updateHover(pointerRay);\n   * ```\n   * @param ray - The ray to compare with\n   * @returns Whether the origin and direction match\n   */\n  public equals(ray: Ray): boolean {\n    return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);\n  }\n\n  /**\n   * Writes the point `origin + direction * t` into `out`\n   *\n   * With a unit-length `direction`, `t` is the distance from `origin`.\n   * @example\n   * ```ts\n   * const reticle = new Vector3();\n   *\n   * aimRay.at(20, reticle);\n   * ```\n   * @param t - The distance along the ray\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The point along the ray\n   */\n  public at(t: number, out?: Vector3): Vector3 {\n    out ||= new Vector3();\n    out.x = this.origin.x + this.direction.x * t;\n    out.y = this.origin.y + this.direction.y * t;\n    out.z = this.origin.z + this.direction.z * t;\n\n    return out;\n  }\n\n  /**\n   * Writes the closest point on this ray to `point` into `out`\n   *\n   * Points behind `origin` give `origin`. Requires a unit-length `direction`.\n   * @example\n   * ```ts\n   * const nearest = new Vector3();\n   *\n   * aimRay.closestPointToPoint(enemy.position, nearest);\n   * ```\n   * @param point - The point to measure from\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The closest point on this ray\n   */\n  public closestPointToPoint(point: PointData3D, out?: Vector3): Vector3 {\n    out ||= new Vector3();\n    const dx = point.x - this.origin.x;\n    const dy = point.y - this.origin.y;\n    const dz = point.z - this.origin.z;\n    const directionDistance = dx * this.direction.x + dy * this.direction.y + dz * this.direction.z;\n\n    if (directionDistance < 0) return out.copyFrom(this.origin);\n\n    return out.copyFrom(this.origin).addScaledVector(this.direction, directionDistance);\n  }\n\n  /**\n   * Returns the Euclidean distance from `point` to the closest point on this ray\n   *\n   * Requires a unit-length `direction`.\n   * @example\n   * ```ts\n   * const nearMiss = aimRay.distanceToPoint(target.position) < 0.5;\n   * ```\n   * @param point - The point to measure from\n   * @returns The distance to the closest point on this ray\n   */\n  public distanceToPoint(point: PointData3D): number {\n    return Math.sqrt(this.distanceSqToPoint(point));\n  }\n\n  /**\n   * Returns the squared Euclidean distance from `point` to the closest point on this ray\n   *\n   * Cheaper than {@link Ray#distanceToPoint}; compare it against a squared radius. Requires a\n   * unit-length `direction`.\n   * @example\n   * ```ts\n   * const locked = enemies.find((enemy: Container3D) => aimRay.distanceSqToPoint(enemy.position) < 0.25);\n   * ```\n   * @param point - The point to measure from\n   * @returns The squared distance to the closest point on this ray\n   */\n  public distanceSqToPoint(point: PointData3D): number {\n    const dx = point.x - this.origin.x;\n    const dy = point.y - this.origin.y;\n    const dz = point.z - this.origin.z;\n    const directionDistance = dx * this.direction.x + dy * this.direction.y + dz * this.direction.z;\n\n    if (directionDistance < 0) return this.origin.distanceToSquared(point);\n\n    const cx = this.origin.x + this.direction.x * directionDistance;\n    const cy = this.origin.y + this.direction.y * directionDistance;\n    const cz = this.origin.z + this.direction.z * directionDistance;\n    const ex = cx - point.x;\n    const ey = cy - point.y;\n    const ez = cz - point.z;\n\n    return ex * ex + ey * ey + ez * ez;\n  }\n\n  /**\n   * Intersects this ray with `sphere`\n   *\n   * An empty sphere is never hit. Requires a unit-length `direction`.\n   * @example\n   * ```ts\n   * const hit = new Vector3();\n   *\n   * if (ray.intersectSphere(planet.boundingSphere, hit)) flag.position.copyFrom(hit);\n   * ```\n   * @param sphere - The sphere to intersect\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The entry point (or the exit point from inside), or `null` when the ray misses\n   * @see {@link Ray#intersectSphereT} For the distance to the same hit, without the point.\n   */\n  public intersectSphere(sphere: Sphere, out?: Vector3): Vector3 | null {\n    const t = this.intersectSphereT(sphere);\n\n    return t === -1 ? null : this.at(t, out);\n  }\n\n  /**\n   * Intersects this ray with `sphere` and returns the distance to the hit rather than the point\n   *\n   * Same hit as {@link Ray#intersectSphere}; {@link Ray#at} turns the distance into the point.\n   * Compare distances to find the nearest of several hits without making a point for each.\n   * Requires a unit-length `direction`.\n   * @example\n   * ```ts\n   * let nearest: Mesh3D | null = null;\n   * let nearestT = Infinity;\n   *\n   * for (const target of targets) {\n   *   const t = ray.intersectSphereT(target.boundingSphere);\n   *\n   *   if (t !== -1 && t < nearestT) {\n   *     nearestT = t;\n   *     nearest = target;\n   *   }\n   * }\n   * ```\n   * @param sphere - The sphere to intersect\n   * @returns The distance `t` to the hit (`>= 0`), or `-1` when the ray misses\n   */\n  public intersectSphereT(sphere: Sphere): number {\n    if (sphere.radius < 0) return -1;\n\n    const cx = sphere.center.x - this.origin.x;\n    const cy = sphere.center.y - this.origin.y;\n    const cz = sphere.center.z - this.origin.z;\n    const tca = cx * this.direction.x + cy * this.direction.y + cz * this.direction.z;\n    const d2 = cx * cx + cy * cy + cz * cz - tca * tca;\n    const radius2 = sphere.radius * sphere.radius;\n\n    if (d2 > radius2) return -1;\n\n    const thc = Math.sqrt(radius2 - d2);\n    const t0 = tca - thc;\n    const t1 = tca + thc;\n\n    if (t1 < 0) return -1;\n\n    return t0 < 0 ? t1 : t0;\n  }\n\n  /**\n   * Returns true when this ray hits `sphere`\n   *\n   * Requires a unit-length `direction`. An empty sphere is never hit.\n   * @example\n   * ```ts\n   * const hovered = enemies.filter((enemy: Mesh3D) => pointerRay.intersectsSphere(enemy.boundingSphere));\n   * ```\n   * @param sphere - The sphere to test\n   * @returns Whether the ray hits the sphere\n   */\n  public intersectsSphere(sphere: Sphere): boolean {\n    if (sphere.radius < 0) return false;\n\n    return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;\n  }\n\n  /**\n   * Intersects this ray with `plane`\n   *\n   * A ray that lies in the plane hits at its origin. Works with a `direction` of any length.\n   * @example\n   * ```ts\n   * const ground = new Plane(new Vector3(0, 1, 0), 0);\n   * const target = new Vector3();\n   *\n   * if (pointerRay.intersectPlane(ground, target)) cursor.position.copyFrom(target);\n   * ```\n   * @param plane - The plane to intersect\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The hit point, or `null` when the ray points away from the plane or runs parallel to it\n   */\n  public intersectPlane(plane: Plane, out?: Vector3): Vector3 | null {\n    const denominator = plane.normal.dot(this.direction);\n\n    if (denominator === 0) {\n      if (plane.distanceToPoint(this.origin) === 0) {\n        out ||= new Vector3();\n\n        return out.copyFrom(this.origin);\n      }\n\n      return null;\n    }\n\n    const t = -plane.distanceToPoint(this.origin) / denominator;\n\n    if (t < 0) return null;\n\n    return this.at(t, out);\n  }\n\n  /**\n   * Returns true when this ray hits `plane`, including when its origin lies on the plane\n   * @example\n   * ```ts\n   * const canLand = dropRay.intersectsPlane(ground);\n   * ```\n   * @param plane - The plane to test\n   * @returns Whether the ray hits the plane\n   */\n  public intersectsPlane(plane: Plane): boolean {\n    const distToPoint = plane.distanceToPoint(this.origin);\n    if (distToPoint === 0) return true;\n    const denominator = plane.normal.dot(this.direction);\n\n    return denominator * distToPoint < 0;\n  }\n\n  /**\n   * Intersects this ray with `box`\n   *\n   * Works with a `direction` of any length.\n   * @example\n   * ```ts\n   * const hit = new Vector3();\n   *\n   * if (localRay.intersectBox(mesh.geometry.bounds3D, hit)) decal.position.copyFrom(hit);\n   * ```\n   * @param box - The box to intersect\n   * @param out - Optional vector to write into; a new `Vector3` when omitted\n   * @returns The entry point (or the exit point from inside), or `null` when the ray misses\n   * @see {@link Ray#intersectBoxT} For the distance to the same hit, without the point.\n   */\n  public intersectBox(box: Box, out?: Vector3): Vector3 | null {\n    const t = this.intersectBoxT(box);\n\n    return t === -1 ? null : this.at(t, out);\n  }\n\n  /**\n   * Returns true when this ray hits `box`\n   * @example\n   * ```ts\n   * const hovered = pointerRay.intersectsBox(buttonBounds);\n   * ```\n   * @param box - The box to test\n   * @returns Whether the ray hits the box\n   */\n  public intersectsBox(box: Box): boolean {\n    return this.intersectBoxT(box) !== -1;\n  }\n\n  /**\n   * Transforms this ray by an affine `matrix`\n   *\n   * The direction comes out unit length, so a `t` measured along the new ray is in the new space's\n   * units: under scale, compare hits as points, not as `t` values.\n   *\n   * `matrix` must be affine (bottom row `[0, 0, 0, 1]`), as a {@link Container3D#worldTransform}\n   * always is and a projection matrix isn't.\n   * @example\n   * ```ts\n   * const worldToLocal = new Matrix4().getInverse(mesh.worldTransform);\n   * const localRay = pointerRay.applyMatrix4(worldToLocal, new Ray());\n   * const overMesh = localRay.intersectsBox(mesh.geometry.bounds3D);\n   * ```\n   * @param matrix - The affine matrix to transform by\n   * @param out - Target to write the result into instead of mutating this ray\n   * @returns The result ray for chaining\n   */\n  public applyMatrix4(matrix: Matrix4, out: Ray = this): this {\n    if (out !== this) out.copyFrom(this);\n    out.origin.applyAffineMatrix4(matrix);\n    out.direction.transformDirection(matrix);\n\n    return out as this;\n  }\n\n  /**\n   * Intersects this ray with `box` and returns the distance to the hit rather than the point\n   *\n   * Same hit as {@link Ray#intersectBox}; {@link Ray#at} turns `t` into the point. With a\n   * unit-length `direction`, `t` is the distance from `origin`. A ray that runs along one of the\n   * box's faces still gets the right entry or exit distance.\n   * @example\n   * ```ts\n   * const t = sightLine.intersectBoxT(wallBounds);\n   * const blocked = t !== -1 && t < distanceToTarget;\n   * ```\n   * @param box - The box to intersect\n   * @returns The distance `t` to the entry point, or to the exit point when the origin is inside\n   * the box, or `-1` when the ray misses\n   */\n  public intersectBoxT(box: Box): number {\n    const invdirx = 1 / this.direction.x;\n    const invdiry = 1 / this.direction.y;\n    const invdirz = 1 / this.direction.z;\n    const origin = this.origin;\n\n    let tmin: number;\n    let tmax: number;\n    let tymin: number;\n    let tymax: number;\n    let tzmin: number;\n    let tzmax: number;\n\n    if (invdirx >= 0) {\n      tmin = (box.min.x - origin.x) * invdirx;\n      tmax = (box.max.x - origin.x) * invdirx;\n    } else {\n      tmin = (box.max.x - origin.x) * invdirx;\n      tmax = (box.min.x - origin.x) * invdirx;\n    }\n\n    if (invdiry >= 0) {\n      tymin = (box.min.y - origin.y) * invdiry;\n      tymax = (box.max.y - origin.y) * invdiry;\n    } else {\n      tymin = (box.max.y - origin.y) * invdiry;\n      tymax = (box.min.y - origin.y) * invdiry;\n    }\n\n    if (tmin > tymax || tymin > tmax) return -1;\n\n    if (tymin > tmin || Number.isNaN(tmin)) tmin = tymin;\n    if (tymax < tmax || Number.isNaN(tmax)) tmax = tymax;\n\n    if (invdirz >= 0) {\n      tzmin = (box.min.z - origin.z) * invdirz;\n      tzmax = (box.max.z - origin.z) * invdirz;\n    } else {\n      tzmin = (box.max.z - origin.z) * invdirz;\n      tzmax = (box.min.z - origin.z) * invdirz;\n    }\n\n    if (tmin > tzmax || tzmin > tmax) return -1;\n\n    if (tzmin > tmin || Number.isNaN(tmin)) tmin = tzmin;\n    if (tzmax < tmax || Number.isNaN(tmax)) tmax = tzmax;\n\n    if (tmax < 0) return -1;\n\n    return tmin >= 0 ? tmin : tmax;\n  }\n\n  /**\n   * Returns a string representation of this ray\n   * @returns A string in the form `[@pixi/3d/math:Ray origin=(0, 0, 0) direction=(0, 0, -1)]`\n   * @advanced\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Ray origin=(${this.origin.x}, ${this.origin.y}, ${this.origin.z}) direction=(${this.direction.x}, ${this.direction.y}, ${this.direction.z})]`;\n  }\n}\n","import type { PointData, PointLike } from 'pixi.js';\n\nimport type { Matrix3 } from '../matrix/Matrix3';\nimport { clamp } from '../utils/clamp';\n\n/**\n * A point or direction in 2D, such as a UV coordinate, a screen position or stick input\n *\n * Math methods change the vector they're called on and return it, so calls chain. Pass an `out`\n * point as the last argument to write the result there instead and leave this one as it is;\n * {@link Vector3} explains why to reuse `out` points in code that runs every frame. Where a method\n * takes a point, any pixi.js `PointData` works, such as a pixi `Point` or a plain `{ x, y }` object.\n * @example\n * ```ts\n * const input = new Vector2(stick.x, stick.y);\n *\n * if (input.magnitudeSquared() > 1) input.normalize();\n * player.position.x += input.x * speed * dt;\n * player.position.z += input.y * speed * dt;\n * ```\n * @category maths\n * @standard\n */\nexport class Vector2 implements PointLike {\n  /**\n   * The x component\n   * @example\n   * ```ts\n   * cursor.x = event.global.x;\n   * ```\n   */\n  public x = 0;\n  /**\n   * The y component\n   * @example\n   * ```ts\n   * cursor.y = event.global.y;\n   * ```\n   */\n  public y = 0;\n\n  /**\n   * A static `Vector2` reset to `(0, 0)` on every access, for a result used straight away\n   *\n   * > [!IMPORTANT] This vector is shared and temporary. Do not store references to it.\n   * @example\n   * ```ts\n   * const dragged = Vector2.shared.copyFrom(event.global).distanceTo(dragStart) > dragThreshold;\n   * ```\n   */\n  static get shared(): Vector2 {\n    _shared.x = 0;\n    _shared.y = 0;\n\n    return _shared;\n  }\n\n  /**\n   * Creates a new `Vector2`\n   * @param x - The x component\n   * @param y - The y component\n   */\n  constructor(x = 0, y = 0) {\n    this.x = x;\n    this.y = y;\n  }\n\n  /**\n   * Sets the x and y components\n   * @example\n   * ```ts\n   * uvOffset.set(0.5, 0);\n   * tiling.set(4); // (4, 4)\n   * ```\n   * @param x - The x component\n   * @param y - The y component, defaults to `x`\n   */\n  public set(x = 0, y = x): this {\n    this.x = x;\n    this.y = y;\n\n    return this;\n  }\n\n  /**\n   * Copies x, y from the given point into this vector\n   * @example\n   * ```ts\n   * dragStart.copyFrom(event.global);\n   * ```\n   * @param p - The point to copy from\n   */\n  public copyFrom(p: PointData): this {\n    this.x = p.x;\n    this.y = p.y;\n\n    return this;\n  }\n\n  /**\n   * Copies this vector's x, y into the given point\n   * @example\n   * ```ts\n   * cursor.copyTo(crosshair.position);\n   * ```\n   * @param p - The point to copy into\n   * @returns The given point with values updated\n   */\n  public copyTo<T extends PointLike>(p: T): T {\n    p.set(this.x, this.y);\n\n    return p;\n  }\n\n  /**\n   * Checks whether `x` and `y` both match `p` exactly, with no tolerance\n   * @example\n   * ```ts\n   * if (!cursor.equals(lastCursor)) updateHover(cursor);\n   * ```\n   * @param p - The point to compare against\n   */\n  public equals(p: PointData): boolean {\n    return p.x === this.x && p.y === this.y;\n  }\n\n  /**\n   * Creates a copy of this vector\n   * @example\n   * ```ts\n   * const dragStart = cursor.clone();\n   * ```\n   */\n  public clone(): Vector2 {\n    return new Vector2(this.x, this.y);\n  }\n\n  /**\n   * Returns a readable string representation of this vector\n   * @example\n   * ```ts\n   * console.log(cursor.toString());\n   * ```\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Vector2 x=${this.x} y=${this.y}]`;\n  }\n\n  /**\n   * Reads `x`, `y` from `array` starting at `offset`\n   * @example\n   * ```ts\n   * uv.fromArray(uvs, vertexIndex * 2);\n   * ```\n   * @param array - The array to read from\n   * @param offset - The index of the first component\n   */\n  public fromArray(array: number[] | Float32Array, offset = 0): this {\n    this.x = array[offset];\n    this.y = array[offset + 1];\n\n    return this;\n  }\n\n  /**\n   * Writes this vector's values into `array` starting at `offset`\n   *\n   * Allocates a new array when one is not supplied.\n   * @example\n   * ```ts\n   * uv.toArray(uvs, vertexIndex * 2);\n   * ```\n   * @param array - The array to write into\n   * @param offset - The index to write the first component at\n   * @returns The array the values were written into\n   */\n  public toArray<T extends number[] | Float32Array = number[]>(array: T = [] as unknown as T, offset = 0): T {\n    array[offset] = this.x;\n    array[offset + 1] = this.y;\n\n    return array;\n  }\n\n  /**\n   * Adds `v` to this vector\n   * @example\n   * ```ts\n   * scroll.add(scrollStep);\n   * anchor.add(labelOffset, labelPosition);\n   * ```\n   * @param v - The point to add\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public add(v: PointData, out: PointLike = this): this {\n    out.x = this.x + v.x;\n    out.y = this.y + v.y;\n\n    return out as this;\n  }\n\n  /**\n   * Subtracts `v` from this vector\n   * @example\n   * ```ts\n   * cursor.subtract(dragStart, dragDelta);\n   * ```\n   * @param v - The point to subtract\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public subtract(v: PointData, out: PointLike = this): this {\n    out.x = this.x - v.x;\n    out.y = this.y - v.y;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies each component of this vector by the matching component of `v`\n   * @example\n   * ```ts\n   * uv.multiply(tiling);\n   * ```\n   * @param v - The point to multiply by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public multiply(v: PointData, out: PointLike = this): this {\n    out.x = this.x * v.x;\n    out.y = this.y * v.y;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies each component of this vector by the scalar `s`\n   * @example\n   * ```ts\n   * input.multiplyScalar(speed * dt, step);\n   * ```\n   * @param s - The scalar to multiply by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public multiplyScalar(s: number, out: PointLike = this): this {\n    out.x = this.x * s;\n    out.y = this.y * s;\n\n    return out as this;\n  }\n\n  /**\n   * Divides each component of this vector by the matching component of `v`\n   * @example\n   * ```ts\n   * pixel.divide({ x: texture.width, y: texture.height }, uv);\n   * ```\n   * @param v - The point to divide by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public divide(v: PointData, out: PointLike = this): this {\n    out.x = this.x / v.x;\n    out.y = this.y / v.y;\n\n    return out as this;\n  }\n\n  /**\n   * Divides each component of this vector by the scalar `s`\n   * @example\n   * ```ts\n   * thumbOffset.divideScalar(stickRadius, stick);\n   * ```\n   * @param s - The scalar to divide by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public divideScalar(s: number, out: PointLike = this): this {\n    return this.multiplyScalar(1 / s, out);\n  }\n\n  /**\n   * Adds `v * s` to this vector, such as a speed times the frame time\n   * @example\n   * ```ts\n   * uvOffset.addScaledVector(scrollSpeed, dt);\n   * ```\n   * @param v - The point to scale and add\n   * @param s - The scalar to multiply `v` by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public addScaledVector(v: PointData, s: number, out: PointLike = this): this {\n    out.x = this.x + v.x * s;\n    out.y = this.y + v.y * s;\n\n    return out as this;\n  }\n\n  /**\n   * Negates each component of this vector, reversing its direction\n   * @example\n   * ```ts\n   * hitDirection.negate(knockback);\n   * ```\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public negate(out: PointLike = this): this {\n    out.x = -this.x;\n    out.y = -this.y;\n\n    return out as this;\n  }\n\n  /**\n   * Sets each component to the smaller of this vector's and `v`'s\n   * @example\n   * ```ts\n   * selectionMin.min(cursor);\n   * ```\n   * @param v - The point to compare with\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public min(v: PointData, out: PointLike = this): this {\n    out.x = Math.min(this.x, v.x);\n    out.y = Math.min(this.y, v.y);\n\n    return out as this;\n  }\n\n  /**\n   * Sets each component to the larger of this vector's and `v`'s\n   * @example\n   * ```ts\n   * selectionMax.max(cursor);\n   * ```\n   * @param v - The point to compare with\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public max(v: PointData, out: PointLike = this): this {\n    out.x = Math.max(this.x, v.x);\n    out.y = Math.max(this.y, v.y);\n\n    return out as this;\n  }\n\n  /**\n   * Clamps each component of this vector between the matching components of `min` and `max`\n   *\n   * Assumes `min <= max` componentwise.\n   * @example\n   * ```ts\n   * cursor.clamp(minimapMin, minimapMax, minimapMarker);\n   * ```\n   * @param min - The lower bound per component\n   * @param max - The upper bound per component\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public clamp(min: PointData, max: PointData, out: PointLike = this): this {\n    out.x = clamp(this.x, min.x, max.x);\n    out.y = clamp(this.y, min.y, max.y);\n\n    return out as this;\n  }\n\n  /**\n   * Scales this vector to unit length, keeping its direction\n   *\n   * A zero vector stays zero.\n   * @example\n   * ```ts\n   * input.normalize();\n   * ```\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public normalize(out: PointLike = this): this {\n    const len = Math.sqrt(this.x * this.x + this.y * this.y) || 1;\n    const inv = 1 / len;\n    out.x = this.x * inv;\n    out.y = this.y * inv;\n\n    return out as this;\n  }\n\n  /**\n   * Scales this vector so its length equals `length`, keeping its direction\n   *\n   * A zero vector stays zero.\n   * @example\n   * ```ts\n   * dashDirection.setLength(dashDistance, dashOffset);\n   * ```\n   * @param length - The target length\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public setLength(length: number, out: PointLike = this): this {\n    const len = Math.sqrt(this.x * this.x + this.y * this.y) || 1;\n    const inv = length / len;\n    out.x = this.x * inv;\n    out.y = this.y * inv;\n\n    return out as this;\n  }\n\n  /**\n   * Computes the length of this vector\n   * @example\n   * ```ts\n   * const stickTilt = stick.magnitude();\n   * ```\n   */\n  public magnitude(): number {\n    return Math.sqrt(this.x * this.x + this.y * this.y);\n  }\n\n  /**\n   * Computes the squared length of this vector\n   *\n   * Cheaper than {@link Vector2#magnitude}, since it skips the square root, and enough to compare\n   * lengths.\n   * @example\n   * ```ts\n   * if (stick.magnitudeSquared() < deadZone * deadZone) stick.set(0);\n   * ```\n   */\n  public magnitudeSquared(): number {\n    return this.x * this.x + this.y * this.y;\n  }\n\n  /**\n   * Computes the distance from this point to `v`\n   * @example\n   * ```ts\n   * if (cursor.distanceTo(dragStart) > dragThreshold) startDrag();\n   * ```\n   * @param v - The point to measure to\n   */\n  public distanceTo(v: PointData): number {\n    const dx = this.x - v.x;\n    const dy = this.y - v.y;\n\n    return Math.sqrt(dx * dx + dy * dy);\n  }\n\n  /**\n   * Computes the squared distance from this point to `v`\n   *\n   * Cheaper than {@link Vector2#distanceTo} and enough to compare distances.\n   * @example\n   * ```ts\n   * const hovered = cursor.distanceToSquared(button.center) < button.radius * button.radius;\n   * ```\n   * @param v - The point to measure to\n   */\n  public distanceToSquared(v: PointData): number {\n    const dx = this.x - v.x;\n    const dy = this.y - v.y;\n\n    return dx * dx + dy * dy;\n  }\n\n  /**\n   * Computes the dot product of this vector and `v`\n   *\n   * For unit vectors it's the cosine of the angle between them: 1 when they point the same way, 0 at\n   * right angles and -1 when opposite.\n   * @example\n   * ```ts\n   * const targetIsAhead = heading.dot(toTarget) > 0;\n   * ```\n   * @param v - The other vector\n   */\n  public dot(v: PointData): number {\n    return this.x * v.x + this.y * v.y;\n  }\n\n  /**\n   * Computes the angle from the +x axis to this vector, turning toward +y\n   * @example\n   * ```ts\n   * cursor.subtract(arrow.position, toCursor);\n   * arrow.rotation = toCursor.angle();\n   * ```\n   * @returns The angle in radians, from -π to π\n   */\n  public angle(): number {\n    return Math.atan2(this.y, this.x);\n  }\n\n  /**\n   * Computes `x * v.y - y * v.x`, the z of the 3D cross product with both vectors at `z = 0`\n   *\n   * The sign says which way to turn from this vector to `v`: positive is the way +x turns toward +y\n   * (counter-clockwise when y points up, clockwise on a pixi screen, where y points down), negative\n   * the other way, and zero when they are parallel.\n   * @example\n   * ```ts\n   * const turnDirection = Math.sign(heading.cross(toTarget));\n   * ```\n   * @param v - The other vector\n   */\n  public cross(v: PointData): number {\n    return this.x * v.y - this.y * v.x;\n  }\n\n  /**\n   * Transforms this point by `m` as a 2D transform: rotation, scale and translation\n   *\n   * The matrix's bottom row is not used, so there is no divide.\n   * @example\n   * ```ts\n   * const uvTransform = new Matrix3().setUvTransform(0.25, 0, 2, 2, 0, 0.5, 0.5);\n   *\n   * uv.applyMatrix3(uvTransform);\n   * ```\n   * @param m - The matrix to apply\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public applyMatrix3(m: Matrix3, out: PointLike = this): this {\n    const x = this.x;\n    const y = this.y;\n    const e = m.elements;\n    out.x = e[0] * x + e[3] * y + e[6];\n    out.y = e[1] * x + e[4] * y + e[7];\n\n    return out as this;\n  }\n\n  /**\n   * Rotates this vector around the origin by `angle` radians, turning +x toward +y\n   * @example\n   * ```ts\n   * stick.rotate(-cameraYaw, moveDirection);\n   * ```\n   * @param angle - The rotation angle in radians\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public rotate(angle: number, out: PointLike = this): this {\n    const c = Math.cos(angle);\n    const s = Math.sin(angle);\n    const x = this.x;\n    const y = this.y;\n    out.x = x * c - y * s;\n    out.y = x * s + y * c;\n\n    return out as this;\n  }\n\n  /**\n   * Rotates this point around `center` by `angle` radians, turning +x toward +y\n   * @example\n   * ```ts\n   * moon.rotateAround(planet, orbitSpeed * dt);\n   * ```\n   * @param center - The point to rotate around\n   * @param angle - The rotation angle in radians\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The vector the result was written into\n   */\n  public rotateAround(center: PointData, angle: number, out: PointLike = this): this {\n    const c = Math.cos(angle);\n    const s = Math.sin(angle);\n    const dx = this.x - center.x;\n    const dy = this.y - center.y;\n    out.x = dx * c - dy * s + center.x;\n    out.y = dx * s + dy * c + center.y;\n\n    return out as this;\n  }\n}\n\nconst _shared = new Vector2();\n","import type { Geometry3D } from '../geometry/Geometry3D';\nimport type { Box } from '../math/shapes/Box';\nimport type { Ray } from '../math/shapes/Ray';\nimport type { Sphere } from '../math/shapes/Sphere';\nimport { Vector2 } from '../math/vector/Vector2';\nimport { Vector3 } from '../math/vector/Vector3';\nimport type { Container3D } from '../scene/Container3D';\n\n/**\n * A hit shape of your own for {@link Container3D#hitVolume}, like `IHitArea` in 2D\n *\n * Any object with these members works, with no base class: an adapter around a physics collider,\n * an analytic capsule, a signed distance field. `Box`, `Sphere` and `Geometry3D` work as they are,\n * with faster built-in tests, so don't wrap them.\n *\n * Everything is in the node's local space, so the volume never deals with transforms.\n * @example\n * ```ts\n * // A flat disc in the node's local XZ plane.\n * class DiscVolume implements IHitVolume3D {\n *   constructor(public radius: number) {}\n *\n *   get boundingRadiusSq(): number {\n *     return this.radius * this.radius;\n *   }\n *\n *   raycast(localRay: Ray, out: HitResult3D): number {\n *     const t = -localRay.origin.y / localRay.direction.y;\n *     if (!Number.isFinite(t) || t < 0) return -1; // behind the origin, or parallel\n *     localRay.at(t, out.point);\n *     if (out.point.x ** 2 + out.point.z ** 2 > this.radius ** 2) return -1;\n *     out.distance = t;\n *     out.normal.set(0, 0, 0);\n *     out.uv.set(0, 0);\n *     out.triangleIndex = -1;\n *     return t;\n *   }\n * }\n *\n * mesh.interactive = true;\n * mesh.hitVolume = new DiscVolume(2);\n * ```\n * @see {@link Container3D#hitVolume} For assigning a volume to a node.\n * @see {@link HitVolume3DInput} For everything else that property accepts.\n * @category events\n * @standard\n */\nexport interface IHitVolume3D {\n  /**\n   * Squared radius of a sphere around the node's local origin that encloses the volume\n   *\n   * A ray that misses this sphere skips {@link IHitVolume3D#raycast | raycast}. It's read on every\n   * pick, so it can change with the shape. `Infinity` suits an unbounded shape, at the cost of a\n   * `raycast` call on every pick.\n   * @example\n   * ```ts\n   * public readonly boundingRadiusSq = Infinity; // an endless ground plane has no bounds\n   * ```\n   */\n  readonly boundingRadiusSq: number;\n\n  /**\n   * Finds where `localRay` first hits the volume\n   *\n   * `localRay.direction` is unit length, so `t` is the distance to the hit in the node's local\n   * units. Hits on nodes of different scale still compare correctly: the picker measures world\n   * distance from `out.point`.\n   *\n   * On a hit, fill `out` as the engine shapes do: `out.point` with `localRay.at(t, out.point)`,\n   * `out.distance` with `t`, and, unless the volume has triangles, `out.normal` and `out.uv` with\n   * zeros and `out.triangleIndex` with `-1`. On a miss, return `-1`; the picker ignores `out`.\n   * @example\n   * ```ts\n   * public raycast(localRay: Ray, out: HitResult3D): number {\n   *   const t = localRay.intersectSphereT(bounds);\n   *   if (t === -1) return -1;\n   *\n   *   localRay.at(t, out.point);\n   *   out.distance = t;\n   *   out.normal.set(0, 0, 0);\n   *   out.uv.set(0, 0);\n   *   out.triangleIndex = -1;\n   *   return t;\n   * }\n   * ```\n   * @param {Ray} localRay - The pick ray in the node's local space, unit-length direction.\n   * @param {HitResult3D} out - Scratch buffer to fill on a hit.\n   * @returns The parametric `t` of the closest hit (`>= 0`), or `-1` for a miss.\n   */\n  raycast(localRay: Ray, out: HitResult3D): number;\n\n  /**\n   * Whether a point in the node's local space is inside the volume\n   *\n   * Only needed for the volume to clip the node's descendants, as every `hitVolume` you set does.\n   * Without it, the volume still picks but never clips.\n   * @example\n   * ```ts\n   * public containsPoint(localPoint: Vector3): boolean {\n   *   return localPoint.x ** 2 + localPoint.z ** 2 <= radius ** 2 && Math.abs(localPoint.y) <= halfHeight;\n   * }\n   * ```\n   * @param {Vector3} localPoint - The point to test, in the node's local space.\n   * @returns Whether the point lies inside the volume.\n   */\n  containsPoint?(localPoint: Vector3): boolean;\n}\n\n/**\n * What {@link Container3D#hitVolume} accepts, like `hitArea` in 2D\n *\n * A string derives the shape from the node:\n *\n * - `'box'`: the node's bounding box.\n * - `'geometry'`: every triangle of the node's own geometry, as stored: skinning and morph targets\n *   don't move it. Hits carry a normal and UV, but every triangle is tested once the ray reaches\n *   the bounding box.\n *\n * An instance gives a shape the node can't work out, in the node's local space:\n *\n * - {@link Box}: an axis-aligned box.\n * - {@link Sphere}: an analytic sphere. A {@link SphereGeometry} works too, but tests every\n *   triangle.\n * - {@link Geometry3D}: a mesh tested per triangle, typically a simpler stand-in for a detailed\n *   model.\n * - {@link IHitVolume3D}: a shape of your own, such as a physics collider.\n * @example\n * ```ts\n * mesh.interactive = true;\n *\n * mesh.hitVolume = 'box';                          // bounding box derived from the node\n * mesh.hitVolume = 'geometry';                     // per triangle, hits carry normal and uv\n * mesh.hitVolume = new Sphere(new Vector3(), 0.5); // the cheapest exact shape for round meshes\n * mesh.hitVolume = new CapsuleGeometry();          // a low-poly stand-in\n * ```\n * @remarks\n * - Only per-triangle shapes (`'geometry'` and `Geometry3D`) give a hit a `normal`, `uv` and\n *   `triangleIndex`. `Box` and `Sphere` hits have zeros and `-1`; an {@link IHitVolume3D} fills in\n *   what it chooses.\n * - Per-triangle tests hit back faces too, and the normal follows the triangle's winding, so it can\n *   face away from the camera.\n * - With the camera inside a box or sphere, a mesh's default bounding box included, the hit is\n *   where the ray leaves it, on the far side.\n * - On a `Mesh3D`, `'box'` and `'geometry'` keep reading the mesh's current geometry, even after a\n *   swap. On a plain `Container3D`, `'box'` measures the subtree once, when set, and unlike\n *   `getLocalBounds()` it includes hidden descendants.\n * - Per-triangle tests need `'triangle-list'` topology and float32 positions. Line, strip and\n *   point geometry, quantised positions (KHR_mesh_quantization), and interleaved geometry\n *   (`interleave: true`) never hit; use `'box'` or a stand-in geometry for those.\n * - `'geometry'` on a plain `Container3D` warns and is ignored, since it has no geometry.\n * @see {@link View3D#raycast} For querying a hit directly rather than through events\n * @category events\n * @standard\n */\nexport type HitVolume3DInput = 'box' | 'geometry' | Box | Sphere | Geometry3D | IHitVolume3D | null;\n\n/** @internal */\nexport type HitVolume3D = Box | Sphere | Geometry3D | IHitVolume3D;\n\n/**\n * The buffer a hit test writes into, which an {@link IHitVolume3D} fills in on a hit\n *\n * Everything in it is in the node's local space; events and {@link View3D#raycast} report the\n * closest hit in world space, as a {@link RaycastHit3D}. One buffer is reused for every test, so a\n * hit has to write every field.\n * @example\n * ```ts\n * public raycast(localRay: Ray, out: HitResult3D): number {\n *   const t = localRay.intersectBoxT(bounds);\n *   if (t !== -1) {\n *     localRay.at(t, out.point);\n *     out.distance = t;\n *     out.normal.set(0, 0, 0);\n *     out.uv.set(0, 0);\n *     out.triangleIndex = -1;\n *   }\n *   return t;\n * }\n * ```\n * @category events\n * @standard\n */\nexport interface HitResult3D {\n  /**\n   * Hit point, in the node's local space\n   * @example\n   * ```ts\n   * localRay.at(t, out.point);\n   * ```\n   */\n  point: Vector3;\n  /**\n   * The hit triangle's flat normal, in local space; zero for a shape without triangles\n   *\n   * Ignored, and reported as zero, while {@link HitResult3D#triangleIndex | triangleIndex} is `-1`.\n   * @example\n   * ```ts\n   * out.normal.set(0, 0, 0);\n   * ```\n   */\n  normal: Vector3;\n  /**\n   * Texture coordinate at the hit; zero for a shape without triangles\n   * @example\n   * ```ts\n   * out.uv.set(0, 0);\n   * ```\n   */\n  uv: Vector2;\n  /**\n   * `t`, the distance along the ray to the hit, in the ray's units\n   * @example\n   * ```ts\n   * out.distance = t;\n   * ```\n   */\n  distance: number;\n  /**\n   * Index of the triangle hit, or `-1` for a shape without triangles\n   * @example\n   * ```ts\n   * out.triangleIndex = -1;\n   * ```\n   */\n  triangleIndex: number;\n}\n\n/** @internal */\nexport function createHitResult3D(): HitResult3D {\n  return {\n    point: new Vector3(),\n    normal: new Vector3(),\n    uv: new Vector2(),\n    distance: -1,\n    triangleIndex: -1,\n  };\n}\n\n/**\n * A hit in world space: what {@link View3D#raycast} returns, and what every 3D pointer event\n * carries as {@link Event3DFields#hit3D | hit3D}\n * @example\n * ```ts\n * const hit = view3d.raycast(event.global);\n * if (hit) marker.position.copyFrom(hit.point);\n *\n * // The same shape on an event; null when the pointer is over nothing.\n * mesh.on('pointertap', (e) => {\n *   if (e.hit3D) marker.position.copyFrom(e.hit3D.point);\n * });\n * ```\n * @remarks\n * - An event's `hit3D` is reused for later events, so copy out anything you keep; see\n *   {@link Event3DFields}.\n * @see {@link Container3D#hitVolume} For choosing the shape each node is picked against\n * @category events\n * @standard\n */\nexport interface RaycastHit3D {\n  /**\n   * The node the hit is reported to\n   *\n   * That is the node the ray struck, or its nearest interactive ancestor when the struck node\n   * isn't interactive (`'auto'` or `'passive'`). The other fields still describe the struck node.\n   * @example\n   * ```ts\n   * const hit = view3d.raycast(e.global);\n   * if (hit) select(hit.target);\n   * ```\n   */\n  target: Container3D;\n  /**\n   * Hit point, in world space\n   * @example\n   * ```ts\n   * if (hit) marker.position.copyFrom(hit.point);\n   * ```\n   */\n  point: Vector3;\n  /**\n   * Hit point in the local space of the node the ray struck\n   *\n   * For another node's space, pass `point` to that node's {@link Container3D#toLocal | toLocal}.\n   * @example\n   * ```ts\n   * // Which half of the dial was grabbed, in the dial's own frame?\n   * dial.on('pointerdown', (e) => {\n   *   grabbedRight = e.hit3D !== null && e.hit3D.localPoint.x > 0;\n   * });\n   * ```\n   */\n  localPoint: Vector3;\n  /**\n   * Distance from the camera to the hit along the ray, in world units\n   *\n   * For an orthographic camera it is measured from the camera plane.\n   * @example\n   * ```ts\n   * if (hit && hit.distance < reach) pickUp(hit.target);\n   * ```\n   */\n  distance: number;\n  /**\n   * The hit triangle's flat normal, in world space; zero when `triangleIndex` is `-1`\n   * @example\n   * ```ts\n   * if (hit && hit.normal.y > 0.7) placeTower(hit.point); // flat enough to build on\n   * ```\n   */\n  normal: Vector3;\n  /**\n   * Texture coordinate at the hit, for a per-triangle shape\n   *\n   * A geometry without float32 UVs gives the hit's barycentric coordinates in its triangle\n   * instead. `Box` and `Sphere` hits give zero.\n   * @example\n   * ```ts\n   * if (hit) paintAt(hit.uv);\n   * ```\n   */\n  uv: Vector2;\n  /**\n   * Index of the triangle hit, or `-1` for a shape without triangles\n   * @example\n   * ```ts\n   * if (hit && hit.triangleIndex !== -1) highlightFace(hit.target, hit.triangleIndex);\n   * ```\n   */\n  triangleIndex: number;\n}\n\n/**\n * Creates an empty {@link RaycastHit3D}, for {@link View3D#raycast} to fill again and again\n *\n * `target` is unset until a raycast hits, so read it only after one returns the hit.\n * @returns The new hit\n * @example\n * ```ts\n * const hover = createRaycastHit3D();\n * app.ticker.add(() => {\n *   if (view3d.raycast(pointer, hover)) cursor3d.position.copyFrom(hover.point);\n * });\n * ```\n * @category events\n * @standard\n */\nexport function createRaycastHit3D(): RaycastHit3D {\n  return {\n    target: null!,\n    point: new Vector3(),\n    localPoint: new Vector3(),\n    normal: new Vector3(),\n    uv: new Vector2(),\n    distance: -1,\n    triangleIndex: -1,\n  };\n}\n\n/** @internal */\nexport function copyRaycastHit3D(from: RaycastHit3D, to: RaycastHit3D): void {\n  to.target = from.target;\n  to.point.copyFrom(from.point);\n  to.localPoint.copyFrom(from.localPoint);\n  to.normal.copyFrom(from.normal);\n  to.uv.copyFrom(from.uv);\n  to.distance = from.distance;\n  to.triangleIndex = from.triangleIndex;\n}\n","import type { Geometry3D } from '../geometry/Geometry3D';\nimport type { Ray } from '../math/shapes/Ray';\nimport type { HitResult3D } from './HitResult3D';\n\nconst EPSILON = 1e-7;\n\n/**\n * Back faces hit too, so meshes with inverted winding still pick. A ray starting inside the bounds\n * always runs the triangle loop, since `intersectBoxT` then gives the exit distance, not the entry.\n * @returns The `t` of the closest hit, or `-1` for a miss.\n * @internal\n */\nexport function intersectRayGeometry(localRay: Ray, geom: Geometry3D, out: HitResult3D, maxT = Infinity): number {\n  if (geom.topology !== 'triangle-list') return -1;\n\n  const bounds = geom.bounds3D;\n  const boundsT = localRay.intersectBoxT(bounds);\n  if (boundsT === -1) return -1;\n  if (boundsT >= maxT && !bounds.containsPoint(localRay.origin)) return -1;\n\n  const positionAttr = geom.attributes.aPosition;\n  if (!positionAttr) return -1;\n\n  const positions = positionAttr.buffer.data;\n  if (!(positions instanceof Float32Array)) return -1;\n\n  const indexBuffer = geom.indexBuffer;\n  const indices = indexBuffer ? (indexBuffer.data as Uint16Array | Uint32Array) : null;\n  const triangleCount = indices ? indices.length / 3 : positions.length / 9;\n\n  const ox = localRay.origin.x;\n  const oy = localRay.origin.y;\n  const oz = localRay.origin.z;\n  const dx = localRay.direction.x;\n  const dy = localRay.direction.y;\n  const dz = localRay.direction.z;\n\n  let bestT = maxT;\n  let bestTri = -1;\n  let bestU = 0;\n  let bestV = 0;\n  let bestNx = 0;\n  let bestNy = 0;\n  let bestNz = 0;\n\n  for (let i = 0; i < triangleCount; i++) {\n    const i0 = indices ? indices[i * 3] : i * 3;\n    const i1 = indices ? indices[i * 3 + 1] : i * 3 + 1;\n    const i2 = indices ? indices[i * 3 + 2] : i * 3 + 2;\n\n    const ax = positions[i0 * 3];\n    const ay = positions[i0 * 3 + 1];\n    const az = positions[i0 * 3 + 2];\n\n    const bx = positions[i1 * 3];\n    const by = positions[i1 * 3 + 1];\n    const bz = positions[i1 * 3 + 2];\n\n    const cx = positions[i2 * 3];\n    const cy = positions[i2 * 3 + 1];\n    const cz = positions[i2 * 3 + 2];\n\n    const e1x = bx - ax;\n    const e1y = by - ay;\n    const e1z = bz - az;\n    const e2x = cx - ax;\n    const e2y = cy - ay;\n    const e2z = cz - az;\n\n    const hx = dy * e2z - dz * e2y;\n    const hy = dz * e2x - dx * e2z;\n    const hz = dx * e2y - dy * e2x;\n\n    const a = e1x * hx + e1y * hy + e1z * hz;\n    if (a > -EPSILON && a < EPSILON) continue;\n\n    const f = 1 / a;\n    const sx = ox - ax;\n    const sy = oy - ay;\n    const sz = oz - az;\n\n    const u = f * (sx * hx + sy * hy + sz * hz);\n    if (u < 0 || u > 1) continue;\n\n    const qx = sy * e1z - sz * e1y;\n    const qy = sz * e1x - sx * e1z;\n    const qz = sx * e1y - sy * e1x;\n\n    const v = f * (dx * qx + dy * qy + dz * qz);\n    if (v < 0 || u + v > 1) continue;\n\n    const t = f * (e2x * qx + e2y * qy + e2z * qz);\n    if (t < EPSILON) continue;\n    if (t >= bestT) continue;\n\n    bestT = t;\n    bestTri = i;\n    bestU = u;\n    bestV = v;\n    bestNx = e1y * e2z - e1z * e2y;\n    bestNy = e1z * e2x - e1x * e2z;\n    bestNz = e1x * e2y - e1y * e2x;\n  }\n\n  if (bestTri < 0) return -1;\n\n  const nLen = Math.sqrt(bestNx * bestNx + bestNy * bestNy + bestNz * bestNz);\n  if (nLen > 0) {\n    out.normal.set(bestNx / nLen, bestNy / nLen, bestNz / nLen);\n  } else {\n    out.normal.set(0, 0, 0);\n  }\n\n  out.point.set(ox + dx * bestT, oy + dy * bestT, oz + dz * bestT);\n  out.distance = bestT;\n  out.triangleIndex = bestTri;\n\n  const uvAttr = geom.attributes.aUV;\n  const uvData = uvAttr?.buffer.data;\n  if (uvData instanceof Float32Array && indices) {\n    const i0 = indices[bestTri * 3];\n    const i1 = indices[bestTri * 3 + 1];\n    const i2 = indices[bestTri * 3 + 2];\n    const w = 1 - bestU - bestV;\n    out.uv.x = uvData[i0 * 2] * w + uvData[i1 * 2] * bestU + uvData[i2 * 2] * bestV;\n    out.uv.y = uvData[i0 * 2 + 1] * w + uvData[i1 * 2 + 1] * bestU + uvData[i2 * 2 + 1] * bestV;\n  } else if (uvData instanceof Float32Array) {\n    const i0 = bestTri * 3;\n    const i1 = bestTri * 3 + 1;\n    const i2 = bestTri * 3 + 2;\n    const w = 1 - bestU - bestV;\n    out.uv.x = uvData[i0 * 2] * w + uvData[i1 * 2] * bestU + uvData[i2 * 2] * bestV;\n    out.uv.y = uvData[i0 * 2 + 1] * w + uvData[i1 * 2 + 1] * bestU + uvData[i2 * 2 + 1] * bestV;\n  } else {\n    out.uv.x = bestU;\n    out.uv.y = bestV;\n  }\n\n  return bestT;\n}\n","import { Geometry3D } from '../geometry/Geometry3D';\nimport { Box } from '../math/shapes/Box';\nimport type { Ray } from '../math/shapes/Ray';\nimport { Sphere } from '../math/shapes/Sphere';\nimport type { HitResult3D, HitVolume3D } from './HitResult3D';\nimport { intersectRayGeometry } from './intersectRayGeometry';\n\n/**\n * Squared radius of a sphere about the node's local origin enclosing `volume`, as the pick in\n * `EventBoundary3D.ts` centres it on the node; uncached, so a shape edited in place picks right\n * @internal\n */\nexport function hitVolumeBoundingRadiusSq(volume: HitVolume3D): number {\n  if (volume instanceof Sphere) {\n    const c = volume.center;\n    const r = Math.sqrt(c.x * c.x + c.y * c.y + c.z * c.z) + Math.max(volume.radius, 0);\n    return r * r;\n  }\n\n  if (volume instanceof Box || volume instanceof Geometry3D) {\n    const box = volume instanceof Geometry3D ? volume.bounds3D : volume;\n    const { min, max } = box;\n    const x = Math.max(min.x * min.x, max.x * max.x);\n    const y = Math.max(min.y * min.y, max.y * max.y);\n    const z = Math.max(min.z * min.z, max.z * max.z);\n\n    return x + y + z;\n  }\n\n  return volume.boundingRadiusSq;\n}\n\n/**\n * @param localRay - The ray in the node's local space, with a unit-length direction, as\n * `IHitVolume3D.raycast` promises.\n * @param volume - The node's resolved hit volume.\n * @param out - Filled on a hit.\n * @param maxT - Nearest `t` found so far; only a `Geometry3D` uses it, to skip its triangle loop.\n * @returns The `t` of the closest hit, or `-1` for a miss.\n * @internal\n */\nexport function intersectRayHitVolume(localRay: Ray, volume: HitVolume3D, out: HitResult3D, maxT = Infinity): number {\n  if (volume instanceof Box) {\n    const t = localRay.intersectBoxT(volume);\n    if (t === -1) return -1;\n    localRay.at(t, out.point);\n    out.distance = t;\n    out.normal.set(0, 0, 0);\n    out.uv.x = 0;\n    out.uv.y = 0;\n    out.triangleIndex = -1;\n    return t;\n  }\n\n  if (volume instanceof Sphere) {\n    const t = localRay.intersectSphereT(volume);\n    if (t === -1) return -1;\n    localRay.at(t, out.point);\n    out.distance = t;\n    out.normal.set(0, 0, 0);\n    out.uv.x = 0;\n    out.uv.y = 0;\n    out.triangleIndex = -1;\n    return t;\n  }\n\n  if (volume instanceof Geometry3D) {\n    return intersectRayGeometry(localRay, volume, out, maxT);\n  }\n\n  return volume.raycast(localRay, out);\n}\n","import type { FederatedPointerEvent, FederatedWheelEvent } from 'pixi.js';\nimport { FederatedMouseEvent } from 'pixi.js';\n\nimport type { Container3D } from '../scene/Container3D';\nimport type { RaycastHit3D } from './HitResult3D';\nimport { createRaycastHit3D } from './HitResult3D';\n\n/**\n * The 3D fields a {@link View3D} adds to the pointer and wheel events it passes into its scene\n *\n * They sit on pixi's own event object, so 2D listeners that run after the View passes the event\n * on, such as the View's plain listeners and bubbling ones on its 2D ancestors, can read them too.\n * @remarks\n * - **Copy out anything you keep.** Pixi reuses event objects, so later events overwrite `hit3D`\n *   and its vectors, as they do `global`.\n * - The View's `on*` handlers and `*capture` listeners run before it passes the event on, so\n *   there the fields can be `null`. Read them in a plain listener, `view3d.on('pointertap', …)`.\n * - In a 3D node's listeners, except on `globalpointermove`, `globalmousemove` and\n *   `globaltouchmove`, `composedPath()` returns the 3D chain, `[view3d.root, …, target]`, in an\n *   array the View can empty after the event. Copy it to keep it.\n * - On events that never passed through a View3D, the fields read `null`. The exception is a 2D\n *   node's `pointerover` and `mouseover` when the pointer moves straight off the View onto it:\n *   `target3D` still names the 3D node it left.\n * @example\n * ```ts\n * mesh.hitVolume = 'geometry'; // per-triangle hits, so `normal` isn't zero\n * mesh.on('pointertap', (e) => {\n *   if (!e.hit3D) return;\n *   spawnDecal(e.hit3D.point, e.hit3D.normal); // reading inside the handler is fine\n *   lastHit.copyFrom(e.hit3D.point);           // keeping the value needs a copy\n * });\n * ```\n * @category events\n * @standard\n */\nexport interface Event3DFields {\n  /**\n   * What the pointer is over: the hit {@link View3D#raycast} would return for `event.global`, or\n   * `null` when the ray hits nothing\n   *\n   * It ignores which node is being told, so a `pointerupoutside` on the pressed node reports where\n   * the pointer was released, such as on a drop target, and a `pointerout` reports the node the\n   * pointer moved onto. It is `null` on the `pointerout` as the pointer leaves the View and on a\n   * release outside the View.\n   * @example\n   * ```ts\n   * ground.on('pointertap', (e) => {\n   *   if (e.hit3D) marker.position.copyFrom(e.hit3D.point); // drop a marker where the ray landed\n   * });\n   *\n   * // Only per-triangle volumes carry surface data\n   * wall.hitVolume = 'geometry';\n   * wall.on('pointertap', (e) => {\n   *   if (e.hit3D && e.hit3D.normal.y > 0.9) console.log('floor, not wall');\n   * });\n   * ```\n   */\n  readonly hit3D: RaycastHit3D | null;\n  /**\n   * The 3D node this event is about, or `null` when it belongs to the View, as on a click on empty\n   * space\n   *\n   * The View's own listeners see the View as `event.target`, while `target3D` still names the node.\n   * @remarks\n   * - In a 3D node's `*upoutside` listeners it names the pressed node.\n   * - During `pointerenter` and `pointerleave`, which don't bubble, it names the node being told.\n   * - When the ray strikes a non-interactive (`'auto'` or `'passive'`) node, it names that node's\n   *   nearest interactive ancestor.\n   * @example\n   * ```ts\n   * // One View-level listener instead of a listener per mesh\n   * view3d.on('pointertap', (e) => {\n   *   if (e.target3D) select(e.target3D);\n   *   else clearSelection();\n   * });\n   * ```\n   */\n  readonly target3D: Container3D | null;\n  /**\n   * The 3D node whose listeners are running, or `null` outside the 3D dispatch\n   *\n   * The 3D counterpart of `currentTarget`: while `target3D` stays on the event's target, this moves\n   * from node to node, so an ancestor's listener reads the ancestor. The View's own listeners read\n   * `null`.\n   * @example\n   * ```ts\n   * // One listener on the group tells which node it fired on\n   * group.on('pointerdown', (e) => {\n   *   // e.target3D is the node hit, or the group when that node isn't interactive\n   *   console.log(e.currentTarget3D === group); // true\n   * });\n   * ```\n   */\n  readonly currentTarget3D: Container3D | null;\n}\n\n/**\n * The type of a pointer handler property on a 3D node, such as\n * {@link IFederatedContainer3D#onclick | onclick}\n * @example\n * ```ts\n * const grow: Pointer3DEventHandler = (e) => e.target3D?.scale.set(1.1);\n *\n * button.onpointerenter = grow;\n * ```\n * @category events\n * @standard\n */\nexport type Pointer3DEventHandler = (event: Pointer3DEvent) => void;\n\n/**\n * The type of {@link IFederatedContainer3D#onwheel | Container3D.onwheel}\n * @example\n * ```ts\n * const push: Wheel3DEventHandler = (e) => {\n *   panel.position.z += e.deltaY * 0.01;\n * };\n *\n * panel.onwheel = push;\n * ```\n * @category events\n * @standard\n */\nexport type Wheel3DEventHandler = (event: Wheel3DEvent) => void;\n\n/**\n * A pixi.js `FederatedPointerEvent` with the {@link Event3DFields | 3D fields}; what a 3D node's\n * pointer, mouse and touch listeners receive\n * @example\n * ```ts\n * function onGrab(e: Pointer3DEvent): void {\n *   if (e.hit3D) grabPoint.copyFrom(e.hit3D.point);\n * }\n *\n * handle.on('pointerdown', onGrab);\n * ```\n * @category events\n * @standard\n */\nexport interface Pointer3DEvent extends FederatedPointerEvent, Event3DFields {}\n\n/**\n * A pixi.js `FederatedWheelEvent` with the {@link Event3DFields | 3D fields}\n * @example\n * ```ts\n * function onZoom(e: Wheel3DEvent): void {\n *   if (e.hit3D) zoomToward(e.hit3D.point, e.deltaY);\n * }\n *\n * view3d.on('wheel', onZoom);\n * ```\n * @category events\n * @standard\n */\nexport interface Wheel3DEvent extends FederatedWheelEvent, Event3DFields {}\n\n/**\n * A token no `nativeEvent` equals, not even a synthetic event's `undefined`\n * @internal\n */\nexport const TOKEN_NONE: unknown = {};\n\ninterface Pick3DStorage {\n  /**\n   * The `nativeEvent` that `_writeFields` in `EventBoundary3D.ts` wrote the fields for; pixi reuses\n   * event objects, so the getters read `null` once the event's `nativeEvent` differs\n   */\n  token: unknown;\n  hit: RaycastHit3D;\n  hasHit: boolean;\n  target: Container3D | null;\n  currentTarget: Container3D | null;\n}\n\n/**\n * On first use, defines the getters on the event itself, for an event whose prototype lacks them,\n * such as one from a second copy of pixi.js\n * @internal\n */\nexport function ensurePick3D(event: FederatedMouseEvent): Pick3DStorage {\n  const e = event as FederatedMouseEvent & { _pick3D?: Pick3DStorage };\n  let storage = e._pick3D;\n  if (storage === undefined) {\n    storage = e._pick3D = {\n      token: TOKEN_NONE,\n      hit: createRaycastHit3D(),\n      hasHit: false,\n      target: null,\n      currentTarget: null,\n    };\n    Object.defineProperties(e, PICK3D_ACCESSORS);\n  }\n  return storage;\n}\n\n/**\n * `configurable`, so evaluating this module twice (two copies of the package, or a dev-server\n * reload) redefines the getters instead of throwing\n */\nconst PICK3D_ACCESSORS: PropertyDescriptorMap = {\n  hit3D: {\n    configurable: true,\n    get(this: FederatedMouseEvent): RaycastHit3D | null {\n      const s = ensurePick3D(this);\n      return s.token === this.nativeEvent && s.hasHit ? s.hit : null;\n    },\n  },\n  target3D: {\n    configurable: true,\n    get(this: FederatedMouseEvent): Container3D | null {\n      const s = ensurePick3D(this);\n      return s.token === this.nativeEvent ? s.target : null;\n    },\n  },\n  currentTarget3D: {\n    configurable: true,\n    get(this: FederatedMouseEvent): Container3D | null {\n      const s = ensurePick3D(this);\n      return s.token === this.nativeEvent ? s.currentTarget : null;\n    },\n  },\n};\n\nObject.defineProperties(FederatedMouseEvent.prototype, PICK3D_ACCESSORS);\n\n/**\n * Lets the View's own listeners read `target3D` without a cast; true at runtime, since\n * `PICK3D_ACCESSORS` sit on `FederatedMouseEvent.prototype`\n */\ndeclare module 'pixi.js' {\n  interface FederatedMouseEvent extends Event3DFields {}\n}\n","import { EventSystem, GlobalResourceRegistry, warn } from 'pixi.js';\nimport type {\n  Cursor,\n  EventEmitter,\n  FederatedMouseEvent,\n  FederatedPointerEvent,\n  FederatedWheelEvent,\n  IHitArea,\n  PointData,\n} from 'pixi.js';\n\nimport { Geometry3D } from '../geometry/Geometry3D';\nimport { Matrix4 } from '../math/matrix/Matrix4';\nimport { Box } from '../math/shapes/Box';\nimport { Ray } from '../math/shapes/Ray';\nimport { Sphere } from '../math/shapes/Sphere';\nimport { Vector2 } from '../math/vector/Vector2';\nimport { Vector3 } from '../math/vector/Vector3';\nimport type { Container3D } from '../scene/Container3D';\nimport type { View3D } from '../scene/View3D';\nimport type { HitResult3D, RaycastHit3D } from './HitResult3D';\nimport { copyRaycastHit3D, createHitResult3D, createRaycastHit3D } from './HitResult3D';\nimport { hitVolumeBoundingRadiusSq, intersectRayHitVolume } from './intersectRayHitVolume';\nimport { ensurePick3D, TOKEN_NONE } from './Pointer3DEvent';\n\n/**\n * Each type gets its own listener: pixi fires alias events (`mousedown`, `tap`, …) with `event.type`\n * still the primary name, so only the emitter key says which one arrived\n */\nconst POINTER_EVENT_TYPES = [\n  'pointerdown',\n  'pointerup',\n  'pointermove',\n  'pointerupoutside',\n  'pointerout',\n  'pointerover',\n  'pointertap',\n  'click',\n  'tap',\n  'rightclick',\n  'contextmenu',\n  'mousedown',\n  'mouseup',\n  'mousemove',\n  'mouseupoutside',\n  'rightdown',\n  'rightup',\n  'rightupoutside',\n  'touchstart',\n  'touchmove',\n  'touchend',\n  'touchendoutside',\n] as const;\n\ntype Forwarded3DPointerType = (typeof POINTER_EVENT_TYPES)[number];\n\n/** The repeat-click window 2D's `EventBoundary` hard-codes */\nconst MULTI_CLICK_INTERVAL_MS = 200;\n\n/**\n * Frees a cancelled touch's record on browsers that never reuse a `pointerId`, since pixi sends no\n * `pointercancel`; long enough that a press held still survives\n */\nconst POINTER_RECORD_STALE_MS = 60_000;\n\ntype Chained3DType = Exclude<Forwarded3DPointerType, `${string}outside`> | 'mouseover' | 'mouseout' | 'wheel';\n\n/** Emitter and handler-property keys per `Chained3DType`, built once so dispatch never concatenates strings */\nconst CHAIN_KEYS: Record<Chained3DType, { onKey: string; captureKey: string }> = Object.create(null);\nfor (const type of [...POINTER_EVENT_TYPES, 'mouseover', 'mouseout', 'wheel'] as const) {\n  if (type.endsWith('outside')) continue;\n  CHAIN_KEYS[type as Chained3DType] = { onKey: 'on' + type, captureKey: type + 'capture' };\n}\n\n/**\n * `eventemitter3`'s internal listener shape, read directly as 2D does, since `emit` can't stop between\n * listeners for `stopImmediatePropagation`\n */\ninterface EmitterListener {\n  fn: (event: FederatedMouseEvent) => void;\n  context: unknown;\n  once: boolean;\n}\n\ninterface EmitterInternal {\n  _events: Record<string, EmitterListener | EmitterListener[] | undefined>;\n}\n\ntype WritableTypeEvent = FederatedMouseEvent & { type: string };\n\n/**\n * A port of 2D's `EventBoundary._notifyListeners`, quirk included: a lone listener runs even after\n * `stopImmediatePropagation`\n */\nfunction notifyListeners3D(node: Container3D, key: string, event: FederatedMouseEvent): void {\n  const emitter = node as unknown as EventEmitter;\n  const listeners = (node as unknown as EmitterInternal)._events[key];\n  if (!listeners) return;\n  if ('fn' in listeners) {\n    if (listeners.once) emitter.removeListener(key, listeners.fn, undefined, true);\n    listeners.fn.call(listeners.context, event);\n  } else {\n    for (let i = 0, j = listeners.length; i < j && !event.propagationImmediatelyStopped; i++) {\n      if (listeners[i].once) emitter.removeListener(key, listeners[i].fn, undefined, true);\n      listeners[i].fn.call(listeners[i].context, event);\n    }\n  }\n}\n\n/** Numbers picks for each node's `_clipRayStamp`; shared by every View, so a moved node's stamp can't match */\nlet _clipPickStamp = 0;\n\nconst CAPTURING_PHASE = 1;\nconst AT_TARGET = 2;\nconst BUBBLING_PHASE = 3;\n\nfunction onHandlerOf(\n  node: Container3D,\n  onKey: string,\n): ((this: Container3D, event: FederatedMouseEvent) => void) | null | undefined {\n  return (\n    node as unknown as Record<string, ((this: Container3D, event: FederatedMouseEvent) => void) | null | undefined>\n  )[onKey];\n}\n\nlet _warnedDefaultEventMode = false;\nGlobalResourceRegistry.register({\n  clear: () => {\n    _warnedDefaultEventMode = false;\n  },\n});\n\ninterface Click3DHistory {\n  clickCount: number;\n  target: Container3D | null;\n  timeStamp: number;\n}\n\n/** Kept apart from the pointer records, which a tap's `pointerout` frees before the next tap counts */\ninterface ClickHistory3D {\n  byButton: (Click3DHistory | null)[];\n  lastClickTime: number;\n}\n\n/**\n * Paths are root-first and stored whole, so `findMountedTarget3D` can fall back to the nearest node\n * still mounted after a removal, as 2D's `TrackingData` does\n */\ninterface PointerRecord3D {\n  /** `null` while the button is up; an empty path is a press on empty space */\n  pressPathByButton: (Container3D[] | null)[];\n  /** Count of non-`null` entries in `pressPathByButton` */\n  heldPressCount: number;\n  overPath: Container3D[] | null;\n  lastEventTime: number;\n  /** `null` means the click belongs to the View */\n  clickTarget3D: Container3D | null;\n  clickDetail: number;\n  /** The release's `nativeEvent`, which pixi's click events share with their `pointerup` */\n  clickToken: unknown;\n}\n\nfunction findMountedTarget3D(path: Container3D[]): Container3D | null {\n  if (path.length === 0) return null;\n  let target = path[0];\n  for (let i = 1; i < path.length; i++) {\n    if (path[i].parent !== target) break;\n    target = path[i];\n  }\n  return target;\n}\n\n/**\n * Pointer events for one {@link View3D}, the 3D counterpart of pixi.js's `EventBoundary`\n *\n * Each View makes one, at `view3d.events`. It sends each pointer event the View gets on to the 3D\n * node under the pointer and its ancestors, with capture, target and bubble phases as in 2D.\n *\n * You rarely need it directly: set {@link IFederatedContainer3D#eventMode | eventMode} on nodes\n * and listen on them. It holds the settings that apply to the whole View.\n * @example\n * ```ts\n * // Events on a 3D node work as they do in 2D.\n * mesh.eventMode = 'static';\n * mesh.cursor = 'pointer';\n * mesh.on('pointertap', (e) => console.log(e.hit3D?.point)); // world-space hit point\n *\n * // The boundary itself is only needed for View-wide settings.\n * view3d.events.enableGlobalMoveEvents = false;\n * ```\n * @see {@link View3D#raycast} For a one-off pick outside the pointer pipeline.\n * @see {@link Event3DFields} For the 3D data carried on the dispatched events.\n * @category events\n * @advanced\n */\nexport class EventBoundary3D {\n  private readonly _view: View3D;\n\n  /**\n   * Every node a pick tests, in no order; each node's `_pickIndex` is its slot\n   * @internal\n   */\n  public _interactiveList: Container3D[] = [];\n\n  /**\n   * Whether interactive 3D nodes hear `globalpointermove` on every pointer move on the page\n   *\n   * The usual tool for a drag that keeps tracking after the pointer leaves the object;\n   * `globalmousemove` and `globaltouchmove` come with it. It also needs the renderer's\n   * `eventFeatures.globalMove` option on, as 2D's global moves do.\n   * @remarks\n   * - Each interactive, visible node hears each move once, in no particular order.\n   * - It costs a little time per node that takes part in picking on every move; turn it off in\n   *   crowded scenes that don't use it.\n   * @default true\n   */\n  public enableGlobalMoveEvents = true;\n\n  private _dynamicPickCount = 0;\n\n  /**\n   * Attached nodes whose `_hitVolumeInput` isn't `null`; picks skip clipping while it is 0\n   * @internal\n   */\n  public _clipVolumeCount = 0;\n\n  /**\n   * Target of pixi's last hit test on the View; one slot is enough, since pixi hit-tests right before\n   * each dispatch and cursor read\n   * @internal\n   */\n  public _currentPick3D: Container3D | null = null;\n\n  /** @internal */\n  public _hitAreaShape: IHitArea | null = null;\n\n  /**\n   * Runs the pick from `hitArea.contains`, because pixi's `hitTestFn` never calls `containsPoint` on a\n   * container with a `hitArea`\n   * @internal\n   */\n  public readonly _hitAreaProxy: IHitArea = {\n    contains: (x, y) => {\n      const shape = this._hitAreaShape;\n      if (shape !== null && !shape.contains(x, y)) {\n        this._currentPick3D = null;\n        return false;\n      }\n      return this._containsPoint(x, y);\n    },\n  };\n\n  private readonly _pointerRecords = new Map<number, PointerRecord3D>();\n\n  /** With `_pathPool`, reused so steady pointer traffic allocates nothing */\n  private readonly _recordPool: PointerRecord3D[] = [];\n\n  private readonly _pathPool: Container3D[][] = [];\n\n  private readonly _clickHistories = new Map<number, ClickHistory3D>();\n\n  private readonly _clickHistoryPool: ClickHistory3D[] = [];\n\n  /** This View's own note of the last move's pick, since every View3D writes the same event's 3D fields */\n  private _movePickToken: unknown = TOKEN_NONE;\n  private _movePick3D: Container3D | null = null;\n\n  private _cursorFallback: Cursor | (string & {}) | undefined;\n\n  /** The hit behind `_currentPick3D`; `_raycast` never writes it, so a listener's call can't change `hit3D` */\n  private readonly _lastHit: RaycastHit3D = createRaycastHit3D();\n\n  /** Handed to the caller on a hit and replaced, so a miss allocates nothing and it never holds a node */\n  private _raycastHit: RaycastHit3D = createRaycastHit3D();\n\n  private readonly _scratchWorldRay = new Ray();\n  private readonly _scratchGlobal = new Vector2();\n  private readonly _scratchLocalRay = new Ray();\n  private readonly _scratchNormalMatrix = new Matrix4();\n  private readonly _scratchWorldPoint = new Vector3();\n  private readonly _scratchCenter = new Vector3();\n  private readonly _scratchHit: HitResult3D = createHitResult3D();\n  /** Apart from the pick loop's scratch, which holds live values while the clip tests run */\n  private readonly _scratchClipRay = new Ray();\n  private readonly _scratchClipPoint = new Vector3();\n\n  /**\n   * Each {@link View3D} makes its own, before you can add listeners, so the View's plain\n   * `view3d.on(type, …)` listeners see the 3D fields; {@link Event3DFields} covers the rest\n   * @param view - The View this boundary serves.\n   */\n  constructor(view: View3D) {\n    this._view = view;\n\n    view.eventMode = 'static';\n\n    for (const type of POINTER_EVENT_TYPES) {\n      view.on(type, (event: FederatedPointerEvent) => this._dispatch3DEvent(type, event));\n    }\n    view.on('wheel', (event: FederatedWheelEvent) => this._forwardToPick(event, 'wheel', this._currentPick3D));\n    view.on('globalpointermove', (event: FederatedPointerEvent) => this._dispatchGlobalMove(event));\n  }\n\n  /**\n   * Resets `_pickIndex` on nodes still listed, such as the root, which `View3D.destroy` never\n   * detaches; the View's own destroy removes the listeners the constructor adds\n   * @internal\n   */\n  public destroy(): void {\n    for (const [id, record] of this._pointerRecords) this._freePointerRecord(id, record);\n    (this._clickHistories as Map<number, ClickHistory3D> | null) = null;\n    (this._clickHistoryPool as ClickHistory3D[] | null) = null;\n    (this._recordPool as PointerRecord3D[] | null) = null;\n    (this._pathPool as Container3D[][] | null) = null;\n    const list = this._interactiveList;\n    for (let i = 0; i < list.length; i++) list[i]._pickIndex = -1;\n    list.length = 0;\n    this._currentPick3D = null;\n    this._hitAreaShape = null;\n    this._movePick3D = null;\n    this._movePickToken = TOKEN_NONE;\n    this._clipVolumeCount = 0;\n  }\n\n  /** @internal */\n  public get _cursor(): Cursor | (string & {}) | undefined {\n    return this._currentPick3D?.cursor ?? this._cursorFallback;\n  }\n\n  /** @internal */\n  public set _cursor(value: Cursor | (string & {}) | undefined) {\n    this._cursorFallback = value;\n  }\n\n  /**\n   * Picks with the last render's transforms, so users pick what they see; checks the renderer\n   * default here, not in the constructor, because the renderer usually comes after the scene\n   * @internal\n   */\n  public _containsPoint(x: number, y: number): boolean {\n    if (!_warnedDefaultEventMode && EventSystem.defaultEventMode !== undefined) {\n      _warnedDefaultEventMode = true;\n      if (EventSystem.defaultEventMode !== 'passive') {\n        warn(\n          `The renderer eventMode default ('${EventSystem.defaultEventMode}') applies only to 2D containers; ` +\n            \"3D nodes default to 'passive'. Set eventMode per node or group.\",\n        );\n      }\n    }\n\n    if (!this._inViewRect(x, y)) {\n      this._currentPick3D = null;\n      return false;\n    }\n\n    const view = this._view;\n    view.worldTransform.apply(this._scratchGlobal.set(x, y), this._scratchGlobal);\n    view.screenToRay(this._scratchGlobal, this._scratchWorldRay, true);\n\n    this._currentPick3D = this._pickWithWorldRay(this._scratchWorldRay, this._lastHit) ? this._lastHit.target : null;\n    return true;\n  }\n\n  /** Must match the rect `View3D.updateBounds` gives the View */\n  private _inViewRect(x: number, y: number): boolean {\n    const view = this._view;\n    const width = view.width;\n    const height = view.height;\n    const nx = (x + view.anchor.x * width) / width;\n    const ny = (y + view.anchor.y * height) / height;\n    return nx >= 0 && nx <= 1 && ny >= 0 && ny <= 1;\n  }\n\n  /** @internal */\n  public _raycast(position: PointData, out?: RaycastHit3D): RaycastHit3D | null {\n    const view = this._view;\n    const local = view.worldTransform.applyInverse(position, this._scratchGlobal);\n    if (!this._inViewRect(local.x, local.y)) return null;\n\n    view.screenToRay(position, this._scratchWorldRay, true);\n    const hit = out ?? this._raycastHit;\n    if (!this._pickWithWorldRay(this._scratchWorldRay, hit)) return null;\n    if (!out) this._raycastHit = createRaycastHit3D();\n    return hit;\n  }\n\n  /**\n   * Does nothing for a node already listed, so callers needn't check\n   * @internal\n   */\n  public _addInteractive(node: Container3D): void {\n    if (node._pickIndex !== -1) return;\n    node._pickIndex = this._interactiveList.push(node) - 1;\n    if (node._eventMode === 'dynamic') this._changeDynamicCount(1);\n  }\n\n  /**\n   * Does nothing for a node not listed\n   * @param node - Node to remove.\n   * @param wasDynamic - Pass it when the node's mode has changed since it was added.\n   * @internal\n   */\n  public _removeInteractive(node: Container3D, wasDynamic: boolean = node._eventMode === 'dynamic'): void {\n    const idx = node._pickIndex;\n    if (idx === -1) return;\n    const list = this._interactiveList;\n    const last = list.pop()!;\n    if (last !== node) {\n      list[idx] = last;\n      last._pickIndex = idx;\n    }\n    node._pickIndex = -1;\n    this._clearPickState(node);\n    if (wasDynamic) this._changeDynamicCount(-1);\n  }\n\n  /**\n   * Makes the View `'dynamic'` while any listed node is, so pixi's ticker picks again under a still\n   * pointer; a `'none'` or `'passive'` set on the View stays\n   * @internal\n   */\n  public _changeDynamicCount(delta: number): void {\n    this._dynamicPickCount += delta;\n    const want = this._dynamicPickCount > 0 ? 'dynamic' : 'static';\n    const cur = this._view.eventMode;\n    if ((cur === 'static' || cur === 'dynamic') && cur !== want) {\n      this._view.eventMode = want;\n    }\n  }\n\n  /** @internal */\n  public _clearPickState(node: Container3D): void {\n    if (this._currentPick3D === node) this._currentPick3D = null;\n    if (this._movePick3D === node) this._movePick3D = null;\n  }\n\n  /**\n   * Compares hits by world distance, since each node's local `t` is in its own units; the ancestor\n   * walk runs last, only for a hit that beats the best so far\n   */\n  private _pickWithWorldRay(worldRay: Ray, out: RaycastHit3D): boolean {\n    const list = this._interactiveList;\n    const ox = worldRay.origin.x;\n    const oy = worldRay.origin.y;\n    const oz = worldRay.origin.z;\n    const clipStamp = this._clipVolumeCount > 0 ? ++_clipPickStamp : 0;\n\n    let bestDistance = Infinity;\n    let bestNode: Container3D | null = null;\n    let bestSurfaceNode: Container3D | null = null;\n    let bestHasSurface = false;\n\n    for (let i = 0; i < list.length; i++) {\n      const node = list[i];\n      const volume = node._hitVolumeResolved ?? node._getDefaultHitVolume();\n      if (!volume) continue;\n      if (node._worldVisible === 0) continue;\n\n      const wt = node.worldTransform.elements;\n      this._scratchCenter.set(wt[12], wt[13], wt[14]);\n      const radiusSq = hitVolumeBoundingRadiusSq(volume) * node._getWorldScaleSq();\n      if (worldRay.distanceSqToPoint(this._scratchCenter) > radiusSq) continue;\n\n      if (clipStamp !== 0 && !this._passesClipPrefilter(node, worldRay, clipStamp)) continue;\n\n      const localPerWorld = this._toLocalRay(worldRay, node._getInverseWorldTransform());\n      const t = intersectRayHitVolume(this._scratchLocalRay, volume, this._scratchHit, bestDistance * localPerWorld);\n      if (t < 0) continue;\n\n      this._scratchHit.point.applyAffineMatrix4(node.worldTransform, this._scratchWorldPoint);\n      const dx = this._scratchWorldPoint.x - ox;\n      const dy = this._scratchWorldPoint.y - oy;\n      const dz = this._scratchWorldPoint.z - oz;\n      const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);\n      if (distance >= bestDistance) continue;\n\n      const target = this._resolvePickTarget(node, this._scratchWorldPoint);\n      if (!target) continue;\n\n      bestDistance = distance;\n      bestNode = target;\n      bestSurfaceNode = node;\n      bestHasSurface = this._scratchHit.triangleIndex !== -1;\n\n      out.point.copyFrom(this._scratchWorldPoint);\n      out.localPoint.copyFrom(this._scratchHit.point);\n      out.normal.copyFrom(this._scratchHit.normal);\n      out.uv.copyFrom(this._scratchHit.uv);\n      out.triangleIndex = this._scratchHit.triangleIndex;\n    }\n\n    if (!bestNode) return false;\n\n    if (bestHasSurface) {\n      bestSurfaceNode!._getInverseWorldTransform().transpose(this._scratchNormalMatrix);\n      out.normal.transformDirection(this._scratchNormalMatrix);\n    } else {\n      out.normal.set(0, 0, 0);\n    }\n    out.target = bestNode;\n    out.distance = bestDistance;\n    return true;\n  }\n\n  /** As `Ray#applyMatrix4` into `_scratchLocalRay`, returning the local length of one world unit along the ray */\n  private _toLocalRay(worldRay: Ray, inverse: Matrix4): number {\n    const local = this._scratchLocalRay;\n    worldRay.origin.applyAffineMatrix4(inverse, local.origin);\n    const d = worldRay.direction;\n    const e = inverse.elements;\n    const x = e[0] * d.x + e[4] * d.y + e[8] * d.z;\n    const y = e[1] * d.x + e[5] * d.y + e[9] * d.z;\n    const z = e[2] * d.x + e[6] * d.y + e[10] * d.z;\n    const length = Math.sqrt(x * x + y * y + z * z) || 1;\n    const scale = 1 / length;\n    local.direction.x = x * scale;\n    local.direction.y = y * scale;\n    local.direction.z = z * scale;\n    return length;\n  }\n\n  /**\n   * Repeats `getAncestorPickState`'s barrier rule, so a pick-list bug costs time rather than a wrong\n   * target, and clips against ancestors' volumes when given `worldPoint`\n   */\n  private _resolvePickTarget(node: Container3D, worldPoint: Vector3 | null = null): Container3D | null {\n    const clip = worldPoint !== null && this._clipVolumeCount > 0;\n    let target = node.isInteractive() ? node : null;\n    let cur = node.parent;\n    while (cur) {\n      if (!cur._interactiveChildren || cur._eventMode === 'none') return null;\n      if (clip && cur._hitVolumeInput !== null && !this._clipContains(cur, worldPoint)) return null;\n      if (target === null && cur.isInteractive()) target = cur;\n      cur = cur.parent;\n    }\n    return target;\n  }\n\n  /**\n   * Must treat each shape as `_clipContains` does; an `IHitVolume3D` passes, since its `raycast` can\n   * miss from inside it\n   */\n  private _passesClipPrefilter(node: Container3D, worldRay: Ray, clipStamp: number): boolean {\n    let cur = node.parent;\n    while (cur) {\n      const volume = cur._hitVolumeInput !== null ? cur._hitVolumeResolved : null;\n      if (volume !== null) {\n        if (cur._clipRayStamp !== clipStamp) {\n          cur._clipRayStamp = clipStamp;\n          const localRay = worldRay.applyMatrix4(cur._getInverseWorldTransform(), this._scratchClipRay);\n          if (volume instanceof Box) {\n            cur._clipRayHit = localRay.intersectBoxT(volume) !== -1;\n          } else if (volume instanceof Sphere) {\n            cur._clipRayHit = localRay.intersectSphereT(volume) !== -1;\n          } else if (volume instanceof Geometry3D) {\n            cur._clipRayHit = localRay.intersectBoxT(volume.bounds3D) !== -1;\n          } else {\n            cur._clipRayHit = true;\n          }\n        }\n        if (!cur._clipRayHit) return false;\n      }\n      cur = cur.parent;\n    }\n    return true;\n  }\n\n  /** Must treat each shape as `_passesClipPrefilter` does */\n  private _clipContains(ancestor: Container3D, worldPoint: Vector3): boolean {\n    const volume = ancestor._hitVolumeResolved;\n    if (volume === null) return true;\n    const local = worldPoint.applyAffineMatrix4(ancestor._getInverseWorldTransform(), this._scratchClipPoint);\n    if (volume instanceof Box) return volume.containsPoint(local);\n    if (volume instanceof Sphere) return volume.containsPoint(local);\n    if (volume instanceof Geometry3D) return volume.bounds3D.containsPoint(local);\n    return volume.containsPoint === undefined || volume.containsPoint(local);\n  }\n\n  /**\n   * `mouseupoutside`, `rightupoutside` and `touchendoutside` do nothing here: `_emitUpOutsideWalk`\n   * already sent them, node by node\n   * @param type - Emitter key, which for an alias differs from `event.type`.\n   * @param event - The event.\n   */\n  private _dispatch3DEvent(type: Forwarded3DPointerType, event: FederatedPointerEvent): void {\n    switch (type) {\n      case 'pointerout': {\n        const record = this._pointerRecords.get(event.pointerId);\n        let stopped = false;\n        if (record) {\n          record.lastEventTime = event.timeStamp;\n          const prev = record.overPath ? findMountedTarget3D(record.overPath) : null;\n          if (record.overPath) {\n            this._releasePath(record.overPath);\n            record.overPath = null;\n          }\n          this._writeFields(event, prev, null);\n          if (prev) {\n            const isMouse = event.pointerType === 'mouse' || event.pointerType === 'pen';\n            stopped = this._emit3DChain(event, 'pointerout', prev);\n            if (isMouse) this._emit3DChain(event, 'mouseout', prev);\n            this._emitEnterLeaveWalk(event, prev, null, false, isMouse);\n          }\n          if (record.heldPressCount === 0) this._freePointerRecord(event.pointerId, record);\n        } else {\n          this._writeFields(event, null, null);\n        }\n        this._currentPick3D = null;\n        if (stopped) this._stopViewPropagation(event);\n        return;\n      }\n\n      case 'pointerover': {\n        const pick = this._currentPick3D;\n        if (!pick) {\n          this._writeFields(event, null, null);\n          return;\n        }\n        const record = this._getPointerRecord(event.pointerId, event.timeStamp);\n        const isMouse = event.pointerType === 'mouse' || event.pointerType === 'pen';\n        this._writeFields(event, pick, pick);\n        const stopped = this._emit3DChain(event, 'pointerover', pick);\n        if (isMouse) this._emit3DChain(event, 'mouseover', pick);\n        this._emitEnterLeaveWalk(event, pick, null, true, isMouse);\n        if (record.overPath) this._releasePath(record.overPath);\n        record.overPath = this._capturePath(pick);\n        if (stopped) this._stopViewPropagation(event);\n        return;\n      }\n\n      case 'pointerdown': {\n        const pick = this._currentPick3D;\n        const record = this._getPointerRecord(event.pointerId, event.timeStamp);\n        const button = event.button ?? 0;\n        const prevPath = record.pressPathByButton[button];\n        if (prevPath) this._releasePath(prevPath);\n        else record.heldPressCount++;\n        record.pressPathByButton[button] = pick ? this._capturePath(pick) : this._acquirePath();\n        record.clickToken = TOKEN_NONE;\n        this._forwardToPick(event, type, pick);\n        return;\n      }\n\n      case 'pointermove': {\n        const pick = this._currentPick3D;\n        this._movePickToken = event.nativeEvent;\n        this._movePick3D = pick;\n        let record = this._pointerRecords.get(event.pointerId);\n        if (!record && pick) record = this._getPointerRecord(event.pointerId, event.timeStamp);\n        if (record) {\n          record.lastEventTime = event.timeStamp;\n          const prev = record.overPath ? findMountedTarget3D(record.overPath) : null;\n          if (prev !== pick) {\n            const isMouse = event.pointerType === 'mouse' || event.pointerType === 'pen';\n            if (prev) {\n              this._writeFields(event, prev, pick);\n              this._emit3DChain(event, 'pointerout', prev);\n              if (isMouse) this._emit3DChain(event, 'mouseout', prev);\n              if (!this._isInChain(prev, pick)) this._emitEnterLeaveWalk(event, prev, pick, false, isMouse);\n            }\n            if (pick) {\n              this._writeFields(event, pick, pick);\n              this._emit3DChain(event, 'pointerover', pick);\n              if (isMouse) this._emit3DChain(event, 'mouseover', pick);\n              if (!prev || !this._isInChain(pick, prev)) this._emitEnterLeaveWalk(event, pick, prev, true, isMouse);\n            }\n            if (record.overPath) this._releasePath(record.overPath);\n            record.overPath = pick ? this._capturePath(pick) : null;\n          }\n        }\n        this._forwardToPick(event, type, pick);\n        return;\n      }\n\n      case 'pointerup': {\n        const pick = this._currentPick3D;\n        const releasePath = pick ? this._capturePath(pick) : null;\n        let stopped = false;\n        this._writeFields(event, pick, pick);\n        if (pick) stopped = this._emit3DChain(event, type, pick, releasePath);\n        this._reconcileRelease(event, releasePath, true);\n        if (releasePath) this._releasePath(releasePath);\n        if (stopped) this._stopViewPropagation(event);\n        return;\n      }\n\n      case 'pointerupoutside':\n        this._writeFields(event, null, null);\n        this._reconcileRelease(event, null, false);\n        return;\n\n      case 'mouseupoutside':\n      case 'rightupoutside':\n      case 'touchendoutside':\n        return;\n\n      case 'click':\n      case 'rightclick':\n      case 'tap':\n      case 'pointertap': {\n        const record = this._pointerRecords.get(event.pointerId);\n        if (record && record.clickToken === event.nativeEvent) {\n          const target = record.clickTarget3D;\n          this._writeFields(event, target, this._currentPick3D);\n          if (!target) {\n            return;\n          }\n          const originalDetail = event.detail;\n          event.detail = record.clickDetail;\n          let stopped: boolean;\n          try {\n            stopped = this._emit3DChain(event, type, target);\n          } finally {\n            event.detail = originalDetail;\n          }\n          if (stopped) this._stopViewPropagation(event);\n          return;\n        }\n        this._forwardToPick(event, type, this._currentPick3D);\n        return;\n      }\n\n      case 'mousedown':\n      case 'rightdown':\n      case 'touchstart':\n      case 'mousemove':\n      case 'touchmove':\n      case 'mouseup':\n      case 'rightup':\n      case 'touchend':\n        this._forwardToPick(event, type, this._currentPick3D);\n        return;\n\n      case 'contextmenu':\n        this._forwardToPick(event, type, this._currentPick3D);\n        return;\n    }\n  }\n\n  /** Writes the 3D fields even on a miss, so the View's listeners never read ones an earlier dispatch left */\n  private _forwardToPick(event: FederatedMouseEvent, type: Chained3DType, pick: Container3D | null): void {\n    this._writeFields(event, pick, pick);\n    if (pick && this._emit3DChain(event, type, pick)) this._stopViewPropagation(event);\n  }\n\n  /**\n   * Tests against the release chain captured before `pointerup` ran, as 2D tests its cached\n   * `composedPath()`, so a listener that moves nodes can't change the outcome\n   */\n  private _reconcileRelease(\n    event: FederatedPointerEvent,\n    releasePath: Container3D[] | null,\n    insideView: boolean,\n  ): void {\n    const record = this._pointerRecords.get(event.pointerId);\n    if (record) record.lastEventTime = event.timeStamp;\n    const button = event.button ?? 0;\n    const pressPath = record ? record.pressPathByButton[button] : null;\n    if (!record || !pressPath) return;\n\n    const pressTarget = findMountedTarget3D(pressPath);\n    record.pressPathByButton[button] = null;\n    record.heldPressCount--;\n    this._releasePath(pressPath);\n\n    let clickTarget = pressTarget;\n    if (pressTarget && (releasePath === null || !releasePath.includes(pressTarget))) {\n      clickTarget = this._emitUpOutsideWalk(event, pressTarget, releasePath);\n    }\n\n    if (insideView) {\n      record.clickTarget3D = clickTarget;\n      record.clickDetail = clickTarget ? this._countClick(event.pointerId, button, clickTarget) : 0;\n      record.clickToken = event.nativeEvent;\n    } else if (record.heldPressCount === 0) {\n      this._freePointerRecord(event.pointerId, record);\n    }\n  }\n\n  /**\n   * Matches 2D's upoutside walk: interactive nodes only, no capture pass, and no stop between nodes\n   * @returns The first ancestor on the release chain, the click target, or `null` for the View.\n   */\n  private _emitUpOutsideWalk(\n    event: FederatedPointerEvent,\n    pressTarget: Container3D,\n    releasePath: Container3D[] | null,\n  ): Container3D | null {\n    const pointerType = event.pointerType;\n    let aliasType: string | null = null;\n    let aliasOnKey = '';\n    if (pointerType === 'touch') {\n      aliasType = 'touchendoutside';\n      aliasOnKey = 'ontouchendoutside';\n    } else if (pointerType === 'mouse' || pointerType === 'pen') {\n      aliasType = event.button === 2 ? 'rightupoutside' : 'mouseupoutside';\n      aliasOnKey = event.button === 2 ? 'onrightupoutside' : 'onmouseupoutside';\n    }\n\n    const storage = ensurePick3D(event);\n    const e = event as WritableTypeEvent;\n    const originalType = e.type;\n    const originalTarget = event.target;\n    const originalCurrent = event.currentTarget;\n    const originalTarget3D = storage.target;\n    const originalCurrent3D = storage.currentTarget;\n    const originalPath = event.path;\n    const originalPhase = event.eventPhase;\n    const originalStopped = event.propagationStopped;\n    const originalImmediate = event.propagationImmediatelyStopped;\n    event.propagationStopped = false;\n    event.propagationImmediatelyStopped = false;\n    event.eventPhase = BUBBLING_PHASE;\n    event.target = pressTarget as unknown as FederatedPointerEvent['target'];\n    storage.target = pressTarget;\n\n    let cur: Container3D | null = pressTarget;\n    try {\n      while (cur && (releasePath === null || !releasePath.includes(cur))) {\n        if (cur.isInteractive()) {\n          event.currentTarget = cur as unknown as FederatedPointerEvent['currentTarget'];\n          storage.currentTarget = cur;\n          e.type = 'pointerupoutside';\n          onHandlerOf(cur, 'onpointerupoutside')?.call(cur, event);\n          notifyListeners3D(cur, 'pointerupoutside', event);\n          if (aliasType) {\n            e.type = aliasType;\n            onHandlerOf(cur, aliasOnKey)?.call(cur, event);\n            notifyListeners3D(cur, aliasType, event);\n          }\n        }\n        cur = cur.parent;\n      }\n    } finally {\n      e.type = originalType;\n      event.target = originalTarget;\n      event.currentTarget = originalCurrent;\n      storage.target = originalTarget3D;\n      storage.currentTarget = originalCurrent3D;\n      event.path = originalPath;\n      event.eventPhase = originalPhase;\n      event.propagationStopped = originalStopped;\n      event.propagationImmediatelyStopped = originalImmediate;\n    }\n    return cur;\n  }\n\n  private _isInChain(node: Container3D, chainTail: Container3D | null): boolean {\n    let cur = chainTail;\n    while (cur) {\n      if (cur === node) return true;\n      cur = cur.parent;\n    }\n    return false;\n  }\n\n  private _countClick(pointerId: number, button: number, target: Container3D): number {\n    const now = performance.now();\n    let entry = this._clickHistories.get(pointerId);\n    if (!entry) {\n      this._sweepClickHistories(now);\n      entry = this._clickHistoryPool.pop() ?? { byButton: [], lastClickTime: 0 };\n      this._clickHistories.set(pointerId, entry);\n    }\n    entry.lastClickTime = now;\n    let history = entry.byButton[button];\n    if (!history) {\n      history = entry.byButton[button] = { clickCount: 0, target: null, timeStamp: 0 };\n    }\n    if (history.target === target && now - history.timeStamp < MULTI_CLICK_INTERVAL_MS) {\n      history.clickCount++;\n    } else {\n      history.clickCount = 1;\n    }\n    history.target = target;\n    history.timeStamp = now;\n    return history.clickCount;\n  }\n\n  private _sweepClickHistories(now: number): void {\n    for (const [id, entry] of this._clickHistories) {\n      if (now - entry.lastClickTime >= MULTI_CLICK_INTERVAL_MS) {\n        const byButton = entry.byButton;\n        for (let i = 0; i < byButton.length; i++) {\n          const history = byButton[i];\n          if (history) {\n            history.clickCount = 0;\n            history.target = null;\n            history.timeStamp = 0;\n          }\n        }\n        this._clickHistoryPool.push(entry);\n        this._clickHistories.delete(id);\n      }\n    }\n  }\n\n  /**\n   * Sets `propagationImmediatelyStopped` too: the View's own listeners share a list with this\n   * dispatcher, and pixi only checks `propagationStopped` between targets\n   */\n  private _stopViewPropagation(event: FederatedMouseEvent): void {\n    event.propagationStopped = true;\n    event.propagationImmediatelyStopped = true;\n  }\n\n  private _getPointerRecord(pointerId: number, now: number): PointerRecord3D {\n    let record = this._pointerRecords.get(pointerId);\n    if (!record) {\n      this._sweepStaleRecords(now);\n      record = this._recordPool.pop() ?? {\n        pressPathByButton: [],\n        heldPressCount: 0,\n        overPath: null,\n        lastEventTime: 0,\n        clickTarget3D: null,\n        clickDetail: 0,\n        clickToken: TOKEN_NONE,\n      };\n      this._pointerRecords.set(pointerId, record);\n    }\n    record.lastEventTime = now;\n    return record;\n  }\n\n  private _sweepStaleRecords(now: number): void {\n    for (const [id, record] of this._pointerRecords) {\n      if (now - record.lastEventTime >= POINTER_RECORD_STALE_MS) this._freePointerRecord(id, record);\n    }\n  }\n\n  private _freePointerRecord(pointerId: number, record: PointerRecord3D): void {\n    this._pointerRecords.delete(pointerId);\n    const paths = record.pressPathByButton;\n    for (let i = 0; i < paths.length; i++) {\n      const path = paths[i];\n      if (path) {\n        this._releasePath(path);\n        paths[i] = null;\n      }\n    }\n    record.heldPressCount = 0;\n    if (record.overPath) {\n      this._releasePath(record.overPath);\n      record.overPath = null;\n    }\n    record.clickTarget3D = null;\n    record.clickDetail = 0;\n    record.clickToken = TOKEN_NONE;\n    this._recordPool.push(record);\n  }\n\n  private _acquirePath(): Container3D[] {\n    return this._pathPool.pop() ?? [];\n  }\n\n  private _releasePath(path: Container3D[]): void {\n    path.length = 0;\n    this._pathPool.push(path);\n  }\n\n  private _capturePath(node: Container3D): Container3D[] {\n    const path = this._acquirePath();\n    let cur: Container3D | null = node;\n    while (cur) {\n      path.push(cur);\n      cur = cur.parent;\n    }\n    path.reverse();\n    return path;\n  }\n\n  /** The token is `event.nativeEvent`, which the `Event3DFields` getters in `Pointer3DEvent.ts` check */\n  private _writeFields(event: FederatedMouseEvent, target: Container3D | null, pick: Container3D | null): void {\n    const s = ensurePick3D(event);\n    if (pick !== null) copyRaycastHit3D(this._lastHit, s.hit);\n    s.hasHit = pick !== null;\n    s.target = target;\n    s.token = event.nativeEvent;\n  }\n\n  /**\n   * Mirrors 2D's `propagate` with `event.path` set to the frozen chain, so `composedPath()` neither\n   * allocates nor sees moves; restores the event's dispatch state after, for pixi's own dispatch\n   * @param event - The event.\n   * @param type - Emitter key.\n   * @param from - The dispatch target.\n   * @param frozenPath - A chain the caller captured and frees itself.\n   * @returns Whether a listener stopped the chain.\n   */\n  private _emit3DChain(\n    event: FederatedMouseEvent,\n    type: Chained3DType,\n    from: Container3D,\n    frozenPath?: Container3D[] | null,\n  ): boolean {\n    const storage = ensurePick3D(event);\n    const e = event as WritableTypeEvent;\n    const originalType = e.type;\n    const originalTarget = event.target;\n    const originalCurrent = event.currentTarget;\n    const originalCurrent3D = storage.currentTarget;\n    const originalPath = event.path;\n    const originalPhase = event.eventPhase;\n    const originalStopped = event.propagationStopped;\n    const originalImmediate = event.propagationImmediatelyStopped;\n\n    event.propagationStopped = false;\n    event.propagationImmediatelyStopped = false;\n    e.type = type;\n    event.target = from as unknown as FederatedMouseEvent['target'];\n\n    const { onKey, captureKey } = CHAIN_KEYS[type];\n    const ownsPath = frozenPath === undefined || frozenPath === null;\n    const path = frozenPath ?? this._capturePath(from);\n    event.path = path as unknown as FederatedMouseEvent['path'];\n    let stopped = false;\n\n    try {\n      event.eventPhase = CAPTURING_PHASE;\n      for (let i = 0, last = path.length - 1; i < last; i++) {\n        const cur = path[i];\n        if (!cur.isInteractive()) continue;\n        event.currentTarget = cur as unknown as FederatedMouseEvent['currentTarget'];\n        storage.currentTarget = cur;\n        onHandlerOf(cur, onKey)?.call(cur, event);\n        notifyListeners3D(cur, captureKey, event);\n        if (event.propagationStopped || event.propagationImmediatelyStopped) {\n          stopped = true;\n          break;\n        }\n      }\n\n      if (!stopped && from.isInteractive()) {\n        event.eventPhase = AT_TARGET;\n        event.currentTarget = from as unknown as FederatedMouseEvent['currentTarget'];\n        storage.currentTarget = from;\n        onHandlerOf(from, onKey)?.call(from, event);\n        notifyListeners3D(from, captureKey, event);\n        notifyListeners3D(from, type, event);\n        if (event.propagationStopped || event.propagationImmediatelyStopped) stopped = true;\n      }\n\n      if (!stopped) {\n        event.eventPhase = BUBBLING_PHASE;\n        for (let i = path.length - 2; i >= 0; i--) {\n          const cur = path[i];\n          if (!cur.isInteractive()) continue;\n          event.currentTarget = cur as unknown as FederatedMouseEvent['currentTarget'];\n          storage.currentTarget = cur;\n          onHandlerOf(cur, onKey)?.call(cur, event);\n          notifyListeners3D(cur, type, event);\n          if (event.propagationStopped || event.propagationImmediatelyStopped) {\n            stopped = true;\n            break;\n          }\n        }\n      }\n    } finally {\n      if (ownsPath) this._releasePath(path);\n      e.type = originalType;\n      event.target = originalTarget;\n      event.currentTarget = originalCurrent;\n      storage.currentTarget = originalCurrent3D;\n      event.path = originalPath;\n      event.eventPhase = originalPhase;\n      event.propagationStopped = originalStopped;\n      event.propagationImmediatelyStopped = originalImmediate;\n    }\n    return stopped;\n  }\n\n  /** Mirrors 2D's enter and leave walks: each interactive node is told as its own target, `*capture` listeners included */\n  private _emitEnterLeaveWalk(\n    event: FederatedMouseEvent,\n    from: Container3D,\n    boundary: Container3D | null,\n    enter: boolean,\n    isMouse: boolean,\n  ): void {\n    const type = enter ? 'pointerenter' : 'pointerleave';\n    const captureKey = enter ? 'pointerentercapture' : 'pointerleavecapture';\n    const onKey = enter ? 'onpointerenter' : 'onpointerleave';\n    const aliasType = enter ? 'mouseenter' : 'mouseleave';\n    const aliasCaptureKey = enter ? 'mouseentercapture' : 'mouseleavecapture';\n    const aliasOnKey = enter ? 'onmouseenter' : 'onmouseleave';\n\n    const storage = ensurePick3D(event);\n    const e = event as WritableTypeEvent;\n    const originalType = e.type;\n    const originalTarget = event.target;\n    const originalCurrent = event.currentTarget;\n    const originalPath = event.path;\n    const originalPhase = event.eventPhase;\n    const originalStopped = event.propagationStopped;\n    const originalImmediate = event.propagationImmediatelyStopped;\n    const originalTarget3D = storage.target;\n    const originalCurrent3D = storage.currentTarget;\n\n    event.propagationStopped = false;\n    event.propagationImmediatelyStopped = false;\n    event.eventPhase = AT_TARGET;\n\n    let cur: Container3D | null = from;\n    try {\n      while (cur && (enter ? cur !== boundary : !this._isInChain(cur, boundary))) {\n        if (cur.isInteractive()) {\n          storage.target = cur;\n          storage.currentTarget = cur;\n          event.target = cur as unknown as FederatedMouseEvent['target'];\n          event.currentTarget = cur as unknown as FederatedMouseEvent['currentTarget'];\n          e.type = type;\n          onHandlerOf(cur, onKey)?.call(cur, event);\n          notifyListeners3D(cur, captureKey, event);\n          notifyListeners3D(cur, type, event);\n          if (isMouse) {\n            e.type = aliasType;\n            onHandlerOf(cur, aliasOnKey)?.call(cur, event);\n            notifyListeners3D(cur, aliasCaptureKey, event);\n            notifyListeners3D(cur, aliasType, event);\n          }\n        }\n        cur = cur.parent;\n      }\n    } finally {\n      storage.target = originalTarget3D;\n      storage.currentTarget = originalCurrent3D;\n      e.type = originalType;\n      event.target = originalTarget;\n      event.currentTarget = originalCurrent;\n      event.path = originalPath;\n      event.eventPhase = originalPhase;\n      event.propagationStopped = originalStopped;\n      event.propagationImmediatelyStopped = originalImmediate;\n    }\n  }\n\n  /** Skips a node with no global-move listener first, so the fan-out stays cheap when nothing listens */\n  private _dispatchGlobalMove(event: FederatedPointerEvent): void {\n    if (!this.enableGlobalMoveEvents) return;\n    const list = this._interactiveList;\n    if (list.length === 0) return;\n\n    const movePick = this._movePickToken === event.nativeEvent ? this._movePick3D : null;\n    this._writeFields(event, movePick, movePick);\n    const storage = ensurePick3D(event);\n\n    const pointerType = event.pointerType;\n    let aliasType: string | null = null;\n    let aliasOnKey = '';\n    if (pointerType === 'touch') {\n      aliasType = 'globaltouchmove';\n      aliasOnKey = 'onglobaltouchmove';\n    } else if (pointerType === 'mouse' || pointerType === 'pen') {\n      aliasType = 'globalmousemove';\n      aliasOnKey = 'onglobalmousemove';\n    }\n\n    const e = event as WritableTypeEvent;\n    const originalType = e.type;\n    const originalCurrent = event.currentTarget;\n    const originalCurrent3D = storage.currentTarget;\n    const originalPhase = event.eventPhase;\n    const originalStopped = event.propagationStopped;\n    const originalImmediate = event.propagationImmediatelyStopped;\n\n    event.propagationStopped = false;\n    event.propagationImmediatelyStopped = false;\n    event.eventPhase = BUBBLING_PHASE;\n\n    try {\n      for (let i = 0; i < list.length; i++) {\n        const node = list[i];\n        const nodeEvents = (node as unknown as EmitterInternal)._events;\n        if (\n          nodeEvents.globalpointermove === undefined &&\n          !node.onglobalpointermove &&\n          (aliasType === null || (nodeEvents[aliasType] === undefined && !onHandlerOf(node, aliasOnKey)))\n        ) {\n          continue;\n        }\n        if (!node.isInteractive()) continue;\n        if (node._worldVisible === 0) continue;\n        if (!this._resolvePickTarget(node)) continue;\n        event.currentTarget = node as unknown as FederatedPointerEvent['currentTarget'];\n        storage.currentTarget = node;\n        e.type = 'globalpointermove';\n        onHandlerOf(node, 'onglobalpointermove')?.call(node, event);\n        notifyListeners3D(node, 'globalpointermove', event);\n        if (aliasType) {\n          e.type = aliasType;\n          onHandlerOf(node, aliasOnKey)?.call(node, event);\n          notifyListeners3D(node, aliasType, event);\n        }\n      }\n    } finally {\n      e.type = originalType;\n      event.currentTarget = originalCurrent;\n      storage.currentTarget = originalCurrent3D;\n      event.eventPhase = originalPhase;\n      event.propagationStopped = originalStopped;\n      event.propagationImmediatelyStopped = originalImmediate;\n    }\n  }\n}\n","import type { Cursor, EventMode } from 'pixi.js';\n\nimport { Matrix4 } from '../math/matrix/Matrix4';\nimport type { Container3D } from '../scene/Container3D';\nimport type { EventBoundary3D } from './EventBoundary3D';\nimport type { FederatedEventEmitterTypes3D } from './FederatedEventMap3D';\nimport type { HitVolume3D, HitVolume3DInput } from './HitResult3D';\nimport type { Pointer3DEventHandler, Wheel3DEventHandler } from './Pointer3DEvent';\nimport { resolveHitVolume } from './resolveHitVolume';\n\n/**\n * The pointer-event members of every {@link Container3D}\n *\n * They work as on a pixi.js `Container`. Set {@link IFederatedContainer3D#eventMode | eventMode}\n * to `'static'` and the node is picked by a ray from the pointer and fires its listeners. A\n * {@link Mesh3D} is picked against its geometry's bounding box unless you set a\n * {@link IFederatedContainer3D#hitVolume | hitVolume}. A plain `Container3D` has no shape of its\n * own, so it only hears events from its children.\n * @example\n * ```ts\n * mesh.eventMode = 'static'; // pickable, and fires listeners\n * mesh.hitVolume = 'geometry'; // per triangle, so hits carry a normal\n * mesh.cursor = 'pointer';\n * mesh.on('pointertap', (e) => {\n *   if (e.hit3D) spawnDecal(e.hit3D.point, e.hit3D.normal);\n * });\n *\n * // Or the property form, no emitter involved\n * mesh.onpointerenter = () => mesh.scale.set(1.1);\n * mesh.onpointerleave = () => mesh.scale.set(1);\n * ```\n * @remarks\n * - An `on*` handler property runs before the node's `on()` listeners in every phase, so an\n *   ancestor's handler runs twice per event, in the capture pass and again in the bubble pass. 2D\n *   does the same.\n * - Event objects are reused; see {@link Event3DFields} before keeping one.\n * @see {@link View3D#raycast} For a one-off pick that needs no listeners.\n * @category events\n * @standard\n */\nexport interface IFederatedContainer3D {\n  /**\n   * `undefined` until set, which means `'passive'`\n   * @internal\n   */\n  _eventMode?: EventMode;\n\n  /**\n   * How this node takes part in pointer events, as on a pixi.js `Container`\n   *\n   * - `'none'`: never picked, and neither is anything below it. The subtree costs nothing per\n   *   pointer event.\n   * - `'passive'` (default): fires no listeners and is never the target. Under an interactive\n   *   ancestor it is still picked, and the hit goes to that ancestor with this node's surface\n   *   data. So one `'static'` group makes its whole subtree clickable, with the group as target.\n   * - `'auto'`: as `'passive'`, but ray-tested even with no interactive ancestor, which costs time\n   *   and finds no target. Prefer `'passive'`.\n   * - `'static'`: picked against its {@link IFederatedContainer3D#hitVolume | hitVolume}, and fires\n   *   listeners.\n   * - `'dynamic'`: as `'static'`, and the {@link View3D} also picks again while a mouse or pen is\n   *   still, so a node that moves under it gets its enter and leave events.\n   *\n   * The renderer's `eventMode` option only sets the default for 2D containers, and the View warns\n   * once when it isn't `'passive'`. Picking costs time for each node that takes part, so set the\n   * mode on the nodes and groups that need it.\n   * @default 'passive'\n   * @example\n   * ```ts\n   * button.eventMode = 'static';   // a clickable mesh\n   * spinner.eventMode = 'dynamic'; // it moves under a still pointer\n   * panel.eventMode = 'none';      // decoration; skip it and its children\n   *\n   * // A whole model that answers as one target; its meshes need no setup\n   * robot.eventMode = 'static';\n   * ```\n   */\n  eventMode: EventMode;\n\n  /**\n   * Shorthand for {@link IFederatedContainer3D#eventMode | eventMode}, as on a pixi.js `Container`\n   *\n   * `true` sets `'static'` and `false` sets `'passive'`. It reads `true` for `'static'` and\n   * `'dynamic'`. `false` doesn't stop picking: under an interactive ancestor, a `'passive'` node is\n   * still picked on that ancestor's behalf. Set `eventMode = 'none'` to take a node and its\n   * subtree out of picking.\n   * @example\n   * ```ts\n   * mesh.interactive = true;  // eventMode = 'static'\n   * mesh.interactive = false; // eventMode = 'passive'\n   * ```\n   */\n  interactive: boolean;\n\n  /**\n   * Whether this node fires listeners and can be an event target\n   *\n   * True for `eventMode` `'static'` and `'dynamic'`, as in 2D.\n   * @example\n   * ```ts\n   * mesh.eventMode = 'dynamic';\n   * mesh.isInteractive(); // true\n   *\n   * mesh.eventMode = 'auto';\n   * mesh.isInteractive(); // false: hit-tested, but never the target\n   * ```\n   */\n  isInteractive(): boolean;\n\n  /** @internal */\n  _interactiveChildren: boolean;\n\n  /**\n   * Whether this node's descendants can be picked, as on a pixi.js `Container`\n   *\n   * `false` takes the whole subtree out of picking: descendants neither hit nor block what is\n   * behind them, and cost nothing per pointer event. The node itself still picks by its own\n   * `eventMode` and volume, so it can answer for the subtree.\n   * @default true\n   * @example\n   * ```ts\n   * menu.interactiveChildren = false; // nothing in the menu can be picked\n   * menu.interactiveChildren = true;  // every button picks again, eventMode intact\n   *\n   * // One sphere answers for the whole robot: one ray test instead of one per mesh\n   * robot.eventMode = 'static';\n   * robot.hitVolume = new Sphere(new Vector3(), 2);\n   * robot.interactiveChildren = false;\n   * ```\n   */\n  interactiveChildren: boolean;\n\n  /**\n   * CSS cursor shown while this node is the pointer's target\n   *\n   * Only the target's own cursor counts, as in 2D: a hit on a `'passive'` child shows its\n   * interactive ancestor's cursor, so set it on the node with the listeners. `null` shows the\n   * {@link View3D}'s own cursor. Any CSS cursor value works, `url(...)` included.\n   * @default null\n   * @example\n   * ```ts\n   * button.cursor = 'pointer';\n   * handle.cursor = 'grab';\n   * blade.cursor = 'url(\"crosshair.png\") 8 8, crosshair'; // custom, with a hotspot\n   * ```\n   * @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/cursor} MDN Cursor Documentation\n   */\n  cursor: Cursor | (string & {}) | null;\n\n  /** @internal */\n  _hitVolumeInput: HitVolume3DInput | null;\n\n  /**\n   * `null` when `_hitVolumeInput` is `null` or invalid\n   * @internal\n   */\n  _hitVolumeResolved: HitVolume3D | null;\n\n  /**\n   * Shape the pointer ray is tested against when picking this node, like `hitArea` in 2D\n   *\n   * Setting it doesn't make the node interactive; {@link IFederatedContainer3D#eventMode | eventMode}\n   * does that. Left `null`, a {@link Mesh3D} uses its geometry's bounding box and a plain\n   * `Container3D` has no shape, so it only hears events from its children.\n   *\n   * A shape you set also clips the node's descendants, as `hitArea` does in 2D: a descendant only\n   * hits where the hit point is inside every such shape above it, whatever those nodes'\n   * `eventMode`. A clipped hit doesn't block what is behind it. A `Geometry3D` clips by its bounding\n   * box, an {@link IHitVolume3D} only through its optional `containsPoint`, and the default\n   * bounding box never clips. A ray that misses a `Box` or `Sphere` shape, or a `Geometry3D`'s\n   * bounding box, skips the exact test of every descendant under it.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.interactive = true;                  // picked by its bounding box\n   * mesh.hitVolume = 'geometry';              // picked per triangle\n   * mesh.hitVolume = new Sphere(center, 0.4); // a cheaper or tighter shape\n   * mesh.hitVolume = null;                    // back to the bounding box\n   *\n   * // Children of the porthole only pick inside its sphere\n   * porthole.hitVolume = new Sphere(new Vector3(), 1);\n   * ```\n   * @see {@link HitVolume3DInput} For what each accepted value resolves to.\n   */\n  hitVolume: HitVolume3DInput | null;\n\n  /**\n   * The pick `_clipRayHit` was tested in; `_clipPickStamp` in `EventBoundary3D.ts` numbers picks\n   * @internal\n   */\n  _clipRayStamp: number;\n\n  /** @internal */\n  _clipRayHit: boolean;\n\n  /** @internal */\n  _isPickCandidate(): boolean;\n\n  /**\n   * Slot in the View's pick list, `-1` while off it; only `EventBoundary3D` writes it\n   * @internal\n   */\n  _pickIndex: number;\n\n  /** @internal */\n  _hasPickVolume(): boolean;\n\n  /** @internal */\n  _getDefaultHitVolume(): HitVolume3D | null;\n\n  /**\n   * Allocated on the first pick, so nodes that are never picked carry no matrix\n   * @internal\n   */\n  _invWorldTransform: Matrix4 | null;\n  /** @internal */\n  _invWorldTransformId: number;\n\n  /** @internal */\n  _worldScaleSq: number;\n  /** @internal */\n  _worldScaleSqId: number;\n\n  /**\n   * The cached inverse of `worldTransform`; callers must not write to it\n   * @internal\n   */\n  _getInverseWorldTransform(): Matrix4;\n\n  /**\n   * Squared largest singular value of `worldTransform`, which unlike the largest axis scale still\n   * bounds a sheared transform\n   * @internal\n   */\n  _getWorldScaleSq(): number;\n\n  /**\n   * Property-based handler for the `click` event\n   *\n   * Fired when a mouse click on this node completes, with any button but the right one.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.eventMode = 'static';\n   * mesh.onclick = (e) => {\n   *   if (e.hit3D) marker.position.copyFrom(e.hit3D.point);\n   * };\n   * ```\n   * @see {@link IFederatedContainer3D#onpointertap} For the equivalent for every pointer type.\n   */\n  onclick: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `contextmenu` event\n   *\n   * Fired when the browser is about to open its context menu over this node; call\n   * `preventDefault()` to keep it closed.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.oncontextmenu = (e) => {\n   *   e.preventDefault();\n   *   openMenuFor(mesh, e.global);\n   * };\n   * ```\n   */\n  oncontextmenu: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `mousedown` event\n   *\n   * Fired when a mouse button other than the right one goes down over this node.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onmousedown = (e) => {\n   *   if (e.button === 1) startPan(e.global); // middle button\n   * };\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerdown} For the equivalent for every pointer type.\n   */\n  onmousedown: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `mouseenter` event\n   *\n   * Fired when the mouse enters this node. Doesn't bubble.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onmouseenter = () => (tooltip.visible = true);\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerenter} For the equivalent for every pointer type.\n   */\n  onmouseenter: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `mouseleave` event\n   *\n   * Fired when the mouse leaves this node. Doesn't bubble.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onmouseleave = () => (tooltip.visible = false);\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerleave} For the equivalent for every pointer type.\n   */\n  onmouseleave: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `mousemove` event\n   *\n   * Fired while the mouse moves across this node.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onmousemove = (e) => tooltip.position.copyFrom(e.global);\n   * ```\n   * @see {@link IFederatedContainer3D#onpointermove} For the equivalent for every pointer type.\n   */\n  onmousemove: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `globalmousemove` event\n   *\n   * Fired on every mouse move, wherever the pointer is on the page.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onglobalmousemove = (e) => {\n   *   if (dragging) dragTo(e.global);\n   * };\n   * ```\n   * @see {@link IFederatedContainer3D#onglobalpointermove} For the equivalent for every pointer type.\n   */\n  onglobalmousemove: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `mouseout` event\n   *\n   * Fired when the mouse moves off this node. Bubbles, unlike `mouseleave`.\n   * @default null\n   * @example\n   * ```ts\n   * shelf.onmouseout = (e) => unhighlight(e.target3D);\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerout} For the equivalent for every pointer type.\n   */\n  onmouseout: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `mouseover` event\n   *\n   * Fired when the mouse moves onto this node. Bubbles, unlike `mouseenter`.\n   * @default null\n   * @example\n   * ```ts\n   * // One handler on the shelf hears every item on it\n   * shelf.onmouseover = (e) => highlight(e.target3D);\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerover} For the equivalent for every pointer type.\n   */\n  onmouseover: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `mouseup` event\n   *\n   * Fired when a mouse button other than the right one is released over this node.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onmouseup = (e) => {\n   *   if (e.button === 1) endPan();\n   * };\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerup} For the equivalent for every pointer type.\n   */\n  onmouseup: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `mouseupoutside` event\n   *\n   * Fired when a mouse button that went down on this node is released anywhere else.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onmouseupoutside = () => endPan();\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerupoutside} For the equivalent for every pointer type.\n   */\n  onmouseupoutside: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointercancel` event\n   *\n   * Never called: pixi delivers no pointer cancellation, in 2D either.\n   * @default null\n   * @example\n   * ```ts\n   * // End a drag on these two instead\n   * handle.onpointerup = endDrag;\n   * handle.onpointerupoutside = endDrag;\n   * ```\n   */\n  onpointercancel: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointerdown` event\n   *\n   * Fired when a pointer goes down on this node: mouse, touch or pen alike.\n   * @default null\n   * @example\n   * ```ts\n   * handle.eventMode = 'static';\n   * handle.onpointerdown = (e) => {\n   *   if (!e.hit3D) return;\n   *   dragOffset.copyFrom(e.hit3D.localPoint); // where on the handle it was grabbed\n   *   dragging = true;\n   * };\n   * ```\n   */\n  onpointerdown: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointerenter` event\n   *\n   * Fired when a pointer enters this node. Doesn't bubble, so an ancestor hears it only when the\n   * pointer enters the ancestor itself.\n   * @default null\n   * @example\n   * ```ts\n   * button.eventMode = 'static';\n   * button.onpointerenter = () => button.scale.set(1.1);\n   * ```\n   */\n  onpointerenter: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointerleave` event\n   *\n   * Fired when a pointer leaves this node. Doesn't bubble.\n   * @default null\n   * @example\n   * ```ts\n   * button.onpointerleave = () => button.scale.set(1);\n   * ```\n   */\n  onpointerleave: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointermove` event\n   *\n   * Fired while a pointer moves across this node.\n   * @default null\n   * @example\n   * ```ts\n   * // Trail the cursor across the surface it is over\n   * table.eventMode = 'static';\n   * table.onpointermove = (e) => {\n   *   if (e.hit3D) cursorMarker.position.copyFrom(e.hit3D.point);\n   * };\n   * ```\n   */\n  onpointermove: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `globalpointermove` event\n   *\n   * Fired on every pointer move on the page, whether or not the pointer is over this node. The\n   * node still needs `eventMode` `'static'` or `'dynamic'` to hear it.\n   * @default null\n   * @example\n   * ```ts\n   * // Keep a drag going once the pointer runs off the dragged mesh\n   * mesh.onglobalpointermove = (e) => {\n   *   const hit = dragging && view3d.screenToWorld(e.global, ground);\n   *   if (hit) mesh.position.copyFrom(hit);\n   * };\n   * ```\n   */\n  onglobalpointermove: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointerout` event\n   *\n   * Fired when a pointer moves off this node. Bubbles, unlike `pointerleave`.\n   * @default null\n   * @example\n   * ```ts\n   * shelf.onpointerout = (e) => unhighlight(e.target3D);\n   * ```\n   */\n  onpointerout: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointerover` event\n   *\n   * Fired when a pointer moves onto this node. Bubbles, unlike `pointerenter`.\n   * @default null\n   * @example\n   * ```ts\n   * // One handler on the shelf hears every item on it\n   * shelf.onpointerover = (e) => highlight(e.target3D);\n   * ```\n   */\n  onpointerover: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointertap` event\n   *\n   * Fired when a pointer completes a tap on this node, for any pointer type and any button, right\n   * clicks included.\n   * @default null\n   * @example\n   * ```ts\n   * // Works for mouse, touch and pen alike\n   * mesh.eventMode = 'static';\n   * mesh.onpointertap = (e) => select(e.target3D);\n   * ```\n   */\n  onpointertap: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointerup` event\n   *\n   * Fired when a pointer is released over this node.\n   * @default null\n   * @example\n   * ```ts\n   * handle.onpointerup = () => {\n   *   dragging = false;\n   * };\n   * ```\n   */\n  onpointerup: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `pointerupoutside` event\n   *\n   * Fired when a pointer that went down on this node is released anywhere else. The event's\n   * `target3D` is the node that was pressed, and `hit3D` is what the pointer was released over.\n   * @default null\n   * @example\n   * ```ts\n   * // The release that ends a drag usually happens off the mesh\n   * handle.onpointerupoutside = () => {\n   *   dragging = false;\n   * };\n   * ```\n   */\n  onpointerupoutside: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `rightclick` event\n   *\n   * Fired when a right click completes on this node.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onrightclick = () => openMenuFor(mesh);\n   * ```\n   */\n  onrightclick: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `rightdown` event\n   *\n   * Fired when the right mouse button goes down over this node.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onrightdown = (e) => startRotate(e.global);\n   * ```\n   */\n  onrightdown: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `rightup` event\n   *\n   * Fired when the right mouse button is released over this node.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onrightup = endRotate;\n   * ```\n   */\n  onrightup: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `rightupoutside` event\n   *\n   * Fired when the right mouse button that went down on this node is released anywhere else.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onrightupoutside = endRotate;\n   * ```\n   */\n  onrightupoutside: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `tap` event\n   *\n   * Fired when a touch completes a tap on this node. Chrome gives each touch a new `pointerId`, and\n   * `detail` only counts repeat taps by the same one, so it stays `1` there; time a double tap yourself.\n   * @default null\n   * @example\n   * ```ts\n   * let lastTap = 0;\n   * mesh.ontap = (e) => {\n   *   if (e.timeStamp - lastTap < 300) focusOn(mesh); // double tap\n   *   lastTap = e.timeStamp;\n   * };\n   * ```\n   * @see {@link IFederatedContainer3D#onpointertap} For the equivalent for every pointer type.\n   */\n  ontap: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `touchcancel` event\n   *\n   * Never called: pixi delivers no touch cancellation, in 2D either.\n   * @default null\n   * @example\n   * ```ts\n   * // End a drag on these two instead\n   * handle.ontouchend = endDrag;\n   * handle.ontouchendoutside = endDrag;\n   * ```\n   */\n  ontouchcancel: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `touchend` event\n   *\n   * Fired when a touch lifts off this node.\n   * @default null\n   * @example\n   * ```ts\n   * handle.ontouchend = endDrag;\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerup} For the equivalent for every pointer type.\n   */\n  ontouchend: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `touchendoutside` event\n   *\n   * Fired when a touch that started on this node lifts off anywhere else.\n   * @default null\n   * @example\n   * ```ts\n   * handle.ontouchendoutside = endDrag;\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerupoutside} For the equivalent for every pointer type.\n   */\n  ontouchendoutside: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `touchmove` event\n   *\n   * Fired while a touch moves across this node.\n   * @default null\n   * @example\n   * ```ts\n   * canvasMesh.hitVolume = 'geometry'; // per triangle, so hits carry a uv\n   * canvasMesh.ontouchmove = (e) => {\n   *   if (e.hit3D) paintAt(e.hit3D.uv);\n   * };\n   * ```\n   * @see {@link IFederatedContainer3D#onpointermove} For the equivalent for every pointer type.\n   */\n  ontouchmove: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `globaltouchmove` event\n   *\n   * Fired on every touch move, wherever the touch is on the page.\n   * @default null\n   * @example\n   * ```ts\n   * mesh.onglobaltouchmove = (e) => {\n   *   if (dragging) dragTo(e.global);\n   * };\n   * ```\n   * @see {@link IFederatedContainer3D#onglobalpointermove} For the equivalent for every pointer type.\n   */\n  onglobaltouchmove: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `touchstart` event\n   *\n   * Fired when a touch lands on this node.\n   * @default null\n   * @example\n   * ```ts\n   * handle.ontouchstart = (e) => startDrag(e.pointerId);\n   * ```\n   * @see {@link IFederatedContainer3D#onpointerdown} For the equivalent for every pointer type.\n   */\n  ontouchstart: Pointer3DEventHandler | null;\n\n  /**\n   * Property-based handler for the `wheel` event\n   *\n   * Fired when the wheel turns while the pointer is over this node.\n   * @default null\n   * @example\n   * ```ts\n   * // Scroll to push the panel away from the camera\n   * panel.eventMode = 'static';\n   * panel.onwheel = (e) => {\n   *   panel.position.z += e.deltaY * 0.01;\n   * };\n   * ```\n   */\n  onwheel: Wheel3DEventHandler | null;\n}\n\ntype OnHandlerKey = Extract<keyof IFederatedContainer3D, `on${string}`>;\n\n/**\n * The pointer-event options of {@link Container3DOptions}\n *\n * `eventMode`, `interactive`, `interactiveChildren`, `cursor`, `hitVolume`, and every `on*`\n * handler, as on {@link IFederatedContainer3D}.\n * @example\n * ```ts\n * const door = new Container3D({\n *   eventMode: 'static',\n *   cursor: 'pointer',\n *   hitVolume: new Box(new Vector3(-1, 0, -0.1), new Vector3(1, 2, 0.1)),\n *   onpointertap: () => openDoor(),\n * });\n * ```\n * @category events\n * @standard\n */\nexport interface Federated3DOptions extends Partial<\n  Pick<\n    IFederatedContainer3D,\n    'eventMode' | 'interactive' | 'interactiveChildren' | 'cursor' | 'hitVolume' | OnHandlerKey\n  >\n> {}\n\n/** @internal */\nexport const PICK_BLOCKED = 0;\n/** @internal */\nexport const PICK_BARE = 1;\n/** @internal */\nexport const PICK_COVERED = 2;\n\n/** @internal */\nexport type AncestorPickState = typeof PICK_BLOCKED | typeof PICK_BARE | typeof PICK_COVERED;\n\n/**\n * Blocked under an `eventMode: 'none'` or `interactiveChildren: false` ancestor, else covered under an\n * interactive one; `View3D._attach` and `EventBoundary3D._resolvePickTarget` must apply the same rule\n * @internal\n */\nexport function getAncestorPickState(node: Container3D): AncestorPickState {\n  let covered = false;\n  let cur = node.parent;\n  while (cur) {\n    const mode = cur._eventMode;\n    if (mode === 'none' || !cur._interactiveChildren) return PICK_BLOCKED;\n    if (mode === 'static' || mode === 'dynamic') covered = true;\n    cur = cur.parent;\n  }\n  return covered ? PICK_COVERED : PICK_BARE;\n}\n\nfunction registerSubtree(node: Container3D, events: EventBoundary3D, underInteractive: boolean): void {\n  const children = node.children;\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    const mode = child._eventMode;\n    if (mode === 'none') continue;\n    const interactive = mode === 'static' || mode === 'dynamic';\n    if (interactive || mode === 'auto' || (underInteractive && child._hasPickVolume())) {\n      events._addInteractive(child);\n    }\n    if (child._interactiveChildren) registerSubtree(child, events, underInteractive || interactive);\n  }\n}\n\nfunction unregisterSubtree(node: Container3D, events: EventBoundary3D): void {\n  const children = node.children;\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    if (child._pickIndex !== -1) events._removeInteractive(child);\n    if (child._eventMode !== 'none' && child._interactiveChildren) unregisterSubtree(child, events);\n  }\n}\n\nfunction registerCoveredSubtree(node: Container3D, events: EventBoundary3D): void {\n  const children = node.children;\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    const mode = child._eventMode;\n    if (mode === 'none') continue;\n    const interactive = mode === 'static' || mode === 'dynamic';\n    if (interactive) continue;\n    if (mode !== 'auto' && child._hasPickVolume()) events._addInteractive(child);\n    if (child._interactiveChildren) registerCoveredSubtree(child, events);\n  }\n}\n\nfunction unregisterCoveredSubtree(node: Container3D, events: EventBoundary3D): void {\n  const children = node.children;\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    const mode = child._eventMode;\n    if (mode === 'none') continue;\n    const interactive = mode === 'static' || mode === 'dynamic';\n    if (interactive) continue;\n    if (mode !== 'auto' && child._pickIndex !== -1) events._removeInteractive(child);\n    if (child._interactiveChildren) unregisterCoveredSubtree(child, events);\n  }\n}\n\n/**\n * Mixed into `Container3D.prototype`, so a node that never uses events carries no storage for its\n * defaults\n * @internal\n */\nexport const FederatedContainer3D: IFederatedContainer3D & ThisType<Container3D> = {\n  onclick: null,\n  oncontextmenu: null,\n  onmousedown: null,\n  onmouseenter: null,\n  onmouseleave: null,\n  onmousemove: null,\n  onglobalmousemove: null,\n  onmouseout: null,\n  onmouseover: null,\n  onmouseup: null,\n  onmouseupoutside: null,\n  onpointercancel: null,\n  onpointerdown: null,\n  onpointerenter: null,\n  onpointerleave: null,\n  onpointermove: null,\n  onglobalpointermove: null,\n  onpointerout: null,\n  onpointerover: null,\n  onpointertap: null,\n  onpointerup: null,\n  onpointerupoutside: null,\n  onrightclick: null,\n  onrightdown: null,\n  onrightup: null,\n  onrightupoutside: null,\n  ontap: null,\n  ontouchcancel: null,\n  ontouchend: null,\n  ontouchendoutside: null,\n  ontouchmove: null,\n  onglobaltouchmove: null,\n  ontouchstart: null,\n  onwheel: null,\n\n  _eventMode: undefined,\n\n  get eventMode(): EventMode {\n    return this._eventMode ?? 'passive';\n  },\n\n  set eventMode(value: EventMode) {\n    const prev = this._eventMode ?? 'passive';\n    this._eventMode = value;\n\n    if (!this._view3d || value === prev) return;\n\n    const events = this._view3d.events;\n    const wasDynamic = prev === 'dynamic';\n\n    let ancestorState: AncestorPickState | -1 = -1;\n\n    let shouldRegister = false;\n    if (value !== 'none' && (this._isPickCandidate() || this._hasPickVolume())) {\n      ancestorState = getAncestorPickState(this);\n      if (ancestorState !== PICK_BLOCKED) {\n        shouldRegister = this._isPickCandidate() || ancestorState === PICK_COVERED;\n      }\n    }\n\n    const registered = this._pickIndex !== -1;\n    if (shouldRegister !== registered) {\n      if (shouldRegister) {\n        events._addInteractive(this);\n      } else {\n        events._removeInteractive(this, wasDynamic);\n      }\n    } else if (registered && wasDynamic !== (value === 'dynamic')) {\n      events._changeDynamicCount(value === 'dynamic' ? 1 : -1);\n    }\n\n    const wasInteractive = prev === 'static' || prev === 'dynamic';\n    const nowInteractive = value === 'static' || value === 'dynamic';\n    const wasBarrier = prev === 'none' || !this._interactiveChildren;\n    const nowBarrier = value === 'none' || !this._interactiveChildren;\n    if (\n      (wasInteractive === nowInteractive && wasBarrier === nowBarrier) ||\n      (wasBarrier && nowBarrier) ||\n      this.children.length === 0\n    ) {\n      return;\n    }\n\n    if (ancestorState === -1) ancestorState = getAncestorPickState(this);\n    if (ancestorState === PICK_BLOCKED) return;\n\n    if (nowBarrier) {\n      unregisterSubtree(this, events);\n    } else if (wasBarrier) {\n      registerSubtree(this, events, nowInteractive || ancestorState === PICK_COVERED);\n    } else if (ancestorState !== PICK_COVERED) {\n      if (nowInteractive) {\n        registerCoveredSubtree(this, events);\n      } else {\n        unregisterCoveredSubtree(this, events);\n      }\n    }\n  },\n\n  get interactive(): boolean {\n    return this.isInteractive();\n  },\n\n  set interactive(value: boolean) {\n    this.eventMode = value ? 'static' : 'passive';\n  },\n\n  isInteractive(): boolean {\n    return this._eventMode === 'static' || this._eventMode === 'dynamic';\n  },\n\n  _isPickCandidate(): boolean {\n    return this._eventMode === 'static' || this._eventMode === 'dynamic' || this._eventMode === 'auto';\n  },\n\n  _pickIndex: -1,\n\n  _hasPickVolume(): boolean {\n    return this._hitVolumeInput !== null || this._getDefaultHitVolume() !== null;\n  },\n\n  _interactiveChildren: true,\n\n  get interactiveChildren(): boolean {\n    return this._interactiveChildren;\n  },\n\n  set interactiveChildren(value: boolean) {\n    const prev = this._interactiveChildren;\n    this._interactiveChildren = value;\n\n    if (!this._view3d || value === prev || this.children.length === 0) return;\n\n    if (this._eventMode === 'none') return;\n\n    const ancestorState = getAncestorPickState(this);\n    if (ancestorState === PICK_BLOCKED) return;\n\n    const events = this._view3d.events;\n    if (!value) {\n      unregisterSubtree(this, events);\n    } else {\n      registerSubtree(this, events, this.isInteractive() || ancestorState === PICK_COVERED);\n    }\n  },\n\n  cursor: null,\n\n  _hitVolumeInput: null,\n  _hitVolumeResolved: null,\n  _clipRayStamp: 0,\n  _clipRayHit: false,\n\n  get hitVolume(): HitVolume3DInput | null {\n    return this._hitVolumeInput;\n  },\n\n  set hitVolume(value: HitVolume3DInput | null) {\n    const wasExplicit = this._hitVolumeInput !== null;\n    this._hitVolumeInput = value;\n    this._hitVolumeResolved = resolveHitVolume(this, value);\n\n    if (!this._view3d) return;\n\n    if (wasExplicit !== (value !== null)) {\n      this._view3d.events._clipVolumeCount += value !== null ? 1 : -1;\n    }\n\n    if (this._eventMode !== undefined && this._eventMode !== 'passive') return;\n    if (this._hasPickVolume() && getAncestorPickState(this) === PICK_COVERED) {\n      this._view3d.events._addInteractive(this);\n    } else {\n      this._view3d.events._removeInteractive(this);\n    }\n  },\n\n  _getDefaultHitVolume(): HitVolume3D | null {\n    return null;\n  },\n\n  _invWorldTransform: null,\n  _invWorldTransformId: -1,\n  _worldScaleSq: 0,\n  _worldScaleSqId: -1,\n\n  _getInverseWorldTransform(): Matrix4 {\n    if (this._invWorldTransform === null) {\n      this._invWorldTransform = new Matrix4();\n      this._invWorldTransformId = -1;\n    }\n    if (this._invWorldTransformId !== this._worldTransformId) {\n      this._invWorldTransform.getInverse(this.worldTransform);\n      this._invWorldTransformId = this._worldTransformId;\n    }\n    return this._invWorldTransform;\n  },\n\n  _getWorldScaleSq(): number {\n    if (this._worldScaleSqId !== this._worldTransformId) {\n      this._worldScaleSq = this.worldTransform.getMaxSingularValueSq();\n      this._worldScaleSqId = this._worldTransformId;\n    }\n    return this._worldScaleSq;\n  },\n};\n\ndeclare global {\n  namespace PixiMixins {\n    interface Container3D extends IFederatedContainer3D {}\n\n    interface Container3DOptions extends Federated3DOptions {}\n\n    interface Container3DEvents extends FederatedEventEmitterTypes3D {}\n  }\n}\n","import type { Cursor, IHitArea, PointData } from 'pixi.js';\n\nimport type { View3D } from '../scene/View3D';\nimport type { RaycastHit3D } from './HitResult3D';\n\n/**\n * The pointer-event members of {@link View3D}\n *\n * Pixi treats a View as one 2D object. When pixi hit-tests it, the View casts a ray into the scene\n * and passes the event on to the 3D node it hits.\n * @example\n * ```ts\n * view3d.cursor = 'crosshair';                    // shown over empty space\n * view3d.hitArea = new Rectangle(0, 0, 400, 300); // only this part takes pointer events\n *\n * const hit = view3d.raycast({ x: 200, y: 150 }); // a pick without an event\n * ```\n * @see {@link EventBoundary3D} For event settings that apply to the whole View, at `view3d.events`.\n * @category events\n * @standard\n */\nexport interface IView3DEvents {\n  /**\n   * Whether a point in the View's local 2D space is inside the View; pixi's hit test for the View\n   *\n   * It answers `true` anywhere in the View's rectangle, so a click on empty space still reaches the\n   * View, and \"click empty space to deselect\" needs no extra wiring. It also picks the 3D node\n   * under the point for the event that follows.\n   * @remarks\n   * - The View hides interactive 2D content behind it from pointer events. To let them through,\n   *   put the 2D UI above the View, set {@link View3D#hitArea} to cover only part of it, or set the\n   *   View's `eventMode` to `'none'` or `'passive'`, which turn off 3D pointer events too.\n   *   `'passive'` lets 2D content through only while no 2D ancestor of the View is interactive.\n   * - Calling it from a listener changes the pick the rest of that event uses. Use\n   *   {@link View3D#raycast} to query the scene.\n   * @example\n   * ```ts\n   * const overView = view3d.containsPoint(view3d.toLocal({ x: 400, y: 300 }));\n   * ```\n   * @param {PointData} point - Point in the View's local 2D space.\n   */\n  containsPoint(point: PointData): boolean;\n\n  /**\n   * CSS cursor shown over the View, except where the event's 3D target\n   * ({@link Event3DFields#target3D | target3D}) sets its own {@link Container3D#cursor | cursor}\n   *\n   * Reading it back returns the cursor in effect now, which can be the node's.\n   * @example\n   * ```ts\n   * view3d.cursor = 'default'; // shown over empty space\n   * mesh.cursor = 'pointer';   // shown while the ray hits the mesh\n   * ```\n   */\n  cursor?: Cursor | (string & {});\n\n  /**\n   * Limits pointer events to a shape inside the View, in View-local 2D space, with 3D picking\n   * still working inside it\n   * @remarks\n   * - The interactive region is where the shape and the View's rectangle overlap: a shape can\n   *   shrink it but never extend it past the View, unlike 2D, where `hitArea` replaces the bounds.\n   * - Outside the shape the View isn't hit at all, so events reach the content behind it.\n   * - Reading it back returns another object, not your shape, so keep your own reference.\n   * - {@link View3D#raycast} and {@link View3D#containsPoint} ignore the shape.\n   * @example\n   * ```ts\n   * // Only the top-left 400×300 of the View is interactive;\n   * // clicks outside it fall through to the 2D content behind.\n   * view3d.hitArea = new Rectangle(0, 0, 400, 300);\n   * ```\n   */\n  hitArea?: IHitArea | null;\n\n  /**\n   * Casts a ray through a 2D point and returns the closest hit\n   *\n   * `position` is in the space of `event.global`, as for {@link View3D#screenToRay}. Use it to pick\n   * outside pointer events: placing decals, line of sight, drag-and-drop targets.\n   * @remarks\n   * - Only nodes that take part in picking can be hit: interactive nodes and, under them, nodes\n   *   with a shape (see {@link IFederatedContainer3D#eventMode}). In a scene where nothing is\n   *   interactive it always returns `null`.\n   * - Without `out` it allocates a new {@link RaycastHit3D} for each hit. Pass a hit from\n   *   {@link createRaycastHit3D} as `out` to pick every frame without garbage.\n   * - It uses the transforms and visibility from the last render, so a node or camera moved, shown\n   *   or hidden since then is picked as it was drawn.\n   * - Hidden nodes, and nodes under a hidden ancestor, neither hit nor block what is behind them.\n   * - A {@link Container3D#hitVolume | hitVolume} you set on an ancestor clips its descendants'\n   *   hits, as it does for pointer events.\n   * @param {PointData} position - 2D global point to cast through (e.g. `event.global`).\n   * @param {RaycastHit3D} [out] - Hit to write into, returned on a hit and untouched on a miss.\n   * Defaults to a new one for each hit.\n   * @returns The closest hit, or `null` on a miss or when the point falls outside the View's 2D rect.\n   * @example\n   * ```ts\n   * // Drop a decal wherever the user taps.\n   * view3d.on('pointertap', (e) => {\n   *   const hit = view3d.raycast(e.global);\n   *   if (hit) decal.position.copyFrom(hit.point); // world-space hit point\n   * });\n   *\n   * // Follow the pointer every frame, reusing one hit.\n   * const hover = createRaycastHit3D();\n   * app.ticker.add(() => {\n   *   if (view3d.raycast(pointer, hover)) cursor3d.position.copyFrom(hover.point);\n   * });\n   * ```\n   * @see {@link View3D#screenToRay} For the ray on its own, without a scene pick.\n   */\n  raycast(position: PointData, out?: RaycastHit3D): RaycastHit3D | null;\n}\n\n/** @internal */\nexport const View3DEvents: IView3DEvents & ThisType<View3D> = {\n  containsPoint(point: PointData): boolean {\n    return this.events._containsPoint(point.x, point.y);\n  },\n\n  get cursor(): Cursor | (string & {}) | undefined {\n    return this.events._cursor;\n  },\n\n  set cursor(value: Cursor | (string & {}) | undefined) {\n    this.events._cursor = value;\n  },\n\n  get hitArea(): IHitArea | null {\n    return this.events._hitAreaShape !== null ? this.events._hitAreaProxy : null;\n  },\n\n  /**\n   * Ignores the boundary's own hit area, which the getter hands back; stored as the shape, its\n   * `contains` would call itself forever\n   */\n  set hitArea(value: IHitArea | null | undefined) {\n    if (value === this.events._hitAreaProxy) return;\n    this.events._hitAreaShape = value ?? null;\n  },\n\n  raycast(position: PointData, out?: RaycastHit3D): RaycastHit3D | null {\n    return this.events._raycast(position, out);\n  },\n};\n\ndeclare global {\n  namespace PixiMixins {\n    interface View3D extends IView3DEvents {}\n  }\n}\n","/** @internal */\nexport function clampSegments(value: number, min: number): number {\n  if (!Number.isFinite(value)) return min;\n\n  return Math.max(min, Math.floor(value));\n}\n","import { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\nimport { clampSegments } from './utils/clampSegments';\n\n/**\n * Options for {@link CapsuleGeometry}\n * @example\n * ```ts\n * const options: Partial<CapsuleGeometryOptions> = { radius: 0.25, height: 1.5 };\n * const capsule = new CapsuleGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface CapsuleGeometryOptions extends Geometry3DOptions {\n  /**\n   * The radius of the capsule, shared by the cylindrical mid-section and the hemispherical caps\n   * @default 0.5\n   * @example\n   * ```ts\n   * const thin = new CapsuleGeometry({ radius: 0.1 });\n   * ```\n   */\n  radius: number;\n  /**\n   * The total height of the capsule along the Y axis, including the caps\n   *\n   * The cylindrical portion is `height - 2 * radius`; when `height <= 2 * radius` there is no\n   * cylinder, and the capsule is a sphere of `radius`.\n   * @default 2\n   * @example\n   * ```ts\n   * const tall = new CapsuleGeometry({ radius: 0.5, height: 3 });\n   * ```\n   */\n  height: number;\n  /**\n   * The number of segments around the circumference\n   *\n   * Floored, and clamped to a minimum of 3. Each cap is split into `ceil(radialSegments / 2)`\n   * bands from rim to pole.\n   * @default 32\n   * @example\n   * ```ts\n   * const lowPoly = new CapsuleGeometry({ radialSegments: 8 });\n   * ```\n   */\n  radialSegments: number;\n  /**\n   * The number of segments along the cylindrical portion; the caps follow `radialSegments`\n   *\n   * Floored, and clamped to a minimum of 1.\n   * @default 8\n   * @example\n   * ```ts\n   * const bendable = new CapsuleGeometry({ height: 4, heightSegments: 32 });\n   * ```\n   */\n  heightSegments: number;\n}\n\n/**\n * A capsule geometry oriented along the +Y axis and centered on the origin: a cylindrical\n * mid-section with hemispherical caps on each end\n *\n * Normals are smooth across the seams between the caps and the cylinder. UVs wrap once around the\n * circumference (`u` from 0 to 1), and `v` runs from 0 at the top pole to 1 at the bottom one, the\n * top cap, cylinder and bottom cap each taking a share in proportion to its height.\n * @example\n * ```ts\n * const capsule = new CapsuleGeometry({\n *   radius: 0.5,\n *   height: 2,\n *   radialSegments: 32,\n *   heightSegments: 8,\n * });\n * ```\n * @see {@link CylinderGeometry} For flat ends instead of rounded caps\n * @category geometry\n * @standard\n */\nexport class CapsuleGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `CapsuleGeometry`\n   * @example\n   * ```ts\n   * CapsuleGeometry.defaultOptions.radialSegments = 16;\n   * ```\n   */\n  public static defaultOptions: CapsuleGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    radius: 0.5,\n    height: 2,\n    radialSegments: 32,\n    heightSegments: 8,\n  };\n\n  /**\n   * Creates a new `CapsuleGeometry`\n   * @param options - See {@link CapsuleGeometryOptions} for available options\n   */\n  constructor(options: Partial<CapsuleGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...CapsuleGeometry.defaultOptions,\n      ...options,\n    };\n    const { radius, height } = resolvedOptions;\n    const radialSegments = clampSegments(resolvedOptions.radialSegments, 3);\n    const heightSegments = clampSegments(resolvedOptions.heightSegments, 1);\n    const capSegments = Math.max(1, Math.ceil(radialSegments / 2));\n\n    const cylinderHeight = Math.max(0, height - 2 * radius);\n    const halfCylinderHeight = cylinderHeight * 0.5;\n\n    const totalHeight = cylinderHeight + 2 * radius;\n    const invTotalHeight = 1 / totalHeight;\n    const capUVHeight = radius * invTotalHeight;\n    const cylinderUVHeight = cylinderHeight * invTotalHeight;\n\n    const invRadial = 1 / radialSegments;\n    const invHeight = 1 / heightSegments;\n    const invCapSegments = 1 / capSegments;\n    const radialStride = radialSegments + 1;\n\n    const sinTable = new Float32Array(radialStride);\n    const cosTable = new Float32Array(radialStride);\n    const angleStep = Math.PI * 2 * invRadial;\n    for (let i = 0; i < radialStride; i++) {\n      const theta = i * angleStep;\n      sinTable[i] = Math.sin(theta);\n      cosTable[i] = Math.cos(theta);\n    }\n\n    const topHemiRings = capSegments;\n    const bodyRings = heightSegments + 1;\n    const bottomHemiRings = capSegments;\n    const totalRings = topHemiRings + bodyRings + bottomHemiRings;\n    const quadRows = totalRings - 1;\n\n    const vertCount = totalRings * radialStride;\n    const indexCount = (quadRows - 1) * radialSegments * 6;\n\n    const positions = new Float32Array(vertCount * 3);\n    const normals = new Float32Array(vertCount * 3);\n    const uvs = new Float32Array(vertCount * 2);\n    const IndexArray = vertCount > 65536 ? Uint32Array : Uint16Array;\n    const indices = new IndexArray(indexCount);\n\n    let pi = 0;\n    let ni = 0;\n    let ui = 0;\n    let ii = 0;\n\n    for (let y = 0; y < capSegments; y++) {\n      const t = y * invCapSegments;\n      const phi = (1 - t) * (Math.PI / 2);\n      const v = capUVHeight * t;\n      const cosPhi = Math.cos(phi);\n      const sinPhi = Math.sin(phi);\n      const ringRadius = cosPhi * radius;\n      const posY = sinPhi * radius + halfCylinderHeight;\n\n      for (let x = 0; x <= radialSegments; x++) {\n        const u = x * invRadial;\n        const cosTheta = cosTable[x];\n        const sinTheta = sinTable[x];\n\n        positions[pi++] = ringRadius * cosTheta;\n        positions[pi++] = posY;\n        positions[pi++] = ringRadius * sinTheta;\n\n        normals[ni++] = cosPhi * cosTheta;\n        normals[ni++] = sinPhi;\n        normals[ni++] = cosPhi * sinTheta;\n\n        uvs[ui++] = u;\n        uvs[ui++] = v;\n      }\n    }\n\n    for (let y = 0; y <= heightSegments; y++) {\n      const t = y * invHeight;\n      const posY = halfCylinderHeight - t * cylinderHeight;\n      const v = capUVHeight + t * cylinderUVHeight;\n\n      for (let x = 0; x <= radialSegments; x++) {\n        const u = x * invRadial;\n        const cosTheta = cosTable[x];\n        const sinTheta = sinTable[x];\n\n        positions[pi++] = radius * cosTheta;\n        positions[pi++] = posY;\n        positions[pi++] = radius * sinTheta;\n\n        normals[ni++] = cosTheta;\n        normals[ni++] = 0;\n        normals[ni++] = sinTheta;\n\n        uvs[ui++] = u;\n        uvs[ui++] = v;\n      }\n    }\n\n    for (let y = 1; y <= capSegments; y++) {\n      const t = y * invCapSegments;\n      const phi = t * (Math.PI / 2);\n      const v = capUVHeight + cylinderUVHeight + capUVHeight * t;\n      const cosPhi = Math.cos(phi);\n      const sinPhi = Math.sin(phi);\n      const ringRadius = cosPhi * radius;\n      const posY = -sinPhi * radius - halfCylinderHeight;\n\n      for (let x = 0; x <= radialSegments; x++) {\n        const u = x * invRadial;\n        const cosTheta = cosTable[x];\n        const sinTheta = sinTable[x];\n\n        positions[pi++] = ringRadius * cosTheta;\n        positions[pi++] = posY;\n        positions[pi++] = ringRadius * sinTheta;\n\n        normals[ni++] = cosPhi * cosTheta;\n        normals[ni++] = -sinPhi;\n        normals[ni++] = cosPhi * sinTheta;\n\n        uvs[ui++] = u;\n        uvs[ui++] = v;\n      }\n    }\n\n    const lastRow = quadRows - 1;\n    for (let y = 0; y < quadRows; y++) {\n      const atNorthPole = y === 0;\n      const atSouthPole = y === lastRow;\n\n      for (let x = 0; x < radialSegments; x++) {\n        const a = y * radialStride + x;\n        const b = a + 1;\n        const c = a + radialStride;\n        const d = c + 1;\n\n        if (!atNorthPole) {\n          indices[ii++] = a;\n          indices[ii++] = b;\n          indices[ii++] = c;\n        }\n        if (!atSouthPole) {\n          indices[ii++] = b;\n          indices[ii++] = d;\n          indices[ii++] = c;\n        }\n      }\n    }\n\n    super({\n      ...resolvedOptions,\n      positions,\n      normals,\n      uvs,\n      indices,\n    });\n  }\n}\n","import { clampSegments } from './clampSegments';\n\ninterface CylinderBuffers {\n  positions: Float32Array;\n  normals: Float32Array;\n  uvs: Float32Array;\n  indices: Uint16Array | Uint32Array;\n}\n\n/** @internal */\nexport function buildCylinderBuffers(\n  radiusTop: number,\n  radiusBottom: number,\n  height: number,\n  rawRadialSegments: number,\n  rawHeightSegments: number,\n  openEnded: boolean,\n): CylinderBuffers {\n  const radialSegments = clampSegments(rawRadialSegments, 3);\n  const heightSegments = clampSegments(rawHeightSegments, 1);\n\n  const halfHeight = height * 0.5;\n  const slope = (radiusBottom - radiusTop) / height;\n  const normalLength = Math.sqrt(1 + slope * slope);\n  const invNormalLength = 1 / normalLength;\n  const slopeNormal = slope * invNormalLength;\n\n  const invRadial = 1 / radialSegments;\n  const invHeight = 1 / heightSegments;\n  const radialStride = radialSegments + 1;\n\n  const sinTable = new Float32Array(radialStride);\n  const cosTable = new Float32Array(radialStride);\n  const angleStep = Math.PI * 2 * invRadial;\n  for (let i = 0; i < radialStride; i++) {\n    const theta = i * angleStep;\n    sinTable[i] = Math.sin(theta);\n    cosTable[i] = Math.cos(theta);\n  }\n\n  const topApex = radiusTop === 0;\n  const bottomApex = radiusBottom === 0;\n\n  const sideVertCount = radialStride * (heightSegments + 1);\n  const fullSideIndexCount = radialSegments * heightSegments * 6;\n  const apexSavings = (topApex ? radialSegments * 3 : 0) + (bottomApex ? radialSegments * 3 : 0);\n  const sideIndexCount = fullSideIndexCount - apexSavings;\n\n  const hasTopCap = !openEnded && !topApex;\n  const hasBottomCap = !openEnded && !bottomApex;\n  const topCapVertCount = hasTopCap ? radialStride + 1 : 0;\n  const bottomCapVertCount = hasBottomCap ? radialStride + 1 : 0;\n  const topCapIndexCount = hasTopCap ? radialSegments * 3 : 0;\n  const bottomCapIndexCount = hasBottomCap ? radialSegments * 3 : 0;\n\n  const vertCount = sideVertCount + topCapVertCount + bottomCapVertCount;\n  const indexCount = sideIndexCount + topCapIndexCount + bottomCapIndexCount;\n\n  const positions = new Float32Array(vertCount * 3);\n  const normals = new Float32Array(vertCount * 3);\n  const uvs = new Float32Array(vertCount * 2);\n  const IndexArray = vertCount > 65536 ? Uint32Array : Uint16Array;\n  const indices = new IndexArray(indexCount);\n\n  let pi = 0;\n  let ni = 0;\n  let ui = 0;\n  let ii = 0;\n\n  for (let y = 0; y <= heightSegments; y++) {\n    const v = y * invHeight;\n    const radius = v * (radiusBottom - radiusTop) + radiusTop;\n    const posY = halfHeight - v * height;\n\n    for (let x = 0; x <= radialSegments; x++) {\n      const u = x * invRadial;\n      const sinTheta = sinTable[x];\n      const cosTheta = cosTable[x];\n\n      positions[pi++] = radius * cosTheta;\n      positions[pi++] = posY;\n      positions[pi++] = radius * sinTheta;\n\n      normals[ni++] = cosTheta * invNormalLength;\n      normals[ni++] = slopeNormal;\n      normals[ni++] = sinTheta * invNormalLength;\n\n      uvs[ui++] = u;\n      uvs[ui++] = v;\n    }\n  }\n\n  for (let y = 0; y < heightSegments; y++) {\n    const apexAtTop = topApex && y === 0;\n    const apexAtBottom = bottomApex && y === heightSegments - 1;\n\n    for (let x = 0; x < radialSegments; x++) {\n      const a = y * radialStride + x;\n      const b = a + 1;\n      const c = a + radialStride;\n      const d = c + 1;\n\n      if (!apexAtTop) {\n        indices[ii++] = a;\n        indices[ii++] = b;\n        indices[ii++] = c;\n      }\n      if (!apexAtBottom) {\n        indices[ii++] = b;\n        indices[ii++] = d;\n        indices[ii++] = c;\n      }\n    }\n  }\n\n  if (hasTopCap) {\n    const centerIndex = pi / 3;\n\n    positions[pi++] = 0;\n    positions[pi++] = halfHeight;\n    positions[pi++] = 0;\n    normals[ni++] = 0;\n    normals[ni++] = 1;\n    normals[ni++] = 0;\n    uvs[ui++] = 0.5;\n    uvs[ui++] = 0.5;\n\n    for (let x = 0; x <= radialSegments; x++) {\n      const cosTheta = cosTable[x];\n      const sinTheta = sinTable[x];\n\n      positions[pi++] = radiusTop * cosTheta;\n      positions[pi++] = halfHeight;\n      positions[pi++] = radiusTop * sinTheta;\n      normals[ni++] = 0;\n      normals[ni++] = 1;\n      normals[ni++] = 0;\n      uvs[ui++] = cosTheta * 0.5 + 0.5;\n      uvs[ui++] = sinTheta * 0.5 + 0.5;\n    }\n\n    for (let x = 0; x < radialSegments; x++) {\n      indices[ii++] = centerIndex;\n      indices[ii++] = centerIndex + x + 2;\n      indices[ii++] = centerIndex + x + 1;\n    }\n  }\n\n  if (hasBottomCap) {\n    const centerIndex = pi / 3;\n\n    positions[pi++] = 0;\n    positions[pi++] = -halfHeight;\n    positions[pi++] = 0;\n    normals[ni++] = 0;\n    normals[ni++] = -1;\n    normals[ni++] = 0;\n    uvs[ui++] = 0.5;\n    uvs[ui++] = 0.5;\n\n    for (let x = 0; x <= radialSegments; x++) {\n      const cosTheta = cosTable[x];\n      const sinTheta = sinTable[x];\n\n      positions[pi++] = radiusBottom * cosTheta;\n      positions[pi++] = -halfHeight;\n      positions[pi++] = radiusBottom * sinTheta;\n      normals[ni++] = 0;\n      normals[ni++] = -1;\n      normals[ni++] = 0;\n      uvs[ui++] = cosTheta * 0.5 + 0.5;\n      uvs[ui++] = sinTheta * 0.5 + 0.5;\n    }\n\n    for (let x = 0; x < radialSegments; x++) {\n      indices[ii++] = centerIndex;\n      indices[ii++] = centerIndex + x + 1;\n      indices[ii++] = centerIndex + x + 2;\n    }\n  }\n\n  return { positions, normals, uvs, indices };\n}\n","import { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\nimport { buildCylinderBuffers } from './utils/buildCylinderBuffers';\n\n/**\n * Options for {@link ConeGeometry}\n * @example\n * ```ts\n * const options: Partial<ConeGeometryOptions> = { radius: 0.5, height: 1 };\n * const cone = new ConeGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface ConeGeometryOptions extends Geometry3DOptions {\n  /**\n   * The radius of the base ring (at `-height/2`)\n   * @default 1\n   * @example\n   * ```ts\n   * const wide = new ConeGeometry({ radius: 2 });\n   * ```\n   */\n  radius: number;\n  /**\n   * The total height of the cone along the Y axis\n   * @default 2\n   * @example\n   * ```ts\n   * const spike = new ConeGeometry({ radius: 0.2, height: 3 });\n   * ```\n   */\n  height: number;\n  /**\n   * The number of segments around the circumference\n   *\n   * Floored, and clamped to a minimum of 3.\n   * @default 32\n   * @example\n   * ```ts\n   * const pyramid = new ConeGeometry({ radialSegments: 4 });\n   * ```\n   */\n  radialSegments: number;\n  /**\n   * The number of segments along the height\n   *\n   * Floored, and clamped to a minimum of 1.\n   * @default 1\n   * @example\n   * ```ts\n   * const bendable = new ConeGeometry({ heightSegments: 8 });\n   * ```\n   */\n  heightSegments: number;\n  /**\n   * When `true`, the base cap is skipped and only the side surface is generated\n   * @default false\n   * @example\n   * ```ts\n   * const funnel = new ConeGeometry({ openEnded: true });\n   * ```\n   */\n  openEnded: boolean;\n}\n\n/**\n * A cone geometry oriented along the +Y axis and centered on the origin, with the apex at\n * `+height/2` and the base ring at `-height/2`\n *\n * Side normals are smooth and follow the slope. UVs wrap once around the circumference (`u` from\n * 0 to 1), and `v` runs from 0 at the apex to 1 at the base.\n * @example\n * ```ts\n * const cone = new ConeGeometry({\n *   radius: 1,\n *   height: 2,\n *   radialSegments: 32,\n *   heightSegments: 1,\n *   openEnded: false,\n * });\n * ```\n * @see {@link CylinderGeometry} For a cone with its top cut off\n * @category geometry\n * @standard\n */\nexport class ConeGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `ConeGeometry`\n   * @example\n   * ```ts\n   * ConeGeometry.defaultOptions.radialSegments = 16;\n   * ```\n   */\n  public static defaultOptions: ConeGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    radius: 1,\n    height: 2,\n    radialSegments: 32,\n    heightSegments: 1,\n    openEnded: false,\n  };\n\n  /**\n   * Creates a new `ConeGeometry`\n   * @param options - See {@link ConeGeometryOptions} for available options\n   */\n  constructor(options: Partial<ConeGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...ConeGeometry.defaultOptions,\n      ...options,\n    };\n    const { radius, height, radialSegments, heightSegments, openEnded } = resolvedOptions;\n    const buffers = buildCylinderBuffers(0, radius, height, radialSegments, heightSegments, openEnded);\n\n    super({\n      ...resolvedOptions,\n      ...buffers,\n    });\n  }\n}\n","import { Box } from '../math/shapes/Box';\nimport { Vector3 } from '../math/vector/Vector3';\nimport { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\nimport { clampSegments } from './utils/clampSegments';\n\n/**\n * Options for {@link CubeGeometry}\n * @example\n * ```ts\n * const options: Partial<CubeGeometryOptions> = { width: 2, height: 1, depth: 1 };\n * const brick = new CubeGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface CubeGeometryOptions extends Geometry3DOptions {\n  /**\n   * The full extent of the cube along the local X axis\n   * @default 1\n   * @example\n   * ```ts\n   * const plank = new CubeGeometry({ width: 4, height: 0.1 });\n   * ```\n   */\n  width: number;\n  /**\n   * The full extent of the cube along the local Y axis\n   * @default 1\n   * @example\n   * ```ts\n   * const pillar = new CubeGeometry({ height: 5 });\n   * ```\n   */\n  height: number;\n  /**\n   * The full extent of the cube along the local Z axis\n   * @default 1\n   * @example\n   * ```ts\n   * const wall = new CubeGeometry({ width: 10, height: 3, depth: 0.2 });\n   * ```\n   */\n  depth: number;\n  /**\n   * Subdivision count along the X axis; applied to the front, back, top and bottom faces\n   *\n   * Floored, and clamped to a minimum of 1.\n   * @default 1\n   * @example\n   * ```ts\n   * const ribbed = new CubeGeometry({ width: 4, widthSegments: 16 });\n   * ```\n   */\n  widthSegments: number;\n  /**\n   * Subdivision count along the Y axis; applied to the front, back, left and right faces\n   *\n   * Floored, and clamped to a minimum of 1.\n   * @default 1\n   * @example\n   * ```ts\n   * const tower = new CubeGeometry({ height: 8, heightSegments: 8 });\n   * ```\n   */\n  heightSegments: number;\n  /**\n   * Subdivision count along the Z axis; applied to the top, bottom, left and right faces\n   *\n   * Floored, and clamped to a minimum of 1.\n   * @default 1\n   * @example\n   * ```ts\n   * const corridor = new CubeGeometry({ depth: 20, depthSegments: 20 });\n   * ```\n   */\n  depthSegments: number;\n}\n\n/**\n * A box geometry with six axis-aligned faces, centered on the origin\n *\n * Faces share no vertices, so the edges light hard. Each face's UVs run from (0, 0) at its\n * bottom-left to (1, 1) at its top-right. As on a default {@link PlaneGeometry}, `v` grows upward,\n * so an image texture shows upside down on the side faces.\n * @example\n * ```ts\n * const cube = new CubeGeometry({\n *   width: 1,\n *   height: 1,\n *   depth: 1,\n *   widthSegments: 1,\n *   heightSegments: 1,\n *   depthSegments: 1,\n * });\n * ```\n * @category geometry\n * @standard\n */\nexport class CubeGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `CubeGeometry`\n   * @example\n   * ```ts\n   * CubeGeometry.defaultOptions.width = 2;\n   * ```\n   */\n  public static defaultOptions: CubeGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    width: 1,\n    height: 1,\n    depth: 1,\n    widthSegments: 1,\n    heightSegments: 1,\n    depthSegments: 1,\n  };\n\n  /**\n   * Creates a new `CubeGeometry`\n   * @param options - See {@link CubeGeometryOptions} for available options\n   */\n  constructor(options: Partial<CubeGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...CubeGeometry.defaultOptions,\n      ...options,\n    };\n    const { width, height, depth } = resolvedOptions;\n    const widthSegments = clampSegments(resolvedOptions.widthSegments, 1);\n    const heightSegments = clampSegments(resolvedOptions.heightSegments, 1);\n    const depthSegments = clampSegments(resolvedOptions.depthSegments, 1);\n\n    const halfW = width / 2;\n    const halfH = height / 2;\n    const halfD = depth / 2;\n\n    const vertCount =\n      2 * ((widthSegments + 1) * (heightSegments + 1)) +\n      2 * ((widthSegments + 1) * (depthSegments + 1)) +\n      2 * ((depthSegments + 1) * (heightSegments + 1));\n    const idxCount =\n      2 * (widthSegments * heightSegments * 6) +\n      2 * (widthSegments * depthSegments * 6) +\n      2 * (depthSegments * heightSegments * 6);\n\n    const positions = new Float32Array(vertCount * 3);\n    const normals = new Float32Array(vertCount * 3);\n    const uvs = new Float32Array(vertCount * 2);\n    const indices = vertCount <= 65536 ? new Uint16Array(idxCount) : new Uint32Array(idxCount);\n\n    const offsets = { pos: 0, nrm: 0, uv: 0, idx: 0, vert: 0 };\n\n    const addFace = (corners: number[][], nx: number, ny: number, nz: number, segmentsX: number, segmentsY: number) => {\n      const startIndex = offsets.vert;\n      const rowSize = segmentsX + 1;\n\n      const c00x = corners[0][0];\n      const c00y = corners[0][1];\n      const c00z = corners[0][2];\n      const c10x = corners[1][0];\n      const c10y = corners[1][1];\n      const c10z = corners[1][2];\n      const c11x = corners[2][0];\n      const c11y = corners[2][1];\n      const c11z = corners[2][2];\n      const c01x = corners[3][0];\n      const c01y = corners[3][1];\n      const c01z = corners[3][2];\n\n      let posOffset = offsets.pos;\n      let nrmOffset = offsets.nrm;\n      let uvOffset = offsets.uv;\n\n      for (let y = 0; y <= segmentsY; y++) {\n        const v = y / segmentsY;\n        const leftX = c00x + (c01x - c00x) * v;\n        const leftY = c00y + (c01y - c00y) * v;\n        const leftZ = c00z + (c01z - c00z) * v;\n        const rightX = c10x + (c11x - c10x) * v;\n        const rightY = c10y + (c11y - c10y) * v;\n        const rightZ = c10z + (c11z - c10z) * v;\n\n        for (let x = 0; x <= segmentsX; x++) {\n          const u = x / segmentsX;\n\n          positions[posOffset++] = leftX + (rightX - leftX) * u;\n          positions[posOffset++] = leftY + (rightY - leftY) * u;\n          positions[posOffset++] = leftZ + (rightZ - leftZ) * u;\n\n          normals[nrmOffset++] = nx;\n          normals[nrmOffset++] = ny;\n          normals[nrmOffset++] = nz;\n\n          uvs[uvOffset++] = u;\n          uvs[uvOffset++] = v;\n        }\n      }\n\n      offsets.pos = posOffset;\n      offsets.nrm = nrmOffset;\n      offsets.uv = uvOffset;\n      offsets.vert = startIndex + rowSize * (segmentsY + 1);\n\n      let idxOffset = offsets.idx;\n      for (let y = 0; y < segmentsY; y++) {\n        const rowOffset0 = startIndex + y * rowSize;\n        const rowOffset1 = rowOffset0 + rowSize;\n\n        for (let x = 0; x < segmentsX; x++) {\n          const a = rowOffset0 + x;\n          const b = a + 1;\n          const d = rowOffset1 + x;\n          const c = d + 1;\n\n          indices[idxOffset++] = a;\n          indices[idxOffset++] = b;\n          indices[idxOffset++] = c;\n          indices[idxOffset++] = a;\n          indices[idxOffset++] = c;\n          indices[idxOffset++] = d;\n        }\n      }\n      offsets.idx = idxOffset;\n    };\n\n    addFace(\n      [\n        [-halfW, -halfH, halfD],\n        [halfW, -halfH, halfD],\n        [halfW, halfH, halfD],\n        [-halfW, halfH, halfD],\n      ],\n      0,\n      0,\n      1,\n      widthSegments,\n      heightSegments,\n    );\n\n    addFace(\n      [\n        [halfW, -halfH, -halfD],\n        [-halfW, -halfH, -halfD],\n        [-halfW, halfH, -halfD],\n        [halfW, halfH, -halfD],\n      ],\n      0,\n      0,\n      -1,\n      widthSegments,\n      heightSegments,\n    );\n\n    addFace(\n      [\n        [-halfW, halfH, halfD],\n        [halfW, halfH, halfD],\n        [halfW, halfH, -halfD],\n        [-halfW, halfH, -halfD],\n      ],\n      0,\n      1,\n      0,\n      widthSegments,\n      depthSegments,\n    );\n\n    addFace(\n      [\n        [-halfW, -halfH, -halfD],\n        [halfW, -halfH, -halfD],\n        [halfW, -halfH, halfD],\n        [-halfW, -halfH, halfD],\n      ],\n      0,\n      -1,\n      0,\n      widthSegments,\n      depthSegments,\n    );\n\n    addFace(\n      [\n        [halfW, -halfH, halfD],\n        [halfW, -halfH, -halfD],\n        [halfW, halfH, -halfD],\n        [halfW, halfH, halfD],\n      ],\n      1,\n      0,\n      0,\n      depthSegments,\n      heightSegments,\n    );\n\n    addFace(\n      [\n        [-halfW, -halfH, -halfD],\n        [-halfW, -halfH, halfD],\n        [-halfW, halfH, halfD],\n        [-halfW, halfH, -halfD],\n      ],\n      -1,\n      0,\n      0,\n      depthSegments,\n      heightSegments,\n    );\n\n    const bounds3D =\n      resolvedOptions.bounds3D ?? new Box(new Vector3(-halfW, -halfH, -halfD), new Vector3(halfW, halfH, halfD));\n\n    super({\n      ...resolvedOptions,\n      bounds3D,\n      positions,\n      normals,\n      uvs,\n      indices,\n    });\n  }\n}\n","import { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\nimport { buildCylinderBuffers } from './utils/buildCylinderBuffers';\n\n/**\n * Options for {@link CylinderGeometry}\n * @example\n * ```ts\n * const options: Partial<CylinderGeometryOptions> = { radiusTop: 0.5, radiusBottom: 0.5, height: 3 };\n * const column = new CylinderGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface CylinderGeometryOptions extends Geometry3DOptions {\n  /**\n   * The radius of the top ring, at `+height/2`; `0` collapses it to a point\n   * @default 1\n   * @example\n   * ```ts\n   * const bucket = new CylinderGeometry({ radiusTop: 1, radiusBottom: 0.7 });\n   * ```\n   */\n  radiusTop: number;\n  /**\n   * The radius of the bottom ring, at `-height/2`; `0` collapses it to a point\n   * @default 1\n   * @example\n   * ```ts\n   * const lampshade = new CylinderGeometry({ radiusTop: 0.4, radiusBottom: 1, openEnded: true });\n   * ```\n   */\n  radiusBottom: number;\n  /**\n   * The total height of the cylinder along the Y axis\n   * @default 2\n   * @example\n   * ```ts\n   * const coin = new CylinderGeometry({ height: 0.1 });\n   * ```\n   */\n  height: number;\n  /**\n   * The number of segments around the circumference\n   *\n   * Floored, and clamped to a minimum of 3.\n   * @default 32\n   * @example\n   * ```ts\n   * const hexPrism = new CylinderGeometry({ radialSegments: 6 });\n   * ```\n   */\n  radialSegments: number;\n  /**\n   * The number of segments along the height\n   *\n   * Floored, and clamped to a minimum of 1.\n   * @default 1\n   * @example\n   * ```ts\n   * const bendable = new CylinderGeometry({ height: 6, heightSegments: 24 });\n   * ```\n   */\n  heightSegments: number;\n  /**\n   * When `true`, the end caps are skipped and only the side surface is generated\n   * @default false\n   * @example\n   * ```ts\n   * const tube = new CylinderGeometry({ openEnded: true });\n   * ```\n   */\n  openEnded: boolean;\n}\n\n/**\n * A cylinder geometry oriented along the +Y axis and centered on the origin, with the top ring at\n * `+height/2` and the bottom ring at `-height/2`\n *\n * Unequal radii make a truncated cone. The side's normals are smooth and follow the slope between\n * the two radii. Its UVs wrap once around the circumference (`u` from 0 to 1), and `v` runs from 0\n * at the top to 1 at the bottom. A cap's UVs map it onto the circle inscribed in the texture.\n * @example\n * ```ts\n * const cylinder = new CylinderGeometry({\n *   radiusTop: 1,\n *   radiusBottom: 1,\n *   height: 2,\n *   radialSegments: 32,\n *   heightSegments: 1,\n *   openEnded: false,\n * });\n * ```\n * @see {@link CapsuleGeometry} For rounded caps instead of flat ends\n * @category geometry\n * @standard\n */\nexport class CylinderGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `CylinderGeometry`\n   * @example\n   * ```ts\n   * CylinderGeometry.defaultOptions.radialSegments = 16;\n   * ```\n   */\n  public static defaultOptions: CylinderGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    radiusTop: 1,\n    radiusBottom: 1,\n    height: 2,\n    radialSegments: 32,\n    heightSegments: 1,\n    openEnded: false,\n  };\n\n  /**\n   * Creates a new `CylinderGeometry`\n   * @param options - See {@link CylinderGeometryOptions} for available options\n   */\n  constructor(options: Partial<CylinderGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...CylinderGeometry.defaultOptions,\n      ...options,\n    };\n    const { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded } = resolvedOptions;\n    const buffers = buildCylinderBuffers(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded);\n\n    super({\n      ...resolvedOptions,\n      ...buffers,\n    });\n  }\n}\n","import { BufferUsage, getAttributeInfoFromFormat, Geometry, uid } from 'pixi.js';\nimport type { VertexFormat } from 'pixi.js';\n\nimport { Buffer3D } from '../core/buffers/Buffer3D';\nimport type { Geometry3D } from './Geometry3D';\nimport { alignTo4Bytes } from './utils/Geometry3DUtils';\n\n/** @internal */\nexport interface GeometryAllocation {\n  atlas: GeometryAtlas;\n  baseVertex: number;\n  firstIndex: number;\n  indexCount: number;\n  vertexCount: number;\n}\n\nconst DEFAULT_VERTEX_CAPACITY = 1024;\nconst DEFAULT_INDEX_CAPACITY = 2048;\n\ninterface GeometryAtlasOptions {\n  referenceGeometry: Geometry3D;\n  initialVertexCapacity?: number;\n  initialIndexCapacity?: number;\n  rebaseIndices?: boolean;\n}\n\n/** @internal */\nexport class GeometryAtlas {\n  public readonly uid: number = uid('geometryAtlas');\n\n  public readonly attributeKey: string;\n\n  public readonly vertexStride: number = 0;\n\n  private _vertexBuffer: Buffer3D;\n  private _indexBuffer: Buffer3D;\n  /** Buffers growth replaced, kept until `destroy` because draws recorded earlier in the frame may still read them */\n  private readonly _retiredBuffers: Buffer3D[] = [];\n  /** Kept until `destroy`, like `_retiredBuffers` */\n  private readonly _retiredGeometries: Geometry[] = [];\n  private _vertexCount = 0;\n  private _indexCount = 0;\n  private _deadVertexCount = 0;\n  private _deadIndexCount = 0;\n\n  /** In offset order, which `defragment`'s in-place slide relies on */\n  private readonly _liveAllocations: GeometryAllocation[] = [];\n\n  private _vertexDirtyMin = Infinity;\n  private _vertexDirtyMax = -Infinity;\n  private _indexDirtyMin = Infinity;\n  private _indexDirtyMax = -Infinity;\n\n  /**\n   * Bumped when growth or a compaction leaves draw commands recorded against the atlas stale\n   * @internal\n   */\n  public _bufferVersion = 0;\n\n  public geometry: Geometry;\n\n  private readonly _attributeInfo: { name: string; format: VertexFormat; offset: number; byteSize: number }[];\n\n  /** Whether `add` bakes `baseVertex` into the index values, for WebGL 2, which has no `baseVertex` draw parameter */\n  public readonly rebaseIndices: boolean;\n\n  constructor(options: GeometryAtlasOptions) {\n    const {\n      referenceGeometry,\n      initialVertexCapacity = DEFAULT_VERTEX_CAPACITY,\n      initialIndexCapacity = DEFAULT_INDEX_CAPACITY,\n      rebaseIndices = false,\n    } = options;\n\n    this.rebaseIndices = rebaseIndices;\n\n    this.attributeKey = referenceGeometry.attributeKey;\n\n    const attrs = referenceGeometry.attributes;\n    const sortedKeys = Object.keys(attrs).sort();\n\n    if (!sortedKeys.some((k) => !attrs[k].instance)) {\n      throw new Error('GeometryAtlas: reference geometry has no vertex attributes');\n    }\n\n    let computedStride = 0;\n\n    this._attributeInfo = [];\n\n    for (const name of sortedKeys) {\n      const srcAttr = attrs[name];\n\n      if (srcAttr.instance) continue;\n\n      const format = srcAttr.format!;\n      const byteSize = getAttributeInfoFromFormat(format).stride;\n\n      computedStride = alignTo4Bytes(computedStride);\n      const offset = computedStride;\n\n      computedStride += byteSize;\n\n      this._attributeInfo.push({ name, format, offset, byteSize });\n    }\n\n    this.vertexStride = alignTo4Bytes(computedStride);\n\n    this._vertexBuffer = new Buffer3D({\n      data: new Uint8Array(initialVertexCapacity * this.vertexStride),\n      usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,\n      label: 'GeometryAtlas-vertex',\n      shrinkToFit: false,\n    });\n\n    this._indexBuffer = new Buffer3D({\n      data: new Uint32Array(initialIndexCapacity),\n      usage: BufferUsage.INDEX | BufferUsage.COPY_DST,\n      label: 'GeometryAtlas-index',\n      shrinkToFit: false,\n    });\n\n    this.geometry = this._buildMergedGeometry();\n  }\n\n  /**\n   * Copies through `Uint32Array` views, as a float copy alters quantized normals that read as NaN. The\n   * word copy is unrolled to four words, the largest vertex format, because that beats an inner loop\n   */\n  public add(geometry: Geometry3D): GeometryAllocation {\n    const existing = geometry._geometryAtlasAllocation;\n    if (existing && existing.atlas === this) return existing;\n\n    for (const name in geometry.attributes) {\n      if (geometry.attributes[name].instance) {\n        throw new Error(\n          `GeometryAtlas: Cannot add geometry with instance attribute \"${name}\". ` +\n            `The Atlas is for merging vertex data only; instance data would be lost.`,\n        );\n      }\n    }\n\n    if (geometry.attributeKey !== this.attributeKey) {\n      throw new Error(\n        `GeometryAtlas: attribute structure mismatch. Expected \"${this.attributeKey}\", got \"${geometry.attributeKey}\"`,\n      );\n    }\n\n    const vertexCount = geometry.vertexCount;\n    const srcIndices = geometry.indexBuffer.data;\n    const indexCount = srcIndices.length;\n\n    const vertexCapacity = this._vertexBuffer.data.byteLength / this.vertexStride;\n    const indexCapacity = this._indexBuffer.data.length;\n\n    const needsVertexRoom = this._vertexCount + vertexCount > vertexCapacity;\n    const needsIndexRoom = this._indexCount + indexCount > indexCapacity;\n\n    if (needsVertexRoom || needsIndexRoom) {\n      const liveVertices = this._vertexCount - this._deadVertexCount;\n      const liveIndices = this._indexCount - this._deadIndexCount;\n      const vertexFits = liveVertices + vertexCount <= vertexCapacity;\n      const indexFits = liveIndices + indexCount <= indexCapacity;\n\n      if (vertexFits && indexFits) {\n        this.defragment();\n      } else {\n        if (this._deadVertexCount > 0 || this._deadIndexCount > 0) {\n          this.defragment();\n        }\n        this._ensureVertexCapacity(this._vertexCount + vertexCount);\n        this._ensureIndexCapacity(this._indexCount + indexCount);\n      }\n    }\n\n    const baseVertex = this._vertexCount;\n    const firstIndex = this._indexCount;\n    this._vertexCount += vertexCount;\n    this._indexCount += indexCount;\n\n    const vertexData = this._vertexBuffer.data;\n    const indexData = this._indexBuffer.data;\n    const vertexStride = this.vertexStride;\n    const dstByteOffset = baseVertex * vertexStride;\n    const byteLength = vertexCount * vertexStride;\n\n    if (this._matchesAtlasLayout(geometry)) {\n      const src = geometry.attributes[this._attributeInfo[0].name].buffer.data;\n      vertexData.set(new Uint8Array(src.buffer, src.byteOffset, byteLength), dstByteOffset);\n    } else {\n      const vertexWords = new Uint32Array(vertexData.buffer);\n\n      for (const { name, offset, byteSize } of this._attributeInfo) {\n        const attr = geometry.attributes[name];\n        const data = attr.buffer.data;\n        const srcStride = attr.stride ?? byteSize;\n        const srcOffset = attr.offset ?? 0;\n\n        if (((data.byteOffset | srcOffset | srcStride | byteSize) & 3) === 0) {\n          const srcWords = new Uint32Array(data.buffer, data.byteOffset, data.byteLength >> 2);\n          const srcStep = srcStride >> 2;\n          const dstStep = vertexStride >> 2;\n          let src = srcOffset >> 2;\n          let dst = (dstByteOffset + offset) >> 2;\n\n          for (let i = 0; i < vertexCount; i++) {\n            vertexWords[dst] = srcWords[src];\n            if (byteSize > 4) vertexWords[dst + 1] = srcWords[src + 1];\n            if (byteSize > 8) vertexWords[dst + 2] = srcWords[src + 2];\n            if (byteSize > 12) vertexWords[dst + 3] = srcWords[src + 3];\n            src += srcStep;\n            dst += dstStep;\n          }\n        } else {\n          const srcBytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n          let src = srcOffset;\n          let dst = dstByteOffset + offset;\n\n          for (let i = 0; i < vertexCount; i++) {\n            for (let b = 0; b < byteSize; b++) vertexData[dst + b] = srcBytes[src + b];\n            src += srcStride;\n            dst += vertexStride;\n          }\n        }\n      }\n    }\n\n    this._markVertexDirty(dstByteOffset, dstByteOffset + byteLength);\n\n    if (this.rebaseIndices) {\n      for (let i = 0; i < indexCount; i++) {\n        indexData[firstIndex + i] = srcIndices[i] + baseVertex;\n      }\n    } else {\n      indexData.set(srcIndices, firstIndex);\n    }\n\n    this._markIndexDirty(firstIndex, firstIndex + indexCount);\n\n    const allocation: GeometryAllocation = {\n      atlas: this,\n      baseVertex,\n      firstIndex,\n      indexCount,\n      vertexCount,\n    };\n\n    geometry._geometryAtlasAllocation = allocation;\n    geometry._atlasVacated = false;\n    this._liveAllocations.push(allocation);\n    return allocation;\n  }\n\n  /**\n   * Doesn't version the atlas, since the range keeps its bytes until a compaction; on a destroyed atlas it only\n   * clears the geometry's allocation\n   */\n  public remove(geometry: Geometry3D): void {\n    const alloc = geometry._geometryAtlasAllocation;\n    if (!alloc) return;\n\n    geometry._geometryAtlasAllocation = null;\n    geometry._atlasVacated = true;\n    if (this._vertexBuffer === null) return;\n\n    this._deadVertexCount += alloc.vertexCount;\n    this._deadIndexCount += alloc.indexCount;\n\n    const idx = this._liveAllocations.indexOf(alloc);\n    if (idx !== -1) this._liveAllocations.splice(idx, 1);\n  }\n\n  public update(): void {\n    if (this._vertexDirtyMin < this._vertexDirtyMax) {\n      const size = this._vertexDirtyMax - this._vertexDirtyMin;\n      this._vertexBuffer.update(size, this._vertexDirtyMin);\n      this._vertexDirtyMin = Infinity;\n      this._vertexDirtyMax = -Infinity;\n    }\n\n    if (this._indexDirtyMin < this._indexDirtyMax) {\n      const offsetBytes = this._indexDirtyMin * 4;\n      const sizeBytes = (this._indexDirtyMax - this._indexDirtyMin) * 4;\n      this._indexBuffer.update(sizeBytes, offsetBytes);\n      this._indexDirtyMin = Infinity;\n      this._indexDirtyMax = -Infinity;\n    }\n  }\n\n  private _matchesAtlasLayout(geometry: Geometry3D): boolean {\n    const attributes = geometry.attributes;\n    const buffer = attributes[this._attributeInfo[0].name].buffer;\n\n    for (const info of this._attributeInfo) {\n      const attr = attributes[info.name];\n\n      if (attr.buffer !== buffer || attr.stride !== this.vertexStride || (attr.offset ?? 0) !== info.offset) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  private _buildMergedGeometry(): Geometry {\n    const geo = new Geometry();\n\n    for (const { name, format, offset } of this._attributeInfo) {\n      geo.addAttribute(name, { buffer: this._vertexBuffer, format, stride: this.vertexStride, offset });\n    }\n\n    geo.addIndex(this._indexBuffer);\n\n    return geo;\n  }\n\n  private _markVertexDirty(startByte: number, endByte: number): void {\n    if (startByte < this._vertexDirtyMin) this._vertexDirtyMin = startByte;\n    if (endByte > this._vertexDirtyMax) this._vertexDirtyMax = endByte;\n  }\n\n  private _markIndexDirty(startIndex: number, endIndex: number): void {\n    if (startIndex < this._indexDirtyMin) this._indexDirtyMin = startIndex;\n    if (endIndex > this._indexDirtyMax) this._indexDirtyMax = endIndex;\n  }\n\n  private _retireCurrentGeometry(): void {\n    if (this.geometry) {\n      this.geometry.indexBuffer = null!;\n      this._retiredGeometries.push(this.geometry);\n    }\n  }\n\n  private _ensureVertexCapacity(requiredVertices: number): void {\n    const oldData = this._vertexBuffer.data;\n    let capacity = oldData.byteLength / this.vertexStride;\n    if (requiredVertices <= capacity) return;\n\n    while (capacity < requiredVertices) capacity *= 2;\n\n    const newData = new Uint8Array(capacity * this.vertexStride);\n    newData.set(oldData);\n\n    this._retiredBuffers.push(this._vertexBuffer);\n\n    this._vertexBuffer = new Buffer3D({\n      data: newData,\n      usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,\n      label: 'GeometryAtlas-vertex',\n      shrinkToFit: false,\n    });\n\n    this._markVertexDirty(0, this._vertexCount * this.vertexStride);\n\n    this._retireCurrentGeometry();\n    this.geometry = this._buildMergedGeometry();\n    this._bufferVersion++;\n  }\n\n  private _ensureIndexCapacity(requiredIndices: number): void {\n    const oldData = this._indexBuffer.data;\n    let capacity = oldData.length;\n    if (requiredIndices <= capacity) return;\n\n    while (capacity < requiredIndices) capacity *= 2;\n\n    const newData = new Uint32Array(capacity);\n    newData.set(oldData);\n\n    this._retiredBuffers.push(this._indexBuffer);\n\n    this._indexBuffer = new Buffer3D({\n      data: newData,\n      usage: BufferUsage.INDEX | BufferUsage.COPY_DST,\n      label: 'GeometryAtlas-index',\n      shrinkToFit: false,\n    });\n\n    this._markIndexDirty(0, this._indexCount);\n\n    this._retireCurrentGeometry();\n    this.geometry = this._buildMergedGeometry();\n    this._bufferVersion++;\n  }\n\n  /**\n   * Destroys the merged geometries without their buffers, which they share, then each buffer once. Packed\n   * geometries keep their allocations here, so `add` into another atlas copies them in afresh\n   */\n  public destroy(): void {\n    if (this._vertexBuffer === null) return;\n\n    if (this.geometry) this.geometry.indexBuffer = null!;\n    this.geometry?.destroy(false);\n    this.geometry = null!;\n\n    this._vertexBuffer.destroy();\n    this._indexBuffer.destroy();\n\n    for (let i = 0; i < this._retiredGeometries.length; i++) {\n      this._retiredGeometries[i].destroy(false);\n    }\n    (this._retiredGeometries as Geometry[] | null) = null;\n\n    for (let i = 0; i < this._retiredBuffers.length; i++) {\n      this._retiredBuffers[i].destroy();\n    }\n    (this._retiredBuffers as Buffer3D[] | null) = null;\n\n    this._vertexBuffer = null!;\n    this._indexBuffer = null!;\n\n    (this._liveAllocations as GeometryAllocation[] | null) = null;\n  }\n\n  /**\n   * Updates live allocations in place, and bumps `_bufferVersion` even for dead space only at the tail, which\n   * the next `add` overwrites while recorded commands may still read it\n   */\n  public defragment(): void {\n    if (this._deadVertexCount === 0 && this._deadIndexCount === 0) return;\n\n    const stride = this.vertexStride;\n    const vertexData = this._vertexBuffer.data;\n    const indexData = this._indexBuffer.data;\n    let writeVertex = 0;\n    let writeIndex = 0;\n\n    const rebase = this.rebaseIndices;\n\n    for (const alloc of this._liveAllocations) {\n      const oldBaseVertex = alloc.baseVertex;\n\n      if (oldBaseVertex !== writeVertex) {\n        const srcByte = oldBaseVertex * stride;\n        const dstByte = writeVertex * stride;\n        const byteLen = alloc.vertexCount * stride;\n        vertexData.copyWithin(dstByte, srcByte, srcByte + byteLen);\n        alloc.baseVertex = writeVertex;\n      }\n      writeVertex += alloc.vertexCount;\n\n      if (alloc.firstIndex !== writeIndex) {\n        indexData.copyWithin(writeIndex, alloc.firstIndex, alloc.firstIndex + alloc.indexCount);\n        alloc.firstIndex = writeIndex;\n      }\n\n      if (rebase && oldBaseVertex !== alloc.baseVertex) {\n        const delta = alloc.baseVertex - oldBaseVertex;\n        for (let i = 0; i < alloc.indexCount; i++) {\n          indexData[alloc.firstIndex + i] += delta;\n        }\n      }\n\n      writeIndex += alloc.indexCount;\n    }\n\n    this._markVertexDirty(0, writeVertex * stride);\n    this._markIndexDirty(0, writeIndex);\n\n    this._vertexCount = writeVertex;\n    this._indexCount = writeIndex;\n    this._deadVertexCount = 0;\n    this._deadIndexCount = 0;\n    this._bufferVersion++;\n  }\n}\n","import { GlobalResourceRegistry } from 'pixi.js';\n\nimport type { Geometry3D } from './Geometry3D';\nimport { GeometryAtlas } from './GeometryAtlas';\nimport type { GeometryAllocation } from './GeometryAtlas';\n\ninterface GeometryAtlasPoolOptions {\n  rebaseIndices: boolean;\n}\n\nconst sharedPools: Record<string, GeometryAtlasPool> = Object.create(null);\n\n/**\n * Outside tests, reach it through {@link GeometryAtlasPool.from}, which shares one pool per `rebaseIndices` value\n * @internal\n */\nexport class GeometryAtlasPool {\n  private _atlases: Record<string, GeometryAtlas> = Object.create(null);\n  private readonly _rebaseIndices: boolean;\n  private _bufferVersion = 0;\n\n  constructor(options: GeometryAtlasPoolOptions) {\n    this._rebaseIndices = options.rebaseIndices;\n  }\n\n  /**\n   * Shared by every renderer with the same `rebaseIndices`, since a geometry holds one allocation that two\n   * pools would each re-cut. No renderer destroys it; pixi's `GlobalResourceRegistry` clears it on\n   * `renderer.destroy(true)`\n   * @returns The shared pool\n   */\n  public static from(options: GeometryAtlasPoolOptions): GeometryAtlasPool {\n    const key = options.rebaseIndices ? 'rebased' : 'geometryLocal';\n    let pool = sharedPools[key];\n\n    if (!pool) {\n      pool = new GeometryAtlasPool(options);\n      sharedPools[key] = pool;\n      GlobalResourceRegistry.register(pool);\n    }\n\n    return pool;\n  }\n\n  /** Bumped when an `allocate` grows or compacts an atlas; a removal never bumps it */\n  get bufferVersion(): number {\n    return this._bufferVersion;\n  }\n\n  /**\n   * Reuses the geometry's allocation only when it's in this pool's atlas; one left in a destroyed or another\n   * pool's atlas is copied in afresh\n   */\n  public allocate(geometry: Geometry3D): GeometryAllocation {\n    const key = geometry.attributeKey;\n    let atlas = this._atlases[key];\n\n    const existing = geometry._geometryAtlasAllocation;\n    if (existing && existing.atlas === atlas) return existing;\n\n    if (!atlas) {\n      atlas = new GeometryAtlas({ referenceGeometry: geometry, rebaseIndices: this._rebaseIndices });\n      this._atlases[key] = atlas;\n    }\n\n    const atlasVersion = atlas._bufferVersion;\n    const allocation = atlas.add(geometry);\n    if (atlas._bufferVersion !== atlasVersion) this._bufferVersion++;\n\n    return allocation;\n  }\n\n  /** Uploads what this frame's `allocate` calls wrote, so call it after them and before drawing */\n  public update(): void {\n    for (const key in this._atlases) this._atlases[key].update();\n  }\n\n  /** Destroys every atlas, leaving the pool usable; named for pixi's `Cleanable`, which the registry calls */\n  public clear(): void {\n    for (const key in this._atlases) this._atlases[key].destroy();\n    this._atlases = Object.create(null);\n  }\n}\n","import { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\n\n/**\n * Options for {@link IcosahedronGeometry}\n * @example\n * ```ts\n * const options: Partial<IcosahedronGeometryOptions> = { radius: 2, detail: 3 };\n * const planet = new IcosahedronGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface IcosahedronGeometryOptions extends Geometry3DOptions {\n  /**\n   * The radius of the circumscribed sphere\n   * @default 1\n   * @example\n   * ```ts\n   * const gem = new IcosahedronGeometry({ radius: 0.25 });\n   * ```\n   */\n  radius: number;\n  /**\n   * The subdivision level\n   *\n   * `0` is the bare 20-face icosahedron, and each step quadruples the face count. The geometry has\n   * `10 * 4^detail + 2` vertices. Floored and clamped to 0 to 7, where 7 gives 163842 vertices; a\n   * value that isn't finite counts as 0.\n   * @default 0\n   * @example\n   * ```ts\n   * const smooth = new IcosahedronGeometry({ detail: 3 });\n   * ```\n   */\n  detail: number;\n}\n\n/** Keeps every vertex index below `0x100000`, which the midpoint cache key needs */\nconst MAX_DETAIL = 7;\n\n/**\n * An icosahedron geometry, the 20-faced regular polyhedron\n *\n * Raising `detail` makes a geodesic sphere with near-uniform faces, without the pinched poles of a\n * UV sphere. Normals point straight out from the center. UVs are equirectangular:\n * `u = 0.5 + atan2(nz, nx) / (2π)`, `v = 0.5 - asin(ny) / π`.\n * The vertices along the seam where `u` wraps from 1 back to 0 are shared, so the triangles that\n * cross it squeeze the whole texture into one strip. Use {@link SphereGeometry} for a textured\n * sphere.\n * @example\n * ```ts\n * const icosahedron = new IcosahedronGeometry({ radius: 1, detail: 0 });\n * const geodesicSphere = new IcosahedronGeometry({ radius: 1, detail: 2 });\n * ```\n * @category geometry\n * @standard\n */\nexport class IcosahedronGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `IcosahedronGeometry`\n   * @example\n   * ```ts\n   * IcosahedronGeometry.defaultOptions.detail = 2;\n   * ```\n   */\n  public static defaultOptions: IcosahedronGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    radius: 1,\n    detail: 0,\n  };\n\n  /**\n   * Creates a new `IcosahedronGeometry`\n   * @param options - See {@link IcosahedronGeometryOptions} for available options\n   */\n  constructor(options: Partial<IcosahedronGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...IcosahedronGeometry.defaultOptions,\n      ...options,\n    };\n    const { radius } = resolvedOptions;\n    const rawDetail = resolvedOptions.detail;\n    const detail = Number.isFinite(rawDetail) ? Math.max(0, Math.min(MAX_DETAIL, Math.floor(rawDetail))) : 0;\n\n    const t = (1 + Math.sqrt(5)) / 2;\n\n    const baseVertices = [\n      -1,\n      t,\n      0,\n      1,\n      t,\n      0,\n      -1,\n      -t,\n      0,\n      1,\n      -t,\n      0,\n      0,\n      -1,\n      t,\n      0,\n      1,\n      t,\n      0,\n      -1,\n      -t,\n      0,\n      1,\n      -t,\n      t,\n      0,\n      -1,\n      t,\n      0,\n      1,\n      -t,\n      0,\n      -1,\n      -t,\n      0,\n      1,\n    ];\n\n    const baseIndices = [\n      0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4,\n      2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1,\n    ];\n\n    const vertCount = 10 * 4 ** detail + 2;\n    const positions = new Float32Array(vertCount * 3);\n    const normals = new Float32Array(vertCount * 3);\n    const uvs = new Float32Array(vertCount * 2);\n    let vertexCount = 0;\n\n    const pushVertex = (x: number, y: number, z: number): number => {\n      const len = Math.sqrt(x * x + y * y + z * z);\n      const nx = x / len;\n      const ny = y / len;\n      const nz = z / len;\n\n      const index = vertexCount;\n      const p = index * 3;\n\n      positions[p] = nx * radius;\n      positions[p + 1] = ny * radius;\n      positions[p + 2] = nz * radius;\n\n      normals[p] = nx;\n      normals[p + 1] = ny;\n      normals[p + 2] = nz;\n\n      const u = 0.5 + Math.atan2(nz, nx) / (2 * Math.PI);\n      const v = 0.5 - Math.asin(ny) / Math.PI;\n      const uv = index * 2;\n      uvs[uv] = u;\n      uvs[uv + 1] = v;\n\n      vertexCount++;\n      return index;\n    };\n\n    for (let i = 0; i < baseVertices.length; i += 3) {\n      pushVertex(baseVertices[i], baseVertices[i + 1], baseVertices[i + 2]);\n    }\n\n    const midpointCache = new Map<number, number>();\n\n    const getMidpoint = (i1: number, i2: number): number => {\n      const lo = i1 < i2 ? i1 : i2;\n      const hi = i1 < i2 ? i2 : i1;\n      const key = lo * 0x100000 + hi;\n      const cached = midpointCache.get(key);\n\n      if (cached !== undefined) {\n        return cached;\n      }\n\n      const a = lo * 3;\n      const b = hi * 3;\n      const x = (positions[a] + positions[b]) / 2;\n      const y = (positions[a + 1] + positions[b + 1]) / 2;\n      const z = (positions[a + 2] + positions[b + 2]) / 2;\n\n      const index = pushVertex(x, y, z);\n\n      midpointCache.set(key, index);\n      return index;\n    };\n\n    let faces = new Uint32Array(baseIndices.length);\n\n    for (let i = 0; i < baseIndices.length; i++) {\n      faces[i] = baseIndices[i];\n    }\n\n    let faceCount = baseIndices.length / 3;\n\n    for (let d = 0; d < detail; d++) {\n      const newFaces = new Uint32Array(faceCount * 4 * 3);\n      let writeOffset = 0;\n\n      for (let f = 0; f < faceCount; f++) {\n        const readOffset = f * 3;\n        const a = faces[readOffset];\n        const b = faces[readOffset + 1];\n        const c = faces[readOffset + 2];\n\n        const ab = getMidpoint(a, b);\n        const bc = getMidpoint(b, c);\n        const ca = getMidpoint(c, a);\n\n        newFaces[writeOffset] = a;\n        newFaces[writeOffset + 1] = ab;\n        newFaces[writeOffset + 2] = ca;\n\n        newFaces[writeOffset + 3] = b;\n        newFaces[writeOffset + 4] = bc;\n        newFaces[writeOffset + 5] = ab;\n\n        newFaces[writeOffset + 6] = c;\n        newFaces[writeOffset + 7] = ca;\n        newFaces[writeOffset + 8] = bc;\n\n        newFaces[writeOffset + 9] = ab;\n        newFaces[writeOffset + 10] = bc;\n        newFaces[writeOffset + 11] = ca;\n\n        writeOffset += 12;\n      }\n\n      faces = newFaces;\n      faceCount *= 4;\n    }\n\n    const indexCount = faceCount * 3;\n    const indices = vertexCount > 65536 ? new Uint32Array(indexCount) : new Uint16Array(indexCount);\n\n    for (let i = 0; i < indexCount; i++) {\n      indices[i] = faces[i];\n    }\n\n    super({\n      ...resolvedOptions,\n      positions,\n      normals,\n      uvs,\n      indices,\n    });\n  }\n}\n","import { NOOP } from 'pixi.js';\n\nimport { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\nimport { clampSegments } from './utils/clampSegments';\n\n/**\n * Options for {@link PlaneGeometry}\n * @example\n * ```ts\n * const options: Partial<PlaneGeometryOptions> = { width: 16, height: 9, flipV: true };\n * const screen = new PlaneGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface PlaneGeometryOptions extends Geometry3DOptions {\n  /**\n   * The width of the plane along the local X axis\n   * @default 1\n   * @example\n   * ```ts\n   * const banner = new PlaneGeometry({ width: 4, height: 1 });\n   * ```\n   */\n  width: number;\n  /**\n   * The height of the plane along the local Y axis\n   * @default 1\n   * @example\n   * ```ts\n   * const poster = new PlaneGeometry({ width: 2, height: 3, flipV: true });\n   * ```\n   */\n  height: number;\n  /**\n   * Subdivision count along the width (X axis)\n   *\n   * Floored, and clamped to a minimum of 1.\n   * @default 1\n   * @example\n   * ```ts\n   * const water = new PlaneGeometry({ width: 50, height: 50, widthSegments: 128, heightSegments: 128 });\n   * ```\n   */\n  widthSegments: number;\n  /**\n   * Subdivision count along the height (Y axis)\n   *\n   * Floored, and clamped to a minimum of 1.\n   * @default 1\n   * @example\n   * ```ts\n   * const flag = new PlaneGeometry({ width: 3, height: 2, widthSegments: 30, heightSegments: 20 });\n   * ```\n   */\n  heightSegments: number;\n  /**\n   * Put `v = 0` on the top edge instead of the bottom, so an image texture shows the right way up\n   *\n   * Set it when the plane shows a picture, which otherwise renders upside down. Only the UVs change.\n   * @default false\n   * @example\n   * ```ts\n   * const photo = new PlaneGeometry({ width: 4, height: 3, flipV: true });\n   * ```\n   */\n  flipV: boolean;\n}\n\n/**\n * A flat plane geometry in the XY plane, centered on the origin and facing +Z\n *\n * Seen from behind it's culled, unless the material is `doubleSided`. UV (0, 0) sits at the\n * bottom-left corner and (1, 1) at the top-right; set `flipV` for an image texture. Subdivide it\n * with `widthSegments` and `heightSegments` when a vertex shader displaces the surface, as for\n * terrain, water or cloth.\n * @example\n * ```ts\n * const plane = new PlaneGeometry({\n *   width: 10,\n *   height: 10,\n *   widthSegments: 32,\n *   heightSegments: 32,\n * });\n * ```\n * @see {@link PlaneGeometry.spriteQuad} For a shared 1×1 quad set up for images\n * @category geometry\n * @standard\n */\nexport class PlaneGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `PlaneGeometry`\n   * @example\n   * ```ts\n   * PlaneGeometry.defaultOptions.flipV = true;\n   * ```\n   */\n  public static defaultOptions: PlaneGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    width: 1,\n    height: 1,\n    widthSegments: 1,\n    heightSegments: 1,\n    flipV: false,\n  };\n\n  /** Built on first read, so importing the module builds nothing */\n  private static _spriteQuad: PlaneGeometry | null = null;\n\n  /**\n   * The shared 1×1 quad every {@link Sprite3D} draws, built as `new PlaneGeometry({ flipV: true })`\n   *\n   * Give it to {@link BatchedMesh3D} slots with a `billboardMode` to draw billboards without a scene\n   * node per sprite. Its `destroy` does nothing, as with pixi's `Texture.WHITE`, so no `destroy`\n   * call can pull it out from under the sprites.\n   * @example\n   * ```ts\n   * const sprites = new BatchedMesh3D({ size: 10_000, parent: view.root });\n   * sprites.setGeometryAt(0, PlaneGeometry.spriteQuad);\n   * sprites.items[0].billboardMode = 'spherical';\n   * ```\n   */\n  public static get spriteQuad(): PlaneGeometry {\n    return (PlaneGeometry._spriteQuad ??= (() => {\n      const quad = new PlaneGeometry({ flipV: true });\n      quad.destroy = NOOP;\n      return quad;\n    })());\n  }\n\n  /**\n   * Creates a new `PlaneGeometry`\n   * @param options - See {@link PlaneGeometryOptions} for available options\n   */\n  constructor(options: Partial<PlaneGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...PlaneGeometry.defaultOptions,\n      ...options,\n    };\n    const { width, height, flipV } = resolvedOptions;\n    const widthSegments = clampSegments(resolvedOptions.widthSegments, 1);\n    const heightSegments = clampSegments(resolvedOptions.heightSegments, 1);\n\n    const vertCount = (widthSegments + 1) * (heightSegments + 1);\n    const triCount = widthSegments * heightSegments * 2;\n\n    const positions = new Float32Array(vertCount * 3);\n    const normals = new Float32Array(vertCount * 3);\n    const uvs = new Float32Array(vertCount * 2);\n    const indices = vertCount > 65536 ? new Uint32Array(triCount * 3) : new Uint16Array(triCount * 3);\n\n    const halfW = width * 0.5;\n    const halfH = height * 0.5;\n    const invW = 1 / widthSegments;\n    const invH = 1 / heightSegments;\n\n    let pi = 0;\n    let ni = 0;\n    let ui = 0;\n\n    for (let y = 0; y <= heightSegments; ++y) {\n      const v = y * invH;\n\n      for (let x = 0; x <= widthSegments; ++x) {\n        const u = x * invW;\n\n        positions[pi++] = u * width - halfW;\n        positions[pi++] = v * height - halfH;\n        positions[pi++] = 0;\n\n        normals[ni++] = 0;\n        normals[ni++] = 0;\n        normals[ni++] = 1;\n\n        uvs[ui++] = u;\n        uvs[ui++] = flipV ? 1 - v : v;\n      }\n    }\n\n    const rowSize = widthSegments + 1;\n    let ii = 0;\n\n    for (let y = 0; y < heightSegments; ++y) {\n      const rowOffset0 = (y + 0) * rowSize;\n      const rowOffset1 = (y + 1) * rowSize;\n\n      for (let x = 0; x < widthSegments; ++x) {\n        const offset0 = rowOffset0 + x;\n        const offset1 = rowOffset1 + x;\n\n        indices[ii++] = offset0;\n        indices[ii++] = offset0 + 1;\n        indices[ii++] = offset1;\n\n        indices[ii++] = offset1;\n        indices[ii++] = offset0 + 1;\n        indices[ii++] = offset1 + 1;\n      }\n    }\n\n    super({\n      ...resolvedOptions,\n      positions,\n      normals,\n      uvs,\n      indices,\n    });\n  }\n}\n","import { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\nimport { clampSegments } from './utils/clampSegments';\n\n/**\n * Options for {@link SphereGeometry}\n * @example\n * ```ts\n * const options: Partial<SphereGeometryOptions> = { radius: 0.5, widthSegments: 64, heightSegments: 32 };\n * const ball = new SphereGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface SphereGeometryOptions extends Geometry3DOptions {\n  /**\n   * The radius of the sphere\n   * @default 1\n   * @example\n   * ```ts\n   * const marble = new SphereGeometry({ radius: 0.05 });\n   * ```\n   */\n  radius: number;\n  /**\n   * The number of horizontal segments (longitudes around the +Y axis)\n   *\n   * Floored, and clamped to a minimum of 3.\n   * @default 32\n   * @example\n   * ```ts\n   * const smooth = new SphereGeometry({ widthSegments: 64, heightSegments: 32 });\n   * ```\n   */\n  widthSegments: number;\n  /**\n   * The number of vertical segments (latitudes between the poles)\n   *\n   * Floored, and clamped to a minimum of 2.\n   * @default 16\n   * @example\n   * ```ts\n   * const lowPoly = new SphereGeometry({ widthSegments: 8, heightSegments: 6 });\n   * ```\n   */\n  heightSegments: number;\n}\n\n/**\n * A UV sphere geometry built as a longitude-by-latitude grid around the +Y axis\n *\n * UVs are equirectangular: `u` wraps once around the Y axis, starting at +X, and `v` runs from 0 at\n * the north pole (+Y) to 1 at the south pole, so an image's top row lands on the north pole.\n *\n * Triangles crowd together at the poles, where a texture pinches. For even triangles, use\n * {@link IcosahedronGeometry}.\n * @example\n * ```ts\n * const sphere = new SphereGeometry({\n *   radius: 1,\n *   widthSegments: 32,\n *   heightSegments: 16,\n * });\n * ```\n * @category geometry\n * @standard\n */\nexport class SphereGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `SphereGeometry`\n   * @example\n   * ```ts\n   * SphereGeometry.defaultOptions.widthSegments = 16;\n   * ```\n   */\n  public static defaultOptions: SphereGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    radius: 1,\n    widthSegments: 32,\n    heightSegments: 16,\n  };\n\n  /**\n   * Creates a new `SphereGeometry`\n   * @param options - See {@link SphereGeometryOptions} for available options\n   */\n  constructor(options: Partial<SphereGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...SphereGeometry.defaultOptions,\n      ...options,\n    };\n    const { radius } = resolvedOptions;\n    const widthSegments = clampSegments(resolvedOptions.widthSegments, 3);\n    const heightSegments = clampSegments(resolvedOptions.heightSegments, 2);\n\n    const vertCount = (widthSegments + 1) * (heightSegments + 1);\n    const triCount = (heightSegments - 1) * widthSegments * 2;\n\n    const positions = new Float32Array(vertCount * 3);\n    const normals = new Float32Array(vertCount * 3);\n    const uvs = new Float32Array(vertCount * 2);\n    const indices = vertCount <= 65536 ? new Uint16Array(triCount * 3) : new Uint32Array(triCount * 3);\n\n    const sinPhi = new Float64Array(heightSegments + 1);\n    const cosPhi = new Float64Array(heightSegments + 1);\n\n    for (let y = 0; y <= heightSegments; y++) {\n      const phi = (y / heightSegments) * Math.PI;\n\n      sinPhi[y] = Math.sin(phi);\n      cosPhi[y] = Math.cos(phi);\n    }\n\n    const sinTheta = new Float64Array(widthSegments + 1);\n    const cosTheta = new Float64Array(widthSegments + 1);\n\n    for (let x = 0; x <= widthSegments; x++) {\n      const theta = (x / widthSegments) * Math.PI * 2;\n\n      sinTheta[x] = Math.sin(theta);\n      cosTheta[x] = Math.cos(theta);\n    }\n\n    let posOffset = 0;\n    let uvOffset = 0;\n\n    for (let y = 0; y <= heightSegments; y++) {\n      const v = y / heightSegments;\n      const sp = sinPhi[y];\n      const cp = cosPhi[y];\n\n      for (let x = 0; x <= widthSegments; x++) {\n        const u = x / widthSegments;\n        const st = sinTheta[x];\n        const ct = cosTheta[x];\n\n        const nx = sp * ct;\n        const ny = cp;\n        const nz = sp * st;\n\n        positions[posOffset] = nx * radius;\n        positions[posOffset + 1] = ny * radius;\n        positions[posOffset + 2] = nz * radius;\n\n        normals[posOffset] = nx;\n        normals[posOffset + 1] = ny;\n        normals[posOffset + 2] = nz;\n\n        posOffset += 3;\n\n        uvs[uvOffset] = u;\n        uvs[uvOffset + 1] = v;\n\n        uvOffset += 2;\n      }\n    }\n\n    const rowSize = widthSegments + 1;\n    let idxOffset = 0;\n\n    for (let y = 0; y < heightSegments; y++) {\n      for (let x = 0; x < widthSegments; x++) {\n        const a = y * rowSize + x;\n        const b = a + 1;\n        const c = a + rowSize;\n        const d = c + 1;\n\n        if (y !== 0) {\n          indices[idxOffset] = a;\n          indices[idxOffset + 1] = b;\n          indices[idxOffset + 2] = c;\n          idxOffset += 3;\n        }\n        if (y !== heightSegments - 1) {\n          indices[idxOffset] = b;\n          indices[idxOffset + 1] = d;\n          indices[idxOffset + 2] = c;\n          idxOffset += 3;\n        }\n      }\n    }\n\n    super({\n      ...resolvedOptions,\n      positions,\n      normals,\n      uvs,\n      indices,\n    });\n  }\n}\n","import { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\nimport { clampSegments } from './utils/clampSegments';\n\n/**\n * Options for {@link TorusGeometry}\n * @example\n * ```ts\n * const options: Partial<TorusGeometryOptions> = { radius: 2, tube: 0.25 };\n * const ring = new TorusGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface TorusGeometryOptions extends Geometry3DOptions {\n  /**\n   * The major radius, measured from the center of the torus to the center of the tube\n   * @default 1\n   * @example\n   * ```ts\n   * const hoop = new TorusGeometry({ radius: 3, tube: 0.1 });\n   * ```\n   */\n  radius: number;\n  /**\n   * The radius of the tube\n   *\n   * Keep it below `radius`; a larger tube passes through itself at the center.\n   * @default 0.4\n   * @example\n   * ```ts\n   * const donut = new TorusGeometry({ radius: 1, tube: 0.6 });\n   * ```\n   */\n  tube: number;\n  /**\n   * The number of segments around the tube cross-section\n   *\n   * Floored, and clamped to a minimum of 3.\n   * @default 12\n   * @example\n   * ```ts\n   * const smooth = new TorusGeometry({ radialSegments: 32, tubularSegments: 96 });\n   * ```\n   */\n  radialSegments: number;\n  /**\n   * The number of segments around the torus ring\n   *\n   * Floored, and clamped to a minimum of 3.\n   * @default 48\n   * @example\n   * ```ts\n   * const hexRing = new TorusGeometry({ tubularSegments: 6 });\n   * ```\n   */\n  tubularSegments: number;\n  /**\n   * The angle in radians the ring sweeps around the +Y axis; less than `2π` leaves the ring open\n   * @default Math.PI * 2\n   * @example\n   * ```ts\n   * const arch = new TorusGeometry({ arc: Math.PI });\n   * ```\n   */\n  arc: number;\n  /**\n   * Where the tube's cross-section starts, in radians from the ring's outer edge toward +Y\n   *\n   * With a `thetaLength` below `2π`, it picks where the gap in the tube falls, as for a gutter.\n   * @default 0\n   * @example\n   * ```ts\n   * const gutter = new TorusGeometry({ thetaStart: Math.PI, thetaLength: Math.PI });\n   * ```\n   */\n  thetaStart: number;\n  /**\n   * The angle in radians the cross-section sweeps; less than `2π` leaves the tube open\n   * @default Math.PI * 2\n   * @example\n   * ```ts\n   * const outerHalf = new TorusGeometry({ thetaStart: -Math.PI / 2, thetaLength: Math.PI });\n   * ```\n   */\n  thetaLength: number;\n}\n\n/**\n * A torus (donut) geometry lying in the XZ plane around the +Y axis\n *\n * UVs map `u` around the ring (0 at the start of the arc, 1 at the end) and `v` around the tube\n * cross-section (0 at `thetaStart`, 1 at the end of `thetaLength`).\n * @example\n * ```ts\n * const torus = new TorusGeometry({\n *   radius: 1,\n *   tube: 0.4,\n *   radialSegments: 12,\n *   tubularSegments: 48,\n *   arc: Math.PI * 2,\n * });\n * ```\n * @category geometry\n * @standard\n */\nexport class TorusGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `TorusGeometry`\n   * @example\n   * ```ts\n   * TorusGeometry.defaultOptions.tube = 0.2;\n   * ```\n   */\n  public static defaultOptions: TorusGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    radius: 1,\n    tube: 0.4,\n    radialSegments: 12,\n    tubularSegments: 48,\n    arc: Math.PI * 2,\n    thetaStart: 0,\n    thetaLength: Math.PI * 2,\n  };\n\n  /**\n   * Creates a new `TorusGeometry`\n   * @param options - See {@link TorusGeometryOptions} for available options\n   */\n  constructor(options: Partial<TorusGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...TorusGeometry.defaultOptions,\n      ...options,\n    };\n    const { radius, tube, arc, thetaStart, thetaLength } = resolvedOptions;\n    const radialSegmentCount = clampSegments(resolvedOptions.radialSegments, 3);\n    const tubularSegmentCount = clampSegments(resolvedOptions.tubularSegments, 3);\n\n    const vertCount = (radialSegmentCount + 1) * (tubularSegmentCount + 1);\n    const idxCount = radialSegmentCount * tubularSegmentCount * 6;\n\n    const positions = new Float32Array(vertCount * 3);\n    const normals = new Float32Array(vertCount * 3);\n    const uvs = new Float32Array(vertCount * 2);\n    const indices = vertCount > 65536 ? new Uint32Array(idxCount) : new Uint16Array(idxCount);\n\n    const cosU = new Float64Array(tubularSegmentCount + 1);\n    const sinU = new Float64Array(tubularSegmentCount + 1);\n\n    for (let i = 0; i <= tubularSegmentCount; i++) {\n      const u = (i / tubularSegmentCount) * arc;\n\n      cosU[i] = Math.cos(u);\n      sinU[i] = Math.sin(u);\n    }\n\n    let posIdx = 0;\n    let normIdx = 0;\n    let uvIdx = 0;\n\n    for (let j = 0; j <= radialSegmentCount; j++) {\n      const v = thetaStart + (j / radialSegmentCount) * thetaLength;\n      const cosV = Math.cos(v);\n      const sinV = Math.sin(v);\n      const vRow = j / radialSegmentCount;\n      const ringRadius = radius + tube * cosV;\n      const yOffset = tube * sinV;\n\n      for (let i = 0; i <= tubularSegmentCount; i++) {\n        const cu = cosU[i];\n        const su = sinU[i];\n\n        positions[posIdx++] = ringRadius * cu;\n        positions[posIdx++] = yOffset;\n        positions[posIdx++] = ringRadius * su;\n\n        normals[normIdx++] = cosV * cu;\n        normals[normIdx++] = sinV;\n        normals[normIdx++] = cosV * su;\n\n        uvs[uvIdx++] = i / tubularSegmentCount;\n        uvs[uvIdx++] = vRow;\n      }\n    }\n\n    const rowSize = tubularSegmentCount + 1;\n    let idxIdx = 0;\n\n    for (let j = 1; j <= radialSegmentCount; j++) {\n      for (let i = 1; i <= tubularSegmentCount; i++) {\n        const a = rowSize * j + i - 1;\n        const b = rowSize * (j - 1) + i - 1;\n        const c = rowSize * (j - 1) + i;\n        const d = rowSize * j + i;\n\n        indices[idxIdx++] = a;\n        indices[idxIdx++] = d;\n        indices[idxIdx++] = b;\n        indices[idxIdx++] = b;\n        indices[idxIdx++] = d;\n        indices[idxIdx++] = c;\n      }\n    }\n\n    super({\n      ...resolvedOptions,\n      positions,\n      normals,\n      uvs,\n      indices,\n    });\n  }\n}\n","import { Geometry3D } from './Geometry3D';\nimport type { Geometry3DOptions } from './Geometry3D';\nimport { clampSegments } from './utils/clampSegments';\n\n/**\n * Options for {@link TorusKnotGeometry}\n * @example\n * ```ts\n * const options: Partial<TorusKnotGeometryOptions> = { p: 3, q: 5, tube: 0.2 };\n * const knot = new TorusKnotGeometry(options);\n * ```\n * @category geometry\n * @standard\n */\nexport interface TorusKnotGeometryOptions extends Geometry3DOptions {\n  /**\n   * The overall scale of the knot; the centerline stays between `0.5 * radius` and `1.5 * radius`\n   * from the Y axis\n   * @default 1\n   * @example\n   * ```ts\n   * const big = new TorusKnotGeometry({ radius: 4, tube: 0.8 });\n   * ```\n   */\n  radius: number;\n  /**\n   * The radius of the tube swept along the knot path\n   * @default 0.4\n   * @example\n   * ```ts\n   * const wire = new TorusKnotGeometry({ tube: 0.05 });\n   * ```\n   */\n  tube: number;\n  /**\n   * The number of segments along the knot's centerline\n   *\n   * Floored, and clamped to a minimum of 3. Tightly wound knots need more to stay smooth.\n   * @default 64\n   * @example\n   * ```ts\n   * const smooth = new TorusKnotGeometry({ p: 3, q: 7, tubularSegments: 256 });\n   * ```\n   */\n  tubularSegments: number;\n  /**\n   * The number of segments around the tube cross-section\n   *\n   * Floored, and clamped to a minimum of 3.\n   * @default 8\n   * @example\n   * ```ts\n   * const roundTube = new TorusKnotGeometry({ radialSegments: 16 });\n   * ```\n   */\n  radialSegments: number;\n  /**\n   * How many times the knot winds around the +Y axis; {@link TorusKnotGeometry} says which values to use\n   * @default 2\n   * @example\n   * ```ts\n   * const cinquefoil = new TorusKnotGeometry({ p: 2, q: 5 });\n   * ```\n   */\n  p: number;\n  /**\n   * How many times the knot winds through the torus's hole; {@link TorusKnotGeometry} says which values to use\n   * @default 3\n   * @example\n   * ```ts\n   * const trefoil = new TorusKnotGeometry({ p: 2, q: 3 });\n   * ```\n   */\n  q: number;\n}\n\n/**\n * A torus knot geometry, formed by sweeping a circular tube along a `(p, q)` torus knot path\n *\n * The centerline winds `p` times around the +Y axis and `q` times through the torus's hole: `(2, 3)`\n * is a trefoil, and `(3, 7)` is more tightly wound. Use whole numbers that share no factor: other\n * numbers leave a gap where the tube's ends should meet, and a shared factor runs the tube over the\n * same loop more than once.\n * @example\n * ```ts\n * const trefoil = new TorusKnotGeometry({\n *   radius: 1,\n *   tube: 0.4,\n *   tubularSegments: 64,\n *   radialSegments: 8,\n *   p: 2,\n *   q: 3,\n * });\n * ```\n * @category geometry\n * @standard\n */\nexport class TorusKnotGeometry extends Geometry3D {\n  /**\n   * Defaults for every new `TorusKnotGeometry`\n   * @example\n   * ```ts\n   * TorusKnotGeometry.defaultOptions.tubularSegments = 128;\n   * ```\n   */\n  public static defaultOptions: TorusKnotGeometryOptions = {\n    ...Geometry3D.defaultOptions,\n    radius: 1,\n    tube: 0.4,\n    tubularSegments: 64,\n    radialSegments: 8,\n    p: 2,\n    q: 3,\n  };\n\n  /**\n   * Creates a new `TorusKnotGeometry`\n   * @param options - See {@link TorusKnotGeometryOptions} for available options\n   */\n  constructor(options: Partial<TorusKnotGeometryOptions> = {}) {\n    const resolvedOptions = {\n      ...TorusKnotGeometry.defaultOptions,\n      ...options,\n    };\n    const { radius, tube, p, q } = resolvedOptions;\n    const tubularSegmentCount = clampSegments(resolvedOptions.tubularSegments, 3);\n    const radialSegmentCount = clampSegments(resolvedOptions.radialSegments, 3);\n\n    const vertCount = (radialSegmentCount + 1) * (tubularSegmentCount + 1);\n    const idxCount = radialSegmentCount * tubularSegmentCount * 6;\n\n    const positions = new Float32Array(vertCount * 3);\n    const normals = new Float32Array(vertCount * 3);\n    const uvs = new Float32Array(vertCount * 2);\n    const indices = vertCount > 65536 ? new Uint32Array(idxCount) : new Uint16Array(idxCount);\n\n    const cosV = new Float64Array(radialSegmentCount + 1);\n    const sinV = new Float64Array(radialSegmentCount + 1);\n\n    for (let j = 0; j <= radialSegmentCount; j++) {\n      const v = (j / radialSegmentCount) * Math.PI * 2;\n\n      cosV[j] = Math.cos(v);\n      sinV[j] = Math.sin(v);\n    }\n\n    const k = q / p;\n    let posIdx = 0;\n    let normIdx = 0;\n    let uvIdx = 0;\n\n    for (let i = 0; i <= tubularSegmentCount; i++) {\n      const u = (i / tubularSegmentCount) * p * Math.PI * 2;\n      const cosU = Math.cos(u);\n      const sinU = Math.sin(u);\n      const cosKu = Math.cos(k * u);\n      const sinKu = Math.sin(k * u);\n      const radial = (2 + cosKu) * 0.5;\n      const cx = radius * radial * cosU;\n      const cy = radius * sinKu * 0.5;\n      const cz = radius * radial * sinU;\n\n      const tx = radius * 0.5 * (-k * sinKu * cosU - (2 + cosKu) * sinU);\n      const ty = radius * 0.5 * k * cosKu;\n      const tz = radius * 0.5 * (-k * sinKu * sinU + (2 + cosKu) * cosU);\n\n      const bxRaw = ty * cz - tz * cy;\n      const byRaw = tz * cx - tx * cz;\n      const bzRaw = tx * cy - ty * cx;\n      const binormalLen = Math.sqrt(bxRaw * bxRaw + byRaw * byRaw + bzRaw * bzRaw);\n      const bx = bxRaw / binormalLen;\n      const by = byRaw / binormalLen;\n      const bz = bzRaw / binormalLen;\n\n      const nxRaw = by * tz - bz * ty;\n      const nyRaw = bz * tx - bx * tz;\n      const nzRaw = bx * ty - by * tx;\n      const normalLen = Math.sqrt(nxRaw * nxRaw + nyRaw * nyRaw + nzRaw * nzRaw);\n      const nx = nxRaw / normalLen;\n      const ny = nyRaw / normalLen;\n      const nz = nzRaw / normalLen;\n\n      const uRow = i / tubularSegmentCount;\n\n      for (let j = 0; j <= radialSegmentCount; j++) {\n        const cosVj = cosV[j];\n        const sinVj = sinV[j];\n        const radialNx = -cosVj * nx + sinVj * bx;\n        const radialNy = -cosVj * ny + sinVj * by;\n        const radialNz = -cosVj * nz + sinVj * bz;\n\n        positions[posIdx++] = cx + tube * radialNx;\n        positions[posIdx++] = cy + tube * radialNy;\n        positions[posIdx++] = cz + tube * radialNz;\n\n        normals[normIdx++] = radialNx;\n        normals[normIdx++] = radialNy;\n        normals[normIdx++] = radialNz;\n\n        uvs[uvIdx++] = uRow;\n        uvs[uvIdx++] = j / radialSegmentCount;\n      }\n    }\n\n    const rowSize = radialSegmentCount + 1;\n    let idxIdx = 0;\n\n    for (let j = 1; j <= tubularSegmentCount; j++) {\n      for (let i = 1; i <= radialSegmentCount; i++) {\n        const a = rowSize * (j - 1) + (i - 1);\n        const b = rowSize * j + (i - 1);\n        const c = rowSize * j + i;\n        const d = rowSize * (j - 1) + i;\n\n        indices[idxIdx++] = a;\n        indices[idxIdx++] = b;\n        indices[idxIdx++] = d;\n        indices[idxIdx++] = b;\n        indices[idxIdx++] = c;\n        indices[idxIdx++] = d;\n      }\n    }\n\n    super({\n      ...resolvedOptions,\n      positions,\n      normals,\n      uvs,\n      indices,\n    });\n  }\n}\n","import { getAttributeInfoFromFormat } from 'pixi.js';\nimport type { Attribute, Geometry } from 'pixi.js';\n\ntype ComponentView = {\n  new (buffer: ArrayBufferLike, byteOffset: number, length: number): ArrayLike<number>;\n  readonly BYTES_PER_ELEMENT: number;\n};\n\nconst COMPONENT_READERS: Record<string, { View: ComponentView; scale: number; min: number }> = {\n  float32: { View: Float32Array, scale: 1, min: -Infinity },\n  snorm8: { View: Int8Array, scale: 1 / 127, min: -1 },\n  unorm8: { View: Uint8Array, scale: 1 / 255, min: -Infinity },\n  sint8: { View: Int8Array, scale: 1, min: -Infinity },\n  uint8: { View: Uint8Array, scale: 1, min: -Infinity },\n  snorm16: { View: Int16Array, scale: 1 / 32767, min: -1 },\n  unorm16: { View: Uint16Array, scale: 1 / 65535, min: -Infinity },\n  sint16: { View: Int16Array, scale: 1, min: -Infinity },\n  uint16: { View: Uint16Array, scale: 1, min: -Infinity },\n  sint32: { View: Int32Array, scale: 1, min: -Infinity },\n  uint32: { View: Uint32Array, scale: 1, min: -Infinity },\n};\n\n/**\n * Reads a vertex attribute as floats, `size` per vertex, however the geometry stores it\n *\n * Use it for maths on a mesh on the CPU, such as merging, welding or sampling its surface. Getters\n * such as {@link Geometry3D#normals} return data as stored, which can be quantized integers or a\n * whole interleaved buffer; this decodes either.\n *\n * Values come out as the vertex shader reads them: `snorm` formats as -1 to 1, `unorm` as 0 to 1,\n * and float and raw integer (`sint`, `uint`) formats as stored, so raw integer positions read in\n * the same space as {@link Geometry3D#bounds3D}, and the mesh's transform scales them. Morph\n * targets and skinning aren't applied.\n *\n * It copies on every call, so read once and keep the result, or pass `out` to reuse an array.\n * @example\n * ```ts\n * const normals = getAttributeData(geometry, 'aNormal', 3);\n * const normal = new Vector3().fromArray(normals, vertexIndex * 3);\n *\n * const merged = new Float32Array((first.vertexCount + second.vertexCount) * 3);\n * getAttributeData(first, 'aPosition', 3, merged);\n * getAttributeData(second, 'aPosition', 3, merged.subarray(first.vertexCount * 3));\n * ```\n * @param geometry - A {@link Geometry3D}, or a pixi `Geometry` whose attributes give a `format`,\n *   and a `stride` and `offset` when they share a buffer\n * @param attributeId - Shader attribute name, such as `aPosition`, `aNormal`, `aUV` or `aTangent`\n * @param size - Components per vertex to read, at most what the format holds: 3 for positions and\n *   normals, 2 for UVs, 4 for tangents\n * @param out - Array to fill from index 0, at least `size` floats per vertex; a new one is allocated\n *   when omitted\n * @returns `out`, or the new array\n * @category geometry\n * @standard\n */\nexport function getAttributeData(\n  geometry: Geometry,\n  attributeId: string,\n  size: number,\n  out?: Float32Array,\n): Float32Array {\n  const attribute: Attribute | undefined = geometry.getAttribute(attributeId);\n  if (!attribute) throw new Error(`[getAttributeData] The geometry has no ${attributeId} attribute.`);\n\n  const format = attribute.format;\n  const reader = format && COMPONENT_READERS[format.split('x', 1)[0]];\n  const info = reader && getAttributeInfoFromFormat(format);\n  if (!info || size > info.size) {\n    throw new Error(\n      `[getAttributeData] Can't read ${attributeId}, stored as ${format ?? 'no format'}, as ${size} floats per vertex.`,\n    );\n  }\n\n  const { View, scale, min } = reader;\n  const data = attribute.buffer.data;\n  const view = new View(data.buffer, data.byteOffset, Math.floor(data.byteLength / View.BYTES_PER_ELEMENT));\n  const stride = (attribute.stride || info.stride) / View.BYTES_PER_ELEMENT;\n  const offset = (attribute.offset ?? 0) / View.BYTES_PER_ELEMENT;\n  const vertexCount = Math.floor(view.length / stride);\n  const length = vertexCount * size;\n\n  if (out && out.length < length) {\n    throw new Error(`[getAttributeData] out holds ${out.length} floats, but ${attributeId} needs ${length}.`);\n  }\n\n  const result = out ?? new Float32Array(length);\n\n  for (let v = 0; v < vertexCount; v++) {\n    const src = v * stride + offset;\n    const dst = v * size;\n    for (let c = 0; c < size; c++) {\n      const value = view[src + c] * scale;\n      result[dst + c] = value < min ? min : value;\n    }\n  }\n\n  return result;\n}\n","import { mathConstantsBit } from '../../../core/shader/bits/mathConstantsBit';\nimport { createLightingBit } from '../../../core/shader/createLightingBit';\n\n/**\n * Normalized to read as bright as `pbrLightingBit`, and takes the environment's diffuse as `iblBit`\n * does, with no `1 / PI`, so Phong and PBR meshes match under the same lights\n * @internal\n */\nexport const phongLightingBit = createLightingBit({\n  name: 'phongLighting',\n\n  requires: [mathConstantsBit],\n\n  preLighting: {\n    gpu: /*wgsl*/ `\n  var directLight = vec3<f32>(0.0);\n\n  let albedoOverPI = albedo * INV_PI;\n  let specScale = (shininess * 0.5 + 1.0) * INV_PI * 0.25 * specularStrength;\n`,\n    gl: /*glsl*/ `\n  vec3 directLight = vec3(0.0);\n\n  vec3 albedoOverPI = albedo * INV_PI;\n  float specScale = (shininess * 0.5 + 1.0) * INV_PI * 0.25 * specularStrength;\n`,\n  },\n\n  perLight: {\n    gpu: /*wgsl*/ `\n    let halfVector = normalize(viewDir + lightDir);\n    let nDotH = max(dot(normal, halfVector), 0.0);\n    let vDotH = max(dot(viewDir, halfVector), 0.0);\n\n    let fc5 = exp2((-5.55473 * vDotH - 6.98316) * vDotH);\n    let fresnel = specularColor + (vec3<f32>(1.0) - specularColor) * fc5;\n    let specular = fresnel * (specScale * pow(nDotH, shininess));\n\n    let irradiance = light.color * (nDotL * attenuation * shadow);\n    directLight += (albedoOverPI + specular) * irradiance;\n`,\n    gl: /*glsl*/ `\n    vec3 halfVector = normalize(viewDir + lightDir);\n    float nDotH = max(dot(normal, halfVector), 0.0);\n    float vDotH = max(dot(viewDir, halfVector), 0.0);\n\n    float fc5 = exp2((-5.55473 * vDotH - 6.98316) * vDotH);\n    vec3 fresnel = specularColor + (vec3(1.0) - specularColor) * fc5;\n    vec3 specular = fresnel * (specScale * pow(nDotH, shininess));\n\n    vec3 irradiance = light.color * (nDotL * attenuation * shadow);\n    directLight += (albedoOverPI + specular) * irradiance;\n`,\n  },\n\n  postLighting: {\n    gpu: /*wgsl*/ `\n  let ambient = global.uGlobalLightParams.xyz * albedoOverPI + sampleEnvironment(normal, 1.0) * albedo;\n  finalColor = ambient + directLight + emissive;\n`,\n    gl: /*glsl*/ `\n  vec3 ambient = uGlobalLightParams.xyz * albedoOverPI + sampleEnvironment(normal, 1.0) * albedo;\n  finalColor = ambient + directLight + emissive;\n`,\n  },\n});\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Declares the `normal` slot, `normalScale` and `alphaCutoff` for the bits that join per mesh or in\n * `'mask'` mode, since the material's layout is fixed at construction\n * @internal\n */\nexport const phongMaterialBit: ShaderBit = {\n  name: 'phongMaterial',\n\n  textures: ['baseColor', 'normal'],\n\n  bindings: {\n    material: {\n      baseColor: 'vec4<f32>',\n      specularColor: 'vec3<f32>',\n      shininess: 'f32',\n      specularStrength: 'f32',\n      alphaCutoff: 'f32',\n      normalScale: 'f32',\n    },\n  },\n\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  var emissive: vec3<f32> = vec3<f32>(0.0);\n  var specularStrength = material.specularStrength;\n\n  var baseColor = material.baseColor;\n\n  var baseTex = sampleBaseColor(input.vUV);\n  let baseTexLinear = baseTex.rgb / max(baseTex.a, 0.001);\n  baseTex = vec4<f32>(pow(baseTexLinear, vec3<f32>(2.2)), baseTex.a);\n  baseColor *= baseTex;\n\n  albedo *= baseColor.rgb;\n  alpha *= baseColor.a;\n\n  let viewDir = normalize(camera.uCameraPosition.xyz - input.vPosition);\n  let specularColor = material.specularColor;\n  let shininess = max(material.shininess, 1.0);\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  vec3 emissive = vec3(0.0);\n  float specularStrength = material.specularStrength;\n\n  vec4 baseColor = material.baseColor;\n\n  vec4 baseTex = sampleBaseColor(vUV);\n  vec3 baseTexLinear = baseTex.rgb / max(baseTex.a, 0.001);\n  baseTex.rgb = pow(baseTexLinear, vec3(2.2));\n  baseColor *= baseTex;\n\n  albedo *= baseColor.rgb;\n  alpha *= baseColor.a;\n\n  vec3 viewDir = normalize(uCameraPosition.xyz - vPosition);\n  vec3 specularColor = material.specularColor;\n  float shininess = max(material.shininess, 1.0);\n`,\n    },\n  },\n};\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Must follow `phongMaterialBit`, which declares the `specularStrength` it scales\n * @internal\n */\nexport const phongSpecularTextureBit: ShaderBit = {\n  name: 'phongSpecularTexture',\n\n  textures: ['specular'],\n\n  gpu: {\n    fragment: {\n      material: /*wgsl*/ `\n  specularStrength *= sampleSpecular(input.vUV).r;\n`,\n    },\n  },\n\n  gl: {\n    fragment: {\n      material: /*glsl*/ `\n  specularStrength *= sampleSpecular(vUV).r;\n`,\n    },\n  },\n};\n","import { Color } from 'pixi.js';\nimport type { ColorSource, Texture, TextureDestroyOptions, TypeOrBool } from 'pixi.js';\n\nimport { alphaMaskBit } from '../../core/shader/bits/alphaMaskBit';\nimport { emissiveBit } from '../../core/shader/bits/emissiveBit';\nimport { uvTransformBit } from '../../core/shader/bits/uvTransformBit';\nimport type { ShaderBit } from '../../core/shader/ShaderBit';\nimport { ShaderDescriptor } from '../../core/shader/ShaderDescriptor';\nimport { NORMAL_MAP } from '../../core/textures/DefaultTextures';\nimport type { View3D } from '../../scene/View3D';\nimport { BaseMaterial3D, writeLinearRgb } from '../BaseMaterial3D';\nimport type { BaseMaterial3DOptions } from '../BaseMaterial3D';\nimport { readFeatureProps } from '../utils/createFeaturePropsClass';\nimport type { MaterialData } from '../utils/createMaterialDataClass';\nimport type { MaterialTextures } from '../utils/createMaterialTexturesClass';\nimport { EmissivePropsClass } from '../utils/emissiveProps';\nimport type { EmissiveOptions, EmissiveProps } from '../utils/emissiveProps';\nimport { phongLightingBit } from './bits/phongLightingBit';\nimport { phongMaterialBit } from './bits/phongMaterialBit';\nimport { phongSpecularTextureBit } from './bits/phongSpecularTextureBit';\n\n/**\n * Options for {@link PhongMaterial}\n * @example\n * ```ts\n * const options: PhongMaterialOptions = { baseColor: 0x8a5a2b, shininess: 12 };\n * const wood = new PhongMaterial(options);\n * ```\n * @category materials\n * @standard\n */\nexport interface PhongMaterialOptions extends Omit<BaseMaterial3DOptions, 'descriptor'> {\n  /**\n   * Specular tint; the default gives a faint highlight\n   *\n   * Fresnel lifts even a black tint toward white at grazing angles, so remove the highlight with\n   * {@link PhongMaterialOptions#specularStrength} instead.\n   * @default 0x111111\n   * @example\n   * ```ts\n   * const metalish = new PhongMaterial({ baseColor: 0x333333, specularColor: 0xcccccc });\n   * ```\n   */\n  specularColor?: ColorSource;\n  /**\n   * Specular exponent: higher gives a smaller, sharper highlight; values below 1 act as 1\n   * @default 30\n   * @example\n   * ```ts\n   * const glossy = new PhongMaterial({ shininess: 120 });\n   * ```\n   */\n  shininess?: number;\n  /**\n   * Scales the whole highlight, Fresnel rim included; 0 removes it\n   * @default 1\n   * @example\n   * ```ts\n   * const chalk = new PhongMaterial({ specularStrength: 0 });\n   * ```\n   */\n  specularStrength?: number;\n  /**\n   * Map whose red channel scales `specularStrength` per texel\n   *\n   * Only a material built with one can swap it later, through `material.textures.specular`.\n   * @example\n   * ```ts\n   * const tiles = new PhongMaterial({ baseColorTexture: tilesTexture, specularTexture: groutMask });\n   * ```\n   */\n  specularTexture?: Texture;\n  /**\n   * Tangent-space normal map with green pointing up the image, as glTF and OpenGL use\n   *\n   * Invert the green channel of a DirectX-style map, or its bumps light from the wrong side. Needs\n   * UVs on the geometry. Can also be assigned later through `material.textures.normal`.\n   * @example\n   * ```ts\n   * const stone = new PhongMaterial({ baseColorTexture: stoneTexture, normalTexture: stoneNormals });\n   * ```\n   */\n  normalTexture?: Texture;\n  /**\n   * Strength of the normal map's bumps; no effect without a map\n   * @default 1\n   * @example\n   * ```ts\n   * const subtle = new PhongMaterial({ normalTexture: stoneNormals, normalScale: 0.4 });\n   * ```\n   */\n  normalScale?: number;\n  /**\n   * The material's own glow; passing the group turns it on\n   *\n   * Change it later through {@link PhongMaterial#emissive}.\n   * @example\n   * ```ts\n   * const screen = new PhongMaterial({ emissive: { texture: screenTexture, strength: 2 } });\n   * ```\n   */\n  emissive?: EmissiveOptions;\n}\n\n/**\n * The fields of {@link PhongMaterial#data}\n *\n * `emissive` and `emissiveStrength` exist only on a material built with an `emissive` group; the\n * rest always do.\n * @category materials\n * @advanced\n */\nexport interface PhongData extends MaterialData {\n  /** Base colour in linear light, alpha in the last lane */\n  baseColor: Float32Array;\n  /** Specular tint in linear light */\n  specularColor: Float32Array;\n  /** Specular exponent */\n  shininess: number;\n  /** Scale on the whole highlight */\n  specularStrength: number;\n  /** Cutoff for `alphaMode: 'mask'` */\n  alphaCutoff: number;\n  /** Strength of the normal map's bumps */\n  normalScale: number;\n  /** Glow colour in linear light */\n  emissive?: Float32Array;\n  /** Multiplier on the glow */\n  emissiveStrength?: number;\n}\n\n/**\n * The texture slots of a {@link PhongMaterial}, as `material.textures`\n * @example\n * ```ts\n * const material = new PhongMaterial({ specularTexture: shineMask });\n * material.textures.specular = otherShineMask;\n * ```\n * @category materials\n * @standard\n */\nexport interface PhongMaterialTextures extends MaterialTextures {\n  /**\n   * Base colour map\n   * @example\n   * ```ts\n   * material.textures.baseColor = await Assets.load('bricks.png');\n   * ```\n   */\n  baseColor: Texture;\n  /**\n   * Tangent-space normal map; holds a flat map until you assign one\n   * @example\n   * ```ts\n   * material.textures.normal = await Assets.load('bricks-normal.png');\n   * ```\n   */\n  normal: Texture;\n  /**\n   * Map whose red channel scales the highlight; only on a material built with `specularTexture`\n   * @example\n   * ```ts\n   * material.textures.specular = wetPatches;\n   * ```\n   */\n  specular?: Texture;\n  /**\n   * Glow map; only on a material built with an `emissive` group\n   * @example\n   * ```ts\n   * material.textures.emissive = await Assets.load('lit-windows.png');\n   * ```\n   */\n  emissive?: Texture;\n}\n\n/**\n * A Blinn-Phong material: diffuse shading plus a specular highlight\n *\n * Cheaper than {@link Material3D} and easy to art-direct: `shininess` sets the size of the\n * highlight and `specularColor` its tint. A Phong mesh and a PBR mesh read at the same brightness\n * under the same lights.\n *\n * The view's `environment` adds diffuse fill only; highlights come from direct lights, so use\n * {@link Material3D} for surfaces that should reflect their surroundings. The specular and emissive\n * maps cost nothing unless you pass them at construction, and the normal map costs nothing until\n * you assign one.\n *\n * `extraBits` run after the material's own maps and before lighting, so they see the textured\n * `albedo` and `alpha`. Their `end` code runs after lighting and before tone mapping.\n * @example\n * ```ts\n * const material = new PhongMaterial({\n *   baseColor: 0x2f6f8b,\n *   specularColor: 0x777777,\n *   shininess: 48,\n * });\n * ```\n * @category materials\n * @standard\n */\nexport class PhongMaterial extends BaseMaterial3D<PhongData, PhongMaterialTextures, PhongMaterialOptions> {\n  /**\n   * Runtime glow controls; present only when the material was built with an `emissive` group\n   * @example\n   * ```ts\n   * const lantern = new PhongMaterial({ emissive: { color: 0xffaa33 } });\n   * lantern.emissive!.strength = 3;\n   * ```\n   */\n  public readonly emissive?: EmissiveProps;\n\n  /** Both the layout and `getPrimaryDescriptor` read it, so the two can't drift */\n  private readonly _featureBits: ShaderBit[] = [];\n\n  private _specularColorTint = 0x111111;\n\n  constructor(options: PhongMaterialOptions = {}) {\n    const { specularTexture, normalTexture, emissive } = options;\n\n    super(options);\n\n    const textures: Record<string, Texture | undefined> = {\n      baseColor: options.baseColorTexture,\n      normal: normalTexture ?? NORMAL_MAP,\n      ...options.textures,\n    };\n    if (specularTexture) {\n      textures.specular = specularTexture;\n      this._featureBits.push(phongSpecularTextureBit);\n    }\n    if (emissive) {\n      textures.emissive = emissive.texture;\n      this._featureBits.push(emissiveBit);\n    }\n\n    this._deriveLayoutFromBits([phongMaterialBit, uvTransformBit, ...this._featureBits, ...this.extraBits], textures);\n\n    this.shininess = options.shininess ?? 30;\n    this.specularStrength = options.specularStrength ?? 1;\n    this.specularColor = options.specularColor ?? 0x111111;\n    this.normalScale = options.normalScale ?? 1;\n    if (emissive) {\n      const props = (this.emissive = new EmissivePropsClass(this));\n      props.color = emissive.color ?? 0xffffff;\n      props.strength = emissive.strength ?? 1;\n    }\n  }\n\n  /** One per environment bit; env bits declare no material fields or textures, so each fits the layout */\n  private _descriptorByEnvKey: Record<string, ShaderDescriptor> = Object.create(null);\n\n  /**\n   * The shader descriptor for a view, one per kind of environment\n   * @param view - View whose environment picks the descriptor\n   * @advanced\n   */\n  public override getPrimaryDescriptor(view: View3D): ShaderDescriptor {\n    if (this._variantDirty) {\n      this._descriptorByEnvKey = Object.create(null);\n      this._variantDirty = false;\n    }\n\n    const envBit = view._envBit;\n    let descriptor = this._descriptorByEnvKey[envBit.name];\n    if (descriptor) return descriptor;\n\n    const bits: ShaderBit[] = [phongMaterialBit, envBit, uvTransformBit];\n    for (let i = 0; i < this._featureBits.length; i++) bits.push(this._featureBits[i]);\n    for (let i = 0; i < this.extraBits.length; i++) bits.push(this.extraBits[i]);\n    bits.push(phongLightingBit);\n    if (this._alphaMode === 'mask') bits.push(alphaMaskBit);\n\n    descriptor = new ShaderDescriptor({});\n    descriptor.update({ bitsGpu: bits, bitsGl: bits });\n    this._descriptorByEnvKey[envBit.name] = descriptor;\n    return descriptor;\n  }\n\n  /**\n   * The base options plus the specular values, maps and emissive group\n   * @advanced\n   */\n  protected override _toOptions(): PhongMaterialOptions {\n    const { emissive, textures } = this;\n\n    return {\n      ...super._toOptions(),\n      specularColor: this.specularColor,\n      shininess: this.shininess,\n      specularStrength: this.specularStrength,\n      normalScale: this.normalScale,\n      specularTexture: textures.specular,\n      normalTexture: textures.normal,\n      emissive: emissive && readFeatureProps(emissive),\n    };\n  }\n\n  /**\n   * Specular exponent: higher gives a smaller, sharper highlight\n   *\n   * Values below 1 act as 1.\n   * @example\n   * ```ts\n   * material.shininess = 80;\n   * ```\n   */\n  public get shininess(): number {\n    return this.data.shininess;\n  }\n\n  /**\n   * Sets the specular exponent\n   * @param value - Specular exponent\n   */\n  public set shininess(value: number) {\n    this.data.shininess = value;\n  }\n\n  /**\n   * Scales the whole highlight, Fresnel rim included; 0 removes it\n   *\n   * A specular map multiplies on top of it.\n   * @example\n   * ```ts\n   * material.specularStrength = 0.5;\n   * ```\n   */\n  public get specularStrength(): number {\n    return this.data.specularStrength;\n  }\n\n  /**\n   * Sets the highlight scale\n   * @param value - Scale; 0 removes the highlight\n   */\n  public set specularStrength(value: number) {\n    this.data.specularStrength = value;\n  }\n\n  /**\n   * Strength of the normal map's bumps, as glTF's `normalTextureInfo.scale`; 1 leaves the map as\n   * authored\n   * @example\n   * ```ts\n   * material.normalScale = 2;\n   * ```\n   */\n  public get normalScale(): number {\n    return this.data.normalScale;\n  }\n\n  /**\n   * Sets the strength of the normal map's bumps\n   * @param value - Multiplier on the bumps\n   */\n  public set normalScale(value: number) {\n    this.data.normalScale = value;\n  }\n\n  /**\n   * Specular tint (rgb); takes any {@link ColorSource} and reads back a hex number, like\n   * `Container.tint`\n   * @example\n   * ```ts\n   * material.specularColor = 'white';\n   * ```\n   */\n  public get specularColor(): number {\n    return this._specularColorTint;\n  }\n\n  /**\n   * Sets the specular tint\n   * @param value - Display colour\n   */\n  public set specularColor(value: ColorSource) {\n    const colour = Color.shared.setValue(value);\n    this._specularColorTint = colour.toNumber();\n    const packed = this.data?.specularColor;\n    if (packed) {\n      writeLinearRgb(packed, 0, colour);\n      this.update();\n    }\n  }\n\n  /**\n   * Frees the material for good, as {@link BaseMaterial3D#destroy} does\n   * @param options - Whether to destroy the textures too\n   * @example\n   * ```ts\n   * mesh.material.destroy();\n   * ```\n   */\n  public override destroy(options?: TypeOrBool<TextureDestroyOptions>): void {\n    if (this.destroyed) return;\n    super.destroy(options);\n\n    (this._descriptorByEnvKey as Record<string, ShaderDescriptor> | null) = null;\n    (this._featureBits as ShaderBit[] | null) = null;\n    (this as { /** @internal */ emissive?: EmissiveProps }).emissive = undefined;\n  }\n}\n","import { warn } from 'pixi.js';\n\nimport type { TypedFixedArray } from '../utils/misc';\nimport type { Matrix4 } from './Matrix4';\n\n/**\n * A 3x3 matrix, for 2D affine transforms such as UV transforms, and for the normal matrix of a 3D\n * transform\n *\n * {@link Matrix3#elements} holds the nine values column by column, the order shaders use, and a\n * `Matrix3` can be the value of a `mat3x3<f32>` uniform as it is. The 2D methods\n * ({@link Matrix3#translate}, {@link Matrix3#rotate}, {@link Matrix3#scale}) each apply after the\n * transform built so far, like pixi's `Matrix`.\n *\n * Methods that change the matrix do so in place, or write into an `out` matrix when you pass one\n * and leave this matrix as it is.\n * @example\n * ```ts\n * const tile = new Matrix3().scale(4, 4).translate(0.5, 0);\n * const uv = new Vector2(0.25, 0.75).applyMatrix3(tile);\n *\n * const normalMatrix = new Matrix3().getNormalMatrix(mesh.worldTransform);\n * const uniforms = new UniformGroup({ uNormalMatrix: { value: normalMatrix, type: 'mat3x3<f32>' } });\n * ```\n * @category maths\n * @standard\n */\nexport class Matrix3 {\n  /**\n   * The nine values, column by column: a 2D translation sits at indices 6 and 7\n   * @example\n   * ```ts\n   * const scrollU = uvTransform.elements[6];\n   * ```\n   */\n  public elements: TypedFixedArray<9>;\n\n  /**\n   * The array {@link Matrix3#toArray} writes into when given no `out`; `null` until its first call\n   * @example\n   * ```ts\n   * uvTransform.toArray(true);\n   * const rowMajor = uvTransform.array!;\n   * ```\n   * @default null\n   * @advanced\n   */\n  public array: Float32Array | null = null;\n\n  /**\n   * A shared `Matrix3`, reset to identity on every access, for a one-off calculation\n   *\n   * > [!IMPORTANT] This matrix is shared and temporary. Do not store references to it.\n   * @example\n   * ```ts\n   * const turned = new Vector2(1, 0).applyMatrix3(Matrix3.shared.rotate(angle));\n   * ```\n   */\n  static get shared(): Matrix3 {\n    return _sharedMatrix.identity();\n  }\n\n  /**\n   * A read-only identity matrix\n   *\n   * > [!IMPORTANT] This is a shared instance; do not mutate it. Use {@link Matrix3.shared} when you\n   * > need a writable temporary.\n   * @example\n   * ```ts\n   * const untransformed = uvTransform.equals(Matrix3.IDENTITY);\n   * ```\n   */\n  static get IDENTITY(): Readonly<Matrix3> {\n    return _identityMatrix.identity();\n  }\n\n  /**\n   * Creates a new `Matrix3`, defaulting to the identity matrix\n   * @param elements - Optional column-major backing array of 9 floats, used as is rather than copied\n   */\n  constructor(elements?: TypedFixedArray<9>) {\n    this.elements = elements || (new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]) as TypedFixedArray<9>);\n  }\n\n  /**\n   * Sets the 9 elements from arguments given row by row, as the matrix is written on paper\n   * @example\n   * ```ts\n   * const skew = new Matrix3().set(\n   *   1, 0.3, 0,\n   *   0, 1, 0,\n   *   0, 0, 1,\n   * );\n   * ```\n   * @param n11 - Row 1, column 1\n   * @param n12 - Row 1, column 2\n   * @param n13 - Row 1, column 3\n   * @param n21 - Row 2, column 1\n   * @param n22 - Row 2, column 2\n   * @param n23 - Row 2, column 3\n   * @param n31 - Row 3, column 1\n   * @param n32 - Row 3, column 2\n   * @param n33 - Row 3, column 3\n   * @returns This matrix\n   */\n  public set(\n    n11: number,\n    n12: number,\n    n13: number,\n    n21: number,\n    n22: number,\n    n23: number,\n    n31: number,\n    n32: number,\n    n33: number,\n  ): this {\n    const te = this.elements;\n\n    te[0] = n11;\n    te[1] = n21;\n    te[2] = n31;\n    te[3] = n12;\n    te[4] = n22;\n    te[5] = n32;\n    te[6] = n13;\n    te[7] = n23;\n    te[8] = n33;\n\n    return this;\n  }\n\n  /**\n   * Resets this matrix to the identity matrix\n   * @example\n   * ```ts\n   * uvTransform.identity().translate(scroll, 0);\n   * ```\n   * @returns This matrix\n   */\n  public identity(): this {\n    return this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);\n  }\n\n  /**\n   * Checks whether this matrix equals the identity matrix exactly\n   * @example\n   * ```ts\n   * if (!uvTransform.isIdentity()) uniforms.uniforms.uUvTransform = uvTransform;\n   * ```\n   * @returns True when every element matches the identity matrix\n   */\n  public isIdentity(): boolean {\n    const e = this.elements;\n\n    return (\n      e[0] === 1 &&\n      e[1] === 0 &&\n      e[2] === 0 &&\n      e[3] === 0 &&\n      e[4] === 1 &&\n      e[5] === 0 &&\n      e[6] === 0 &&\n      e[7] === 0 &&\n      e[8] === 1\n    );\n  }\n\n  /**\n   * Copies the elements of `m` into this matrix\n   * @example\n   * ```ts\n   * previousUvTransform.copyFrom(uvTransform);\n   * ```\n   * @param m - Matrix to copy from\n   * @returns This matrix\n   */\n  public copyFrom(m: Matrix3): this {\n    const te = this.elements;\n    const me = m.elements;\n\n    te[0] = me[0];\n    te[1] = me[1];\n    te[2] = me[2];\n    te[3] = me[3];\n    te[4] = me[4];\n    te[5] = me[5];\n    te[6] = me[6];\n    te[7] = me[7];\n    te[8] = me[8];\n\n    return this;\n  }\n\n  /**\n   * Copies this matrix's elements into `target`\n   * @example\n   * ```ts\n   * uvTransform.copyTo(previousUvTransform);\n   * ```\n   * @param target - Matrix to copy into\n   * @returns The given target matrix\n   */\n  public copyTo<T extends Matrix3>(target: T): T {\n    const te = target.elements;\n    const me = this.elements;\n\n    te[0] = me[0];\n    te[1] = me[1];\n    te[2] = me[2];\n    te[3] = me[3];\n    te[4] = me[4];\n    te[5] = me[5];\n    te[6] = me[6];\n    te[7] = me[7];\n    te[8] = me[8];\n\n    return target;\n  }\n\n  /**\n   * Checks whether all 9 elements of this matrix match `m` exactly, with no tolerance\n   * @example\n   * ```ts\n   * if (!uvTransform.equals(previousUvTransform)) material.update();\n   * ```\n   * @param m - Matrix to compare against\n   * @returns True when every element matches\n   */\n  public equals(m: Matrix3): boolean {\n    const te = this.elements;\n    const me = m.elements;\n\n    return (\n      te[0] === me[0] &&\n      te[1] === me[1] &&\n      te[2] === me[2] &&\n      te[3] === me[3] &&\n      te[4] === me[4] &&\n      te[5] === me[5] &&\n      te[6] === me[6] &&\n      te[7] === me[7] &&\n      te[8] === me[8]\n    );\n  }\n\n  /**\n   * Creates a new `Matrix3` with the same elements\n   * @example\n   * ```ts\n   * const mirrored = uvTransform.clone().scale(-1, 1);\n   * ```\n   * @returns The new matrix\n   */\n  public clone(): Matrix3 {\n    return new Matrix3().copyFrom(this);\n  }\n\n  /**\n   * Formats this matrix as a readable row-by-row string\n   * @returns The string representation\n   * @advanced\n   */\n  public toString(): string {\n    const e = this.elements;\n\n    return `[@pixi/3d/math:Matrix3 [${e[0]}, ${e[3]}, ${e[6]} | ${e[1]}, ${e[4]}, ${e[7]} | ${e[2]}, ${e[5]}, ${e[8]}]]`;\n  }\n\n  /**\n   * Reads the 9 elements from `array` (column-major) starting at `offset`\n   * @example\n   * ```ts\n   * const frameTransform = new Matrix3().fromArray(packedTransforms, frame * 9);\n   * ```\n   * @param array - Source array of column-major elements\n   * @param offset - Index of the first element to read\n   * @returns This matrix\n   */\n  public fromArray(array: ArrayLike<number>, offset = 0): this {\n    const e = this.elements;\n\n    e[0] = array[offset];\n    e[1] = array[offset + 1];\n    e[2] = array[offset + 2];\n    e[3] = array[offset + 3];\n    e[4] = array[offset + 4];\n    e[5] = array[offset + 5];\n    e[6] = array[offset + 6];\n    e[7] = array[offset + 7];\n    e[8] = array[offset + 8];\n\n    return this;\n  }\n\n  /**\n   * Writes this matrix's elements into a Float32Array\n   *\n   * Without `out`, writes into and returns {@link Matrix3#array}.\n   * @example\n   * ```ts\n   * const rowMajor = new Float32Array(9);\n   *\n   * uvTransform.toArray(true, rowMajor);\n   * ```\n   * @param transpose - `true` writes row-major instead of column-major\n   * @param out - Optional destination array\n   * @returns The populated array\n   */\n  public toArray(transpose?: boolean, out?: Float32Array): Float32Array {\n    if (!this.array) this.array = new Float32Array(9);\n    const arr = out || this.array;\n    const e = this.elements;\n\n    if (transpose) {\n      arr[0] = e[0];\n      arr[1] = e[3];\n      arr[2] = e[6];\n      arr[3] = e[1];\n      arr[4] = e[4];\n      arr[5] = e[7];\n      arr[6] = e[2];\n      arr[7] = e[5];\n      arr[8] = e[8];\n    } else {\n      arr[0] = e[0];\n      arr[1] = e[1];\n      arr[2] = e[2];\n      arr[3] = e[3];\n      arr[4] = e[4];\n      arr[5] = e[5];\n      arr[6] = e[6];\n      arr[7] = e[7];\n      arr[8] = e[8];\n    }\n\n    return arr;\n  }\n\n  /**\n   * Multiplies this matrix by `m`: `this = this * m`, so `m` applies to a point first\n   * @example\n   * ```ts\n   * const atlasUv = new Matrix3();\n   *\n   * frameTransform.multiply(tileTransform, atlasUv);\n   * ```\n   * @param m - Matrix to multiply by\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public multiply(m: Matrix3, out: Matrix3 = this): this {\n    _multiplyMatrices(this, m, out);\n\n    return out as this;\n  }\n\n  /**\n   * Pre-multiplies this matrix by `m`: `this = m * this`, so `m` applies to a point last\n   * @example\n   * ```ts\n   * uvTransform.premultiply(frameTransform);\n   * ```\n   * @param m - Matrix to pre-multiply by\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public premultiply(m: Matrix3, out: Matrix3 = this): this {\n    _multiplyMatrices(m, this, out);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this matrix to `a * b`, so `b` applies to a point first\n   * @example\n   * ```ts\n   * atlasUv.multiplyMatrices(frameTransform, tileTransform);\n   * ```\n   * @param a - Left operand\n   * @param b - Right operand\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public multiplyMatrices(a: Matrix3, b: Matrix3, out: Matrix3 = this): this {\n    _multiplyMatrices(a, b, out);\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies every element of this matrix by the scalar `s`\n   * @param s - Scalar to multiply by\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   * @advanced\n   */\n  public multiplyScalar(s: number, out: Matrix3 = this): this {\n    const te = out.elements;\n    const se = this.elements;\n\n    te[0] = se[0] * s;\n    te[3] = se[3] * s;\n    te[6] = se[6] * s;\n    te[1] = se[1] * s;\n    te[4] = se[4] * s;\n    te[7] = se[7] * s;\n    te[2] = se[2] * s;\n    te[5] = se[5] * s;\n    te[8] = se[8] * s;\n\n    return out as this;\n  }\n\n  /**\n   * Pixi-style alias for {@link Matrix3#multiply}: `this = this * m`\n   * @example\n   * ```ts\n   * frameTransform.append(tileTransform, atlasUv);\n   * ```\n   * @param m - Matrix to append\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public append(m: Matrix3, out: Matrix3 = this): this {\n    return this.multiply(m, out);\n  }\n\n  /**\n   * Pixi-style alias for {@link Matrix3#premultiply}: `this = m * this`\n   * @example\n   * ```ts\n   * uvTransform.prepend(frameTransform);\n   * ```\n   * @param m - Matrix to prepend\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public prepend(m: Matrix3, out: Matrix3 = this): this {\n    return this.premultiply(m, out);\n  }\n\n  /**\n   * Alias for {@link Matrix3#multiplyMatrices}: this matrix becomes `a * b`\n   * @example\n   * ```ts\n   * atlasUv.appendFrom(frameTransform, tileTransform);\n   * ```\n   * @param a - Left operand\n   * @param b - Right operand\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public appendFrom(a: Matrix3, b: Matrix3, out: Matrix3 = this): this {\n    return this.multiplyMatrices(a, b, out);\n  }\n\n  /**\n   * Computes the determinant of this matrix\n   *\n   * Negative when the transform mirrors, and 0 when it flattens a dimension and can't be inverted.\n   * @example\n   * ```ts\n   * const mirrored = uvTransform.determinant() < 0;\n   * ```\n   * @returns The determinant\n   */\n  public determinant(): number {\n    const te = this.elements;\n\n    const a = te[0];\n    const b = te[1];\n    const c = te[2];\n    const d = te[3];\n    const e = te[4];\n    const f = te[5];\n    const g = te[6];\n    const h = te[7];\n    const i = te[8];\n\n    return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;\n  }\n\n  /**\n   * Transposes this matrix\n   * @example\n   * ```ts\n   * const rowMajor = new Matrix3();\n   *\n   * normalMatrix.transpose(rowMajor);\n   * ```\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public transpose(out: Matrix3 = this): this {\n    const m = this.elements;\n    const te = out.elements;\n\n    const m0 = m[0];\n    const m1 = m[1];\n    const m2 = m[2];\n    const m3 = m[3];\n    const m4 = m[4];\n    const m5 = m[5];\n    const m6 = m[6];\n    const m7 = m[7];\n    const m8 = m[8];\n\n    te[0] = m0;\n    te[1] = m3;\n    te[2] = m6;\n    te[3] = m1;\n    te[4] = m4;\n    te[5] = m7;\n    te[6] = m2;\n    te[7] = m5;\n    te[8] = m8;\n\n    return out as this;\n  }\n\n  /**\n   * Sets this matrix to the inverse of `m`\n   *\n   * When `m` can't be inverted (its determinant is 0), the result is the identity and a warning is\n   * logged.\n   * @example\n   * ```ts\n   * const screenToUv = new Matrix3().getInverse(uvToScreen);\n   * ```\n   * @param m - Matrix to invert\n   * @param throwOnDegenerate - `true` throws instead of warning when `m` can't be inverted\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public getInverse(m: Matrix3, throwOnDegenerate?: boolean, out: Matrix3 = this): this {\n    const me = m.elements;\n    const te = out.elements;\n\n    const n11 = me[0];\n    const n21 = me[1];\n    const n31 = me[2];\n    const n12 = me[3];\n    const n22 = me[4];\n    const n32 = me[5];\n    const n13 = me[6];\n    const n23 = me[7];\n    const n33 = me[8];\n\n    const t11 = n33 * n22 - n32 * n23;\n    const t12 = n32 * n13 - n33 * n12;\n    const t13 = n23 * n12 - n22 * n13;\n\n    const det = n11 * t11 + n21 * t12 + n31 * t13;\n\n    if (det === 0) {\n      const msg = \"Matrix3: .getInverse() can't invert matrix, determinant is 0\";\n\n      if (throwOnDegenerate === true) {\n        throw new Error(msg);\n      } else {\n        warn(msg);\n      }\n\n      out.identity();\n      return out as this;\n    }\n\n    const detInv = 1 / det;\n\n    te[0] = t11 * detInv;\n    te[1] = (n31 * n23 - n33 * n21) * detInv;\n    te[2] = (n32 * n21 - n31 * n22) * detInv;\n\n    te[3] = t12 * detInv;\n    te[4] = (n33 * n11 - n31 * n13) * detInv;\n    te[5] = (n31 * n12 - n32 * n11) * detInv;\n\n    te[6] = t13 * detInv;\n    te[7] = (n21 * n13 - n23 * n11) * detInv;\n    te[8] = (n22 * n11 - n21 * n12) * detInv;\n\n    return out as this;\n  }\n\n  /**\n   * Moves this 2D transform by `(tx, ty)`, applied after the transform built so far, like pixi's\n   * `Matrix.translate`\n   * @example\n   * ```ts\n   * app.ticker.add((ticker) => {\n   *   uvTransform.identity().translate((ticker.lastTime * 0.0001) % 1, 0);\n   * });\n   * ```\n   * @param tx - Translation along x\n   * @param ty - Translation along y\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public translate(tx: number, ty: number, out: Matrix3 = this): this {\n    if (out !== this) out.copyFrom(this);\n    const te = out.elements;\n\n    te[0] += tx * te[2];\n    te[3] += tx * te[5];\n    te[6] += tx * te[8];\n    te[1] += ty * te[2];\n    te[4] += ty * te[5];\n    te[7] += ty * te[8];\n\n    return out as this;\n  }\n\n  /**\n   * Scales this 2D transform by `(sx, sy)` about the origin, applied after the transform built so\n   * far, like pixi's `Matrix.scale`\n   * @example\n   * ```ts\n   * const tiled = new Matrix3().scale(4, 4);\n   * ```\n   * @param sx - Scale along x\n   * @param sy - Scale along y\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public scale(sx: number, sy: number, out: Matrix3 = this): this {\n    if (out !== this) out.copyFrom(this);\n    const te = out.elements;\n\n    te[0] *= sx;\n    te[3] *= sx;\n    te[6] *= sx;\n    te[1] *= sy;\n    te[4] *= sy;\n    te[7] *= sy;\n\n    return out as this;\n  }\n\n  /**\n   * Rotates this matrix by `theta` radians around the origin (2D affine)\n   *\n   * The rotation applies after the existing transform, and a positive angle turns +x toward +y,\n   * the same as pixi's `Matrix.rotate`.\n   * @example\n   * ```ts\n   * const spin = new Matrix3().translate(-0.5, -0.5).rotate(angle).translate(0.5, 0.5);\n   * ```\n   * @param theta - Rotation angle in radians\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public rotate(theta: number, out: Matrix3 = this): this {\n    if (out !== this) out.copyFrom(this);\n    const c = Math.cos(theta);\n    const s = Math.sin(theta);\n\n    const te = out.elements;\n\n    const a11 = te[0];\n    const a12 = te[3];\n    const a13 = te[6];\n    const a21 = te[1];\n    const a22 = te[4];\n    const a23 = te[7];\n\n    te[0] = c * a11 - s * a21;\n    te[3] = c * a12 - s * a22;\n    te[6] = c * a13 - s * a23;\n\n    te[1] = s * a11 + c * a21;\n    te[4] = s * a12 + c * a22;\n    te[7] = s * a13 + c * a23;\n\n    return out as this;\n  }\n\n  /**\n   * Sets this matrix to a UV transform: rotate by `rotation` and scale by `(sx, sy)`, both about\n   * `(cx, cy)`, then offset by `(tx, ty)`\n   *\n   * A positive `rotation` turns +u toward -v. The rotation applies before the scale, which is the\n   * opposite of glTF's `KHR_texture_transform`, so the two disagree when the scale is non-uniform\n   * and the rotation isn't zero. A material's UVs take a pixi `Matrix` in\n   * {@link BaseMaterial3D#uvTransform} instead.\n   * @example\n   * ```ts\n   * const uvTransform = new Matrix3().setUvTransform(0, 0, 2, 2, Math.PI / 4, 0.5, 0.5);\n   * ```\n   * @param tx - Translation along u\n   * @param ty - Translation along v\n   * @param sx - Scale along u\n   * @param sy - Scale along v\n   * @param rotation - Rotation angle in radians\n   * @param cx - Rotation center u\n   * @param cy - Rotation center v\n   * @returns This matrix\n   */\n  public setUvTransform(\n    tx: number,\n    ty: number,\n    sx: number,\n    sy: number,\n    rotation: number,\n    cx: number,\n    cy: number,\n  ): this {\n    const c = Math.cos(rotation);\n    const s = Math.sin(rotation);\n\n    return this.set(\n      sx * c,\n      sx * s,\n      -sx * (c * cx + s * cy) + cx + tx,\n      -sy * s,\n      sy * c,\n      -sy * (-s * cx + c * cy) + cy + ty,\n      0,\n      0,\n      1,\n    );\n  }\n\n  /**\n   * Sets this matrix to the upper-left 3x3 block of the given {@link Matrix4}: its rotation and\n   * scale, without the translation\n   * @example\n   * ```ts\n   * const linear = new Matrix3().setFromMatrix4(mesh.worldTransform);\n   * const worldOffset = localOffset.clone().applyMatrix3(linear);\n   * ```\n   * @param m - Matrix to read from\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public setFromMatrix4(m: Matrix4, out: Matrix3 = this): this {\n    const me = m.elements;\n\n    out.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);\n\n    return out as this;\n  }\n\n  /**\n   * Sets this matrix to the normal matrix of `matrix4`: the inverse transpose of its upper-left\n   * 3x3 block\n   *\n   * Normals transformed by it stay at right angles to the surface when the model has non-uniform\n   * scale; renormalize them after. A matrix with zero scale on an axis gives the identity and logs\n   * a warning.\n   * @example\n   * ```ts\n   * const normalMatrix = new Matrix3().getNormalMatrix(mesh.worldTransform);\n   * const worldNormal = hitNormal.clone().applyMatrix3(normalMatrix).normalize();\n   * ```\n   * @param matrix4 - World matrix to derive the normal matrix from\n   * @param out - Optional target; defaults to writing into this matrix\n   * @returns The matrix the result was written to\n   */\n  public getNormalMatrix(matrix4: Matrix4, out: Matrix3 = this): this {\n    out.setFromMatrix4(matrix4).getInverse(out).transpose();\n\n    return out as this;\n  }\n}\n\nfunction _multiplyMatrices(a: Matrix3, b: Matrix3, target: Matrix3): Matrix3 {\n  const ae = a.elements;\n  const be = b.elements;\n  const te = target.elements;\n\n  const a11 = ae[0];\n  const a12 = ae[3];\n  const a13 = ae[6];\n  const a21 = ae[1];\n  const a22 = ae[4];\n  const a23 = ae[7];\n  const a31 = ae[2];\n  const a32 = ae[5];\n  const a33 = ae[8];\n\n  const b11 = be[0];\n  const b12 = be[3];\n  const b13 = be[6];\n  const b21 = be[1];\n  const b22 = be[4];\n  const b23 = be[7];\n  const b31 = be[2];\n  const b32 = be[5];\n  const b33 = be[8];\n\n  te[0] = a11 * b11 + a12 * b21 + a13 * b31;\n  te[3] = a11 * b12 + a12 * b22 + a13 * b32;\n  te[6] = a11 * b13 + a12 * b23 + a13 * b33;\n\n  te[1] = a21 * b11 + a22 * b21 + a23 * b31;\n  te[4] = a21 * b12 + a22 * b22 + a23 * b32;\n  te[7] = a21 * b13 + a22 * b23 + a23 * b33;\n\n  te[2] = a31 * b11 + a32 * b21 + a33 * b31;\n  te[5] = a31 * b12 + a32 * b22 + a33 * b32;\n  te[8] = a31 * b13 + a32 * b23 + a33 * b33;\n\n  return target;\n}\n\nconst _sharedMatrix = new Matrix3();\nconst _identityMatrix = new Matrix3();\n","import type { SHAPE_PRIMITIVE_3D } from '../misc/const';\nimport type { PointData3D } from '../vector/PointData3D';\n\n/**\n * A point given as `radius`, `theta` and `y`: its distance from the Y axis, its angle around that\n * axis measured from +Z toward +X, and its height\n *\n * Use it to lay things out around a vertical axis, such as a ring of pillars or a spiral staircase,\n * then convert back with {@link Vector3#setFromCylindrical}.\n * @example\n * ```ts\n * const step = new Cylindrical();\n *\n * for (let i = 0; i < stairs.length; i++) {\n *   step.set(4, i * 0.4, i * 0.25);\n *   stairs[i].position.setFromCylindrical(step);\n * }\n * ```\n * @category maths\n * @standard\n */\nexport class Cylindrical {\n  /**\n   * Distance from the Y axis\n   * @example\n   * ```ts\n   * ring.radius = arenaRadius - 1;\n   * ```\n   */\n  public radius = 0;\n  /**\n   * Angle in radians around the Y axis, measured from +Z toward +X\n   * @example\n   * ```ts\n   * carousel.theta += ticker.deltaMS * 0.001;\n   * ```\n   */\n  public theta = 0;\n  /**\n   * Height above the XZ plane\n   * @example\n   * ```ts\n   * spiral.y += climbSpeed;\n   * ```\n   */\n  public y = 0;\n\n  /**\n   * Names the shape without an `instanceof` check, like the `type` on pixi's 2D shapes\n   * @readonly\n   * @default 'cylindrical'\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type: SHAPE_PRIMITIVE_3D = 'cylindrical';\n\n  /**\n   * Creates a new `Cylindrical`\n   * @param radius - Distance from the Y axis\n   * @param theta - Azimuthal angle (radians) measured from +Z\n   * @param y - Height above the XZ plane\n   */\n  constructor(radius = 1, theta = 0, y = 0) {\n    this.radius = radius;\n    this.theta = theta;\n    this.y = y;\n  }\n\n  /**\n   * Sets `radius`, `theta` and `y`\n   * @example\n   * ```ts\n   * const slot = new Cylindrical().set(6, (index / count) * Math.PI * 2, 0);\n   * ```\n   * @param radius - Distance from the Y axis\n   * @param theta - Azimuthal angle (radians) measured from +Z\n   * @param y - Height above the XZ plane\n   * @returns This instance for chaining\n   */\n  public set(radius: number, theta: number, y: number): this {\n    this.radius = radius;\n    this.theta = theta;\n    this.y = y;\n\n    return this;\n  }\n\n  /**\n   * Copies `other` into this instance\n   * @example\n   * ```ts\n   * restingSlot.copyFrom(slot);\n   * ```\n   * @param other - The coordinates to copy from\n   * @returns This instance for chaining\n   */\n  public copyFrom(other: Cylindrical): this {\n    this.radius = other.radius;\n    this.theta = other.theta;\n    this.y = other.y;\n\n    return this;\n  }\n\n  /**\n   * Copies this instance into `target` and returns it\n   * @example\n   * ```ts\n   * slot.copyTo(restingSlot);\n   * ```\n   * @param target - The instance to copy into\n   * @returns The given `target`\n   */\n  public copyTo<T extends Cylindrical>(target: T): T {\n    target.radius = this.radius;\n    target.theta = this.theta;\n    target.y = this.y;\n\n    return target;\n  }\n\n  /**\n   * Creates a new `Cylindrical` with the same values\n   * @example\n   * ```ts\n   * const start = slot.clone();\n   * ```\n   * @returns The new instance\n   */\n  public clone(): Cylindrical {\n    return new Cylindrical().copyFrom(this);\n  }\n\n  /**\n   * Returns true when `radius`, `theta` and `y` match `other` exactly (no epsilon tolerance)\n   * @example\n   * ```ts\n   * const settled = slot.equals(restingSlot);\n   * ```\n   * @param other - The coordinates to compare with\n   * @returns Whether all components match\n   */\n  public equals(other: Cylindrical): boolean {\n    return other.radius === this.radius && other.theta === this.theta && other.y === this.y;\n  }\n\n  /**\n   * Sets this instance from the Cartesian point `v`\n   * @example\n   * ```ts\n   * const around = new Cylindrical().setFromPoint3D(player.position);\n   * ```\n   * @param v - The Cartesian point to convert\n   * @returns This instance for chaining\n   */\n  public setFromPoint3D(v: PointData3D): this {\n    return this.setFromCartesianCoords(v.x, v.y, v.z);\n  }\n\n  /**\n   * Sets this instance from Cartesian `(x, y, z)`\n   * @example\n   * ```ts\n   * const around = new Cylindrical().setFromCartesianCoords(pointer.x, 0, pointer.z);\n   * ```\n   * @param x - The Cartesian x coordinate\n   * @param y - The Cartesian y coordinate\n   * @param z - The Cartesian z coordinate\n   * @returns This instance for chaining\n   */\n  public setFromCartesianCoords(x: number, y: number, z: number): this {\n    this.radius = Math.sqrt(x * x + z * z);\n    this.theta = Math.atan2(x, z);\n    this.y = y;\n\n    return this;\n  }\n\n  /**\n   * Returns a string representation of these coordinates\n   * @returns A string in the form `[@pixi/3d/math:Cylindrical radius=1 theta=0 y=0]`\n   * @advanced\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Cylindrical radius=${this.radius} theta=${this.theta} y=${this.y}]`;\n  }\n}\n","import type { SHAPE_PRIMITIVE_3D } from '../misc/const';\nimport { clamp } from '../utils/clamp';\nimport type { PointData3D } from '../vector/PointData3D';\n\n/**\n * A point given as `radius`, `phi` and `theta` around the origin: its distance, its angle down\n * from +Y, and its angle around +Y, measured from +Z toward +X\n *\n * Use it for anything that orbits: convert a position in, change the angles, then convert back\n * with {@link Vector3#setFromSpherical}.\n * @example\n * ```ts\n * const orbit = new Spherical().setFromPoint3D(camera.position);\n *\n * orbit.theta += 0.01;\n * orbit.phi -= 0.005;\n * orbit.makeSafe();\n * camera.position.setFromSpherical(orbit);\n * camera.lookAt({ x: 0, y: 0, z: 0 });\n * ```\n * @category maths\n * @standard\n */\nexport class Spherical {\n  /**\n   * Distance from the origin\n   * @example\n   * ```ts\n   * orbit.radius = Math.max(2, orbit.radius - wheelDelta * 0.01);\n   * ```\n   */\n  public radius = 0;\n  /**\n   * Angle in radians down from +Y: `0` points straight up, `π / 2` lies level, `π` points straight\n   * down\n   * @example\n   * ```ts\n   * orbit.phi = Math.PI / 3;\n   * ```\n   */\n  public phi = 0;\n  /**\n   * Angle in radians around +Y, measured from +Z toward +X\n   * @example\n   * ```ts\n   * orbit.theta += ticker.deltaMS * 0.0005;\n   * ```\n   */\n  public theta = 0;\n\n  /**\n   * Names the shape without an `instanceof` check, like the `type` on pixi's 2D shapes\n   * @readonly\n   * @default 'spherical'\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type: SHAPE_PRIMITIVE_3D = 'spherical';\n\n  /**\n   * Creates a new `Spherical`\n   * @param radius - Distance from origin\n   * @param phi - Polar angle (radians) measured from +Y\n   * @param theta - Azimuthal angle (radians) measured from +Z\n   */\n  constructor(radius = 1, phi = 0, theta = 0) {\n    this.radius = radius;\n    this.phi = phi;\n    this.theta = theta;\n  }\n\n  /**\n   * Sets `radius`, `phi` and `theta`\n   * @example\n   * ```ts\n   * const sunDirection = new Vector3().setFromSpherical(new Spherical().set(1, sunPolarAngle, sunAzimuth));\n   * ```\n   * @param radius - Distance from origin\n   * @param phi - Polar angle (radians) measured from +Y\n   * @param theta - Azimuthal angle (radians) measured from +Z\n   * @returns This spherical, for chaining\n   */\n  public set(radius: number, phi: number, theta: number): this {\n    this.radius = radius;\n    this.phi = phi;\n    this.theta = theta;\n\n    return this;\n  }\n\n  /**\n   * Copies `other` into this spherical\n   * @example\n   * ```ts\n   * savedView.copyFrom(orbit);\n   * ```\n   * @param other - The spherical to copy from\n   * @returns This spherical, for chaining\n   */\n  public copyFrom(other: Spherical): this {\n    this.radius = other.radius;\n    this.phi = other.phi;\n    this.theta = other.theta;\n\n    return this;\n  }\n\n  /**\n   * Copies this spherical into `target`\n   * @example\n   * ```ts\n   * orbit.copyTo(savedView);\n   * ```\n   * @param target - The spherical to copy into\n   * @returns The target with values updated\n   */\n  public copyTo<T extends Spherical>(target: T): T {\n    target.radius = this.radius;\n    target.phi = this.phi;\n    target.theta = this.theta;\n\n    return target;\n  }\n\n  /**\n   * Creates a copy of this spherical\n   * @example\n   * ```ts\n   * const resetView = orbit.clone();\n   * ```\n   * @returns A new `Spherical` with the same values\n   */\n  public clone(): Spherical {\n    return new Spherical().copyFrom(this);\n  }\n\n  /**\n   * Checks whether `other` matches this spherical\n   * @example\n   * ```ts\n   * if (!orbit.equals(lastOrbit)) saveCameraState(orbit);\n   * ```\n   * @param other - The spherical to compare with\n   * @returns `true` when `radius`, `phi` and `theta` match exactly (no epsilon tolerance)\n   */\n  public equals(other: Spherical): boolean {\n    return other.radius === this.radius && other.phi === this.phi && other.theta === this.theta;\n  }\n\n  /**\n   * Keeps `phi` a millionth of a radian away from both poles\n   *\n   * A camera that looks at its target with +Y up flips at a pole, so call this after changing\n   * `phi` and before converting back.\n   * @example\n   * ```ts\n   * orbit.phi -= pointerDeltaY * 0.01;\n   * orbit.makeSafe();\n   * ```\n   * @returns This spherical, for chaining\n   */\n  public makeSafe(): this {\n    const EPS = 0.000001;\n    this.phi = clamp(this.phi, EPS, Math.PI - EPS);\n\n    return this;\n  }\n\n  /**\n   * Sets this spherical from the Cartesian point `v`\n   * @example\n   * ```ts\n   * const orbit = new Spherical().setFromPoint3D(camera.position);\n   * ```\n   * @param v - The Cartesian point to convert\n   * @returns This spherical, for chaining\n   */\n  public setFromPoint3D(v: PointData3D): this {\n    return this.setFromCartesianCoords(v.x, v.y, v.z);\n  }\n\n  /**\n   * Sets this spherical from Cartesian `(x, y, z)`\n   *\n   * Zero-radius inputs collapse `theta` and `phi` to 0.\n   * @example\n   * ```ts\n   * orbit.setFromCartesianCoords(eye.x - target.x, eye.y - target.y, eye.z - target.z);\n   * ```\n   * @param x - Position on the x axis\n   * @param y - Position on the y axis\n   * @param z - Position on the z axis\n   * @returns This spherical, for chaining\n   */\n  public setFromCartesianCoords(x: number, y: number, z: number): this {\n    this.radius = Math.sqrt(x * x + y * y + z * z);\n\n    if (this.radius === 0) {\n      this.theta = 0;\n      this.phi = 0;\n    } else {\n      this.theta = Math.atan2(x, z);\n      this.phi = Math.acos(clamp(y / this.radius, -1, 1));\n    }\n\n    return this;\n  }\n\n  /**\n   * Returns a readable string representation of this spherical\n   * @returns A string in the form `[@pixi/3d/math:Spherical radius=1 phi=0 theta=0]`\n   * @advanced\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Spherical radius=${this.radius} phi=${this.phi} theta=${this.theta}]`;\n  }\n}\n","/**\n * Creates a random function that returns the same sequence of numbers in `[0, 1)` for the same seed\n *\n * Use it wherever `Math.random` would go when results must repeat, such as a level generated from a\n * shared seed or a replay. It runs mulberry32, seeded by hashing the string with xmur3, and isn't\n * safe for cryptography.\n * @see https://stackoverflow.com/a/47593316\n * @example\n * ```ts\n * const random = seededRandom(`level-${levelNumber}`);\n *\n * for (const slot of treeSlots) {\n *   if (random() < 0.3) plantTree(slot, 0.8 + random() * 0.4);\n * }\n * ```\n * @param seed - Any string; the same string always gives the same sequence\n * @returns Function that can be used in place of `Math.random`\n * @category maths\n * @standard\n */\nexport function seededRandom(seed: string): () => number {\n  return mulberry32(xmur3(seed)());\n}\n\nfunction xmur3(str: string): () => number {\n  let h = 1779033703 ^ str.length;\n\n  for (let i = 0; i < str.length; i++) {\n    h = Math.imul(h ^ str.charCodeAt(i), 3432918353);\n    h = (h << 13) | (h >>> 19);\n  }\n\n  return (): number => {\n    h = Math.imul(h ^ (h >>> 16), 2246822507);\n    h = Math.imul(h ^ (h >>> 13), 3266489909);\n\n    return (h ^= h >>> 16) >>> 0;\n  };\n}\n\n/** The state sits in an `Int32Array`, not a closure variable, because draws measured faster that way */\nfunction mulberry32(seed: number): () => number {\n  const state = new Int32Array(1);\n\n  state[0] = seed;\n\n  return (): number => {\n    const a = (state[0] = (state[0] + 0x6d2b79f5) | 0);\n    let t = Math.imul(a ^ (a >>> 15), a | 1);\n\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n","import type { Matrix4 } from '../matrix/Matrix4';\nimport { clamp } from '../utils/clamp';\nimport type { PointData4D } from './PointData4D';\nimport type { PointLike4D } from './PointLike4D';\n\n/**\n * A four-component vector, such as a position with a `w`, an RGBA colour or a plane equation\n *\n * Math methods work on all four components, change the vector they're called on and return it; pass\n * an `out` point last to write the result there instead. Where a method takes a point, any\n * {@link PointData4D} works, such as a plain `{ x, y, z, w }` object.\n * @example\n * ```ts\n * const clip = new Vector4(point.x, point.y, point.z, 1).applyMatrix4(camera.viewProjection);\n *\n * if (clip.w > 0) clip.divideScalar(clip.w);\n * ```\n * @category maths\n * @standard\n */\nexport class Vector4 implements PointLike4D {\n  /**\n   * The x component\n   * @example\n   * ```ts\n   * const screenX = clip.x / clip.w;\n   * ```\n   */\n  public x = 0;\n  /**\n   * The y component\n   * @example\n   * ```ts\n   * const screenY = clip.y / clip.w;\n   * ```\n   */\n  public y = 0;\n  /**\n   * The z component\n   * @example\n   * ```ts\n   * const depth = clip.z / clip.w;\n   * ```\n   */\n  public z = 0;\n  /**\n   * The fourth component, by convention `1` for a position and `0` for a direction\n   * @example\n   * ```ts\n   * const behindCamera = clip.w <= 0;\n   * ```\n   */\n  public w = 1;\n\n  /**\n   * A static `Vector4` reset to `(0, 0, 0, 1)` on every access, for a result used straight away\n   *\n   * > [!IMPORTANT] This vector is shared and temporary. Do not store references to it.\n   * @example\n   * ```ts\n   * const clipW = Vector4.shared.set(point.x, point.y, point.z).applyMatrix4(camera.viewProjection).w;\n   * ```\n   */\n  static get shared(): Vector4 {\n    _shared.x = 0;\n    _shared.y = 0;\n    _shared.z = 0;\n    _shared.w = 1;\n\n    return _shared;\n  }\n\n  /**\n   * Creates a new `Vector4`\n   * @param x - The x component\n   * @param y - The y component\n   * @param z - The z component\n   * @param w - The fourth component, defaults to `1`\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  /**\n   * Sets all four components\n   * @example\n   * ```ts\n   * position.set(0, 2, -5);\n   * direction.set(0, 0, -1, 0);\n   * ```\n   * @param x - The x component\n   * @param y - The y component, defaults to `x`\n   * @param z - The z component, defaults to `x`\n   * @param w - The fourth component, defaults to `1`, not to `x`\n   */\n  public set(x = 0, y = x, z = x, w = 1): this {\n    this.x = x;\n    this.y = y;\n    this.z = z;\n    this.w = w;\n\n    return this;\n  }\n\n  /**\n   * Copies x, y, z, w from the given point into this vector\n   * @example\n   * ```ts\n   * previousClip.copyFrom(clip);\n   * ```\n   * @param p - The point to copy from\n   */\n  public copyFrom(p: PointData4D): this {\n    this.x = p.x;\n    this.y = p.y;\n    this.z = p.z;\n    this.w = p.w;\n\n    return this;\n  }\n\n  /**\n   * Copies this vector's x, y, z, w into the given point\n   * @example\n   * ```ts\n   * clip.copyTo(previousClip);\n   * ```\n   * @param p - The point to copy into\n   * @returns The given point\n   */\n  public copyTo<T extends PointLike4D>(p: T): T {\n    p.set(this.x, this.y, this.z, this.w);\n\n    return p;\n  }\n\n  /**\n   * Checks whether `x`, `y`, `z` and `w` all match `p` exactly, with no tolerance\n   * @example\n   * ```ts\n   * if (!tint.equals(lastTint)) applyTint(tint);\n   * ```\n   * @param p - The point to compare against\n   */\n  public equals(p: PointData4D): boolean {\n    return p.x === this.x && p.y === this.y && p.z === this.z && p.w === this.w;\n  }\n\n  /**\n   * Creates a copy of this vector\n   * @example\n   * ```ts\n   * const startColor = color.clone();\n   * ```\n   */\n  public clone(): Vector4 {\n    return new Vector4(this.x, this.y, this.z, this.w);\n  }\n\n  /**\n   * Builds a debug string for this vector\n   * @example\n   * ```ts\n   * console.log(clip.toString());\n   * ```\n   * @returns A string of the form `[@pixi/3d/math:Vector4 x=... y=... z=... w=...]`\n   */\n  public toString(): string {\n    return `[@pixi/3d/math:Vector4 x=${this.x} y=${this.y} z=${this.z} w=${this.w}]`;\n  }\n\n  /**\n   * Reads `x`, `y`, `z`, `w` from `array` starting at `offset`\n   * @example\n   * ```ts\n   * tangent.fromArray(tangents, vertexIndex * 4);\n   * ```\n   * @param array - The source array\n   * @param offset - Index of the first component in `array`\n   */\n  public fromArray(array: number[] | Float32Array, offset = 0): this {\n    this.x = array[offset];\n    this.y = array[offset + 1];\n    this.z = array[offset + 2];\n    this.w = array[offset + 3];\n\n    return this;\n  }\n\n  /**\n   * Writes this vector's values into `array` starting at `offset`\n   * @example\n   * ```ts\n   * color.toArray(instanceColors, instanceIndex * 4);\n   * ```\n   * @param array - The destination array; a new one is allocated when omitted\n   * @param offset - Index of the first component in `array`\n   * @returns The destination array\n   */\n  public toArray<T extends number[] | Float32Array = number[]>(array: T = [] as unknown as T, offset = 0): T {\n    array[offset] = this.x;\n    array[offset + 1] = this.y;\n    array[offset + 2] = this.z;\n    array[offset + 3] = this.w;\n\n    return array;\n  }\n\n  /**\n   * Adds `v` to this vector\n   * @example\n   * ```ts\n   * baseColor.add(hitFlash, displayColor);\n   * ```\n   * @param v - The point to add\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public add(v: PointData4D, out: PointLike4D = this): this {\n    out.x = this.x + v.x;\n    out.y = this.y + v.y;\n    out.z = this.z + v.z;\n    out.w = this.w + v.w;\n\n    return out as this;\n  }\n\n  /**\n   * Subtracts `v` from this vector\n   * @example\n   * ```ts\n   * targetColor.subtract(color, colorStep);\n   * ```\n   * @param v - The point to subtract\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public subtract(v: PointData4D, out: PointLike4D = this): this {\n    out.x = this.x - v.x;\n    out.y = this.y - v.y;\n    out.z = this.z - v.z;\n    out.w = this.w - v.w;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies each component of this vector by the matching component of `v`\n   * @example\n   * ```ts\n   * baseColor.multiply(teamTint, displayColor);\n   * ```\n   * @param v - The point to multiply by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public multiply(v: PointData4D, out: PointLike4D = this): this {\n    out.x = this.x * v.x;\n    out.y = this.y * v.y;\n    out.z = this.z * v.z;\n    out.w = this.w * v.w;\n\n    return out as this;\n  }\n\n  /**\n   * Multiplies each component of this vector by the scalar `s`\n   * @example\n   * ```ts\n   * color.multiplyScalar(brightness);\n   * ```\n   * @param s - The scalar to multiply by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public multiplyScalar(s: number, out: PointLike4D = this): this {\n    out.x = this.x * s;\n    out.y = this.y * s;\n    out.z = this.z * s;\n    out.w = this.w * s;\n\n    return out as this;\n  }\n\n  /**\n   * Divides each component of this vector by the matching component of `v`\n   * @example\n   * ```ts\n   * hdrColor.divide(whitePoint, displayColor);\n   * ```\n   * @param v - The point to divide by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public divide(v: PointData4D, out: PointLike4D = this): this {\n    out.x = this.x / v.x;\n    out.y = this.y / v.y;\n    out.z = this.z / v.z;\n    out.w = this.w / v.w;\n\n    return out as this;\n  }\n\n  /**\n   * Divides each component of this vector by the scalar `s`\n   * @example\n   * ```ts\n   * clip.divideScalar(clip.w);\n   * ```\n   * @param s - The scalar to divide by\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public divideScalar(s: number, out: PointLike4D = this): this {\n    return this.multiplyScalar(1 / s, out);\n  }\n\n  /**\n   * Adds `v * s` to this vector\n   * @example\n   * ```ts\n   * color.addScaledVector(colorStep, fadeSpeed * dt);\n   * ```\n   * @param v - The point to scale and add\n   * @param s - The scalar applied to `v`\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public addScaledVector(v: PointData4D, s: number, out: PointLike4D = this): this {\n    out.x = this.x + v.x * s;\n    out.y = this.y + v.y * s;\n    out.z = this.z + v.z * s;\n    out.w = this.w + v.w * s;\n\n    return out as this;\n  }\n\n  /**\n   * Negates each component of this vector\n   * @example\n   * ```ts\n   * clipPlane.negate();\n   * ```\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public negate(out: PointLike4D = this): this {\n    out.x = -this.x;\n    out.y = -this.y;\n    out.z = -this.z;\n    out.w = -this.w;\n\n    return out as this;\n  }\n\n  /**\n   * Sets each component to the smaller of this vector's and `v`'s\n   * @example\n   * ```ts\n   * color.min({ x: 1, y: 1, z: 1, w: 1 });\n   * ```\n   * @param v - The point to compare against\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public min(v: PointData4D, out: PointLike4D = this): this {\n    out.x = Math.min(this.x, v.x);\n    out.y = Math.min(this.y, v.y);\n    out.z = Math.min(this.z, v.z);\n    out.w = Math.min(this.w, v.w);\n\n    return out as this;\n  }\n\n  /**\n   * Sets each component to the larger of this vector's and `v`'s\n   * @example\n   * ```ts\n   * color.max({ x: 0, y: 0, z: 0, w: 0 });\n   * ```\n   * @param v - The point to compare against\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public max(v: PointData4D, out: PointLike4D = this): this {\n    out.x = Math.max(this.x, v.x);\n    out.y = Math.max(this.y, v.y);\n    out.z = Math.max(this.z, v.z);\n    out.w = Math.max(this.w, v.w);\n\n    return out as this;\n  }\n\n  /**\n   * Clamps each component of this vector between the matching components of `min` and `max`\n   *\n   * Assumes `min <= max` componentwise.\n   * @example\n   * ```ts\n   * hdrColor.clamp({ x: 0, y: 0, z: 0, w: 0 }, { x: 1, y: 1, z: 1, w: 1 }, displayColor);\n   * ```\n   * @param min - The lower bound per component\n   * @param max - The upper bound per component\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public clamp(min: PointData4D, max: PointData4D, out: PointLike4D = this): this {\n    out.x = clamp(this.x, min.x, max.x);\n    out.y = clamp(this.y, min.y, max.y);\n    out.z = clamp(this.z, min.z, max.z);\n    out.w = clamp(this.w, min.w, max.w);\n\n    return out as this;\n  }\n\n  /**\n   * Scales this vector to unit length across all four components\n   *\n   * A zero vector stays zero.\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- same operation as on Vector3\n  public normalize(out: PointLike4D = this): this {\n    const len = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w) || 1;\n    const inv = 1 / len;\n    out.x = this.x * inv;\n    out.y = this.y * inv;\n    out.z = this.z * inv;\n    out.w = this.w * inv;\n\n    return out as this;\n  }\n\n  /**\n   * Scales this vector so its length across all four components equals `length`\n   *\n   * A zero vector stays zero.\n   * @param length - The target length\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- same operation as on Vector3\n  public setLength(length: number, out: PointLike4D = this): this {\n    const len = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w) || 1;\n    const inv = length / len;\n    out.x = this.x * inv;\n    out.y = this.y * inv;\n    out.z = this.z * inv;\n    out.w = this.w * inv;\n\n    return out as this;\n  }\n\n  /** Computes the length of this vector across all four components */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- same operation as on Vector3\n  public magnitude(): number {\n    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n  }\n\n  /**\n   * Computes the squared length of this vector\n   *\n   * Cheaper than {@link Vector4#magnitude}, since it skips the square root, and enough to compare\n   * lengths.\n   * @example\n   * ```ts\n   * const moving = velocity.magnitudeSquared() > 0.0001;\n   * ```\n   */\n  public magnitudeSquared(): number {\n    return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;\n  }\n\n  /**\n   * Computes the distance from this vector to `v` across all four components\n   * @example\n   * ```ts\n   * const colorDifference = pixel.distanceTo(keyColor);\n   * ```\n   * @param v - The point to measure to\n   */\n  public distanceTo(v: PointData4D): number {\n    return Math.sqrt(this.distanceToSquared(v));\n  }\n\n  /**\n   * Computes the squared distance from this vector to `v`\n   *\n   * Cheaper than {@link Vector4#distanceTo} and enough to compare distances.\n   * @example\n   * ```ts\n   * if (pixel.distanceToSquared(keyColor) < tolerance * tolerance) pixel.w = 0;\n   * ```\n   * @param v - The point to measure to\n   */\n  public distanceToSquared(v: PointData4D): number {\n    const dx = this.x - v.x;\n    const dy = this.y - v.y;\n    const dz = this.z - v.z;\n    const dw = this.w - v.w;\n\n    return dx * dx + dy * dy + dz * dz + dw * dw;\n  }\n\n  /**\n   * Computes the dot product of this vector and `v`\n   *\n   * With a plane `(nx, ny, nz, d)` whose normal has unit length and a point whose `w` is 1, it's the\n   * point's signed distance from the plane.\n   * @example\n   * ```ts\n   * const inFront = clipPlane.dot(point) > 0;\n   * ```\n   * @param v - The other vector\n   */\n  public dot(v: PointData4D): number {\n    return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;\n  }\n\n  /**\n   * Computes the angle between this vector and `v` across all four components\n   *\n   * Returns π/2 when either vector has zero length.\n   * @param v - The other vector\n   * @returns The angle in radians, from 0 to π\n   */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- same operation as on Vector3\n  public angleTo(v: PointData4D): number {\n    const denominator = Math.sqrt(this.magnitudeSquared() * (v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w));\n    if (denominator === 0) return Math.PI / 2;\n    const theta = this.dot(v) / denominator;\n\n    return Math.acos(clamp(theta, -1, 1));\n  }\n\n  /**\n   * Multiplies this vector by `m`, `w` included, without a divide\n   *\n   * A position (`w = 1`) picks up the matrix's translation and a direction (`w = 0`) doesn't. With a\n   * projection matrix the result is in clip space; divide by `w` to get x and y from -1 to 1 across\n   * the view.\n   * @example\n   * ```ts\n   * clip.set(point.x, point.y, point.z).applyMatrix4(camera.viewProjection);\n   * ```\n   * @param m - The matrix to apply\n   * @param out - The target to write the result into, defaults to this vector\n   * @returns The `out` point\n   */\n  public applyMatrix4(m: Matrix4, out: PointLike4D = this): this {\n    const x = this.x;\n    const y = this.y;\n    const z = this.z;\n    const w = this.w;\n    const e = m.elements;\n    out.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;\n    out.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;\n    out.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;\n    out.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;\n\n    return out as this;\n  }\n}\n\nconst _shared = new Vector4();\n","import type { ShaderBit } from '../../core/shader/ShaderBit';\nimport type { ShaderBitTemplate } from '../../core/shader/ShaderBitTemplate';\n\n/**\n * `fxInputUv` needs each clamp rect inset half a texel, as `RenderGraph._inputClamp` writes it; `linearDepth`\n * needs depth stored as `(ndc + 1) / 2`, which the depth remap in `CameraData.ts` gives WebGPU too\n * @internal\n */\nexport const fxhBit: ShaderBit = {\n  name: 'effectFxh',\n  attributes: {\n    aPosition: 'float32x2',\n  },\n  interStage: {\n    vUv: 'vec2<f32>',\n  },\n  bindings: {\n    fxh: {\n      uFxClip: 'vec4<f32>',\n      uFxTexel: 'vec4<f32>',\n      uFxInputClamp: 'vec4<f32>',\n      uFxInput2Clamp: 'vec4<f32>',\n    },\n  },\n  gpu: {\n    header: /* wgsl */ `\nfn linearDepth(d: f32) -> f32 {\n  let n = fxh.uFxClip.x;\n  let f = fxh.uFxClip.y;\n  let z = d * 2.0 - 1.0;\n  return 2.0 * n * f / (f + n - z * (f - n));\n}\nfn texel() -> vec2<f32> {\n  return fxh.uFxTexel.xy;\n}\nfn viewTexel() -> vec2<f32> {\n  return fxh.uFxTexel.xy * fxh.uFxTexel.w;\n}\nfn fxInputUv(uv: vec2<f32>, clampRect: vec4<f32>) -> vec2<f32> {\n  return clamp(uv * (clampRect.xy + clampRect.zw), clampRect.xy, clampRect.zw);\n}\n`,\n  },\n  gl: {\n    header: /* glsl */ `\nfloat linearDepth(float d) {\n  float n = uFxClip.x;\n  float f = uFxClip.y;\n  float z = d * 2.0 - 1.0;\n  return 2.0 * n * f / (f + n - z * (f - n));\n}\nvec2 texel() {\n  return uFxTexel.xy;\n}\nvec2 viewTexel() {\n  return uFxTexel.xy * uFxTexel.w;\n}\nvec2 fxInputUv(vec2 uv, vec4 clampRect) {\n  return clamp(uv * (clampRect.xy + clampRect.zw), clampRect.xy, clampRect.zw);\n}\n`,\n  },\n};\n\n/**\n * `sampleColor` reads level 0 explicitly: `texture()` picks a level from derivatives, undefined in a divergent\n * branch. `sampleColorLod` clamps every level to level 0's rect, since a per-level inset crops coarse levels.\n * @internal\n */\nexport const colorReadBit: ShaderBit = {\n  name: 'effectColorRead',\n  bindings: {\n    fx: {\n      uTexture: 'texture_2d<f32>',\n      uTextureSampler: 'sampler',\n    },\n  },\n  gpu: {\n    header: /* wgsl */ `\nfn sampleColor(uv: vec2<f32>) -> vec4<f32> {\n  return textureSampleLevel(uTexture, uTextureSampler, fxInputUv(uv, fxh.uFxInputClamp), 0.0);\n}\nfn sampleColorLod(uv: vec2<f32>, lod: f32) -> vec4<f32> {\n  return textureSampleLevel(uTexture, uTextureSampler, fxInputUv(uv, fxh.uFxInputClamp), lod);\n}\nfn inputTexel() -> vec2<f32> {\n  return 1.0 / (vec2<f32>(textureDimensions(uTexture, 0)) * (fxh.uFxInputClamp.xy + fxh.uFxInputClamp.zw));\n}\n`,\n  },\n  gl: {\n    header: /* glsl */ `\nvec4 sampleColor(vec2 uv) {\n  return textureLod(uTexture, fxInputUv(uv, uFxInputClamp), 0.0);\n}\nvec4 sampleColorLod(vec2 uv, float lod) {\n  return textureLod(uTexture, fxInputUv(uv, uFxInputClamp), lod);\n}\nvec2 inputTexel() {\n  return 1.0 / (vec2(textureSize(uTexture, 0)) * (uFxInputClamp.xy + uFxInputClamp.zw));\n}\n`,\n  },\n};\n\n/**\n * Clamps with its own rect, since the second input can sit in a different pool bucket from the first\n * @internal\n */\nexport const color2ReadBit: ShaderBit = {\n  name: 'effectColor2Read',\n  bindings: {\n    fx: {\n      uTexture2: 'texture_2d<f32>',\n      uTexture2Sampler: 'sampler',\n    },\n  },\n  gpu: {\n    header: /* wgsl */ `\nfn sampleColor2(uv: vec2<f32>) -> vec4<f32> {\n  return textureSampleLevel(uTexture2, uTexture2Sampler, fxInputUv(uv, fxh.uFxInput2Clamp), 0.0);\n}\n`,\n  },\n  gl: {\n    header: /* glsl */ `\nvec4 sampleColor2(vec2 uv) {\n  return textureLod(uTexture2, fxInputUv(uv, uFxInput2Clamp), 0.0);\n}\n`,\n  },\n};\n\n/**\n * `DEPTH_HELPER_CALL` in `PostEffect.ts` must name each helper here but `fxDepthContent`. The helpers map\n * through the view's `uViewportUVScale`, not a clamp rect, since the scene depth is allocated at the scene's size.\n * @internal\n */\nexport const depthReadBitGpu: ShaderBit = {\n  name: 'effectDepthRead',\n  bindings: {\n    fx: {\n      uFxDepthTexture: 'texture_depth_2d',\n    },\n  },\n  gpu: {\n    header: /* wgsl */ `\nfn fxDepthContent() -> vec2<f32> {\n  return round(camera.uViewportUVScale * vec2<f32>(textureDimensions(uFxDepthTexture, 0)));\n}\nfn depthTexel() -> vec2<f32> {\n  return 1.0 / fxDepthContent();\n}\nfn sampleDepth(uv: vec2<f32>) -> f32 {\n  let content = fxDepthContent();\n  let coord = min(vec2<i32>(clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)) * content), vec2<i32>(content) - 1);\n  return textureLoad(uFxDepthTexture, coord, 0);\n}\nfn viewPos(uv: vec2<f32>) -> vec3<f32> {\n  let lz = linearDepth(sampleDepth(uv));\n  let ndc = uv * 2.0 - 1.0;\n  return vec3<f32>(ndc.x * lz / fxh.uFxClip.z, ndc.y * lz / fxh.uFxClip.w, -lz);\n}\n`,\n  },\n};\n\n/**\n * WebGL form of {@link depthReadBitGpu}\n * @internal\n */\nexport const depthReadBitGl: ShaderBit = {\n  name: 'effectDepthRead',\n  bindings: {\n    fx: {\n      uFxDepthTexture: 'texture_2d<f32>',\n    },\n  },\n  gl: {\n    header: /* glsl */ `\nvec2 fxDepthContent() {\n  return round(uViewportUVScale * vec2(textureSize(uFxDepthTexture, 0)));\n}\nvec2 depthTexel() {\n  return 1.0 / fxDepthContent();\n}\nfloat sampleDepth(vec2 uv) {\n  vec2 content = fxDepthContent();\n  ivec2 coord = min(ivec2(clamp(uv, 0.0, 1.0) * content), ivec2(content) - 1);\n  return texelFetch(uFxDepthTexture, coord, 0).r;\n}\nvec3 viewPos(vec2 uv) {\n  float lz = linearDepth(sampleDepth(uv));\n  vec2 ndc = uv * 2.0 - 1.0;\n  return vec3(ndc.x * lz / uFxClip.z, ndc.y * lz / uFxClip.w, -lz);\n}\n`,\n  },\n};\n\n/**\n * `FullscreenPass.render` sets groups by their index in `bindGroups`. `end` code sees `fxColor`, `finalColor` and,\n * in WGSL, `input`, as `toneOutputBits` needs.\n * @internal\n */\nexport const fullscreenEffectTemplate: ShaderBitTemplate = {\n  bindGroups: [{ name: 'global', ubo: true }, 'camera', 'fx', 'fxh'],\n  gpu: /* wgsl */ `\n{{header}}\n\n@vertex\nfn mainVertex(input: VertexInput) -> VertexOutput {\n  var output: VertexOutput;\n  output.position = vec4<f32>(input.aPosition, 0.0, 1.0);\n  let uv = input.aPosition * 0.5 + 0.5;\n  output.vUv = vec2<f32>(uv.x, mix(uv.y, 1.0 - uv.y, fxh.uFxTexel.z));\n  return output;\n}\n\n@fragment\nfn mainFragment(input: FragmentInput) -> @location(0) vec4<f32> {\n  let fxColor = effect(input.vUv);\n  var finalColor = fxColor.rgb;\n  {{fragmentEnd}}\n  return vec4<f32>(finalColor, fxColor.a);\n}\n`,\n  gl: {\n    vertex: /* glsl */ `#version 300 es\n\n{{header}}\n\nvoid main() {\n  vec2 uv = aPosition * 0.5 + 0.5;\n  vUv = vec2(uv.x, mix(uv.y, 1.0 - uv.y, uFxTexel.z));\n  gl_Position = vec4(aPosition, 0.0, 1.0);\n}\n`,\n    fragment: /* glsl */ `#version 300 es\n\n{{header}}\n\nout vec4 fragColor;\n\nvoid main() {\n  vec4 fxColor = effect(vUv);\n  vec3 finalColor = fxColor.rgb;\n  {{end}}\n  fragColor = vec4(finalColor, fxColor.a);\n}\n`,\n  },\n};\n","import { BindGroup, State, Texture, TextureStyle, UniformGroup } from 'pixi.js';\nimport type { BLEND_MODES, Shader, WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport { getCameraData } from '../../core/CameraData';\nimport { fullscreenTriangleGeometry } from '../../core/fullscreenTriangleGeometry';\nimport type { PassBuilder } from '../../core/render-graph/PassBuilder';\nimport type { ColorHandle, DepthHandle } from '../../core/render-graph/ResourceHandle';\nimport type { TextureBinding } from '../../core/render-graph/TextureBinding';\nimport { RenderPass, RenderPassBit } from '../../core/render-passes/RenderPass';\nimport type { RenderSession } from '../../core/render-passes/RenderSession';\nimport type { BindingGroup, ShaderBit } from '../../core/shader/ShaderBit';\nimport { DEPTH_VIEW_PLACEHOLDER } from '../../core/textures/DefaultTextures';\nimport {\n  color2ReadBit,\n  colorReadBit,\n  depthReadBitGl,\n  depthReadBitGpu,\n  fullscreenEffectTemplate,\n  fxhBit,\n} from './fullscreenEffectShader';\nimport type { EffectFragment } from './PostEffect';\n\n/**\n * Constructor options for {@link FullscreenPass}\n * @category rendering\n * @advanced\n */\nexport interface FullscreenPassOptions {\n  /** Renderer to build for; inside a `build`, the `renderer` on its context */\n  renderer: WebGLRenderer | WebGPURenderer;\n  /**\n   * Debug name for the pass; other fullscreen passes can share it\n   * @default 'fullscreen'\n   */\n  label?: string;\n  /**\n   * Shader body defining `effect(uv)`; {@link EffectFragment} lists what it can call\n   *\n   * {@link passthroughFragment} copies the colour input unchanged.\n   */\n  fragment: EffectFragment;\n  /**\n   * Uniforms the fragment declares; {@link EffectFragment} gives their names in the shader\n   *\n   * Passes that share one fragment object must declare the same uniform names and types, though\n   * their values can differ.\n   */\n  uniforms?: UniformGroup | null;\n  /**\n   * Graph resources the fragment samples\n   *\n   * Each read given adds its helpers to the shader, so a fragment that calls a helper without\n   * its read fails to compile.\n   */\n  reads?: {\n    /** Colour input, read with `sampleColor`, `sampleColorLod` and `inputTexel` */\n    color?: ColorHandle;\n    /** Second colour input, read with `sampleColor2` */\n    color2?: ColorHandle;\n    /** Scene depth, read with `sampleDepth`, `viewPos` and `depthTexel` */\n    depth?: DepthHandle;\n  };\n  /**\n   * Where the pass draws: a graph handle, or `null` for the view's rect on screen, blended\n   * premultiplied over the 2D content beneath\n   *\n   * A handle to an imported `RenderTexture` works too, and the image lands upright in it on both\n   * backends.\n   */\n  writes: ColorHandle | null;\n  /**\n   * Blend mode for drawing over what the target already holds, such as adding a bloom level onto\n   * the one below it\n   *\n   * Left out, the pass overwrites the target. Ignored when `writes` is `null`.\n   */\n  blendMode?: Exclude<BLEND_MODES, 'inherit'>;\n  /**\n   * Shader bits whose fragment `end` code runs after `effect(uv)`, in order\n   *\n   * They read the result as `fxColor` and change its RGB in `finalColor`; the pass keeps\n   * `fxColor`'s alpha.\n   */\n  extraBits?: readonly ShaderBit[];\n}\n\n/**\n * A fragment that copies its colour input unchanged, for a {@link FullscreenPass} with a `reads.color`\n *\n * The input is stretched over the whole target, whatever their sizes.\n * @example\n * ```ts\n * graph.addPass(\n *   new FullscreenPass({ renderer, fragment: passthroughFragment, reads: { color: normals }, writes: copy }),\n * );\n * ```\n * @category rendering\n * @advanced\n */\nexport const passthroughFragment: EffectFragment = {\n  gpu: 'fn effect(uv: vec2<f32>) -> vec4<f32> { return sampleColor(uv); }',\n  gl: 'vec4 effect(vec2 uv) { return sampleColor(uv); }',\n};\n\nconst fragmentBitCache = new WeakMap<EffectFragment, ShaderBit>();\nlet fragmentBitCount = 0;\n\n/** Cached per fragment object with the first caller's uniform types, as `FullscreenPassOptions.uniforms` warns */\nfunction getFragmentBit(fragment: EffectFragment, uniforms: UniformGroup | null): ShaderBit {\n  let bit = fragmentBitCache.get(fragment);\n  if (bit) return bit;\n\n  const fx: BindingGroup = Object.create(null);\n  if (uniforms) {\n    for (const name in uniforms.uniformStructures) {\n      fx[name] = uniforms.uniformStructures[name].type as BindingGroup[string];\n    }\n  }\n\n  bit = {\n    name: `effectFragment:${fragmentBitCount++}`,\n    bindings: { fx },\n    gpu: { header: fragment.gpu },\n    gl: { header: fragment.gl },\n  };\n\n  fragmentBitCache.set(fragment, bit);\n  return bit;\n}\n\n/** A binding is `null` when the pass has no such read */\ninterface FxBindings {\n  group: BindGroup;\n  color: TextureBinding | null;\n  color2: TextureBinding | null;\n  depth: TextureBinding | null;\n}\n\n/**\n * Names each resource as the read bits in `fullscreenEffectShader.ts` declare it; depth binds here, not in the\n * view's global group, which would keep it bound while the next frame's scene draws into it\n */\nfunction createFxBindings(\n  uniforms: UniformGroup | null,\n  reads: NonNullable<FullscreenPassOptions['reads']>,\n): FxBindings {\n  const entries: NonNullable<ConstructorParameters<typeof BindGroup>[0]> = {};\n\n  if (uniforms !== null && Object.keys(uniforms.uniformStructures).length > 0) entries.fx = uniforms;\n  if (reads.color) {\n    entries.uTexture = Texture.WHITE.source;\n    entries.uTextureSampler = new TextureStyle({ scaleMode: 'linear', addressMode: 'clamp-to-edge' });\n  }\n  if (reads.color2) {\n    entries.uTexture2 = Texture.WHITE.source;\n    entries.uTexture2Sampler = new TextureStyle({ scaleMode: 'linear', addressMode: 'clamp-to-edge' });\n  }\n  if (reads.depth) entries.uFxDepthTexture = DEPTH_VIEW_PLACEHOLDER;\n\n  const group = new BindGroup(entries);\n  return {\n    group,\n    color: reads.color ? { group, slot: 'uTexture' } : null,\n    color2: reads.color2 ? { group, slot: 'uTexture2' } : null,\n    depth: reads.depth ? { group, slot: 'uFxDepthTexture' } : null,\n  };\n}\n\nconst WHOLE_TEXTURE_CLAMP: readonly number[] = [0, 0, 1, 1];\n\n/**\n * One fullscreen draw of an `effect(uv)` fragment, reading graph handles and writing one\n *\n * The building block of every post effect. A single-shader {@link PostEffect} adds one for you;\n * a multi-pass effect adds several from its `build`, and a custom graph can add them directly.\n * The graph binds its inputs each frame and the pass supplies the helpers {@link EffectFragment}\n * lists, so the fragment only has to define `effect(uv)`.\n * @example\n * ```ts\n * graph.addPass(new FullscreenPass({ renderer, reads: { depth }, writes: ao, fragment: AO_FRAGMENT }));\n * ```\n * @category rendering\n * @advanced\n */\nexport class FullscreenPass extends RenderPass {\n  private readonly _fragment: EffectFragment;\n  private readonly _uniforms: UniformGroup | null;\n  private readonly _reads: NonNullable<FullscreenPassOptions['reads']>;\n  private readonly _writes: ColorHandle | null;\n  private readonly _extraBits: readonly ShaderBit[];\n  private readonly _isWebGL: boolean;\n\n  private readonly _state: State;\n  private readonly _fxBindGroup: BindGroup;\n  private readonly _fxhBindGroup: BindGroup;\n  private readonly _fxhUniforms: UniformGroup;\n  private readonly _colorBinding: TextureBinding | null;\n  private readonly _color2Binding: TextureBinding | null;\n  private readonly _depthBinding: TextureBinding | null;\n\n  private _shader: Shader | null = null;\n  private _destroyed = false;\n\n  constructor(options: FullscreenPassOptions) {\n    super({ renderer: options.renderer, name: options.label ?? 'fullscreen', bit: RenderPassBit.NONE });\n\n    this._fragment = options.fragment;\n    this._uniforms = options.uniforms ?? null;\n    this._reads = options.reads ?? {};\n    this._writes = options.writes;\n    this._extraBits = options.extraBits ?? [];\n    this._isWebGL = 'gl' in options.renderer;\n\n    const state = new State();\n    state.depthTest = false;\n    state.depthMask = false;\n    state.culling = false;\n    state.blend = this._writes === null || options.blendMode !== undefined;\n    if (this._writes !== null && options.blendMode) state.blendMode = options.blendMode;\n    this._state = state;\n\n    const fx = createFxBindings(this._uniforms, this._reads);\n    this._fxBindGroup = fx.group;\n    this._colorBinding = fx.color;\n    this._color2Binding = fx.color2;\n    this._depthBinding = fx.depth;\n\n    this._fxhUniforms = new UniformGroup({\n      uFxClip: { value: new Float32Array(4), type: 'vec4<f32>' },\n      uFxTexel: { value: new Float32Array(4), type: 'vec4<f32>' },\n      uFxInputClamp: { value: new Float32Array(WHOLE_TEXTURE_CLAMP), type: 'vec4<f32>' },\n      uFxInput2Clamp: { value: new Float32Array(WHOLE_TEXTURE_CLAMP), type: 'vec4<f32>' },\n    });\n    this._fxhBindGroup = new BindGroup({ fxh: this._fxhUniforms });\n  }\n\n  /**\n   * Declares the pass's reads and its write\n   *\n   * When it draws to the view's target, it declares that target's depth too, as\n   * {@link PassBuilder#writeColor} requires.\n   * @param b - Builder collecting the pass's resource dependencies.\n   */\n  public override setup(b: PassBuilder): void {\n    if (this._reads.color) b.sample(this._reads.color, this._colorBinding!);\n    if (this._reads.color2) b.sample(this._reads.color2, this._color2Binding!);\n    if (this._reads.depth) b.sample(this._reads.depth, this._depthBinding!);\n\n    if (this._writes) {\n      b.writeColor(this._writes);\n    } else {\n      b.writeColor(b.defaultColor);\n      b.writeDepth(b.defaultDepth);\n    }\n  }\n\n  /**\n   * Draws the effect for this frame, binding its groups in the order the effect template declares\n   * @param session - Per-frame render session supplying the resolved textures.\n   */\n  public override render(session: RenderSession): void {\n    if (!this._shader) this._compile();\n\n    this._updateHeaderUniforms(session);\n\n    this._shader!.groups[0] = session.globalBindGroup;\n    this._shader!.groups[1] = getCameraData(session.view3d.camera).bindGroup;\n    this._shader!.groups[2] = this._fxBindGroup;\n    this._shader!.groups[3] = this._fxhBindGroup;\n\n    this.pipe.renderGeometry(fullscreenTriangleGeometry(), this._shader!, this._state);\n  }\n\n  /**\n   * V flips on WebGPU, and again when the bound target's front-face inversion differs from the default target's;\n   * the Y scale comes from the camera's GPU projection, negated on WebGPU, so `viewPos` is Y up on both backends\n   */\n  private _updateHeaderUniforms(session: RenderSession): void {\n    const camera = session.view3d.camera;\n    const gpu = getCameraData(camera).projection.elements;\n    const clip = this._fxhUniforms.uniforms.uFxClip as Float32Array;\n    clip[0] = camera.near;\n    clip[1] = camera.far;\n    clip[2] = gpu[0];\n    clip[3] = this._isWebGL ? gpu[5] : -gpu[5];\n    const texelLanes = this._fxhUniforms.uniforms.uFxTexel as Float32Array;\n    texelLanes[0] = 1 / session.activeViewport.width;\n    texelLanes[1] = 1 / session.activeViewport.height;\n    const frontFaceInverted = (session.renderer as WebGLRenderer | WebGPURenderer).renderTarget.isFrontFaceInverted();\n    texelLanes[2] = (this._isWebGL ? 0 : 1) ^ (frontFaceInverted !== session.defaultFrontFaceInverted ? 1 : 0);\n    texelLanes[3] = session.activeViewport.width / session.viewport.width;\n\n    const graph = session.view3d._graph;\n    if (this._reads.color) {\n      graph._inputClamp(this._reads.color, session, this._fxhUniforms.uniforms.uFxInputClamp as Float32Array);\n    }\n    if (this._reads.color2) {\n      graph._inputClamp(this._reads.color2, session, this._fxhUniforms.uniforms.uFxInput2Clamp as Float32Array);\n    }\n    this._fxhUniforms.update();\n  }\n\n  private _compile(): void {\n    const bits: ShaderBit[] = [fxhBit];\n    if (this._reads.color) bits.push(colorReadBit);\n    if (this._reads.color2) bits.push(color2ReadBit);\n    if (this._reads.depth) bits.push(this._isWebGL ? depthReadBitGl : depthReadBitGpu);\n    bits.push(getFragmentBit(this._fragment, this._uniforms), ...this._extraBits);\n\n    this._shader = this.pipe.renderer.material3d.compilePassShader(bits, fullscreenEffectTemplate);\n  }\n\n  /** Releases the pass's shader and bind groups, leaving the `uniforms` it was given to their owner */\n  public override destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n\n    this._shader?.destroy();\n    this._shader = null;\n    this._fxBindGroup.destroy();\n    this._fxhBindGroup.destroy();\n  }\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { ColorHandle } from '../../core/render-graph/ResourceHandle';\nimport { toneOutputBits } from '../../core/shader/bits/tonemapping/toneMappingBits';\nimport type { ToneMapping } from '../../scene/View3D';\nimport { FullscreenPass, passthroughFragment } from './FullscreenPass';\n\n/**\n * Options for an {@link OutputPass}\n * @category rendering\n * @advanced\n */\nexport interface OutputPassOptions {\n  /** The renderer the pass draws with */\n  renderer: WebGLRenderer | WebGPURenderer;\n  /** The image to show: the scene colour, or the last post effect's result */\n  source: ColorHandle;\n  /**\n   * The tone curve and display encode to apply to the image, for a scene that holds linear light\n   *\n   * Left out, or `'custom'`, the pass copies the image unchanged.\n   */\n  toneMapping?: ToneMapping;\n  /**\n   * Where the image lands; {@link FullscreenPassOptions#writes} has the choices\n   * @default null\n   */\n  writes?: ColorHandle | null;\n}\n\n/**\n * Finishes a view's image: applies the tone curve and display encode to a scene that holds linear\n * light, or copies the image unchanged (see {@link View3D#toneMapping})\n *\n * A see-through background keeps its edges over the 2D content beneath. Unless it copies, the pass\n * also dithers so smooth gradients don't band in an 8-bit target. A custom graph whose scene is linear\n * ({@link RenderGraph#sceneIsLinear}) needs one to finish the image. Inside a\n * {@link View3DOptions#graph | graph} builder, pass the builder's `options.toneMapping`, so a\n * change to {@link View3D#toneMapping} reaches the pass when the graph rebuilds.\n * @example\n * ```ts\n * graph.addPass(new OutputPass({ renderer, source: graph.sceneColor, toneMapping: options.toneMapping }));\n * ```\n * @category rendering\n * @advanced\n */\nexport class OutputPass extends FullscreenPass {\n  constructor(options: OutputPassOptions) {\n    super({\n      renderer: options.renderer,\n      label: 'output',\n      fragment: passthroughFragment,\n      reads: { color: options.source },\n      writes: options.writes ?? null,\n      extraBits: toneOutputBits(options.toneMapping),\n    });\n  }\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { RenderGraph } from '../core/render-graph/RenderGraph';\nimport type { ColorHandle, DepthHandle } from '../core/render-graph/ResourceHandle';\nimport type { SceneOutput } from '../core/render-graph/SceneOutput';\n\n/**\n * The stages where a pass draws meshes into the scene; see {@link PassStage}\n * @example\n * ```ts\n * new MeshPass({ name: 'gizmo', stage: 'afterTransparent' });\n * ```\n * @category rendering\n * @standard\n */\nexport type SceneStage = 'beforeOpaque' | 'afterOpaque' | 'afterTransparent';\n\n/**\n * The stages of the post chain, before and after the view's tone curve, reserved for\n * {@link PostEffect}; see {@link PassStage}\n * @example\n * ```ts\n * view.passes = [new BloomEffect(), new TintEffect({ stage: 'beforeToneMapping' })];\n * ```\n * @category rendering\n * @standard\n */\nexport type EffectStage = 'beforeToneMapping' | 'afterToneMapping';\n\n/**\n * Where in the default graph a {@link Pass3D} contributes its passes\n *\n * The first three are scene stages ({@link SceneStage}), where a pass usually draws meshes into the\n * scene's colour and depth. The last two are the post chain ({@link EffectStage}), where\n * full-screen effects each read the image the one before wrote.\n *\n * - `'beforeOpaque'`: before the view clears its depth and draws the scene, so a pass here can fill\n *   a texture the scene then samples: a security-camera feed, a mirror, a portal.\n * - `'afterOpaque'`: straight after the opaque draw, so glass refracts what the pass draws and\n *   transparent surfaces draw over it. Suits outlines and decals. A pass whose camera has a render\n *   texture draws into that texture instead, so glass doesn't refract it.\n * - `'afterTransparent'`: after every scene draw, before the post chain. Overlays, gizmos,\n *   debug wireframes.\n * - `'beforeToneMapping'`: post effects that read the scene as light, in a float texture, before\n *   the view's tone curve, so brightness above 1 is still there: bloom, depth of field, motion\n *   blur, ambient occlusion. A {@link PostEffect} runs here unless it says otherwise.\n * - `'afterToneMapping'`: post effects that read the picture as it will show, after the curve,\n *   such as antialiasing that finds edges by their brightness on screen, a tint, or a viewer that\n *   shows data as colours.\n * @example\n * ```ts\n * view.passes = [new MeshPass({ name: 'gizmo', stage: 'afterTransparent' })];\n * ```\n * @category rendering\n * @standard\n */\nexport type PassStage = SceneStage | EffectStage;\n\n/**\n * What a {@link Pass3D} receives at build time\n *\n * Scene-stage passes draw into `graph.sceneColor` and `graph.sceneDepth`. Post effects receive\n * {@link EffectIO}, which adds their input and output.\n * @category rendering\n * @advanced\n */\nexport interface PassContext {\n  /** Renderer the graph is being built for */\n  readonly renderer: WebGLRenderer | WebGPURenderer;\n  /** Copy of the scene's colour after the opaque draw, with mips; the image glass refracts */\n  readonly opaqueColor: ColorHandle;\n  /** Copy of the scene's depth after the opaque draw */\n  readonly opaqueDepth: DepthHandle;\n}\n\n/**\n * Constructor options shared by every {@link Pass3D}\n * @example\n * ```ts\n * interface MyGridPassOptions extends Pass3DOptions {\n *   spacing?: number;\n * }\n * ```\n * @category rendering\n * @standard\n */\nexport interface Pass3DOptions {\n  /**\n   * Whether the pass starts enabled; see {@link Pass3D#enabled}\n   * @default true\n   * @example\n   * ```ts\n   * view.passes = [new MeshPass({ name: 'wireframe', enabled: false })];\n   * ```\n   */\n  enabled?: boolean;\n}\n\n/**\n * Base class for everything added to {@link View3D#passes}\n *\n * A pass needs no renderer to construct, can be shared across views, and holds the properties you\n * tune. When a view builds its render graph, it calls {@link Pass3D#build} at the pass's\n * {@link PassStage}, and the pass adds its render passes there. Array order only matters between\n * passes at the same stage.\n *\n * {@link MeshPass} redraws opted-in meshes with an override shader, and {@link PostEffect} runs a\n * fullscreen fragment over the frame. Subclass this directly for anything else.\n * @example\n * ```ts\n * class MyRearViewPass extends Pass3D {\n *   public readonly stage = 'afterTransparent';\n *\n *   public build(graph: RenderGraph, ctx: PassContext): void {\n *     graph.addPass(\n *       new ForwardRenderPass({ renderer: ctx.renderer, name: 'opaque', sort: 'key', camera: rearCamera }),\n *     );\n *   }\n * }\n *\n * view.passes = [new MyRearViewPass()];\n * ```\n * @category rendering\n * @standard\n */\nexport abstract class Pass3D {\n  /**\n   * Whether this pass runs\n   *\n   * Flipping it rebuilds the view's render graph on the next render, which suits a settings toggle\n   * but not a change every frame; animate an effect's own properties instead. It can also\n   * recompile the view's materials; {@link View3D#passes} says when.\n   * @example\n   * ```ts\n   * const wireframe = new MeshPass({ name: 'wireframe' });\n   * view.passes = [wireframe];\n   * wireframe.enabled = false;\n   * ```\n   */\n  public enabled: boolean;\n\n  /** The {@link PassStage} at which the view calls {@link Pass3D#build} */\n  public abstract readonly stage: PassStage;\n\n  /**\n   * Extra outputs the view's scene draw writes beside its colour while this pass is enabled\n   *\n   * Each costs the scene draw a texture and the shader work to fill it, and any output makes the\n   * view draw its scene into a texture first, as a post effect does. Reach an output's texture with\n   * {@link RenderGraph#getSceneOutput}, to read it or draw into it.\n   * @example\n   * ```ts\n   * const objectIdOutput: SceneOutput = { name: 'objectId', format: 'r32uint' };\n   *\n   * class MyPickingPass extends Pass3D {\n   *   public readonly stage = 'afterTransparent';\n   *   public readonly requiredOutputs = [objectIdOutput];\n   *   public build(): void {}\n   * }\n   * ```\n   */\n  public readonly requiredOutputs?: readonly SceneOutput[];\n\n  constructor(options: Pass3DOptions = {}) {\n    this.enabled = options.enabled ?? true;\n  }\n\n  /**\n   * Adds this pass's render passes and textures to the graph\n   *\n   * Called once per graph build at this pass's stage. Handles become textures only inside a render\n   * pass's `render(session)`, through {@link RenderGraph#getTexture}, never here.\n   * @param graph - Render graph being built; add passes and transients to it.\n   * @param ctx - Renderer and shared handles for this build.\n   * @advanced\n   */\n  public abstract build(graph: RenderGraph, ctx: PassContext): void;\n\n  /**\n   * Releases GPU resources the pass made outside the graph; the base class has none\n   *\n   * The view never calls it, not on replacing `view.passes` nor on its own destroy, since a pass\n   * can be shared. Call it yourself once the pass is retired. Override it only for resources of your\n   * own: the render passes added in `build` go with the view's graph, and a plain `UniformGroup`\n   * needs no release.\n   * @example\n   * ```ts\n   * view.passes = [];\n   * wireframe.destroy();\n   * ```\n   */\n  public destroy(): void {}\n}\n","import type { UniformGroup } from 'pixi.js';\n\nimport type { RenderGraph } from '../../core/render-graph/RenderGraph';\nimport type { ColorHandle } from '../../core/render-graph/ResourceHandle';\nimport { Pass3D } from '../Pass3D';\nimport type { EffectStage, Pass3DOptions, PassContext } from '../Pass3D';\nimport { FullscreenPass } from './FullscreenPass';\n\n/** Must name each helper `depthReadBitGpu` in `fullscreenEffectShader.ts` defines, except `fxDepthContent` */\nconst DEPTH_HELPER_CALL = /\\b(?:sampleDepth|viewPos|depthTexel)\\s*\\(/;\n\n/**\n * Shader bodies for a post effect, one per backend, each defining the function run for every pixel\n *\n *  - WGSL: `fn effect(uv: vec2<f32>) -> vec4<f32>`\n *  - GLSL: `vec4 effect(vec2 uv)`\n *\n * `uv` runs from 0 to 1 across the view's viewport, the right way up for the pass's target. The\n * fragment can call these helpers, the first three only when the pass has the matching read\n * ({@link FullscreenPassOptions#reads}):\n *\n *  - `sampleColor(uv)` and `sampleColorLod(uv, lod)`: the colour input, the LOD form reading mips\n *    when the input has them ({@link PostEffect#inputMips}); `inputTexel()`: one texel of that\n *    input as a UV step\n *  - `sampleColor2(uv)`: the second colour input, such as a scene output\n *  - `sampleDepth(uv)`: raw scene depth; `viewPos(uv)`: the view-space position there;\n *    `depthTexel()`: one depth texel as a UV step, coarser than `texel()` when the effect runs at a\n *    finer resolution than the scene\n *  - `linearDepth(d)`: linear depth from a raw depth value. It and `viewPos` assume a perspective\n *    camera, and give wrong values under an orthographic one.\n *  - `texel()`: one pixel of the pass's target as a UV step\n *  - `viewTexel()`: one physical pixel of the view on screen as a UV step, for a size that has to\n *    look the same at any `View3D.resolution` and in any pass of the effect\n *\n * Declared uniforms are `fx.<name>` in WGSL and plain `<name>` in GLSL. To project samples of your\n * own, `fxh.uFxClip` in WGSL and `uFxClip` in GLSL hold (near, far, projection[0], projection[5]),\n * set so that `viewPos` and points projected with them are in view space, Y up, on both backends.\n * @category filters\n * @advanced\n */\nexport interface EffectFragment {\n  /** WGSL body compiled for the WebGPU backend */\n  gpu: string;\n  /** GLSL body compiled for the WebGL backend */\n  gl: string;\n}\n\n/**\n * What {@link PostEffect#build} receives: the {@link PassContext} plus this effect's input and output\n *\n * Anything else, such as the scene depth, comes from the graph.\n * @category filters\n * @advanced\n */\nexport interface EffectIO extends PassContext {\n  /** The image this effect reads: the scene, or the result of the step before it */\n  readonly input: ColorHandle;\n  /**\n   * Where this effect's final image must go; pass it as a {@link FullscreenPass}'s `writes`\n   *\n   * `null` when the effect is the last step and draws straight to the view's target.\n   */\n  readonly output: ColorHandle | null;\n}\n\n/**\n * Constructor options shared by every {@link PostEffect}\n * @example\n * ```ts\n * interface MyVignetteEffectOptions extends PostEffectOptions {\n *   strength?: number;\n * }\n * ```\n * @category filters\n * @standard\n */\nexport interface PostEffectOptions extends Pass3DOptions {\n  /**\n   * Whether the effect reads the scene as light, before the tone curve, or the picture as it will\n   * show, after it\n   *\n   * Each effect class picks the right one by default, so set it only to move one instance, such as\n   * a tint meant for the light rather than the picture. See {@link PostEffect#stage}.\n   * @default 'beforeToneMapping', unless the effect's class says otherwise\n   * @example\n   * ```ts\n   * new TintEffect({ tint: 0xffaa66, stage: 'beforeToneMapping' });\n   * ```\n   */\n  stage?: EffectStage;\n}\n\n/**\n * Base class for fullscreen post effects, added to a view through {@link View3D#passes}\n *\n * After the scene draws, the view runs its `'beforeToneMapping'` effects in array order, then the\n * tone curve, then its `'afterToneMapping'` effects, each reading the image the step before drew.\n * Any enabled post effect makes the view draw its scene into a texture first, and a\n * `'beforeToneMapping'` one also makes that texture float, holding linear light; see\n * {@link View3D#toneMapping}.\n *\n * ## Authoring\n *\n * A single-shader effect sets `fragment`, and `uniforms` if it has any, and exposes properties that\n * write into those uniforms. A property write shows on the next frame.\n *\n * An effect runs at `'beforeToneMapping'` unless it passes another stage to `super`. There it\n * reads linear light, brightness above 1 included, which suits blur, glow, depth of field and\n * occlusion. Pass `'afterToneMapping'` for an effect that judges the picture as it shows, such as\n * edge detection or a final colour grade, or one that shows data rather than light, such as depth\n * or normals, so the tone curve leaves its colours alone. Spread the caller's options after the\n * stage, so one instance can still pick its own:\n *\n * ```ts\n * class MyOutlineEffect extends PostEffect {\n *   constructor(options: PostEffectOptions = {}) {\n *     super({ stage: 'afterToneMapping', ...options });\n *   }\n * }\n * ```\n *\n * A multi-pass effect overrides {@link PostEffect#build} and adds its own passes to the render\n * graph. Its final image must go to `io.output`:\n *\n * ```ts\n * public override build(graph: RenderGraph, io: EffectIO): void {\n *   const ao = graph.createColor({ resolution: 1, format: 'rgba8unorm' });\n *   graph.addPass(new FullscreenPass({\n *     renderer: io.renderer,\n *     reads: { depth: graph.sceneDepth },\n *     writes: ao,\n *     fragment: AO_FRAGMENT,\n *   }));\n *   graph.addPass(new FullscreenPass({\n *     renderer: io.renderer,\n *     reads: { color: io.input, color2: ao },\n *     writes: io.output,\n *     fragment: MERGE_FRAGMENT,\n *   }));\n * }\n * ```\n *\n * Toggling, reordering and retiring an effect work as for any pass; {@link View3D#passes} has\n * the rules.\n * @example\n * ```ts\n * class MyGreyscaleEffect extends PostEffect {\n *   protected readonly fragment: EffectFragment = {\n *     gpu: `\n * fn effect(uv: vec2<f32>) -> vec4<f32> {\n *   let color = sampleColor(uv);\n *   let luma = dot(color.rgb, vec3<f32>(0.2126, 0.7152, 0.0722));\n *   return vec4<f32>(vec3<f32>(luma), color.a);\n * }\n * `,\n *     gl: `\n * vec4 effect(vec2 uv) {\n *   vec4 color = sampleColor(uv);\n *   float luma = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n *   return vec4(vec3(luma), color.a);\n * }\n * `,\n *   };\n * }\n *\n * view.passes = [new MyGreyscaleEffect()];\n * ```\n * @category filters\n * @standard\n */\nexport abstract class PostEffect extends Pass3D {\n  /**\n   * The stage the effect runs at, set by the {@link PostEffectOptions.stage | stage} option\n   * @advanced\n   */\n  public readonly stage: EffectStage;\n\n  /**\n   * Whether the effect's input has mips, for an effect that reads coarse levels with\n   * `sampleColorLod`, such as a blur\n   *\n   * Costs a mip generation every frame and about a third more memory for the input, so leave it\n   * `false` unless the effect samples levels above 0.\n   * @advanced\n   */\n  public readonly inputMips: boolean = false;\n\n  /** The shader the default {@link PostEffect#build} draws; see {@link EffectFragment} */\n  protected readonly fragment?: EffectFragment;\n\n  /**\n   * Uniforms the {@link PostEffect#fragment} declares, or `null` for none\n   *\n   * They outlive graph rebuilds, so values set on them stay.\n   */\n  protected readonly uniforms: UniformGroup | null = null;\n\n  constructor(options: PostEffectOptions = {}) {\n    super(options);\n    this.stage = options.stage ?? 'beforeToneMapping';\n  }\n\n  /**\n   * Writes one component of a vector uniform from a property setter, and marks the group changed\n   * so the GPU copy updates\n   * @param group - Uniform group the lane belongs to.\n   * @param name - Uniform name inside the group; its value must be a `Float32Array`.\n   * @param lane - Component index within the uniform.\n   * @param value - New value for that lane.\n   */\n  protected writeLane(group: UniformGroup, name: string, lane: number, value: number): void {\n    (group.uniforms[name] as Float32Array)[lane] = value;\n    group.update();\n  }\n\n  /**\n   * Adds this effect's passes to the graph\n   *\n   * The default adds one {@link FullscreenPass} that draws `fragment`, binding the\n   * scene depth only when the fragment calls `sampleDepth`, `viewPos` or `depthTexel` by name. On an\n   * antialiased canvas, reading the depth costs a copy of it each frame, shared by every effect that\n   * reads it. Override it for a multi-pass effect, as the class docs show; {@link Pass3D#build} says\n   * when handles become textures.\n   * @param graph - Render graph being built; add passes and transients to it.\n   * @param io - This effect's input and output, plus the renderer and opaque copies\n   * @advanced\n   */\n  public override build(graph: RenderGraph, io: EffectIO): void {\n    const fragment = this.fragment;\n    if (!fragment) {\n      throw new Error(`${this.constructor.name}: provide a \\`fragment\\` or override \\`build()\\`.`);\n    }\n\n    const readsDepth = DEPTH_HELPER_CALL.test(fragment.gpu) || DEPTH_HELPER_CALL.test(fragment.gl);\n    graph.addPass(\n      new FullscreenPass({\n        renderer: io.renderer,\n        label: this.constructor.name,\n        fragment,\n        uniforms: this.uniforms,\n        reads: { color: io.input, depth: readsDepth ? graph.sceneDepth : undefined },\n        writes: io.output,\n      }),\n    );\n  }\n}\n","import type { RenderGraph } from '../../core/render-graph/RenderGraph';\nimport { ForwardRenderPass } from '../../core/render-passes/ForwardRenderPass';\nimport type { PassDescriptorOptions } from '../../materials/PassDescriptor';\nimport type { Camera3D } from '../../scene/cameras/Camera3D';\nimport { Pass3D } from '../Pass3D';\nimport type { Pass3DOptions, PassContext, SceneStage } from '../Pass3D';\n\n/**\n * Constructor options for {@link MeshPass}\n * @category rendering\n * @advanced\n */\nexport interface MeshPassOptions extends Pass3DOptions {\n  /**\n   * The name materials opt in with, through their `passes` option; {@link RenderPassOptions#name}\n   * says when two passes can share one\n   */\n  name: string;\n  /**\n   * Where in the default graph the pass draws\n   *\n   * Left out, a pass whose camera has a render texture draws at `'beforeOpaque'`, so the texture\n   * is complete before any material samples it; any other pass draws at `'afterOpaque'`.\n   */\n  stage?: SceneStage;\n  /** Human-readable explanation shown by graph tooling */\n  description?: string;\n  /**\n   * Shader, state and topology for meshes whose material doesn't override them for this pass\n   *\n   * A material's own `passes[name]` entry wins field by field; anything it leaves out falls\n   * back to this, then to the material's own state and topology.\n   */\n  descriptor?: PassDescriptorOptions;\n  /**\n   * Draw order; {@link ForwardRenderPassOptions#sort} has the choices\n   * @default 'key'\n   */\n  sort?: 'key' | 'distance';\n  /**\n   * Camera to draw from, instead of the view's own\n   *\n   * Add it to the view's scene (`view.root.addChild(camera)`) so its transform stays current. Its\n   * `viewport` places the image. Give it a `renderTexture` to draw into that texture instead, for a\n   * material to show; a mesh that samples the texture while this camera draws it sees last frame's\n   * picture. The pass draws only the meshes opted in by name, so glass seen from this camera needs\n   * passes of its own, added from the `build` of a {@link Pass3D} listed after this one at the same\n   * stage; {@link RenderPassOptions#camera} lists them.\n   */\n  camera?: Camera3D;\n}\n\n/**\n * Redraws every mesh that opts in by name, with an override shader and state\n *\n * A material joins by naming the pass in its `passes` option, as in `passes: { outline: true }`,\n * and a single mesh with {@link Mesh3D#enablePass}. This pass draws them again: for outlines,\n * wireframes, selection masks or decals. Batching, skinning and morph targets work as in the main\n * draw.\n * @example\n * ```ts\n * new View3D({ passes: [new MeshPass({ name: 'wireframe', descriptor: wireframeDescriptor })] });\n * new Material3D({ passes: { wireframe: true } });\n * ```\n * @category rendering\n * @advanced\n */\nexport class MeshPass extends Pass3D {\n  /** Pass name materials opt in with */\n  public readonly name: string;\n\n  private readonly _options: MeshPassOptions;\n\n  constructor(options: MeshPassOptions) {\n    super(options);\n    this.name = options.name;\n    this._options = options;\n  }\n\n  /** The stage the pass draws at; {@link MeshPassOptions#stage} says how it's picked when left out */\n  public get stage(): SceneStage {\n    return this._options.stage ?? (this._options.camera?.renderTexture ? 'beforeOpaque' : 'afterOpaque');\n  }\n\n  /**\n   * Adds the draw of this pass's meshes\n   * @param graph - Render graph being built.\n   * @param ctx - Renderer and shared handles for this build.\n   */\n  public build(graph: RenderGraph, ctx: PassContext): void {\n    const options = this._options;\n    graph.addPass(\n      new ForwardRenderPass({\n        renderer: ctx.renderer,\n        name: options.name,\n        description: options.description,\n        descriptor: options.descriptor,\n        sort: options.sort ?? 'key',\n        camera: options.camera,\n      }),\n    );\n  }\n}\n","import { definedProps } from 'pixi.js';\n\nimport type { BatchInstanceData } from '../core/batcher/BatchInstanceData';\nimport type { BatchMatrices } from '../core/batcher/BatchMatrices';\nimport type { InstanceDataOptions } from '../core/batcher/instanceDataLayout';\nimport { Mesh3DBatch } from '../core/batcher/Mesh3DBatch';\nimport type { Geometry3D } from '../geometry/Geometry3D';\nimport type { BaseMaterial3D } from '../materials/BaseMaterial3D';\nimport type { Matrix4 } from '../math/matrix/Matrix4';\nimport type { Destroy3DOptions } from '../utils/Destroy3DOptions';\nimport { resolveDestroy3DFlag } from '../utils/Destroy3DOptions';\nimport { Container3D } from './Container3D';\nimport type { Container3DOptions } from './Container3D';\nimport type { BillboardMode } from './Mesh3D';\nimport type { CullMode } from './View3D';\n\n/**\n * Constructor options for {@link BatchedMesh3D}\n *\n * The {@link Container3DOptions} apply too, except `width`, `height` and `depth`: the slots aren't\n * children, so the node has no bounds to size against. `label` defaults to `'BatchedMesh3D'`.\n * @example\n * ```ts\n * const batched = new BatchedMesh3D({ size: 1000, label: 'crowd', parent: view.root });\n * ```\n * @category scene\n * @standard\n */\nexport interface BatchedMesh3DOptions extends Omit<Container3DOptions, 'width' | 'height' | 'depth'> {\n  /**\n   * Number of slots, fixed for the batch's lifetime; required\n   *\n   * Every slot takes memory whether it draws or not, so size it to the most you'll draw at once.\n   * @example\n   * ```ts\n   * const forest = new BatchedMesh3D({ size: treePositions.length });\n   * ```\n   */\n  size: number;\n  /**\n   * Frustum-culling mode for this batch; see {@link BatchedMesh3D#cull | cull}\n   * @default 'off'\n   * @example\n   * ```ts\n   * const forest = new BatchedMesh3D({ size: treePositions.length, cull: 'gpu' });\n   * ```\n   */\n  cull?: CullMode;\n  /**\n   * Fields every slot carries besides its matrix, for shader bits to read as `instance.<name>`\n   *\n   * Use it for values that differ per slot and change often, where a material per slot would not\n   * do: a tint, a fade, the parameters a vertex bit shapes the slot with. Each field is a `vec4`,\n   * in the `{ value, type }` shape of a pixi `UniformGroup` entry, and `value` is what every slot\n   * starts with. Names are letters, digits and single underscores, starting with a letter. The\n   * fields are fixed for the batch's lifetime.\n   *\n   * A bit declares the fields it reads in `bindings.instance` and reads them in either stage:\n   *\n   * ```ts\n   * const tintBit: ShaderBit = {\n   *   name: 'tint',\n   *   bindings: { instance: { tint: 'vec4<f32>' } },\n   *   gpu: { fragment: { material: 'albedo *= instance.tint.rgb;' } },\n   *   gl: { fragment: { material: 'albedo *= instance.tint.rgb;' } },\n   * };\n   * ```\n   *\n   * Changing a value uploads only the instance data, not the matrices. Each field read in fragment\n   * code takes a varying, so keep those few. Shadows don't run material bits, so a bit that moves\n   * vertices from instance data doesn't move the slot's shadow.\n   * @example\n   * ```ts\n   * const boxes = new BatchedMesh3D({\n   *   size: 1000,\n   *   instanceData: { tint: { value: [1, 1, 1, 1], type: 'vec4<f32>' } },\n   * });\n   *\n   * boxes.setInstanceDataAt(0, 'tint', 1, 0.2, 0.2, 1);\n   * ```\n   * @see {@link BatchedMesh3D.instanceData} For writing many slots a frame.\n   * @advanced\n   */\n  instanceData?: InstanceDataOptions;\n}\n\n/**\n * The settings of one {@link BatchedMesh3D} slot that aren't set through the batch's `set*At`\n * methods, reached through {@link BatchedMesh3D#items | items}\n *\n * A change shows once you call {@link BatchedMesh3D#invalidate | invalidate} for the slot.\n * @example\n * ```ts\n * const slot: BatchedMesh3DSlot = batched.items[0];\n *\n * slot.receiveShadow = false;\n * batched.invalidate(0);\n * ```\n * @category scene\n * @standard\n */\nexport interface BatchedMesh3DSlot {\n  /**\n   * How the slot turns to face the camera; see {@link Mesh3D#billboardMode}\n   * @default 'none'\n   * @example\n   * ```ts\n   * grass.items[i].billboardMode = 'cylindrical';\n   * grass.invalidate(i);\n   * ```\n   */\n  billboardMode: BillboardMode;\n  /**\n   * Whether the slot is shadowed by lights that cast shadows; see {@link Mesh3D#receiveShadow}\n   * @default true\n   * @example\n   * ```ts\n   * water.items[i].receiveShadow = false;\n   * water.invalidate(i);\n   * ```\n   */\n  receiveShadow: boolean;\n}\n\n/**\n * A scene node that draws many meshes as slots of one batch, with no scene node per mesh\n *\n * Reach for it for crowds, foliage, debris and other large counts. Each slot is a geometry, a\n * material and a matrix, and updating a slot costs a few array writes. Moving the `BatchedMesh3D`\n * moves every slot at no extra cost.\n *\n * The slot count is fixed at construction. Fill slots with\n * {@link BatchedMesh3D#setGeometryAt | setGeometryAt},\n * {@link BatchedMesh3D#setMaterialAt | setMaterialAt} and\n * {@link BatchedMesh3D#setMatrixAt | setMatrixAt}, then put each one in its passes with\n * {@link BatchedMesh3D#setPassesAt | setPassesAt}. A slot needs a geometry and a material only\n * while it's in a pass, so spare slots can stay empty. To spawn and despawn, show and hide slots\n * with {@link BatchedMesh3D#setVisibleAt | setVisibleAt}.\n *\n * Unlike a {@link Mesh3D}, a slot doesn't notice when its material's shader changes; see\n * {@link BatchedMesh3D#invalidate | invalidate}. For per-slot values a shader reads, such as a\n * tint, see {@link BatchedMesh3DOptions#instanceData | instanceData}.\n * @example\n * ```ts\n * import { BatchedMesh3D, RenderPassBit } from '@pixi/3d';\n *\n * const batched = new BatchedMesh3D({ size: 1000 });\n *\n * for (let i = 0; i < 1000; i++) {\n *   batched.setGeometryAt(i, cubeGeometry);\n *   batched.setMaterialAt(i, material);\n *   batched.setMatrixAt(i, matrix);\n *   batched.setPassesAt(i, RenderPassBit.OPAQUE | RenderPassBit.SHADOW);\n * }\n *\n * view.root.addChild(batched);\n *\n * // Moving one slot is a matrix write, cheap enough for every frame.\n * batched.setMatrixAt(0, nextMatrix);\n *\n * // Hide a slot to despawn it; show it again to respawn.\n * batched.setVisibleAt(1, false);\n * ```\n * @see {@link BatchedMesh3DOptions} For the constructor options.\n * @category scene\n * @standard\n */\nexport class BatchedMesh3D extends Container3D {\n  /**\n   * The view registers it, so it's built before `parent` attaches and freed after the node leaves its view\n   * @internal\n   */\n  public readonly batch: Mesh3DBatch;\n\n  /**\n   * Creates a new `BatchedMesh3D`; add it under {@link View3D.root | view.root} to draw it\n   * @example\n   * ```ts\n   * const batched = new BatchedMesh3D({ size: 1000 });\n   * view.root.addChild(batched);\n   * ```\n   * @param options - Construction options; see {@link BatchedMesh3DOptions}.\n   */\n  constructor(options: BatchedMesh3DOptions) {\n    const { size, parent, cull, instanceData, ...rest } = definedProps(options);\n\n    super({ label: 'BatchedMesh3D', ...rest });\n\n    this.batch = new Mesh3DBatch({ size, renderData: this, instanceData });\n    this.batch.cull = cull ?? 'off';\n    parent?.addChild(this);\n  }\n\n  /**\n   * The slots, one per index\n   *\n   * Set a slot's geometry, material and matrix through the `set*At` methods. A slot's\n   * `billboardMode` and `receiveShadow` are set here, followed by\n   * {@link BatchedMesh3D#invalidate | invalidate}.\n   * @example\n   * ```ts\n   * batched.items[0].billboardMode = 'spherical';\n   * batched.invalidate(0);\n   * ```\n   */\n  public get items(): readonly BatchedMesh3DSlot[] {\n    return this.batch.items;\n  }\n\n  /**\n   * Frustum-culling mode for this batch, which ignores the view's own `cull`\n   *\n   * Off by default, since a batch usually sits mostly in view. Turn it on for a large batch spread\n   * well beyond the view, such as scattered scenery. Once on, it tests every slot each frame, and\n   * again for each shadow map that redraws, even with the whole batch in view; where the test runs\n   * on the CPU, as under WebGL2, that cost grows with the slot count. A change takes effect on the\n   * next render.\n   * @example\n   * ```ts\n   * // ten thousand trees across the map, most of them off screen: test each one\n   * forest.cull = 'gpu';\n   * ```\n   * @see {@link CullMode} For the modes.\n   */\n  public get cull(): CullMode {\n    return this.batch.cull;\n  }\n\n  /**\n   * Sets this batch's frustum-culling mode\n   * @param value - The culling mode.\n   */\n  public set cull(value: CullMode) {\n    this.batch.cull = value;\n  }\n\n  /**\n   * Number of slots, fixed at construction\n   * @example\n   * ```ts\n   * for (let i = 0; i < batched.size; i++) batched.setMatrixAt(i, matrices[i]);\n   * ```\n   */\n  public get size(): number {\n    return this.batch.items.length;\n  }\n\n  /**\n   * Sets a slot's matrix, relative to this node\n   *\n   * It copies the matrix and allocates nothing, so it's fine for every slot every frame. The matrix\n   * must be affine, with a bottom row of `0, 0, 0, 1`. To skip the copy when rewriting many slots a\n   * frame, write into {@link BatchedMesh3D#matrices | matrices}.\n   * @example\n   * ```ts\n   * batched.setMatrixAt(i, matrix.makeTranslation(x, 0, z));\n   * ```\n   * @param index - The slot index within this batch\n   * @param matrix - The slot's matrix\n   */\n  public setMatrixAt(index: number, matrix: Matrix4): void {\n    this.batch.setMatrixAt(index, matrix);\n  }\n\n  /**\n   * The slot matrices as interleaved data, for rewriting many slots a frame without a copy each\n   *\n   * {@link BatchMatrices} has the layout and the rules:\n   *\n   * ```ts\n   * const { data, stride, offset } = batched.matrices;\n   *\n   * for (let i = 0, o = offset; i < batched.size; i++, o += stride) {\n   *   data[o + 13] = heights[i]; // translation Y\n   * }\n   *\n   * batched.matrices.update();\n   * ```\n   * @advanced\n   */\n  public get matrices(): BatchMatrices {\n    return this.batch.matrices;\n  }\n\n  /**\n   * Writes one instance-data field of the item at `index`\n   *\n   * Allocates nothing, and the next render uploads it. Throws when the batch declares no field of\n   * that name.\n   * @example\n   * ```ts\n   * boxes.setInstanceDataAt(i, 'tint', 1, 0.2, 0.2, 1);\n   * ```\n   * @param index - The slot index within this batch\n   * @param name - The field, as declared in the `instanceData` option\n   * @param x - The field's first number\n   * @param y - The field's second number\n   * @param z - The field's third number\n   * @param w - The field's fourth number\n   * @see {@link BatchedMesh3D.instanceData} For rewriting many slots a frame.\n   * @advanced\n   */\n  public setInstanceDataAt(index: number, name: string, x: number, y: number, z: number, w: number): void {\n    this.batch.setInstanceDataAt(index, name, x, y, z, w);\n  }\n\n  /**\n   * The slots' instance data as interleaved data, for rewriting many slots a frame\n   *\n   * {@link BatchInstanceData} has the layout and the rules:\n   *\n   * ```ts\n   * const { data, stride, offset, fields } = boxes.instanceData;\n   *\n   * for (let i = 0, o = offset + fields.tint; i < boxes.size; i++, o += stride) {\n   *   data[o + 3] = fade[i];\n   * }\n   *\n   * boxes.instanceData.update();\n   * ```\n   *\n   * Throws when the batch was built without the `instanceData` option.\n   * @advanced\n   */\n  public get instanceData(): BatchInstanceData {\n    return this.batch.instanceData;\n  }\n\n  /**\n   * Sets a slot's geometry; the slot rebuilds its shader on the next frame\n   * @example\n   * ```ts\n   * forest.setGeometryAt(i, i % 3 === 0 ? pineGeometry : oakGeometry);\n   * ```\n   * @param index - The slot index within this batch\n   * @param geometry - The slot's geometry\n   */\n  public setGeometryAt(index: number, geometry: Geometry3D): void {\n    this.batch.setGeometryAt(index, geometry);\n  }\n\n  /**\n   * Sets a slot's material; the slot rebuilds its shader on the next frame\n   *\n   * The slot stays in the passes {@link BatchedMesh3D#setPassesAt | setPassesAt} gave it, so\n   * move it there when the new material blends and the old one didn't, or the other way round.\n   * @example\n   * ```ts\n   * crowd.setMaterialAt(i, team === 'red' ? redShirt : blueShirt);\n   * ```\n   * @param index - The slot index within this batch\n   * @param material - The slot's material\n   */\n  public setMaterialAt(index: number, material: BaseMaterial3D): void {\n    this.batch.setMaterialAt(index, material);\n  }\n\n  /**\n   * Shows or hides a slot, the way {@link Container3D#visible} does for a mesh\n   *\n   * A hidden slot keeps its geometry, material, matrix and passes, and draws nothing, shadows\n   * included. Every slot starts visible. A flip rebuilds nothing, which makes this the way to spawn\n   * and despawn: size the batch for the most slots you'll use and hide the spare ones. With `cull`\n   * off, the next frame after a flip filters the whole batch, at a cost set by the batch's size, not\n   * the number of flips.\n   *\n   * Blended slots are the exception: the `TRANSPARENT` pass sorts hidden slots too, every frame.\n   * Take a blended slot that stays spare for a while out of the pass with\n   * {@link BatchedMesh3D#setPassesAt | setPassesAt}, which costs one rebuild, and keep hiding one\n   * that flips often.\n   * @example\n   * ```ts\n   * bullets.setVisibleAt(i, false); // despawn\n   * bullets.setVisibleAt(j, true); // spawn\n   * ```\n   * @param index - The slot index within this batch\n   * @param visible - Whether the slot draws\n   */\n  public setVisibleAt(index: number, visible: boolean): void {\n    this.batch.setVisibleAt(index, visible);\n  }\n\n  /**\n   * Whether a slot is shown, as {@link BatchedMesh3D#setVisibleAt | setVisibleAt} left it\n   *\n   * A slot in no pass can still read `true`.\n   * @example\n   * ```ts\n   * for (let i = 0; i < bullets.size; i++) {\n   *   if (bullets.getVisibleAt(i)) continue;\n   *   bullets.setMatrixAt(i, muzzleMatrix);\n   *   bullets.setVisibleAt(i, true);\n   *   break;\n   * }\n   * ```\n   * @param index - The slot index within this batch\n   * @returns `false` while the slot is hidden\n   */\n  public getVisibleAt(index: number): boolean {\n    return this.batch.getVisibleAt(index);\n  }\n\n  /**\n   * Sets which passes draw a slot; `0` takes it out of every pass\n   *\n   * Pass a bitwise OR of {@link RenderPassBit} flags. A slot doesn't pick its passes from its\n   * material the way a {@link Mesh3D} does, so match them yourself: `OPAQUE` for an opaque or\n   * `'mask'` material, `TRANSPARENT` for a `'blend'` one, `TRANSMISSION` in place of `OPAQUE` for\n   * a {@link Material3D} with `transmission`, plus `SHADOW` to cast shadows. No flag joins a custom\n   * {@link MeshPass}, such as an outline.\n   *\n   * A change costs some work on the next frame in each pass it touches, and a slot that joins a\n   * pass rebuilds its shader. To hide and show slots, use\n   * {@link BatchedMesh3D#setVisibleAt | setVisibleAt}, which rebuilds nothing.\n   * @example\n   * ```ts\n   * batched.setPassesAt(i, RenderPassBit.OPAQUE | RenderPassBit.SHADOW);\n   * batched.setPassesAt(j, 0);\n   * ```\n   * @param index - The slot index within this batch\n   * @param passMask - Bitmask of `RenderPassBit` flags for this slot\n   */\n  public setPassesAt(index: number, passMask: number): void {\n    this.batch.setPassesAt(index, passMask);\n  }\n\n  /**\n   * Makes a slot rebuild its shader and draw state on the next frame\n   *\n   * Swapping a slot's geometry or material does this for you. A change to the shader or render\n   * state of a material slots already use doesn't, such as a texture swap, a new `alphaMode` or a\n   * `state` field ({@link BaseMaterial3D} lists them), so call this for each of those slots\n   * afterwards, after changing a slot's `billboardMode` or `receiveShadow`, and after\n   * {@link Geometry3D.unload | unloading} a slot's geometry to apply an edit. A slot's passes\n   * don't follow its material, so when `alphaMode` switches to or from `'blend'`, also move the\n   * slot with {@link BatchedMesh3D#setPassesAt | setPassesAt}: `RenderPassBit.TRANSPARENT` to\n   * blend, `RenderPassBit.OPAQUE` to stop. Values such as\n   * `baseColor`, and the view-wide `toneMapping`, `fog`, `environment` and `shadowFilter`, reach\n   * every slot on their own.\n   * @example\n   * ```ts\n   * leafMaterial.textures.baseColor = autumnLeaves;\n   * for (const i of leafSlots) trees.invalidate(i);\n   * ```\n   * @param index - The slot index within this batch\n   */\n  public invalidate(index: number): void {\n    this.batch.invalidate(index);\n  }\n\n  /**\n   * Frees this batch's GPU memory and unloads its slots' geometries with\n   * {@link Geometry3D.unload}; the next render rebuilds them and draws the same image\n   *\n   * Slot materials are left alone, as {@link Mesh3D.unload} leaves them; call\n   * {@link BaseMaterial3D.unload} to free their textures. A batch taken out of the scene keeps its\n   * GPU memory until this is called or it's destroyed, so adding it back before then is cheap.\n   * @example\n   * ```ts\n   * view.root.removeChild(crowd);\n   * crowd.unload(); // hand back the crowd's GPU memory until it is shown again\n   * ```\n   * @see {@link BatchedMesh3D.destroy} For permanent teardown.\n   */\n  public override unload(): void {\n    if (this.destroyed) return;\n\n    super.unload();\n\n    const seenGeometry = new Set<Geometry3D>();\n    const items = this.batch.items;\n    for (let i = 0; i < items.length; i++) {\n      const geometry = items[i].geometry;\n      if (!geometry) continue;\n      if (!seenGeometry.has(geometry)) {\n        seenGeometry.add(geometry);\n        geometry.unload();\n      }\n      this.batch.invalidate(i);\n    }\n\n    this.batch.unload();\n  }\n\n  /**\n   * Destroys this node and its batch\n   *\n   * The batch is always destroyed. Slot geometries and materials are often shared, so they stay\n   * unless you pass `geometry` or `material`; each is destroyed once, however many slots use it.\n   * `texture` then frees the destroyed materials' textures, and `textureSource` their sources.\n   * @example\n   * ```ts\n   * crowd.destroy({ geometry: true, material: true });\n   * ```\n   * @param options - Teardown flags; see {@link Destroy3DOptions}.\n   */\n  public override destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n\n    super.destroy(options);\n\n    const destroyGeometry = resolveDestroy3DFlag(options, 'geometry');\n    const destroyMaterial = resolveDestroy3DFlag(options, 'material');\n\n    if (destroyGeometry || destroyMaterial) {\n      const seenGeometry = new Set<Geometry3D>();\n      const seenMaterial = new Set<BaseMaterial3D>();\n\n      for (const item of this.batch.items) {\n        if (destroyGeometry && item.geometry && !seenGeometry.has(item.geometry)) {\n          seenGeometry.add(item.geometry);\n          item.geometry.destroy(true);\n        }\n        if (destroyMaterial && item.material && !seenMaterial.has(item.material)) {\n          seenMaterial.add(item.material);\n          item.material.destroy(options);\n        }\n      }\n    }\n\n    this.batch.destroy();\n  }\n}\n","import { DEG_TO_RAD, definedProps, Point, Rectangle } from 'pixi.js';\nimport type { RenderTexture } from 'pixi.js';\n\nimport type { CameraData } from '../../core/CameraData';\nimport { Matrix4 } from '../../math/matrix/Matrix4';\nimport { Frustum } from '../../math/misc/Frustum';\nimport type { Plane } from '../../math/shapes/Plane';\nimport type { Destroy3DOptions } from '../../utils/Destroy3DOptions';\nimport { Container3D } from '../Container3D';\nimport type { Container3DOptions } from '../Container3D';\n\n/**\n * Projection mode for a {@link Camera3D}\n *\n * - `'perspective'`: distant things look smaller, with the view's height set by `fov`.\n * - `'orthographic'`: no foreshortening, with the view's width set by `orthographicSize`. Suits\n *   isometric games, maps and editors.\n * @example\n * ```ts\n * const mode: CameraMode = isometric ? 'orthographic' : 'perspective';\n *\n * view.camera.mode = mode;\n * ```\n * @category scene\n * @standard\n */\nexport type CameraMode = 'perspective' | 'orthographic';\n\n/**\n * Constructor options for {@link Camera3D}\n *\n * Every field has a default. The {@link Container3DOptions} apply too, and `label` defaults to\n * `'Camera3D'`.\n * @example\n * ```ts\n * const camera = new Camera3D({\n *   mode: 'perspective',\n *   fov: 45,\n *   near: 0.1,\n *   far: 500,\n *   label: 'mainCamera',\n * });\n * ```\n * @category scene\n * @standard\n */\nexport interface Camera3DOptions extends Container3DOptions {\n  /**\n   * Projection mode; see {@link Camera3D#mode}\n   * @default 'perspective'\n   * @example\n   * ```ts\n   * const mapCamera = new Camera3D({ mode: 'orthographic', orthographicSize: 20 });\n   * ```\n   */\n  mode?: CameraMode;\n  /**\n   * Vertical field of view in degrees; see {@link Camera3D#fov}\n   * @default 60\n   * @example\n   * ```ts\n   * const camera = new Camera3D({ fov: 45 });\n   * ```\n   */\n  fov?: number;\n  /**\n   * Zoom factor; see {@link Camera3D#zoom}\n   * @default 1\n   * @example\n   * ```ts\n   * const scope = new Camera3D({ zoom: 4 });\n   * ```\n   */\n  zoom?: number;\n  /**\n   * Distance to the near clipping plane, in world units; see {@link Camera3D#near}\n   * @default 0.1\n   * @example\n   * ```ts\n   * const camera = new Camera3D({ near: 0.01, far: 100 });\n   * ```\n   */\n  near?: number;\n  /**\n   * Distance to the far clipping plane, in world units; see {@link Camera3D#far}\n   * @default 1000\n   * @example\n   * ```ts\n   * const camera = new Camera3D({ near: 1, far: 5000 });\n   * ```\n   */\n  far?: number;\n  /**\n   * Half the view's width in world units for an orthographic camera; see\n   * {@link Camera3D#orthographicSize}\n   * @default 5\n   * @example\n   * ```ts\n   * const mapCamera = new Camera3D({ mode: 'orthographic', orthographicSize: 20 });\n   * ```\n   */\n  orthographicSize?: number;\n  /**\n   * Plane that hides everything on the camera's side of it; see {@link Camera3D#clippingPlane}\n   * @default null\n   * @example\n   * ```ts\n   * const reflectionCamera = new Camera3D({ clippingPlane: waterline });\n   * ```\n   */\n  clippingPlane?: Plane | null;\n  /**\n   * Texture this camera draws into; see {@link Camera3D#renderTexture}\n   * @default null\n   * @example\n   * ```ts\n   * const securityCamera = new Camera3D({ renderTexture: RenderTexture.create({ width: 256, height: 256 }) });\n   * ```\n   */\n  renderTexture?: RenderTexture | null;\n}\n\n/**\n * The point of view a scene is drawn from\n *\n * A camera is a {@link Container3D}: move, rotate and parent it like any other node. Cameras face\n * local **-Z**, as in glTF and OpenGL, so {@link Container3D#lookAt | camera.lookAt(target)}\n * points the lens at the target.\n *\n * Every {@link View3D} has a camera to start with. Assign another to {@link View3D#camera}, or\n * hand one to a pass to draw a second view of the scene, such as a minimap or a security feed.\n * A camera must be in the view's scene graph, which keeps its world transform current.\n * `view.camera` adds a camera that has no parent to `view.root`; add any other camera yourself.\n *\n * Change the projection settings at any time: the view rebuilds the matrices from them each time\n * it draws the camera.\n * @example\n * ```ts\n * import { Camera3D } from '@pixi/3d';\n *\n * const camera = new Camera3D({ fov: 45, near: 0.1, far: 500 });\n * camera.position.set(0, 2.5, 7);\n * camera.lookAt({ x: 0, y: 0, z: 0 });\n *\n * view.camera = camera;\n *\n * // Swap to orthographic at runtime:\n * camera.mode = 'orthographic';\n * camera.orthographicSize = 4;\n * ```\n * @see {@link Camera3DOptions} For all constructor options.\n * @see `OrbitCamera` (from `@pixi/3d/extras`) For orbit, pan and zoom controls.\n * @category scene\n * @standard\n */\nexport class Camera3D extends Container3D {\n  /**\n   * Defaults for every new `Camera3D`; an option passed as `undefined` keeps its default\n   * @example\n   * ```ts\n   * Camera3D.defaultOptions.fov = 50;\n   * Camera3D.defaultOptions.far = 2000;\n   * const camera = new Camera3D(); // picks up the overrides above\n   * ```\n   */\n  public static defaultOptions: Camera3DOptions = {\n    mode: 'perspective',\n    fov: 60,\n    zoom: 1,\n    near: 0.1,\n    far: 1000,\n    orthographicSize: 5,\n    clippingPlane: null,\n    renderTexture: null,\n  };\n\n  /**\n   * Projection matrix, from camera space to clip space\n   *\n   * The view rebuilds it from the camera's settings each time it draws the camera, with\n   * {@link Camera3D#clippingPlane | clippingPlane} applied. Read it, but don't write it.\n   * @example\n   * ```ts\n   * const inverseProjection = new Matrix4().getInverse(camera.projection);\n   * ```\n   */\n  public readonly projection: Matrix4 = new Matrix4();\n\n  /**\n   * View matrix, from world space to camera space: the inverse of the camera's world transform\n   *\n   * The view rebuilds it each time it draws the camera. Read it, but don't write it.\n   * @example\n   * ```ts\n   * const inCameraSpace = new Vector3(5, 0, 0).applyMatrix4(camera.view);\n   * const inFront = inCameraSpace.z < 0;\n   * ```\n   */\n  public readonly view: Matrix4 = new Matrix4();\n\n  /**\n   * `projection` times `view`, from world space to clip space\n   *\n   * The view rebuilds it each time it draws the camera. Read it, but don't write it.\n   * @example\n   * ```ts\n   * const ndc = new Vector3(5, 0, 0).applyMatrix4(camera.viewProjection);\n   * ```\n   */\n  public readonly viewProjection: Matrix4 = new Matrix4();\n\n  /**\n   * World-space volume this camera sees, rebuilt each time the view draws the camera\n   *\n   * Culling tests against {@link Camera3D#cullFrustum | cullFrustum}, which is this same object\n   * unless you replace it.\n   * @example\n   * ```ts\n   * const onScreen = camera.frustum.intersectsSphere(enemy.boundingSphere);\n   * ```\n   */\n  public readonly frustum: Frustum = new Frustum();\n\n  /**\n   * Volume meshes are culled against when this camera draws; starts as {@link Camera3D#frustum | frustum}\n   *\n   * Assign another frustum to cull against a different volume, such as a frozen copy to watch\n   * culling from a second viewpoint, and assign `frustum` back to restore. The view never rebuilds\n   * a frustum you assign.\n   * @example\n   * ```ts\n   * const frozen = view.camera.frustum.clone();\n   *\n   * view.camera.cullFrustum = frozen;\n   * ```\n   */\n  public cullFrustum: Frustum = this.frustum;\n\n  /**\n   * Projection mode; change it at any time\n   * @default 'perspective'\n   * @example\n   * ```ts\n   * camera.mode = 'orthographic';\n   * camera.orthographicSize = 10;\n   * ```\n   */\n  public mode: CameraMode;\n\n  /**\n   * Vertical field of view in degrees, for a perspective camera at a `zoom` of 1\n   *\n   * The horizontal field follows from the aspect ratio of the rect the image lands in.\n   * @default 60\n   * @example\n   * ```ts\n   * camera.fov = 35;\n   * ```\n   */\n  public fov = 0;\n\n  /**\n   * Magnification: a zoom of 2 shows the scene twice as large, in either mode\n   *\n   * A perspective camera's vertical field of view becomes `2 * atan(tan(fov / 2) / zoom)`, and an\n   * orthographic camera's half-width is `orthographicSize / zoom`.\n   * @default 1\n   * @example\n   * ```ts\n   * camera.zoom = aiming ? 2 : 1;\n   * ```\n   */\n  public zoom = 0;\n\n  /**\n   * Distance to the near clipping plane, in world units; anything closer isn't drawn\n   *\n   * Keep it as large as the scene allows. Depth precision depends mostly on `near`, hardly on\n   * `far`, and a tiny `near` makes distant surfaces flicker through each other.\n   * @default 0.1\n   * @example\n   * ```ts\n   * camera.near = 0.5;\n   * ```\n   */\n  public near = 0;\n\n  /**\n   * Distance to the far clipping plane, in world units; anything further isn't drawn\n   * @default 1000\n   * @example\n   * ```ts\n   * camera.far = 200;\n   * ```\n   */\n  public far = 0;\n\n  /**\n   * Half the view's width in world units, for an orthographic camera at a `zoom` of 1\n   *\n   * The height follows from the aspect ratio of the rect the image lands in.\n   * @default 5\n   * @example\n   * ```ts\n   * camera.orthographicSize = level.width / 2;\n   * ```\n   */\n  public orthographicSize = 0;\n\n  /**\n   * Plane that hides everything on the camera's side of it, or `null` for none\n   *\n   * A mirror or portal camera uses one to cut its scene at the mirror's or the portal's surface.\n   * The plane is in the camera's view space, and the camera has to sit on the side it hides.\n   * It works only for a perspective camera drawing into a texture or into a view that isn't\n   * rotated.\n   * @example\n   * ```ts\n   * portalCamera.clippingPlane = portalExitClipPlane(exit.worldTransform, portalCamera.worldTransform);\n   * ```\n   */\n  public clippingPlane: Plane | null;\n\n  /**\n   * Texture this camera draws into, or `null` to draw into the view\n   *\n   * Every pass that names this camera, such as `new MeshPass({ name: 'opaque', camera })`, draws\n   * into the texture instead of the view: a security feed on a monitor, a mirror, a portal. The\n   * projection takes the texture's aspect ratio and follows a resize on the next frame. The view's\n   * own camera can't have one; the view throws when it renders.\n   *\n   * The picture lands after the camera's last pass, so a mesh that shows the texture while the\n   * camera draws it shows last frame's picture: a monitor that films itself recurses, one frame late.\n   *\n   * An 8-bit texture, the default, holds the picture with the view's tone curve applied, ready for\n   * a 2D sprite; the view's post effects and the canvas's antialiasing don't reach it. In a view\n   * with a `'beforeToneMapping'` effect, an `rgba16float` texture holds the scene's linear light\n   * instead, brightness above 1 included, which a `PortalMaterial` there needs. A mesh applies the\n   * view's exposure to the feed again. Other materials, such as `FlatMaterial`, apply the tone curve\n   * again too, so an 8-bit feed on one matches the scene only at an exposure of 1 with\n   * `toneMapping: 'none'`.\n   *\n   * Create the texture with `antialias: true` for smooth edges, and with `autoGenerateMipmaps: true`\n   * for the view to regenerate its mipmaps each frame; turning mipmaps on after the texture's first\n   * frame does nothing.\n   * @example\n   * ```ts\n   * const feed = RenderTexture.create({ width: 256, height: 256 });\n   * const securityCamera = new Camera3D({ renderTexture: feed });\n   *\n   * view.root.addChild(securityCamera);\n   * view.passes = [new MeshPass({ name: 'opaque', camera: securityCamera })];\n   * ```\n   */\n  public renderTexture: RenderTexture | null;\n\n  /**\n   * `null` until `getCameraData` makes it on the camera's first draw\n   * @internal\n   */\n  public _cameraData: CameraData | null = null;\n\n  /**\n   * Rect the camera's image fills, as fractions of the view: `(0, 0)` is the top-left corner and\n   * `(1, 1)` the bottom-right\n   *\n   * Defaults to the whole view. For a camera with a {@link Camera3D#renderTexture | renderTexture},\n   * it is a rect of that texture instead.\n   * @example\n   * ```ts\n   * view3d.camera.viewport.set(0, 0, 0.5, 1); // the left half of the view\n   * ```\n   */\n  public readonly viewport: Rectangle = new Rectangle(0, 0, 1, 1);\n\n  /**\n   * Sub-pixel offset the camera's image is drawn at, in the scene's pixels: `+x` moves it right,\n   * `+y` down\n   *\n   * A scene pixel is a physical pixel, or larger when {@link View3D#resolution} draws the scene\n   * smaller. Temporal anti-aliasing and upscalers set a new offset each frame, usually -0.5 to 0.5,\n   * and blend the frames. Only the drawn image moves; the matrices, culling and picking ignore it.\n   * Leave it at `(0, 0)` unless something blends the frames; a changing offset on its own makes the\n   * image shake.\n   * @example\n   * ```ts\n   * camera.jitter.set(0.25, -0.25);\n   * ```\n   * @advanced\n   */\n  public readonly jitter: Point = new Point();\n\n  /** @internal */\n  protected override _lookAtForwardIsPositiveZ: boolean = false;\n\n  /**\n   * Creates a new `Camera3D`\n   * @example\n   * ```ts\n   * const camera = new Camera3D({ fov: 45, near: 0.1, far: 500 });\n   * view.camera = camera;\n   * ```\n   * @param options - Construction options; see {@link Camera3DOptions}\n   */\n  constructor(options: Camera3DOptions = {}) {\n    const { mode, fov, zoom, near, far, orthographicSize, clippingPlane, renderTexture, ...rest } = {\n      ...Camera3D.defaultOptions,\n      ...definedProps(options),\n    };\n\n    super({ label: 'Camera3D', ...rest });\n\n    this.mode = mode!;\n    this.fov = fov!;\n    this.zoom = zoom!;\n    this.near = near!;\n    this.far = far!;\n    this.orthographicSize = orthographicSize!;\n    this.clippingPlane = clippingPlane ?? null;\n    this.renderTexture = renderTexture ?? null;\n  }\n\n  /**\n   * Switches to perspective projection and sets its field of view and clipping planes\n   *\n   * Omitted arguments take their {@link Camera3D.defaultOptions | defaultOptions} value, not the\n   * camera's current one.\n   * @example\n   * ```ts\n   * camera.usePerspective(50, 0.1, 500);\n   * ```\n   * @param fov - Vertical field of view in degrees\n   * @param near - Distance to the near clipping plane\n   * @param far - Distance to the far clipping plane\n   */\n  public usePerspective(\n    fov: number = Camera3D.defaultOptions.fov!,\n    near: number = Camera3D.defaultOptions.near!,\n    far: number = Camera3D.defaultOptions.far!,\n  ): void {\n    this.mode = 'perspective';\n    this.fov = fov;\n    this.near = near;\n    this.far = far;\n  }\n\n  /**\n   * Switches to orthographic projection and sets its size and clipping planes\n   *\n   * Omitted arguments take their {@link Camera3D.defaultOptions | defaultOptions} value, not the\n   * camera's current one.\n   * @example\n   * ```ts\n   * camera.useOrthographic(12);\n   * ```\n   * @param size - Half the view's width in world units at a `zoom` of 1\n   * @param near - Distance to the near clipping plane\n   * @param far - Distance to the far clipping plane\n   */\n  public useOrthographic(\n    size: number = Camera3D.defaultOptions.orthographicSize!,\n    near: number = Camera3D.defaultOptions.near!,\n    far: number = Camera3D.defaultOptions.far!,\n  ): void {\n    this.mode = 'orthographic';\n    this.orthographicSize = size;\n    this.near = near;\n    this.far = far;\n  }\n\n  /**\n   * Forgets where the camera was at its previous render, so its next render reads no motion\n   *\n   * Call it on a cut, such as a teleport, a respawn or a change of shot, so effects that read\n   * motion, such as `MotionBlurEffect`, don't smear the first frame after it. A camera's first\n   * render needs no call. Every render moves the history on, so a view drawn twice in one frame\n   * reads no motion on its second draw.\n   * @example\n   * ```ts\n   * camera.position.copyFrom(spawnPoint);\n   * camera.resetHistory();\n   * ```\n   */\n  public resetHistory(): void {\n    if (this._cameraData) this._cameraData._hasHistory = false;\n  }\n\n  /**\n   * Removes the camera from the scene graph and frees the GPU data it drew from\n   *\n   * The {@link Camera3D#clippingPlane | clippingPlane} and\n   * {@link Camera3D#renderTexture | renderTexture} are yours and are left alone. A view keeps\n   * pointing at its camera after the camera is destroyed, and its next render with meshes to draw\n   * throws, so assign the view another camera first. Calling it again does nothing.\n   * @example\n   * ```ts\n   * view.camera = gameplayCamera;\n   * cutsceneCamera.destroy();\n   * ```\n   * @param options - Forwarded to {@link Container3D#destroy}\n   */\n  public override destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n\n    this._cameraData?.destroy();\n    this._cameraData = null;\n\n    super.destroy(options);\n  }\n\n  /**\n   * Writes the projection this camera's settings give for an aspect ratio into `out`\n   *\n   * It matches {@link Camera3D#projection | projection} apart from the\n   * {@link Camera3D#clippingPlane | clippingPlane} and, when the image is rotated or partly off its\n   * target, a fit to where it lands.\n   * @example\n   * ```ts\n   * const thumbnailProjection = camera.computeProjection(1, new Matrix4());\n   * ```\n   * @param aspect - Width over height of the rect the image fills\n   * @param out - Matrix the projection is written into\n   * @returns `out`\n   * @advanced\n   */\n  public computeProjection(aspect: number, out: Matrix4): Matrix4 {\n    if (this.mode === 'perspective') {\n      out.makePerspective(2 * Math.atan(this._tanHalfFovY()), aspect, this.near, this.far);\n    } else {\n      const size = this.orthographicSize / this.zoom;\n\n      out.makeOrthographic(-size, size, size / aspect, -size / aspect, this.near, this.far);\n    }\n\n    return out;\n  }\n\n  /** @internal */\n  public _tanHalfFovY(): number {\n    return Math.tan((this.fov * DEG_TO_RAD) / 2) / this.zoom;\n  }\n}\n","import { Color } from 'pixi.js';\nimport type { ColorSource } from 'pixi.js';\n\nimport type { CascadeSlot } from '../../core/render-passes/shadow/shadowPassUtils';\nimport { releaseShadowCascades } from '../../core/render-passes/shadow/shadowPassUtils';\nimport type { Matrix4 } from '../../math/matrix/Matrix4';\nimport type { Box } from '../../math/shapes/Box';\nimport type { Destroy3DOptions } from '../../utils/Destroy3DOptions';\nimport { Container3D } from '../Container3D';\nimport type { Container3DOptions } from '../Container3D';\n\n/**\n * The four kinds of {@link Light}, as a light's {@link Light.type | type} reports them\n * @example\n * ```ts\n * const suns = view.lights.filter((light: Light) => light.type === 'directional');\n * ```\n * @category scene\n * @standard\n */\nexport type LightType = 'directional' | 'point' | 'spot' | 'ambient';\n\n/**\n * Shadow options every shadow-casting light takes, whichever way its shadow is placed\n * @example\n * ```ts\n * const tuning: LightShadowCommonOptions = { bias: 0.002, normalBias: 0.05 };\n * const sun = new DirectionalLight({ castShadow: true, shadow: { cascades: 3, ...tuning } });\n * ```\n * @see {@link LightShadowOptions} For the full option set.\n * @category scene\n * @standard\n */\nexport interface LightShadowCommonOptions {\n  /**\n   * Depth offset that keeps a surface from shadowing itself; see {@link LightShadow.bias}\n   * @default 0.001\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { bias: 0.002 } });\n   * ```\n   */\n  bias?: number;\n  /**\n   * Offset along the surface normal that keeps a surface from shadowing itself; see\n   * {@link LightShadow.normalBias}\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { normalBias: 0.05 } });\n   * ```\n   */\n  normalBias?: number;\n}\n\n/**\n * Shadow options for one shadow map over a fixed world-space box, the default placement\n *\n * The box is fitted to the scene's shadow casters, or set with\n * {@link LightShadowBoundsOptions.bounds | bounds}. Suits a scene that fits in one box, such as a\n * room, an arena, a board, or scenery an orbit camera circles. A spot light takes these options\n * but ignores `bounds`: its shadow covers its cone.\n * @example\n * ```ts\n * const sun = new DirectionalLight({\n *   castShadow: true,\n *   shadow: { bounds: Box.fromCenterSize({ x: 0, y: 0, z: 0 }, 40), update: 'manual' },\n * });\n * ```\n * @category scene\n * @standard\n */\nexport interface LightShadowBoundsOptions extends LightShadowCommonOptions {\n  /**\n   * World-space box a directional light's shadow covers; see {@link LightShadow.bounds}\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { bounds: Box.fromCenterSize(arena.position, 30) } });\n   * ```\n   */\n  bounds?: Box;\n  /**\n   * Not available with a fixed box; cascades are the other placement, see\n   * {@link LightShadowCascadesOptions}\n   * @hidden\n   */\n  cascades?: never;\n  /**\n   * How often the shadow redraws; see {@link LightShadow.update}\n   * @default 1\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { update: 4 } });\n   * ```\n   */\n  update?: number | 'manual';\n  /**\n   * Not available with a fixed box; see {@link LightShadowCascadesOptions.maxDistance}\n   * @hidden\n   */\n  maxDistance?: never;\n  /**\n   * Not available with a fixed box; see {@link LightShadowCascadesOptions.lambda}\n   * @hidden\n   */\n  lambda?: never;\n}\n\n/**\n * Shadow options for cascaded shadow maps, which follow the camera, for a directional light\n *\n * The camera's view is cut into slices by distance, and each slice gets its own shadow map, so\n * nearby shadows stay sharp however large the world is. Suits open worlds and anything the\n * camera roams across. Spot lights ignore cascades.\n * @example\n * ```ts\n * const sun = new DirectionalLight({ castShadow: true, shadow: { cascades: 3, maxDistance: 80 } });\n * ```\n * @category scene\n * @standard\n */\nexport interface LightShadowCascadesOptions extends LightShadowCommonOptions {\n  /**\n   * How many slices the camera's view is cut into; see {@link LightShadow.cascades}\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { cascades: 4 } });\n   * ```\n   */\n  cascades: 1 | 2 | 3 | 4;\n  /**\n   * Not available with cascades; a fixed box is the other placement, see\n   * {@link LightShadowBoundsOptions}\n   * @hidden\n   */\n  bounds?: never;\n  /**\n   * How often each cascade redraws; see {@link LightShadow.update}\n   * @default 1\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { cascades: 3, update: [1, 2, 8] } });\n   * ```\n   */\n  update?: number | number[] | 'manual';\n  /**\n   * How far from the camera the cascades reach, in world units; see {@link LightShadow.maxDistance}\n   * @default 50\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { cascades: 3, maxDistance: 120 } });\n   * ```\n   */\n  maxDistance?: number;\n  /**\n   * How the distance is shared out between cascades; see {@link LightShadow.lambda}\n   * @default 0.5\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { cascades: 3, lambda: 0.8 } });\n   * ```\n   */\n  lambda?: number;\n}\n\n/**\n * Shadow options a light takes, in one of two placements\n *\n * A fixed box ({@link LightShadowBoundsOptions}) is the default: one shadow map over the scene's\n * shadow casters, or over the `bounds` you give. Cascades ({@link LightShadowCascadesOptions})\n * follow the camera instead. Passing `bounds` and `cascades` together is a type error. Fields\n * left out take their defaults. Only read while {@link LightOptions.castShadow | castShadow} is\n * `true`.\n * @example\n * ```ts\n * const shadow: LightShadowOptions = openWorld ? { cascades: 3, maxDistance: 80 } : { bounds: arenaBounds };\n * const sun = new DirectionalLight({ castShadow: true, shadow });\n * ```\n * @see {@link Light.shadow} For the resolved shadow state on a constructed light.\n * @category scene\n * @standard\n */\nexport type LightShadowOptions = LightShadowBoundsOptions | LightShadowCascadesOptions;\n\n/**\n * A light's shadow settings, as {@link Light.shadow} holds them\n *\n * The same fields as {@link LightShadowOptions}, with the defaults filled in. Setting both `bounds`\n * and `cascades` here isn't a type error; cascades win and a warning says so.\n * @example\n * ```ts\n * sun.shadow.cascades = 3;\n * sun.shadow.maxDistance = 60;\n * ```\n * @category scene\n * @standard\n */\nexport interface LightShadow {\n  /**\n   * World-space box a directional light's shadow covers, or `undefined` to fit the box to the\n   * scene's shadow casters\n   *\n   * The fitted box follows the scene, so `castShadow: true` alone gives a well-sized shadow; past\n   * 256 shadow casters, see {@link Light.fitShadowBounds}. A box you set is read each time the\n   * shadow redraws, so moving it, say to follow the player, costs nothing extra. Only surfaces\n   * inside the box are sure to get shadows from this light. Ignored when {@link LightShadow.cascades} is set.\n   * @example\n   * ```ts\n   * sun.shadow.bounds = Box.fromCenterSize(player.position, 30);\n   * ```\n   */\n  bounds: Box | undefined;\n  /**\n   * How many slices the camera's view is cut into, each with its own shadow map, from 1 to 4;\n   * `undefined` for a fixed box\n   *\n   * Directional lights only. More cascades keep distant shadows sharper, at the cost of drawing\n   * the shadow casters once per cascade. `1` follows the camera with one map.\n   * @example\n   * ```ts\n   * sun.shadow.cascades = isMobile ? 2 : 4;\n   * ```\n   */\n  cascades: 1 | 2 | 3 | 4 | undefined;\n  /**\n   * How often the shadow redraws\n   *\n   * `1` redraws every frame and `N` every Nth frame. `'manual'`, or `0`, draws once, then again\n   * each time {@link Light.refreshShadows} asks. With cascades, an array gives each cascade its own\n   * rate, and a cascade the array leaves out redraws every frame. Slower rates suit a scene that\n   * doesn't move.\n   * @example\n   * ```ts\n   * sun.shadow.update = [1, 2, 8];\n   * ```\n   */\n  update: number | number[] | 'manual';\n  /**\n   * How far from the camera the cascades reach, in world units, or `undefined` for 50\n   *\n   * Cascades only. They never reach past the camera's far plane, so the\n   * {@link Camera3D.far | far} value caps this. A shorter reach gives sharper shadows.\n   * @example\n   * ```ts\n   * sun.shadow.maxDistance = 30;\n   * ```\n   */\n  maxDistance: number | undefined;\n  /**\n   * How the distance is shared out between cascades, from `0` to `1`\n   *\n   * `0` gives every cascade an equal slice. `1` gives the nearest cascades the thinnest slices,\n   * so the shadows closest to the camera get the most detail. Cascades only.\n   * @example\n   * ```ts\n   * sun.shadow.lambda = 0.8;\n   * ```\n   */\n  lambda: number;\n  /**\n   * Depth offset that keeps a surface from shadowing itself, or `undefined` for 0.001\n   *\n   * It is a fraction of the shadow map's depth range. Raise it if lit surfaces show stripes of\n   * shadow (shadow acne); too much makes shadows start away from their casters.\n   * @example\n   * ```ts\n   * sun.shadow.bias = 0.002;\n   * ```\n   */\n  bias: number | undefined;\n  /**\n   * Offset along the surface normal that keeps a surface from shadowing itself, in world units,\n   * or `undefined` for the default\n   *\n   * A surface the light only grazes moves this far along its normal before its shadow is\n   * looked up, and a surface facing the light barely moves. The default is three shadow-map\n   * texels for a directional light, so it follows the shadow's resolution, and 0.15 for a spot\n   * light. Raise it if shadowed surfaces show striping; lower it if shadows pull away from their\n   * casters.\n   * @example\n   * ```ts\n   * sun.shadow.normalBias = 0.05;\n   * ```\n   */\n  normalBias: number | undefined;\n}\n\n/**\n * Constructor options common to every {@link Light}\n *\n * Each kind of light adds its own, such as {@link PointLightOptions.range}. The\n * {@link Container3DOptions} (`label`, `position`, `eventMode`, …) apply too.\n * @example\n * ```ts\n * const sun = new DirectionalLight({ color: 0xfff4e0, intensity: 3, castShadow: true, label: 'sun' });\n * ```\n * @category scene\n * @standard\n */\nexport interface LightOptions extends Container3DOptions {\n  /**\n   * Colour of the light, as any {@link ColorSource}; see {@link Light.color}\n   * @default 0xffffff\n   * @example\n   * ```ts\n   * const candle = new PointLight({ color: '#ffb46b', range: 3 });\n   * ```\n   */\n  color?: ColorSource;\n  /**\n   * Brightness; see {@link Light.intensity}\n   * @default 1\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ intensity: 3 });\n   * ```\n   */\n  intensity?: number;\n  /**\n   * Whether the light casts shadows; see {@link Light.castShadow}\n   * @default false\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true });\n   * ```\n   */\n  castShadow?: boolean;\n  /**\n   * Shadow settings, read only while `castShadow` is `true`; see {@link LightShadowOptions}\n   * @example\n   * ```ts\n   * const sun = new DirectionalLight({ castShadow: true, shadow: { cascades: 3 } });\n   * ```\n   */\n  shadow?: LightShadowOptions;\n}\n\n/** @internal */\nexport interface ShadowData {\n  inverseLightMatrix: Matrix4;\n  lightProjectionMatrix: Matrix4;\n  cascades?: CascadeSlot[];\n  targetVersion?: number;\n}\n\n/**\n * Base class for every light in the scene\n *\n * A light is a {@link Container3D}: position it, parent it and animate it like any other node.\n * Add it anywhere under {@link View3D.root | view.root} and it lights the view; hide it to switch\n * it off. Lights face local **-Z**, like a {@link Camera3D}, so `light.lookAt(target)` aims it.\n *\n * Create one of the four kinds:\n *\n * - {@link AmbientLight}: the same light on every surface, whatever its direction.\n * - {@link DirectionalLight}: parallel rays from one direction, like the sun. Casts shadows.\n * - {@link PointLight}: light in every direction from a point, like a bulb.\n * - {@link SpotLight}: a cone of light from a point, like a torch. Casts shadows.\n *\n * A view draws up to 32 point, spot and directional lights and ignores the rest. Shadows share\n * 16 shadow maps: one per spot light or uncascaded sun, and one per cascade of a cascaded sun.\n * A shadow-casting light that doesn't fit draws without a shadow, and a warning says so.\n * @example\n * ```ts\n * import { View3D, DirectionalLight, AmbientLight } from '@pixi/3d';\n *\n * const view = new View3D({ width: 800, height: 600 });\n *\n * // Sun with a shadow fitted to the scene.\n * const sun = new DirectionalLight({ intensity: 3, castShadow: true });\n * sun.position.set(5, 10, 5);\n * sun.lookAt({ x: 0, y: 0, z: 0 });\n * view.root.addChild(sun);\n *\n * // Cheap fill so shadowed areas aren't pitch black.\n * view.root.addChild(new AmbientLight({ intensity: 0.3 }));\n * ```\n * @category scene\n * @standard\n */\nexport abstract class Light extends Container3D {\n  /** Which kind of light this is; each subclass sets it */\n  public abstract readonly type: LightType;\n\n  /**\n   * Colour of the light, multiplied by {@link Light.intensity}\n   *\n   * Assign any {@link ColorSource}, in display (sRGB) space as everywhere in pixi, or change the\n   * returned `Color` in place.\n   * @default 0xffffff\n   * @example\n   * ```ts\n   * sun.color = 0xff9a4d;\n   * sun.color.setValue('#ffd8a8');\n   * ```\n   */\n  public get color(): Color {\n    return this._color;\n  }\n\n  /**\n   * Sets the colour, copying the value into the light's own `Color`\n   * @param value - Any colour pixi accepts.\n   */\n  public set color(value: ColorSource) {\n    this._color.setValue(value);\n  }\n\n  /**\n   * Brightness, multiplied into {@link Light.color}\n   *\n   * Values above 1 are fine. A point or spot light dims with the square of the distance, so it\n   * needs a higher intensity than a directional light to look as bright. Lit colour brighter than 1\n   * clips under the default {@link View3D#toneMapping | toneMapping}; a filmic curve such as\n   * `'aces'` rolls it off instead.\n   * @default 1, or 0.5 on an `AmbientLight`\n   * @example\n   * ```ts\n   * lamp.intensity = flicker ? 6 : 8;\n   * ```\n   */\n  public intensity = 0;\n\n  /**\n   * Whether this light casts shadows; only directional and spot lights can\n   *\n   * The first light in a view to cast a shadow makes the view recompile its lit materials, once;\n   * later toggles recompile nothing.\n   * @default false\n   * @example\n   * ```ts\n   * torch.castShadow = settings.shadows;\n   * ```\n   * @see {@link Light.shadow} For per-light shadow tuning.\n   * @see {@link View3DOptions} For `shadowQuality`, which sets the shadow-map resolution.\n   */\n  public castShadow = false;\n\n  /**\n   * Whether this light casts shadows: {@link Light.castShadow | castShadow} is on and its kind\n   * can cast\n   *\n   * Point and ambient lights never do, whatever `castShadow` says.\n   * @example\n   * ```ts\n   * const shadowCasters = view.lights.filter((light: Light) => light.canCastShadow);\n   * ```\n   */\n  get canCastShadow(): boolean {\n    return this.castShadow;\n  }\n\n  /**\n   * This light's shadow settings; see {@link LightShadow}\n   *\n   * Change a field at any time and the shadow's next redraw uses it.\n   * @example\n   * ```ts\n   * sun.shadow.bias = 0.002;\n   * ```\n   */\n  public shadow: LightShadow;\n\n  /** @internal */\n  protected override _lookAtForwardIsPositiveZ = false;\n\n  private readonly _color: Color;\n\n  /** @internal */\n  public _gpuShadowData: ShadowData | null = null;\n\n  /** @internal */\n  public _shadowDataIndex: number = -1;\n\n  /** @internal */\n  public _shadowRefreshRequested = true;\n\n  /** @internal */\n  public _autoShadowBounds: Box | null = null;\n\n  /** @internal */\n  public _autoShadowBoundsFrozen = false;\n\n  constructor(options: LightOptions) {\n    const { color, intensity, castShadow, shadow: s, ...rest } = options;\n\n    super(rest);\n\n    this._color = new Color(color);\n    this.intensity = intensity ?? 1;\n    this.castShadow = castShadow ?? false;\n\n    this.shadow = {\n      bounds: undefined,\n      cascades: undefined,\n      update: 1,\n      maxDistance: undefined,\n      lambda: 0.5,\n      bias: undefined,\n      normalBias: undefined,\n    };\n\n    if (s) {\n      if (s.bounds !== undefined) this.shadow.bounds = s.bounds;\n      if (s.cascades !== undefined) this.shadow.cascades = s.cascades;\n      if (s.update !== undefined) this.shadow.update = s.update;\n      if (s.maxDistance !== undefined) this.shadow.maxDistance = s.maxDistance;\n      if (s.lambda !== undefined) this.shadow.lambda = s.lambda;\n      if (s.bias !== undefined) this.shadow.bias = s.bias;\n      if (s.normalBias !== undefined) this.shadow.normalBias = s.normalBias;\n    }\n  }\n\n  /**\n   * Redraws this light's shadow on the next frame, whatever its {@link LightShadow.update} rate\n   *\n   * With `update: 'manual'`, call it after each change the shadow should show. With a slower rate,\n   * call it after a change that shouldn't wait for the next scheduled redraw.\n   * @example\n   * ```ts\n   * sun.shadow.update = 'manual';\n   * // ...later, after the scene changes:\n   * sun.refreshShadows();\n   * ```\n   */\n  public refreshShadows(): void {\n    this._shadowRefreshRequested = true;\n  }\n\n  /**\n   * Measures the scene again for the fitted shadow box on the next frame, then redraws the shadow\n   *\n   * A view with 256 shadow casters or fewer never needs this: the box is measured each time the\n   * shadow redraws.\n   * Past 256 it is measured once and kept, so call this after moving or spawning casters outside\n   * the box. Instances of a `BatchedMesh3D` count one each. For a cascaded light, a spot light,\n   * or a light with its own {@link LightShadow.bounds | bounds}, it only redraws the shadow, like\n   * {@link Light.refreshShadows}.\n   * @example\n   * ```ts\n   * spawnCity(); // 50k instanced casters: the fitted box was measured once and kept\n   * sun.fitShadowBounds(); // measure again so the new content is inside the box\n   * ```\n   */\n  public fitShadowBounds(): void {\n    this._autoShadowBoundsFrozen = false;\n    this._shadowRefreshRequested = true;\n  }\n\n  /** @internal */\n  public _releaseShadowState(): void {\n    if (!this._gpuShadowData) return;\n\n    releaseShadowCascades(this._gpuShadowData);\n    this._gpuShadowData = null;\n  }\n\n  /**\n   * Removes the light from the scene and frees its shadow's GPU data\n   *\n   * Calling it again does nothing.\n   * @example\n   * ```ts\n   * torch.destroy();\n   * ```\n   * @param options - Forwarded to {@link Container3D.destroy}.\n   */\n  public override destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n\n    this._releaseShadowState();\n\n    this._shadowDataIndex = -1;\n    this._shadowRefreshRequested = false;\n    this._autoShadowBounds = null;\n    this._autoShadowBoundsFrozen = false;\n\n    super.destroy(options);\n  }\n}\n","import { definedProps } from 'pixi.js';\n\nimport { Light } from './Light';\nimport type { LightOptions } from './Light';\n\n/**\n * Constructor options for {@link AmbientLight}\n *\n * The {@link LightOptions} without the shadow fields: ambient light casts no shadows.\n * @example\n * ```ts\n * const fill = new AmbientLight({ color: 0xffffff, intensity: 0.3, label: 'fill' });\n * ```\n * @category scene\n * @standard\n */\nexport interface AmbientLightOptions extends Omit<LightOptions, 'castShadow' | 'shadow'> {\n  /**\n   * Brightness; see {@link Light.intensity}\n   * @default 0.5\n   * @example\n   * ```ts\n   * const fill = new AmbientLight({ intensity: 0.2 });\n   * ```\n   */\n  intensity?: number;\n}\n\n/**\n * Light that reaches every surface equally, whatever its position or direction\n *\n * It lifts shadowed areas off pure black for almost no cost. Several ambient lights add up.\n * It casts no shadows; `castShadow` is ignored. On a {@link Material3D} it lights only the\n * non-metal part, so a fully metallic surface gets nothing from it.\n * @example\n * ```ts\n * import { AmbientLight } from '@pixi/3d';\n *\n * view.root.addChild(new AmbientLight({ color: 0xffffff, intensity: 0.3 }));\n * ```\n * @see {@link Hemisphere} For sky and ground colours that vary with the way a surface faces.\n * @category scene\n * @standard\n */\nexport class AmbientLight extends Light {\n  /**\n   * Defaults for every new `AmbientLight`; an option passed as `undefined` keeps its default\n   * @example\n   * ```ts\n   * AmbientLight.defaultOptions.intensity = 0.2;\n   * ```\n   */\n  public static defaultOptions: AmbientLightOptions = {\n    color: 0xffffff,\n    intensity: 0.5,\n  };\n\n  /** Always `'ambient'` */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type = 'ambient';\n\n  /**\n   * Creates a new `AmbientLight`; add it under {@link View3D.root | view.root} to light the view\n   * @param options - Construction options; see {@link AmbientLightOptions}.\n   */\n  constructor(options: AmbientLightOptions = {}) {\n    super({ label: 'AmbientLight', ...AmbientLight.defaultOptions, ...definedProps(options) });\n  }\n\n  /**\n   * Always `false`: ambient light has no direction to cast along\n   * @advanced\n   */\n  override get canCastShadow(): boolean {\n    return false;\n  }\n}\n","import { definedProps } from 'pixi.js';\n\nimport { Light } from './Light';\nimport type { LightOptions } from './Light';\n\n/**\n * Constructor options for {@link DirectionalLight}, the same as {@link LightOptions}\n * @example\n * ```ts\n * const sun = new DirectionalLight({ intensity: 3, castShadow: true, shadow: { cascades: 3 } });\n * ```\n * @category scene\n * @standard\n */\nexport interface DirectionalLightOptions extends LightOptions {}\n\n/**\n * Light that arrives from one direction everywhere in the scene, like the sun\n *\n * The usual choice for a scene's main light.\n *\n * It shines along its local **-Z** axis, so only its rotation matters: moving it doesn't change\n * the lighting, and its shadow is fitted to the scene or to the camera wherever it sits. Aim it\n * with {@link Container3D.lookAt | lookAt} from any position.\n *\n * Its shadow covers one box over the scene by default. For a large world, turn on\n * {@link LightShadow.cascades | cascades}, which keep shadows near the camera sharp.\n * @example\n * ```ts\n * import { DirectionalLight } from '@pixi/3d';\n *\n * const sun = new DirectionalLight({\n *   color: 0xfff4e0,\n *   intensity: 3,\n *   castShadow: true,\n *   shadow: { cascades: 3, maxDistance: 25, lambda: 0.6 },\n * });\n * sun.position.set(10, 15, 5);\n * sun.lookAt({ x: 0, y: 0, z: 0 }); // local -Z faces origin\n * view.root.addChild(sun);\n * ```\n * @see {@link LightShadow} For shadow tuning fields (bounds, cascades, update, bias).\n * @category scene\n * @standard\n */\nexport class DirectionalLight extends Light {\n  /**\n   * Defaults for every new `DirectionalLight`; an option passed as `undefined` keeps its default\n   * @example\n   * ```ts\n   * DirectionalLight.defaultOptions.castShadow = true;\n   * ```\n   */\n  public static defaultOptions: DirectionalLightOptions = {\n    color: 0xffffff,\n    intensity: 1,\n    castShadow: false,\n  };\n\n  /** Always `'directional'` */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type = 'directional';\n\n  /**\n   * Creates a new `DirectionalLight`; add it under {@link View3D.root | view.root} to light the view\n   * @param options - Construction options; see {@link DirectionalLightOptions}.\n   */\n  constructor(options: DirectionalLightOptions = {}) {\n    super({ label: 'DirectionalLight', ...DirectionalLight.defaultOptions, ...definedProps(options) });\n  }\n}\n","import { definedProps, warn } from 'pixi.js';\n\nimport { Light } from './Light';\nimport type { LightOptions } from './Light';\n\n/**\n * Constructor options for {@link PointLight}: the {@link LightOptions} plus a\n * {@link PointLightOptions.range | range} and a {@link PointLightOptions.radius | radius}\n * @example\n * ```ts\n * const options: PointLightOptions = { color: 0xffd180, intensity: 8, range: 12, radius: 0.25 };\n * const lamp = new PointLight(options);\n * ```\n * @category scene\n * @standard\n */\nexport interface PointLightOptions extends LightOptions {\n  /**\n   * Distance the light reaches, in world units; see {@link PointLight.range}\n   * @default 0\n   * @example\n   * ```ts\n   * const candle = new PointLight({ intensity: 2, range: 3 });\n   * ```\n   */\n  range?: number;\n  /**\n   * Radius of the light's bulb, in world units; see {@link PointLight.radius}\n   * @default 0.1\n   * @example\n   * ```ts\n   * const lantern = new PointLight({ intensity: 4, range: 6, radius: 0.6 });\n   * ```\n   */\n  radius?: number;\n}\n\n/**\n * Light that shines equally in every direction from a point, like a bulb\n *\n * It dims with the square of the distance, fading smoothly to nothing at its\n * {@link PointLight.range | range} when it has one. Only its position matters; rotating it\n * changes nothing. Point lights cast no shadows.\n * @example\n * ```ts\n * import { PointLight } from '@pixi/3d';\n *\n * const lamp = new PointLight({ color: 0xffd180, intensity: 8, range: 12 });\n * lamp.position.set(0, 2, 0);\n * view.root.addChild(lamp);\n * ```\n * @see {@link SpotLight} For a directional cone alternative.\n * @category scene\n * @standard\n */\nexport class PointLight extends Light {\n  /**\n   * Defaults for every new `PointLight`; an option passed as `undefined` keeps its default\n   * @example\n   * ```ts\n   * PointLight.defaultOptions.range = 10;\n   * ```\n   */\n  public static defaultOptions: PointLightOptions = {\n    color: 0xffffff,\n    intensity: 1,\n    range: 0,\n    radius: 0.1,\n  };\n\n  /** Always `'point'` */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type = 'point';\n\n  /**\n   * Distance the light reaches, in world units, or `0` for no limit\n   *\n   * The light fades smoothly to nothing at this distance. Give lights a range when you can: one\n   * without is shaded on every pixel, one with only where it reaches, which matters with many lights.\n   * @default 0\n   * @example\n   * ```ts\n   * lamp.range = 12;\n   * ```\n   */\n  public range = 0;\n\n  /**\n   * Radius of the light's bulb, in world units\n   *\n   * A surface stops getting brighter once it's closer to the light than about this distance. Raise\n   * it past the light's distance from a surface to soften the hot spot there: for a lantern 0.3\n   * above the ground, try 0.6. Surfaces farther than about twice the radius barely change. Values\n   * under 0.01 act as 0.01.\n   * @default 0.1\n   * @example\n   * ```ts\n   * lamp.radius = 0.6;\n   * ```\n   */\n  public radius = 0.1;\n\n  /**\n   * Creates a new `PointLight`; add it under {@link View3D.root | view.root} to light the view\n   *\n   * Warns when `castShadow` is `true`, since point lights cast no shadows.\n   * @param options - Construction options; see {@link PointLightOptions}.\n   */\n  constructor(options: PointLightOptions = {}) {\n    const { range, radius, ...rest } = { ...PointLight.defaultOptions, ...definedProps(options) };\n\n    super({ label: 'PointLight', ...rest });\n\n    this.range = range!;\n    this.radius = radius!;\n\n    if (this.castShadow) {\n      warn('PointLight does not cast shadows; `castShadow` has no effect.');\n    }\n  }\n\n  /**\n   * Always `false`: point lights cast no shadows\n   * @advanced\n   */\n  override get canCastShadow(): boolean {\n    return false;\n  }\n}\n","import { definedProps } from 'pixi.js';\n\nimport { Light } from './Light';\nimport type { LightOptions } from './Light';\n\n/**\n * Constructor options for {@link SpotLight}: the {@link LightOptions} plus the cone's\n * {@link SpotLightOptions.range | range}, {@link SpotLightOptions.radius | radius},\n * {@link SpotLightOptions.coneAngle | coneAngle} and {@link SpotLightOptions.penumbra | penumbra}\n * @example\n * ```ts\n * const options: SpotLightOptions = { intensity: 10, range: 25, coneAngle: 30, penumbra: 0.25 };\n * const flashlight = new SpotLight(options);\n * ```\n * @category scene\n * @standard\n */\nexport interface SpotLightOptions extends LightOptions {\n  /**\n   * Distance the light reaches, in world units; see {@link SpotLight.range}\n   * @default 0\n   * @example\n   * ```ts\n   * const streetLamp = new SpotLight({ intensity: 20, range: 8 });\n   * ```\n   */\n  range?: number;\n  /**\n   * Radius of the light's bulb, in world units; see {@link SpotLight.radius}\n   * @default 0.1\n   * @example\n   * ```ts\n   * const wallLamp = new SpotLight({ intensity: 6, range: 4, radius: 0.5 });\n   * ```\n   */\n  radius?: number;\n  /**\n   * Angle between the cone's axis and its edge, in degrees; see {@link SpotLight.coneAngle}\n   * @default 60\n   * @example\n   * ```ts\n   * const narrowBeam = new SpotLight({ coneAngle: 15 });\n   * ```\n   */\n  coneAngle?: number;\n  /**\n   * How soft the cone's edge is, from `0` to `1`; see {@link SpotLight.penumbra}\n   * @default 0\n   * @example\n   * ```ts\n   * const softSpot = new SpotLight({ coneAngle: 30, penumbra: 0.5 });\n   * ```\n   */\n  penumbra?: number;\n}\n\n/**\n * Light that shines in a cone from a point, like a torch or a stage light\n *\n * The cone points along the light's local **-Z** axis; aim it with\n * {@link Container3D.lookAt | lookAt}. Light stops at the cone's edge, softened by the\n * {@link SpotLight.penumbra | penumbra}, and dims with the square of the distance, fading to\n * nothing at the {@link SpotLight.range | range} when it has one.\n *\n * Its shadow is one perspective map that covers the cone from 1 world unit out to the range,\n * or out to 1000 with no range. Casters closer than 1 unit to the light cast no shadow. The\n * shadow needs a {@link SpotLight.coneAngle | coneAngle} under 90 degrees.\n * @example\n * ```ts\n * import { SpotLight } from '@pixi/3d';\n *\n * const flashlight = new SpotLight({\n *   color: 0xffffff,\n *   intensity: 10,\n *   range: 25,\n *   coneAngle: 30,   // 30° half-angle (60° cone)\n *   penumbra: 0.25,  // soft edge over the outer quarter\n *   castShadow: true,\n * });\n * flashlight.position.set(0, 3, 5);\n * flashlight.lookAt({ x: 0, y: 0, z: 0 });\n * view.root.addChild(flashlight);\n * ```\n * @see {@link PointLight} For the omnidirectional alternative.\n * @category scene\n * @standard\n */\nexport class SpotLight extends Light {\n  /**\n   * Defaults for every new `SpotLight`; an option passed as `undefined` keeps its default\n   * @example\n   * ```ts\n   * SpotLight.defaultOptions.penumbra = 0.2;\n   * ```\n   */\n  public static defaultOptions: SpotLightOptions = {\n    color: 0xffffff,\n    intensity: 1,\n    castShadow: false,\n    range: 0,\n    radius: 0.1,\n    coneAngle: 60,\n    penumbra: 0,\n  };\n\n  /** Always `'spot'` */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only discriminant\n  public readonly type = 'spot';\n\n  /**\n   * Distance the light reaches, in world units, or `0` for no limit\n   *\n   * Works as {@link PointLight.range} does, and also sets how far the shadow reaches.\n   * @default 0\n   * @example\n   * ```ts\n   * flashlight.range = 25;\n   * ```\n   */\n  public range = 0;\n\n  /**\n   * Radius of the light's bulb, in world units\n   *\n   * Works as {@link PointLight.radius} does; it doesn't soften the shadow.\n   * @default 0.1\n   * @example\n   * ```ts\n   * flashlight.radius = 0.5;\n   * ```\n   */\n  public radius = 0.1;\n\n  /**\n   * Angle between the cone's axis and its edge, in degrees, so the cone is twice as wide\n   * @example\n   * ```ts\n   * spot.coneAngle = 30; // a 60° cone\n   * ```\n   * @default 60\n   */\n  public coneAngle = 0;\n\n  /**\n   * How soft the cone's edge is, as a fraction of {@link SpotLight.coneAngle | coneAngle}\n   *\n   * The light is at full strength out to `coneAngle * (1 - penumbra)` and fades to nothing at\n   * `coneAngle`. `0` gives a hard edge; `1` fades all the way from the axis.\n   * @default 0\n   * @example\n   * ```ts\n   * flashlight.penumbra = 0.25;\n   * ```\n   */\n  public penumbra = 0;\n\n  /**\n   * Creates a new `SpotLight`; add it under {@link View3D.root | view.root} to light the view\n   * @param options - Construction options; see {@link SpotLightOptions}.\n   */\n  constructor(options: SpotLightOptions = {}) {\n    const { range, radius, coneAngle, penumbra, ...rest } = { ...SpotLight.defaultOptions, ...definedProps(options) };\n\n    super({ label: 'SpotLight', ...rest });\n\n    this.range = range!;\n    this.radius = radius!;\n    this.coneAngle = coneAngle!;\n    this.penumbra = penumbra!;\n  }\n}\n","import { definedProps } from 'pixi.js';\n\nimport { BONE_MATRIX_FLOATS } from '../core/buffers/BonePit';\nimport { Matrix4 } from '../math/matrix/Matrix4';\nimport type { Container3D } from './Container3D';\n\nconst _bindShape = new Matrix4();\n\nlet nextWorldId = 0;\n\n/**\n * Constructor options for {@link Skeleton}\n *\n * A {@link Model3D} builds its skeletons from the file's skins, so you only need these to rig a\n * mesh in code. Nodes are numbered from 0.\n * @example\n * ```ts\n * const inverseBindMatrices = new Float32Array(32);\n *\n * inverseBindMatrices.set(new Matrix4().elements, 0);\n * inverseBindMatrices.set(new Matrix4().makeTranslation(0, -1, 0).elements, 16);\n *\n * const options: SkeletonOptions = {\n *   parent: new Int16Array([-1, 0]),\n *   joints: new Int16Array([0, 1]),\n *   inverseBindMatrices,\n *   labels: ['base', 'tip'],\n * };\n * ```\n * @category scene\n * @standard\n */\nexport interface SkeletonOptions {\n  /**\n   * Parent of each node, as a node index, or `-1` for a root; its length is the node count\n   *\n   * A parent must come before its children.\n   * @example\n   * ```ts\n   * const chain = new Skeleton({ parent: new Int16Array([-1, 0, 1]), joints, inverseBindMatrices });\n   * ```\n   */\n  parent: Int16Array;\n  /**\n   * The nodes that are joints, as node indices; its length is the joint count\n   *\n   * A skinned geometry's `joints` attribute indexes this list, not the nodes, as glTF's `JOINTS_0`\n   * does. Nodes left out only carry the joints below them.\n   * @example\n   * ```ts\n   * const arm = new Skeleton({\n   *   parent: new Int16Array([-1, 0, 1]),\n   *   joints: new Int16Array([1, 2]),\n   *   inverseBindMatrices,\n   * });\n   * ```\n   */\n  joints: Int16Array;\n  /**\n   * One column-major 4x4 matrix per joint, in `joints` order, taking a vertex from the bind pose\n   * into the joint's space\n   * @example\n   * ```ts\n   * const inverseBindMatrices = new Float32Array(32);\n   *\n   * inverseBindMatrices.set(new Matrix4().elements, 0);\n   * inverseBindMatrices.set(new Matrix4().makeTranslation(0, -1, 0).elements, 16);\n   * ```\n   */\n  inverseBindMatrices: Float32Array;\n  /**\n   * A label for each node, in node order, so {@link Skeleton#indexOf | indexOf} can find it\n   * @example\n   * ```ts\n   * const tail = new Skeleton({ parent, joints, inverseBindMatrices, labels: ['base', 'tip'] });\n   * const tip = tail.indexOf('tip');\n   * ```\n   */\n  labels?: string[];\n  /**\n   * The transform the skinned mesh was bound at, as a column-major 4x4 matrix; the identity when\n   * left out\n   *\n   * Give the mesh the same transform: its bounds then measure the bind pose, and the bone matrices\n   * cancel it, so the skin still draws where the joints put it. It must be a position, rotation and\n   * scale with no shear. A {@link Model3D} works it out from the file.\n   * @example\n   * ```ts\n   * mesh.scale.set(100, 100, 100);\n   * mesh.updateLocalTransform();\n   *\n   * const skeleton = new Skeleton({\n   *   parent,\n   *   joints,\n   *   inverseBindMatrices,\n   *   bindShapeMatrix: mesh.localTransform.toArray(),\n   * });\n   * ```\n   * @advanced\n   */\n  bindShapeMatrix?: Float32Array;\n}\n\n/**\n * The bones of a skinned {@link Mesh3D}, and their pose\n *\n * A {@link Model3D} builds one per skin in its file and gives it to every mesh that skin deforms,\n * so you rarely build one yourself. The bones are numbered nodes: the joints that deform the mesh,\n * plus the nodes above them. Each node's local position, rotation and scale sit in the flat arrays\n * {@link Skeleton#localPosition | localPosition}, {@link Skeleton#localRotation | localRotation}\n * and {@link Skeleton#localScale | localScale}.\n *\n * To pose a bone, write into those arrays and set {@link Skeleton#dirty | dirty}, or call\n * {@link Skeleton#setLocalTRS | setLocalTRS}, which does both. In a {@link Model3D}, a bone with a\n * mesh under it, such as a hand holding a sword, is also one of the model's nodes and follows that\n * node, so move the node instead. The view recomputes a dirty\n * skeleton's matrices before it draws. A playing animation rewrites the bones it drives on every\n * update, so a change you make to one of those lasts only until then.\n *\n * A skeleton from a {@link Model3D} shares its `parent`, `joints` and `inverseBindMatrices` with\n * every model built from the same source, so don't write into them. A skeleton holds no GPU memory.\n * @example\n * ```ts\n * const skeleton = robot.skeletons[0];\n * const head = skeleton.indexOf('Head');\n * const half = Math.PI / 12;\n *\n * // Set the head's local rotation to 30 degrees around Y.\n * skeleton.localRotation.set([0, Math.sin(half), 0, Math.cos(half)], head * 4);\n * skeleton.dirty = true;\n * ```\n * @see {@link SkeletonOptions} For constructor options.\n * @category scene\n * @standard\n */\nexport class Skeleton {\n  /**\n   * Defaults for every new `Skeleton`, empty to start; an option passed as `undefined` keeps its\n   * default\n   * @advanced\n   */\n  public static defaultOptions: Partial<SkeletonOptions> = {};\n\n  /** Number of nodes: the joints plus the nodes above them */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only state\n  public readonly nodeCount: number = 0;\n  /** Number of joints, the nodes that deform the mesh */\n  // oxlint-disable-next-line pixijs-3d/require-standard-example -- read-only state\n  public readonly jointCount: number = 0;\n\n  /**\n   * Parent of each node, as a node index, or `-1` for a root\n   * @example\n   * ```ts\n   * const shoulder = skeleton.parent[skeleton.indexOf('UpperArm')];\n   * ```\n   */\n  public readonly parent: Int16Array;\n  /**\n   * The node index of each joint\n   * @example\n   * ```ts\n   * const handJoint = skeleton.joints.indexOf(skeleton.indexOf('Hand'));\n   * ```\n   */\n  public readonly joints: Int16Array;\n\n  /**\n   * One column-major 4x4 matrix per joint, taking a vertex from the bind pose into the joint's space\n   * @advanced\n   */\n  public readonly inverseBindMatrices: Float32Array;\n\n  /**\n   * Local position of each node, three floats per node: `x, y, z`\n   * @example\n   * ```ts\n   * const hips = skeleton.indexOf('Hips') * 3;\n   *\n   * skeleton.localPosition[hips + 1] -= 0.2;\n   * skeleton.dirty = true;\n   * ```\n   */\n  public readonly localPosition: Float32Array;\n  /**\n   * Local rotation of each node, a four-float quaternion per node: `x, y, z, w`\n   * @example\n   * ```ts\n   * const jaw = skeleton.indexOf('Jaw') * 4;\n   *\n   * skeleton.localRotation.set([Math.sin(open / 2), 0, 0, Math.cos(open / 2)], jaw);\n   * skeleton.dirty = true;\n   * ```\n   */\n  public readonly localRotation: Float32Array;\n  /**\n   * Local scale of each node, three floats per node: `x, y, z`\n   *\n   * A scale that differs between axes skews the lighting of the skin it moves, since the skin's\n   * normals aren't corrected for it.\n   * @example\n   * ```ts\n   * const head = skeleton.indexOf('Head') * 3;\n   *\n   * skeleton.localScale.fill(1.5, head, head + 3);\n   * skeleton.dirty = true;\n   * ```\n   */\n  public readonly localScale: Float32Array;\n\n  /**\n   * The skinning matrix of each joint, in joint order: its posed matrix times its inverse bind\n   *\n   * Each is three rows of four floats, row-major, without the bottom row, which is always\n   * `0, 0, 0, 1`. {@link Skeleton#updateWorld | updateWorld} fills it, and the view uploads it only\n   * after a fill, so pose the local arrays rather than writing this.\n   * @advanced\n   */\n  public readonly worldMatrix: Float32Array;\n\n  /**\n   * Whether the local pose changed since the last {@link Skeleton#updateWorld | updateWorld}\n   *\n   * Set it after writing into the local arrays; {@link Skeleton#setLocalTRS | setLocalTRS} and\n   * animations set it for you. While it's `false`, the view skips recomputing the matrices.\n   * @example\n   * ```ts\n   * skeleton.localScale.fill(1.5, head * 3, head * 3 + 3);\n   * skeleton.dirty = true;\n   * ```\n   */\n  public dirty = true;\n\n  /**\n   * Base of this skeleton's matrices in the drawing view's bone pit; `-1` until first drawn\n   * @internal\n   */\n  public _bonePitIndex = -1;\n  /**\n   * The bone pit tick of its last `BonePit.add`, so a skeleton several meshes share is copied once a frame\n   * @internal\n   */\n  public _bonePitTick = -1;\n  /**\n   * Renewed from one counter shared by every skeleton whenever `worldMatrix` changes, so `BonePit`\n   * can match a slot's matrices without holding the skeleton\n   * @internal\n   */\n  public _worldId = ++nextWorldId;\n\n  private _destroyed = false;\n\n  private readonly _labelToIndex!: Record<string, number>;\n\n  private readonly _bindShapeInverse?: Float32Array;\n  private readonly _nodeWorldMatrix: Float32Array;\n\n  /**\n   * `updateWorld` checks it's non-empty before calling `_syncContainerBones`, which V8 won't inline\n   * @internal\n   */\n  private readonly _containerBones: { boneIndex: number; src: Container3D }[] = [];\n\n  /**\n   * Creates a skeleton with every node at the identity pose: no translation or rotation, and a\n   * scale of 1\n   * @param options - Construction options; see {@link SkeletonOptions}.\n   */\n  constructor(options: SkeletonOptions) {\n    options = { ...Skeleton.defaultOptions, ...definedProps(options) };\n\n    const { parent, joints, inverseBindMatrices, labels, bindShapeMatrix } = options;\n\n    this.nodeCount = parent.length;\n    this.jointCount = joints.length;\n\n    this.parent = parent;\n    this.joints = joints;\n    this.inverseBindMatrices = inverseBindMatrices;\n\n    this.localPosition = new Float32Array(this.nodeCount * 3);\n    this.localRotation = new Float32Array(this.nodeCount * 4);\n    this.localScale = new Float32Array(this.nodeCount * 3);\n\n    this._nodeWorldMatrix = new Float32Array(this.nodeCount * 16);\n    this.worldMatrix = new Float32Array(this.jointCount * BONE_MATRIX_FLOATS);\n\n    for (let i = 0; i < this.nodeCount; i++) {\n      this.localRotation[i * 4 + 3] = 1;\n      this.localScale[i * 3 + 0] = 1;\n      this.localScale[i * 3 + 1] = 1;\n      this.localScale[i * 3 + 2] = 1;\n\n      const m = i * 16;\n      this._nodeWorldMatrix[m + 0] = 1;\n      this._nodeWorldMatrix[m + 5] = 1;\n      this._nodeWorldMatrix[m + 10] = 1;\n      this._nodeWorldMatrix[m + 15] = 1;\n    }\n\n    if (labels) {\n      this._labelToIndex = Object.create(null);\n      for (let i = 0; i < labels.length; i++) this._labelToIndex[labels[i]] = i;\n    }\n\n    if (bindShapeMatrix) {\n      _bindShape.fromArray(bindShapeMatrix).getInverse(_bindShape, true);\n      this._bindShapeInverse = new Float32Array(_bindShape.elements);\n    }\n  }\n\n  /**\n   * Returns the index of the node with a label\n   *\n   * A {@link Model3D} labels each node with its name in the file, or `node_<n>` for an unnamed\n   * one, where `n` is the node's index in the file.\n   * @example\n   * ```ts\n   * const head = skeleton.indexOf('Head');\n   * ```\n   * @param label - Node label to look up\n   * @returns The node index for `label`\n   * @throws {Error} When no node has `label`, or the skeleton was built without `labels`.\n   */\n  public indexOf(label: string): number {\n    const idx = this._labelToIndex[label];\n    if (idx === undefined) throw new Error(`Unknown bone label: ${label}`);\n    return idx;\n  }\n\n  /**\n   * Sets a node's local position, rotation and scale, and marks the skeleton dirty\n   *\n   * Scale defaults to 1 on each axis, so leaving it out resets any scale the node had. The\n   * rotation is used as given, without normalizing, so pass a unit quaternion.\n   * @example\n   * ```ts\n   * const tip = tail.indexOf('tip');\n   *\n   * tail.setLocalTRS(tip, 0, 1, 0, 0, 0, Math.sin(bend / 2), Math.cos(bend / 2));\n   * ```\n   * @param i - Node index; {@link Skeleton#indexOf | indexOf} finds it from a label\n   * @param tx - Translation X\n   * @param ty - Translation Y\n   * @param tz - Translation Z\n   * @param qx - Rotation quaternion X\n   * @param qy - Rotation quaternion Y\n   * @param qz - Rotation quaternion Z\n   * @param qw - Rotation quaternion W\n   * @param sx - Scale X\n   * @param sy - Scale Y\n   * @param sz - Scale Z\n   */\n  public setLocalTRS(\n    i: number,\n    tx: number,\n    ty: number,\n    tz: number,\n    qx: number,\n    qy: number,\n    qz: number,\n    qw: number,\n    sx = 1,\n    sy = 1,\n    sz = 1,\n  ): void {\n    const p = i * 3;\n    this.localPosition[p + 0] = tx;\n    this.localPosition[p + 1] = ty;\n    this.localPosition[p + 2] = tz;\n\n    const r = i * 4;\n    this.localRotation[r + 0] = qx;\n    this.localRotation[r + 1] = qy;\n    this.localRotation[r + 2] = qz;\n    this.localRotation[r + 3] = qw;\n\n    const s = i * 3;\n    this.localScale[s + 0] = sx;\n    this.localScale[s + 1] = sy;\n    this.localScale[s + 2] = sz;\n\n    this.dirty = true;\n  }\n\n  /**\n   * Recomputes {@link Skeleton#worldMatrix | worldMatrix} from the local pose, if the skeleton is\n   * dirty\n   *\n   * The view calls it every frame for each skeleton it draws, so call it yourself only to read\n   * `worldMatrix` before the next render. Bones bound with\n   * {@link Skeleton#bindContainerBone | bindContainerBone} copy their containers' transforms\n   * first, which can make the skeleton dirty.\n   * @advanced\n   */\n  public updateWorld(): void {\n    if (this._containerBones.length !== 0) this._syncContainerBones();\n\n    if (!this.dirty) return;\n\n    for (let i = 0; i < this.nodeCount; i++) {\n      const parentIndex = this.parent[i];\n\n      this._writeTRSToMat4(i, this._nodeWorldMatrix);\n\n      if (parentIndex >= 0) {\n        Matrix4.multiplyAffine(\n          this._nodeWorldMatrix,\n          i * 16,\n          this._nodeWorldMatrix,\n          parentIndex * 16,\n          this._nodeWorldMatrix,\n          i * 16,\n        );\n      } else if (this._bindShapeInverse !== undefined) {\n        Matrix4.multiplyAffine(this._nodeWorldMatrix, i * 16, this._bindShapeInverse, 0, this._nodeWorldMatrix, i * 16);\n      }\n    }\n\n    for (let j = 0; j < this.jointCount; j++) {\n      const nodeIndex = this.joints[j];\n\n      Matrix4.multiplyAffineTo3x4(\n        this.worldMatrix,\n        j * BONE_MATRIX_FLOATS,\n        this._nodeWorldMatrix,\n        nodeIndex * 16,\n        this.inverseBindMatrices,\n        j * 16,\n      );\n    }\n\n    this._worldId = ++nextWorldId;\n    this.dirty = false;\n  }\n\n  /**\n   * Makes a node follow a scene-graph container's local position, rotation and scale\n   *\n   * A {@link Model3D} does this for a node above the joints that also holds meshes, so moving or\n   * animating that container moves the skin. The node follows until the skeleton is destroyed.\n   * @example\n   * ```ts\n   * skeleton.bindContainerBone(skeleton.indexOf('Armature'), armature);\n   * ```\n   * @param boneIndex - Index of the node that follows `src`\n   * @param src - The container to follow\n   * @advanced\n   */\n  public bindContainerBone(boneIndex: number, src: Container3D): void {\n    this._containerBones.push({ boneIndex, src });\n  }\n\n  /**\n   * Reads translation from the local matrix, rebuilt if stale since the transform pass skips hidden nodes, so an\n   * `origin` reaches the skin; compares through `Math.fround`, as a float64 such as 0.1 never equals its float32 copy\n   */\n  private _syncContainerBones(): void {\n    const bones = this._containerBones;\n\n    for (let k = 0; k < bones.length; k++) {\n      const { boneIndex, src } = bones[k];\n\n      if (src._localTransformDirty) {\n        src.updateLocalTransform();\n        src._localTransformDirty = false;\n      }\n\n      const t = src.localTransform.elements;\n      const q = src.quaternion;\n      const s = src.scale;\n      const pi = boneIndex * 3;\n      const ri = boneIndex * 4;\n      const lp = this.localPosition;\n      const lr = this.localRotation;\n      const ls = this.localScale;\n\n      if (\n        lp[pi] !== t[12] ||\n        lp[pi + 1] !== t[13] ||\n        lp[pi + 2] !== t[14] ||\n        lr[ri] !== Math.fround(q.x) ||\n        lr[ri + 1] !== Math.fround(q.y) ||\n        lr[ri + 2] !== Math.fround(q.z) ||\n        lr[ri + 3] !== Math.fround(q.w) ||\n        ls[pi] !== Math.fround(s.x) ||\n        ls[pi + 1] !== Math.fround(s.y) ||\n        ls[pi + 2] !== Math.fround(s.z)\n      ) {\n        lp[pi] = t[12];\n        lp[pi + 1] = t[13];\n        lp[pi + 2] = t[14];\n        lr[ri] = q.x;\n        lr[ri + 1] = q.y;\n        lr[ri + 2] = q.z;\n        lr[ri + 3] = q.w;\n        ls[pi] = s.x;\n        ls[pi + 1] = s.y;\n        ls[pi + 2] = s.z;\n        this.dirty = true;\n      }\n    }\n  }\n\n  /**\n   * Stops the nodes following their containers, without destroying the containers\n   *\n   * A {@link Model3D} destroys its own skeletons. Calling it again does nothing.\n   * @example\n   * ```ts\n   * tailMesh.destroy();\n   * tail.destroy();\n   * ```\n   */\n  public destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n\n    // oxlint-disable-next-line pixijs-3d/destroy-release -- skinned meshes kept from a destroyed Model3D still draw, and updateWorld reads this list every frame\n    this._containerBones.length = 0;\n\n    this._bonePitIndex = -1;\n    this._bonePitTick = -1;\n  }\n\n  /**\n   * Expands the quaternion inline, so no intermediate matrix is made\n   * @internal\n   */\n  private _writeTRSToMat4(i: number, outMat: Float32Array): void {\n    const p = i * 3;\n    const r = i * 4;\n    const s = i * 3;\n    const m = i * 16;\n\n    const tx = this.localPosition[p + 0];\n    const ty = this.localPosition[p + 1];\n    const tz = this.localPosition[p + 2];\n\n    const x = this.localRotation[r + 0];\n    const y = this.localRotation[r + 1];\n    const z = this.localRotation[r + 2];\n    const w = this.localRotation[r + 3];\n\n    const sx = this.localScale[s + 0];\n    const sy = this.localScale[s + 1];\n    const sz = this.localScale[s + 2];\n\n    const x2 = x + x;\n    const y2 = y + y;\n    const z2 = z + z;\n\n    const xx = x * x2;\n    const xy = x * y2;\n    const xz = x * z2;\n    const yy = y * y2;\n    const yz = y * z2;\n    const zz = z * z2;\n    const wx = w * x2;\n    const wy = w * y2;\n    const wz = w * z2;\n\n    outMat[m + 0] = (1 - (yy + zz)) * sx;\n    outMat[m + 1] = (xy + wz) * sx;\n    outMat[m + 2] = (xz - wy) * sx;\n    outMat[m + 3] = 0;\n\n    outMat[m + 4] = (xy - wz) * sy;\n    outMat[m + 5] = (1 - (xx + zz)) * sy;\n    outMat[m + 6] = (yz + wx) * sy;\n    outMat[m + 7] = 0;\n\n    outMat[m + 8] = (xz + wy) * sz;\n    outMat[m + 9] = (yz - wx) * sz;\n    outMat[m + 10] = (1 - (xx + yy)) * sz;\n    outMat[m + 11] = 0;\n\n    outMat[m + 12] = tx;\n    outMat[m + 13] = ty;\n    outMat[m + 14] = tz;\n    outMat[m + 15] = 1;\n  }\n}\n","import { definedProps } from 'pixi.js';\n\nimport { AnimationPlayer } from '../animation/AnimationPlayer';\nimport type { AnimationTarget } from '../animation/AnimationPlayer';\nimport type { Scene3DNode } from '../assets/Scene3DDescriptor';\nimport { Scene3DSource } from '../assets/Scene3DSource';\nimport type { Geometry3D } from '../geometry/Geometry3D';\nimport type { BaseMaterial3D } from '../materials/BaseMaterial3D';\nimport { Matrix4 } from '../math/matrix/Matrix4';\nimport { Quaternion } from '../math/rotation/Quaternion';\nimport { Vector3 } from '../math/vector/Vector3';\nimport type { Destroy3DOptions } from '../utils/Destroy3DOptions';\nimport { BatchedMesh3D } from './BatchedMesh3D';\nimport { Camera3D } from './cameras/Camera3D';\nimport { Container3D } from './Container3D';\nimport type { Container3DOptions } from './Container3D';\nimport { DirectionalLight } from './lights/DirectionalLight';\nimport { PointLight } from './lights/PointLight';\nimport { SpotLight } from './lights/SpotLight';\nimport { Mesh3D } from './Mesh3D';\nimport { Skeleton } from './Skeleton';\n\nconst _matrix = new Matrix4();\nconst _position = new Vector3();\nconst _quaternion = new Quaternion();\nconst _scale = new Vector3();\n\n/** Skips a nested `Model3D`, whose own `unload` already freed its materials during the walk */\nfunction collectMaterials(node: Container3D, out: Set<BaseMaterial3D>): void {\n  if (node instanceof Mesh3D) {\n    out.add(node.material);\n  } else if (node instanceof BatchedMesh3D) {\n    const items = node.batch.items;\n    for (let i = 0; i < items.length; i++) {\n      if (items[i].material) out.add(items[i].material);\n    }\n  }\n\n  const children = node.children;\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    if (!(child instanceof Model3D)) collectMaterials(child, out);\n  }\n}\n\ninterface ModelBuild {\n  nodeMap: Record<number, AnimationTarget>;\n  /**\n   * Each skinned mesh's glTF node index, mapped to its skin's parent node; one never drives a bone,\n   * since it holds the bind shape matrix in place of the node's pose\n   */\n  detachedSkinnedNodes: Map<number, number>;\n  castShadow?: boolean;\n  receiveShadow?: boolean;\n}\n\n/**\n * The materials a {@link Model3D} draws instead of its source's\n *\n * - A record, by material {@link BaseMaterial3D#label | label}: every source material with that\n *   label is replaced. The glTF loader labels materials with their names in the file.\n * - An array, by index into {@link Scene3DSource#materials}; an empty entry keeps the source's.\n * - A function, called once for each source material, returning the material to draw instead.\n * @example\n * ```ts\n * new Model3D({ source, materials: { Paint: redPaint } });\n * new Model3D({ source, materials: (material) => material.clone({ extraBits: [dissolveBit] }) });\n * ```\n * @category scene\n * @standard\n */\nexport type MaterialOverrides =\n  | Readonly<Record<string, BaseMaterial3D>>\n  | readonly (BaseMaterial3D | undefined)[]\n  | ((material: BaseMaterial3D) => BaseMaterial3D);\n\ninterface BuiltMesh {\n  mesh: Mesh3D;\n  /** Index into {@link Scene3DSource#materials} of the material it draws when nothing replaces it */\n  index: number;\n}\n\n/**\n * Each of `materials` with `overrides` applied\n *\n * A function runs once per distinct material, so a material listed at several indices gets one\n * replacement and its meshes keep sharing a batch.\n * @param materials - The source's materials\n * @param overrides - What replaces them\n * @returns One material per source index.\n */\nfunction applyMaterialOverrides(materials: readonly BaseMaterial3D[], overrides: MaterialOverrides): BaseMaterial3D[] {\n  if (typeof overrides === 'function') {\n    const replaced = new Map<BaseMaterial3D, BaseMaterial3D>();\n\n    return materials.map((material) => {\n      let replacement = replaced.get(material);\n      if (!replacement) replaced.set(material, (replacement = overrides(material)));\n\n      return replacement;\n    });\n  }\n\n  if (Array.isArray(overrides)) return materials.map((material, i) => overrides[i] ?? material);\n\n  const byLabel = overrides as Readonly<Record<string, BaseMaterial3D>>;\n\n  return materials.map((material) => (material.label !== undefined && byLabel[material.label]) || material);\n}\n\n/**\n * Options for building a {@link Model3D} from a shared {@link Scene3DSource}\n * @example\n * ```ts\n * const robot = new Model3D({\n *   source: await Assets.load<Scene3DSource>('robot.glb'),\n *   scene: 'Showroom',\n *   castShadow: false,\n *   label: 'robot',\n * });\n * ```\n * @category scene\n * @standard\n */\nexport interface Model3DOptions extends Container3DOptions {\n  /**\n   * The loaded file to build the model from\n   * @example\n   * ```ts\n   * const robot = new Model3D({ source: await Assets.load<Scene3DSource>('robot.glb') });\n   * ```\n   */\n  source: Scene3DSource;\n  /**\n   * Name of the scene to build, one of the keys of {@link Scene3DSource#scene}\n   *\n   * Left out, or a name the file doesn't have, it's the file's default scene, or its first when\n   * the file names no default.\n   * @example\n   * ```ts\n   * const showroom = new Model3D({ source, scene: 'Showroom' });\n   * ```\n   */\n  scene?: string;\n  /**\n   * Whether the model's meshes cast shadows\n   * @default true\n   * @example\n   * ```ts\n   * const grass = new Model3D({ source, castShadow: false });\n   * ```\n   */\n  castShadow?: boolean;\n  /**\n   * Whether the model's meshes receive shadows\n   * @default true\n   * @example\n   * ```ts\n   * const lamp = new Model3D({ source, receiveShadow: false });\n   * ```\n   */\n  receiveShadow?: boolean;\n  /**\n   * Whether the model's {@link Model3D#player | player} advances on `Ticker.shared`\n   *\n   * Set it to `false` to call {@link AnimationPlayer#update} from your own loop.\n   * @default true\n   * @example\n   * ```ts\n   * const robot = new Model3D({ source, autoUpdate: false });\n   *\n   * app.ticker.add((ticker) => robot.player?.update(ticker));\n   * ```\n   */\n  autoUpdate?: boolean;\n  /**\n   * Animation the model starts playing once built\n   *\n   * `true` plays the file's first animation, and a string plays the animation with that label.\n   * Ignored when the file has no animations.\n   * @default false\n   * @example\n   * ```ts\n   * const robot = new Model3D({ source, autoPlay: 'Idle' });\n   * ```\n   */\n  autoPlay?: boolean | string;\n  /**\n   * Materials the model draws instead of its source's, by label, by index or through a function\n   *\n   * Left out, the model draws the source's materials, shared with every model built from it. A\n   * function is called once for each source material, so meshes that shared one share its\n   * replacement. Changing {@link Model3D#materials} later never destroys the materials given here,\n   * even ones a function made, so destroy the ones you made when you're done with them.\n   * `destroy({ children: true, material: true })` destroys whatever the model's meshes draw at that\n   * moment, these included.\n   * @example\n   * ```ts\n   * const enemy = new Model3D({ source, materials: (material) => material.clone() });\n   * ```\n   */\n  materials?: MaterialOverrides;\n}\n\n/**\n * A {@link Container3D} built from a loaded glTF file, a {@link Scene3DSource}\n *\n * It builds the file's scene as nodes: meshes, lights, cameras and empty containers, with a\n * {@link Skeleton} for each skin and an {@link AnimationPlayer} when the file has animations.\n * Geometry, materials and textures stay on the source and are shared, so a model is cheap: build\n * as many from one source as you need for crowds, props or repeated assets. A value written to a\n * shared material shows on every model; {@link Model3D#materials} gives one model materials of its\n * own.\n *\n * A bone with no mesh below it isn't built as a node; it lives only in its skeleton, and anything\n * else under it, such as a light, moves up to the nearest built node, so it doesn't follow the\n * bone. A skinned mesh moves under the lowest node above its skin's joints, and its bounds and\n * hit volume measure the bind pose.\n * @example\n * ```ts\n * import { Assets } from 'pixi.js';\n * import { Model3D, type Scene3DSource } from '@pixi/3d';\n *\n * const source = await Assets.load<Scene3DSource>('robot.glb');\n * const robot = new Model3D(source);\n *\n * view3d.root.addChild(robot);\n * robot.position.set(0, 0, -5);\n *\n * if (robot.player) {\n *   const [walk] = robot.player.animationLabels;\n *   robot.player.play(walk);\n * }\n * ```\n * @see {@link Model3DOptions} For per-instance overrides.\n * @see {@link Container3D.traverse} For changing every node it built.\n * @category scene\n * @standard\n */\nexport class Model3D extends Container3D {\n  /**\n   * Defaults for every new `Model3D`; an option passed as `undefined` keeps its default\n   * @example\n   * ```ts\n   * Model3D.defaultOptions.castShadow = false;\n   * const robot = new Model3D(source); // picks up the override above\n   * ```\n   */\n  public static defaultOptions: Partial<Model3DOptions> = {\n    castShadow: true,\n    receiveShadow: true,\n    autoUpdate: true,\n    autoPlay: false,\n  };\n\n  /**\n   * The source this model was built from, shared with every other model built from it\n   * @example\n   * ```ts\n   * const twin = new Model3D(robot.source);\n   * ```\n   */\n  public readonly source: Scene3DSource;\n\n  /**\n   * Plays the file's animations on this model; `undefined` when the file has none\n   * @example\n   * ```ts\n   * robot.player?.play('Walk');\n   * ```\n   */\n  public player?: AnimationPlayer;\n\n  /**\n   * One {@link Skeleton} per skin in the file, in file order, with skins that have the same joints\n   * and inverse bind matrices counted once; empty when it has none\n   * @example\n   * ```ts\n   * const skeleton = robot.skeletons[0];\n   * const head = skeleton.indexOf('Head');\n   * ```\n   */\n  public skeletons: Skeleton[] = [];\n\n  /**\n   * The cameras in the built scene, in the order they were built; empty when the file has none\n   *\n   * Each sits where the file placed it. {@link View3D.from} makes the first one the view's camera\n   * unless you pass one.\n   * @example\n   * ```ts\n   * if (model.cameras.length > 0) view3d.camera = model.cameras[0];\n   * ```\n   */\n  public cameras: Camera3D[] = [];\n\n  private readonly _builtMeshes: BuiltMesh[] = [];\n\n  /** What `materials` resolved to, one per source index; unset while the model draws the source's */\n  private _materials?: BaseMaterial3D[];\n\n  /** @param options - The source to build from, or {@link Model3DOptions} with it. */\n  constructor(options: Model3DOptions | Scene3DSource) {\n    if (options instanceof Scene3DSource) options = { source: options };\n\n    const {\n      source,\n      scene: sceneName,\n      castShadow,\n      receiveShadow,\n      autoUpdate,\n      autoPlay,\n      hitVolume,\n      width,\n      height,\n      depth,\n      parent,\n      materials,\n      ...rest\n    } = {\n      ...Model3D.defaultOptions,\n      ...definedProps(options),\n    };\n\n    super({ label: 'Model3D', ...rest });\n\n    this.source = source;\n    if (materials) this._materials = applyMaterialOverrides(source.materials, materials);\n\n    const descriptor = source._descriptor;\n    const skeletons = this.skeletons;\n    const build: ModelBuild = { nodeMap: {}, detachedSkinnedNodes: new Map(), castShadow, receiveShadow };\n    const { nodeMap, detachedSkinnedNodes } = build;\n\n    if (descriptor.skins) {\n      descriptor.skins.forEach((s) => {\n        const skeleton = new Skeleton({\n          parent: s.skeletonParent,\n          joints: s.skeletonJoints,\n          inverseBindMatrices: s.inverseBindMatrices,\n          labels: s.skeletonLabels,\n          bindShapeMatrix: s.bindShapeMatrix,\n        });\n\n        skeletons.push(skeleton);\n\n        if (!s.skeletonNodes) return;\n\n        for (let i = 0; i < s.skeletonNodes.length; i++) {\n          const gltfNodeIndex = s.skeletonNodes[i];\n          const node = descriptor.nodes?.[gltfNodeIndex];\n\n          if (node) {\n            const t = node.position;\n            const r = node.rotation;\n            const sc = node.scale;\n\n            skeleton.setLocalTRS(\n              i,\n              t?.[0] ?? 0,\n              t?.[1] ?? 0,\n              t?.[2] ?? 0,\n              r?.[0] ?? 0,\n              r?.[1] ?? 0,\n              r?.[2] ?? 0,\n              r?.[3] ?? 1,\n              sc?.[0] ?? 1,\n              sc?.[1] ?? 1,\n              sc?.[2] ?? 1,\n            );\n          }\n\n          nodeMap[gltfNodeIndex] = { skeleton, boneIndex: i };\n        }\n      });\n    }\n\n    if (descriptor.scenes && descriptor.scenes.length > 0) {\n      let scene = descriptor.scenes[descriptor.defaultScene ?? 0];\n\n      if (sceneName) {\n        scene = source.scene[sceneName] || scene;\n      }\n\n      if (scene.children) {\n        scene.children.forEach((nodeIndex) => {\n          const nodes = this._createNode(nodeIndex, build);\n\n          if (nodes.length) this.addChild(...nodes);\n        });\n      }\n    } else if (descriptor.nodes) {\n      if (descriptor.nodes.length > 0) {\n        const nodes = this._createNode(0, build);\n        if (nodes.length) this.addChild(...nodes);\n      }\n    }\n\n    for (const [index, parentNode] of detachedSkinnedNodes) {\n      const skinParent = nodeMap[parentNode];\n\n      (skinParent instanceof Container3D ? skinParent : this).addChild(nodeMap[index] as Container3D);\n    }\n\n    if (descriptor.skins) {\n      for (let skinIdx = 0; skinIdx < descriptor.skins.length; skinIdx++) {\n        const skeleton = skeletons[skinIdx];\n        const skeletonNodes = descriptor.skins[skinIdx].skeletonNodes;\n\n        if (!skeletonNodes) continue;\n\n        for (let i = 0; i < skeletonNodes.length; i++) {\n          const nodeIndex = skeletonNodes[i];\n\n          if (detachedSkinnedNodes.has(nodeIndex)) continue;\n\n          const mapped = nodeMap[nodeIndex];\n\n          if (mapped instanceof Container3D) skeleton.bindContainerBone(i, mapped);\n        }\n      }\n    }\n\n    const animationKeys = Object.keys(source.animations);\n\n    if (animationKeys.length) {\n      this.player = new AnimationPlayer({\n        target: this,\n        animations: source.animations,\n        nodeMap,\n        autoUpdate,\n        autoPlay,\n      });\n    }\n\n    if (hitVolume !== undefined) this.hitVolume = hitVolume;\n    if (width !== undefined) this.width = width;\n    if (height !== undefined) this.height = height;\n    if (depth !== undefined) this.depth = depth;\n    parent?.addChild(this);\n  }\n\n  private _createMesh(nodeData: Scene3DNode, build: ModelBuild): Container3D {\n    const primitives = this.source.geometries[nodeData.geometry!];\n\n    if (!primitives) return new Container3D();\n\n    const materialIndices = nodeData.materials || [];\n    const skeleton = nodeData.skin !== undefined ? this.skeletons[nodeData.skin] : undefined;\n\n    const targetCount = primitives[0]?.morphTargetCount ?? 0;\n    /**\n     * Shared by every primitive, as glTF morphs them by the same weights (§3.7.2.2); a container of\n     * primitives carries it too, so the node's `weights` animation channel reaches each one\n     */\n    let weights: Float32Array | undefined;\n    if (targetCount > 0) {\n      weights = new Float32Array(targetCount);\n      if (nodeData.weights && nodeData.weights.length === targetCount) weights.set(nodeData.weights);\n    }\n\n    const makeMesh = (geometry: Geometry3D, i: number) => {\n      const index = materialIndices[i];\n      const mesh = new Mesh3D({\n        geometry,\n        material: this.materials[index],\n        skeleton,\n        castShadow: build.castShadow,\n        receiveShadow: build.receiveShadow,\n        weights,\n      });\n\n      this._builtMeshes.push({ mesh, index });\n\n      return mesh;\n    };\n\n    if (primitives.length === 1) return makeMesh(primitives[0], 0);\n\n    const container = new Container3D();\n\n    primitives.forEach((geometry, i) => container.addChild(makeMesh(geometry, i)));\n\n    if (weights) (container as Container3D & { /** @internal */ weights?: Float32Array }).weights = weights;\n\n    return container;\n  }\n\n  private _createLight(nodeData: Scene3DNode): Container3D {\n    const lightData = this.source._descriptor.lights?.[nodeData.light!];\n\n    if (!lightData) return new Container3D();\n\n    const { type, color, intensity, range, coneAngle, penumbra } = lightData;\n\n    if (type === 0) return new DirectionalLight({ color, intensity });\n    if (type === 1) return new PointLight({ color, intensity, range });\n    if (type === 2) return new SpotLight({ color, intensity, range, coneAngle, penumbra });\n\n    return new Container3D();\n  }\n\n  private _createCamera(nodeData: Scene3DNode): Container3D {\n    const cameraData = this.source._descriptor.cameras?.[nodeData.camera!];\n\n    if (!cameraData) return new Container3D();\n\n    const { mode, fov, near, far, orthographicSize } = cameraData;\n    const camera = new Camera3D({\n      mode: mode === 1 ? 'orthographic' : 'perspective',\n      fov,\n      near,\n      far,\n      orthographicSize,\n    });\n\n    this.cameras.push(camera);\n\n    return camera;\n  }\n\n  private _createNode(index: number, build: ModelBuild): Container3D[] {\n    const descriptor = this.source._descriptor;\n    const nodeData = descriptor.nodes?.[index];\n\n    if (!nodeData) return [];\n\n    const childContainers = nodeData.children?.flatMap((child) => this._createNode(child, build)) ?? [];\n\n    if (nodeData.isJoint) return childContainers;\n\n    let container: Container3D;\n\n    if (nodeData.geometry !== undefined) {\n      container = this._createMesh(nodeData, build);\n    } else if (nodeData.light !== undefined) {\n      container = this._createLight(nodeData);\n    } else if (nodeData.camera !== undefined) {\n      container = this._createCamera(nodeData);\n    } else {\n      container = new Container3D();\n    }\n\n    const skin = nodeData.skin !== undefined ? descriptor.skins?.[nodeData.skin] : undefined;\n    /**\n     * The joint matrices already run up to the skin's parent node, so a skinned mesh moves there and\n     * ignores its own node transform, as glTF requires (§3.7.3.2)\n     */\n    const detachSkinned = skin !== undefined && nodeData.geometry !== undefined;\n\n    if (detachSkinned) {\n      if (skin.bindShapeMatrix) {\n        _matrix.fromArray(skin.bindShapeMatrix).decompose(_position, _quaternion, _scale);\n        container.position.copyFrom(_position);\n        container.quaternion.copyFrom(_quaternion);\n        container.scale.copyFrom(_scale);\n      }\n    } else {\n      if (nodeData.position) container.position.fromArray(nodeData.position);\n      if (nodeData.scale) container.scale.fromArray(nodeData.scale);\n      if (nodeData.rotation) container.quaternion.fromArray(nodeData.rotation);\n    }\n\n    if (nodeData.label) container.label = nodeData.label;\n\n    if (nodeData.visible === false) container.visible = false;\n\n    if (childContainers.length) container.addChild(...childContainers);\n\n    build.nodeMap[index] = container;\n\n    if (detachSkinned) {\n      build.detachedSkinnedNodes.set(index, skin.parentNode ?? -1);\n\n      return [];\n    }\n\n    return [container];\n  }\n\n  /**\n   * The material each source index draws on this model, in the order of\n   * {@link Scene3DSource#materials}\n   *\n   * It's the source's own list until the model is given materials, so a value written to an entry\n   * shows on every model that draws it. Assign a {@link MaterialOverrides} record, array or\n   * function to give the model materials of its own; the meshes it built switch at once.\n   * `undefined` goes back to the source's. Assigning sets every mesh the model built that's still\n   * in it, including one whose material you changed yourself, so reapply those afterwards if you\n   * want them back. A mesh you moved out of the model keeps what it draws.\n   *\n   * Assigning never destroys the materials it replaces: destroy the ones you made when you're done\n   * with them. Copies a function made are listed only here, so take them from this list, leaving\n   * out the source's own, before you assign again.\n   * @example\n   * ```ts\n   * const dissolving = source.materials.map((material) => material.clone({ extraBits: [dissolveBit] }));\n   *\n   * enemy.materials = dissolving; // on death; every enemy can share these copies\n   * enemy.materials = undefined; // back to the source's\n   * ```\n   */\n  public get materials(): readonly BaseMaterial3D[] {\n    return this._materials ?? this.source.materials;\n  }\n\n  /**\n   * Gives the model materials of its own, or the source's back with `undefined`, and switches the\n   * meshes it built that are still in it\n   * @param value - What replaces the source's materials.\n   */\n  public set materials(value: MaterialOverrides | undefined) {\n    this._materials = value && applyMaterialOverrides(this.source.materials, value);\n\n    const materials = this.materials;\n    for (const { mesh, index } of this._builtMeshes) {\n      let node = mesh.parent;\n      while (node && node !== this) node = node.parent;\n      if (node) mesh.material = materials[index];\n    }\n  }\n\n  /**\n   * Builds a `Model3D` from a source; the same as `new Model3D({ ...options, source })`\n   * @example\n   * ```ts\n   * const robot = Model3D.from(source, { castShadow: false, autoPlay: 'Idle' });\n   * ```\n   * @param source - The source to build from.\n   * @param options - Per-instance overrides; see {@link Model3DOptions}.\n   */\n  public static from(source: Scene3DSource, options?: Omit<Model3DOptions, 'source'>): Model3D {\n    return new Model3D({ ...options, source });\n  }\n\n  /**\n   * Unloads this model's geometry, materials and textures, for a model out of use for a while\n   *\n   * The textures free their GPU memory; {@link Geometry3D.unload} says what the geometry frees.\n   * Nothing is lost: rendering the model again uploads everything and draws the same image. The\n   * geometry and materials are shared with every model built from the same source, and they're\n   * unloaded all the same; those models upload them again when they next draw.\n   * @example\n   * ```ts\n   * view.root.removeChild(robot);\n   * robot.unload(); // geometry and textures both come back on the next render\n   * ```\n   * @see {@link Model3D.destroy} For permanent teardown.\n   */\n  public override unload(): void {\n    super.unload();\n\n    const materials = new Set<BaseMaterial3D>();\n    collectMaterials(this, materials);\n    for (const material of materials) material.unload();\n  }\n\n  /**\n   * Destroys this model, its animation player and its skeletons\n   *\n   * The skeletons go whatever the flags, but a skinned mesh you keep from the model still draws.\n   * The nodes follow `children` as on any {@link Container3D}. The {@link Model3D#source | source}\n   * is never destroyed, since other models can share it, and its geometry, materials and textures\n   * go only when you pass their flags along with `children`.\n   * @example\n   * ```ts\n   * robot.destroy({ children: true });\n   * ```\n   * @param options - Teardown flags; see {@link Destroy3DOptions}.\n   */\n  public override destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n\n    this.player?.destroy();\n    this.player = undefined;\n\n    for (const skeleton of this.skeletons) skeleton.destroy();\n    (this.skeletons as Skeleton[] | null) = null;\n    (this.cameras as Camera3D[] | null) = null;\n    (this._builtMeshes as BuiltMesh[] | null) = null;\n    this._materials = undefined;\n\n    super.destroy(options);\n  }\n}\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Ramps a particle's opacity from its spawn value to `aAlphaEnd` across its life; set the end to 0\n * to fade out\n *\n * Compose it after {@link particleLifetimeBit}.\n * @category scene\n * @advanced\n */\nexport const particleAlphaOverLifeBit = {\n  name: 'particleAlphaOverLife',\n\n  attributes: {\n    aAlphaEnd: 'float32',\n  },\n\n  gpu: {\n    vertex: {\n      beforeTransform: /*wgsl*/ `\n  particleColor.a = mix(particleColor.a, input.aAlphaEnd, particleProgress);\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      beforeTransform: /*glsl*/ `\n  particleColor.a = mix(particleColor.a, aAlphaEnd, particleProgress);\n`,\n    },\n  },\n} satisfies ShaderBit;\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * How each particle's quad faces the camera\n *\n * - `'spherical'`: faces the camera fully, the classic billboard\n * - `'cylindrical'`: turns about world Y only, so the quad stays upright; suits fire, smoke\n *   columns and grass cards\n * - `'horizontal'`: doesn't face the camera; the quad lies flat on the world's XZ (ground) plane.\n *   Suits impact rings, blob shadows and scorch marks\n *\n * Not the same as `BillboardMode`, which turns a whole `Mesh3D` about its origin.\n * @example\n * ```ts\n * const fire = new ParticleSystem3D({ billboard: 'cylindrical' });\n * const ripples = new ParticleSystem3D({ billboard: 'horizontal' });\n * ```\n * @category scene\n * @standard\n */\nexport type ParticleBillboardMode = 'spherical' | 'cylindrical' | 'horizontal';\n\n/**\n * One generator for both languages, so the maths can't drift; the `max` keeps a camera rolled onto\n * its side, whose right axis has no XZ part, from dividing by zero\n */\nfunction billboardBasis(mode: ParticleBillboardMode, gpu: boolean): string {\n  const vec3 = gpu ? 'vec3<f32>' : 'vec3';\n  const view = gpu ? 'camera.uViewMatrix' : 'uViewMatrix';\n  const decl = gpu ? 'let' : 'vec3';\n  const right = `${view}[0][0], ${view}[1][0], ${view}[2][0]`;\n\n  if (mode === 'horizontal') {\n    return `\n  ${decl} billboardRight = ${vec3}(1.0, 0.0, 0.0);\n  ${decl} billboardUp    = ${vec3}(0.0, 0.0, 1.0);\n`;\n  }\n\n  if (mode === 'cylindrical') {\n    const flat = gpu ? `${vec3}(camRight.x, 0.0, camRight.z)` : 'vec3(camRight.x, 0.0, camRight.z)';\n    const flatLen = gpu ? 'length(vec2<f32>(camRight.x, camRight.z))' : 'length(camRight.xz)';\n\n    return `\n  ${decl} camRight = ${vec3}(${right});\n  ${decl} billboardRight = ${flat} / max(${flatLen}, 1e-5);\n  ${decl} billboardUp = ${vec3}(0.0, 1.0, 0.0);\n`;\n  }\n\n  return `\n  ${decl} billboardRight = ${vec3}(${right});\n  ${decl} billboardUp    = ${vec3}(${view}[0][1], ${view}[1][1], ${view}[2][1]);\n`;\n}\n\nfunction billboardBasisWgsl(mode: ParticleBillboardMode): string {\n  return billboardBasis(mode, true);\n}\n\nfunction billboardBasisGlsl(mode: ParticleBillboardMode): string {\n  return billboardBasis(mode, false);\n}\n\n/**\n * Which {@link getParticleBit} variant to build\n * @category scene\n * @advanced\n */\nexport interface ParticleBitOptions {\n  /** How each quad faces the camera */\n  billboard: ParticleBillboardMode;\n  /** Whether each particle carries an `aParticleUVFrame` flipbook window, 8 bytes a vertex */\n  frames: boolean;\n  /** Whether particle positions are relative to the mesh rather than in world space */\n  localSpace: boolean;\n}\n\nconst cache: Record<string, ShaderBit> = Object.create(null);\n\n/**\n * The shader bit that turns each particle's four vertices into a camera-facing quad\n *\n * The geometry repeats each particle's centre in `aPosition` (`float32x3`) on all four vertices,\n * and gives each vertex its corner, `(0, 0)` to `(1, 1)`, in `aUV` (`unorm8x2`). The bit declares\n * `aParticleSizeRot` (`float32x2`), `aParticleColor` (`unorm8x4`) and, with `frames`,\n * `aParticleUVFrame` (`unorm16x4`); {@link ParticleBuiltInValues} says what each holds.\n *\n * A bit composed after it can grow, spin or recolour a particle by assigning the vertex-stage\n * locals `particleSize`, `particleRotation` and `particleColor` in its `beforeTransform`.\n * `particleColor` is in display space, so a colour ramp blends as a 2D tween does.\n * @param options - Which variant to build\n * @returns The bit for that variant, the same object on every call\n * @category scene\n * @advanced\n */\nexport function getParticleBit(options: ParticleBitOptions): ShaderBit {\n  const { billboard, frames, localSpace } = options;\n  const key = `particle:${billboard}:${localSpace ? 'local' : 'world'}${frames ? ':frames' : ''}`;\n\n  const existing = cache[key];\n  if (existing) return existing;\n\n  const centreGpu = localSpace ? 'worldPosition.xyz' : 'position.xyz';\n  const centreGl = centreGpu;\n\n  const bit: ShaderBit = {\n    name: key,\n\n    attributes: {\n      aParticleSizeRot: 'float32x2',\n      aParticleColor: 'unorm8x4',\n      ...(frames ? ({ aParticleUVFrame: 'unorm16x4' } as const) : null),\n    },\n\n    interStage: {\n      vParticleColor: 'vec4<f32>',\n    },\n\n    gpu: {\n      vertex: {\n        beforeTransform: /*wgsl*/ `\n  let particleCorner = vec2<f32>(uv.x - 0.5, 0.5 - uv.y);\n${frames ? '  uv = input.aParticleUVFrame.xy + uv * input.aParticleUVFrame.zw;\\n' : ''}\n  var particleSize = input.aParticleSizeRot.x;\n  var particleRotation = input.aParticleSizeRot.y;\n  var particleColor = input.aParticleColor;\n`,\n\n        afterTransform: /*wgsl*/ `${billboardBasisWgsl(billboard)}\n  let particleCos = cos(particleRotation);\n  let particleSin = sin(particleRotation);\n  let particleSpun = vec2<f32>(\n    particleCorner.x * particleCos - particleCorner.y * particleSin,\n    particleCorner.x * particleSin + particleCorner.y * particleCos\n  ) * particleSize;\n\n  worldPosition = vec4<f32>(\n    ${centreGpu} + billboardRight * particleSpun.x + billboardUp * particleSpun.y,\n    1.0\n  );\n  clipPosition = camera.uViewProjectionMatrix * worldPosition;\n`,\n\n        end: 'output.vParticleColor = vec4<f32>(decodeColor(particleColor.rgb), particleColor.a);',\n      },\n      fragment: {\n        material: /*wgsl*/ `\n  albedo *= input.vParticleColor.rgb;\n  alpha *= input.vParticleColor.a;\n`,\n      },\n    },\n\n    gl: {\n      vertex: {\n        beforeTransform: /*glsl*/ `\n  vec2 particleCorner = vec2(uv.x - 0.5, 0.5 - uv.y);\n${frames ? '  uv = aParticleUVFrame.xy + uv * aParticleUVFrame.zw;\\n' : ''}\n  float particleSize = aParticleSizeRot.x;\n  float particleRotation = aParticleSizeRot.y;\n  vec4 particleColor = aParticleColor;\n`,\n\n        afterTransform: /*glsl*/ `${billboardBasisGlsl(billboard)}\n  float particleCos = cos(particleRotation);\n  float particleSin = sin(particleRotation);\n  vec2 particleSpun = vec2(\n    particleCorner.x * particleCos - particleCorner.y * particleSin,\n    particleCorner.x * particleSin + particleCorner.y * particleCos\n  ) * particleSize;\n\n  worldPosition = vec4(\n    ${centreGl} + billboardRight * particleSpun.x + billboardUp * particleSpun.y,\n    1.0\n  );\n  gl_Position = uProjectionMatrix * uViewMatrix * worldPosition;\n`,\n\n        end: 'vParticleColor = vec4(decodeColor(particleColor.rgb), particleColor.a);',\n      },\n      fragment: {\n        material: /*glsl*/ `\n  albedo *= vParticleColor.rgb;\n  alpha *= vParticleColor.a;\n`,\n      },\n    },\n  };\n\n  cache[key] = bit;\n  return bit;\n}\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Ramps a particle's tint from its spawn colour to `aColorEnd` across its life\n *\n * `aColorEnd` takes `{ x, y, z, w }`, each 0 to 1 in display (sRGB) space, not a `ColorSource`;\n * `w` is unused, since {@link particleAlphaOverLifeBit} ramps opacity. Compose it after\n * {@link particleLifetimeBit}.\n * @category scene\n * @advanced\n */\nexport const particleColorOverLifeBit = {\n  name: 'particleColorOverLife',\n\n  attributes: {\n    aColorEnd: 'unorm8x4',\n  },\n\n  gpu: {\n    vertex: {\n      beforeTransform: /*wgsl*/ `\n  particleColor = vec4<f32>(mix(particleColor.rgb, input.aColorEnd.rgb, particleProgress), particleColor.a);\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      beforeTransform: /*glsl*/ `\n  particleColor.rgb = mix(particleColor.rgb, aColorEnd.rgb, particleProgress);\n`,\n    },\n  },\n} satisfies ShaderBit;\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\nconst GRID_BINDING = { uFlipbookGrid: 'vec3<f32>' } as const;\n\nconst WINDOW_WGSL = /*wgsl*/ `\n    let cols = material.uFlipbookGrid.x;\n    let rows = material.uFlipbookGrid.y;\n    let col = frame % cols;\n    let row = floor(frame / cols);\n    let window = vec4<f32>(col / cols, row / rows, 1.0 / cols, 1.0 / rows);\n    uv = window.xy + uv * window.zw;`;\n\nconst WINDOW_GLSL = /*glsl*/ `\n    float cols = material.uFlipbookGrid.x;\n    float rows = material.uFlipbookGrid.y;\n    float col = mod(frame, cols);\n    float row = floor(frame / cols);\n    vec4 window = vec4(col / cols, row / rows, 1.0 / cols, 1.0 / rows);\n    uv = window.xy + uv * window.zw;`;\n\n/**\n * Plays the flipbook once over a particle's life, first frame at birth and last at death\n *\n * Give the container the whole sheet as its one texture, not an array of frames, and set its\n * `uFlipbookGrid` uniform to `[columns, rows, frameCount]`. Frames run left to right, then top to\n * bottom, in equal cells. Compose it after {@link particleLifetimeBit}.\n * @category scene\n * @advanced\n */\nexport const particleFlipbookOverLifeBit = {\n  name: 'particleFlipbookOverLife',\n\n  bindings: { material: GRID_BINDING },\n\n  gpu: {\n    vertex: {\n      beforeTransform: /*wgsl*/ `\n  {\n    let count = material.uFlipbookGrid.z;\n    let frame = min(floor(particleProgress * count), count - 1.0);\n${WINDOW_WGSL}\n  }\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      beforeTransform: /*glsl*/ `\n  {\n    float count = material.uFlipbookGrid.z;\n    float frame = min(floor(particleProgress * count), count - 1.0);\n${WINDOW_GLSL}\n  }\n`,\n    },\n  },\n} satisfies ShaderBit;\n\n/**\n * Plays the flipbook at `uFrameRate` frames per second from birth, looping\n *\n * Set up the sheet as for {@link particleFlipbookOverLifeBit}, and compose it after\n * {@link particleLifetimeBit}.\n * @category scene\n * @advanced\n */\nexport const particleFlipbookRateBit = {\n  name: 'particleFlipbookRate',\n\n  bindings: {\n    material: {\n      ...GRID_BINDING,\n      uFrameRate: 'f32',\n    },\n  },\n\n  gpu: {\n    vertex: {\n      beforeTransform: /*wgsl*/ `\n  {\n    let count = material.uFlipbookGrid.z;\n    let frame = floor(particleAge * material.uFrameRate) % count;\n${WINDOW_WGSL}\n  }\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      beforeTransform: /*glsl*/ `\n  {\n    float count = material.uFlipbookGrid.z;\n    float frame = mod(floor(particleAge * material.uFrameRate), count);\n${WINDOW_GLSL}\n  }\n`,\n    },\n  },\n} satisfies ShaderBit;\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Gives every particle a clock, which the other lifetime bits read\n *\n * Each particle carries its `aBirth` time and `aLife` length in seconds, and you advance the\n * container's `uParticleTime` uniform yourself, so you can pause or scrub the system. A particle\n * draws only from its birth until its life runs out.\n *\n * Bits composed after it can read two locals in their `beforeTransform` or later: `particleAge`,\n * seconds since birth, and `particleProgress`, age over life from 0 to 1.\n * @category scene\n * @advanced\n */\nexport const particleLifetimeBit = {\n  name: 'particleLifetime',\n\n  attributes: {\n    aBirth: 'float32',\n    aLife: 'float32',\n  },\n\n  bindings: {\n    material: {\n      uParticleTime: 'f32',\n    },\n  },\n\n  gpu: {\n    vertex: {\n      beforeTransform: /*wgsl*/ `\n  let particleAge = material.uParticleTime - input.aBirth;\n  let particleProgress = clamp(particleAge / max(input.aLife, 1e-6), 0.0, 1.0);\n`,\n      afterTransform: /*wgsl*/ `\n  if (particleAge < 0.0 || particleAge > input.aLife) {\n    clipPosition = vec4<f32>(0.0, 0.0, 2.0, 1.0);\n  }\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      beforeTransform: /*glsl*/ `\n  float particleAge = material.uParticleTime - aBirth;\n  float particleProgress = clamp(particleAge / max(aLife, 1e-6), 0.0, 1.0);\n`,\n      afterTransform: /*glsl*/ `\n  if (particleAge < 0.0 || particleAge > aLife) {\n    gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n  }\n`,\n    },\n  },\n} satisfies ShaderBit;\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Moves each particle from its launch point along a ballistic path, worked out on the GPU\n *\n * `aPosition` is the launch point and `aVel` the launch velocity, per particle. The container's\n * `uGravity` uniform is the acceleration, and `uDrag` the linear drag per second, 0 for none.\n * Compose it after {@link particleLifetimeBit}.\n * @category scene\n * @advanced\n */\nexport const particleMotionBit = {\n  name: 'particleMotion',\n\n  attributes: {\n    aVel: 'float32x3',\n  },\n\n  bindings: {\n    material: {\n      uGravity: 'vec3<f32>',\n      uDrag: 'f32',\n    },\n  },\n\n  gpu: {\n    vertex: {\n      beforeTransform: /*wgsl*/ `\n  {\n    let k = material.uDrag;\n    let t = particleAge;\n    var a = t;\n    var b = t * t * 0.5;\n\n    if (k > 1e-4) {\n      a = (1.0 - exp(-k * t)) / k;\n      b = (t - a) / k;\n    }\n\n    position = vec4<f32>(position.xyz + input.aVel * a + material.uGravity * b, 1.0);\n  }\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      beforeTransform: /*glsl*/ `\n  {\n    float k = material.uDrag;\n    float t = particleAge;\n    float a = t;\n    float b = t * t * 0.5;\n\n    if (k > 1e-4) {\n      a = (1.0 - exp(-k * t)) / k;\n      b = (t - a) / k;\n    }\n\n    position = vec4(position.xyz + aVel * a + material.uGravity * b, 1.0);\n  }\n`,\n    },\n  },\n} satisfies ShaderBit;\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Ramps a particle's size from its spawn value to `aSizeEnd` across its life\n *\n * Compose it after {@link particleLifetimeBit}.\n * @category scene\n * @advanced\n */\nexport const particleSizeOverLifeBit = {\n  name: 'particleSizeOverLife',\n\n  attributes: {\n    aSizeEnd: 'float32',\n  },\n\n  gpu: {\n    vertex: {\n      beforeTransform: /*wgsl*/ `\n  particleSize = mix(particleSize, input.aSizeEnd, particleProgress);\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      beforeTransform: /*glsl*/ `\n  particleSize = mix(particleSize, aSizeEnd, particleProgress);\n`,\n    },\n  },\n} satisfies ShaderBit;\n","import type { ShaderBit } from '../../../core/shader/ShaderBit';\n\n/**\n * Spins a particle in its quad's plane at `aSpin` radians per second, from its spawn rotation\n *\n * Compose it after {@link particleLifetimeBit}.\n * @category scene\n * @advanced\n */\nexport const particleSpinBit = {\n  name: 'particleSpin',\n\n  attributes: {\n    aSpin: 'float32',\n  },\n\n  gpu: {\n    vertex: {\n      beforeTransform: /*wgsl*/ `\n  particleRotation += input.aSpin * particleAge;\n`,\n    },\n  },\n\n  gl: {\n    vertex: {\n      beforeTransform: /*glsl*/ `\n  particleRotation += aSpin * particleAge;\n`,\n    },\n  },\n} satisfies ShaderBit;\n","import type { BLEND_MODES, Texture } from 'pixi.js';\n\nimport { alphaMaskBit } from '../../core/shader/bits/alphaMaskBit';\nimport { uvTransformBit } from '../../core/shader/bits/uvTransformBit';\nimport type { ShaderBit } from '../../core/shader/ShaderBit';\nimport { ShaderDescriptor } from '../../core/shader/ShaderDescriptor';\nimport { BaseMaterial3D } from '../../materials/BaseMaterial3D';\nimport type { AlphaMode, ColorSpace } from '../../materials/BaseMaterial3D';\nimport { flatMaterialBit } from '../../materials/flat/bits/flatMaterialBit';\nimport type { MaterialData } from '../../materials/utils/createMaterialDataClass';\nimport type { MaterialTextures } from '../../materials/utils/createMaterialTexturesClass';\nimport type { View3D } from '../View3D';\nimport { getParticleBit } from './bits/particleBit';\nimport type { ParticleBillboardMode } from './bits/particleBit';\n\n/**\n * How particles blend over the scene; pixi's advanced modes, such as `'overlay'`, aren't available\n *\n * - `'normal'` covers what's behind: smoke, dust, debris\n * - `'add'` only brightens: fire, sparks, magic, anything that glows\n * - `'multiply'` only darkens: stains, shadowy wisps, dark smoke\n * - `'screen'` brightens softly without blowing out: glows and hazes\n * @example\n * ```ts\n * const blendMode: ParticleBlendMode = glowing ? 'add' : 'normal';\n * const particles = new ParticleSystem3D({ blendMode });\n * ```\n * @category scene\n * @standard\n */\nexport type ParticleBlendMode = Extract<BLEND_MODES, 'normal' | 'add' | 'multiply' | 'screen'>;\n\n/**\n * Constructor options for {@link ParticleMaterial}\n * @category scene\n * @advanced\n */\nexport interface ParticleMaterialOptions {\n  /**\n   * Name for debugging and for finding the material\n   * @example\n   * ```ts\n   * new ParticleMaterial({ label: 'sparks' });\n   * ```\n   */\n  label?: string;\n  /** The sprite (or whole sprite sheet, for flipbooks) every particle samples */\n  texture?: Texture;\n  /**\n   * How each quad faces the camera\n   * @default 'spherical'\n   */\n  billboard?: ParticleBillboardMode;\n  /**\n   * Whether the geometry carries a per-particle `aParticleUVFrame` flipbook window\n   *\n   * `texture` must then be the whole sheet, not one frame of it, or the constructor throws.\n   * @default false\n   */\n  useFrames?: boolean;\n  /**\n   * Whether particle positions are relative to the mesh rather than in world space\n   * @default false\n   */\n  localSpace?: boolean;\n  /**\n   * How particles blend over the scene; see {@link ParticleBlendMode}\n   *\n   * Ignored unless `alphaMode` is `'blend'`.\n   * @default 'normal'\n   */\n  blendMode?: ParticleBlendMode;\n  /**\n   * How particle transparency works; see {@link ParticleContainer3DOptions.alphaMode}\n   * @default 'blend'\n   */\n  alphaMode?: AlphaMode;\n  /**\n   * Alpha below which a texel is cut away under `alphaMode: 'mask'`\n   * @default 0.5\n   */\n  alphaCutoff?: number;\n  /** Extra shader bits composed after the particle bit; see {@link ParticleContainer3DOptions.extraBits} */\n  extraBits?: readonly ShaderBit[];\n  /** Textures for the extra bits' declarations, by name, as `BaseMaterial3DOptions.textures` */\n  textures?: Record<string, Texture | undefined>;\n  /**\n   * Whether the view's fog reaches these particles\n   *\n   * Defaults to `true` for `'normal'` blending only, since fog would show other blend modes' quads\n   * as glowing or staining rectangles.\n   */\n  fog?: boolean;\n}\n\n/**\n * The unlit material {@link ParticleContainer3D} builds for its particles\n *\n * Use it yourself only on geometry with the same particle attributes, and `useFrames` and\n * `localSpace` to match. Its blend mode is `material.state.blendMode`; after changing that on a\n * mesh that's already drawing, call the mesh's `invalidate()`, which\n * {@link ParticleContainer3D#blendMode} does for you.\n * @category scene\n * @advanced\n */\nexport class ParticleMaterial extends BaseMaterial3D<MaterialData, MaterialTextures, ParticleMaterialOptions> {\n  /** `'display'`, since particles only multiply their colours */\n  public override colorSpace: ColorSpace = 'display';\n\n  /** `false`: lights and shadows don't reach particles */\n  public override lit = false;\n\n  /**\n   * Never changes, so the data layout can't shift; `ParticleContainer3D._attributes` lays out the\n   * attributes of all but the first two, which declare none\n   */\n  private readonly _bits: readonly ShaderBit[];\n\n  private readonly _billboard: ParticleBillboardMode;\n  private readonly _useFrames: boolean;\n  private readonly _localSpace: boolean;\n\n  constructor(options: ParticleMaterialOptions = {}) {\n    const billboard = options.billboard ?? 'spherical';\n    const useFrames = options.useFrames ?? false;\n    const localSpace = options.localSpace ?? false;\n\n    super({\n      label: options.label,\n      baseColorTexture: options.texture,\n      alphaMode: options.alphaMode ?? 'blend',\n      alphaCutoff: options.alphaCutoff,\n      extraBits: options.extraBits,\n      doubleSided: true,\n      fog: options.fog ?? (options.blendMode ?? 'normal') === 'normal',\n    });\n\n    if (useFrames && options.texture !== undefined) {\n      const { frame, source } = options.texture;\n\n      if (frame.x !== 0 || frame.y !== 0 || frame.width !== source.width || frame.height !== source.height) {\n        throw new Error('[ParticleMaterial] useFrames needs the whole sheet as its texture, not one frame of it.');\n      }\n    }\n\n    this._billboard = billboard;\n    this._useFrames = useFrames;\n    this._localSpace = localSpace;\n    this._descriptor = new ShaderDescriptor({});\n\n    this._bits = [\n      flatMaterialBit,\n      uvTransformBit,\n      getParticleBit({ billboard, frames: useFrames, localSpace }),\n      ...this.extraBits,\n    ];\n    this._deriveLayoutFromBits(this._bits, { baseColor: options.texture, ...options.textures });\n\n    if (this._alphaMode === 'blend') this.state.blendMode = options.blendMode ?? 'normal';\n  }\n\n  /**\n   * The particle shader, with the alpha cutoff under `alphaMode: 'mask'`\n   * @param _view - Unused; the descriptor is the same in every view\n   */\n  public override getPrimaryDescriptor(_view: View3D): ShaderDescriptor {\n    if (!this._variantDirty) return this._descriptor!;\n\n    const bits = this._bits.slice();\n\n    if (this._alphaMode === 'mask') bits.push(alphaMaskBit);\n\n    this._descriptor!.update({ bitsGpu: bits, bitsGl: bits });\n    this._variantDirty = false;\n\n    return this._descriptor!;\n  }\n\n  /**\n   * The options a particle material takes, read back: its sheet, the three that pick the particle\n   * bit, the blend and alpha modes, fog and its extra bits' slots\n   * @advanced\n   */\n  protected override _toOptions(): ParticleMaterialOptions {\n    const { label, alphaMode, alphaCutoff, fog, textures } = super._toOptions();\n\n    return {\n      label,\n      texture: this.textures.baseColor,\n      billboard: this._billboard,\n      useFrames: this._useFrames,\n      localSpace: this._localSpace,\n      blendMode: this.state.blendMode as ParticleBlendMode,\n      alphaMode,\n      alphaCutoff,\n      fog,\n      textures,\n    };\n  }\n}\n","/**\n * Packs a tint and opacity into the 32-bit word {@link ParticleContainer3D.writePacked} takes\n *\n * Red lands in the low byte and alpha in the high byte, as {@link ParticleContainerViews.u32} holds\n * the colour.\n * @param color - `0xRRGGBB` tint, in display (sRGB) space\n * @param alpha - Opacity, 0 to 1\n * @returns The packed word\n * @category scene\n * @advanced\n */\nexport function packParticleColor(color: number, alpha: number): number {\n  const r = (color >> 16) & 0xff;\n  const g = (color >> 8) & 0xff;\n  const b = color & 0xff;\n  const a = alpha <= 0 ? 0 : alpha >= 1 ? 255 : (alpha * 255 + 0.5) | 0;\n\n  return (r | (g << 8) | (b << 16) | (a << 24)) >>> 0;\n}\n","import { warn } from 'pixi.js';\nimport type { Texture } from 'pixi.js';\n\nconst NO_PACKED_FRAMES = new Uint16Array(0);\n\n/**\n * Packs each flipbook frame's window on its sheet, `(u0, v0, uScale, vScale)`, as the four\n * `unorm16` values a particle's `aParticleUVFrame` holds\n *\n * A single frame needs no window and gets an empty array. Rotated frames aren't supported.\n * @param textures - The flipbook frames, in frame order\n * @returns Four values per frame, or an empty array for a single frame\n * @throws If the frames don't all share one `TextureSource`.\n * @category scene\n * @advanced\n */\nexport function packParticleFrames(textures: readonly Texture[]): Uint16Array {\n  if (textures.length <= 1) return NO_PACKED_FRAMES;\n\n  const source = textures[0].source;\n\n  for (let i = 1; i < textures.length; i++) {\n    if (textures[i].source !== source) {\n      throw new Error(\n        '[ParticleContainer3D] Flipbook frames must all come from one texture source — a particle system ' +\n          'draws in a single call and can only bind one texture. Pack the frames into a sprite sheet.',\n      );\n    }\n  }\n\n  const packedFrames = new Uint16Array(textures.length * 4);\n  const sw = source.width;\n  const sh = source.height;\n\n  for (let i = 0; i < textures.length; i++) {\n    const texture = textures[i];\n\n    if (texture.rotate) {\n      warn(\n        `[ParticleContainer3D] Frame ${i} is rotated in its sprite sheet; particles sample axis-aligned ` +\n          'frames only. Re-pack the sheet with rotation disabled.',\n      );\n    }\n\n    const frame = texture.frame;\n    const o = i * 4;\n\n    packedFrames[o] = quantize(frame.x / sw);\n    packedFrames[o + 1] = quantize(frame.y / sh);\n    packedFrames[o + 2] = quantize(frame.width / sw);\n    packedFrames[o + 3] = quantize(frame.height / sh);\n  }\n\n  return packedFrames;\n}\n\nfunction quantize(value: number): number {\n  return Math.round(Math.min(Math.max(value, 0), 1) * 65535);\n}\n","/**\n * A 0 to 1 value as a byte, clamped so an overshoot can't spill into the next channel of a packed word\n * @internal\n */\nexport function unorm8(v: number): number {\n  return v <= 0 ? 0 : v >= 1 ? 255 : (v * 255 + 0.5) | 0;\n}\n\n/**\n * A 0 to 1 value as a clamped 16-bit integer\n * @internal\n */\nexport function unorm16(v: number): number {\n  return v <= 0 ? 0 : v >= 1 ? 65535 : (v * 65535 + 0.5) | 0;\n}\n","import { Buffer, BufferUsage, createIndicesForQuads } from 'pixi.js';\n\n/** @internal */\nexport const VERTS_PER_PARTICLE = 4;\n\n/** @internal */\nexport const INDICES_PER_PARTICLE = 6;\n\n/** @internal */\nexport const MAX_U16_CAPACITY = 16384;\n\nfunction buildUvBuffer(vertexCount: number): Buffer {\n  return new Buffer({\n    data: cornerIds(vertexCount),\n    usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,\n    label: 'particle-corners',\n    shrinkToFit: false,\n  });\n}\n\n/**\n * Corners `(0, 1)`, `(1, 1)`, `(1, 0)`, `(0, 0)` round the quad's edge, as `createIndicesForQuads`\n * splits it, padded to the 4-byte stride WebGPU requires, which `ParticleContainer3D` gives `aUV`\n */\nfunction cornerIds(vertexCount: number): Uint8Array {\n  const data = new Uint8Array(vertexCount * 4);\n\n  for (let v = 0; v < vertexCount; v += VERTS_PER_PARTICLE) {\n    const o = v * 4;\n\n    data[o + 1] = 255;\n    data[o + 4] = 255;\n    data[o + 5] = 255;\n    data[o + 8] = 255;\n  }\n\n  return data;\n}\n\n/** Passes pixi its own array, since pixi moves to 32-bit indices by index count, not by the highest index */\nfunction buildIndices(capacity: number): Uint16Array | Uint32Array {\n  const indices =\n    capacity <= MAX_U16_CAPACITY\n      ? new Uint16Array(capacity * INDICES_PER_PARTICLE)\n      : new Uint32Array(capacity * INDICES_PER_PARTICLE);\n\n  return createIndicesForQuads(capacity, indices);\n}\n\n/**\n * The corner and index buffers every container draws a prefix of, through its geometry's `indexCount`\n * @internal\n */\nexport interface SharedQuadBuffers {\n  readonly corners: Buffer;\n  readonly indices: Buffer;\n  capacity: number;\n  users: number;\n}\n\nconst MIN_SHARED_QUADS = 256;\n\n/** One pair per index width, so a small container never draws with 32-bit indices */\nlet shared16: SharedQuadBuffers | null = null;\nlet shared32: SharedQuadBuffers | null = null;\n\n/**\n * The shared pair covering at least `capacity` quads, grown in place when too small\n *\n * Plain pixi `Buffer`s, so a growth's `change` event re-records the draws that baked the old ones.\n * @internal\n */\nexport function ensureQuadBuffers(capacity: number): SharedQuadBuffers {\n  const wide = capacity > MAX_U16_CAPACITY;\n  let current = wide ? shared32 : shared16;\n\n  if (current === null || current.corners.destroyed || current.indices.destroyed) {\n    const size = wide ? capacity : Math.min(Math.max(capacity, MIN_SHARED_QUADS), MAX_U16_CAPACITY);\n\n    current = {\n      corners: buildUvBuffer(size * VERTS_PER_PARTICLE),\n      indices: new Buffer({\n        data: buildIndices(size),\n        usage: BufferUsage.INDEX | BufferUsage.COPY_DST,\n        label: 'particle-indices',\n        shrinkToFit: false,\n      }),\n      capacity: size,\n      users: 0,\n    };\n\n    if (wide) shared32 = current;\n    else shared16 = current;\n\n    return current;\n  }\n\n  if (current.capacity < capacity) {\n    let size = Math.max(capacity, current.capacity * 2);\n\n    if (!wide) size = Math.min(size, MAX_U16_CAPACITY);\n\n    current.corners.data = cornerIds(size * VERTS_PER_PARTICLE);\n    current.indices.data = buildIndices(size);\n    current.capacity = size;\n  }\n\n  return current;\n}\n\n/**\n * {@link ensureQuadBuffers}, counting one more user until its {@link releaseQuadBuffers}\n * @internal\n */\nexport function acquireQuadBuffers(capacity: number): SharedQuadBuffers {\n  const pair = ensureQuadBuffers(capacity);\n\n  pair.users++;\n\n  return pair;\n}\n\n/**\n * Lets go of a pair taken with {@link acquireQuadBuffers}, destroying it once no container holds it\n * @internal\n */\nexport function releaseQuadBuffers(pair: SharedQuadBuffers): void {\n  if (--pair.users > 0) return;\n\n  pair.corners.destroy();\n  pair.indices.destroy();\n\n  if (shared16 === pair) shared16 = null;\n  else if (shared32 === pair) shared32 = null;\n}\n","import { getAttributeInfoFromFormat } from 'pixi.js';\nimport type { PointData, VertexFormat } from 'pixi.js';\n\nimport type { PointData3D } from '../../../math/vector/PointData3D';\nimport type { PointData4D } from '../../../math/vector/PointData4D';\n\nconst POSITION_BYTES = 12;\n\n/** Kept out of the interleaved order, though each still counts toward {@link MAX_VERTEX_ATTRIBUTES} */\nconst NOT_INTERLEAVED = new Set(['aUV', 'aPosition']);\n\n/** The vertex inputs WebGL 2 and WebGPU both guarantee */\nconst MAX_VERTEX_ATTRIBUTES = 16;\n\n/** @internal */\nexport interface ParticleAttribute {\n  format: VertexFormat;\n  offset: number;\n  /** `offset` in 32-bit elements */\n  index: number;\n  components: 1 | 2 | 3 | 4;\n  /** `'unsupported'` has no packer, and throws only when `setParticle` writes it */\n  kind: 'float' | 'unorm8' | 'unorm16' | 'color' | 'unsupported';\n}\n\ninterface ParticleLayout {\n  attributes: Record<string, ParticleAttribute>;\n  vertexStride: number;\n}\n\nfunction resolveParticleAttribute(name: string, format: VertexFormat, offset: number): ParticleAttribute {\n  const index = offset / 4;\n\n  if (name === 'aParticleColor') return { format, offset, index, components: 4, kind: 'color' };\n\n  switch (format) {\n    case 'float32':\n      return { format, offset, index, components: 1, kind: 'float' };\n    case 'float32x2':\n      return { format, offset, index, components: 2, kind: 'float' };\n    case 'float32x3':\n      return { format, offset, index, components: 3, kind: 'float' };\n    case 'float32x4':\n      return { format, offset, index, components: 4, kind: 'float' };\n    case 'unorm8x4':\n      return { format, offset, index, components: 4, kind: 'unorm8' };\n    case 'unorm16x4':\n      return { format, offset, index, components: 4, kind: 'unorm16' };\n    default:\n      return { format, offset, index, components: 4, kind: 'unsupported' };\n  }\n}\n\n/**\n * Throws unless `value` has the shape the attribute takes\n * @internal\n */\nexport function expectShape(name: string, value: unknown, components: number): asserts value is PointData4D {\n  const ok =\n    components === 1\n      ? typeof value === 'number'\n      : typeof value === 'object' &&\n        value !== null &&\n        typeof (value as PointData).x === 'number' &&\n        typeof (value as PointData).y === 'number' &&\n        (components < 3 || typeof (value as PointData3D).z === 'number') &&\n        (components < 4 || typeof (value as PointData4D).w === 'number');\n\n  if (!ok) {\n    const want = components === 1 ? 'a number' : `{ ${['x', 'y', 'z', 'w'].slice(0, components).join(', ')} }`;\n    throw new Error(`[ParticleContainer3D] '${name}' takes ${want}, got ${JSON.stringify(value)}`);\n  }\n}\n\n/**\n * Derives the interleaved vertex layout from the attributes the composed bits declare\n *\n * `aPosition` leads as `float32x3`: `ParticleContainerViews` promises it at offset 0, and the material\n * systems pick the position bit by its format.\n * @internal\n */\nexport function buildParticleLayout(declared: Record<string, VertexFormat>): ParticleLayout {\n  const attributes: Record<string, ParticleAttribute> = Object.create(null);\n  let offset = POSITION_BYTES;\n\n  attributes.aPosition = resolveParticleAttribute('aPosition', 'float32x3', 0);\n\n  let count = NOT_INTERLEAVED.size;\n\n  for (const [name, format] of Object.entries(declared)) {\n    if (NOT_INTERLEAVED.has(name)) continue;\n\n    offset = Math.ceil(offset / 4) * 4;\n    attributes[name] = resolveParticleAttribute(name, format, offset);\n    offset += getAttributeInfoFromFormat(format).stride;\n    count++;\n  }\n\n  if (count > MAX_VERTEX_ATTRIBUTES) {\n    throw new Error(\n      `[ParticleContainer3D] the composed bits need ${count} vertex attributes and the GPU guarantees ` +\n        `${MAX_VERTEX_ATTRIBUTES}. Pack some into fewer, wider formats.`,\n    );\n  }\n\n  return { attributes, vertexStride: Math.ceil(offset / 4) * 4 };\n}\n","import { Buffer, BufferUsage, Color, definedProps, Texture } from 'pixi.js';\nimport type { Attribute, ColorSource } from 'pixi.js';\n\nimport { collectAttributes } from '../../core/shader/codegen/collectAttributes';\nimport type { ShaderBit } from '../../core/shader/ShaderBit';\nimport { Geometry3D } from '../../geometry/Geometry3D';\nimport type { AlphaMode } from '../../materials/BaseMaterial3D';\nimport type { Destroy3DOptions } from '../../utils/Destroy3DOptions';\nimport { warnOnce } from '../../utils/warnOnce';\nimport type { Container3DOptions } from '../Container3D';\nimport type { BillboardMode } from '../Mesh3D';\nimport { Mesh3D } from '../Mesh3D';\nimport { getParticleBit } from './bits/particleBit';\nimport type { ParticleBillboardMode } from './bits/particleBit';\nimport { ParticleMaterial } from './ParticleMaterial';\nimport type { ParticleBlendMode } from './ParticleMaterial';\nimport { packParticleColor } from './utils/packParticleColor';\nimport { packParticleFrames } from './utils/packParticleFrames';\nimport { unorm16, unorm8 } from './utils/packUnorm';\nimport {\n  acquireQuadBuffers,\n  INDICES_PER_PARTICLE,\n  releaseQuadBuffers,\n  VERTS_PER_PARTICLE,\n} from './utils/particleGeometry';\nimport type { SharedQuadBuffers } from './utils/particleGeometry';\nimport { buildParticleLayout, expectShape } from './utils/particleLayout';\nimport type { ParticleAttribute } from './utils/particleLayout';\nimport type { ParticleAttributeValue, ParticleValues } from './utils/particleValues';\n\n/**\n * Whether particle positions are in world space or move with their container; see\n * {@link ParticleContainer3DOptions.space}\n * @example\n * ```ts\n * const space: ParticleSpace = followsShip ? 'local' : 'world';\n * const exhaust = new ParticleSystem3D({ space });\n * ```\n * @category scene\n * @standard\n */\nexport type ParticleSpace = 'world' | 'local';\n\n/**\n * Constructor options for {@link ParticleContainer3D}\n *\n * The container builds its own geometry and material, so it takes the {@link Container3DOptions}\n * rather than the mesh ones, less `width`, `height` and `depth`, since particles have no bounds to\n * measure. Particles never cast or receive shadows.\n * @example\n * ```ts\n * const sparks = new ParticleContainer3D({\n *   texture: spark,\n *   capacity: 500,\n *   blendMode: 'add',\n *   space: 'local',\n * });\n * ```\n * @see {@link ParticleContainer3D} For the constructed container.\n * @category scene\n * @standard\n */\nexport interface ParticleContainer3DOptions<B extends readonly ShaderBit[] = readonly ShaderBit[]> extends Omit<\n  Container3DOptions,\n  'width' | 'height' | 'depth'\n> {\n  /**\n   * The sprite drawn for every particle\n   *\n   * Pass an array of frames for a flipbook. The frames must share one `TextureSource`, such as a\n   * sprite sheet.\n   * @default Texture.WHITE\n   * @example\n   * ```ts\n   * const sparks = new ParticleSystem3D({ texture: sparkTexture });\n   * const flames = new ParticleSystem3D({ texture: sheet.animations.flame, frameMode: 'animate' });\n   * ```\n   */\n  texture?: Texture | readonly Texture[];\n  /**\n   * How many particles the system can hold, fixed for its lifetime\n   *\n   * Every slot costs 4 vertices whether or not a particle is in it, so size it to the peak you\n   * need.\n   * @default 1000\n   * @example\n   * ```ts\n   * const puff = new ParticleSystem3D({ capacity: 64 });\n   * ```\n   */\n  capacity?: number;\n  /**\n   * How each particle faces the camera; see {@link ParticleBillboardMode}\n   * @default 'spherical'\n   * @example\n   * ```ts\n   * const fire = new ParticleSystem3D({ billboard: 'cylindrical' });\n   * ```\n   */\n  billboard?: ParticleBillboardMode;\n  /**\n   * How particles blend over the scene; see {@link ParticleBlendMode}\n   * @default 'normal'\n   * @example\n   * ```ts\n   * const sparks = new ParticleSystem3D({ blendMode: 'add' });\n   * ```\n   */\n  blendMode?: ParticleBlendMode;\n  /**\n   * Whether particle positions are in world space (`'world'`) or relative to this node\n   * (`'local'`)\n   *\n   * World-space particles are left behind as the emitter moves, which suits smoke and dust.\n   * Local-space particles move with the node, so a system on a moving object travels with it, at\n   * no extra cost. Particle size is a world-space diameter either way; the node's scale doesn't\n   * change it.\n   * @default 'world'\n   * @example\n   * ```ts\n   * const exhaust = new ParticleSystem3D({ space: 'local' });\n   * ship.addChild(exhaust);\n   * ```\n   */\n  space?: ParticleSpace;\n  /**\n   * How particle transparency works\n   *\n   * - `'blend'`: blends over the scene with {@link ParticleContainer3DOptions.blendMode | blendMode}.\n   *   Particles draw in slot order, not sorted by depth, which shows under `'normal'` blending.\n   * - `'mask'`: hard-edged cutouts that write depth, so they overlap correctly in any order; suits\n   *   leaves and debris.\n   * - `'opaque'`: solid quads, the cheapest; only for textures with no transparent texels.\n   * @default 'blend'\n   * @example\n   * ```ts\n   * const leaves = new ParticleSystem3D({ texture: leafTexture, alphaMode: 'mask' });\n   * ```\n   */\n  alphaMode?: AlphaMode;\n  /**\n   * Alpha below which a texel is cut away under `alphaMode: 'mask'`\n   * @default 0.5\n   * @example\n   * ```ts\n   * const leaves = new ParticleSystem3D({ texture: leafTexture, alphaMode: 'mask', alphaCutoff: 0.3 });\n   * ```\n   */\n  alphaCutoff?: number;\n  /**\n   * Extra shader bits composed into the particle material\n   *\n   * Each bit's `attributes` get space in every particle, writable with\n   * {@link ParticleContainer3D.setParticle}, and its `material` bindings become fields on the\n   * container's {@link ParticleContainer3D.uniforms | uniforms}. The bits run after the base colour\n   * is sampled, so they see and can change `albedo` and `alpha`; {@link getParticleBit} lists the\n   * vertex-stage locals they can change.\n   * @example\n   * ```ts\n   * const particles = new ParticleContainer3D({ extraBits: [particleLifetimeBit, particleAlphaOverLifeBit] });\n   * ```\n   */\n  extraBits?: B;\n}\n\n/**\n * Typed-array views over the particle vertex buffer, for code that writes particles itself\n * instead of through {@link ParticleContainer3D.setParticleAt | setParticleAt}\n *\n * All three views share one `ArrayBuffer`. Each particle is 4 consecutive vertices holding the\n * same data. Vertex `v`'s position starts at `f32[v * floatStride]`, and any other attribute sits\n * `offsets[name] / 4` elements after that. Call {@link ParticleContainer3D.markDirty | markDirty}\n * for what you write.\n * @category scene\n * @advanced\n */\nexport interface ParticleContainerViews {\n  /** The buffer as floats: position, size, rotation, and the float attributes of extra bits */\n  f32: Float32Array;\n  /** The buffer as 32-bit words, for packed attributes such as the `unorm8x4` colour */\n  u32: Uint32Array;\n  /** The buffer as 16-bit words, for the `unorm16x4` flipbook frame of a system with frames */\n  u16: Uint16Array;\n  /**\n   * Elements per vertex in {@link ParticleContainerViews.f32} and\n   * {@link ParticleContainerViews.u32}: 6 for a plain system, 8 with frames, more with extra bits'\n   * attributes; twice that in {@link ParticleContainerViews.u16}\n   */\n  floatStride: number;\n  /** Bytes per vertex: 24 for a plain system, 32 with frames, more with extra bits' attributes */\n  vertexStride: number;\n  /** Byte offset of each attribute within a vertex, by name, built-ins and extra bits' alike */\n  offsets: Readonly<Record<string, number>>;\n}\n\n/**\n * A fixed pool of camera-facing quads drawn in one call, which you move yourself\n *\n * Use it to draw a simulation you already have, such as a physics solver or a replayed recording.\n * For particles that move on their own, use `ParticleSystem3D` from `@pixi/3d/extras`, which\n * extends this class.\n *\n * Write particles with {@link ParticleContainer3D.setParticleAt | setParticleAt}, which allocates\n * nothing, then call {@link ParticleContainer3D.upload | upload}. A slot with a size of 0 draws\n * nothing.\n * @example\n * ```ts\n * const particles = new ParticleContainer3D({ texture: smoke, capacity: 500, blendMode: 'add' });\n * view.root.addChild(particles);\n *\n * // Drive it yourself:\n * particles.setParticleAt(0, x, y, z, 0.5, 0, 0xff6622, 0.8);\n * particles.upload();\n *\n * // One tint for the whole pool? Pack it once, then write through writePacked:\n * const tint = packParticleColor(0xff6622, 0.8);\n *\n * for (let i = 0; i < count; i++) particles.writePacked(i, x[i], y[i], z[i], 0.5, 0, tint);\n * particles.upload();\n * ```\n * @see {@link ParticleContainer3DOptions} for the constructor options.\n * @typeParam B - The extra bits, inferred from `extraBits`; they decide what\n * {@link ParticleContainer3D.setParticle} accepts. On the bare `ParticleContainer3D` type,\n * `setParticle` type-checks only the built-in attributes.\n * @category scene\n * @advanced\n */\nexport class ParticleContainer3D<B extends readonly ShaderBit[] = readonly ShaderBit[]> extends Mesh3D {\n  /** How many particles the pool holds, fixed at construction */\n  public readonly capacity: number = 0;\n\n  /** Whether particle positions are in world space or this node's, fixed at construction */\n  public readonly space: ParticleSpace;\n\n  /** Typed-array views over the vertex buffer; see {@link ParticleContainerViews} */\n  public readonly data: ParticleContainerViews;\n\n  /**\n   * The flipbook frames, in frame order; one entry for a single sprite\n   *\n   * A `ParticleSystem3D` with `frameMode` `'animate'` or `'overLife'` holds one texture over the\n   * whole sheet here instead.\n   */\n  public readonly textures: readonly Texture[];\n\n  /** Each frame's window in the vertex buffer's `unorm16x4` encoding; empty for a single sprite */\n  protected readonly _packedFrames: Uint16Array;\n  /** A flipbook's whole sheet, so the material's UV transform is identity, as `ParticleMaterial` requires */\n  private readonly _sheet: Texture | null;\n\n  private readonly _vertexBuffer: Buffer;\n  /**\n   * Shared with other containers until `destroy`; `aUV` goes last, since the vertex count comes from\n   * the first attribute and the shared corner buffer can be bigger\n   */\n  private readonly _quads: SharedQuadBuffers;\n  private readonly _floatStride: number = 0;\n  private readonly _sizeRotIndex: number = 0;\n  private readonly _colorIndex: number = 0;\n  /** `-1` when the system has one frame */\n  private readonly _uvFrameIndex: number = 0;\n  /** Built from the bits of `ParticleMaterial._bits` that declare attributes: the particle bit and the extra bits */\n  private readonly _attributes: Record<string, ParticleAttribute>;\n  private readonly _bytesPerParticle: number = 0;\n  private readonly _particleMaterial: ParticleMaterial;\n\n  /** Inclusive dirty particle range; `_dirtyHi < _dirtyLo` means nothing pending */\n  private _dirtyLo = 0;\n  private _dirtyHi = -1;\n\n  /** Highest slot written since the last `clear`; every slot past it is still zero */\n  private _written = -1;\n\n  /** Defaults for every new `ParticleContainer3D`; an option passed as `undefined` keeps its default */\n  public static override defaultOptions: ParticleContainer3DOptions = {\n    capacity: 1000,\n    billboard: 'spherical',\n    blendMode: 'normal',\n    space: 'world',\n    alphaMode: 'blend',\n    alphaCutoff: 0.5,\n  };\n\n  /**\n   * Creates a particle container; add it under a {@link View3D}'s root to draw it\n   * @param options - Construction options; see {@link ParticleContainer3DOptions}.\n   */\n  constructor(options: ParticleContainer3DOptions<B> = {}) {\n    const { capacity, billboard, blendMode, space, texture, extraBits, alphaMode, alphaCutoff, parent, ...rest } = {\n      ...ParticleContainer3D.defaultOptions,\n      ...definedProps(options),\n    };\n\n    if (capacity === undefined || !Number.isInteger(capacity) || capacity < 1) {\n      throw new Error(`[ParticleContainer3D] capacity must be a whole number of at least 1, got ${capacity}`);\n    }\n\n    const textures: readonly Texture[] =\n      texture === undefined\n        ? [Texture.WHITE]\n        : Array.isArray(texture)\n          ? (texture as readonly Texture[]).slice()\n          : [texture as Texture];\n    if (textures.length === 0) throw new Error('[ParticleContainer3D] texture: [] names no frames');\n\n    const packedFrames = packParticleFrames(textures);\n    const useFrames = textures.length > 1;\n    const sheet = useFrames ? new Texture({ source: textures[0].source }) : null;\n\n    const particleBit = getParticleBit({ billboard: billboard!, frames: useFrames, localSpace: space === 'local' });\n    const layout = buildParticleLayout(collectAttributes([particleBit, ...(extraBits ?? [])]));\n    const { vertexStride } = layout;\n    const floatStride = vertexStride / 4;\n    const vertexCount = capacity * VERTS_PER_PARTICLE;\n\n    const words = new ArrayBuffer(vertexCount * vertexStride);\n    const f32 = new Float32Array(words);\n    const vertexBuffer = new Buffer({\n      data: f32,\n      usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,\n      label: 'particle-vertices',\n      shrinkToFit: false,\n    });\n\n    const attributes: Record<string, Attribute> = {};\n\n    for (const [name, a] of Object.entries(layout.attributes)) {\n      attributes[name] = { buffer: vertexBuffer, format: a.format, stride: vertexStride, offset: a.offset };\n    }\n\n    const quads = acquireQuadBuffers(capacity);\n\n    attributes.aUV = { buffer: quads.corners, format: 'unorm8x2', stride: 4, offset: 0 };\n\n    const geometry = new Geometry3D({\n      attributes,\n      indices: quads.indices,\n      indexCount: capacity * INDICES_PER_PARTICLE,\n      topology: 'triangle-list',\n      dynamic: true,\n    });\n\n    const material = new ParticleMaterial({\n      texture: sheet ?? textures[0],\n      billboard,\n      useFrames,\n      localSpace: space === 'local',\n      blendMode,\n      alphaMode,\n      alphaCutoff,\n      extraBits,\n    });\n\n    super({ label: 'ParticleContainer3D', ...rest, geometry, material, castShadow: false, receiveShadow: false });\n\n    this.capacity = capacity;\n    this.space = space!;\n    this.textures = textures;\n    this._packedFrames = packedFrames;\n    this._sheet = sheet;\n    this._particleMaterial = material;\n    this._vertexBuffer = vertexBuffer;\n    this._quads = quads;\n    this._floatStride = floatStride;\n    this._sizeRotIndex = layout.attributes.aParticleSizeRot.index;\n    this._colorIndex = layout.attributes.aParticleColor.index;\n    this._uvFrameIndex = useFrames ? layout.attributes.aParticleUVFrame.index : -1;\n    this._attributes = layout.attributes;\n    this._bytesPerParticle = VERTS_PER_PARTICLE * vertexStride;\n    this._dirtyLo = capacity;\n\n    this.data = {\n      f32,\n      u32: new Uint32Array(words),\n      u16: new Uint16Array(words),\n      floatStride,\n      vertexStride,\n      offsets: Object.fromEntries(Object.entries(layout.attributes).map(([name, a]) => [name, a.offset])),\n    };\n\n    parent?.addChild(this);\n  }\n\n  /**\n   * The uniforms the composed bits declare in their `material` bindings, by name\n   *\n   * Assigning one uploads it, so `particles.uniforms.uParticleTime = t` is a whole per-frame update.\n   * A vector takes an array, such as `uGravity = [0, -9.8, 0]`; a `{ x, y, z }` object is silently\n   * ignored. A vector reads back as a `Float32Array`, and writing one of its elements isn't\n   * uploaded until you call `particles.material.update()`.\n   */\n  get uniforms(): Record<string, unknown> {\n    return this._particleMaterial.data;\n  }\n\n  /** Always `'none'`; particles face the camera through the `billboard` option instead */\n  override get billboardMode(): BillboardMode {\n    return 'none';\n  }\n\n  /**\n   * Ignored; a value other than `'none'` warns\n   * @param value - Ignored\n   */\n  override set billboardMode(value: BillboardMode) {\n    if (value === 'none') return;\n    warnOnce(\n      'pixijs-3d-particle-billboard-mode',\n      `[ParticleContainer3D] billboardMode '${value}' is ignored — a particle container orients each quad ` +\n        'itself. Pass the `billboard` option to the constructor instead.',\n    );\n  }\n\n  /**\n   * How particles blend over the scene; see {@link ParticleBlendMode}\n   *\n   * Ignored unless `alphaMode` is `'blend'`. A change rebuilds the draw state, so prefer setting it\n   * once at construction. Fog reaches the particles only if the blend mode was `'normal'` at\n   * construction; a later change doesn't turn it on or off.\n   */\n  get blendMode(): ParticleBlendMode {\n    return this._particleMaterial.state.blendMode as ParticleBlendMode;\n  }\n\n  /**\n   * Sets the blend mode\n   * @param value - How particles blend over the scene.\n   */\n  set blendMode(value: ParticleBlendMode) {\n    const material = this._particleMaterial;\n\n    if (material.alphaMode !== 'blend' || material.state.blendMode === value) return;\n    material.state.blendMode = value;\n    this.invalidate();\n  }\n\n  /**\n   * Writes one particle, to go out with the next {@link upload}\n   *\n   * Positions are in world space unless the container was built with `space: 'local'`. A `size`\n   * of 0 empties the slot. To write many particles with one tint, {@link writePacked} skips\n   * packing the colour on every call.\n   * @param index - Slot to write, 0 to `capacity - 1`.\n   * @param x - Particle centre x.\n   * @param y - Particle centre y.\n   * @param z - Particle centre z.\n   * @param size - World-space diameter.\n   * @param rotation - Spin in the quad's plane, in radians.\n   * @param color - `0xRRGGBB` tint, in display (sRGB) space.\n   * @param alpha - Opacity, 0 to 1.\n   * @param frame - Flipbook frame index, wrapping past the last frame; ignored with one frame.\n   */\n  public setParticleAt(\n    index: number,\n    x: number,\n    y: number,\n    z: number,\n    size: number,\n    rotation = 0,\n    color = 0xffffff,\n    alpha = 1,\n    frame = 0,\n  ): void {\n    this.writePacked(index, x, y, z, size, rotation, packParticleColor(color, alpha), frame);\n  }\n\n  /**\n   * {@link setParticleAt} with a colour already packed by {@link packParticleColor}\n   *\n   * Use it when a tint is fixed, or changes less often than you write particles: pack it once,\n   * then write many.\n   * @param index - Slot to write, 0 to `capacity - 1`.\n   * @param x - Particle centre x.\n   * @param y - Particle centre y.\n   * @param z - Particle centre z.\n   * @param size - World-space diameter.\n   * @param rotation - Spin in the quad's plane, in radians.\n   * @param packedColor - Tint and opacity as `packParticleColor` returns them.\n   * @param frame - Flipbook frame index, wrapping past the last frame; ignored with one frame.\n   */\n  public writePacked(\n    index: number,\n    x: number,\n    y: number,\n    z: number,\n    size: number,\n    rotation: number,\n    packedColor: number,\n    frame = 0,\n  ): void {\n    this._checkIndex(index);\n\n    const stride = this._floatStride;\n    const sizeRot = this._sizeRotIndex;\n    const colorIndex = this._colorIndex;\n    const { f32, u32 } = this.data;\n    let o = index * VERTS_PER_PARTICLE * stride;\n\n    for (let v = 0; v < VERTS_PER_PARTICLE; v++) {\n      f32[o] = x;\n      f32[o + 1] = y;\n      f32[o + 2] = z;\n      f32[o + sizeRot] = size;\n      f32[o + sizeRot + 1] = rotation;\n      u32[o + colorIndex] = packedColor;\n      o += stride;\n    }\n\n    if (this._uvFrameIndex >= 0) this._writeFrame(index, frame);\n\n    if (index < this._dirtyLo) this._dirtyLo = index;\n    if (index > this._dirtyHi) this._dirtyHi = index;\n    if (index > this._written) this._written = index;\n  }\n\n  /** Kept out of `writePacked`, so that stays small enough for V8 to inline into a caller's loop */\n  private _writeFrame(index: number, frame: number): void {\n    const stride = this._floatStride;\n    const uvFrame = this._uvFrameIndex;\n    const u16 = this.data.u16;\n    const n = this.textures.length;\n    const w = (((Math.floor(frame) % n) + n) % n) * 4;\n    const packed = this._packedFrames;\n    const u0 = packed[w];\n    const v0 = packed[w + 1];\n    const us = packed[w + 2];\n    const vs = packed[w + 3];\n    let o = index * VERTS_PER_PARTICLE * stride;\n\n    for (let v = 0; v < VERTS_PER_PARTICLE; v++) {\n      const h = (o + uvFrame) * 2;\n\n      u16[h] = u0;\n      u16[h + 1] = v0;\n      u16[h + 2] = us;\n      u16[h + 3] = vs;\n\n      o += stride;\n    }\n  }\n\n  /**\n   * Writes any of a particle's attributes by name, to go out with the next {@link upload}\n   *\n   * Every `float32` to `float32x4`, `unorm8x4` and `unorm16x4` attribute the composed bits declare\n   * can be written, built-ins included, so a bit that declares `aVel` makes `{ aVel: { x, y, z } }`\n   * valid here; other formats throw, so write them through {@link data}. Attributes not named keep\n   * their values. Each value takes the shape of its format; see {@link ParticleValues}. Declare your\n   * bits with `satisfies ShaderBit`, not `: ShaderBit`, or their names and shapes aren't\n   * type-checked.\n   *\n   * It looks each name up, so it's slower than {@link setParticleAt}: use it to spawn a particle,\n   * not to rewrite every particle every frame.\n   * @param index - Slot to write, 0 to `capacity - 1`.\n   * @param values - Attribute name to value. An undeclared name throws.\n   */\n  public setParticle(index: number, values: ParticleValues<B>): void {\n    this._checkIndex(index);\n\n    const record = values as Record<string, ParticleAttributeValue>;\n    const attributes = this._attributes;\n    const stride = this._floatStride;\n    const { f32, u32, u16 } = this.data;\n    const base = index * VERTS_PER_PARTICLE * stride;\n\n    for (const name in record) {\n      const attribute = attributes[name];\n\n      if (attribute === undefined) {\n        throw new Error(\n          `[ParticleContainer3D] no attribute '${name}'. The composed bits declare: ${Object.keys(attributes).join(', ')}`,\n        );\n      }\n\n      const value = record[name];\n\n      if (value === undefined) continue;\n\n      let o = base + attribute.index;\n\n      switch (attribute.kind) {\n        case 'float': {\n          const n = attribute.components;\n\n          expectShape(name, value, n);\n\n          if (n === 1) {\n            for (let v = 0; v < VERTS_PER_PARTICLE; v++, o += stride) f32[o] = value as unknown as number;\n          } else {\n            for (let v = 0; v < VERTS_PER_PARTICLE; v++, o += stride) {\n              f32[o] = value.x;\n              f32[o + 1] = value.y;\n              if (n > 2) f32[o + 2] = value.z;\n              if (n > 3) f32[o + 3] = value.w;\n            }\n          }\n          break;\n        }\n        case 'color': {\n          const packed = packParticleColor(Color.shared.setValue(value as ColorSource).toNumber(), Color.shared.alpha);\n\n          for (let v = 0; v < VERTS_PER_PARTICLE; v++, o += stride) u32[o] = packed;\n          break;\n        }\n        case 'unorm8': {\n          expectShape(name, value, 4);\n\n          const packed =\n            (unorm8(value.x) | (unorm8(value.y) << 8) | (unorm8(value.z) << 16) | (unorm8(value.w) << 24)) >>> 0;\n\n          for (let v = 0; v < VERTS_PER_PARTICLE; v++, o += stride) u32[o] = packed;\n          break;\n        }\n        case 'unorm16': {\n          expectShape(name, value, 4);\n\n          let h = o * 2;\n\n          for (let v = 0; v < VERTS_PER_PARTICLE; v++, h += stride * 2) {\n            u16[h] = unorm16(value.x);\n            u16[h + 1] = unorm16(value.y);\n            u16[h + 2] = unorm16(value.z);\n            u16[h + 3] = unorm16(value.w);\n          }\n          break;\n        }\n        default:\n          throw new Error(\n            `[ParticleContainer3D] setParticle has no packer for '${name}'. Write it through data.offsets.`,\n          );\n      }\n    }\n\n    if (index < this._dirtyLo) this._dirtyLo = index;\n    if (index > this._dirtyHi) this._dirtyHi = index;\n    if (index > this._written) this._written = index;\n  }\n\n  /**\n   * Marks particles `lo` to `hi`, inclusive, for the next {@link upload}\n   *\n   * Only needed after writing through {@link data} directly; the setters mark what they write.\n   * The upload is one range spanning everything marked, so two far-apart particles send all the\n   * slots between them. A range given the wrong way round marks the whole pool, and one past either\n   * end is clamped to it.\n   * @param lo - First particle in the range.\n   * @param hi - Last particle in the range, inclusive.\n   */\n  public markDirty(lo: number, hi: number): void {\n    const last = this.capacity - 1;\n\n    if (lo > hi) {\n      lo = 0;\n      hi = last;\n    }\n    if (lo < 0) lo = 0;\n    if (hi > last) hi = last;\n\n    if (lo < this._dirtyLo) this._dirtyLo = lo;\n    if (hi > this._dirtyHi) this._dirtyHi = hi;\n    if (hi > this._written) this._written = hi;\n  }\n\n  /** Sends the particles written since the last upload to the GPU; call it after each frame's writes */\n  public upload(): void {\n    const lo = this._dirtyLo;\n    const hi = this._dirtyHi;\n\n    if (hi < lo) return;\n\n    this._vertexBuffer.update((hi - lo + 1) * this._bytesPerParticle, lo * this._bytesPerParticle);\n\n    this._dirtyLo = this.capacity;\n    this._dirtyHi = -1;\n  }\n\n  /**\n   * Empties every slot, from the next {@link upload} on\n   *\n   * It costs up to the highest slot written since the last clear, not the whole capacity.\n   */\n  public clear(): void {\n    if (this._written < 0) return;\n\n    this.data.f32.fill(0, 0, (this._written + 1) * VERTS_PER_PARTICLE * this._floatStride);\n    this.markDirty(0, this._written);\n    this._written = -1;\n  }\n\n  /** Throws, since a write past the pool lands nowhere but its upload range runs past the buffer */\n  private _checkIndex(index: number): void {\n    if (!(index >= 0 && index < this.capacity)) {\n      throw new Error(`[ParticleContainer3D] particle ${index} is outside the pool of ${this.capacity}`);\n    }\n  }\n\n  /**\n   * Destroys the container and the geometry and material it built\n   *\n   * `children` works as for any node. `texture` frees a single sprite's texture but leaves a\n   * flipbook's frames; add `textureSource` to free the sheet behind them.\n   * @param options - Teardown flags; see {@link Destroy3DOptions}.\n   */\n  public override destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n\n    const geometry = this.geometry;\n    const material = this.material;\n\n    super.destroy(options);\n    geometry.destroy(false);\n    releaseQuadBuffers(this._quads);\n    this._vertexBuffer.destroy();\n    material.destroy(options);\n    this._sheet?.destroy(false);\n  }\n\n  /** Empty: under `geometry: true` the base would destroy the shared quad buffers; `destroy` keeps them */\n  protected override _destroyGeometry(): void {}\n}\n","import { ObservablePoint, Texture, definedProps } from 'pixi.js';\nimport type { ColorSource, PointData, TextureSourceLike } from 'pixi.js';\n\nimport { PlaneGeometry } from '../geometry/PlaneGeometry';\nimport type { AlphaMode, BaseMaterial3D } from '../materials/BaseMaterial3D';\nimport { FlatMaterial } from '../materials/flat/FlatMaterial';\nimport type { Vector3 } from '../math/vector/Vector3';\nimport type { Destroy3DOptions } from '../utils/Destroy3DOptions';\nimport { resolveDestroy3DFlag } from '../utils/Destroy3DOptions';\nimport { warnOnce } from '../utils/warnOnce';\nimport type { Size3D } from './Container3D';\nimport { Mesh3D } from './Mesh3D';\nimport type { BillboardMode, Mesh3DOptions } from './Mesh3D';\n\nfunction warnUnsizedTexture(): void {\n  warnOnce(\n    'pixijs-3d-sprite3d-size-unloaded',\n    '[@pixi/3d] A Sprite3D was sized in world units while its texture had no dimensions (still ' +\n      'loading?). The write was dropped — size the sprite after the texture resolves, or set ' +\n      '`scale` directly.',\n  );\n}\n\n/**\n * Constructor options for {@link Sprite3D}\n *\n * `texture`, `tint`, `alpha`, `alphaMode` and `alphaCutoff` shape the sprite's material. Without\n * `material` they build the unlit {@link FlatMaterial} the sprite makes; with one, those you set\n * are written into it, `texture` into its `baseColor` slot. The other {@link Mesh3DOptions} apply\n * too, and `label` defaults to `'Sprite3D'`.\n * @example\n * ```ts\n * const markerMaterial = new Material3D({ roughness: 0.8 });\n * const marker = new Sprite3D({\n *   material: markerMaterial,\n *   texture: markerTexture,\n *   alphaMode: 'mask',\n *   label: 'marker',\n *   parent: view.root,\n * });\n * ```\n * @category scene\n * @standard\n */\nexport interface Sprite3DOptions extends Omit<Mesh3DOptions, 'geometry' | 'material' | 'skeleton' | 'weights'> {\n  /**\n   * The material to draw the quad with; it needs a `baseColor` texture slot\n   *\n   * It can be shared between sprites. Left out, the sprite makes an unlit, double-sided\n   * {@link FlatMaterial} of its own and frees it on destroy.\n   * @example\n   * ```ts\n   * const leaves = new Material3D({ baseColorTexture: leafTexture, alphaMode: 'mask' });\n   * const card = new Sprite3D({ material: leaves, billboardMode: 'cylindrical' });\n   * ```\n   */\n  material?: BaseMaterial3D;\n  /**\n   * The image on the quad\n   *\n   * Its untrimmed pixel size times {@link Sprite3DOptions.pixelSize | pixelSize} sets the sprite's\n   * world size.\n   * @default a passed material's `baseColor` texture, else `Texture.WHITE`\n   * @example\n   * ```ts\n   * const tree = new Sprite3D({ texture: await Assets.load('tree.png') });\n   * ```\n   */\n  texture?: Texture;\n  /**\n   * Colour multiplied into the texture, any `ColorSource`, as with `Container.tint`\n   * @default 0xffffff\n   * @example\n   * ```ts\n   * const glow = new Sprite3D({ texture: glowTexture, tint: 0xffaa33 });\n   * ```\n   */\n  tint?: ColorSource;\n  /**\n   * Opacity multiplied into the texture's alpha\n   * @default 1\n   * @example\n   * ```ts\n   * const smoke = new Sprite3D({ texture: smokeTexture, alpha: 0.5 });\n   * ```\n   */\n  alpha?: number;\n  /**\n   * How the texture's alpha is used\n   *\n   * `'blend'` draws the sprite in the transparent pass, which sorts back to front every frame: the\n   * right default for soft edges. `'mask'` cuts away pixels below\n   * {@link Sprite3DOptions.alphaCutoff | alphaCutoff} in the opaque pass, with depth writes and no\n   * sorting, so it batches better than `'blend'`; it's the usual pick for foliage. `'opaque'` draws\n   * the whole quad solid.\n   * @default 'blend'\n   * @example\n   * ```ts\n   * const leaf = new Sprite3D({ texture: leafTexture, alphaMode: 'mask' });\n   * ```\n   */\n  alphaMode?: AlphaMode;\n  /**\n   * Alpha below which `'mask'` mode cuts a pixel away\n   * @default 0.5\n   * @example\n   * ```ts\n   * const leaf = new Sprite3D({ texture: leafTexture, alphaMode: 'mask', alphaCutoff: 0.3 });\n   * ```\n   */\n  alphaCutoff?: number;\n  /**\n   * How the quad turns to face the camera; see {@link BillboardMode}\n   *\n   * Sprites with different modes don't share a draw; the {@link Sprite3D} class notes say when\n   * that costs draw calls.\n   * @default 'spherical'\n   * @example\n   * ```ts\n   * const tree = new Sprite3D({ texture: treeTexture, billboardMode: 'cylindrical' });\n   * ```\n   */\n  billboardMode?: BillboardMode;\n  /**\n   * Which point of the image sits on the node's origin, as a fraction of its size, with `y`\n   * measured down from the top edge\n   *\n   * A single number sets both axes. `0.5` centres the image, and `{ x: 0.5, y: 1 }` stands it on\n   * the origin. Left out, the texture's `defaultAnchor` applies, as on pixi's 2D `Sprite`; without\n   * one it's centred, unlike the 2D `Sprite`'s `(0, 0)`. The {@link Sprite3D} class notes cover how\n   * it behaves in each billboard mode.\n   * @default 0.5\n   * @example\n   * ```ts\n   * const tree = new Sprite3D({ texture: treeTexture, anchor: { x: 0.5, y: 1 } });\n   * ```\n   */\n  anchor?: PointData | number;\n  /**\n   * World units per texture pixel, which sets the sprite's size\n   *\n   * At the default 0.01 a 512 px texture is 5.12 units across, which suits a scene measured in\n   * metres.\n   * @default 0.01\n   * @example\n   * ```ts\n   * const tile = new Sprite3D({ texture: tileTexture, pixelSize: 1 / 32 });\n   * ```\n   */\n  pixelSize?: number;\n  /**\n   * The sprite's width in world units, in place of\n   * {@link Sprite3DOptions.pixelSize | pixelSize} on this axis\n   *\n   * Pass only `width` or only `height` and the other follows the texture's aspect ratio:\n   * `{ height: 4 }` on a 128×200 texture gives 2.56 × 4. Pass both to stretch the image to that\n   * box. It ends up in `scale`, as on pixi's 2D `Sprite`, but unlike there a lone `width` or\n   * `height` keeps the aspect ratio; the {@link Sprite3D#width} and {@link Sprite3D#height}\n   * accessors set one axis each.\n   *\n   * It's measured against the texture once, at construction. A texture still loading has no size,\n   * so the value is dropped with a warning; size the sprite once it loads.\n   * @example\n   * ```ts\n   * const sign = new Sprite3D({ texture: signTexture, width: 2 });\n   * ```\n   */\n  width?: number;\n  /**\n   * The sprite's height in world units, in place of\n   * {@link Sprite3DOptions.pixelSize | pixelSize} on this axis; see\n   * {@link Sprite3DOptions.width} for how it combines with `width`\n   * @example\n   * ```ts\n   * const tree = new Sprite3D({ texture: treeTexture, height: 4 });\n   * ```\n   */\n  height?: number;\n  /**\n   * Whether the sprite casts shadows\n   *\n   * Off by default because a billboarded sprite casts the shadow of its unturned quad, which\n   * doesn't turn with the camera and can thin to a sliver. In `'none'` mode a sprite casts once it's\n   * `'opaque'` or `'mask'` and its front faces the light, though a masked one's shadow doesn't show\n   * its holes yet. A blended one, the default, casts nothing.\n   * @default false\n   * @example\n   * ```ts\n   * const sign = new Sprite3D({\n   *   texture: signTexture,\n   *   billboardMode: 'none',\n   *   alphaMode: 'opaque',\n   *   castShadow: true,\n   * });\n   * ```\n   */\n  castShadow?: boolean;\n  /**\n   * Whether the sprite is shadowed\n   *\n   * Only a lit material takes shadows, so it does nothing with the default {@link FlatMaterial}.\n   * @default true\n   * @example\n   * ```ts\n   * const card = new Sprite3D({ material: litLeaves, receiveShadow: false });\n   * ```\n   */\n  receiveShadow?: boolean;\n}\n\n/**\n * A textured quad in the 3D scene, sized from its texture and, by default, turned to face the\n * camera\n *\n * It's `texture pixels × pixelSize` world units across, with the familiar sprite API: `anchor`,\n * `tint`, `alpha`, `width` and `height`, plus `alphaMode` for cutouts. It draws with an unlit\n * {@link FlatMaterial} unless you give it another material; a {@link Material3D} gives a lit\n * billboard, which a flat stand-in needs to match the lighting of the model it replaces.\n *\n * ## Batching\n *\n * Sprites that share a material type, billboard mode, alpha mode and image source, such as the\n * frames of one sprite sheet, draw together as one instanced draw. On WebGPU, sprites with\n * materials of their own, as each sprite makes by default, need more than 16 in a row for that;\n * 16 or fewer draw one each. Switching frames within a sheet costs almost nothing. The opaque pass\n * (`'mask'` and `'opaque'`) groups mixed modes and sources well. The transparent pass (`'blend'`)\n * sorts back to front, so every change of mode or source along that order starts a new draw: give\n * each blended effect one mode and one sprite sheet. Tint, alpha, size and position can vary\n * freely.\n *\n * Turning to face the camera costs no CPU time; the GPU does it. Hundreds to a few thousand\n * sprites is what it's built for. For tens of thousands that you set and forget, fill\n * {@link BatchedMesh3D} slots instead: give each one {@link PlaneGeometry.spriteQuad}, a matrix\n * whose X and Y scale carry the texture's world size, and a `billboardMode`.\n *\n * ## Anchor and origin\n *\n * - `'none'`: the anchor is exact, as on a 2D sprite.\n * - `'cylindrical'`: `anchor.y` is exact, so a tree anchored at its feet turns around its base.\n *   `anchor.x` swings around the spin axis.\n * - `'spherical'`: an off-centre anchor drifts as the camera orbits. The centred default is exact.\n *\n * `origin` is in world size units, texture pixels × `pixelSize` before `scale`, and applies after\n * `anchor`. A 200×400 px texture at the default `pixelSize` is 2 × 4 units, so with the centred\n * anchor `origin = { x: 1, y: 2, z: 0 }` turns the sprite around its top-right corner. Under a\n * billboard mode it behaves like an off-centre anchor.\n *\n * ## Limitations\n *\n * - Children inherit the texture size, so children and `toLocal` work in quad units, where the\n *   image spans -0.5 to 0.5. Treat a sprite as a leaf node.\n * - {@link Container3D#reparentChild | reparentChild} would apply the texture size and anchor\n *   twice, so it isn't supported; plain `addChild` and `removeChild` are fine.\n * - A `ContainerTexture` draws upside down on a sprite.\n * @example\n * ```ts\n * import { Sprite3D, View3D } from '@pixi/3d';\n *\n * const glow = new Sprite3D({ texture: glowTexture, tint: 0xffaa33 });\n * glow.position.set(0, 1.5, 0);\n * view.root.addChild(glow);\n *\n * // A 4-unit-tall tree standing on the ground, cut out rather than blended.\n * // Width follows the texture's aspect ratio.\n * const tree = new Sprite3D({\n *   texture: treeTexture,\n *   billboardMode: 'cylindrical',\n *   anchor: { x: 0.5, y: 1 },\n *   alphaMode: 'mask',\n *   height: 4,\n * });\n *\n * // Later, in world units; each accessor writes one axis of `scale`.\n * tree.height = 6;\n * ```\n * @see {@link Sprite3DOptions} For the constructor options.\n * @category scene\n * @standard\n */\nexport class Sprite3D extends Mesh3D {\n  /**\n   * Defaults for every new `Sprite3D`; an option passed as `undefined` keeps its default\n   *\n   * `tint`, `alpha`, `alphaMode` and `alphaCutoff` apply only to the {@link FlatMaterial} the\n   * sprite makes, never to a material you pass.\n   * @example\n   * ```ts\n   * // Author against a 32px-per-unit tile set:\n   * Sprite3D.defaultOptions.pixelSize = 1 / 32;\n   * ```\n   */\n  public static defaultOptions: Pick<\n    Required<Sprite3DOptions>,\n    'billboardMode' | 'tint' | 'alpha' | 'alphaMode' | 'alphaCutoff' | 'pixelSize' | 'castShadow' | 'receiveShadow'\n  > = {\n    billboardMode: 'spherical',\n    tint: 0xffffff,\n    alpha: 1,\n    alphaMode: 'blend',\n    alphaCutoff: 0.5,\n    pixelSize: 0.01,\n    castShadow: false,\n    receiveShadow: true,\n  };\n\n  /**\n   * Creates a self-contained sprite from a texture, or from anything `Texture.from` accepts: an\n   * asset alias or URL already in the cache, an image, a canvas or a `TextureSource`\n   *\n   * The 3D counterpart of pixi's `Sprite.from`. An alias the cache doesn't have draws nothing, and\n   * pixi warns; load the asset first.\n   * @example\n   * ```ts\n   * await Assets.load('tree.png');\n   * const tree = Sprite3D.from('tree.png');\n   * ```\n   * @param source - The texture, or the source to build one from.\n   * @param skipCache - Build a fresh texture instead of reusing a cached one for `source`; an alias\n   * or URL always comes from the cache.\n   * @returns A sprite drawing that texture on its own {@link FlatMaterial}.\n   */\n  public static from(source: Texture | TextureSourceLike, skipCache = false): Sprite3D {\n    if (source instanceof Texture) return new Sprite3D(source);\n\n    return new Sprite3D(Texture.from(source, skipCache) ?? Texture.EMPTY);\n  }\n\n  private _texture: Texture;\n  private _pixelSize = 0;\n  private readonly _anchor: ObservablePoint;\n  private readonly _ownsMaterial: boolean;\n\n  /** Only `dynamic` textures get it, as on pixi's 2D `Sprite`, so frame swaps stay cheap */\n  private readonly _onTextureUpdate = (): void => {\n    this.material._deriveUvFrame();\n    this._onUpdate();\n  };\n\n  /**\n   * Creates a `Sprite3D`; add it under {@link View3D.root | view.root} to draw it\n   *\n   * A bare `Texture` is short for `{ texture }`, as with pixi's 2D `Sprite`. Throws when a\n   * `material` you pass has no `baseColor` slot.\n   * @example\n   * ```ts\n   * const glow = new Sprite3D(glowTexture);\n   * ```\n   * @param options - Construction options, or the texture to draw; see {@link Sprite3DOptions}.\n   */\n  constructor(options: Sprite3DOptions | Texture = {}) {\n    if (options instanceof Texture) options = { texture: options };\n\n    const explicit = definedProps(options);\n    /**\n     * `width`, `height` and `parent` stay out of `Mesh3D`'s constructor, which would apply them\n     * before the sprite has its texture\n     */\n    const {\n      material: supplied,\n      texture,\n      tint,\n      alpha,\n      alphaMode,\n      alphaCutoff,\n      pixelSize,\n      anchor,\n      width,\n      height,\n      parent,\n      castShadow,\n      receiveShadow,\n      billboardMode,\n      ...rest\n    } = { ...Sprite3D.defaultOptions, ...explicit };\n\n    if (supplied && supplied._slotByName.baseColor === undefined) {\n      throw new Error(\n        '[Sprite3D] The supplied material has no `baseColor` texture slot, so the sprite has ' +\n          'no image to size itself from. Use a material built from a baseColor-bearing bit ' +\n          '(FlatMaterial, Material3D, PhongMaterial, ...).',\n      );\n    }\n\n    super({\n      label: 'Sprite3D',\n      ...rest,\n      geometry: PlaneGeometry.spriteQuad,\n      material:\n        supplied ??\n        new FlatMaterial({\n          baseColorTexture: texture ?? Texture.WHITE,\n          baseColor: tint,\n          alpha,\n          alphaMode,\n          alphaCutoff,\n          doubleSided: true,\n        }),\n      castShadow,\n      receiveShadow,\n      billboardMode,\n    });\n\n    this._ownsMaterial = supplied === undefined;\n\n    this._pixelSize = pixelSize;\n    this._texture = this.material.textures.baseColor ?? Texture.WHITE;\n    if (this._texture.dynamic) this._texture.on('update', this._onTextureUpdate);\n\n    if (supplied) {\n      if (texture) this.texture = texture;\n      if (explicit.tint !== undefined) this.tint = explicit.tint;\n      if (explicit.alpha !== undefined) this.alpha = explicit.alpha;\n      if (explicit.alphaMode !== undefined) this.alphaMode = explicit.alphaMode;\n      if (explicit.alphaCutoff !== undefined) this.alphaCutoff = explicit.alphaCutoff;\n    }\n\n    this._anchor = new ObservablePoint({ _onUpdate: () => this._onUpdate() }, 0.5, 0.5);\n    const initialAnchor = anchor ?? this._texture.defaultAnchor;\n    if (initialAnchor !== undefined) this.anchor = initialAnchor;\n\n    if (width !== undefined || height !== undefined) this._fitSize(width, height);\n    parent?.addChild(this);\n  }\n\n  private _fitSize(width: number | undefined, height: number | undefined): void {\n    const { width: pixelWidth, height: pixelHeight } = this._texture.orig;\n    if (pixelWidth === 0 || pixelHeight === 0) {\n      warnUnsizedTexture();\n      return;\n    }\n\n    this.width = width ?? (height! * pixelWidth) / pixelHeight;\n    this.height = height ?? (width! * pixelHeight) / pixelWidth;\n  }\n\n  /**\n   * The image on the quad\n   *\n   * Assigning another re-sizes the sprite; switching frames within one sprite sheet is cheap. It\n   * writes the material's `baseColor` slot, so on a shared material it changes every sprite using\n   * it. A sprite follows in-place changes only to a texture that was `dynamic` when it got it, as\n   * pixi's 2D `Sprite` does.\n   * @example\n   * ```ts\n   * coin.texture = sheet.textures[`coin_${frame}.png`];\n   * ```\n   */\n  get texture(): Texture {\n    return this._texture;\n  }\n\n  /**\n   * Swaps the image and re-sizes the sprite; rotated sprite sheet frames work too\n   * @param value - Image to draw on the quad.\n   */\n  set texture(value: Texture) {\n    if (this._texture === value) return;\n\n    if (this._texture.dynamic) this._texture.off('update', this._onTextureUpdate);\n    this._texture = value;\n    if (value.dynamic) value.on('update', this._onTextureUpdate);\n\n    this.material.textures.baseColor = value;\n    this._onUpdate();\n  }\n\n  /**\n   * Which point of the image sits on the node's origin, as a fraction of its size, with `y`\n   * measured down from the top edge\n   *\n   * `(0.5, 0.5)` is centred, and `y = 1` stands the sprite on the origin. Assign a point or a\n   * single number for both axes, or change it in place. The {@link Sprite3D} class notes cover\n   * how it behaves in each billboard mode.\n   * @example\n   * ```ts\n   * tree.anchor.set(0.5, 1);\n   * ```\n   */\n  get anchor(): ObservablePoint {\n    return this._anchor;\n  }\n\n  /**\n   * Sets the anchor from a point or a single number for both axes\n   * @param value - Fractions of the image's size, `y` measured from its top edge.\n   */\n  set anchor(value: PointData | number) {\n    if (typeof value === 'number') {\n      this._anchor.set(value);\n    } else {\n      this._anchor.copyFrom(value);\n    }\n  }\n\n  /**\n   * World units per texture pixel, which sets the sprite's size without touching `scale`\n   * @example\n   * ```ts\n   * sprite.pixelSize = 1 / 64;\n   * ```\n   */\n  get pixelSize(): number {\n    return this._pixelSize;\n  }\n\n  /**\n   * Re-sizes the sprite without touching `scale`\n   * @param value - World units per texture pixel.\n   */\n  set pixelSize(value: number) {\n    if (this._pixelSize === value) return;\n    this._pixelSize = value;\n    this._onUpdate();\n  }\n\n  /**\n   * Colour multiplied into the texture\n   *\n   * As with `Container.tint`, it takes any `ColorSource` and reads back as a hex number. Opacity\n   * is {@link Sprite3D#alpha}. It writes the material's `baseColor`, so on a shared material it\n   * recolours every sprite using it.\n   * @example\n   * ```ts\n   * glow.tint = 'orange';\n   * ```\n   */\n  get tint(): number {\n    return this.material.baseColor;\n  }\n\n  /**\n   * Sets the colour multiplied into the texture\n   * @param value - Colour to multiply by.\n   */\n  set tint(value: ColorSource) {\n    this.material.baseColor = value;\n  }\n\n  /**\n   * Opacity multiplied into the texture's alpha\n   *\n   * It writes the material, so on a shared material it fades every sprite using it.\n   * @example\n   * ```ts\n   * ghost.alpha = 0.4;\n   * ```\n   */\n  get alpha(): number {\n    return this.material.alpha;\n  }\n\n  /**\n   * Sets the opacity multiplied into the texture's alpha\n   * @param value - Opacity from 0 to 1.\n   */\n  set alpha(value: number) {\n    this.material.alpha = value;\n  }\n\n  /**\n   * How the texture's alpha is used; see {@link Sprite3DOptions.alphaMode}\n   *\n   * A blended sprite casts no shadow. It writes the material, so on a shared material it changes\n   * every sprite using it.\n   * @example\n   * ```ts\n   * leaf.alphaMode = 'mask';\n   * ```\n   */\n  get alphaMode(): AlphaMode {\n    return this.material.alphaMode;\n  }\n\n  /**\n   * Sets how the texture's alpha is used\n   * @param value - How alpha is used.\n   */\n  set alphaMode(value: AlphaMode) {\n    if (this.material.alphaMode === value) return;\n    this.material.alphaMode = value;\n  }\n\n  /**\n   * Alpha below which `'mask'` mode cuts a pixel away; it writes the material\n   * @example\n   * ```ts\n   * leaf.alphaCutoff = 0.3;\n   * ```\n   */\n  get alphaCutoff(): number {\n    return this.material.alphaCutoff;\n  }\n\n  /**\n   * Sets the alpha below which `'mask'` mode cuts a pixel away\n   * @param value - Alpha from 0 to 1.\n   */\n  set alphaCutoff(value: number) {\n    this.material.alphaCutoff = value;\n  }\n\n  /**\n   * The sprite's width in world units: `|scale.x| × texture width × pixelSize`\n   *\n   * Assigning writes `scale.x` and leaves {@link Sprite3D#height} alone, as on pixi's 2D `Sprite`;\n   * to keep the aspect ratio, pass {@link Sprite3DOptions.width | width} at construction.\n   * @example\n   * ```ts\n   * sign.width = 2;\n   * ```\n   */\n  public override get width(): number {\n    return Math.abs(this.scale.x) * this._texture.orig.width * this._pixelSize;\n  }\n\n  /**\n   * Sets `scale.x` for a width in world units\n   * @param value - Width in world units.\n   */\n  public override set width(value: number) {\n    const scale = this._scaleForWorldSize(value, this._texture.orig.width, this.scale.x);\n    if (scale !== null) this.scale.x = scale;\n  }\n\n  /**\n   * The sprite's height in world units: `|scale.y| × texture height × pixelSize`\n   *\n   * Assigning writes `scale.y` only; see {@link Sprite3D#width}.\n   * @example\n   * ```ts\n   * tree.height = 6;\n   * ```\n   */\n  public override get height(): number {\n    return Math.abs(this.scale.y) * this._texture.orig.height * this._pixelSize;\n  }\n\n  /**\n   * Sets `scale.y` for a height in world units\n   * @param value - Height in world units.\n   */\n  public override set height(value: number) {\n    const scale = this._scaleForWorldSize(value, this._texture.orig.height, this.scale.y);\n    if (scale !== null) this.scale.y = scale;\n  }\n\n  /**\n   * Returns the sprite's size in world units, from the texture like {@link Sprite3D#width}\n   *\n   * A sprite is flat, so `depth` is always 0.\n   * @example\n   * ```ts\n   * const { width, height } = sprite.getSize();\n   * ```\n   * @param out - Object to write into; a new one when omitted\n   * @returns The size, written into `out`\n   */\n  public override getSize(out: Size3D = { width: 0, height: 0, depth: 0 }): Size3D {\n    out.width = this.width;\n    out.height = this.height;\n    out.depth = 0;\n\n    return out;\n  }\n\n  /**\n   * Sizes the sprite in world units, from the texture like {@link Sprite3D#width}\n   *\n   * A single number sets both axes, and a missing `height` takes the width, as in pixi's 2D\n   * `Sprite`. A sprite is flat, so any `depth` is ignored.\n   * @param value - Target width, or an object with `width` and optional `height`\n   * @param height - Target height; defaults to the width\n   * @param _depth - Ignored; a sprite is flat\n   * @example\n   * ```ts\n   * sprite.setSize(2, 1);\n   * sprite.setSize({ width: 3 }); // 3 × 3\n   * ```\n   */\n  public override setSize(\n    value: number | (Pick<Size3D, 'width'> & Partial<Size3D>),\n    height?: number,\n    _depth?: number,\n  ): void {\n    if (typeof value === 'object') {\n      height = value.height ?? value.width;\n      value = value.width;\n    } else {\n      height ??= value;\n    }\n\n    this.width = value;\n    this.height = height;\n  }\n\n  private _scaleForWorldSize(size: number, pixels: number, currentScale: number): number | null {\n    if (pixels === 0) {\n      warnUnsizedTexture();\n\n      return null;\n    }\n\n    return (size / (pixels * this._pixelSize)) * (Math.sign(currentScale) || 1);\n  }\n\n  /**\n   * Rebuilds {@link Container3D.localTransform | localTransform} with the texture's world size and\n   * the anchor offset in it\n   *\n   * A texture with no size yet, such as one still loading, shrinks the quad to a point.\n   * @advanced\n   */\n  public override updateLocalTransform(): void {\n    const quat = this.quaternion;\n\n    if (this.rotationDirty) {\n      this.rotationDirty = false;\n\n      const rx = this.rotation._x;\n      const ry = this.rotation._y;\n      const rz = this.rotation._z;\n\n      const c1 = Math.cos(rx / 2);\n      const c2 = Math.cos(ry / 2);\n      const c3 = Math.cos(rz / 2);\n\n      const s1 = Math.sin(rx / 2);\n      const s2 = Math.sin(ry / 2);\n      const s3 = Math.sin(rz / 2);\n\n      quat._x = s1 * c2 * c3 + c1 * s2 * s3;\n      quat._y = c1 * s2 * c3 - s1 * c2 * s3;\n      quat._z = c1 * c2 * s3 + s1 * s2 * c3;\n      quat._w = c1 * c2 * c3 - s1 * s2 * s3;\n    }\n\n    const x = quat._x;\n    const y = quat._y;\n    const z = quat._z;\n    const w = quat._w;\n\n    const x2 = x + x;\n    const y2 = y + y;\n    const z2 = z + z;\n\n    const xx = x * x2;\n    const xy = x * y2;\n    const xz = x * z2;\n    const yy = y * y2;\n    const yz = y * z2;\n    const zz = z * z2;\n    const wx = w * x2;\n    const wy = w * y2;\n    const wz = w * z2;\n\n    const out = this.localTransform.elements;\n\n    const pixelSize = this._pixelSize;\n    const sx = this.scale._x * (this._texture.orig.width * pixelSize);\n    const sy = this.scale._y * (this._texture.orig.height * pixelSize);\n    const sz = this.scale._z;\n\n    out[0] = (1 - (yy + zz)) * sx;\n    out[1] = (xy + wz) * sx;\n    out[2] = (xz - wy) * sx;\n    out[4] = (xy - wz) * sy;\n    out[5] = (1 - (xx + zz)) * sy;\n    out[6] = (yz + wx) * sy;\n    out[8] = (xz + wy) * sz;\n    out[9] = (yz - wx) * sz;\n    out[10] = (1 - (xx + yy)) * sz;\n\n    const dx = 0.5 - this._anchor._x;\n    const dy = this._anchor._y - 0.5;\n\n    out[12] = this.position._x + dx * out[0] + dy * out[4];\n    out[13] = this.position._y + dx * out[1] + dy * out[5];\n    out[14] = this.position._z + dx * out[2] + dy * out[6];\n\n    if (this._origin !== null) this._addOriginOffset();\n  }\n\n  /**\n   * Reads `quaternion` and `scale` rather than the matrix, whose basis carries a size that can be 0\n   * @param out - Receives the offset.\n   */\n  protected override _getOriginOffset(out: Vector3): Vector3 {\n    const origin = this._origin!;\n\n    const ox = origin._x;\n    const oy = origin._y;\n    const oz = origin._z;\n    const vx = ox * this.scale._x;\n    const vy = oy * this.scale._y;\n    const vz = oz * this.scale._z;\n\n    const quat = this.quaternion;\n    const x = quat._x;\n    const y = quat._y;\n    const z = quat._z;\n    const w = quat._w;\n\n    const x2 = x + x;\n    const y2 = y + y;\n    const z2 = z + z;\n\n    const xx = x * x2;\n    const xy = x * y2;\n    const xz = x * z2;\n    const yy = y * y2;\n    const yz = y * z2;\n    const zz = z * z2;\n    const wx = w * x2;\n    const wy = w * y2;\n    const wz = w * z2;\n\n    out.x = ox - ((1 - (yy + zz)) * vx + (xy - wz) * vy + (xz + wy) * vz);\n    out.y = oy - ((xy + wz) * vx + (1 - (xx + zz)) * vy + (yz - wx) * vz);\n    out.z = oz - ((xz - wy) * vx + (yz + wx) * vy + (1 - (xx + yy)) * vz);\n\n    return out;\n  }\n\n  /**\n   * Destroys the sprite; the shared quad geometry always survives, even `destroy(true)`\n   *\n   * A material the sprite made is always destroyed; one you gave it stays unless you pass\n   * `material`. `texture` frees the sprite's texture, as on pixi's 2D `Sprite`, and\n   * `textureSource` its source too; `textureSource` alone frees nothing. Children get your options\n   * unchanged.\n   * @example\n   * ```ts\n   * sprite.destroy({ texture: true, textureSource: true });\n   * ```\n   * @param options - Teardown flags; see {@link Destroy3DOptions}.\n   */\n  public override destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n\n    const texture = this._texture;\n    const material = this.material;\n    const materialWasLive = !material.destroyed;\n    if (texture.dynamic) texture.off('update', this._onTextureUpdate);\n\n    super.destroy(options);\n\n    const cascadeFreedMaterial = materialWasLive && material.destroyed;\n    if (!cascadeFreedMaterial) {\n      if (this._ownsMaterial && materialWasLive) {\n        material.destroy(options);\n      } else if (resolveDestroy3DFlag(options, 'texture')) {\n        texture.destroy(resolveDestroy3DFlag(options, 'textureSource'));\n      }\n    }\n\n    this._texture = null!;\n  }\n\n  /** Spares the quad every sprite shares, while children still get the caller's `geometry` flag */\n  protected override _destroyGeometry(): void {}\n}\n","import type { WebGLRenderer, WebGPURenderer } from 'pixi.js';\n\nimport type { ShadowRenderPassGl } from '../../core/gl/ShadowRenderPassGl';\nimport type { ShadowRenderPassGpu } from '../../core/gpu/ShadowRenderPassGpu';\nimport { RenderGraph } from '../../core/render-graph/RenderGraph';\nimport type { ColorHandle, DepthHandle } from '../../core/render-graph/ResourceHandle';\nimport type { SceneOutput } from '../../core/render-graph/SceneOutput';\nimport { collectSceneOutputs } from '../../core/render-graph/sceneOutputs';\nimport type { GlobalTextureBindings } from '../../core/render-graph/TextureBinding';\nimport { BackgroundPass } from '../../core/render-passes/background/BackgroundPass';\nimport { BlendedRefractionPass } from '../../core/render-passes/blended-refraction/BlendedRefractionPass';\nimport { CopyDepthPass } from '../../core/render-passes/copy-depth/CopyDepthPass';\nimport { CopyOpaquePass } from '../../core/render-passes/copy-opaque/CopyOpaquePass';\nimport { DepthClearPass } from '../../core/render-passes/depth-clear/DepthClearPass';\nimport { OpaqueRenderPass } from '../../core/render-passes/opaque/OpaqueRenderPass';\nimport type { RenderSession } from '../../core/render-passes/RenderSession';\nimport { TransmissionRenderPass } from '../../core/render-passes/transmission/TransmissionRenderPass';\nimport { TransparentRenderPass } from '../../core/render-passes/transparent/TransparentRenderPass';\nimport { assertFloatRenderable } from '../../core/textures/floatRenderTargets';\nimport { isResolvableFormat } from '../../core/textures/isResolvableFormat';\nimport { OutputPass } from '../../post-processing/effects/OutputPass';\nimport { PostEffect } from '../../post-processing/effects/PostEffect';\nimport type { Pass3D, PassContext } from '../../post-processing/Pass3D';\nimport type { ToneMapping } from '../View3D';\n\n/**\n * Handles to the textures {@link createDefaultGraph3D} shares between its passes, so a pass added\n * on top can sample them instead of copying the scene again\n *\n * The opaque copies can be larger than the view. The view fills a sub-rect at the texture's origin,\n * so scale view UVs by the camera's `uViewportUVScale` before sampling. They match the scene's\n * resolution texel for texel.\n * @category rendering\n * @advanced\n */\nexport interface DefaultGraph3DHandles {\n  /** Copy of the opaque scene's colour, with mipmaps, as transmissive and refractive materials see it */\n  opaqueColor: ColorHandle;\n  /** Copy of the opaque scene's depth; {@link CopyDepthPass} says when it's taken */\n  opaqueDepth: DepthHandle;\n  /** The shadow-map array, one layer per light or cascade */\n  shadowMap: DepthHandle;\n}\n\n/**\n * Options for {@link createDefaultGraph3D}: the same object a {@link View3D} hands its\n * custom `graph` builder, so a builder that starts from the default graph forwards it verbatim\n * @category rendering\n * @advanced\n */\nexport interface DefaultGraph3DOptions {\n  /**\n   * Draw the scene into its own texture, then onto the screen, instead of straight to the screen\n   *\n   * Any enabled post effect in `passes`, or entry in `sceneOutputs`, turns it on. A {@link View3D}\n   * sets it from {@link View3DOptions#composite}, and while its {@link View3D#resolution} differs\n   * from its target's, so a custom builder that drops it draws at the target's resolution.\n   */\n  composite?: boolean;\n  /** The view's user passes; each contributes at its own stage, post effects in array order within their stage */\n  passes?: readonly Pass3D[];\n  /**\n   * Scene outputs to attach besides the ones the enabled `passes`\n   * {@link Pass3D#requiredOutputs | require}; see {@link SceneOutput}\n   *\n   * Set it in a custom graph builder whose own passes use outputs. An output in both lists is\n   * attached once. Any entry turns `composite` on.\n   */\n  sceneOutputs?: readonly SceneOutput[];\n  /**\n   * The view's tone mapping, which the output pass applies when an enabled `'beforeToneMapping'`\n   * effect keeps the scene linear\n   */\n  toneMapping: ToneMapping;\n  /** The view's global texture bindings; forward the value the view passes in */\n  globalTextureBindings: GlobalTextureBindings;\n}\n\n/**\n * Builds the render graph a {@link View3D} uses unless its `graph` option supplies one\n *\n * Start from it in a custom `graph` builder to add passes the {@link Pass3D} stages can't\n * express. The passes run in this order, with each user pass built at its {@link PassStage}:\n *\n * 1. The shadow pass.\n * 2. `'beforeOpaque'` user passes.\n * 3. A depth reset over the view's rect, which clears each scene output but keeps any colour drawn\n *    before it, then the background and the opaque scene.\n * 4. `'afterOpaque'` user passes.\n * 5. Copies of the opaque depth and colour, then the transmissive, blended-refraction and\n *    transparent scene. Blended-refraction draws don't write scene outputs.\n * 6. `'afterTransparent'` user passes.\n * 7. The `'beforeToneMapping'` effects, in array order, then the tone curve, then the\n *    `'afterToneMapping'` effects. Unless the tone mapping is `'custom'`, an output pass applies the\n *    curve after a `'beforeToneMapping'` effect, and the scene draw applies it otherwise.\n *\n * In composite mode the scene draws into textures at {@link View3D#resolution}, which the graph's\n * other textures inherit unless an effect sets its own. The scene's textures are multisampled when\n * the canvas has `antialias`, unless a scene output's format can't be (see {@link SceneOutput}).\n * Each effect reads what the one before it wrote, and the last step stretches the image onto the\n * view's rect.\n *\n * With a `'beforeToneMapping'` effect enabled, the scene colour and every colour texture made\n * without a format are `rgba16float`, so brightness above 1 reaches each of those effects. Unless\n * the tone mapping is `'custom'`, the `'afterToneMapping'` effects read `rgba8unorm`. An effect\n * whose `inputMips` is set gets an input with mipmaps.\n *\n * The graph comes back compiled, so authoring mistakes throw here rather than on the first frame.\n * @example\n * ```ts\n * new View3D({\n *   graph: (renderer, options) => {\n *     const { graph, handles } = createDefaultGraph3D(renderer, options);\n *     graph.addPass(new MyHeatHazePass({ renderer, opaqueColorHandle: handles.opaqueColor }));\n *     return graph;\n *   },\n * });\n * ```\n * @param renderer - The renderer the graph draws with.\n * @param options - What the view hands its `graph` builder; see {@link DefaultGraph3DOptions}.\n * @returns The compiled graph and the {@link DefaultGraph3DHandles} its passes share.\n * @throws If a pass that isn't a {@link PostEffect} claims the `'beforeToneMapping'` or\n *   `'afterToneMapping'` stage.\n * @throws If a `'beforeToneMapping'` effect is enabled on WebGL 2 without\n *   `EXT_color_buffer_float`, which the float scene needs.\n * @category rendering\n * @advanced\n */\nexport function createDefaultGraph3D(\n  renderer: WebGLRenderer | WebGPURenderer,\n  options: DefaultGraph3DOptions,\n): {\n  /** The compiled render graph */\n  graph: RenderGraph;\n  /** Textures the default passes share */\n  handles: DefaultGraph3DHandles;\n} {\n  const enabled = options.passes?.filter((p) => p.enabled) ?? [];\n  const beforeOpaque = enabled.filter((p) => p.stage === 'beforeOpaque');\n  const afterOpaque = enabled.filter((p) => p.stage === 'afterOpaque');\n  const afterTransparent = enabled.filter((p) => p.stage === 'afterTransparent');\n  const beforeToneMapping = enabled.filter((p): p is PostEffect => p.stage === 'beforeToneMapping');\n  const afterToneMapping = enabled.filter((p): p is PostEffect => p.stage === 'afterToneMapping');\n  assertPostEffects(renderer, beforeToneMapping, afterToneMapping);\n\n  const sceneIsLinear = beforeToneMapping.length > 0;\n  const toneMapping = options.toneMapping;\n  const outputToneMapping = sceneIsLinear && toneMapping !== 'custom' ? toneMapping : undefined;\n\n  const sceneOutputs = collectSceneOutputs(options.passes ?? [], options.sceneOutputs);\n  const effectCount = beforeToneMapping.length + afterToneMapping.length;\n  const composite = (options.composite ?? false) || effectCount > 0 || sceneOutputs.length > 0;\n\n  const copiesScene = composite && effectCount === 0;\n  const outputStep: 'outputPass'[] = outputToneMapping || copiesScene ? ['outputPass'] : [];\n  const chain: (PostEffect | 'outputPass')[] = [...beforeToneMapping, ...outputStep, ...afterToneMapping];\n  const firstStep = chain[0];\n  const sceneColorNeedsMips = firstStep instanceof PostEffect && firstStep.inputMips;\n  const antialias =\n    renderer.view.antialias && sceneOutputs.every((output) => isResolvableFormat(renderer, output.format));\n\n  const graph = new RenderGraph({\n    globalTextureBindings: options.globalTextureBindings,\n    defaultColor: (s: RenderSession) => s.defaultTarget.colorTexture,\n    defaultDepth: (s: RenderSession) => s.defaultTarget.depthStencilTexture!,\n    sceneColor: composite\n      ? {\n          antialias,\n          autoGenerateMipmaps: sceneColorNeedsMips,\n          format: sceneIsLinear ? 'rgba16float' : undefined,\n          label: 'sceneColor',\n        }\n      : undefined,\n    sceneDepth: composite ? { antialias, label: 'sceneDepth' } : undefined,\n    sceneOutputs,\n  });\n\n  const opaqueColorHandle = graph.createColor({ autoGenerateMipmaps: true, label: 'opaqueColorCopy' });\n  const opaqueDepthHandle = graph.createDepth({ label: 'opaqueDepthCopy' });\n\n  const ctx: PassContext = { renderer, opaqueColor: opaqueColorHandle, opaqueDepth: opaqueDepthHandle };\n\n  const shadowMapHandle = addShadowPass(graph, renderer);\n\n  for (const pass of beforeOpaque) pass.build(graph, ctx);\n\n  graph.addPass(new DepthClearPass({ renderer, attachedOutputs: sceneOutputs }));\n  graph.addPass(new BackgroundPass({ renderer, attachedOutputs: sceneOutputs }));\n  graph.addPass(new OpaqueRenderPass({ renderer, attachedOutputs: sceneOutputs }));\n\n  for (const pass of afterOpaque) pass.build(graph, ctx);\n\n  graph.addPass(new CopyDepthPass({ renderer, opaqueDepthHandle }));\n  graph.addPass(new CopyOpaquePass({ renderer, opaqueColorHandle }));\n\n  graph.addPass(new TransmissionRenderPass({ renderer, opaqueColorHandle, attachedOutputs: sceneOutputs }));\n  graph.addPass(new BlendedRefractionPass({ renderer, opaqueColorHandle, opaqueDepthHandle }));\n  graph.addPass(new TransparentRenderPass({ renderer, attachedOutputs: sceneOutputs }));\n\n  for (const pass of afterTransparent) pass.build(graph, ctx);\n\n  let input = graph.sceneColor;\n  for (let i = 0; i < chain.length; i++) {\n    const step = chain[i];\n    const next = chain[i + 1];\n    const output =\n      next === undefined\n        ? null\n        : graph.createColor({\n            autoGenerateMipmaps: next !== 'outputPass' && next.inputMips,\n            format: outputToneMapping && i >= beforeToneMapping.length ? 'rgba8unorm' : undefined,\n            label: 'effectChain',\n          });\n    if (step === 'outputPass') {\n      graph.addPass(new OutputPass({ renderer, source: input, toneMapping: outputToneMapping, writes: output }));\n    } else {\n      step.build(graph, { ...ctx, input, output });\n    }\n    if (output) input = output;\n  }\n\n  graph.compile();\n\n  return {\n    graph,\n    handles: {\n      opaqueColor: opaqueColorHandle,\n      opaqueDepth: opaqueDepthHandle,\n      shadowMap: shadowMapHandle,\n    },\n  };\n}\n\nfunction assertPostEffects(\n  renderer: WebGLRenderer | WebGPURenderer,\n  beforeToneMapping: readonly Pass3D[],\n  afterToneMapping: readonly Pass3D[],\n): void {\n  for (const pass of [...beforeToneMapping, ...afterToneMapping]) {\n    if (!(pass instanceof PostEffect)) {\n      throw new Error(\n        `${pass.constructor.name}: the '${pass.stage}' stage is reserved for PostEffect subclasses (extend PostEffect, or use a scene stage).`,\n      );\n    }\n  }\n  if (beforeToneMapping.length > 0) {\n    assertFloatRenderable(renderer, `View3D, for the float scene that ${beforeToneMapping[0].constructor.name} reads`);\n  }\n}\n\n/**\n * Imports the shadow map through a getter, since a shadow quality change replaces the pass's target; the getter\n * first runs at execute time, after `shadowPass` is set\n */\nfunction addShadowPass(graph: RenderGraph, renderer: WebGLRenderer | WebGPURenderer): DepthHandle {\n  let shadowPass: ShadowRenderPassGpu | ShadowRenderPassGl;\n  const shadowMapHandle = graph.importDepth(() => shadowPass.renderTarget.depthStencilTexture!);\n\n  shadowPass = renderer.renderPipes.view3d.createShadowPass({ shadowMapHandle });\n  graph.addPass(shadowPass);\n\n  return shadowMapHandle;\n}\n","import { Box } from '../../math/shapes/Box';\nimport { Sphere } from '../../math/shapes/Sphere';\nimport type { Camera3D } from '../cameras/Camera3D';\nimport type { Container3D } from '../Container3D';\n\nconst _bounds = new Box();\nconst _sphere = new Sphere();\n\n/**\n * Moves a perspective camera onto the +Z side of `target` without turning it, so it must still face local -Z\n * @internal\n */\nexport function frameCamera(camera: Camera3D, target: Container3D, aspect: number): void {\n  const { center, radius } = _sphere.setFromBox(target.getLocalBounds(_bounds));\n\n  const fit = radius > 0 ? radius : 1;\n  const tanHalfFovY = camera._tanHalfFovY();\n  const halfFovY = Math.atan(tanHalfFovY);\n  const halfFovX = Math.atan(tanHalfFovY * aspect);\n  const distance = fit / Math.sin(Math.min(halfFovX, halfFovY));\n\n  camera.near = distance / 100;\n  camera.far = distance * 100;\n  camera.position.set(center.x, center.y, center.z + distance);\n}\n","import { clearList } from 'pixi.js';\n\nimport { Matrix4 } from '../../math/matrix/Matrix4';\nimport { Container3D } from '../Container3D';\nimport type { View3D } from '../View3D';\n\n/**\n * Parent for roots, so the update never null-checks; its identity `worldTransform` and `worldVisible` of 1 must\n * never change\n */\nconst TEMP_PARENT_3D = /* @__PURE__ */ (() => {\n  const p = new Container3D();\n  p._worldVisible = 1;\n  return p;\n})();\n\n/**\n * Skips a queued container whose view or depth changed after it was queued, since the queue where it is now has it\n * @internal\n */\nexport function updateView3DTransforms(view3d: View3D) {\n  const childrenToUpdate = view3d._childrenToUpdate;\n\n  const updateTick = view3d._updateTick++;\n\n  for (const j in childrenToUpdate) {\n    const renderGroupDepth = Number(j);\n\n    const childrenAtDepth = childrenToUpdate[j];\n\n    const list = childrenAtDepth.list;\n    const index = childrenAtDepth.index;\n\n    for (let i = 0; i < index; i++) {\n      const child = list[i];\n\n      if (child._view3d === view3d && child._relativeSceneDepth === renderGroupDepth) {\n        const parent = child.parent ?? TEMP_PARENT_3D;\n        updateTransformAndChildren3D(child, parent, updateTick, false, false);\n      }\n    }\n\n    clearList(list, index);\n\n    childrenAtDepth.index = 0;\n  }\n}\n\n/**\n * Updates a subtree once per `updateTick`; clears `didChange` first, so a setter run mid-update re-queues, and leaves a\n * hidden node's transform dirty flags set for when it's shown\n * @internal\n */\nexport function updateTransformAndChildren3D(\n  container: Container3D,\n  parent: Container3D,\n  updateTick: number,\n  transformDirty: boolean,\n  visibleDirty: boolean,\n) {\n  if (updateTick === container._updateTick) return;\n  container._updateTick = updateTick;\n\n  container.didChange = false;\n\n  transformDirty ||= container._worldTransformDirty;\n  visibleDirty ||= container._worldVisibleDirty;\n\n  if (visibleDirty) {\n    container._worldVisible = parent._worldVisible * container._visible;\n    container._storeWorldVisible();\n  }\n\n  if (container._worldVisible && transformDirty) {\n    if (container._localTransformDirty) {\n      container.updateLocalTransform();\n      container._localTransformDirty = false;\n    }\n\n    Matrix4.multiplyAffine(\n      container.worldTransform.elements as Float32Array,\n      0,\n      parent.worldTransform.elements as Float32Array,\n      0,\n      container.localTransform.elements as Float32Array,\n      0,\n    );\n\n    container._worldTransformId++;\n    container._storeWorldTransform();\n  }\n\n  container._worldVisibleDirty = false;\n  container._worldTransformDirty = container._worldVisible ? false : transformDirty;\n\n  const children = container.children;\n  const length = children.length;\n\n  for (let i = 0; i < length; i++) {\n    updateTransformAndChildren3D(children[i], container, updateTick, transformDirty, visibleDirty);\n  }\n}\n","import { clearList } from 'pixi.js';\n\nimport {\n  MESH3D_LANE_GEOMETRY,\n  MESH3D_LANE_MATERIAL,\n  MESH3D_STORE_STRIDE,\n} from '../../core/buffers/Mesh3DDataStoreBuffer';\nimport { getCameraData } from '../../core/CameraData';\nimport type { View3DPipeGl } from '../../core/gl/View3DPipeGl';\nimport type { View3DPipeGpu } from '../../core/gpu/View3DPipeGpu';\nimport { prepareCamera } from '../../core/prepareCamera';\nimport type { RenderSession } from '../../core/render-passes/RenderSession';\nimport { validateCamera } from '../../core/validateCamera';\nimport type { View3D } from '../View3D';\nimport { updateView3DTransforms } from './updateView3DTransforms';\n\n/**\n * Per-frame scene update. Bones and morphs settle before the batch walks, since store rows copy their offsets, and\n * `Mesh3DBatch.applyEdits` runs last, once every joining item has its keys\n * @returns `false` when the view camera is fully off-screen, and the caller draws nothing\n * @internal\n */\nexport function updateView3DScene(view3d: View3D, pipe: View3DPipeGpu | View3DPipeGl, session: RenderSession): boolean {\n  updateView3DTransforms(view3d);\n  validateCamera(view3d);\n\n  prepareCamera(view3d.camera, session);\n  const frame = getCameraData(view3d.camera).frame;\n  if (frame.width <= 0 || frame.height <= 0) return false;\n\n  view3d._syncShadowSampling();\n\n  refillBonePit(view3d);\n  pipe._morphStoreBuffer.sync(view3d._morphedMeshes.items);\n\n  updateSceneBatch(view3d, pipe);\n  updateUserBatches(view3d, pipe);\n\n  restampMorphedGeometry(view3d, pipe);\n  invalidateGrownStores(view3d);\n\n  const batches = view3d._meshBatches;\n  for (let b = 0; b < batches.length; b++) batches[b].applyEdits();\n\n  return true;\n}\n\n/**\n * The pit refills every frame, so a skeleton's base moves when a skinned mesh joins or leaves, and the store row that\n * bakes the base is re-emitted when it moves\n */\nfunction refillBonePit(view3d: View3D): void {\n  view3d._bonePit.clear();\n  const skinnedMeshes = view3d._skinnedMeshes.items;\n  for (let i = 0; i < view3d._skinnedMeshes.items.length; i++) {\n    const mesh = skinnedMeshes[i];\n    const skeleton = mesh.skeleton!;\n    skeleton.updateWorld();\n    const base = view3d._bonePit.add(skeleton);\n    if (mesh._lastBonePitIndex !== base) {\n      mesh._lastBonePitIndex = base;\n      mesh._markStoreDirty();\n    }\n  }\n  view3d._bonePit.update();\n}\n\n/**\n * Drains the mesh update queue, keeping meshes queued during the drain for next frame. A geometry is packed before its\n * row is staged, since the row bakes the atlas `baseVertex`\n */\nfunction updateSceneBatch(view3d: View3D, pipe: View3DPipeGpu | View3DPipeGl): void {\n  const geomStore = pipe.geometryDataStoreBuffer;\n  const queue = view3d._renderablesToUpdate;\n  const queued = queue.list;\n  const queuedCount = queue.index;\n  for (let i = 0; i < queuedCount; i++) {\n    const renderable = queued[i];\n    renderable.didRenderableUpdate = false;\n    if (renderable._view3d !== view3d) continue;\n\n    const material = renderable.material;\n\n    const membershipMask = renderable.renderPassMask;\n    if (membershipMask !== renderable._lastRenderPass) {\n      view3d._sceneBatch.setPassesAt(view3d._meshSlots.getIndex(renderable), membershipMask);\n    }\n\n    let rebuildsLists = false;\n    if (renderable._lastDescriptorDirtyId !== material._descriptorDirtyId) {\n      rebuildsLists = renderable._lastDescriptorDirtyId !== -1;\n      renderable._lastDescriptorDirtyId = material._descriptorDirtyId;\n      renderable._batchDirty = true;\n    }\n\n    if (renderable._lastRenderPass === 0) continue;\n\n    const geometry = renderable.geometry;\n    const unpacked = geometry._geometryAtlasAllocation === null && !geometry.dynamic;\n    if (renderable._batchDirty || unpacked) {\n      renderable._batchDirty = false;\n      rebuildsLists ||= unpacked && geometry._atlasVacated;\n\n      pipe.renderer.material3d.ensureMaterial(renderable, view3d._sceneBatch, view3d);\n\n      if (!geometry.dynamic) {\n        geometry._geometryAtlasAllocation = pipe.atlasPool.allocate(geometry);\n      }\n      geomStore.set(geometry);\n\n      let bits = renderable.renderPassMask & view3d._dirtyHookBits;\n      while (bits) {\n        const bit = bits & -bits;\n        view3d.passByBit[bit].onRenderableDirty(renderable, view3d._sceneBatch, rebuildsLists);\n        bits ^= bit;\n      }\n    }\n\n    if (renderable._storeDirty) {\n      renderable._storeDirty = false;\n      view3d._sceneBatch.storeBuffer.set(renderable);\n    }\n  }\n\n  const requeued = queue.index - queuedCount;\n  for (let i = 0; i < requeued; i++) queued[i] = queued[queuedCount + i];\n  clearList(queued, requeued);\n  queue.index = requeued;\n\n  view3d._sceneBatch.storeBuffer.update();\n}\n\n/**\n * Skips a slot in no pass, which `Mesh3DBatch.setPassesAt` re-queues when it joins one; packs each geometry before\n * staging its row, as `updateSceneBatch` does\n */\nfunction updateUserBatches(view3d: View3D, pipe: View3DPipeGpu | View3DPipeGl): void {\n  const geomStore = pipe.geometryDataStoreBuffer;\n  for (let b = 1; b < view3d._meshBatches.length; b++) {\n    const batch = view3d._meshBatches[b];\n\n    batch.writeBatchWorldMatrix(batch.renderData.worldTransform);\n\n    const dirtyIndices = batch._dirtyIndices!;\n    const dirtyCount = batch._dirtyCount;\n\n    for (let d = 0; d < dirtyCount; d++) {\n      const item = batch.items[dirtyIndices[d]];\n      item._batchDirty = false;\n      const passes = item._lastRenderPass;\n      if (passes === 0) continue;\n\n      const material = item.material;\n      let rebuildsLists =\n        item.geometry._geometryAtlasAllocation === null && !item.geometry.dynamic && item.geometry._atlasVacated;\n      if (item._lastDescriptorDirtyId !== material._descriptorDirtyId) {\n        rebuildsLists ||= item._lastDescriptorDirtyId !== -1;\n        item._lastDescriptorDirtyId = material._descriptorDirtyId;\n      }\n\n      pipe.renderer.material3d.ensureMaterial(item, batch, view3d);\n\n      if (!item.geometry.dynamic) {\n        item.geometry._geometryAtlasAllocation = pipe.atlasPool.allocate(item.geometry);\n      }\n      geomStore.set(item.geometry);\n\n      batch.storeBuffer.u32Data[item._storeIndex * MESH3D_STORE_STRIDE + MESH3D_LANE_MATERIAL] =\n        material._materialIndex;\n      batch.storeBuffer.u32Data[item._storeIndex * MESH3D_STORE_STRIDE + MESH3D_LANE_GEOMETRY] =\n        item.geometry._geometryDataIndex;\n      batch.storeBuffer.markDirty(item._storeIndex);\n\n      let bits = passes & view3d._dirtyHookBits;\n      while (bits) {\n        const bit = bits & -bits;\n        view3d.passByBit[bit].onRenderableDirty(item, batch, rebuildsLists);\n        bits ^= bit;\n      }\n    }\n    batch._dirtyCount = 0;\n    batch.storeBuffer.update();\n    batch.instanceStoreBuffer?.update();\n  }\n}\n\n/**\n * Morphed geometry rows bake the atlas `baseVertex`, which growth and compaction move without dirtying a mesh; runs\n * after the batch walks, so this frame's allocations are in place\n */\nfunction restampMorphedGeometry(view3d: View3D, pipe: View3DPipeGpu | View3DPipeGl): void {\n  const geomStore = pipe.geometryDataStoreBuffer;\n  const atlasBufferVersion = pipe.atlasPool.bufferVersion;\n  if (view3d._lastAtlasBufferVersion !== atlasBufferVersion) {\n    view3d._lastAtlasBufferVersion = atlasBufferVersion;\n    const morphedMeshes = view3d._morphedMeshes.items;\n    for (let i = 0; i < morphedMeshes.length; i++) geomStore.set(morphedMeshes[i].geometry);\n  }\n}\n\n/** Covers the view's own stores; `detectSharedCacheInvalidation` covers the shared atlas, material and morph stores */\nfunction invalidateGrownStores(view3d: View3D): void {\n  for (let b = 0; b < view3d._meshBatches.length; b++) {\n    const batch = view3d._meshBatches[b];\n    const storeVersion = batch.storeBuffer.bufferVersion;\n    if (batch._lastStoreBufferVersion !== storeVersion) {\n      batch._lastStoreBufferVersion = storeVersion;\n      batch.invalidateDrawCaches();\n    }\n  }\n  const boneVersion = view3d._bonePit.bufferVersion;\n  if (view3d._lastBonePitBufferVersion !== boneVersion) {\n    view3d._lastBonePitBufferVersion = boneVersion;\n    view3d._invalidateDrawCaches();\n  }\n}\n","interface HasUid {\n  uid: number;\n}\n\n/**\n * Removal leaves a `null` hole, so an item's index holds while it is listed; walkers of `items` skip holes\n * @internal\n */\nexport class StableList<T extends HasUid> {\n  /** Never replaced, since `View3D._sceneBatch` keeps a reference to it */\n  public readonly items: (T | null)[] = [];\n\n  /** Count of slots ever used, holes included, not of live items */\n  public count = 0;\n\n  private _freeList: Uint32Array = new Uint32Array(1024);\n  private _freeCount = 0;\n  private readonly _uidToIndex = new Map<number, number>();\n\n  /** Doesn't check for duplicates: adding a listed item strands its first slot */\n  public add(item: T): void {\n    let index: number;\n\n    if (this._freeCount > 0) {\n      index = this._freeList[--this._freeCount];\n    } else {\n      index = this.count++;\n    }\n\n    this.items[index] = item;\n    this._uidToIndex.set(item.uid, index);\n  }\n\n  public remove(item: T): void {\n    const index = this._uidToIndex.get(item.uid);\n    if (index === undefined) return;\n\n    this.items[index] = null;\n    this._uidToIndex.delete(item.uid);\n\n    if (this._freeCount >= this._freeList.length) {\n      const bigger = new Uint32Array(this._freeList.length * 2);\n      bigger.set(this._freeList);\n      this._freeList = bigger;\n    }\n\n    this._freeList[this._freeCount++] = index;\n  }\n\n  public getIndex(item: T): number {\n    return this._uidToIndex.get(item.uid) ?? -1;\n  }\n}\n","import type {\n  ColorSource,\n  ContainerChild,\n  Optional,\n  PointData,\n  Renderer,\n  Size,\n  ViewContainerOptions,\n  WebGLRenderer,\n  WebGPURenderer,\n} from 'pixi.js';\nimport { Color, CubeTexture, definedProps, Matrix, ObservablePoint, Point, ViewContainer } from 'pixi.js';\n\nimport type { Scene3DSource } from '../assets/Scene3DSource';\nimport { Mesh3DBatch } from '../core/batcher/Mesh3DBatch';\nimport type { Mesh3DData } from '../core/batcher/Mesh3DData';\nimport { BonePit } from '../core/buffers/BonePit';\nimport { LightDataList } from '../core/LightDataList';\nimport { MAX_LIGHTS } from '../core/lightLimits';\nimport type { RenderGraph } from '../core/render-graph/RenderGraph';\nimport { RenderPassBit } from '../core/render-passes/RenderPass';\nimport type { RenderPass } from '../core/render-passes/RenderPass';\nimport type { ShadowFilter, ShadowQuality } from '../core/render-passes/shadow/shadowPassUtils';\nimport { envSourceCubeBit } from '../core/shader/bits/envSourceCubeBit';\nimport { envSourceDefaultBit } from '../core/shader/bits/envSourceDefaultBit';\nimport { envSourceHemisphereBit } from '../core/shader/bits/envSourceHemisphereBit';\nimport { exp2FogBit } from '../core/shader/bits/fog/exp2FogBit';\nimport { exponentialFogBit } from '../core/shader/bits/fog/exponentialFogBit';\nimport { linearFogBit } from '../core/shader/bits/fog/linearFogBit';\nimport { TONE_MAPPING_BITS } from '../core/shader/bits/tonemapping/toneMappingBits';\nimport type { ShaderBit } from '../core/shader/ShaderBit';\nimport { ShadowDataList } from '../core/ShadowDataList';\nimport { EventBoundary3D } from '../events/EventBoundary3D';\nimport type { AncestorPickState } from '../events/FederatedEventTarget3D';\nimport { getAncestorPickState, PICK_BLOCKED, PICK_COVERED } from '../events/FederatedEventTarget3D';\nimport { Matrix4 } from '../math/matrix/Matrix4';\nimport type { Plane } from '../math/shapes/Plane';\nimport { Ray } from '../math/shapes/Ray';\nimport type { PointData3D } from '../math/vector/PointData3D';\nimport { Vector3 } from '../math/vector/Vector3';\nimport type { Pass3D } from '../post-processing/Pass3D';\nimport type { Destroy3DOptions } from '../utils/Destroy3DOptions';\nimport { resolveDestroy3DFlag } from '../utils/Destroy3DOptions';\nimport { StableList } from '../utils/StableList';\nimport { UnstableList } from '../utils/UnstableList';\nimport { warnOnce } from '../utils/warnOnce';\nimport { BatchedMesh3D } from './BatchedMesh3D';\nimport { Camera3D } from './cameras/Camera3D';\nimport { Container3D } from './Container3D';\nimport { DirectionalLight } from './lights/DirectionalLight';\nimport type { Hemisphere } from './lights/environment/Hemisphere';\nimport { Light } from './lights/Light';\nimport { Mesh3D } from './Mesh3D';\nimport { Model3D } from './Model3D';\nimport type { Model3DOptions } from './Model3D';\nimport { createDefaultGraph3D } from './utils/createDefaultGraph3D';\nimport type { DefaultGraph3DOptions } from './utils/createDefaultGraph3D';\nimport { frameCamera } from './utils/frameCamera';\nimport type { View3DGlobalData } from './View3DGlobalData';\n\ndeclare global {\n  namespace PixiMixins {\n    /**\n     * Augmentation hook for members mixed into {@link View3D}\n     *\n     * Declare added members here and merge their implementation onto the class with pixi.js's\n     * `extensions.mixin(View3D, myMixin)`, as pixi's 2D `Container` does. The interaction members\n     * `containsPoint`, `cursor`, `hitArea` and `raycast` arrive this way.\n     */\n    interface View3D {}\n    /** Augmentation hook for constructor options mixed into {@link View3DOptions} */\n    interface View3DOptions {}\n  }\n}\n\n/**\n * The tone curve and display encode a view applies to what it draws; see {@link View3D#toneMapping}\n *\n * - `'none'` (default): the sRGB encode alone. The scene shows as lit, and anything brighter than 1\n *   clips.\n * - `'aces'`, `'reinhard'` and `'uncharted2'`: a filmic curve that rolls off bright light, then the\n *   sRGB encode. Use one, usually `'aces'`, when strong lights or a bright environment push lit\n *   colour past 1.\n * - `'custom'`: neither. The view outputs raw linear light, for a post effect that does its own\n *   tone mapping and encoding. Leave that effect at the default `'beforeToneMapping'` stage, so it\n *   reads the scene in float with brightness above 1 intact.\n *\n * It applies to every material, lit or unlit, so unlit art such as sprites, particles and flat\n * materials matches pixi 2D under `'none'` at exposure 1, and a filmic curve shifts it too.\n * @example\n * ```ts\n * const view = new View3D({ width, height, toneMapping: 'reinhard' });\n *\n * view.toneMapping = 'aces';\n * ```\n * @category environment\n * @standard\n */\nexport type ToneMapping = 'aces' | 'reinhard' | 'uncharted2' | 'none' | 'custom';\n\n/**\n * How a view or a {@link BatchedMesh3D} skips what's outside the camera's view\n *\n * - `'gpu'`: culls on the GPU, off the main thread. WebGL, and Safari or any iOS browser for all\n *   but very large batches, cull on the CPU instead. So do blended meshes, which draw sorted back\n *   to front.\n * - `'cpu'`: culls on the CPU every frame. Can suit a frame that waits on the GPU.\n * - `'off'`: draws everything. Suits a scene that always fits in view.\n *\n * A skinned mesh is tested at its bind pose, so an animation that carries it far from that pose\n * can make it vanish near the edge of the screen. Use `'off'` for a view that shows one.\n * @example\n * ```ts\n * const view = new View3D({ cull: 'cpu' });\n * ```\n * @category scene\n * @standard\n */\nexport type CullMode = 'off' | 'cpu' | 'gpu';\n\n/**\n * How distance fog thickens with depth, the distance in front of the camera\n *\n * - `'linear'`: `smoothstep(near, far, depth)`, from no fog at `near` to full fog at `far`.\n * - `'exponential'`: `1 - exp(-density * depth)`. A soft haze that starts right at the camera.\n * - `'exp2'`: `1 - exp(-(density * depth)²)`. Clear near the camera, then closing in.\n * @example\n * ```ts\n * new View3D({ width, height, fog: { type: 'exponential', color: 0xadb2ba, density: 0.18 } });\n * ```\n * @category environment\n * @standard\n */\nexport type FogType = 'linear' | 'exponential' | 'exp2';\n\nconst FOG_BITS: Record<FogType, ShaderBit> = {\n  linear: linearFogBit,\n  exponential: exponentialFogBit,\n  exp2: exp2FogBit,\n};\n\n/** Depth of the near plane after projection: camera projections run from -1 at `near` to 1 at `far` */\nconst NEAR_PLANE_NDC_Z = -1;\n\nconst _screenMatrix2D = new Matrix();\nconst _screenPoint = new Point();\nconst _projMatrix = new Matrix4();\nconst _camMatrix = new Matrix4();\nconst _screenVec = new Vector3();\nconst _screenRay = new Ray();\n\n/**\n * Distance fog settings for {@link View3D#fog}\n *\n * Materials with `fog` turned off, such as a skybox or water that fades itself, ignore it.\n * @example\n * ```ts\n * const haze: Fog = { type: 'linear', color: 0xadb2ba, near: 30, far: 55 };\n *\n * view.fog = haze;\n * haze.far = 80;\n *\n * view.fog = { type: 'exp2', color: 0xadb2ba, density: 0.05 };\n * view.fog = null;\n * ```\n * @category environment\n * @standard\n */\nexport interface Fog {\n  /**\n   * How the fog thickens with distance; see {@link FogType}\n   *\n   * Read-only: assign a new object to {@link View3D#fog} to switch curves.\n   * @default 'linear'\n   * @example\n   * ```ts\n   * view.fog = { type: 'exp2', density: 0.04 };\n   * ```\n   */\n  readonly type?: FogType;\n  /**\n   * Fog colour, in display (sRGB) space like every other colour\n   *\n   * Exposure and the tone curve apply to it as they do to the scene, so give\n   * {@link View3D#background} the same colour and fully fogged surfaces meet it with no seam,\n   * whatever the tone mapping and exposure.\n   * @default 0xcccccc\n   * @example\n   * ```ts\n   * view.fog = { color: 'lightsteelblue', near: 20, far: 60 };\n   * ```\n   */\n  color?: ColorSource;\n  /**\n   * Distance where linear fog starts, in world units; the other curves ignore it\n   * @default 0\n   * @example\n   * ```ts\n   * view.fog = { type: 'linear', near: 10, far: 40 };\n   * ```\n   */\n  near?: number;\n  /**\n   * Distance where linear fog becomes solid, in world units; the other curves ignore it\n   * @default 99999999\n   * @example\n   * ```ts\n   * view.fog = { type: 'linear', near: 0, far: 120 };\n   * ```\n   */\n  far?: number;\n  /**\n   * How quickly exponential fog thickens, where `0` means no fog; linear fog ignores it\n   * @default 0\n   * @example\n   * ```ts\n   * view.fog = { type: 'exponential', density: 0.02 };\n   * ```\n   */\n  density?: number;\n}\n\n/**\n * Constructor options for {@link View3D}\n *\n * pixi's own container options, such as `label`, `position`, `eventMode` and the `on*` handlers,\n * work too.\n * @example\n * ```ts\n * const view = new View3D({\n *   width: 1280,\n *   height: 720,\n *   anchor: 0.5,\n *   shadowQuality: 'high',\n *   toneMapping: 'aces',\n *   exposure: 1.2,\n *   fog: { type: 'linear', color: 0xadb2ba, near: 30, far: 55 },\n *   environment: { skyColor: 0x88ccff, groundColor: 0x553311 },\n * });\n * ```\n * @typeParam TRoot - Type of {@link View3DOptions#root | root}, inferred from the `root` you pass.\n * @category scene\n * @standard\n */\nexport interface View3DOptions<TRoot extends Container3D = Container3D>\n  extends PixiMixins.View3DOptions, Omit<ViewContainerOptions, 'children' | 'isRenderGroup'> {\n  /**\n   * Root of the 3D scene; see {@link View3D#root}\n   * @default new Container3D()\n   * @example\n   * ```ts\n   * const view = new View3D({ root: new Model3D(source) });\n   *\n   * view.root.player?.play('Wave');\n   * ```\n   */\n  root?: TRoot;\n  /**\n   * Camera to draw from, added to {@link View3DOptions#root | root} when it has no parent; see\n   * {@link View3D#camera}\n   * @default new Camera3D()\n   * @example\n   * ```ts\n   * const view = new View3D({ camera: new Camera3D({ fov: 45 }) });\n   * ```\n   */\n  camera?: Camera3D;\n  /**\n   * Width of the 3D viewport in pixels\n   * @default 256\n   * @example\n   * ```ts\n   * const view = new View3D({ width: 800, height: 600 });\n   * ```\n   */\n  width?: number;\n  /**\n   * Height of the 3D viewport in pixels; see {@link View3DOptions#width | width}\n   * @default 256\n   * @example\n   * ```ts\n   * const view = new View3D({ width: 800, height: 600 });\n   * ```\n   */\n  height?: number;\n  /**\n   * Match the renderer's screen size on every render, following it when the canvas resizes;\n   * see {@link View3D#autoResize}\n   * @default false\n   * @example\n   * ```ts\n   * const view = new View3D({ autoResize: true });\n   * ```\n   */\n  autoResize?: boolean;\n  /**\n   * Where the view's origin sits, as a fraction of its size; see {@link View3D#anchor}\n   * @default 0\n   * @example\n   * ```ts\n   * const view = new View3D({ width: 400, height: 300, anchor: 0.5 });\n   * ```\n   */\n  anchor?: PointData | number;\n  /**\n   * Size of the shadow maps; see {@link View3D#shadowQuality}\n   * @default 'medium'\n   * @example\n   * ```ts\n   * const view = new View3D({ shadowQuality: 'low' });\n   * ```\n   */\n  shadowQuality?: ShadowQuality;\n  /**\n   * How soft shadow edges are; see {@link View3D#shadowFilter}\n   * @default 'pcf'\n   * @example\n   * ```ts\n   * const view = new View3D({ shadowFilter: 'hard' });\n   * ```\n   */\n  shadowFilter?: ShadowFilter;\n  /**\n   * Light from the surroundings: a cube map, a {@link Hemisphere} gradient, or `null` for none;\n   * see {@link View3D#environment}\n   * @default null\n   * @example\n   * ```ts\n   * const view = new View3D({ environment: { skyColor: 0x88ccff, groundColor: 0x553311 } });\n   * ```\n   */\n  environment?: CubeTexture | Hemisphere | null;\n  /**\n   * Drawn behind the scene: a cube map, a {@link Hemisphere} gradient, a plain colour, or `null`\n   * for none; see {@link View3D#background}\n   * @default null\n   * @example\n   * ```ts\n   * const view = new View3D({ environment: sky, background: sky });\n   *\n   * // Pass the fog the same colour and distant geometry melts into the background\n   * const misty = new View3D({ background: 0x968c34, fog: { color: 0x968c34, near: 20, far: 60 } });\n   * ```\n   */\n  background?: CubeTexture | Hemisphere | ColorSource | null;\n  /**\n   * Tone mapping curve; see {@link View3D#toneMapping}\n   * @default 'none'\n   * @example\n   * ```ts\n   * const view = new View3D({ toneMapping: 'aces' });\n   * ```\n   */\n  toneMapping?: ToneMapping;\n  /**\n   * Brightness multiplier applied before tone mapping; see {@link View3D#exposure}\n   * @default 1.0\n   * @example\n   * ```ts\n   * const view = new View3D({ exposure: 1.4 });\n   * ```\n   */\n  exposure?: number;\n  /**\n   * Distance fog, left out for none; see {@link View3D#fog}\n   * @example\n   * ```ts\n   * const view = new View3D({ fog: { type: 'linear', color: 0xadb2ba, near: 30, far: 55 } });\n   * ```\n   */\n  fog?: Fog;\n  /**\n   * How the view culls its meshes outside the camera's view; see {@link CullMode}\n   * @default 'gpu'\n   * @example\n   * ```ts\n   * const view = new View3D({ cull: 'off' });\n   * ```\n   */\n  cull?: CullMode;\n  /**\n   * Draw the scene into its own texture, then onto the screen, instead of straight to the screen\n   *\n   * The view does this anyway while it has an enabled post effect, an enabled pass that\n   * {@link Pass3D#requiredOutputs | requires} a scene output, or a {@link View3D#resolution} other\n   * than its target's; {@link View3D#resolution} says when to set it yourself. On a canvas with\n   * `antialias` the texture is multisampled too, unless a scene output's format rules that out; see\n   * {@link SceneOutput}.\n   * @default false\n   * @example\n   * ```ts\n   * const view = new View3D({ width: 320, height: 240, composite: true });\n   * ```\n   */\n  composite?: boolean;\n  /**\n   * Texels per logical pixel the scene is drawn at, or `'inherit'` for the target's; see\n   * {@link View3D#resolution}\n   * @default 'inherit'\n   * @example\n   * ```ts\n   * const view = new View3D({ resolution: 1 });\n   * ```\n   */\n  resolution?: number | 'inherit';\n  /**\n   * Passes and post effects for this view, the same as assigning {@link View3D#passes} later\n   * @example\n   * ```ts\n   * const view = new View3D({ passes: [new OutlinePass({ width: 0.05 }), new BloomEffect()] });\n   * ```\n   */\n  passes?: readonly Pass3D[];\n  /**\n   * Builds the render graph for this view\n   *\n   * Runs on the first render and again each time the view rebuilds its graph, such as after\n   * {@link View3D#passes} is assigned, a pass's `enabled` flips, or {@link View3D#unload}. A rebuild\n   * destroys the old graph and its passes, so make the passes inside the callback.\n   *\n   * Leave it out to use {@link createDefaultGraph3D}; to add passes to that pipeline, use\n   * {@link View3DOptions#passes} instead. For a different pipeline, start from\n   * `createDefaultGraph3D` and append, or build a bare {@link RenderGraph}. Forward `options`\n   * either way: it carries what every graph needs, and keeps `passes`, `composite` and\n   * `toneMapping` working. A pass that uses a scene output the graph doesn't attach throws when the\n   * view builds it.\n   * @example Modify the default graph\n   * ```ts\n   * new View3D({\n   *   width,\n   *   height,\n   *   graph: (renderer, options) => {\n   *     const { graph } = createDefaultGraph3D(renderer, options);\n   *     graph.addPass(new MyOutlinePass({ renderer }));\n   *     return graph;\n   *   },\n   * });\n   * ```\n   */\n  graph?: (renderer: WebGLRenderer | WebGPURenderer, options: DefaultGraph3DOptions) => RenderGraph;\n}\n\n/**\n * Options for {@link View3D.from}: every {@link View3DOptions} field but `root`, the\n * {@link Model3DOptions} a model takes per instance, and `light`\n * @example\n * ```ts\n * const view = View3D.from(source, {\n *   width: 800,\n *   height: 600,\n *   toneMapping: 'reinhard',\n *   scene: 'Showroom',\n *   autoPlay: true,\n * });\n * ```\n * @see {@link View3D.from} For what the camera and light defaults do.\n * @category scene\n * @standard\n */\nexport interface View3DFromOptions\n  extends\n    Omit<View3DOptions, 'root'>,\n    Pick<Model3DOptions, 'scene' | 'castShadow' | 'receiveShadow' | 'autoUpdate' | 'autoPlay' | 'materials'> {\n  /**\n   * Add a {@link DirectionalLight} under the camera when the file brings no lights of its own\n   *\n   * The light follows the camera, so it lights whatever the camera faces. Set to `false` to light\n   * the scene yourself.\n   * @default true\n   * @example\n   * ```ts\n   * const view = View3D.from(source, { light: false, environment: studio });\n   * ```\n   */\n  light?: boolean;\n}\n\n// oxlint-disable-next-line pixijs-3d/require-export-jsdoc, pixijs-3d/require-member-api-doc, no-unused-vars\nexport interface View3D<TRoot extends Container3D = Container3D> extends PixiMixins.View3D {}\n\n/**\n * A 3D scene drawn inside pixi's 2D display list\n *\n * A `View3D` is a pixi display object: add it to the stage, then move, mask or filter it like a\n * sprite. Everything 3D goes under its {@link View3D#root | root}.\n *\n * The view holds the {@link View3D#camera | camera} and the settings for the whole scene: tone\n * mapping, exposure, fog, environment light, background and shadows. A change to some of them\n * recompiles the materials, so don't change those every frame; each one's doc says which.\n *\n * The view also sends pointer events into the scene. Set {@link Container3D#eventMode | eventMode}\n * on a node and it gets pixi's pointer events, hit-tested against its\n * {@link Container3D#hitVolume | hitVolume}. {@link View3D#raycast | raycast} picks without\n * sending an event. The view itself starts with `eventMode` `'static'`, so it catches the pointer\n * anywhere in its rectangle.\n * @example\n * ```ts\n * import { Application } from 'pixi.js';\n * import { View3D, DirectionalLight } from '@pixi/3d';\n *\n * const app = new Application();\n * await app.init({ resizeTo: window });\n *\n * // Fills the screen and follows it when the canvas resizes.\n * const view = new View3D({ autoResize: true, shadowQuality: 'high', toneMapping: 'aces' });\n * app.stage.addChild(view);\n *\n * view.camera.position.set(0, 2.5, 7);\n *\n * const light = new DirectionalLight({ intensity: 3, castShadow: true });\n * view.root.addChild(light);\n * view.root.addChild(mesh);\n *\n * // A fixed-size inset.\n * const inset = new View3D({ width: 320, height: 240 });\n * ```\n * @see {@link View3DOptions} For all constructor options.\n * @typeParam TRoot - Type of {@link View3D#root}, inferred from the `root` you pass.\n * @category scene\n * @standard\n */\nexport class View3D<TRoot extends Container3D = Container3D> extends ViewContainer<View3DGlobalData> {\n  /**\n   * Defaults for every new `View3D`; an option passed as `undefined` keeps its default\n   *\n   * Don't set `root` or `camera` here: every view would share the one object.\n   * @example\n   * ```ts\n   * View3D.defaultOptions.shadowQuality = 'high';\n   * View3D.defaultOptions.toneMapping = 'reinhard';\n   *\n   * const view = new View3D();\n   * ```\n   */\n  public static defaultOptions: View3DOptions = {\n    width: 256,\n    height: 256,\n    anchor: 0,\n    shadowQuality: 'medium',\n    shadowFilter: 'pcf',\n    toneMapping: 'none',\n    exposure: 1.0,\n    autoResize: false,\n  };\n\n  /** @internal */\n  public override allowChildren = false;\n\n  /**\n   * The `name` that `View3DPipeGpu` and `View3DPipeGl` register under\n   * @internal\n   */\n  public override readonly renderPipeId: string = 'view3d';\n  /** @internal */\n  public override batched = false;\n\n  /**\n   * Root of the 3D scene\n   *\n   * Add meshes and lights under it, at any depth, and the view finds them. Pass it in the options\n   * rather than assigning it later: the view only tracks the root it was built with.\n   *\n   * Typed as whatever you passed as `root`, so a view built around a {@link Model3D} keeps the\n   * model's API here.\n   * @example\n   * ```ts\n   * view.root.addChild(mesh);\n   * view.root.addChild(light);\n   *\n   * const modelView = new View3D({ root: new Model3D(source) });\n   * modelView.root.player?.play('Wave');\n   * ```\n   */\n  public root: TRoot;\n\n  /**\n   * Sends the pointer events pixi delivers to the view on to the 3D nodes under the pointer; the\n   * 3D counterpart of pixi's `EventBoundary`\n   *\n   * It listens on the view itself, so `view.removeAllListeners()`, or `view.off(type)` without a\n   * handler, stops 3D events for good; pass your handler to `off`.\n   * @example\n   * ```ts\n   * const view = new View3D({ width: 800, height: 600 });\n   *\n   * view.events.enableGlobalMoveEvents = false;\n   * ```\n   * @see {@link View3D#raycast} For a one-off ray cast that dispatches nothing.\n   */\n  public readonly events: EventBoundary3D;\n\n  private _camera!: Camera3D;\n  private readonly _anchor: ObservablePoint = new ObservablePoint({ _onUpdate: () => this.onViewUpdate() });\n  private _width = 0;\n  private _height = 0;\n  /**\n   * Whether the view matches the renderer's screen size on every render\n   *\n   * Setting {@link View3D#width | width}, {@link View3D#height | height} or\n   * {@link View3D#setSize | setSize} turns it off. The view reads the screen size at the start of\n   * each render, so until its first render it reports the `width` and `height` it was built with.\n   * @example\n   * ```ts\n   * const view = new View3D({ autoResize: true });\n   *\n   * view.setSize(320, 240); // autoResize is now false\n   * view.autoResize = true; // follows the screen again from the next render\n   * ```\n   * @default false\n   */\n  public autoResize: boolean;\n  private _frameOnResize = false;\n  private _userOnRender: ((renderer: Renderer) => void) | null = null;\n\n  /**\n   * Takes the screen size before pixi updates bounds, so filters, culling and hit tests see it the same frame\n   * @internal\n   */\n  public override readonly _onRender = (renderer: Renderer): void => {\n    if (this.autoResize) this._resize(renderer.screen.width, renderer.screen.height);\n    this._userOnRender?.(renderer);\n  };\n\n  /**\n   * Callback pixi runs at the start of every render of the stage this view is on, or `null`\n   *\n   * It runs before the view updates its scene, so changes made in it show in the same frame.\n   * @example\n   * ```ts\n   * view.onRender = () => {\n   *   spinner.rotation.y += 0.01;\n   * };\n   * ```\n   */\n  override get onRender(): ((renderer: Renderer) => void) | null {\n    return this._userOnRender;\n  }\n\n  /**\n   * Sets the per-render callback\n   * @param func - Callback run at the start of every render; `null` removes it.\n   */\n  override set onRender(func: ((renderer: Renderer) => void) | null) {\n    this._userOnRender = func ?? null;\n  }\n\n  /**\n   * Every {@link Light} in the scene, in the order they joined it\n   *\n   * The view keeps the list in step with the scene, so read it but don't change it: add a light by\n   * putting it under {@link View3D#root | root}.\n   * @example\n   * ```ts\n   * for (const light of view.lights) light.intensity *= 0.5;\n   * ```\n   */\n  public lights: Light[] = [];\n  /**\n   * Size of each shadow map; see {@link ShadowQuality}\n   * @default 'medium'\n   * @example\n   * ```ts\n   * view.shadowQuality = isMobile ? 'low' : 'high';\n   * ```\n   */\n  public shadowQuality: ShadowQuality;\n  private _shadowFilter: ShadowFilter = 'pcf';\n  /**\n   * Brightness multiplier for the whole scene, background and fog included, applied before tone\n   * mapping\n   *\n   * It scales unlit materials too, in linear light, so at 2 an unlit colour draws about 1.37 times\n   * as bright on screen. Free to change every frame.\n   * @example\n   * ```ts\n   * view.exposure = 1.5;\n   * ```\n   * @default 1.0\n   */\n  public exposure = 1.0;\n  private _background: CubeTexture | Hemisphere | number | null = null;\n\n  private _toneMapping: ToneMapping = 'none';\n  /**\n   * `null` while the scene draws as linear light: under `'custom'`, or while a graph pass applies the curve\n   * @internal\n   */\n  public _toneMappingBit: ShaderBit | null = TONE_MAPPING_BITS.none;\n\n  private _fog: Fog | null = null;\n  /** @internal */\n  public _fogBit: ShaderBit | null = null;\n\n  private _environment: CubeTexture | Hemisphere | null = null;\n  /**\n   * Never `null`: with no environment, a default bit still gives lit shaders `sampleEnvironment`\n   * @internal\n   */\n  public _envBit: ShaderBit = envSourceDefaultBit;\n\n  /**\n   * Indices never move, since ID buffers and store rows refer to a mesh by its slot; `meshes` is the dense list\n   * @internal\n   */\n  public readonly _meshSlots = new StableList<Mesh3D>();\n\n  /** @internal */\n  public meshes = new UnstableList<Mesh3D>('_allMeshIndex');\n  /** @internal */\n  public _skinnedMeshes = new UnstableList<Mesh3D>('_skinnedMeshIndex');\n\n  /** @internal */\n  public _morphedMeshes = new UnstableList<Mesh3D>('_morphedMeshIndex');\n\n  /**\n   * Destroyed after the scene detaches through it, and after `unload` frees the bind groups over its buffers\n   *\n   * Holds `_meshSlots.items` itself, which `StableList` never replaces.\n   * @internal\n   */\n  public readonly _sceneBatch: Mesh3DBatch = new Mesh3DBatch({\n    items: this._meshSlots.items as Mesh3DData[],\n  });\n\n  /**\n   * `[0]` is always the scene batch, and user batches follow\n   * @internal\n   */\n  public readonly _meshBatches: Mesh3DBatch[] = [this._sceneBatch];\n\n  /**\n   * Bumped whenever `_meshBatches` gains or loses a batch, so holders of per-batch state rescan only then\n   * @internal\n   */\n  public _meshBatchesDirtyId = 0;\n\n  /**\n   * The pass that owns each draw-list bit\n   * @internal\n   */\n  public readonly passByBit: Record<number, RenderPass> = Object.create(null);\n\n  /**\n   * Every bit in `passByBit` ORed together\n   * @internal\n   */\n  public _dirtyHookBits = 0;\n\n  /**\n   * Valid only while `_passesInitialized`; a teardown leaves the destroyed graph here\n   * @internal\n   */\n  public _graph!: RenderGraph;\n\n  private _passesInitialized = false;\n\n  private _graphGlobalData: View3DGlobalData | null = null;\n\n  private readonly _buildGraph?: (\n    renderer: WebGLRenderer | WebGPURenderer,\n    options: DefaultGraph3DOptions,\n  ) => RenderGraph;\n\n  private readonly _composite: boolean;\n\n  /**\n   * The `composite` asked of the graph builder, not whether the graph composites; comparing the\n   * request keeps a view with a post effect from rebuilding every frame\n   */\n  private _compositeRequested = false;\n\n  private _passes: readonly Pass3D[] = [];\n\n  private _passesEnabledKey = 0;\n\n  /** @internal */\n  public readonly _lightDataList = new LightDataList();\n  /** @internal */\n  public readonly _shadowDataList = new ShadowDataList();\n  /**\n   * Whether lit shaders compile shadow sampling; never turns back off, so toggling a shadow recompiles nothing\n   * @internal\n   */\n  public _hasShadows = false;\n  /** @internal */\n  public _bonePit = new BonePit();\n\n  /** @internal */\n  public _lastBonePitBufferVersion = 0;\n\n  /**\n   * A watermark of its own, apart from `View3DGlobalData.lastAtlasBufferVersion`: with one shared\n   * watermark, whichever check read it first would hide the change from the other\n   * @internal\n   */\n  public _lastAtlasBufferVersion = 0;\n\n  /**\n   * Transform update queue, bucketed by `_relativeSceneDepth` so parents update before children\n   * @internal\n   */\n  public readonly _childrenToUpdate: Record<number, { list: Container3D[]; index: number }> = Object.create(null);\n\n  /**\n   * Meshes queued for the next scene update; only the first `index` entries are live, and the\n   * drain skips one that has left the view\n   * @internal\n   */\n  public readonly _renderablesToUpdate: { list: Mesh3D[]; index: number } = { list: [], index: 0 };\n  /** @internal */\n  public _updateTick = 0;\n\n  /** @param options - See {@link View3DOptions}. */\n  constructor(options: View3DOptions<TRoot> = {}) {\n    super({});\n\n    const {\n      root,\n      camera,\n      width,\n      height,\n      anchor,\n      shadowQuality,\n      shadowFilter,\n      environment,\n      background,\n      toneMapping,\n      exposure,\n      fog,\n      cull,\n      composite,\n      resolution,\n      graph,\n      passes,\n      parent,\n      autoResize,\n      ...rest\n    } = { ...View3D.defaultOptions, ...definedProps(options) };\n\n    this.events = new EventBoundary3D(this);\n\n    this.shadowQuality = shadowQuality!;\n    this._shadowFilter = shadowFilter!;\n    this.environment = environment ?? null;\n    this.background = background ?? null;\n    this._toneMapping = toneMapping!;\n    this.exposure = exposure!;\n    this._composite = composite ?? false;\n    this.resolution = resolution ?? 'inherit';\n    this._buildGraph = graph;\n    if (passes) this._passes = passes.slice();\n\n    if (fog) this.fog = fog;\n\n    this.anchor = anchor!;\n    this._width = width!;\n    this._height = height!;\n    this.autoResize = autoResize!;\n\n    this.root = (root ?? new Container3D()) as TRoot;\n    this._attach(this.root);\n\n    this._sceneBatch.cull = cull ?? 'gpu';\n    this.camera = camera ?? new Camera3D();\n\n    Object.assign(this, rest);\n    parent?.addChild(this);\n  }\n\n  /**\n   * Builds a view whose root is a {@link Model3D} of `source`, with a camera and light ready to\n   * render it\n   *\n   * The camera is `options.camera`, else the file's first camera, else a new {@link Camera3D} on\n   * the model's +Z side, facing it, just far enough back that the sphere around the model's bounds\n   * fits the view. An auto-sized view places that camera on its first render, once it knows its\n   * aspect. That camera's near and far planes sit at a hundredth and a hundred times its distance\n   * from the model. A file with no lights gets one; see {@link View3DFromOptions#light}.\n   * @example\n   * ```ts\n   * const view = View3D.from(await Assets.load('robot.glb'), { autoResize: true, environment });\n   * app.stage.addChild(view);\n   * view.root.player?.play('Wave');\n   * ```\n   * @param source - The loaded glTF or GLB to build the scene from.\n   * @param options - View options plus the per-instance model options; see {@link View3DFromOptions}.\n   */\n  public static from(source: Scene3DSource, options: View3DFromOptions = {}): View3D<Model3D> {\n    const { scene, castShadow, receiveShadow, autoUpdate, autoPlay, materials, light, ...viewOptions } = options;\n    const root = new Model3D({ source, scene, castShadow, receiveShadow, autoUpdate, autoPlay, materials });\n    const camera = viewOptions.camera ?? root.cameras[0];\n    const view = new View3D({ ...viewOptions, root, camera });\n\n    if (!camera) {\n      if (view.autoResize) view._frameOnResize = true;\n      else frameCamera(view.camera, root, view.width / view.height);\n    }\n    if (light !== false && !view.lights.length) view.camera.addChild(new DirectionalLight());\n\n    return view;\n  }\n\n  /**\n   * The camera this view draws from\n   *\n   * Assigning a camera with no parent adds it to {@link View3D#root | root}. Assigning one that has\n   * a parent outside this view's scene throws: add it, or its ancestor, under `view.root` first.\n   * A render with meshes to draw throws while the camera or any of its parents is hidden, or once\n   * it leaves the scene without a new camera assigned.\n   * @example\n   * ```ts\n   * view.camera.fov = 45;\n   * view.camera.position.set(0, 2.5, 7);\n   *\n   * const closeUp = new Camera3D({ fov: 30 });\n   * view.camera = closeUp;\n   * ```\n   */\n  get camera(): Camera3D {\n    return this._camera;\n  }\n\n  /**\n   * Sets the camera\n   * @param value - Camera to draw from.\n   */\n  set camera(value: Camera3D) {\n    if (this._camera === value) return;\n    this._camera = value;\n\n    if (value._view3d === this) return;\n\n    if (value.parent !== null) {\n      throw new Error(\n        \"Camera3D is parented under a Container3D that isn't in this View3D's scene graph. \" +\n          'Add the camera (or its ancestor) to view3d.root first.',\n      );\n    }\n\n    this.root.addChild(value);\n  }\n\n  /**\n   * Where the view's origin sits, as a fraction of its size, like a sprite's anchor\n   *\n   * `0` puts the origin at the top-left corner, `0.5` centers it, and `1` puts it at the\n   * bottom-right. Assign a number for both axes or a point for each.\n   * @example\n   * ```ts\n   * view.anchor = 0.5; // centered\n   * view.anchor = { x: 0, y: 1 }; // bottom-left\n   * ```\n   */\n  get anchor(): ObservablePoint {\n    return this._anchor;\n  }\n\n  /**\n   * Sets the anchor\n   * @param value - A number for both axes, or a point.\n   */\n  set anchor(value: PointData | number) {\n    if (typeof value === 'number') {\n      this._anchor.set(value);\n    } else {\n      this._anchor.copyFrom(value);\n    }\n  }\n\n  /**\n   * Width of the 3D viewport in pixels\n   *\n   * Unlike a plain pixi.js `Container`, setting it resizes the viewport instead of scaling\n   * the view, the same as `TilingSprite.width`.\n   * @example\n   * ```ts\n   * view.width = 320;\n   * ```\n   * @see {@link View3D#setSize} For setting width and height in one update.\n   */\n  override get width(): number {\n    return this._width;\n  }\n\n  /**\n   * Sets the width\n   * @param value - Width in pixels.\n   */\n  override set width(value: number) {\n    this.setSize(value, this._height);\n  }\n\n  /**\n   * Height of the 3D viewport in pixels; setting it resizes the viewport, as\n   * {@link View3D#width | width} does\n   * @example\n   * ```ts\n   * view.height = 240;\n   * ```\n   * @see {@link View3D#setSize} For setting width and height in one update.\n   */\n  override get height(): number {\n    return this._height;\n  }\n\n  /**\n   * Sets the height\n   * @param value - Height in pixels.\n   */\n  override set height(value: number) {\n    this.setSize(this._width, value);\n  }\n\n  /**\n   * Resizes the 3D viewport in one update and turns {@link View3D#autoResize | autoResize} off\n   * @example\n   * ```ts\n   * view.setSize(512); // 512 × 512\n   * view.setSize({ width: 800, height: 600 });\n   * ```\n   * @param value - Width in pixels, or an object with `width` and optional `height`.\n   * @param height - Height in pixels; defaults to the width.\n   */\n  public override setSize(value: number | Optional<Size, 'height'>, height?: number): void {\n    this.autoResize = false;\n\n    if (typeof value === 'object') {\n      height = value.height ?? value.width;\n      value = value.width;\n    }\n\n    this._resize(value, height ?? value);\n  }\n\n  private _resize(width: number, height: number): void {\n    if (width === this._width && height === this._height) return;\n\n    this._width = width;\n    this._height = height;\n\n    this.onViewUpdate();\n\n    if (this._frameOnResize) {\n      this._frameOnResize = false;\n      frameCamera(this._camera, this.root, width / height);\n    }\n  }\n\n  /**\n   * Returns the viewport size in pixels\n   * @example\n   * ```ts\n   * const { width, height } = view.getSize();\n   * ```\n   * @param out - Object to write into instead of allocating a new one.\n   * @returns The `out` object, or a new one.\n   */\n  public override getSize(out?: Size): Size {\n    out ||= {} as Size;\n    out.width = this._width;\n    out.height = this._height;\n\n    return out;\n  }\n\n  /**\n   * Projects a world-space point, such as one from {@link Container3D#getGlobalPosition}, to pixi's\n   * global 2D coordinates\n   *\n   * The result is in the same space as `event.global`, so you can assign it straight to a 2D\n   * object's position. It accounts for the view's {@link View3D#anchor | anchor}, its place on the\n   * stage, and the camera's {@link Camera3D#viewport | viewport}. Convert a point in a node's own\n   * space with {@link Container3D#toGlobal} first.\n   *\n   * Returns `null` for a point at or behind a perspective camera: the cue to hide a label that\n   * tracks it. Also returns `null`, and warns once, when the view or the camera's viewport has\n   * zero area. With {@link View3D#autoResize | autoResize}, the view takes the screen size only as\n   * it draws, so a label placed from `app.ticker` lags a frame after a resize; size a view that\n   * carries labels from the renderer's `resize` event instead.\n   * @param position - World-space point to project.\n   * @param out - 2D point the result is written into. Defaults to a new `Point`.\n   * @param skipUpdate - `true` to use cached transforms (see {@link Container3D#getGlobalTransform}).\n   * @example\n   * ```ts\n   * const label = new Text({ text: 'player' });\n   * const world = new Vector3();\n   * const screen = new Point();\n   * app.stage.addChild(label);\n   *\n   * app.ticker.add(() => {\n   *   // Reused out objects keep the per-frame code from allocating\n   *   const p = view3d.worldToScreen(mesh.getGlobalPosition(world), screen);\n   *   label.visible = p !== null;\n   *   if (p) label.position.copyFrom(p);\n   * });\n   * ```\n   * @see {@link View3D#screenToRay} / {@link View3D#screenToWorld} For the reverse direction.\n   */\n  public worldToScreen<P extends PointData = Point>(position: PointData3D, out?: P, skipUpdate = false): P | null {\n    const camera = this._camera;\n\n    camera.getGlobalTransform(_camMatrix, skipUpdate);\n    _camMatrix.getInverse(_camMatrix);\n    _screenVec.copyFrom(position).applyAffineMatrix4(_camMatrix);\n\n    if (camera.mode === 'perspective' && _screenVec.z >= 0) return null;\n\n    const width = this._width;\n    const height = this._height;\n    const { x: vx, y: vy, width: vw, height: vh } = camera.viewport;\n    const localW = vw * width;\n    const localH = vh * height;\n\n    if (!(localW > 0) || !(localH > 0)) {\n      warnOnce('View3D.worldToScreen:degenerate', 'View3D.worldToScreen: view size or camera viewport has zero area.');\n\n      return null;\n    }\n\n    camera.computeProjection(localW / localH, _projMatrix);\n    _screenVec.applyMatrix4(_projMatrix);\n\n    _screenPoint.x = (vx - this._anchor.x) * width + (_screenVec.x * 0.5 + 0.5) * localW;\n    _screenPoint.y = (vy - this._anchor.y) * height + (0.5 - _screenVec.y * 0.5) * localH;\n\n    return this.getGlobalTransform(_screenMatrix2D, skipUpdate).apply(_screenPoint, out);\n  }\n\n  /**\n   * Builds the world-space {@link Ray} through a point in pixi's global 2D coordinates, such as\n   * `event.global`\n   *\n   * The inverse of {@link View3D#worldToScreen | worldToScreen}: every point on the ray projects\n   * back to `position`. A perspective camera's ray starts at the camera; an orthographic camera's\n   * starts on the camera's plane and runs along its forward axis. Either way, `ray.at(t)` is `t`\n   * world units from the camera, which for a perspective camera is distance along a slanted ray,\n   * not depth.\n   *\n   * When the view or the camera's viewport has zero area, it warns once and returns a ray with a\n   * zero origin and direction.\n   * @param position - 2D global point to cast through, such as `event.global`.\n   * @param out - Ray the result is written into. Defaults to a new `Ray`.\n   * @param skipUpdate - `true` to use cached transforms (see {@link Container3D#getGlobalTransform}).\n   * @example\n   * ```ts\n   * view3d.on('pointermove', (e) => {\n   *   const ray = view3d.screenToRay(e.global);\n   *   const hit = ray.intersectPlane(ground, cursorPos);\n   * });\n   * ```\n   * @see {@link View3D#screenToWorld} For going straight to a point on a plane or at a distance.\n   */\n  public screenToRay(position: PointData, out: Ray = new Ray(), skipUpdate = false): Ray {\n    const camera = this._camera;\n    const width = this._width;\n    const height = this._height;\n    const { x: vx, y: vy, width: vw, height: vh } = camera.viewport;\n    const localW = vw * width;\n    const localH = vh * height;\n\n    if (!(localW > 0) || !(localH > 0)) {\n      warnOnce('View3D.screenToRay:degenerate', 'View3D.screenToRay: view size or camera viewport has zero area.');\n      out.origin.set(0);\n      out.direction.set(0);\n\n      return out;\n    }\n\n    this.getGlobalTransform(_screenMatrix2D, skipUpdate).applyInverse(position, _screenPoint);\n    const ndcX = ((_screenPoint.x - (vx - this._anchor.x) * width) / localW) * 2 - 1;\n    const ndcY = 1 - ((_screenPoint.y - (vy - this._anchor.y) * height) / localH) * 2;\n\n    camera.computeProjection(localW / localH, _projMatrix);\n    _projMatrix.getInverse(_projMatrix);\n    _screenVec.set(ndcX, ndcY, NEAR_PLANE_NDC_Z).applyMatrix4(_projMatrix);\n\n    camera.getGlobalTransform(_camMatrix, skipUpdate);\n\n    if (camera.mode === 'perspective') {\n      _camMatrix.extractPosition(out.origin);\n      _screenVec.applyAffineMatrix4(_camMatrix);\n      out.direction.copyFrom(_screenVec).subtract(out.origin).normalize();\n    } else {\n      _screenVec.z = 0;\n      _screenVec.applyAffineMatrix4(_camMatrix, out.origin);\n      out.direction.set(0, 0, -1).transformDirection(_camMatrix);\n    }\n\n    return out;\n  }\n\n  /**\n   * Converts a point in pixi's global 2D coordinates, such as `event.global`, to the world-space\n   * point `distance` units along its {@link View3D#screenToRay | ray}\n   * @param position - 2D global point to convert.\n   * @param distance - Distance along the ray, in world units from the camera.\n   * @param out - Point the result is written into. Defaults to a new {@link Vector3}.\n   * @param skipUpdate - `true` to use cached transforms (see {@link Container3D#getGlobalTransform}).\n   * @example\n   * ```ts\n   * marker.position.copyFrom(view3d.screenToWorld(e.global, 10));\n   * ```\n   * @see {@link View3D#worldToScreen} For the reverse direction.\n   */\n  public screenToWorld(position: PointData, distance: number, out?: Vector3, skipUpdate?: boolean): Vector3;\n  /**\n   * Converts a point in pixi's global 2D coordinates, such as `event.global`, to where its\n   * {@link View3D#screenToRay | ray} meets a plane: the usual way to find the spot on the ground\n   * under the pointer\n   *\n   * Returns `null` when the ray points away from the plane or runs parallel to it.\n   * @param position - 2D global point to convert.\n   * @param plane - World-space plane to intersect.\n   * @param out - Point the result is written into. Defaults to a new {@link Vector3}.\n   * @param skipUpdate - `true` to use cached transforms (see {@link Container3D#getGlobalTransform}).\n   * @example\n   * ```ts\n   * const ground = new Plane(new Vector3(0, 1, 0), 0);\n   *\n   * view3d.on('pointertap', (e) => {\n   *   const hit = view3d.screenToWorld(e.global, ground);\n   *   if (hit) tree.position.copyFrom(hit);\n   * });\n   * ```\n   * @see {@link View3D#worldToScreen} For the reverse direction.\n   */\n  public screenToWorld(position: PointData, plane: Plane, out?: Vector3, skipUpdate?: boolean): Vector3 | null;\n  /**\n   * Implementation of the overloads above\n   * @param position - 2D global point to convert.\n   * @param target - Distance along the ray, or the world-space plane to intersect.\n   * @param out - Point the result is written into. Defaults to a new {@link Vector3}.\n   * @param skipUpdate - `true` to use cached transforms.\n   * @example\n   * ```ts\n   * const spot = view3d.screenToWorld(e.global, ground) ?? view3d.screenToWorld(e.global, 20);\n   * ```\n   */\n  public screenToWorld(position: PointData, target: number | Plane, out?: Vector3, skipUpdate = false): Vector3 | null {\n    const ray = this.screenToRay(position, _screenRay, skipUpdate);\n\n    return typeof target === 'number' ? ray.at(target, out) : ray.intersectPlane(target, out);\n  }\n\n  /**\n   * Tone mapping for everything the view draws; see {@link ToneMapping}\n   *\n   * With no enabled `'beforeToneMapping'` effect in {@link View3D#passes | passes}, the curve is\n   * built into the material shaders, and a change recompiles them on the next frame. With one, the\n   * scene draws as linear light, so the effects see brightness above 1, and the curve runs once\n   * over the whole image after the last of them; a change rebuilds the render graph. Either way, don't change it every\n   * frame.\n   *\n   * The two look the same apart from see-through surfaces: with an effect, transparent surfaces\n   * blend, and glass refracts, in linear light before the curve.\n   * @example\n   * ```ts\n   * view.toneMapping = 'reinhard';\n   * ```\n   */\n  public get toneMapping(): ToneMapping {\n    return this._toneMapping;\n  }\n\n  /**\n   * Sets the tone mapping\n   * @param value - The curve for everything the view draws.\n   */\n  public set toneMapping(value: ToneMapping) {\n    if (this._toneMapping === value) return;\n    this._toneMapping = value;\n    if (this._passesInitialized && this._graph.sceneIsLinear) {\n      this._teardownGraph();\n      return;\n    }\n    this._toneMappingBit = TONE_MAPPING_BITS[value];\n    this._invalidateMaterialShaders();\n  }\n\n  /**\n   * How this view culls its meshes outside the camera's view; see {@link CullMode}\n   *\n   * A change rebuilds nothing. A {@link BatchedMesh3D} ignores it and culls by its own\n   * {@link BatchedMesh3D#cull | cull}.\n   * @default 'gpu'\n   * @example\n   * ```ts\n   * view.cull = gpuBound ? 'cpu' : 'gpu';\n   * ```\n   */\n  public get cull(): CullMode {\n    return this._sceneBatch.cull;\n  }\n\n  /**\n   * Sets how this view culls its meshes\n   * @param value - The culling mode.\n   */\n  public set cull(value: CullMode) {\n    this._sceneBatch.cull = value;\n  }\n\n  /**\n   * Texels per logical pixel the scene is drawn at, or `'inherit'` to take the resolution of the\n   * 2D target the view lands on\n   *\n   * Absolute, like a pixi filter's `resolution`: `1` on a DPR 2 screen draws the scene at half the\n   * physical size and stretches it over the view. Lower it for dynamic resolution when a device\n   * falls behind. Post effects' textures follow it unless an effect sets its own, and\n   * `Camera3D.jitter` comes out in the scene's pixels.\n   *\n   * A resolution other than the target's turns on {@link View3DOptions#composite | composite mode}.\n   * Turning composite mode on or off rebuilds the render graph on the next render, like assigning\n   * {@link View3D#passes}, so a dynamic-resolution loop that returns to the target's resolution\n   * rebuilds at every crossing; `composite: true`, or an enabled post effect, keeps that to once at\n   * most. Any other change rebuilds nothing, and allocates new textures only when the size crosses\n   * a power of two or the canvas size.\n   * @default 'inherit'\n   * @example\n   * ```ts\n   * // Draw the scene at two thirds of the screen's width and height\n   * view.resolution = app.renderer.resolution * 0.67;\n   * ```\n   */\n  public resolution: number | 'inherit';\n\n  /**\n   * How soft the edges of this view's shadows are; see {@link ShadowFilter}\n   *\n   * Once a light in the view casts shadows, a change recompiles the materials on the next frame;\n   * before that it compiles nothing.\n   * @default 'pcf'\n   * @example\n   * ```ts\n   * view.shadowFilter = isMobile ? 'hard' : 'pcf-high';\n   * ```\n   */\n  public get shadowFilter(): ShadowFilter {\n    return this._shadowFilter;\n  }\n\n  /**\n   * Sets the shadow filter\n   * @param value - Edge filtering for the shadows this view draws.\n   */\n  public set shadowFilter(value: ShadowFilter) {\n    if (this._shadowFilter === value) return;\n    this._shadowFilter = value;\n    this._invalidateMaterialShaders();\n  }\n\n  /**\n   * Distance fog, or `null` for none\n   *\n   * The view keeps the object you assign, so changing its `color`, `near`, `far` or `density`\n   * later is free. A new curve, or turning fog on or off, recompiles the materials on the next\n   * frame, like changing {@link View3D#toneMapping | toneMapping}.\n   * @example\n   * ```ts\n   * const haze: Fog = { type: 'linear', color: 0xadb2ba, near: 30, far: 55 };\n   *\n   * view.fog = haze;\n   * haze.far = 80;\n   * view.fog = null;\n   * ```\n   * @see {@link Fog} For the settings and their defaults.\n   */\n  public get fog(): Fog | null {\n    return this._fog;\n  }\n\n  /**\n   * Sets the fog\n   * @param value - Fog settings, or `null` for none.\n   */\n  public set fog(value: Fog | null) {\n    if (this._fog === value) return;\n    this._fog = value;\n    const nextBit = value ? FOG_BITS[value.type ?? 'linear'] : null;\n    if (nextBit !== this._fogBit) {\n      this._fogBit = nextBit;\n      this._invalidateMaterialShaders();\n    }\n  }\n\n  /**\n   * Passes and post effects added to this view\n   *\n   * One list holds both kinds: a {@link MeshPass} redraws the meshes that opt in at its stage, a\n   * {@link PostEffect} filters the scene's light or the finished picture, and any other\n   * {@link Pass3D} runs where it says. Items at the same stage run in array order, and the post\n   * effects run `'beforeToneMapping'` ones first, then the tone curve, then `'afterToneMapping'`\n   * ones.\n   *\n   * Assigning a new array rebuilds the render graph on the next render; changing the array in\n   * place does nothing. Flipping an item's `enabled` also rebuilds the graph, which suits a\n   * settings toggle; for changes every frame, use each item's own properties. Turning a scene\n   * output on or off recompiles the materials on the next frame, and so does turning on the first\n   * `'beforeToneMapping'` effect or turning off the last.\n   *\n   * The items stay yours: replacing the list never destroys them, and one instance can serve\n   * several views.\n   * @example\n   * ```ts\n   * view.passes = [new OutlinePass({ width: 0.05 }), new SsaoEffect()];\n   * view.passes[1].enabled = false;\n   * view.passes = [];\n   * ```\n   */\n  public get passes(): readonly Pass3D[] {\n    return this._passes;\n  }\n\n  /**\n   * Sets the pass list; `null` clears it\n   * @param value - Passes and post effects to run; the array is copied.\n   */\n  public set passes(value: readonly Pass3D[] | null) {\n    this._passes = value ? value.slice() : [];\n    if (this._passesInitialized) this._teardownGraph();\n  }\n\n  /** Bit `i & 31` per enabled pass, so a flip goes unnoticed while the pass 32 places away is enabled */\n  private _computePassesKey(): number {\n    let key = 0;\n    for (let i = 0; i < this._passes.length; i++) {\n      if (this._passes[i].enabled) key |= 1 << (i & 31);\n    }\n    return key;\n  }\n\n  /**\n   * Needs the view's bind group, so `unload` runs it before pixi's own; the passes unload before the\n   * graph is destroyed, and every light redraws its shadow, since the new shadow map starts empty\n   */\n  private _teardownGraph(): void {\n    this._graph.unload();\n    for (let i = 0; i < this.lights.length; i++) this.lights[i].refreshShadows();\n    this._graph.destroy();\n    this._passesInitialized = false;\n    this._graphGlobalData = null;\n    this._invalidateMaterialShaders();\n  }\n\n  /**\n   * Light from the surroundings, which fills in where the direct lights don't reach\n   *\n   * - A `CubeTexture`: image-based lighting from a cube map, reflections included. The first frame\n   *   that uses a cube map prefilters it, once, into a copy 128 to 256 pixels wide per face that\n   *   lighting and reflections read, so faces wider than 256 sharpen the background but not\n   *   reflections. The copy stays on the GPU until the cube map is destroyed with `destroy(true)` or\n   *   `Assets.unload`, even after the view switches away. A float cube, such as one {@link loadHdr}\n   *   makes from an `.hdr` file, is read as linear light, so an HDR environment keeps highlights\n   *   brighter than white; any other format is read as sRGB. On WebGL the prefilter needs\n   *   `EXT_color_buffer_float`, and throws without it.\n   * - A {@link Hemisphere}: a cheap gradient from sky to ground, with no textures. A good default\n   *   on mobile.\n   * - `null`: none, and the cheapest.\n   *\n   * Switching between kinds recompiles the materials on the next frame, like changing\n   * {@link View3D#toneMapping | toneMapping}. Changing a hemisphere's colours is free.\n   * @example\n   * ```ts\n   * view.environment = { skyColor: 0x88ccff, groundColor: 0x553311 };\n   *\n   * view.environment = await Assets.load<CubeTexture>('studio.cubemap');\n   *\n   * // An HDR panorama keeps the sun brighter than white\n   * view.environment = await Assets.load<CubeTexture>('sunset.hdr');\n   * ```\n   */\n  public get environment(): CubeTexture | Hemisphere | null {\n    return this._environment;\n  }\n\n  /**\n   * Sets the environment\n   * @param value - Cube map, hemisphere gradient, or `null` for none.\n   */\n  public set environment(value: CubeTexture | Hemisphere | null) {\n    if (this._environment === value) return;\n    this._environment = value;\n    const nextBit =\n      value === null ? envSourceDefaultBit : value instanceof CubeTexture ? envSourceCubeBit : envSourceHemisphereBit;\n    if (nextBit !== this._envBit) {\n      this._envBit = nextBit;\n      this._invalidateMaterialShaders();\n    }\n  }\n\n  /**\n   * Drawn behind the scene: a cube map, a {@link Hemisphere} gradient, a plain colour, or `null`\n   * for none\n   *\n   * Exposure and tone mapping apply to it. Set it to the same object as the\n   * {@link View3D#environment | environment} and the sky you see matches the light and reflections\n   * the scene receives. A hemisphere's fields are read every frame, so changing them is free. A view\n   * with no meshes draws nothing, background included, until a mesh joins its scene.\n   *\n   * A colour takes any `ColorSource` in display (sRGB) space and reads back as a hex number; its\n   * alpha is ignored. Exposure and the tone curve shift it on screen: under `'aces'`, white draws\n   * as light grey. To fade distant geometry into it, give the fog the same\n   * {@link Fog#color | color}. For a flat backdrop with no fog that shows the exact colour, leave\n   * `background` null and set the app's `backgroundColor`, which is never tone-mapped.\n   * @example\n   * ```ts\n   * const env = await Assets.load<CubeTexture>('env.cubemap');\n   * view.environment = env;\n   * view.background = env; // show the same cube map behind the scene\n   *\n   * // One hemisphere lights the scene and draws the sky behind it\n   * const sky: Hemisphere = { skyColor: 0x88ccff, groundColor: 0x553311 };\n   * view.environment = sky;\n   * view.background = sky;\n   * sky.skyColor = 0xff8800; // sunset, on the next frame\n   *\n   * // Distant geometry fades into a plain background\n   * view.background = 'skyblue';\n   * view.fog = { type: 'linear', color: 'skyblue', near: 20, far: 60 };\n   * view.background; // 0x87ceeb\n   * ```\n   */\n  public get background(): CubeTexture | Hemisphere | number | null {\n    return this._background;\n  }\n\n  /**\n   * Sets the background\n   * @param value - Cube map, hemisphere gradient, display-space colour, or `null` for none.\n   */\n  public set background(value: CubeTexture | Hemisphere | ColorSource | null) {\n    this._background =\n      value === null || value instanceof CubeTexture || (typeof value === 'object' && 'skyColor' in value)\n        ? value\n        : Color.shared.setValue(value).toNumber();\n  }\n\n  /**\n   * Turns shadow sampling on once one of the first `MAX_LIGHTS` packed lights casts\n   * @internal\n   */\n  public _syncShadowSampling(): void {\n    if (this._hasShadows) return;\n\n    const lights = this.lights;\n    let packedLightCount = 0;\n\n    for (let i = 0; i < lights.length; i++) {\n      const light = lights[i];\n\n      if (!light._worldVisible || light.type === 'ambient') continue;\n      if (packedLightCount >= MAX_LIGHTS) return;\n\n      packedLightCount++;\n\n      if (!light.canCastShadow) continue;\n\n      this._hasShadows = true;\n      this._invalidateMaterialShaders();\n\n      return;\n    }\n  }\n\n  /** Refills each user batch's `_dirtyIndices` from the start, since appending every index could run past its end */\n  private _invalidateMaterialShaders(): void {\n    const meshes = this.meshes.items;\n    for (let i = 0; i < meshes.length; i++) meshes[i]._markBatchDirty();\n\n    for (let b = 1; b < this._meshBatches.length; b++) {\n      const batch = this._meshBatches[b];\n      const items = batch.items;\n      for (let i = 0; i < items.length; i++) items[i]._batchDirty = true;\n      if (batch._dirtyIndices) {\n        for (let i = 0; i < items.length; i++) batch._dirtyIndices[i] = i;\n        batch._dirtyCount = items.length;\n      }\n    }\n  }\n\n  /**\n   * Queues a mesh for the next scene update; `Mesh3D._queueMeshUpdate` makes sure it isn't queued already\n   * @internal\n   */\n  public _onRenderableUpdate(mesh: Mesh3D): void {\n    const queue = this._renderablesToUpdate;\n    queue.list[queue.index++] = mesh;\n  }\n\n  /** @internal */\n  protected updateBounds(): void {\n    const bounds = this._bounds;\n\n    const width = this._width;\n    const height = this._height;\n    const { x, y } = this._anchor;\n\n    bounds.minX = -x * width;\n    bounds.maxX = bounds.minX + width;\n\n    bounds.minY = -y * height;\n    bounds.maxY = bounds.minY + height;\n  }\n\n  /**\n   * Registers `child` and its subtree; pick state follows the rule of `getAncestorPickState` in\n   * `FederatedEventTarget3D.ts`, and `events` must exist first, since picking registers on it\n   * @internal\n   */\n  public _attach(child: Container3D, ancestorPickState: AncestorPickState = getAncestorPickState(child)) {\n    child._updateTick = -1;\n\n    child._view3d = this;\n\n    if (child === this.root) {\n      child._relativeSceneDepth = 0;\n    } else {\n      child._relativeSceneDepth = child.parent!._relativeSceneDepth + 1;\n    }\n\n    child.didChange = true;\n    this._onChildUpdate(child);\n\n    const mode = child._eventMode;\n    const childPickState: AncestorPickState =\n      mode === 'none' || !child._interactiveChildren || ancestorPickState === PICK_BLOCKED\n        ? PICK_BLOCKED\n        : mode === 'static' || mode === 'dynamic'\n          ? PICK_COVERED\n          : ancestorPickState;\n\n    const children = child.children;\n\n    for (let i = 0; i < children.length; i++) {\n      this._attach(children[i], childPickState);\n    }\n\n    if (child instanceof BatchedMesh3D) {\n      this._meshBatches.push(child.batch);\n      this._meshBatchesDirtyId++;\n    } else if (child instanceof Mesh3D) {\n      this._meshSlots.add(child);\n      this.meshes.add(child);\n\n      if (child.skeleton) {\n        this._skinnedMeshes.add(child);\n      }\n\n      if (child._morph) {\n        this._morphedMeshes.add(child);\n      }\n      child.geometry._meshes.add(child);\n      child.material._meshes.add(child);\n      child._markBatchDirty();\n    } else if (child instanceof Light) {\n      this.lights.push(child);\n    }\n\n    if (\n      ancestorPickState !== PICK_BLOCKED &&\n      (child._isPickCandidate() || (ancestorPickState === PICK_COVERED && mode !== 'none' && child._hasPickVolume()))\n    ) {\n      this.events._addInteractive(child);\n    }\n\n    if (child._hitVolumeInput !== null) this.events._clipVolumeCount++;\n  }\n\n  /**\n   * Unregisters `child` and its subtree; a mesh's `_lastWorldVisible` resets so one that comes back\n   * hidden still writes its store row. The root never detaches, so `destroy` frees its mesh lists and morph slot.\n   * @internal\n   */\n  public _detach(child: Container3D) {\n    const children = child.children;\n\n    for (let i = 0; i < children.length; i++) {\n      this._detach(children[i]);\n    }\n\n    if (child instanceof BatchedMesh3D) {\n      const idx = this._meshBatches.indexOf(child.batch);\n      if (idx > 0) {\n        this._meshBatches.splice(idx, 1);\n        this._meshBatchesDirtyId++;\n      }\n    } else if (child instanceof Mesh3D) {\n      const slotIndex = this._meshSlots.getIndex(child);\n      this._sceneBatch.setPassesAt(slotIndex, 0);\n\n      this._meshSlots.remove(child);\n      this.meshes.remove(child);\n      this._sceneBatch.storeBuffer.remove(child);\n      child.geometry._meshes.remove(child);\n      child.material._meshes.remove(child);\n      child.didRenderableUpdate = false;\n      child._lastWorldVisible = 1;\n      child._lastBonePitIndex = -1;\n\n      if (child.skeleton) {\n        this._skinnedMeshes.remove(child);\n      }\n\n      if (child._morph) {\n        this._morphedMeshes.remove(child);\n        child._morph._store?.freeSlot(child._morph);\n      }\n    } else if (child instanceof Light) {\n      const index = this.lights.indexOf(child);\n\n      if (index > -1) {\n        this.lights.splice(index, 1);\n      }\n\n      child._releaseShadowState();\n    }\n\n    if (child._pickIndex !== -1) {\n      this.events._removeInteractive(child);\n    } else {\n      this.events._clearPickState(child);\n    }\n\n    if (child._hitVolumeInput !== null) this.events._clipVolumeCount--;\n\n    child._view3d = null;\n  }\n\n  /** @internal */\n  public _onChildUpdate(child: Container3D) {\n    let childrenToUpdate = this._childrenToUpdate[child._relativeSceneDepth];\n\n    if (!childrenToUpdate) {\n      childrenToUpdate = this._childrenToUpdate[child._relativeSceneDepth] = {\n        index: 0,\n        list: [],\n      };\n    }\n\n    childrenToUpdate.list[childrenToUpdate.index++] = child;\n  }\n\n  /**\n   * Rebuilds every batch's draw commands next frame; keep it for what the whole view binds, such as a\n   * shared store reallocating\n   * @internal\n   */\n  public _invalidateDrawCaches(): void {\n    for (let b = 0; b < this._meshBatches.length; b++) this._meshBatches[b].invalidateDrawCaches();\n  }\n\n  /**\n   * Re-records every batch's WebGPU bundles next frame, keeping the draw commands\n   * @internal\n   */\n  public _invalidateBundleCaches(): void {\n    for (let b = 0; b < this._meshBatches.length; b++) this._meshBatches[b].invalidateBundleCaches();\n  }\n\n  /**\n   * Lets go of the pooled textures this view still binds, before pixi's texture pool destroys them;\n   * without a graph there's nothing to do, since its teardown already let them go\n   * @internal\n   */\n  public _releasePooledTextures(): void {\n    if (!this._passesInitialized) return;\n    this._graph._releaseTransients();\n    this._invalidateBundleCaches();\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.addChild()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override addChild<U extends ContainerChild[]>(..._children: U): U[0] {\n    throw new Error('View3D.addChild() is not available. Use view.root.addChild() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.removeChild()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override removeChild<U extends ContainerChild[]>(..._children: U): U[0] {\n    throw new Error('View3D.removeChild() is not available. Use view.root.removeChild() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.removeChildren()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override removeChildren(_beginIndex?: number, _endIndex?: number): ContainerChild[] {\n    throw new Error('View3D.removeChildren() is not available. Use view.root.removeChildren() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.removeChildAt()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override removeChildAt<U extends ContainerChild>(_index: number): U {\n    throw new Error('View3D.removeChildAt() is not available. Use view.root.removeChildAt() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.getChildAt()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override getChildAt<U extends ContainerChild>(_index: number): U {\n    throw new Error('View3D.getChildAt() is not available. Use view.root.getChildAt() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.setChildIndex()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override setChildIndex(_child: ContainerChild, _index: number): void {\n    throw new Error('View3D.setChildIndex() is not available. Use view.root.setChildIndex() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.getChildIndex()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override getChildIndex(_child: ContainerChild): number {\n    throw new Error('View3D.getChildIndex() is not available. Use view.root.getChildIndex() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.addChildAt()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override addChildAt<U extends ContainerChild>(_child: U, _index: number): U {\n    throw new Error('View3D.addChildAt() is not available. Use view.root.addChildAt() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.swapChildren()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override swapChildren<U extends ContainerChild>(_child: U, _child2: U): void {\n    throw new Error('View3D.swapChildren() is not available. Use view.root.swapChildren() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.reparentChild()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override reparentChild<U extends ContainerChild[]>(..._child: U): U[0] {\n    throw new Error('View3D.reparentChild() is not available. Use view.root.reparentChild() instead.');\n  }\n\n  /**\n   * Not available on `View3D`; use `view.root.reparentChildAt()` instead\n   * @throws {Error} Always.\n   * @ignore\n   */\n  public override reparentChildAt<U extends ContainerChild>(_child: U, _index: number): U {\n    throw new Error('View3D.reparentChildAt() is not available. Use view.root.reparentChildAt() instead.');\n  }\n\n  /**\n   * Builds the render graph when there is none or it went stale, compiling it again since a custom\n   * builder may not have; the view camera's pass owns a shared draw-list bit even when a texture camera's comes first\n   * @throws If the graph was built with another renderer's global data.\n   * @internal\n   */\n  public _ensureInitialized(\n    renderer: WebGLRenderer | WebGPURenderer,\n    globalData: View3DGlobalData,\n    targetResolution: number,\n  ): void {\n    const sceneResolution = this.resolution === 'inherit' ? targetResolution : this.resolution;\n    const composite = this._composite || sceneResolution !== targetResolution;\n\n    if (this._passesInitialized) {\n      const passesChanged = this._passes.length > 0 && this._passesEnabledKey !== this._computePassesKey();\n      const compositeChanged =\n        composite !== this._compositeRequested && !(composite && this._graph.sceneColor !== this._graph.defaultColor);\n      if (passesChanged || compositeChanged) this._teardownGraph();\n    }\n\n    if (this._passesInitialized) {\n      if (this._graphGlobalData !== globalData) {\n        throw new Error('View3D: a view renders with one renderer; its render graph was built for another');\n      }\n    } else {\n      this._graphGlobalData = globalData;\n\n      const graphOptions: DefaultGraph3DOptions = {\n        composite,\n        passes: this._passes,\n        toneMapping: this._toneMapping,\n        globalTextureBindings: globalData.globalTextureBindings,\n      };\n      this._graph = this._buildGraph\n        ? this._buildGraph(renderer, graphOptions)\n        : createDefaultGraph3D(renderer, graphOptions).graph;\n      this._graph.compile();\n      this._toneMappingBit = this._graph.sceneIsLinear ? null : TONE_MAPPING_BITS[this._toneMapping];\n      this._passesEnabledKey = this._computePassesKey();\n      this._compositeRequested = composite;\n\n      for (const k in this.passByBit) delete this.passByBit[k];\n      this._dirtyHookBits = 0;\n      for (const graphPass of this._graph.passes) {\n        const pass = graphPass as RenderPass;\n        if (pass.bit === RenderPassBit.NONE) continue;\n        const owner = this.passByBit[pass.bit];\n        if (pass.camera) {\n          if (owner) continue;\n        } else if (owner && !owner.camera) {\n          throw new Error(`Render pass \"${pass.name}\" is used twice in this view; give the second one a camera.`);\n        }\n        this.passByBit[pass.bit] = pass;\n        this._dirtyHookBits |= pass.bit;\n      }\n\n      for (const graphPass of this._graph.passes) {\n        const pass = graphPass as RenderPass;\n        if (pass.bit === RenderPassBit.NONE || !pass.descriptor) continue;\n        if (this.passByBit[pass.bit] === pass) continue;\n        throw new Error(\n          `Render pass \"${pass.name}\" has a descriptor, but another pass owns that name. ` +\n            'Put the descriptor there, or give this pass its own name.',\n        );\n      }\n\n      this._passesInitialized = true;\n    }\n\n    this._graph.resolution = this._graph.sceneColor === this._graph.defaultColor ? targetResolution : sceneResolution;\n  }\n\n  /**\n   * Frees this view's GPU memory now, for a scene you'll show again later\n   *\n   * The next render that draws the view rebuilds everything, so nothing needs re-creating by\n   * hand. It frees the view's draw state, shadow map, uniforms and buffers, and keeps CPU data:\n   * the scene and every typed array, the way a 2D texture keeps its source image across `unload`.\n   * The scene's geometry and textures stay on the GPU; {@link Container3D#unload} says how to free them.\n   *\n   * pixi's garbage collector calls it for a view that has been out of the stage for\n   * `gcMaxUnusedTime`. It never collects a view still in a stage, even a hidden one, nor one that\n   * is a render group or left the stage inside one (`isRenderGroup`, `cacheAsTexture`, or rendered\n   * directly, as `extract` does); set `autoGarbageCollect` to `false` to keep any view.\n   * @example\n   * ```ts\n   * view.visible = false; // hiding alone never frees anything\n   * view.unload();\n   * ```\n   * @see {@link View3D#destroy} For permanent teardown.\n   */\n  public override unload(): void {\n    if (this.destroyed) return;\n\n    for (let i = 0; i < this._meshBatches.length; i++) this._meshBatches[i].unload();\n\n    for (let i = 0; i < this.lights.length; i++) {\n      const light = this.lights[i];\n      if (!light._gpuShadowData) continue;\n      light._releaseShadowState();\n      light.refreshShadows();\n    }\n\n    this._bonePit.unload();\n\n    if (this._passesInitialized) this._teardownGraph();\n\n    super.unload();\n  }\n\n  /**\n   * Destroys this view and the GPU resources it owns\n   *\n   * The view's own GPU state always goes, whatever `options` says. With the `children` flag,\n   * {@link View3D#root | root} is destroyed too, with the same `options`, so the `geometry`,\n   * `material` and `texture` flags apply to it. Without the flag, the scene's nodes survive for you\n   * to reuse, but they're removed from `root`, which is left empty.\n   * @example\n   * ```ts\n   * view.destroy({ children: true });\n   * ```\n   * @param options - Teardown options; see {@link Destroy3DOptions}. A boolean stands in for every\n   *   flag. Leaving it out destroys nothing shared.\n   */\n  public override destroy(options?: Destroy3DOptions): void {\n    if (this.destroyed) return;\n\n    this.unload();\n\n    const root = this.root;\n    if (root instanceof Mesh3D && !root.destroyed) {\n      root.geometry._meshes.remove(root);\n      root.material._meshes.remove(root);\n      root.didRenderableUpdate = false;\n    }\n\n    if (resolveDestroy3DFlag(options, 'children')) {\n      this.root.destroy(options);\n    } else {\n      this.root.removeChildren(0, this.root.children.length);\n      this.root._view3d = null;\n    }\n\n    if (this._passesInitialized && this._graph) this._graph.destroy();\n\n    this._bonePit.destroy();\n\n    const morphedMeshes = this._morphedMeshes.items;\n    for (let i = 0; i < morphedMeshes.length; i++) {\n      const morph = morphedMeshes[i]._morph!;\n      morph._store?.freeSlot(morph);\n    }\n\n    this._sceneBatch.destroy();\n\n    this._meshSlots.items.length = 0;\n    this._meshSlots.count = 0;\n    (this.meshes as UnstableList<Mesh3D> | null) = null;\n    (this._skinnedMeshes as UnstableList<Mesh3D> | null) = null;\n    (this._morphedMeshes as UnstableList<Mesh3D> | null) = null;\n    (this._childrenToUpdate as View3D['_childrenToUpdate'] | null) = null;\n    (this._renderablesToUpdate as View3D['_renderablesToUpdate'] | null) = null;\n\n    this.events.destroy();\n\n    (this.passByBit as Record<number, RenderPass> | null) = null;\n    this._dirtyHookBits = 0;\n\n    super.destroy(options);\n\n    (this.lights as Light[] | null) = null;\n    (this._meshBatches as Mesh3DBatch[] | null) = null;\n  }\n}\n","import type { BindGroup, UniformData } from 'pixi.js';\n\nimport type { GlobalUniformGroup } from '../core/GlobalUniformGroup';\nimport type { GlobalTextureBindings } from '../core/render-graph/TextureBinding';\n\n/**\n * A view's global uniforms and bind group for one renderer, at `view._gpuData[renderer.uid]`;\n * pixi destroys it when the view unloads or the renderer is destroyed\n * @internal\n */\nexport class View3DGlobalData<TExtra extends Record<string, UniformData> = Record<never, UniformData>> {\n  public readonly globalUniformGroup: GlobalUniformGroup<TExtra>;\n\n  public readonly globalBindGroup: BindGroup;\n\n  public readonly globalTextureBindings: GlobalTextureBindings;\n\n  /** Last-seen `bufferVersion` of each shared store; `-1` makes the first render rebuild the draw caches */\n  public lastMaterialStoreBufferVersion = -1;\n  /** Separate from `View3D._lastAtlasBufferVersion` on purpose; that field says why */\n  public lastAtlasBufferVersion = -1;\n  public lastMorphStoreBufferVersion = -1;\n  public lastGeometryStoreBufferVersion = -1;\n\n  private _destroyed = false;\n\n  constructor(\n    globalUniformGroup: GlobalUniformGroup<TExtra>,\n    globalBindGroup: BindGroup,\n    globalTextureBindings: GlobalTextureBindings,\n  ) {\n    this.globalUniformGroup = globalUniformGroup;\n    this.globalBindGroup = globalBindGroup;\n    this.globalTextureBindings = globalTextureBindings;\n  }\n\n  /** Destroys the bind group before the buffer it binds */\n  public destroy(): void {\n    if (this._destroyed) return;\n    this._destroyed = true;\n\n    this.globalBindGroup.destroy();\n    this.globalUniformGroup.buffer?.destroy();\n  }\n}\n","import type { UniformData } from 'pixi.js';\nimport { uniformParsers } from 'pixi.js';\n\n/**\n * The `vec3<f32>` tests check `type` because pixi's uniform-buffer path doesn't, and the `mat3x3` buffer write\n * skips every fourth float, the padding a uniform buffer gives each column\n * @internal\n */\nexport function addUniformParsers(): void {\n  uniformParsers.push({\n    type: 'mat4x4<f32>',\n    test: (data: UniformData) => (data.value as { elements?: ArrayLike<number> }).elements?.length === 16,\n    uniform: `\n        gl.uniformMatrix4fv(ud[name].location, false, uv[name].elements);\n        `,\n    ubo: `\n        var v = uv[name].elements;\n        for(var i=0;i<16;i++)\n        {\n            data[offset + i] = v[i];\n        }\n    `,\n  });\n\n  uniformParsers.push({\n    type: 'mat3x3<f32>',\n    test: (data: UniformData) => (data.value as { elements?: ArrayLike<number> }).elements?.length === 9,\n    uniform: `\n        gl.uniformMatrix3fv(ud[name].location, false, uv[name].elements);\n        `,\n    ubo: `\n        var v = uv[name].elements;\n        data[offset] = v[0];\n        data[offset + 1] = v[1];\n        data[offset + 2] = v[2];\n        data[offset + 4] = v[3];\n        data[offset + 5] = v[4];\n        data[offset + 6] = v[5];\n        data[offset + 8] = v[6];\n        data[offset + 9] = v[7];\n        data[offset + 10] = v[8];\n    `,\n  });\n\n  uniformParsers.push({\n    type: 'vec3<f32>',\n    test: (data: UniformData) =>\n      data.type === 'vec3<f32>' && data.size === 1 && (data.value as { x?: number }).x !== undefined,\n    uniform: `\n        cv = ud[name].value;\n        v = uv[name];\n\n        if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.z)\n        {\n            cv[0] = v.x;\n            cv[1] = v.y;\n            cv[2] = v.z;\n            gl.uniform3f(ud[name].location, v.x, v.y, v.z);\n        }\n        `,\n    ubo: `\n        v = uv[name];\n        data[offset] = v.x;\n        data[offset + 1] = v.y;\n        data[offset + 2] = v.z;\n    `,\n  });\n\n  uniformParsers.push({\n    type: 'vec3<f32>',\n    test: (data: UniformData) =>\n      data.type === 'vec3<f32>' &&\n      (data.value as { r?: number }).r !== undefined &&\n      (data.value as { g?: number }).g !== undefined &&\n      (data.value as { b?: number }).b !== undefined,\n    uniform: `\n        cv = ud[name].value;\n        v = uv[name];\n\n        if(cv[0] !== v.r || cv[1] !== v.g || cv[2] !== v.b)\n        {\n            cv[0] = v.r;\n            cv[1] = v.g;\n            cv[2] = v.b;\n            gl.uniform3f(ud[name].location, v.r, v.g, v.b);\n        }\n        `,\n    ubo: `\n        v = uv[name];\n        data[offset] = v.r;\n        data[offset + 1] = v.g;\n        data[offset + 2] = v.b;\n    `,\n  });\n}\n","import { extensions } from 'pixi.js';\n\nimport { loadCubemap } from './loaders/cubemap/loadCubemap';\nimport { loadGlb } from './loaders/gltf/loadGlb';\nimport { loadGltf } from './loaders/gltf/loadGltf';\nimport { loadHdr } from './loaders/hdr/loadHdr';\n\nextensions.add(loadGltf, loadGlb, loadCubemap, loadHdr);\n","import { extensions } from 'pixi.js';\n\nimport { Container3D } from '../scene/Container3D';\nimport { View3D } from '../scene/View3D';\nimport { FederatedContainer3D } from './FederatedEventTarget3D';\nimport { View3DEvents } from './View3DEvents';\n\nextensions.mixin(Container3D, FederatedContainer3D);\nextensions.mixin(View3D, View3DEvents);\n","import { extensions, ExtensionType } from 'pixi.js';\n\nimport './assets/init';\nimport './events/init';\nimport { addUniformParsers } from './utils/addUniformParsers';\n\n/** Loaded lazily, so a page downloads only the backend its renderer picks */\nconst backendLoaders = [\n  { extension: { type: ExtensionType.WebGLLoader, name: 'pixijs-3d' }, load: () => import('./core/gl/init') },\n  { extension: { type: ExtensionType.WebGPULoader, name: 'pixijs-3d' }, load: () => import('./core/gpu/init') },\n];\n\naddUniformParsers();\nextensions.add(...backendLoaders);\n"],"mappings":";;;;;48BA6EA,IAAa,GAAb,KAAuB,CASrB,MAKA,OAUA,SAAkB,EAKlB,YAAY,EAA2B,CACrC,KAAK,MAAQ,EAAQ,MACrB,KAAK,OAAS,EAAQ,QAAU,CAAC,EACjC,KAAK,SAAW,EAAQ,UAAY,KAAK,aAAa,CACxD,CAEA,cAA+B,CAC7B,IAAI,EAAU,EACd,IAAK,IAAI,EAAI,EAAG,EAAI,KAAK,OAAO,OAAQ,IAAK,CAC3C,IAAM,EAAQ,KAAK,OAAO,GACpB,EAAY,EAAM,MAAM,EAAM,MAAM,OAAS,GAC/C,EAAY,IACd,EAAU,EAEd,CAEA,OAAO,CAC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