@luma.gl/engine 10.0.0-alpha.4 → 10.0.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/animation/animation-clip.cjs +36 -0
- package/dist/animation/animation-interpolation.cjs +115 -0
- package/dist/animation/animation-mixer.cjs +302 -0
- package/dist/animation/animation-track.cjs +55 -0
- package/dist/animation/animator.cjs +75 -0
- package/dist/animation/deform-positions.cjs +69 -0
- package/dist/animation/deform-positions.d.ts +13 -0
- package/dist/animation/deform-positions.d.ts.map +1 -0
- package/dist/animation/deform-positions.js +49 -0
- package/dist/animation/deform-positions.js.map +1 -0
- package/dist/animation/key-frames.cjs +81 -0
- package/dist/animation/morph-targets.cjs +162 -0
- package/dist/animation/node-animation-binding.cjs +67 -0
- package/dist/animation/node-animation-binding.d.ts +9 -0
- package/dist/animation/node-animation-binding.d.ts.map +1 -0
- package/dist/animation/node-animation-binding.js +45 -0
- package/dist/animation/node-animation-binding.js.map +1 -0
- package/dist/animation/property-animation-binding.cjs +159 -0
- package/dist/animation/property-animation-binding.d.ts +29 -0
- package/dist/animation/property-animation-binding.d.ts.map +1 -0
- package/dist/animation/property-animation-binding.js +138 -0
- package/dist/animation/property-animation-binding.js.map +1 -0
- package/dist/animation/scenegraph-animator.cjs +122 -0
- package/dist/animation/scenegraph-animator.d.ts +37 -0
- package/dist/animation/scenegraph-animator.d.ts.map +1 -0
- package/dist/animation/scenegraph-animator.js +99 -0
- package/dist/animation/scenegraph-animator.js.map +1 -0
- package/dist/animation/skin.cjs +49 -0
- package/dist/animation/texture-transform.cjs +41 -0
- package/dist/animation/texture-transform.d.ts +8 -0
- package/dist/animation/texture-transform.d.ts.map +1 -0
- package/dist/animation/texture-transform.js +17 -0
- package/dist/animation/texture-transform.js.map +1 -0
- package/dist/animation/timeline.cjs +129 -0
- package/dist/animation-loop/animation-loop-template.cjs +33 -0
- package/dist/animation-loop/animation-loop.cjs +498 -0
- package/dist/animation-loop/animation-loop.d.ts +2 -1
- package/dist/animation-loop/animation-loop.d.ts.map +1 -1
- package/dist/animation-loop/animation-loop.js +9 -3
- package/dist/animation-loop/animation-loop.js.map +1 -1
- package/dist/animation-loop/animation-props.cjs +15 -0
- package/dist/animation-loop/make-animation-loop.cjs +104 -0
- package/dist/animation-loop/request-animation-frame.cjs +43 -0
- package/dist/application-utils/load-file.cjs +77 -0
- package/dist/application-utils/random.cjs +38 -0
- package/dist/audio/audio-controller.cjs +429 -0
- package/dist/audio/audio-controller.d.ts +146 -0
- package/dist/audio/audio-controller.d.ts.map +1 -0
- package/dist/audio/audio-controller.js +445 -0
- package/dist/audio/audio-controller.js.map +1 -0
- package/dist/audio/audio-environment.cjs +157 -0
- package/dist/audio/audio-environment.d.ts +49 -0
- package/dist/audio/audio-environment.d.ts.map +1 -0
- package/dist/audio/audio-environment.js +148 -0
- package/dist/audio/audio-environment.js.map +1 -0
- package/dist/audio/audio-graph.cjs +182 -0
- package/dist/audio/audio-graph.d.ts +58 -0
- package/dist/audio/audio-graph.d.ts.map +1 -0
- package/dist/audio/audio-graph.js +181 -0
- package/dist/audio/audio-graph.js.map +1 -0
- package/dist/compute/buffer-transform.cjs +146 -0
- package/dist/compute/buffer-transform.d.ts +15 -5
- package/dist/compute/buffer-transform.d.ts.map +1 -1
- package/dist/compute/buffer-transform.js +56 -12
- package/dist/compute/buffer-transform.js.map +1 -1
- package/dist/compute/computation.cjs +331 -0
- package/dist/compute/computation.d.ts +2 -4
- package/dist/compute/computation.d.ts.map +1 -1
- package/dist/compute/computation.js +3 -14
- package/dist/compute/computation.js.map +1 -1
- package/dist/compute/swap.cjs +132 -0
- package/dist/compute/texture-transform.cjs +142 -0
- package/dist/compute/texture-transform.d.ts +11 -7
- package/dist/compute/texture-transform.d.ts.map +1 -1
- package/dist/compute/texture-transform.js +16 -6
- package/dist/compute/texture-transform.js.map +1 -1
- package/dist/controls/orbit-controls.cjs +283 -0
- package/dist/controls/orbit-controls.d.ts +2 -0
- package/dist/controls/orbit-controls.d.ts.map +1 -1
- package/dist/controls/orbit-controls.js +2 -1
- package/dist/controls/orbit-controls.js.map +1 -1
- package/dist/debug/copy-texture-to-image.cjs +84 -0
- package/dist/debug/debug-framebuffer.cjs +113 -0
- package/dist/debug/debug-shader-layout.cjs +45 -0
- package/dist/debug/pixel-data-utils.cjs +54 -0
- package/dist/dist.dev.js +11756 -5632
- package/dist/dist.min.js +39 -35
- package/dist/dynamic-buffer/dynamic-buffer.cjs +39 -0
- package/dist/dynamic-buffer/dynamic-buffer.d.ts +1 -170
- package/dist/dynamic-buffer/dynamic-buffer.d.ts.map +1 -1
- package/dist/dynamic-buffer/dynamic-buffer.js +2 -312
- package/dist/dynamic-buffer/dynamic-buffer.js.map +1 -1
- package/dist/dynamic-texture/dynamic-texture.cjs +27 -0
- package/dist/dynamic-texture/dynamic-texture.d.ts +1 -114
- package/dist/dynamic-texture/dynamic-texture.d.ts.map +1 -1
- package/dist/dynamic-texture/dynamic-texture.js +2 -584
- package/dist/dynamic-texture/dynamic-texture.js.map +1 -1
- package/dist/dynamic-texture/texture-binding-source.cjs +31 -0
- package/dist/dynamic-texture/texture-binding-source.d.ts +1 -54
- package/dist/dynamic-texture/texture-binding-source.d.ts.map +1 -1
- package/dist/dynamic-texture/texture-binding-source.js +2 -51
- package/dist/dynamic-texture/texture-binding-source.js.map +1 -1
- package/dist/dynamic-texture/texture-data.cjs +53 -0
- package/dist/dynamic-texture/texture-data.d.ts +1 -145
- package/dist/dynamic-texture/texture-data.d.ts.map +1 -1
- package/dist/dynamic-texture/texture-data.js +2 -209
- package/dist/dynamic-texture/texture-data.js.map +1 -1
- package/dist/dynamic-texture/video-texture.cjs +269 -0
- package/dist/dynamic-texture/video-texture.d.ts +1 -1
- package/dist/dynamic-texture/video-texture.d.ts.map +1 -1
- package/dist/experimental/controls/comparison-splitter.cjs +231 -0
- package/dist/experimental/controls/comparison-splitter.d.ts +54 -0
- package/dist/experimental/controls/comparison-splitter.d.ts.map +1 -0
- package/dist/experimental/controls/comparison-splitter.js +215 -0
- package/dist/experimental/controls/comparison-splitter.js.map +1 -0
- package/dist/experimental/controls/flat-controller.cjs +301 -0
- package/dist/experimental/controls/flat-controller.d.ts +80 -0
- package/dist/experimental/controls/flat-controller.d.ts.map +1 -0
- package/dist/experimental/controls/flat-controller.js +295 -0
- package/dist/experimental/controls/flat-controller.js.map +1 -0
- package/dist/experimental/controls/index.cjs +35 -0
- package/dist/experimental/controls/index.cjs.map +6 -0
- package/dist/experimental/controls/index.d.ts +7 -0
- package/dist/experimental/controls/index.d.ts.map +1 -0
- package/dist/experimental/controls/index.js +7 -0
- package/dist/experimental/controls/index.js.map +1 -0
- package/dist/experimental/controls/orbit-controls.cjs +27 -0
- package/dist/experimental/controls/orbit-controls.d.ts +3 -0
- package/dist/experimental/controls/orbit-controls.d.ts.map +1 -0
- package/dist/experimental/controls/orbit-controls.js +5 -0
- package/dist/experimental/controls/orbit-controls.js.map +1 -0
- package/dist/experimental/materials/emissive-material.cjs +126 -0
- package/dist/experimental/materials/emissive-material.d.ts +38 -0
- package/dist/experimental/materials/emissive-material.d.ts.map +1 -0
- package/dist/experimental/materials/emissive-material.js +100 -0
- package/dist/experimental/materials/emissive-material.js.map +1 -0
- package/dist/experimental/materials/glass-material.cjs +570 -0
- package/dist/experimental/materials/glass-material.d.ts +107 -0
- package/dist/experimental/materials/glass-material.d.ts.map +1 -0
- package/dist/experimental/materials/glass-material.js +544 -0
- package/dist/experimental/materials/glass-material.js.map +1 -0
- package/dist/experimental/materials/glass-transmission.cjs +954 -0
- package/dist/experimental/materials/glass-transmission.d.ts +193 -0
- package/dist/experimental/materials/glass-transmission.d.ts.map +1 -0
- package/dist/experimental/materials/glass-transmission.js +928 -0
- package/dist/experimental/materials/glass-transmission.js.map +1 -0
- package/dist/experimental/materials/index.cjs +61 -0
- package/dist/experimental/materials/index.cjs.map +6 -0
- package/dist/experimental/materials/index.d.ts +14 -0
- package/dist/experimental/materials/index.d.ts.map +1 -0
- package/dist/experimental/materials/index.js +11 -0
- package/dist/experimental/materials/index.js.map +1 -0
- package/dist/experimental/materials/optical-caustics.cjs +201 -0
- package/dist/experimental/materials/optical-caustics.d.ts +69 -0
- package/dist/experimental/materials/optical-caustics.d.ts.map +1 -0
- package/dist/experimental/materials/optical-caustics.js +180 -0
- package/dist/experimental/materials/optical-caustics.js.map +1 -0
- package/dist/experimental/materials/optical-lighting.cjs +169 -0
- package/dist/experimental/materials/optical-lighting.d.ts +7 -0
- package/dist/experimental/materials/optical-lighting.d.ts.map +1 -0
- package/dist/experimental/materials/optical-lighting.js +144 -0
- package/dist/experimental/materials/optical-lighting.js.map +1 -0
- package/dist/experimental/materials/optical-point-lights.cjs +258 -0
- package/dist/experimental/materials/optical-point-lights.d.ts +68 -0
- package/dist/experimental/materials/optical-point-lights.d.ts.map +1 -0
- package/dist/experimental/materials/optical-point-lights.js +237 -0
- package/dist/experimental/materials/optical-point-lights.js.map +1 -0
- package/dist/experimental/materials/reflective-material.cjs +216 -0
- package/dist/experimental/materials/reflective-material.d.ts +46 -0
- package/dist/experimental/materials/reflective-material.d.ts.map +1 -0
- package/dist/experimental/materials/reflective-material.js +190 -0
- package/dist/experimental/materials/reflective-material.js.map +1 -0
- package/dist/experimental/textures/html-texture.cjs +221 -0
- package/dist/experimental/textures/html-texture.d.ts +85 -0
- package/dist/experimental/textures/html-texture.d.ts.map +1 -0
- package/dist/experimental/textures/html-texture.js +206 -0
- package/dist/experimental/textures/html-texture.js.map +1 -0
- package/dist/experimental/textures/index.cjs +33 -0
- package/dist/experimental/textures/index.cjs.map +6 -0
- package/dist/experimental/textures/index.d.ts +5 -0
- package/dist/experimental/textures/index.d.ts.map +1 -0
- package/dist/experimental/textures/index.js +7 -0
- package/dist/experimental/textures/index.js.map +1 -0
- package/dist/experimental/textures/packed-pixels.cjs +248 -0
- package/dist/experimental/textures/packed-pixels.d.ts +17 -0
- package/dist/experimental/textures/packed-pixels.d.ts.map +1 -0
- package/dist/experimental/textures/packed-pixels.js +237 -0
- package/dist/experimental/textures/packed-pixels.js.map +1 -0
- package/dist/experimental/textures/rgba-decoder.cjs +60 -0
- package/dist/experimental/textures/rgba-decoder.d.ts +29 -0
- package/dist/experimental/textures/rgba-decoder.d.ts.map +1 -0
- package/dist/experimental/textures/rgba-decoder.js +43 -0
- package/dist/experimental/textures/rgba-decoder.js.map +1 -0
- package/dist/experimental/webxr/index.cjs +38 -0
- package/dist/experimental/webxr/index.cjs.map +6 -0
- package/dist/experimental/webxr/index.d.ts +9 -0
- package/dist/experimental/webxr/index.d.ts.map +1 -0
- package/dist/experimental/webxr/index.js +8 -0
- package/dist/experimental/webxr/index.js.map +1 -0
- package/dist/experimental/webxr/webxr-animation-frame-provider.cjs +38 -0
- package/dist/experimental/webxr/webxr-animation-frame-provider.d.ts +9 -0
- package/dist/experimental/webxr/webxr-animation-frame-provider.d.ts.map +1 -0
- package/dist/experimental/webxr/webxr-animation-frame-provider.js +17 -0
- package/dist/experimental/webxr/webxr-animation-frame-provider.js.map +1 -0
- package/dist/experimental/webxr/webxr-camera-texture.cjs +157 -0
- package/dist/experimental/webxr/webxr-camera-texture.d.ts +48 -0
- package/dist/experimental/webxr/webxr-camera-texture.d.ts.map +1 -0
- package/dist/experimental/webxr/webxr-camera-texture.js +144 -0
- package/dist/experimental/webxr/webxr-camera-texture.js.map +1 -0
- package/dist/experimental/webxr/webxr-input.cjs +93 -0
- package/dist/experimental/webxr/webxr-input.d.ts +24 -0
- package/dist/experimental/webxr/webxr-input.d.ts.map +1 -0
- package/dist/experimental/webxr/webxr-input.js +70 -0
- package/dist/experimental/webxr/webxr-input.js.map +1 -0
- package/dist/experimental/webxr/webxr-manager.cjs +356 -0
- package/dist/experimental/webxr/webxr-manager.d.ts +91 -0
- package/dist/experimental/webxr/webxr-manager.d.ts.map +1 -0
- package/dist/experimental/webxr/webxr-manager.js +354 -0
- package/dist/experimental/webxr/webxr-manager.js.map +1 -0
- package/dist/experimental/webxr/webxr-types.cjs +15 -0
- package/dist/experimental/webxr/webxr-types.d.ts +152 -0
- package/dist/experimental/webxr/webxr-types.d.ts.map +1 -0
- package/dist/experimental/webxr/webxr-types.js +5 -0
- package/dist/experimental/webxr/webxr-types.js.map +1 -0
- package/dist/geometry/edge-geometry.cjs +171 -0
- package/dist/geometry/geometry-primitives.cjs +189 -0
- package/dist/geometry/geometry-primitives.d.ts +6 -0
- package/dist/geometry/geometry-primitives.d.ts.map +1 -1
- package/dist/geometry/geometry-primitives.js +8 -0
- package/dist/geometry/geometry-primitives.js.map +1 -1
- package/dist/geometry/geometry-table.cjs +15 -0
- package/dist/geometry/geometry-utils.cjs +147 -0
- package/dist/geometry/geometry.cjs +90 -0
- package/dist/geometry/gpu-geometry.cjs +130 -0
- package/dist/geometry/gpu-vector-geometry-adapter.cjs +88 -0
- package/dist/geometry/gpu-vector-geometry-adapter.d.ts +5 -0
- package/dist/geometry/gpu-vector-geometry-adapter.d.ts.map +1 -0
- package/dist/geometry/gpu-vector-geometry-adapter.js +73 -0
- package/dist/geometry/gpu-vector-geometry-adapter.js.map +1 -0
- package/dist/geometry/gpu-vector-geometry.cjs +40 -0
- package/dist/geometry/gpu-vector-geometry.d.ts +21 -0
- package/dist/geometry/gpu-vector-geometry.d.ts.map +1 -0
- package/dist/geometry/gpu-vector-geometry.js +19 -0
- package/dist/geometry/gpu-vector-geometry.js.map +1 -0
- package/dist/geometry/mesh-simplification.cjs +385 -0
- package/dist/geometry/ring-geometry.cjs +104 -0
- package/dist/geometry/ring-geometry.d.ts +17 -0
- package/dist/geometry/ring-geometry.d.ts.map +1 -0
- package/dist/geometry/ring-geometry.js +94 -0
- package/dist/geometry/ring-geometry.js.map +1 -0
- package/dist/geometry/stroke-geometry.cjs +171 -0
- package/dist/graph/models/index.cjs +66 -0
- package/dist/graph/models/index.cjs.map +6 -0
- package/dist/graph/models/index.d.ts +7 -0
- package/dist/graph/models/index.d.ts.map +1 -0
- package/dist/graph/models/index.js +10 -0
- package/dist/graph/models/index.js.map +1 -0
- package/dist/graph/models/path/path-attribute-model.cjs +421 -0
- package/dist/graph/models/path/path-attribute-model.d.ts +142 -0
- package/dist/graph/models/path/path-attribute-model.d.ts.map +1 -0
- package/dist/graph/models/path/path-attribute-model.js +409 -0
- package/dist/graph/models/path/path-attribute-model.js.map +1 -0
- package/dist/graph/models/path/path-storage-model.cjs +711 -0
- package/dist/graph/models/path/path-storage-model.d.ts +174 -0
- package/dist/graph/models/path/path-storage-model.d.ts.map +1 -0
- package/dist/graph/models/path/path-storage-model.js +720 -0
- package/dist/graph/models/path/path-storage-model.js.map +1 -0
- package/dist/graph/models/path/path-trips-storage-model.cjs +271 -0
- package/dist/graph/models/path/path-trips-storage-model.d.ts +58 -0
- package/dist/graph/models/path/path-trips-storage-model.d.ts.map +1 -0
- package/dist/graph/models/path/path-trips-storage-model.js +248 -0
- package/dist/graph/models/path/path-trips-storage-model.js.map +1 -0
- package/dist/graph/models/polygon/polygon-attribute-model.cjs +117 -0
- package/dist/graph/models/polygon/polygon-attribute-model.d.ts +53 -0
- package/dist/graph/models/polygon/polygon-attribute-model.d.ts.map +1 -0
- package/dist/graph/models/polygon/polygon-attribute-model.js +101 -0
- package/dist/graph/models/polygon/polygon-attribute-model.js.map +1 -0
- package/dist/graph/models/polygon/polygon-shaders.cjs +283 -0
- package/dist/graph/models/polygon/polygon-shaders.d.ts +77 -0
- package/dist/graph/models/polygon/polygon-shaders.d.ts.map +1 -0
- package/dist/graph/models/polygon/polygon-shaders.js +242 -0
- package/dist/graph/models/polygon/polygon-shaders.js.map +1 -0
- package/dist/graph/models/polygon/polygon-storage-model.cjs +111 -0
- package/dist/graph/models/polygon/polygon-storage-model.d.ts +53 -0
- package/dist/graph/models/polygon/polygon-storage-model.d.ts.map +1 -0
- package/dist/graph/models/polygon/polygon-storage-model.js +92 -0
- package/dist/graph/models/polygon/polygon-storage-model.js.map +1 -0
- package/dist/graph/physics/index.cjs +50 -0
- package/dist/graph/physics/index.cjs.map +6 -0
- package/dist/graph/physics/index.d.ts +12 -0
- package/dist/graph/physics/index.d.ts.map +1 -0
- package/dist/graph/physics/index.js +12 -0
- package/dist/graph/physics/index.js.map +1 -0
- package/dist/graph/physics/physics-scenegraph.cjs +92 -0
- package/dist/graph/physics/physics-scenegraph.d.ts +35 -0
- package/dist/graph/physics/physics-scenegraph.d.ts.map +1 -0
- package/dist/graph/physics/physics-scenegraph.js +80 -0
- package/dist/graph/physics/physics-scenegraph.js.map +1 -0
- package/dist/graph/physics/scenegraph-behaviors.cjs +164 -0
- package/dist/graph/physics/scenegraph-behaviors.d.ts +37 -0
- package/dist/graph/physics/scenegraph-behaviors.d.ts.map +1 -0
- package/dist/graph/physics/scenegraph-behaviors.js +145 -0
- package/dist/graph/physics/scenegraph-behaviors.js.map +1 -0
- package/dist/graph/physics/scenegraph-instance.cjs +246 -0
- package/dist/graph/physics/scenegraph-instance.d.ts +59 -0
- package/dist/graph/physics/scenegraph-instance.d.ts.map +1 -0
- package/dist/graph/physics/scenegraph-instance.js +241 -0
- package/dist/graph/physics/scenegraph-instance.js.map +1 -0
- package/dist/graph/physics/scenegraph-joints.cjs +51 -0
- package/dist/graph/physics/scenegraph-joints.d.ts +5 -0
- package/dist/graph/physics/scenegraph-joints.d.ts.map +1 -0
- package/dist/graph/physics/scenegraph-joints.js +31 -0
- package/dist/graph/physics/scenegraph-joints.js.map +1 -0
- package/dist/graph/physics/scenegraph-motion.cjs +177 -0
- package/dist/graph/physics/scenegraph-motion.d.ts +37 -0
- package/dist/graph/physics/scenegraph-motion.d.ts.map +1 -0
- package/dist/graph/physics/scenegraph-motion.js +168 -0
- package/dist/graph/physics/scenegraph-motion.js.map +1 -0
- package/dist/graph/physics/scenegraph-properties.cjs +170 -0
- package/dist/graph/physics/scenegraph-properties.d.ts +37 -0
- package/dist/graph/physics/scenegraph-properties.d.ts.map +1 -0
- package/dist/graph/physics/scenegraph-properties.js +186 -0
- package/dist/graph/physics/scenegraph-properties.js.map +1 -0
- package/dist/graph/physics/scenegraph-publication.cjs +112 -0
- package/dist/graph/physics/scenegraph-publication.d.ts +23 -0
- package/dist/graph/physics/scenegraph-publication.d.ts.map +1 -0
- package/dist/graph/physics/scenegraph-publication.js +99 -0
- package/dist/graph/physics/scenegraph-publication.js.map +1 -0
- package/dist/graph/physics/scenegraph-session.cjs +256 -0
- package/dist/graph/physics/scenegraph-session.d.ts +68 -0
- package/dist/graph/physics/scenegraph-session.d.ts.map +1 -0
- package/dist/graph/physics/scenegraph-session.js +249 -0
- package/dist/graph/physics/scenegraph-session.js.map +1 -0
- package/dist/graph/tables/gpu-table-geometry.cjs +84 -0
- package/dist/graph/tables/gpu-table-geometry.d.ts +32 -0
- package/dist/graph/tables/gpu-table-geometry.d.ts.map +1 -0
- package/dist/graph/tables/gpu-table-geometry.js +67 -0
- package/dist/graph/tables/gpu-table-geometry.js.map +1 -0
- package/dist/graph/tables/gpu-table-model.cjs +459 -0
- package/dist/graph/tables/gpu-table-model.d.ts +67 -0
- package/dist/graph/tables/gpu-table-model.d.ts.map +1 -0
- package/dist/graph/tables/gpu-table-model.js +457 -0
- package/dist/graph/tables/gpu-table-model.js.map +1 -0
- package/dist/graph/tables/gpu-table-transform.cjs +341 -0
- package/dist/graph/tables/gpu-table-transform.d.ts +61 -0
- package/dist/graph/tables/gpu-table-transform.d.ts.map +1 -0
- package/dist/graph/tables/gpu-table-transform.js +333 -0
- package/dist/graph/tables/gpu-table-transform.js.map +1 -0
- package/dist/graph/tables/index.cjs +33 -0
- package/dist/graph/tables/index.cjs.map +6 -0
- package/dist/graph/tables/index.d.ts +4 -0
- package/dist/graph/tables/index.d.ts.map +1 -0
- package/dist/graph/tables/index.js +7 -0
- package/dist/graph/tables/index.js.map +1 -0
- package/dist/index.cjs +303 -9569
- package/dist/index.cjs.map +3 -3
- package/dist/index.d.ts +32 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +26 -3
- package/dist/index.js.map +1 -1
- package/dist/interactivity/interactivity.cjs +570 -0
- package/dist/interactivity/interactivity.d.ts +107 -0
- package/dist/interactivity/interactivity.d.ts.map +1 -0
- package/dist/interactivity/interactivity.js +575 -0
- package/dist/interactivity/interactivity.js.map +1 -0
- package/dist/interactivity/physics.cjs +15 -0
- package/dist/interactivity/physics.d.ts +12 -0
- package/dist/interactivity/physics.d.ts.map +1 -0
- package/dist/interactivity/physics.js +5 -0
- package/dist/interactivity/physics.js.map +1 -0
- package/dist/material/material-factory.cjs +99 -0
- package/dist/material/material-factory.d.ts +1 -1
- package/dist/material/material-factory.d.ts.map +1 -1
- package/dist/material/material.cjs +239 -0
- package/dist/material/material.d.ts +2 -2
- package/dist/material/material.d.ts.map +1 -1
- package/dist/material/material.js +2 -2
- package/dist/material/material.js.map +1 -1
- package/dist/model/gpu-vector-bindings.cjs +226 -0
- package/dist/model/gpu-vector-bindings.d.ts +36 -0
- package/dist/model/gpu-vector-bindings.d.ts.map +1 -0
- package/dist/model/gpu-vector-bindings.js +217 -0
- package/dist/model/gpu-vector-bindings.js.map +1 -0
- package/dist/model/gpu-vector-draw-batches.cjs +82 -0
- package/dist/model/gpu-vector-draw-batches.d.ts +5 -0
- package/dist/model/gpu-vector-draw-batches.d.ts.map +1 -0
- package/dist/model/gpu-vector-draw-batches.js +73 -0
- package/dist/model/gpu-vector-draw-batches.js.map +1 -0
- package/dist/model/gpu-vector-model-batches.cjs +94 -0
- package/dist/model/gpu-vector-model-batches.d.ts +41 -0
- package/dist/model/gpu-vector-model-batches.d.ts.map +1 -0
- package/dist/model/gpu-vector-model-batches.js +77 -0
- package/dist/model/gpu-vector-model-batches.js.map +1 -0
- package/dist/model/gpu-vector-model.cjs +1264 -0
- package/dist/model/gpu-vector-model.d.ts +352 -0
- package/dist/model/gpu-vector-model.d.ts.map +1 -0
- package/dist/model/gpu-vector-model.js +1375 -0
- package/dist/model/gpu-vector-model.js.map +1 -0
- package/dist/model/model.cjs +134 -0
- package/dist/model/model.d.ts +21 -305
- package/dist/model/model.d.ts.map +1 -1
- package/dist/model/model.js +68 -1092
- package/dist/model/model.js.map +1 -1
- package/dist/model/split-uniforms-and-bindings.cjs +44 -0
- package/dist/model/split-uniforms-and-bindings.d.ts +1 -1
- package/dist/model/split-uniforms-and-bindings.d.ts.map +1 -1
- package/dist/model/split-uniforms-and-bindings.js +5 -2
- package/dist/model/split-uniforms-and-bindings.js.map +1 -1
- package/dist/models/billboard-texture-model.cjs +167 -0
- package/dist/models/billboard-texture-model.d.ts +1 -1
- package/dist/models/billboard-texture-model.d.ts.map +1 -1
- package/dist/models/billboard-texture-model.js +1 -1
- package/dist/models/billboard-texture-model.js.map +1 -1
- package/dist/models/billboard-texture-module.cjs +61 -0
- package/dist/models/clip-space.cjs +103 -0
- package/dist/models/directional-light-model.cjs +45 -0
- package/dist/models/light-model-utils.cjs +426 -0
- package/dist/models/point-light-model.cjs +44 -0
- package/dist/models/spot-light-model.cjs +45 -0
- package/dist/modules/picking/color-picking.cjs +209 -0
- package/dist/modules/picking/color-picking.d.ts +1 -1
- package/dist/modules/picking/index-color-picking.cjs +230 -0
- package/dist/modules/picking/index-color-picking.d.ts +1 -1
- package/dist/modules/picking/index-picking.cjs +201 -0
- package/dist/modules/picking/index-picking.d.ts +1 -1
- package/dist/modules/picking/legacy-color-picking.cjs +28 -0
- package/dist/modules/picking/legacy-color-picking.d.ts +1 -1
- package/dist/modules/picking/legacy-picking-manager.cjs +92 -0
- package/dist/modules/picking/picking-manager.cjs +360 -0
- package/dist/modules/picking/picking-uniforms.cjs +140 -0
- package/dist/modules/picking/picking-uniforms.d.ts +1 -1
- package/dist/modules/picking/picking-uniforms.d.ts.map +1 -1
- package/dist/modules/picking/picking.cjs +43 -0
- package/dist/modules/picking/picking.d.ts +1 -1
- package/dist/passes/get-fragment-shader.cjs +119 -0
- package/dist/passes/shader-pass-renderer.cjs +722 -0
- package/dist/passes/shader-pass-renderer.d.ts +2 -2
- package/dist/passes/shader-pass-renderer.d.ts.map +1 -1
- package/dist/passes/shader-pass-renderer.js +1 -1
- package/dist/passes/shader-pass-renderer.js.map +1 -1
- package/dist/passes/texture-transform-module.cjs +78 -0
- package/dist/scenegraph/controllers/area-light-controller.cjs +143 -0
- package/dist/scenegraph/controllers/area-light-controller.d.ts +31 -0
- package/dist/scenegraph/controllers/area-light-controller.d.ts.map +1 -0
- package/dist/scenegraph/controllers/area-light-controller.js +130 -0
- package/dist/scenegraph/controllers/area-light-controller.js.map +1 -0
- package/dist/scenegraph/controllers/billboard-controller.cjs +156 -0
- package/dist/scenegraph/controllers/billboard-controller.d.ts +45 -0
- package/dist/scenegraph/controllers/billboard-controller.d.ts.map +1 -0
- package/dist/scenegraph/controllers/billboard-controller.js +156 -0
- package/dist/scenegraph/controllers/billboard-controller.js.map +1 -0
- package/dist/scenegraph/controllers/joint-controller.cjs +71 -0
- package/dist/scenegraph/controllers/joint-controller.d.ts +30 -0
- package/dist/scenegraph/controllers/joint-controller.d.ts.map +1 -0
- package/dist/scenegraph/controllers/joint-controller.js +53 -0
- package/dist/scenegraph/controllers/joint-controller.js.map +1 -0
- package/dist/scenegraph/controllers/material-variants.cjs +61 -0
- package/dist/scenegraph/controllers/material-variants.d.ts +42 -0
- package/dist/scenegraph/controllers/material-variants.d.ts.map +1 -0
- package/dist/scenegraph/controllers/material-variants.js +40 -0
- package/dist/scenegraph/controllers/material-variants.js.map +1 -0
- package/dist/scenegraph/controllers/morph-controller.cjs +61 -0
- package/dist/scenegraph/controllers/morph-controller.d.ts +19 -0
- package/dist/scenegraph/controllers/morph-controller.d.ts.map +1 -0
- package/dist/scenegraph/controllers/morph-controller.js +41 -0
- package/dist/scenegraph/controllers/morph-controller.js.map +1 -0
- package/dist/scenegraph/controllers/skin-controller.cjs +111 -0
- package/dist/scenegraph/controllers/skin-controller.d.ts +36 -0
- package/dist/scenegraph/controllers/skin-controller.d.ts.map +1 -0
- package/dist/scenegraph/controllers/skin-controller.js +90 -0
- package/dist/scenegraph/controllers/skin-controller.js.map +1 -0
- package/dist/scenegraph/group-node.cjs +129 -0
- package/dist/scenegraph/model-node.cjs +68 -0
- package/dist/scenegraph/physics-transforms.cjs +95 -0
- package/dist/scenegraph/physics-transforms.d.ts +13 -0
- package/dist/scenegraph/physics-transforms.d.ts.map +1 -0
- package/dist/scenegraph/physics-transforms.js +72 -0
- package/dist/scenegraph/physics-transforms.js.map +1 -0
- package/dist/scenegraph/published-transforms.cjs +37 -0
- package/dist/scenegraph/published-transforms.d.ts +17 -0
- package/dist/scenegraph/published-transforms.d.ts.map +1 -0
- package/dist/scenegraph/published-transforms.js +16 -0
- package/dist/scenegraph/published-transforms.js.map +1 -0
- package/dist/scenegraph/scenegraph-bounds.cjs +51 -0
- package/dist/scenegraph/scenegraph-node.cjs +182 -0
- package/dist/shader-inputs.cjs +231 -0
- package/dist/shader-inputs.d.ts +1 -1
- package/dist/shader-inputs.d.ts.map +1 -1
- package/dist/utils/buffer-layout-helper.cjs +52 -0
- package/dist/utils/buffer-layout-order.cjs +37 -0
- package/dist/utils/deep-equal.cjs +65 -0
- package/dist/utils/get-platform-info.cjs +21 -0
- package/dist/utils/get-platform-info.d.ts +2 -0
- package/dist/utils/get-platform-info.d.ts.map +1 -0
- package/dist/utils/get-platform-info.js +5 -0
- package/dist/utils/get-platform-info.js.map +1 -0
- package/dist/utils/gpu-vector-batch-structure.cjs +45 -0
- package/dist/utils/gpu-vector-batch-structure.d.ts +12 -0
- package/dist/utils/gpu-vector-batch-structure.d.ts.map +1 -0
- package/dist/utils/gpu-vector-batch-structure.js +27 -0
- package/dist/utils/gpu-vector-batch-structure.js.map +1 -0
- package/dist/utils/shader-module-utils.cjs +148 -0
- package/dist/utils/uid.cjs +32 -0
- package/package.json +45 -7
- package/src/animation/deform-positions.ts +62 -0
- package/src/animation/node-animation-binding.ts +54 -0
- package/src/animation/property-animation-binding.ts +212 -0
- package/src/animation/scenegraph-animator.ts +117 -0
- package/src/animation/texture-transform.ts +59 -0
- package/src/animation-loop/animation-loop.ts +10 -3
- package/src/audio/audio-controller.ts +583 -0
- package/src/audio/audio-environment.ts +202 -0
- package/src/audio/audio-graph.ts +253 -0
- package/src/compute/buffer-transform.ts +71 -16
- package/src/compute/computation.ts +4 -19
- package/src/compute/texture-transform.ts +25 -12
- package/src/controls/orbit-controls.ts +4 -1
- package/src/dynamic-buffer/dynamic-buffer.ts +15 -449
- package/src/dynamic-texture/dynamic-texture.ts +5 -760
- package/src/dynamic-texture/texture-binding-source.ts +8 -90
- package/src/dynamic-texture/texture-data.ts +31 -340
- package/src/dynamic-texture/video-texture.ts +1 -1
- package/src/experimental/controls/comparison-splitter.ts +269 -0
- package/src/experimental/controls/flat-controller.ts +403 -0
- package/src/experimental/controls/index.ts +16 -0
- package/src/experimental/controls/orbit-controls.ts +6 -0
- package/src/experimental/materials/emissive-material.ts +120 -0
- package/src/experimental/materials/glass-material.ts +607 -0
- package/src/experimental/materials/glass-transmission.ts +1023 -0
- package/src/experimental/materials/index.ts +49 -0
- package/src/experimental/materials/optical-caustics.ts +234 -0
- package/src/experimental/materials/optical-lighting.ts +148 -0
- package/src/experimental/materials/optical-point-lights.ts +288 -0
- package/src/experimental/materials/reflective-material.ts +214 -0
- package/src/experimental/textures/html-texture.ts +285 -0
- package/src/experimental/textures/index.ts +8 -0
- package/src/experimental/textures/packed-pixels.ts +351 -0
- package/src/experimental/textures/rgba-decoder.ts +79 -0
- package/src/experimental/webxr/index.ts +21 -0
- package/src/experimental/webxr/webxr-animation-frame-provider.ts +22 -0
- package/src/experimental/webxr/webxr-camera-texture.ts +195 -0
- package/src/experimental/webxr/webxr-input.ts +117 -0
- package/src/experimental/webxr/webxr-manager.ts +524 -0
- package/src/experimental/webxr/webxr-types.ts +192 -0
- package/src/geometry/geometry-primitives.ts +11 -0
- package/src/geometry/gpu-vector-geometry-adapter.ts +78 -0
- package/src/geometry/gpu-vector-geometry.ts +33 -0
- package/src/geometry/ring-geometry.ts +117 -0
- package/src/graph/models/index.ts +45 -0
- package/src/graph/models/path/path-attribute-model.ts +563 -0
- package/src/graph/models/path/path-storage-model.ts +996 -0
- package/src/graph/models/path/path-trips-storage-model.ts +286 -0
- package/src/graph/models/polygon/polygon-attribute-model.ts +165 -0
- package/src/graph/models/polygon/polygon-shaders.ts +279 -0
- package/src/graph/models/polygon/polygon-storage-model.ts +146 -0
- package/src/graph/physics/index.ts +24 -0
- package/src/graph/physics/physics-scenegraph.ts +112 -0
- package/src/graph/physics/scenegraph-behaviors.ts +169 -0
- package/src/graph/physics/scenegraph-instance.ts +296 -0
- package/src/graph/physics/scenegraph-joints.ts +37 -0
- package/src/graph/physics/scenegraph-motion.ts +175 -0
- package/src/graph/physics/scenegraph-properties.ts +241 -0
- package/src/graph/physics/scenegraph-publication.ts +116 -0
- package/src/graph/physics/scenegraph-session.ts +317 -0
- package/src/graph/tables/gpu-table-geometry.ts +88 -0
- package/src/graph/tables/gpu-table-model.ts +661 -0
- package/src/graph/tables/gpu-table-transform.ts +497 -0
- package/src/graph/tables/index.ts +18 -0
- package/src/index.ts +130 -13
- package/src/interactivity/interactivity.ts +670 -0
- package/src/interactivity/physics.ts +19 -0
- package/src/material/material-factory.ts +1 -1
- package/src/material/material.ts +2 -2
- package/src/model/gpu-vector-bindings.ts +276 -0
- package/src/model/gpu-vector-draw-batches.ts +116 -0
- package/src/model/gpu-vector-model-batches.ts +142 -0
- package/src/model/gpu-vector-model.ts +1819 -0
- package/src/model/model.ts +91 -1444
- package/src/model/split-uniforms-and-bindings.ts +6 -3
- package/src/models/billboard-texture-model.ts +1 -1
- package/src/modules/picking/legacy-picking-manager.ts +1 -1
- package/src/modules/picking/picking-uniforms.ts +1 -1
- package/src/passes/shader-pass-renderer.ts +2 -2
- package/src/scenegraph/controllers/area-light-controller.ts +152 -0
- package/src/scenegraph/controllers/billboard-controller.ts +204 -0
- package/src/scenegraph/controllers/joint-controller.ts +81 -0
- package/src/scenegraph/controllers/material-variants.ts +70 -0
- package/src/scenegraph/controllers/morph-controller.ts +61 -0
- package/src/scenegraph/controllers/skin-controller.ts +125 -0
- package/src/scenegraph/physics-transforms.ts +82 -0
- package/src/scenegraph/published-transforms.ts +18 -0
- package/src/shader-inputs.ts +1 -1
- package/src/utils/get-platform-info.ts +5 -0
- package/src/utils/gpu-vector-batch-structure.ts +36 -0
- package/dist/compute/kernel.d.ts +0 -54
- package/dist/compute/kernel.d.ts.map +0 -1
- package/dist/compute/kernel.js +0 -103
- package/dist/compute/kernel.js.map +0 -1
- package/dist/compute/render-kernel.d.ts +0 -65
- package/dist/compute/render-kernel.d.ts.map +0 -1
- package/dist/compute/render-kernel.js +0 -129
- package/dist/compute/render-kernel.js.map +0 -1
- package/src/compute/kernel.ts +0 -146
- package/src/compute/render-kernel.ts +0 -192
package/dist/dist.min.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
else if (typeof define === 'function' && define.amd) define([], factory);
|
|
5
5
|
else if (typeof exports === 'object') exports['luma'] = factory();
|
|
6
6
|
else root['luma'] = factory();})(globalThis, function () {
|
|
7
|
-
"use strict";var __exports__=(()=>{var Cs=Object.create;var bt=Object.defineProperty;var Es=Object.getOwnPropertyDescriptor;var Ls=Object.getOwnPropertyNames;var Os=Object.getPrototypeOf,Rs=Object.prototype.hasOwnProperty;var An=(i,e)=>()=>{try{return e||i((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ks=(i,e)=>{for(var t in e)bt(i,t,{get:e[t],enumerable:!0})},yt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ls(e))!Rs.call(i,r)&&r!==t&&bt(i,r,{get:()=>e[r],enumerable:!(n=Es(e,r))||n.enumerable});return i},_t=(i,e,t)=>(yt(i,e,"default"),t&&yt(t,e,"default")),L=(i,e,t)=>(t=i!=null?Cs(Os(i)):{},yt(e||!i||!i.__esModule?bt(t,"default",{value:i,enumerable:!0}):t,i)),Ns=i=>yt(bt({},"__esModule",{value:!0}),i);var R=An((yc,Pn)=>{Pn.exports=globalThis.luma});var re=An((Au,pr)=>{pr.exports=globalThis.luma});var pt={};ks(pt,{AnimationAction:()=>Ze,AnimationClip:()=>At,AnimationClipController:()=>vt,AnimationLoop:()=>ke,AnimationLoopTemplate:()=>Gt,AnimationMixer:()=>Pt,AnimationTrack:()=>Tt,Animator:()=>It,AsyncTexture:()=>gc,BackgroundTextureModel:()=>Ue,BufferTransform:()=>Kt,ClipSpace:()=>me,Computation:()=>We,ConeGeometry:()=>ge,CubeGeometry:()=>Qt,CylinderGeometry:()=>ei,DirectionalLightModel:()=>si,DynamicBuffer:()=>G,DynamicTexture:()=>Z,GPUGeometry:()=>Ne,Geometry:()=>B,GroupNode:()=>hi,IcoSphereGeometry:()=>Jt,Kernel:()=>xi,KeyFrames:()=>jt,LegacyPickingManager:()=>Ii,Material:()=>Ge,MaterialFactory:()=>ze,Model:()=>W,ModelNode:()=>ui,OrbitControls:()=>Vt,PickingManager:()=>bi,PlaneGeometry:()=>ti,PointLightModel:()=>ni,RenderKernel:()=>yi,ScenegraphNode:()=>oe,ShaderInputs:()=>X,ShaderPassRenderer:()=>gi,SphereGeometry:()=>$e,SpotLightModel:()=>ri,Swap:()=>Xe,SwapBuffers:()=>mi,SwapFramebuffers:()=>Ye,TextureTransform:()=>Zt,Timeline:()=>zt,TruncatedConeGeometry:()=>Ve,VideoTexture:()=>pi,_resolveLoadFileUrl:()=>fi,applyMorphTargets:()=>Si,cancelAnimationFramePolyfill:()=>$t,colorPicking:()=>dt,decodeMorphTargetAttribute:()=>Pi,evaluateAnimationSampler:()=>Mt,getIndexPickingModule:()=>As,indexColorPicking:()=>vi,indexPicking:()=>ft,legacyColorPicking:()=>Ss,loadImage:()=>cs,loadImageBitmap:()=>as,makeAnimationLoop:()=>fr,makeEdgeGeometry:()=>hn,makeEdgeGeometryFromGeometries:()=>Kr,makeInterleavedGeometry:()=>Ee,makeRandomGenerator:()=>ns,makeStrokeGeometry:()=>Qr,picking:()=>Ts,requestAnimationFramePolyfill:()=>Ut,resolvePickingBackend:()=>ws,resolvePickingMode:()=>_i,setPathPrefix:()=>os,simplifyMesh:()=>is,supportsIndexPicking:()=>lt,updateMorphTargetBuffers:()=>kn,updateSkinJointMatrices:()=>hr});_t(pt,L(R(),1));var Sn=L(R(),1),vt=class{name;playing=!0;speed=1;startTime=0;constructor(e={}){this.name=e.name||"unnamed",Object.assign(this,e)}setTime(e){if(!this.playing)return;let n=(e/1e3-this.startTime)*this.speed;this.applyTime(n)}},It=class{clips;animations;constructor(e){this.clips=e,this.animations=e}animate(e){Sn.log.warn(`${this.constructor.name}#animate is deprecated. Use ${this.constructor.name}#setTime instead`)(),this.setTime(e)}setTime(e){this.clips.forEach(t=>t.setTime(e))}getAnimations(){return this.clips}};function Mt(i,e,t="vector"){let{input:n,output:r,interpolation:s="LINEAR"}=e;if(!n.length||!r.length||!Number.isFinite(i))return null;let o=n.length-1;if(i<=n[0]||o===0)return Mi(r,s,0,t);if(i>=n[o])return Mi(r,s,o,t);let a=0,c=o;for(;c-a>1;){let f=Math.floor((a+c)/2);n[f]<=i?a=f:c=f}let h=n[a],l=n[c]-h;if(l<=0||s==="STEP")return Mi(r,s,a,t);let d=(i-h)/l;switch(s){case"LINEAR":{let f=r[a],p=r[c];return!f||!p?null:t==="quaternion"?wt(f,p,d):Fs(f,p,d)}case"CUBICSPLINE":{let f=r[a*3+1],p=r[a*3+2],b=r[c*3],g=r[c*3+1];if(!f||!p||!b||!g)return null;let _=Ds(f,p,b,g,l,d);return t==="quaternion"?Se(_):_}default:return null}}function wt(i,e,t){let n=Se(i),r=Se(e),s=n.reduce((l,d,f)=>l+d*r[f],0),o=s<0?-1:1;if(s=Math.min(Math.abs(s),1),s>.9995)return Se(n.map((l,d)=>l+t*(r[d]*o-l)));let a=Math.acos(s),c=Math.sin(a),h=Math.sin((1-t)*a)/c,u=Math.sin(t*a)/c*o;return Se(n.map((l,d)=>l*h+r[d]*u))}function Mi(i,e,t,n){let r=i[e==="CUBICSPLINE"?t*3+1:t];return r?n==="quaternion"?Se(r):[...r]:null}function Fs(i,e,t){return i.map((n,r)=>(1-t)*n+t*e[r])}function Ds(i,e,t,n,r,s){let o=s*s,a=o*s;return i.map((c,h)=>(2*a-3*o+1)*c+(a-2*o+s)*e[h]*r+(-2*a+3*o)*n[h]+(a-o)*t[h]*r)}function Se(i){let e=Math.hypot(...i);return e>0?i.map(t=>t/e):[0,0,0,1]}var Tt=class{name;times;values;interpolation;valueType;binding;constructor(e){this.name=e.name||e.binding.id||"unnamed",this.times=e.times,this.values=e.values,this.interpolation=e.interpolation||"LINEAR",this.valueType=e.valueType||"vector",this.binding=e.binding}get duration(){return this.times[this.times.length-1]||0}get sampler(){return{input:this.times,output:this.values,interpolation:this.interpolation}}evaluate(e){return Mt(e,this.sampler,this.valueType)}};var At=class{name;tracks;duration;constructor(e){this.name=e.name||"unnamed",this.tracks=e.tracks,this.duration=e.duration??Math.max(0,...e.tracks.map(t=>t.duration))}};var Ze=class{clip;mixer;time=0;timeScale;weight;loop;repetitions;paused=!1;playing=!1;elapsedTime=0;fade=null;constructor(e,t,n={}){this.mixer=e,this.clip=t,this.loop=n.loop||"repeat",this.repetitions=n.repetitions??Number.POSITIVE_INFINITY,this.timeScale=n.timeScale??1,this.weight=n.weight??1}play(){return this.playing=!0,this.paused=!1,this}pause(){return this.paused=!0,this}resume(){return this.playing=!0,this.paused=!1,this}stop(){return this.playing=!1,this.paused=!1,this.fade=null,this.reset()}reset(){return this.elapsedTime=0,this.time=0,this}setTime(e){return this.elapsedTime=e,this.time=this.resolveLocalTime(e),this}setLoop(e,t=Number.POSITIVE_INFINITY){return this.loop=e,this.repetitions=t,this.time=this.resolveLocalTime(this.elapsedTime),this}setEffectiveWeight(e){return this.weight=Math.max(0,e),this.fade=null,this}setEffectiveTimeScale(e){return this.timeScale=e,this}fadeIn(e){return this.scheduleFade(1,e)}fadeOut(e){return this.scheduleFade(0,e)}crossFadeTo(e,t){return e.weight=0,e.play().fadeIn(t),this.fadeOut(t)}crossFadeFrom(e,t){return e.crossFadeTo(this,t),this}advance(e){!this.playing||this.paused||(this.advanceFade(Math.abs(e)),this.elapsedTime+=e*this.timeScale,this.time=this.resolveLocalTime(this.elapsedTime),this.hasFinished()&&(this.playing=!1))}get shouldApply(){return(this.playing||this.hasFinished())&&this.weight>0}scheduleFade(e,t){return t<=0?(this.weight=e,this.fade=null,this):(this.fade={duration:t,elapsedTime:0,startWeight:this.weight,endWeight:e},this)}advanceFade(e){if(!this.fade)return;this.fade.elapsedTime+=e;let t=Math.min(this.fade.elapsedTime/this.fade.duration,1);this.weight=this.fade.startWeight+(this.fade.endWeight-this.fade.startWeight)*t,t===1&&(this.fade=null)}hasFinished(){let e=this.clip.duration;return e<=0?this.loop==="once":this.loop==="once"?this.elapsedTime>=e||this.elapsedTime<0:Number.isFinite(this.repetitions)&&Math.abs(this.elapsedTime)>=e*this.repetitions}resolveLocalTime(e){let t=this.clip.duration;if(t<=0)return 0;if(this.loop==="once")return Math.min(Math.max(e,0),t);if(Number.isFinite(this.repetitions)&&Math.abs(e)>=t*this.repetitions)return this.loop==="ping-pong"&&this.repetitions%2===0||e<0?0:t;let n=e>=0&&e<t?e:(e%t+t)%t;if(this.loop==="repeat")return n;let r=Math.floor(e/t);return Math.abs(r%2)===0?n:t-n}},Pt=class{time=0;timeScale=1;clips=new Map;actions=new Map;initialValues=new Map;constructor(e=[]){e.forEach(t=>this.addClip(t))}addClip(e){return this.clips.set(e.name,e),this}clipAction(e,t){let n=typeof e=="string"?this.clips.get(e):e;if(!n)throw new Error(`Unknown animation clip: ${e}`);this.addClip(n);let r=this.actions.get(n);return r||(r=new Ze(this,n,t),this.actions.set(n,r)),r}getAction(e){let t=this.clips.get(e);return t?this.actions.get(t):void 0}update(e){return this.advance(e),this.applyValues(),this}advance(e){let t=e*this.timeScale;return this.time+=t,this.actions.forEach(n=>n.advance(t)),this}setTime(e){return this.time=e,this.actions.forEach(t=>{t.paused||t.setTime(e*t.timeScale)}),this.applyValues(),this}stopAllAction(){return this.actions.forEach(e=>e.stop()),this}applyValues(){let e=new Map;this.actions.forEach(t=>{!t.shouldApply&&!(t.playing&&t.weight===0)||t.clip.tracks.forEach(n=>{let r=n.evaluate(t.time);if(!r)return;let s=n.binding.id||n.binding;if(!this.initialValues.has(s)){let h=n.binding.getValue?.();h&&this.initialValues.set(s,[...h])}if(t.weight===0&&!this.initialValues.has(s))return;let o=e.get(s);if(!o){e.set(s,{binding:n.binding,value:[...r],valueType:n.valueType,weight:t.weight});return}if(t.weight===0)return;let a=o.weight+t.weight,c=t.weight/a;o.value=n.valueType==="quaternion"?wt(o.value,r,c):o.value.map((h,u)=>h+(r[u]-h)*c),o.weight=a})}),e.forEach(({binding:t,value:n,valueType:r,weight:s},o)=>{let a=s<1?this.initialValues.get(o):void 0;a&&a.length===n.length&&(n=r==="quaternion"?wt(a,n,s):n.map((c,h)=>a[h]+(c-a[h])*s)),t.setValue(n)})}};var Bs=0,$=class{constructor(e){this.userData={},this.id=e.id||`geometry-${++Bs}`,this.topology=e.topology,this.attributes={};let t=e.indices?Cn(e.indices):void 0;for(let[n,r]of Object.entries(e.attributes||{})){let s=Cn(r);if((n==="POSITION"||n==="positions")&&(s.size||(s.size=3)),n==="indices"){if(t)throw new Error("Geometry has multiple index attributes");t=s}else this.attributes[n]=s}if(t){if(!(t.value instanceof Uint16Array||t.value instanceof Uint32Array))throw new Error("Geometry indices must be a Uint16Array or Uint32Array");t.size=1,this.indices=t,zs(t,this.attributes)}if(this.vertexCount=e.vertexCount??js(this.attributes,this.indices),!Number.isInteger(this.vertexCount)||this.vertexCount<0)throw new Error("Geometry vertexCount must be a non-negative integer")}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}};function Cn(i){let e=En(i)?{value:i}:{...i};if(!En(e.value))throw new Error("Geometry attributes must contain a typed-array value");if(e.size!==void 0&&(!Number.isInteger(e.size)||e.size<1))throw new Error("Geometry attribute size must be a positive integer");if(e.size&&e.value.length%e.size!==0)throw new Error("Geometry attribute length must be divisible by its size");return e}function En(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function zs(i,e){let t=-1;for(let n of i.value)t=Math.max(t,Number(n));for(let[n,r]of Object.entries(e))if(!r.constant&&r.size){let s=r.value.length/r.size;if(t>=s)throw new Error(`Geometry index ${t} exceeds ${n} vertex count ${s}`)}}function js(i,e){if(e)return e.value.length;let t=1/0;for(let n of Object.values(i))!n.constant&&n.size&&(t=Math.min(t,n.value.length/n.size));if(!Number.isFinite(t))throw new Error("Geometry has no countable attributes");return t}function Qe(i){if(!i.indices)return i;let e=i.indices.value,t={};for(let[n,r]of Object.entries(i.attributes)){if(!r)continue;if(r.constant||!r.size){t[n]=r;continue}let s=r.value.constructor,o=new s(e.length*r.size);for(let a=0;a<e.length;a++)for(let c=0;c<r.size;c++)o[a*r.size+c]=r.value[Number(e[a])*r.size+c];t[n]={...r,value:o}}return{attributes:t}}function Y(i,e){if(!Number.isFinite(i)||i<=0)throw new Error(`${e} must be greater than zero`)}function St(i,e){if(!Number.isFinite(i)||i<0)throw new Error(`${e} must be non-negative`)}function H(i,e,t=1){if(!Number.isInteger(i)||i<t)throw new Error(`${e} must be an integer >= ${t}`)}function fe(i,e){return i>65535?new Uint32Array(e):new Uint16Array(e)}var Ct=class extends ${constructor(e={}){let t=e.size||[1,1,1];Y(t[0],"size[0]"),Y(t[1],"size[1]"),Y(t[2],"size[2]");let n=[t[0]/2,t[1]/2,t[2]/2],r=[],s=[],o=[],a=[],c=[{n:[1,0,0],u:[0,0,-1],v:[0,1,0],h1:n[2],h2:n[1]},{n:[-1,0,0],u:[0,0,1],v:[0,1,0],h1:n[2],h2:n[1]},{n:[0,1,0],u:[1,0,0],v:[0,0,-1],h1:n[0],h2:n[2]},{n:[0,-1,0],u:[1,0,0],v:[0,0,1],h1:n[0],h2:n[2]},{n:[0,0,1],u:[1,0,0],v:[0,1,0],h1:n[0],h2:n[1]},{n:[0,0,-1],u:[-1,0,0],v:[0,1,0],h1:n[0],h2:n[1]}];for(let h of c){let u=r.length/3;for(let[l,d,f,p]of[[-1,-1,0,0],[1,-1,1,0],[1,1,1,1],[-1,1,0,1]])r.push(h.n[0]*n[0]+h.u[0]*h.h1*l+h.v[0]*h.h2*d,h.n[1]*n[1]+h.u[1]*h.h1*l+h.v[1]*h.h2*d,h.n[2]*n[2]+h.u[2]*h.h1*l+h.v[2]*h.h2*d),s.push(...h.n),o.push(f,p);a.push(u,u+1,u+2,u,u+2,u+3)}super({id:e.id,topology:"triangle-list",indices:fe(24,a),attributes:{POSITION:{size:3,value:new Float32Array(r)},NORMAL:{size:3,value:new Float32Array(s)},TEXCOORD_0:{size:2,value:new Float32Array(o)},...e.attributes}})}},Je=class extends Ct{constructor(e={}){let t=e.size??1;super({...e,size:[t,t,t]})}};function wi(i,e){let t=[],n=[],r=[],s=[],o=e+1;for(let a=0;a<i.length;a++){let c=i[a];for(let h=0;h<=e;h++){let u=h/e,l=u*Math.PI*2,d=Math.sin(l),f=Math.cos(l);t.push(d*c.radius,c.y,f*c.radius),n.push(d*c.normalRadius,c.normalY,f*c.normalRadius),r.push(u,a/(i.length-1))}}for(let a=0;a<i.length-1;a++)for(let c=0;c<e;c++){let h=a*o+c,u=h+1,l=h+o,d=l+1;s.push(h,u,d,h,d,l)}return{positions:t,normals:n,texCoords:r,indices:s,indexArray:fe(t.length/3,s)}}var Ce=class extends ${constructor(e={}){let{topRadius:t=0,bottomRadius:n=0,topCap:r=!1,bottomCap:s=!1,height:o=1,nradial:a=10,nvertical:c=1,verticalAxis:h="y"}=e;if(St(t,"topRadius"),St(n,"bottomRadius"),t===0&&n===0)throw new Error("At least one radius must be greater than zero");Y(o,"height"),H(a,"nradial",3),H(c,"nvertical");let u=[],l=[],d=[],f=[],p=a+1,b=(n-t)/o,g=1/Math.hypot(1,b),_=(m,x,M,w,T)=>{let P=u.length/3/p;for(let E=0;E<=a;E++){let A=E/a,O=A*Math.PI*2,C=Math.sin(O),D=Math.cos(O),mt=Ln([C*m,x,D*m],h),de=Ln([C*M,w,D*M],h);u.push(...mt),l.push(...de),d.push(A,T)}return P},v=(m,x)=>{for(let M=0;M<a;M++){let w=m*p+M,T=w+1,P=x*p+M,E=P+1;f.push(w,T,E,w,E,P)}},y;if(s){let m=_(0,-o/2,0,-1,0),x=_(n,-o/2,0,-1,1);v(m,x),y=_(n,-o/2,g,b*g,0)}for(let m=0;m<=c;m++){let x=m/c,M=n+(t-n)*x,w=_(M,(x-.5)*o,g,b*g,x);y!==void 0&&!(s&&m===0)&&v(y,w),y=w}if(r&&y!==void 0){let m=_(t,o/2,0,1,1),x=_(0,o/2,0,1,0);v(m,x)}let I=u.length/3;super({id:e.id,topology:"triangle-list",indices:fe(I,f),attributes:{POSITION:{size:3,value:new Float32Array(u)},NORMAL:{size:3,value:new Float32Array(l)},TEXCOORD_0:{size:2,value:new Float32Array(d)},...e.attributes}})}};function Ln(i,e){switch(e){case"x":return[i[1],i[2],i[0]];case"z":return[i[2],i[0],i[1]];default:return[i[0],i[1],i[2]]}}var et=class extends ${constructor(e){let{sizeX:t,sizeZ:n,nx:r=1,nz:s=1}=e;Y(t,"sizeX"),Y(n,"sizeZ"),H(r,"nx"),H(s,"nz");let o=[],a=[],c=[],h=[];for(let d=0;d<=s;d++){let f=d/s;for(let p=0;p<=r;p++){let b=p/r;o.push((b-.5)*t,0,(.5-f)*n),a.push(0,1,0),c.push(b,f)}}let u=r+1;for(let d=0;d<s;d++)for(let f=0;f<r;f++){let p=d*u+f,b=p+1,g=p+u,_=g+1;h.push(p,b,_,p,_,g)}let l=o.length/3;super({id:e.id,topology:"triangle-list",indices:fe(l,h),attributes:{POSITION:{size:3,value:new Float32Array(o)},NORMAL:{size:3,value:new Float32Array(a)},TEXCOORD_0:{size:2,value:new Float32Array(c)},...e.attributes}})}};var tt=class extends ${constructor(e={}){let{radius:t=.5,nlat:n=10,nlong:r=10}=e;Y(t,"radius"),H(n,"nlat",2),H(r,"nlong",3);let s=[];for(let a=0;a<=n;a++){let c=-Math.PI/2+a/n*Math.PI,h=Math.cos(c),u=Math.sin(c);s.push({radius:t*h,y:t*u,normalRadius:h,normalY:u})}let o=wi(s,r);super({id:e.id,topology:"triangle-list",indices:o.indexArray,attributes:{POSITION:{size:3,value:new Float32Array(o.positions)},NORMAL:{size:3,value:new Float32Array(o.normals)},TEXCOORD_0:{size:2,value:new Float32Array(o.texCoords)},...e.attributes}})}};var it=class extends ${constructor(e={}){let{radius:t=.5,iterations:n=0}=e;if(Y(t,"radius"),H(n,"iterations",0),n>8)throw new Error("iterations must be <= 8");let r=(1+Math.sqrt(5))/2,s=[[-1,r,0],[1,r,0],[-1,-r,0],[1,-r,0],[0,-1,r],[0,1,r],[0,-1,-r],[0,1,-r],[r,0,-1],[r,0,1],[-r,0,-1],[-r,0,1]].map(Et),o=[[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,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]].map(u=>u.map(l=>s[l]));for(let u=0;u<n;u++){let l=[];for(let[d,f,p]of o){let b=Et([d[0]+f[0],d[1]+f[1],d[2]+f[2]]),g=Et([f[0]+p[0],f[1]+p[1],f[2]+p[2]]),_=Et([p[0]+d[0],p[1]+d[1],p[2]+d[2]]);l.push([d,b,_],[f,g,b],[p,_,g],[b,g,_])}o=l}let a=[],c=[],h=[];for(let u of o)for(let l of u)a.push(l[0]*t,l[1]*t,l[2]*t),c.push(...l),h.push(.5+Math.atan2(l[0],l[2])/(2*Math.PI),.5-Math.asin(l[1])/Math.PI);super({id:e.id,topology:"triangle-list",attributes:{POSITION:{size:3,value:new Float32Array(a)},NORMAL:{size:3,value:new Float32Array(c)},TEXCOORD_0:{size:2,value:new Float32Array(h)},...e.attributes}})}};function Et(i){let e=Math.hypot(...i);return i.map(t=>t/e)}var On=L(R(),1),B=class extends ${bufferLayout;constructor(e){let t={},n=new Map;for(let[o,a]of Object.entries(e.attributes)){let c=_e(o),h=n.get(c);h&&delete t[h],n.set(c,o),t[o]=a}let r=e.indices,s=r instanceof Uint8Array?new Uint16Array(r):r&&!ArrayBuffer.isView(r)&&r.value instanceof Uint8Array?{...r,value:new Uint16Array(r.value)}:r;super({...e,attributes:t,indices:s});for(let[o,a]of Object.entries(t))!ArrayBuffer.isView(a)&&Object.isExtensible(a)&&o!=="indices"&&(Object.assign(a,this.attributes[o]),this.attributes[o]=a);this.bufferLayout=e.bufferLayout||Ti(this.attributes)}};function _e(i){switch(i){case"POSITION":return"positions";case"NORMAL":return"normals";case"TEXCOORD_0":return"texCoords";case"TEXCOORD_1":return"texCoords1";case"COLOR_0":return"colors";default:return i}}function Ti(i){let e=[];for(let[t,n]of Object.entries(i)){if(!n)continue;let{value:r,size:s,normalized:o}=n;if(s===void 0)throw new Error(`Attribute ${t} is missing a size`);e.push({name:_e(t),format:On.vertexFormatDecoder.getVertexFormatFromAttribute(r,s,o)})}return e}var Ai=L(R(),1);function Ee(i,e={}){let t=e.bufferName||"geometry";if(Gs(i,t))return i;let n=e.minAttributeAlignment||4,r=Us(i,e.attributes),s=[],o=0,a=1/0;for(let[u,l]of r){if(!l)continue;if(l.constant)throw new Error(`Attribute ${u} is constant`);let{value:d,size:f,normalized:p}=l;if(!ArrayBuffer.isView(d))throw new Error(`Attribute ${u} is missing typed array data`);if(f===void 0)throw new Error(`Attribute ${u} is missing a size`);let b=Ai.vertexFormatDecoder.getVertexFormatFromAttribute(d,f,p),g=Ai.vertexFormatDecoder.getVertexFormatInfo(b);o=Rn(o,n),s.push({sourceName:u,attributeName:_e(u),value:d,size:f,format:b,byteOffset:o,byteLength:g.byteLength}),o+=g.byteLength;let _=d.length/f;if(!Number.isInteger(_))throw new Error(`Attribute ${u} length is not divisible by size`);a=Math.min(a,_)}if(s.length===0||!Number.isFinite(a))throw new Error(`Geometry ${i.id} has no interleavable attributes`);let c=Rn(o,n),h=new ArrayBuffer(a*c);for(let u of s)$s(h,a,c,u);return new B({id:i.id,topology:i.topology||"triangle-list",vertexCount:i.vertexCount,indices:i.indices,attributes:{[t]:{value:new Uint8Array(h),size:c,byteStride:c}},bufferLayout:[{name:t,stepMode:"vertex",byteStride:c,attributes:s.map(u=>({attribute:u.attributeName,format:u.format,byteOffset:u.byteOffset}))}]})}function Gs(i,e){if(i.bufferLayout?.length!==1)return!1;let t=i.bufferLayout[0];return t.name===e&&!!t.attributes?.length&&!!i.attributes[e]}function Us(i,e){let t=new Map,n=e||Object.keys(i.attributes);for(let r of n){let s=i.attributes[r];s&&t.set(_e(r),[r,s])}return Array.from(t.values())}function $s(i,e,t,n){let r=n.value.constructor,s=r.BYTES_PER_ELEMENT;if(n.byteOffset%s!==0||t%s!==0)throw new Error(`Attribute ${n.sourceName} is not aligned to its component type`);let o=new r(i),a=n.value,c=n.byteOffset/s,h=t/s;for(let u=0;u<e;u++){let l=u*n.size,d=u*h+c;for(let f=0;f<n.size;f++)o[d+f]=a[l+f]}}function Rn(i,e){return Math.ceil(i/e)*e}function Pi(i){let e=i.value;if(e instanceof Float32Array)return e;let t=new Float32Array(e.length),n=Nn(e),r=e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array;for(let s=0;s<e.length;s++){let o=Number(e[s]);t[s]=i.normalized&&n?r?Math.max(o/n,-1):o/n:o}return t}function Si(i,e,t){let n={};for(let r of["POSITION","NORMAL","TANGENT"]){let s=i[r];if(!s)continue;let o=new Float32Array(s),a=r==="TANGENT"?4:3,c=Math.floor(s.length/a);for(let h=0;h<Math.min(e.length,t.length);h++){let u=t[h],l=e[h][r];if(!u||!l)continue;let d=r==="TANGENT"&&l.length===c*4?4:3;for(let f=0;f<c;f++){let p=f*a,b=f*d;for(let g=0;g<3;g++)o[p+g]+=(l[b+g]||0)*u}}r!=="POSITION"&&Xs(o,a),n[r]=o}return n}function kn(i,e,t,n){let r={};for(let l of["POSITION","NORMAL","TANGENT"]){let d=e.attributes[l];d&&(r[l]=Pi(d))}let s=Si(r,t,n),o={};for(let[l,d]of Object.entries(e.attributes))d&&(o[l]=d);for(let l of["POSITION","NORMAL","TANGENT"]){let d=s[l],f=o[l];d&&f&&(o[l]={...f,value:Vs(f,d)})}let a=new B({id:e.id,topology:e.topology||"triangle-list",vertexCount:e.vertexCount,indices:e.indices,attributes:o,bufferLayout:e.bufferLayout}),h=Ee(a).attributes.geometry?.value,u=i._gpuGeometry?.attributes.geometry||i.bufferAttributes.geometry;if(h&&u){u.write(h);return}for(let l of["POSITION","NORMAL","TANGENT"]){let d=s[l];if(d){let f=l==="POSITION"?"positions":l==="NORMAL"?"normals":"TANGENT";i.bufferAttributes[f]?.write(d)}}}function Vs(i,e){if(i.value instanceof Float32Array)return e;let t=i.value.slice(),n=Nn(t),r=t instanceof Int8Array||t instanceof Int16Array||t instanceof Int32Array;for(let s=0;s<e.length;s++){let o=e[s];t[s]=i.normalized&&n?Math.round(Math.max(r?-1:0,Math.min(1,o))*n):o}return t}function Nn(i){return i instanceof Int8Array?127:i instanceof Uint8Array||i instanceof Uint8ClampedArray?255:i instanceof Int16Array?32767:i instanceof Uint16Array?65535:i instanceof Int32Array?2147483647:i instanceof Uint32Array?4294967295:0}function Xs(i,e){for(let t=0;t<i.length;t+=e){let n=Math.hypot(i[t],i[t+1],i[t+2]);n>0&&(i[t]/=n,i[t+1]/=n,i[t+2]/=n)}}var _h=1/Math.PI*180,vh=1/180*Math.PI,Ys={EPSILON:1e-12,debug:!1,precision:4,printTypes:!1,printDegrees:!1,printRowMajor:!0,_cartographicRadians:!1};globalThis.mathgl=globalThis.mathgl||{config:{...Ys}};var U=globalThis.mathgl.config;function Fn(i,{precision:e=U.precision}={}){return i=Ws(i),`${parseFloat(i.toPrecision(e))}`}function Le(i){return Array.isArray(i)||ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Ci(i,e,t){let n=U.EPSILON;t&&(U.EPSILON=t);try{if(i===e)return!0;if(Le(i)&&Le(e)){if(i.length!==e.length)return!1;for(let r=0;r<i.length;++r)if(!Ci(i[r],e[r]))return!1;return!0}return i&&i.equals?i.equals(e):e&&e.equals?e.equals(i):typeof i=="number"&&typeof e=="number"?Math.abs(i-e)<=U.EPSILON*Math.max(1,Math.abs(i),Math.abs(e)):!1}finally{U.EPSILON=n}}function Ws(i){return Math.round(i/U.EPSILON)*U.EPSILON}var Oe=class extends Array{clone(){return new this.constructor().copy(this)}fromArray(e,t=0){for(let n=0;n<this.ELEMENTS;++n)this[n]=e[n+t];return this.check()}toArray(e=[],t=0){for(let n=0;n<this.ELEMENTS;++n)e[t+n]=this[n];return e}toObject(e){return e}from(e){return Array.isArray(e)?this.copy(e):this.fromObject(e)}to(e){return e===this?this:Le(e)?this.toArray(e):this.toObject(e)}toTarget(e){return e?this.to(e):this}toString(){return this.formatString(U)}formatString(e){let t="";for(let n=0;n<this.ELEMENTS;++n)t+=(n>0?", ":"")+Fn(this[n],e);return`${e.printTypes?this.constructor.name:""}[${t}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(!Ci(this[t],e[t]))return!1;return!0}exactEquals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(this[t]!==e[t])return!1;return!0}negate(){for(let e=0;e<this.ELEMENTS;++e)this[e]=-this[e];return this.check()}lerp(e,t,n){if(n===void 0)return this.lerp(this,e,t);for(let r=0;r<this.ELEMENTS;++r){let s=e[r],o=typeof t=="number"?t:t[r];this[r]=s+n*(o-s)}return this.check()}min(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.min(e[t],this[t]);return this.check()}max(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.max(e[t],this[t]);return this.check()}clamp(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e[n]),t[n]);return this.check()}add(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]+=t[n];return this.check()}subtract(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]-=t[n];return this.check()}scale(e){if(typeof e=="number")for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;else for(let t=0;t<this.ELEMENTS&&t<e.length;++t)this[t]*=e[t];return this.check()}multiplyByScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}check(){if(U.debug&&!this.validate())throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);return this}validate(){let e=this.length===this.ELEMENTS;for(let t=0;t<this.ELEMENTS;++t)e=e&&Number.isFinite(this[t]);return e}};function Hs(i,e){if(i.length!==e)return!1;for(let t=0;t<i.length;++t)if(!Number.isFinite(i[t]))return!1;return!0}function V(i){if(!Number.isFinite(i))throw new Error(`Invalid number ${JSON.stringify(i)}`);return i}function Lt(i,e,t=""){if(U.debug&&!Hs(i,e))throw new Error(`math.gl: ${t} some fields set to invalid numbers'`);return i}var Ot=class extends Oe{toString(){let e="[";if(U.printRowMajor){e+="row-major:";for(let t=0;t<this.RANK;++t)for(let n=0;n<this.RANK;++n)e+=` ${this[n*this.RANK+t]}`}else{e+="column-major:";for(let t=0;t<this.ELEMENTS;++t)e+=` ${this[t]}`}return e+="]",e}getElementIndex(e,t){return t*this.RANK+e}getElement(e,t){return this[t*this.RANK+e]}setElement(e,t,n){return this[t*this.RANK+e]=V(n),this}getColumn(e,t=new Array(this.RANK).fill(-0)){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)t[r]=this[n+r];return t}setColumn(e,t){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)this[n+r]=t[r];return this}};function Ei(i,e){if(!i)throw new Error(`math.gl assertion ${e}`)}var Rt=class extends Oe{get x(){return this[0]}set x(e){this[0]=V(e)}get y(){return this[1]}set y(e){this[1]=V(e)}len(){return Math.sqrt(this.lengthSquared())}magnitude(){return this.len()}lengthSquared(){let e=0;for(let t=0;t<this.ELEMENTS;++t)e+=this[t]*this[t];return e}magnitudeSquared(){return this.lengthSquared()}distance(e){return Math.sqrt(this.distanceSquared(e))}distanceSquared(e){let t=0;for(let n=0;n<this.ELEMENTS;++n){let r=this[n]-e[n];t+=r*r}return V(t)}dot(e){let t=0;for(let n=0;n<this.ELEMENTS;++n)t+=this[n]*e[n];return V(t)}normalize(){let e=this.magnitude();if(e!==0)for(let t=0;t<this.ELEMENTS;++t)this[t]/=e;return this.check()}multiply(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]*=t[n];return this.check()}divide(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]/=t[n];return this.check()}lengthSq(){return this.lengthSquared()}distanceTo(e){return this.distance(e)}distanceToSquared(e){return this.distanceSquared(e)}getComponent(e){return Ei(e>=0&&e<this.ELEMENTS,"index is out of range"),V(this[e])}setComponent(e,t){return Ei(e>=0&&e<this.ELEMENTS,"index is out of range"),this[e]=t,this.check()}addVectors(e,t){return this.copy(e).add(t)}subVectors(e,t){return this.copy(e).subtract(t)}multiplyVectors(e,t){return this.copy(e).multiply(t)}addScaledVector(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]+=e[n]*t;return this.check()}};function Dn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[4]*r+t[12],i[1]=t[1]*n+t[5]*r+t[13],i}function Bn(i,e,t){let n=e[0],r=e[1],s=t[3]*n+t[7]*r||1;return i[0]=(t[0]*n+t[4]*r)/s,i[1]=(t[1]*n+t[5]*r)/s,i}function kt(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s||1;return i[0]=(t[0]*n+t[4]*r+t[8]*s)/o,i[1]=(t[1]*n+t[5]*r+t[9]*s)/o,i[2]=(t[2]*n+t[6]*r+t[10]*s)/o,i}function zn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[2]*r,i[1]=t[1]*n+t[3]*r,i[2]=e[2],i}function qs(i,e){return i[0]*e[0]+i[1]*e[1]+i[2]*e[2]}function jn(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[0],a=t[1],c=t[2];return i[0]=r*c-s*a,i[1]=s*o-n*c,i[2]=n*a-r*o,i}function Nt(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s+t[15];return o=o||1,i[0]=(t[0]*n+t[4]*r+t[8]*s+t[12])/o,i[1]=(t[1]*n+t[5]*r+t[9]*s+t[13])/o,i[2]=(t[2]*n+t[6]*r+t[10]*s+t[14])/o,i}function Gn(i,e,t){let n=e[0],r=e[1],s=e[2];return i[0]=n*t[0]+r*t[3]+s*t[6],i[1]=n*t[1]+r*t[4]+s*t[7],i[2]=n*t[2]+r*t[5]+s*t[8],i}function Un(i,e,t){let n=t[0],r=t[1],s=t[2],o=t[3],a=e[0],c=e[1],h=e[2],u=r*h-s*c,l=s*a-n*h,d=n*c-r*a,f=r*d-s*l,p=s*u-n*d,b=n*l-r*u,g=o*2;return u*=g,l*=g,d*=g,f*=2,p*=2,b*=2,i[0]=a+u+f,i[1]=c+l+p,i[2]=h+d+b,i}function $n(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0],s[1]=r[1]*Math.cos(n)-r[2]*Math.sin(n),s[2]=r[1]*Math.sin(n)+r[2]*Math.cos(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Vn(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[2]*Math.sin(n)+r[0]*Math.cos(n),s[1]=r[1],s[2]=r[2]*Math.cos(n)-r[0]*Math.sin(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Xn(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0]*Math.cos(n)-r[1]*Math.sin(n),s[1]=r[0]*Math.sin(n)+r[1]*Math.cos(n),s[2]=r[2],i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Yn(i,e){let t=i[0],n=i[1],r=i[2],s=e[0],o=e[1],a=e[2],c=Math.sqrt((t*t+n*n+r*r)*(s*s+o*o+a*a)),h=c&&qs(i,e)/c;return Math.acos(Math.min(Math.max(h,-1),1))}var Li=[0,0,0],Ft,q=class i extends Rt{static get ZERO(){return Ft||(Ft=new i(0,0,0),Object.freeze(Ft)),Ft}constructor(e=0,t=0,n=0){super(-0,-0,-0),arguments.length===1&&Le(e)?this.copy(e):(U.debug&&(V(e),V(t),V(n)),this[0]=e,this[1]=t,this[2]=n)}set(e,t,n){return this[0]=e,this[1]=t,this[2]=n,this.check()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this.check()}fromObject(e){return U.debug&&(V(e.x),V(e.y),V(e.z)),this[0]=e.x,this[1]=e.y,this[2]=e.z,this.check()}toObject(e){return e.x=this[0],e.y=this[1],e.z=this[2],e}get ELEMENTS(){return 3}get z(){return this[2]}set z(e){this[2]=V(e)}angle(e){return Yn(this,e)}cross(e){return jn(this,this,e),this.check()}rotateX({radians:e,origin:t=Li}){return $n(this,this,t,e),this.check()}rotateY({radians:e,origin:t=Li}){return Vn(this,this,t,e),this.check()}rotateZ({radians:e,origin:t=Li}){return Xn(this,this,t,e),this.check()}transform(e){return this.transformAsPoint(e)}transformAsPoint(e){return Nt(this,this,e),this.check()}transformAsVector(e){return kt(this,this,e),this.check()}transformByMatrix3(e){return Gn(this,this,e),this.check()}transformByMatrix2(e){return zn(this,this,e),this.check()}transformByQuaternion(e){return Un(this,this,e),this.check()}};function Ks(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function Wn(i,e){if(i===e){let t=e[1],n=e[2],r=e[3],s=e[6],o=e[7],a=e[11];i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=t,i[6]=e[9],i[7]=e[13],i[8]=n,i[9]=s,i[11]=e[14],i[12]=r,i[13]=o,i[14]=a}else i[0]=e[0],i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=e[1],i[5]=e[5],i[6]=e[9],i[7]=e[13],i[8]=e[2],i[9]=e[6],i[10]=e[10],i[11]=e[14],i[12]=e[3],i[13]=e[7],i[14]=e[11],i[15]=e[15];return i}function Hn(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=e[4],a=e[5],c=e[6],h=e[7],u=e[8],l=e[9],d=e[10],f=e[11],p=e[12],b=e[13],g=e[14],_=e[15],v=t*a-n*o,y=t*c-r*o,I=t*h-s*o,m=n*c-r*a,x=n*h-s*a,M=r*h-s*c,w=u*b-l*p,T=u*g-d*p,P=u*_-f*p,E=l*g-d*b,A=l*_-f*b,O=d*_-f*g,C=v*O-y*A+I*E+m*P-x*T+M*w;return C?(C=1/C,i[0]=(a*O-c*A+h*E)*C,i[1]=(r*A-n*O-s*E)*C,i[2]=(b*M-g*x+_*m)*C,i[3]=(d*x-l*M-f*m)*C,i[4]=(c*P-o*O-h*T)*C,i[5]=(t*O-r*P+s*T)*C,i[6]=(g*I-p*M-_*y)*C,i[7]=(u*M-d*I+f*y)*C,i[8]=(o*A-a*P+h*w)*C,i[9]=(n*P-t*A-s*w)*C,i[10]=(p*x-b*I+_*v)*C,i[11]=(l*I-u*x-f*v)*C,i[12]=(a*T-o*E-c*w)*C,i[13]=(t*E-n*T+r*w)*C,i[14]=(b*y-p*m-g*v)*C,i[15]=(u*m-l*y+d*v)*C,i):null}function qn(i){let e=i[0],t=i[1],n=i[2],r=i[3],s=i[4],o=i[5],a=i[6],c=i[7],h=i[8],u=i[9],l=i[10],d=i[11],f=i[12],p=i[13],b=i[14],g=i[15],_=e*o-t*s,v=e*a-n*s,y=t*a-n*o,I=h*p-u*f,m=h*b-l*f,x=u*b-l*p,M=e*x-t*m+n*I,w=s*x-o*m+a*I,T=h*y-u*v+l*_,P=f*y-p*v+b*_;return c*M-r*w+g*T-d*P}function Ri(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3],a=e[4],c=e[5],h=e[6],u=e[7],l=e[8],d=e[9],f=e[10],p=e[11],b=e[12],g=e[13],_=e[14],v=e[15],y=t[0],I=t[1],m=t[2],x=t[3];return i[0]=y*n+I*a+m*l+x*b,i[1]=y*r+I*c+m*d+x*g,i[2]=y*s+I*h+m*f+x*_,i[3]=y*o+I*u+m*p+x*v,y=t[4],I=t[5],m=t[6],x=t[7],i[4]=y*n+I*a+m*l+x*b,i[5]=y*r+I*c+m*d+x*g,i[6]=y*s+I*h+m*f+x*_,i[7]=y*o+I*u+m*p+x*v,y=t[8],I=t[9],m=t[10],x=t[11],i[8]=y*n+I*a+m*l+x*b,i[9]=y*r+I*c+m*d+x*g,i[10]=y*s+I*h+m*f+x*_,i[11]=y*o+I*u+m*p+x*v,y=t[12],I=t[13],m=t[14],x=t[15],i[12]=y*n+I*a+m*l+x*b,i[13]=y*r+I*c+m*d+x*g,i[14]=y*s+I*h+m*f+x*_,i[15]=y*o+I*u+m*p+x*v,i}function Kn(i,e,t){let n=t[0],r=t[1],s=t[2],o,a,c,h,u,l,d,f,p,b,g,_;return e===i?(i[12]=e[0]*n+e[4]*r+e[8]*s+e[12],i[13]=e[1]*n+e[5]*r+e[9]*s+e[13],i[14]=e[2]*n+e[6]*r+e[10]*s+e[14],i[15]=e[3]*n+e[7]*r+e[11]*s+e[15]):(o=e[0],a=e[1],c=e[2],h=e[3],u=e[4],l=e[5],d=e[6],f=e[7],p=e[8],b=e[9],g=e[10],_=e[11],i[0]=o,i[1]=a,i[2]=c,i[3]=h,i[4]=u,i[5]=l,i[6]=d,i[7]=f,i[8]=p,i[9]=b,i[10]=g,i[11]=_,i[12]=o*n+u*r+p*s+e[12],i[13]=a*n+l*r+b*s+e[13],i[14]=c*n+d*r+g*s+e[14],i[15]=h*n+f*r+_*s+e[15]),i}function Zn(i,e,t){let n=t[0],r=t[1],s=t[2];return i[0]=e[0]*n,i[1]=e[1]*n,i[2]=e[2]*n,i[3]=e[3]*n,i[4]=e[4]*r,i[5]=e[5]*r,i[6]=e[6]*r,i[7]=e[7]*r,i[8]=e[8]*s,i[9]=e[9]*s,i[10]=e[10]*s,i[11]=e[11]*s,i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],i}function Qn(i,e,t,n){let r=n[0],s=n[1],o=n[2],a=Math.sqrt(r*r+s*s+o*o),c,h,u,l,d,f,p,b,g,_,v,y,I,m,x,M,w,T,P,E,A,O,C,D;return a<1e-6?null:(a=1/a,r*=a,s*=a,o*=a,h=Math.sin(t),c=Math.cos(t),u=1-c,l=e[0],d=e[1],f=e[2],p=e[3],b=e[4],g=e[5],_=e[6],v=e[7],y=e[8],I=e[9],m=e[10],x=e[11],M=r*r*u+c,w=s*r*u+o*h,T=o*r*u-s*h,P=r*s*u-o*h,E=s*s*u+c,A=o*s*u+r*h,O=r*o*u+s*h,C=s*o*u-r*h,D=o*o*u+c,i[0]=l*M+b*w+y*T,i[1]=d*M+g*w+I*T,i[2]=f*M+_*w+m*T,i[3]=p*M+v*w+x*T,i[4]=l*P+b*E+y*A,i[5]=d*P+g*E+I*A,i[6]=f*P+_*E+m*A,i[7]=p*P+v*E+x*A,i[8]=l*O+b*C+y*D,i[9]=d*O+g*C+I*D,i[10]=f*O+_*C+m*D,i[11]=p*O+v*C+x*D,e!==i&&(i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i)}function Jn(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[4],o=e[5],a=e[6],c=e[7],h=e[8],u=e[9],l=e[10],d=e[11];return e!==i&&(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[4]=s*r+h*n,i[5]=o*r+u*n,i[6]=a*r+l*n,i[7]=c*r+d*n,i[8]=h*r-s*n,i[9]=u*r-o*n,i[10]=l*r-a*n,i[11]=d*r-c*n,i}function er(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],h=e[8],u=e[9],l=e[10],d=e[11];return e!==i&&(i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r-h*n,i[1]=o*r-u*n,i[2]=a*r-l*n,i[3]=c*r-d*n,i[8]=s*n+h*r,i[9]=o*n+u*r,i[10]=a*n+l*r,i[11]=c*n+d*r,i}function tr(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],h=e[4],u=e[5],l=e[6],d=e[7];return e!==i&&(i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r+h*n,i[1]=o*r+u*n,i[2]=a*r+l*n,i[3]=c*r+d*n,i[4]=h*r-s*n,i[5]=u*r-o*n,i[6]=l*r-a*n,i[7]=d*r-c*n,i}function ir(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=t+t,a=n+n,c=r+r,h=t*o,u=n*o,l=n*a,d=r*o,f=r*a,p=r*c,b=s*o,g=s*a,_=s*c;return i[0]=1-l-p,i[1]=u+_,i[2]=d-g,i[3]=0,i[4]=u-_,i[5]=1-h-p,i[6]=f+b,i[7]=0,i[8]=d+g,i[9]=f-b,i[10]=1-h-l,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function nr(i,e,t,n,r,s,o){let a=1/(t-e),c=1/(r-n),h=1/(s-o);return i[0]=s*2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s*2*c,i[6]=0,i[7]=0,i[8]=(t+e)*a,i[9]=(r+n)*c,i[10]=(o+s)*h,i[11]=-1,i[12]=0,i[13]=0,i[14]=o*s*2*h,i[15]=0,i}function Zs(i,e,t,n,r){let s=1/Math.tan(e/2);if(i[0]=s/t,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,r!=null&&r!==1/0){let o=1/(n-r);i[10]=(r+n)*o,i[14]=2*r*n*o}else i[10]=-1,i[14]=-2*n;return i}var rr=Zs;function Qs(i,e,t,n,r,s,o){let a=1/(e-t),c=1/(n-r),h=1/(s-o);return i[0]=-2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*c,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=2*h,i[11]=0,i[12]=(e+t)*a,i[13]=(r+n)*c,i[14]=(o+s)*h,i[15]=1,i}var sr=Qs;function or(i,e,t,n){let r,s,o,a,c,h,u,l,d,f,p=e[0],b=e[1],g=e[2],_=n[0],v=n[1],y=n[2],I=t[0],m=t[1],x=t[2];return Math.abs(p-I)<1e-6&&Math.abs(b-m)<1e-6&&Math.abs(g-x)<1e-6?Ks(i):(l=p-I,d=b-m,f=g-x,r=1/Math.sqrt(l*l+d*d+f*f),l*=r,d*=r,f*=r,s=v*f-y*d,o=y*l-_*f,a=_*d-v*l,r=Math.sqrt(s*s+o*o+a*a),r?(r=1/r,s*=r,o*=r,a*=r):(s=0,o=0,a=0),c=d*a-f*o,h=f*s-l*a,u=l*o-d*s,r=Math.sqrt(c*c+h*h+u*u),r?(r=1/r,c*=r,h*=r,u*=r):(c=0,h=0,u=0),i[0]=s,i[1]=c,i[2]=l,i[3]=0,i[4]=o,i[5]=h,i[6]=d,i[7]=0,i[8]=a,i[9]=u,i[10]=f,i[11]=0,i[12]=-(s*p+o*b+a*g),i[13]=-(c*p+h*b+u*g),i[14]=-(l*p+d*b+f*g),i[15]=1,i)}function ar(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3];return i[0]=t[0]*n+t[4]*r+t[8]*s+t[12]*o,i[1]=t[1]*n+t[5]*r+t[9]*s+t[13]*o,i[2]=t[2]*n+t[6]*r+t[10]*s+t[14]*o,i[3]=t[3]*n+t[7]*r+t[11]*s+t[15]*o,i}var Fi;(function(i){i[i.COL0ROW0=0]="COL0ROW0",i[i.COL0ROW1=1]="COL0ROW1",i[i.COL0ROW2=2]="COL0ROW2",i[i.COL0ROW3=3]="COL0ROW3",i[i.COL1ROW0=4]="COL1ROW0",i[i.COL1ROW1=5]="COL1ROW1",i[i.COL1ROW2=6]="COL1ROW2",i[i.COL1ROW3=7]="COL1ROW3",i[i.COL2ROW0=8]="COL2ROW0",i[i.COL2ROW1=9]="COL2ROW1",i[i.COL2ROW2=10]="COL2ROW2",i[i.COL2ROW3=11]="COL2ROW3",i[i.COL3ROW0=12]="COL3ROW0",i[i.COL3ROW1=13]="COL3ROW1",i[i.COL3ROW2=14]="COL3ROW2",i[i.COL3ROW3=15]="COL3ROW3"})(Fi||(Fi={}));var Js=45*Math.PI/180,eo=1,ki=.1,Ni=500,to=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),k=class extends Ot{static get IDENTITY(){return no()}static get ZERO(){return io()}get ELEMENTS(){return 16}get RANK(){return 4}get INDICES(){return Fi}constructor(e){super(-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0),arguments.length===1&&Array.isArray(e)?this.copy(e):this.identity()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this[4]=e[4],this[5]=e[5],this[6]=e[6],this[7]=e[7],this[8]=e[8],this[9]=e[9],this[10]=e[10],this[11]=e[11],this[12]=e[12],this[13]=e[13],this[14]=e[14],this[15]=e[15],this.check()}set(e,t,n,r,s,o,a,c,h,u,l,d,f,p,b,g){return this[0]=e,this[1]=t,this[2]=n,this[3]=r,this[4]=s,this[5]=o,this[6]=a,this[7]=c,this[8]=h,this[9]=u,this[10]=l,this[11]=d,this[12]=f,this[13]=p,this[14]=b,this[15]=g,this.check()}setRowMajor(e,t,n,r,s,o,a,c,h,u,l,d,f,p,b,g){return this[0]=e,this[1]=s,this[2]=h,this[3]=f,this[4]=t,this[5]=o,this[6]=u,this[7]=p,this[8]=n,this[9]=a,this[10]=l,this[11]=b,this[12]=r,this[13]=c,this[14]=d,this[15]=g,this.check()}toRowMajor(e){return e[0]=this[0],e[1]=this[4],e[2]=this[8],e[3]=this[12],e[4]=this[1],e[5]=this[5],e[6]=this[9],e[7]=this[13],e[8]=this[2],e[9]=this[6],e[10]=this[10],e[11]=this[14],e[12]=this[3],e[13]=this[7],e[14]=this[11],e[15]=this[15],e}identity(){return this.copy(to)}fromObject(e){return this.check()}fromQuaternion(e){return ir(this,e),this.check()}fromMatrix3(e){return this.set(e[0],e[1],e[2],0,e[3],e[4],e[5],0,e[6],e[7],e[8],0,0,0,0,1)}frustum(e){let{left:t,right:n,bottom:r,top:s,near:o=ki,far:a=Ni}=e;return a===1/0?ro(this,t,n,r,s,o):nr(this,t,n,r,s,o,a),this.check()}lookAt(e){let{eye:t,center:n=[0,0,0],up:r=[0,1,0]}=e;return or(this,t,n,r),this.check()}ortho(e){let{left:t,right:n,bottom:r,top:s,near:o=ki,far:a=Ni}=e;return sr(this,t,n,r,s,o,a),this.check()}orthographic(e){let{fovy:t=Js,aspect:n=eo,focalDistance:r=1,near:s=ki,far:o=Ni}=e;cr(t);let a=t/2,c=r*Math.tan(a),h=c*n;return this.ortho({left:-h,right:h,bottom:-c,top:c,near:s,far:o})}perspective(e){let{fovy:t=45*Math.PI/180,aspect:n=1,near:r=.1,far:s=500}=e;return cr(t),rr(this,t,n,r,s),this.check()}determinant(){return qn(this)}getScale(e=[-0,-0,-0]){return e[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]),e[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]),e[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]),e}getTranslation(e=[-0,-0,-0]){return e[0]=this[12],e[1]=this[13],e[2]=this[14],e}getRotation(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=0,e[4]=this[4]*r,e[5]=this[5]*s,e[6]=this[6]*o,e[7]=0,e[8]=this[8]*r,e[9]=this[9]*s,e[10]=this[10]*o,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}getRotationMatrix3(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=this[4]*r,e[4]=this[5]*s,e[5]=this[6]*o,e[6]=this[8]*r,e[7]=this[9]*s,e[8]=this[10]*o,e}transpose(){return Wn(this,this),this.check()}invert(){return Hn(this,this),this.check()}multiplyLeft(e){return Ri(this,e,this),this.check()}multiplyRight(e){return Ri(this,this,e),this.check()}rotateX(e){return Jn(this,this,e),this.check()}rotateY(e){return er(this,this,e),this.check()}rotateZ(e){return tr(this,this,e),this.check()}rotateXYZ(e){return this.rotateX(e[0]).rotateY(e[1]).rotateZ(e[2])}rotateAxis(e,t){return Qn(this,this,e,t),this.check()}scale(e){return Zn(this,this,Array.isArray(e)?e:[e,e,e]),this.check()}translate(e){return Kn(this,this,e),this.check()}transform(e,t){return e.length===4?(t=ar(t||[-0,-0,-0,-0],e,this),Lt(t,4),t):this.transformAsPoint(e,t)}transformAsPoint(e,t){let{length:n}=e,r;switch(n){case 2:r=Dn(t||[-0,-0],e,this);break;case 3:r=Nt(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return Lt(r,e.length),r}transformAsVector(e,t){let n;switch(e.length){case 2:n=Bn(t||[-0,-0],e,this);break;case 3:n=kt(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return Lt(n,e.length),n}makeRotationX(e){return this.identity().rotateX(e)}makeTranslation(e,t,n){return this.identity().translate([e,t,n])}},Dt,Bt;function io(){return Dt||(Dt=new k([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Object.freeze(Dt)),Dt}function no(){return Bt||(Bt=new k,Object.freeze(Bt)),Bt}function cr(i){if(i>Math.PI*2)throw Error("expected radians")}function ro(i,e,t,n,r,s){let o=2*s/(t-e),a=2*s/(r-n),c=(t+e)/(t-e),h=(r+n)/(r-n),u=-1,l=-1,d=-2*s;return i[0]=o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=a,i[6]=0,i[7]=0,i[8]=c,i[9]=h,i[10]=u,i[11]=l,i[12]=0,i[13]=0,i[14]=d,i[15]=0,i}function hr(i){let{joints:e,meshNode:t,worldMatrices:n,inverseBindMatrices:r,target:s}=i,o=e.length,a=s&&s.length===o*16?s:new Float32Array(o*16),c=t?n.get(t)||t.matrix:void 0,h=c?new k(c).invert():null;for(let u=0;u<o;u++){let l=e[u],d=n.get(l)||l.matrix,f=h?new k(h).multiplyRight(d):new k(d),p=u*16;if(r&&r.length>=p+16){let b=new k;for(let g=0;g<16;g++)b[g]=r[p+g];f.multiplyRight(b)}a.set(f,p)}return a}var so=1,oo=1,zt=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(e){let{delay:t=0,duration:n=Number.POSITIVE_INFINITY,rate:r=1,repeat:s=1}=e,o=so++,a={time:0,delay:t,duration:n,rate:r,repeat:s};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(e){this.channels.delete(e);for(let[t,n]of this.animations)n.channel===e&&this.detachAnimation(t)}isFinished(e){let t=this.channels.get(e);return t===void 0?!1:this.time>=t.delay+t.duration*t.repeat}getTime(e){if(e===void 0)return this.time;let t=this.channels.get(e);return t===void 0?-1:t.time}setTime(e){this.time=Math.max(0,e);let t=this.channels.values();for(let r of t)this._setChannelTime(r,this.time);let n=this.animations.values();for(let r of n){let{animation:s,channel:o}=r;s.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(e,t){let n=oo++;return this.animations.set(n,{animation:e,channel:t}),e.setTime(this.getTime(t)),n}detachAnimation(e){this.animations.delete(e)}update(e){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=e),this.setTime(this.time+(e-this.lastEngineTime)),this.lastEngineTime=e)}_setChannelTime(e,t){let n=t-e.delay,r=e.duration*e.repeat;n>=r?e.time=e.duration*e.rate:(e.time=Math.max(0,n)%e.duration,e.time*=e.rate)}};var jt=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(e){this.setKeyFrames(e),this.setTime(0)}setKeyFrames(e){let t=e.length;this.times.length=t,this.values.length=t;for(let n=0;n<t;++n)this.times[n]=e[n][0],this.values[n]=e[n][1];this._calculateKeys(this._lastTime)}setTime(e){e=Math.max(0,e),e!==this._lastTime&&(this._calculateKeys(e),this._lastTime=e)}getStartTime(){return this.times[this.startIndex]}getEndTime(){return this.times[this.endIndex]}getStartData(){return this.values[this.startIndex]}getEndData(){return this.values[this.endIndex]}_calculateKeys(e){let t=0,n=this.times.length;for(t=0;t<n-2&&!(this.times[t+1]>e);++t);this.startIndex=t,this.endIndex=t+1;let r=this.times[this.startIndex],s=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(e-r)/(s-r)),1)}};var Gt=class{constructor(e){}async onInitialize(e){return null}};var lr=L(R(),1);function Ut(i){let e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,i):setTimeout(()=>i(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function $t(i){let e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,i);return}clearTimeout(i)}function nt(){let i;if(typeof window<"u"&&window.performance)i=window.performance.now();else if(typeof process<"u"&&process.hrtime){let e=process.hrtime();i=e[0]*1e3+e[1]/1e6}else i=Date.now();return i}var ve=class{constructor(e,t){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=e,this.type=t,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(e){return this.sampleSize=e,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(e){return this._count+=e,this._samples++,this._checkSampling(),this}subtractCount(e){return this._count-=e,this._samples++,this._checkSampling(),this}addTime(e){return this._time+=e,this.lastTiming=e,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=nt(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(nt()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var Re=class{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,t="count"){return this._getOrCreate({name:e,type:t})}get size(){return Object.keys(this.stats).length}reset(){for(let e of Object.values(this.stats))e.reset();return this}forEach(e){for(let t of Object.values(this.stats))e(t)}getTable(){let e={};return this.forEach(t=>{e[t.name]={time:t.time||0,count:t.count||0,average:t.getAverageTime()||0,hz:t.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(t=>this._getOrCreate(t))}_getOrCreate(e){let{name:t,type:n}=e,r=this.stats[t];return r||(e instanceof ve?r=e:r=new ve(t,n),this.stats[t]=r),r}};var ao=0,co="Animation Loop",ur={requestAnimationFrame:i=>Ut(i),cancelAnimationFrame:i=>$t(i)},ke=class i{static defaultAnimationLoopProps={device:null,mobileQuality:void 0,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>{console.error(e)},stats:void 0,autoResizeViewport:!1,animationFrameProvider:ur};device=null;canvas=null;props;animationProps=null;timeline=null;stats;sharedStats;cpuTime;gpuTime;frameRate;display;_needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;_lastFrameTime=0;constructor(e){if(this.props={...i.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new Re({id:`animation-loop-${ao++}`}),this.sharedStats=lr.luma.stats.get(co),this.frameRate=this.stats.get("Frame Rate"),this.frameRate.setSampleSize(1),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.setProps({autoResizeViewport:e.autoResizeViewport,animationFrameProvider:e.animationFrameProvider}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null),this.device?._disableDebugGPUTime()}delete(){this.destroy()}reportError(e){this._error=e,this.props.onError(e),this.props.onError===i.defaultAnimationLoopProps.onError&&typeof window<"u"&&typeof ErrorEvent<"u"&&window.dispatchEvent(new ErrorEvent("error",{error:e,message:e.message}))}setNeedsRedraw(e){return this._needsRedraw=this._needsRedraw||e,this}needsRedraw(){let e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){if("autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),"animationFrameProvider"in e){let t=e.animationFrameProvider||ur;if(t!==this.props.animationFrameProvider){let n=this._animationFrameId!==null;n&&this._cancelAnimationFrame(),this.props.animationFrameProvider=t,n&&this._requestAnimationFrame()}}return this}async start(){if(this._running)return this;this._running=!0;try{let e;if(!this._initialized){if(this._initialized=!0,await this._initDevice(),this._initialize(),!this._running)return null;await this.props.onInitialize(this._getAnimationProps())}return this._running?(e!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(e){let t=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(t),t}}stop(){if(this._running){let e=this.animationProps;this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1,this._lastFrameTime=0,e&&this.props.onFinalize(e)}return this}redraw(e,t=null){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),this._setupFrame(),this.animationProps&&(this.animationProps.animationFrame=t),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(e){return this.timeline=e,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(e=>{this._resolveNextFrame=e})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeViewport(),this.device?._enableDebugGPUTime()}_setDisplay(e){this.display&&(this.display.destroy(),this.display.animationLoop=null),e&&(e.animationLoop=this),this.display=e}_requestAnimationFrame(){this._running&&(this._animationFrameId=this.props.animationFrameProvider.requestAnimationFrame(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(this.props.animationFrameProvider.cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e,t){if(this._running)try{this.redraw(e,t??null),this._requestAnimationFrame()}catch(n){let r=n instanceof Error?n:new Error(String(n));this.reportError(r),this.stop()}}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}let t=this.props.onRender(this._getAnimationProps());this.device&&t!==!1&&this.device.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){let e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");let t=e?.canvas,n=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:t,useDevicePixels:n,timeline:this.timeline,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,animationFrame:null,_mousePosition:null,mobileQuality:this.props.mobileQuality}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:e,height:t,aspect:n}=this._getSizeAndAspect();(e!==this.animationProps.width||t!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),n!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=e,this.animationProps.height=t,this.animationProps.aspect=n,this.animationProps.needsRedraw=this._needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.getDefaultCanvasContext().canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";let t=document.createElement("div");t.style.position="absolute",t.style.left="10px",t.style.bottom="10px",t.style.width="300px",t.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(t);let n=this.props.onAddHTML(t);n&&(t.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[e,t]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),n=e>0&&t>0?e/t:1;return{width:e,height:t,aspect:n}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(e){let t=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let n=t-this._lastFrameTime;n>0&&this.frameRate.addTime(n)}this._lastFrameTime=t,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let e=this.device.commandEncoder._gpuTimeMs;e!==void 0&&(this.gpuTime.addTime(e),this.device.commandEncoder._gpuTimeMs=void 0)}_updateSharedStats(){if(this.stats!==this.sharedStats){for(let e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{let t=this.sharedStats.get(e.name,e.type);t.sampleSize=e.sampleSize,t.time=e.time,t.count=e.count,t.samples=e.samples,t.lastTiming=e.lastTiming,t.lastSampleTime=e.lastSampleTime,t.lastSampleCount=e.lastSampleCount,t._count=e._count,t._time=e._time,t._samples=e._samples,t._startTime=e._startTime,t._timerPending=e._timerPending})}}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(e){e instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[e.offsetX,e.offsetY])}_onMouseleave(e){this._getAnimationProps()._mousePosition=null}};var dr=L(R(),1);function fr(i,e){let t=null,n=e?.device||dr.luma.createDevice({id:"animation-loop",adapters:e?.adapters,createCanvasContext:!0}),r=new ke({...e,device:n,async onInitialize(o){uo(o.animationLoop.device);try{return t=new i(o),await t?.onInitialize(o)}catch(a){console.error(a),t=null;let c=a instanceof Error?a:new Error(String(a));return ho(o.animationLoop.device,c),o.animationLoop.reportError(c),o.animationLoop.stop(),null}},onRender(o){let a=t?.onRender(o),c=e?.onAfterRender?.(o,t);return e?.onAfterRender?a!==!1||c!==!1:a},onFinalize(o){try{t?.onFinalize(o)}finally{t=null}}}),s=r;return s.getAnimationLoopTemplate=()=>t,r.getInfo=()=>this.AnimationLoopTemplateCtor.info,s}function ho(i,e){if(!i)return;let t=i.getDefaultCanvasContext().canvas;if(t instanceof HTMLCanvasElement){t.style.overflow="visible";let n=document.getElementById("animation-loop-error");n?.remove(),n=document.createElement("h1"),n.id="animation-loop-error",n.innerHTML=e.message,n.style.position="absolute",n.style.top="10px",n.style.left="10px",n.style.color="black",n.style.backgroundColor="red",t.parentElement?.appendChild(n)}}function uo(i){if(!i)return;let e=document.getElementById("animation-loop-error");e&&e.remove()}var lo={target:[0,0,0],distance:10,yaw:0,pitch:.25,roll:0,minDistance:1,maxDistance:100,minPitch:-Math.PI/2+.01,maxPitch:Math.PI/2-.01,rotateSpeed:.006,zoomSpeed:.001,enabled:!0,enableRotate:!1,enableZoom:!0,enablePan:!1,panSpeed:.0018,autoRotate:!1,autoRotateSpeed:.1},Vt=class{canvas;props;yaw;pitch;roll;distance;dragging=!1;activePointers=new Map;lastPointer=[0,0];previousPinchDistance=null;previousPinchAngle=null;previousTimeMilliseconds=null;previousCursor;previousTouchAction;constructor(e,t={}){this.canvas=e,this.props={...lo,...t},this.props.target=[...this.props.target],this.yaw=this.props.yaw,this.pitch=J(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.roll=this.props.roll,this.distance=J(this.props.distance,this.props.minDistance,this.props.maxDistance),this.previousCursor=e.style.cursor,this.previousTouchAction=e.style.touchAction,e.style.cursor="grab",e.style.touchAction="none",e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("pointerup",this.handlePointerUp),e.addEventListener("pointercancel",this.handlePointerUp),e.addEventListener("wheel",this.handleWheel,{passive:!1})}update(e){if(this.previousTimeMilliseconds!==null&&this.props.enabled&&this.props.autoRotate&&!this.dragging){let t=Math.min(Math.max(e-this.previousTimeMilliseconds,0)/1e3,.1);this.yaw+=this.props.autoRotateSpeed*t}this.previousTimeMilliseconds=e}getEyePosition(){let e=this.distance*Math.cos(this.pitch);return[this.props.target[0]+e*Math.sin(this.yaw),this.props.target[1]+this.distance*Math.sin(this.pitch),this.props.target[2]+e*Math.cos(this.yaw)]}getUpDirection(){return this.getCameraFrame().up}getCameraFrame(){let e=Math.sin(this.yaw),t=Math.cos(this.yaw),n=Math.sin(this.pitch),r=Math.cos(this.pitch),s=Math.sin(this.roll),o=Math.cos(this.roll),a=[t,0,-e],c=[-n*e,r,-n*t];return{right:[a[0]*o-c[0]*s,a[1]*o-c[1]*s,a[2]*o-c[2]*s],up:[c[0]*o+a[0]*s,c[1]*o+a[1]*s,c[2]*o+a[2]*s]}}setAutoRotate(e){this.props.autoRotate=e}setProps(e){Object.assign(this.props,e),e.enabled===!1&&this.dragging&&this.endPointerInteraction(),e.target&&(this.props.target=[...e.target]),e.yaw!==void 0&&(this.yaw=e.yaw),(e.pitch!==void 0||e.minPitch!==void 0||e.maxPitch!==void 0)&&(this.pitch=J(e.pitch??this.pitch,this.props.minPitch,this.props.maxPitch)),e.roll!==void 0&&(this.roll=e.roll),(e.distance!==void 0||e.minDistance!==void 0||e.maxDistance!==void 0)&&(this.distance=J(e.distance??this.distance,this.props.minDistance,this.props.maxDistance))}reset(){this.yaw=this.props.yaw,this.pitch=J(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.roll=this.props.roll,this.distance=J(this.props.distance,this.props.minDistance,this.props.maxDistance)}destroy(){this.canvas.removeEventListener("pointerdown",this.handlePointerDown),this.canvas.removeEventListener("pointermove",this.handlePointerMove),this.canvas.removeEventListener("pointerup",this.handlePointerUp),this.canvas.removeEventListener("pointercancel",this.handlePointerUp),this.canvas.removeEventListener("wheel",this.handleWheel),this.endPointerInteraction(),this.canvas.style.cursor=this.previousCursor,this.canvas.style.touchAction=this.previousTouchAction}handlePointerDown=e=>{if(!(!this.props.enabled||e.button!==0||this.activePointers.has(e.pointerId)||this.activePointers.size>=2||this.activePointers.size>0&&e.pointerType!=="touch")){if(this.activePointers.size===0&&this.props.onInteractionStart?.(),this.dragging=!0,this.activePointers.set(e.pointerId,[e.clientX,e.clientY]),this.activePointers.size===1)this.lastPointer=[e.clientX,e.clientY];else{let{center:t,distance:n,angle:r}=this.getMultiPointerState();this.lastPointer=t,this.previousPinchDistance=n,this.previousPinchAngle=n>0?r:null}this.canvas.setPointerCapture(e.pointerId),this.canvas.style.cursor="grabbing"}};handlePointerMove=e=>{if(!this.props.enabled||!this.dragging||!this.activePointers.has(e.pointerId))return;if(this.activePointers.set(e.pointerId,[e.clientX,e.clientY]),this.activePointers.size>1){let{center:r,distance:s,angle:o}=this.getMultiPointerState();this.props.enablePan&&this.panTarget(r[0]-this.lastPointer[0],r[1]-this.lastPointer[1]),this.props.enableZoom&&this.previousPinchDistance&&s>0&&(this.distance=J(this.distance*this.previousPinchDistance/s,this.props.minDistance,this.props.maxDistance)),this.props.enableRotate&&this.previousPinchAngle!==null&&s>0&&(this.roll+=fo(o-this.previousPinchAngle)),this.lastPointer=r,this.previousPinchDistance=s,this.previousPinchAngle=s>0?o:null;return}let t=e.clientX-this.lastPointer[0],n=e.clientY-this.lastPointer[1];this.lastPointer=[e.clientX,e.clientY],this.props.enablePan&&e.shiftKey?this.panTarget(t,n):(this.yaw-=t*this.props.rotateSpeed,this.pitch=J(this.pitch-n*(this.props.pitchSpeed??this.props.rotateSpeed),this.props.minPitch,this.props.maxPitch))};handlePointerUp=e=>{if(!this.activePointers.has(e.pointerId))return;this.canvas.hasPointerCapture(e.pointerId)&&this.canvas.releasePointerCapture(e.pointerId),this.activePointers.delete(e.pointerId),this.previousPinchDistance=null,this.previousPinchAngle=null;let t=this.activePointers.entries().next().value;if(t){this.lastPointer=t[1];return}this.endPointerInteraction()};endPointerInteraction(){this.dragging=!1;for(let e of this.activePointers.keys())this.canvas.hasPointerCapture(e)&&this.canvas.releasePointerCapture(e);this.activePointers.clear(),this.previousPinchDistance=null,this.previousPinchAngle=null,this.canvas.style.cursor="grab"}getMultiPointerState(){let[e,t]=this.activePointers.values(),n=t[0]-e[0],r=t[1]-e[1];return{center:[(e[0]+t[0])/2,(e[1]+t[1])/2],distance:Math.hypot(n,r),angle:Math.atan2(r,n)}}panTarget(e,t){let n=this.distance*this.props.panSpeed,{right:r,up:s}=this.getCameraFrame();this.props.target=[this.props.target[0]+(-r[0]*e+s[0]*t)*n,this.props.target[1]+(-r[1]*e+s[1]*t)*n,this.props.target[2]+(-r[2]*e+s[2]*t)*n]}handleWheel=e=>{if(!this.props.enabled||!this.props.enableZoom)return;e.preventDefault(),this.props.onInteractionStart?.();let t=J(e.deltaY,-240,240);this.distance=J(this.distance*Math.exp(t*this.props.zoomSpeed),this.props.minDistance,this.props.maxDistance)}};function J(i,e,t){return Math.min(Math.max(i,e),t)}function fo(i){return Math.atan2(Math.sin(i),Math.cos(i))}var S=L(R(),1),we=L(re(),1);var Bi=L(R(),1);var Di={};function z(i="id"){Di[i]=Di[i]||1;let e=Di[i]++;return`${i}-${e}`}var Ne=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||z("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&Bi.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function mr(i,e){if(e instanceof Ne)return e;let t=Ee(e),n=po(i,t),{attributes:r,bufferLayout:s}=mo(i,t);return new Ne({topology:t.topology||"triangle-list",bufferLayout:s,vertexCount:t.vertexCount,indices:n,attributes:r})}function po(i,e){if(!e.indices)return;let t=e.indices.value;return i.createBuffer({usage:Bi.Buffer.INDEX,data:t})}function mo(i,e){let t={};for(let[n,r]of Object.entries(e.attributes)){let s=e.bufferLayout?.find(o=>o.name===n)?.name||_e(n);r&&(t[s]=i.createBuffer({data:r.value,id:`${n}-buffer`}))}return{attributes:t,bufferLayout:e.bufferLayout||Ti(e.attributes),vertexCount:e.vertexCount}}function gr(i,e){let t={},n="Values";if(i.attributes.length===0&&!i.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let r of i.attributes)if(r){let s=`${r.location} ${r.name}: ${r.type}`;t[`in ${s}`]={[n]:r.stepMode||"vertex"}}for(let r of i.varyings||[]){let s=`${r.location} ${r.name}`;t[`out ${s}`]={[n]:JSON.stringify(r)}}return t}var xr="__debugFramebufferState";function br(i,e,t){if(i.device.type!=="webgl")return;let n=yo(i.device);if(!n.flushing){if(_o(i)){go(i,t,n);return}e&&bo(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function go(i,e,t){if(t.queuedFramebuffers.length===0)return;let n=i.device,{gl:r}=n,s=r.getParameter(36010),o=r.getParameter(36006),[a,c]=i.device.getDefaultCanvasContext().getDrawingBufferSize(),h=yr(e.top,8),u=yr(e.left,8);t.flushing=!0;try{for(let l of t.queuedFramebuffers){let[d,f,p,b,g]=xo({framebuffer:l,targetWidth:a,targetHeight:c,topPx:h,leftPx:u,minimap:e.minimap});r.bindFramebuffer(36008,l.handle),r.bindFramebuffer(36009,null),r.blitFramebuffer(0,0,l.width,l.height,d,f,p,b,16384,9728),h+=g+8}}finally{r.bindFramebuffer(36008,s),r.bindFramebuffer(36009,o),t.flushing=!1}}function xo(i){let{framebuffer:e,targetWidth:t,targetHeight:n,topPx:r,leftPx:s,minimap:o}=i,a=o?Math.max(Math.floor(t/4),1):t,c=o?Math.max(Math.floor(n/4),1):n,h=Math.min(a/e.width,c/e.height),u=Math.max(Math.floor(e.width*h),1),l=Math.max(Math.floor(e.height*h),1),d=s,f=Math.max(n-r-l,0),p=d+u,b=f+l;return[d,f,p,b,l]}function yo(i){return i.userData[xr]||={flushing:!1,queuedFramebuffers:[]},i.userData[xr]}function bo(i){return"colorAttachments"in i}function _o(i){let e=i.props.framebuffer;return!e||e.handle===null}function yr(i,e){if(!i)return e;let t=Number.parseInt(i,10);return Number.isFinite(t)?t:e}function Fe(i,e,t){if(i===e)return!0;if(!t||!i||!e)return!1;if(Array.isArray(i)){if(!Array.isArray(e)||i.length!==e.length)return!1;for(let n=0;n<i.length;n++)if(!Fe(i[n],e[n],t-1))return!1;return!0}if(Array.isArray(e))return!1;if(typeof i=="object"&&typeof e=="object"){let n=Object.keys(i),r=Object.keys(e);if(n.length!==r.length)return!1;for(let s of n)if(!e.hasOwnProperty(s)||!Fe(i[s],e[s],t-1))return!1;return!0}return!1}var _r=L(R(),1),De=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return(0,_r.getBufferLayoutAttributeNames)(e)}mergeBufferLayouts(e,t){let n=[...e];for(let r of t){let s=n.findIndex(o=>o.name===r.name);s<0?n.push(r):n[s]=r}return n}};var pe=L(R(),1);function vr(i,e){let t=(0,pe.getShaderAttributeLocationMap)(i),n=e.slice();return n.sort((r,s)=>{let o=(0,pe.getMinimumAttributeLocation)((0,pe.getBufferLayoutAttributeNames)(r).map(c=>t[c])),a=(0,pe.getMinimumAttributeLocation)((0,pe.getBufferLayoutAttributeNames)(s).map(c=>t[c]));return o-a}),n}var Xt=L(re(),1);function Be(i,e){if(!i||!e.some(n=>n.bindingLayout?.length))return i;let t={...i,bindings:i.bindings.map(n=>({...n}))};"attributes"in(i||{})&&(t.attributes=i?.attributes||[]);for(let n of e)for(let r of n.bindingLayout||[])for(let s of vo(r.name)){let o=t.bindings.find(a=>a.name===s);o?.group===0&&(o.group=r.group),o&&r.visibility!==void 0&&(o.visibility=r.visibility)}return t}function Ir(i,e,t=[]){return i?e?{...i,attributes:i.attributes.length?wo(i.attributes,e.attributes.filter(n=>t.includes(n.name))):e.attributes,bindings:Mo(i.bindings,e.bindings)}:i:e}function Ie(i){return!!(i.uniformTypes&&!Io(i.uniformTypes))}function Mr(i){let e=[];for(let t of i){let n=(0,Xt.getShaderModuleUniformBlockName)(t),r=new Set([t.vs,t.fs].flatMap(o=>o?(0,Xt.getGLSLUniformBlocks)(o).filter(a=>a.isStd140).map(a=>a.blockName):[])),s=r.has(n)?n:r.size===1?r.values().next().value:void 0;Ie(t)&&s&&e.push({name:s,uniformTypes:t.uniformTypes})}return e}function Yt(i,e){let t=[],n=new Set;for(let r of[...i||[],...e||[]])n.has(r.name)||(n.add(r.name),t.push(r));return t}function vo(i){let e=new Set([i,`${i}Uniforms`]);return i.endsWith("Uniforms")||e.add(`${i}Sampler`),[...e]}function Io(i){for(let e in i)return!1;return!0}function Mo(i,e){let t=i.map(s=>({...s})),n=new Set(i.map(s=>s.name)),r=new Set(i.map(s=>`${s.group}:${s.location}`));for(let s of e){let o=`${s.group}:${s.location}`;!n.has(s.name)&&!r.has(o)&&t.push({...s})}return t}function wo(i,e){let t=i.map(s=>({...s})),n=new Map(i.map(s=>[s.name,s])),r=new Map(i.map(s=>[s.location,s]));for(let s of e){let o=n.get(s.name);if(o){if(o.type!==s.type||o.location!==s.location)throw new Error(`Shader attribute "${s.name}" conflicts with its inferred type or location`);continue}let a=r.get(s.location);if(a)throw new Error(`Shader attributes "${a.name}" and "${s.name}" both use location ${s.location}`);t.push({...s})}return t}var Wt=L(R(),1),zi=L(re(),1);function wr(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Tr(i){return Array.isArray(i)?i.length===0||typeof i[0]=="number":!1}function rt(i){return wr(i)||Tr(i)}function To(i){return rt(i)||typeof i=="number"||typeof i=="boolean"}function Ar(i,e={}){let t={bindings:{},uniforms:{}};return Object.keys(i).forEach(n=>{let r=i[n];Object.prototype.hasOwnProperty.call(e,n)||To(r)?t.uniforms[n]=r:t.bindings[n]=r}),t}var X=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;directBindings={};constructor(e,t){Object.assign(this.options,t);let n=(0,zi.getShaderModuleDependencies)(Object.values(e).filter(Ao));for(let r of n)e[r.name]=r;Wt.log.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[r,s]of Object.entries(e))s&&(this._addModule(s),s.name&&r!==s.name&&!this.options.disableWarnings&&Wt.log.warn(`Module name: ${r} vs ${s.name}`)())}destroy(){}setProps(e){e.bindings&&Object.assign(this.directBindings,e.bindings);for(let t of Object.keys(e)){if(t==="bindings")continue;let n=t,r=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||Wt.log.warn(`Module ${t} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(r,o)||r,{uniforms:h,bindings:u}=Ar(c,s.uniformTypes);this.moduleUniforms[n]=Pr(o,h,s.uniformTypes),this.moduleBindings[n]={...a,...u}}}}getModules(){return Object.values(this.modules)}addModules(e){let t=(0,zi.getShaderModuleDependencies)(e);for(let n of t){let r=n.name;this.modules[r]||(this.modules[r]=n,this._addModule(n))}}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let t of Object.values(this.moduleBindings))Object.assign(e,t);return Object.assign(e,this.directBindings),e}getModuleBindingValues(e){let t=this.moduleBindings[e];return t?{...t}:{}}getDebugTable(){let e={};for(let[t,n]of Object.entries(this.moduleUniforms))for(let[r,s]of Object.entries(n))e[`${t}.${r}`]={type:this.modules[t].uniformTypes?.[r],value:String(s)};return e}_addModule(e){let t=e.name;this.moduleUniforms[t]=Pr({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[t]={}}};function Pr(i={},e={},t={}){let n={...i};for(let[r,s]of Object.entries(e))s!==void 0&&(n[r]=ji(i[r],s,t[r]));return n}function ji(i,e,t){if(!t||typeof t=="string")return st(e);if(Array.isArray(t)){if(Gi(e)||!Array.isArray(e))return st(e);let o=Array.isArray(i)&&!Gi(i)?[...i]:[],a=o.slice();for(let c=0;c<e.length;c++){let h=e[c];h!==void 0&&(a[c]=ji(o[c],h,t[0]))}return a}if(!Ui(e))return st(e);let n=t,r=Ui(i)?i:{},s={...r};for(let[o,a]of Object.entries(e))a!==void 0&&(s[o]=ji(r[o],a,n[o]));return s}function st(i){return ArrayBuffer.isView(i)?Array.prototype.slice.call(i):Array.isArray(i)?Gi(i)?i.slice():i.map(t=>t===void 0?void 0:st(t)):Ui(i)?Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t===void 0?void 0:st(t)])):i}function Gi(i){return ArrayBuffer.isView(i)||Array.isArray(i)&&(i.length===0||typeof i[0]=="number")}function Ui(i){return!!i&&typeof i=="object"&&!Array.isArray(i)&&!ArrayBuffer.isView(i)}function Ao(i){return!!i?.dependencies}var $i=L(R(),1);var Po=$i.Buffer.DEBUG_DATA_MAX_LENGTH,G=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:r,ownsBuffer:s=!0,...o}=t;if(r&&r.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(r&&(o.byteLength!==void 0||o.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||r?.id||z("dynamic-buffer"),c={...o,id:a,usage:o.usage??r?.usage,indexType:o.indexType??r?.indexType};(c.usage||0)&$i.Buffer.INDEX&&!c.indexType&&(o.data instanceof Uint32Array?c.indexType="uint32":o.data instanceof Uint16Array?c.indexType="uint16":o.data instanceof Uint8Array&&(c.indexType="uint8")),delete c.data,delete c.byteOffset,this.device=e,this.id=a,this.props=c,this.usage=c.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:Po,this._ownsBuffer=s,this._buffer=r??this.device.createBuffer({...o,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),o.data&&this._writeDebugData(o.data,o.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let r=null;await this._buffer.mapAndWriteAsync(async(s,o)=>{await e(s,o),r=new Uint8Array(s.slice(0,n))},t,n),this._touch(),r&&this._writeDebugData(r,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let r=null,s=await this._buffer.mapAndReadAsync(async(o,a)=>(r=new Uint8Array(o.slice(0)),await e(o,a)),t,n);return r&&this._writeDebugData(r,t)&&this._touch(),s}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let r=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),s=this._buffer,o=this.debugData.slice(0),{data:a,byteOffset:c,...h}=this.props,u=this.device.createBuffer({...h,byteLength:t});return n&&r>0&&this._copyBufferContents(s,u,r),this._buffer=u,this._resetDebugData(t),n&&o.byteLength>0&&this._writeDebugData(o,0),this._ownsBuffer&&s.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let r=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,s=this.device.createCommandEncoder();s.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:r}),this.device.submit(s.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=new Uint8Array(this.debugData),s=Math.min(n.byteLength,r.byteLength-t);return r.set(n.subarray(0,s),t),s>0}};function Me(i){return i!==null&&typeof i=="object"&&"buffer"in i}function Sr(i){return i instanceof G?i:Me(i)&&i.buffer instanceof G?i.buffer:null}function So(i){return i instanceof G?i.buffer:i}function Ht(i){return{buffer:So(i.buffer),offset:i.offset,size:i.size}}var Cr=L(R(),1);function se(i){return i!==null&&typeof i=="object"&&"resolveTextureBinding"in i&&typeof i.resolveTextureBinding=="function"}function Co(i){return i?.type==="texture"||i?.type==="external-texture"}function qt(i,e,t){let n=(0,Cr.getShaderLayoutBinding)(i,e,{ignoreWarnings:!0});return Co(n)?n:i.bindings.length===0&&t?.fallbackGroup!==void 0?{type:"texture",name:e,group:t.fallbackGroup,location:0}:null}var ee=2,Eo=1e4,Vi="render pipeline initialization failed",Lo=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],W=class i{static async createAsync(e,t){let n=!S.PipelineFactory.getAsyncCompilation(e),r=n?S.PipelineFactory.beginAsyncCompilation(e):S.PipelineFactory.getAsyncCompilation(e),s;try{s=new i(e,t)}finally{n&&S.PipelineFactory.endAsyncCompilation(e,r)}try{return n?await Promise.all(r):await s._pipelineInitialization,s}catch(o){throw s.destroy(),o}}static defaultProps={...S.RenderPipeline.defaultProps,source:void 0,sourceLanguage:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],geometry:null,indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,material:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:we.ShaderAssembler.getDefaultShaderAssembler("glsl"),debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;material=null;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_vertexCountSet=!1;_lastDrawTimestamp=-1;_bindingTable=[];_pipelineInitialization;get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(e,t){let n=i.defaultProps.shaderAssembler,r=Object.hasOwn(t,"vertexCount");this.props={...i.defaultProps,...t,shaderAssembler:t.shaderAssembler??(Xi(n,e.info.shadingLanguage)?n:we.ShaderAssembler.getDefaultShaderAssembler(e.info.shadingLanguage))},this._vertexCountSet=r,t=this.props,this.id=t.id||z("model"),this.device=e,Object.assign(this.userData,t.userData),this.material=t.material||null;let s=Fo(e),o=(0,we.resolveShaderPlugins)(this.props.plugins,s.shaderLanguage),a=(0,we.mergeShaderPluginModules)(this.props.modules,o.modules),c=Object.fromEntries(a.map(p=>[p.name,p])),h=t.shaderInputs||new X(c,{disableWarnings:this.props.disableWarnings});t.shaderInputs&&o.modules.length>0&&h.addModules(o.modules),this.setShaderInputs(h);let u=Yt(this.props.modules,h.getModules()),l={...o.defines,...this.props.defines};if(this.device.type==="webgl"&&(this.props._uniformBlockLayouts=Mr(u)),this.props.shaderLayout=Be(this.props.shaderLayout,u)||null,this.device.type==="webgpu"&&this.props.source){let p=this.props.shaderAssembler;(0,S.assert)(Xi(p,"wgsl"));let{source:b,getUniforms:g,bindingTable:_,entryPoints:v={},shaderLayout:y}=p.assembleWGSLShader({platformInfo:s,...this.props,modules:u,defines:l,pluginInjections:o.injections,pluginVertexInputs:o.vertexInputs,pluginVaryings:o.varyings});this.source=b,this.props.vertexEntryPoint=v.vertex||this.props.vertexEntryPoint,this.props.fragmentEntryPoint=v.fragment||this.props.fragmentEntryPoint,this._getModuleUniforms=g,this._bindingTable=_;let I=y??e.getShaderLayout?.(this.source),m=Oo(I,o.vertexInputs),x=Ir(this.props.shaderLayout,m,Object.keys(o.vertexInputs));this.props.shaderLayout=Be(x||null,u)||null}else{let p=this.props.shaderAssembler;(0,S.assert)(Xi(p,"glsl"));let{vs:b,fs:g,getUniforms:_}=p.assembleGLSLShaderPair({platformInfo:s,...this.props,modules:u,defines:l,pluginInjections:o.injections,pluginVertexInputs:o.vertexInputs,pluginVaryings:o.varyings});this.vs=b,this.fs=g,this._getModuleUniforms=_,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,t.geometry&&this.setGeometry(t.geometry),this.pipelineFactory=t.pipelineFactory||S.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||S.ShaderFactory.getDefaultShaderFactory(this.device);let f=S.PipelineFactory.getAsyncCompilation(this.device);f?(this._pipelineInitialization=this._initializePipelineAsync(t),f.push(this._pipelineInitialization)):(this.pipeline=this._updatePipeline(),this._initializePipelineResources(t))}async _initializePipelineAsync(e){await this._updatePipelineAsync(),this._initializePipelineResources(e)}_initializePipelineResources(e){this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in e&&(this.isInstanced=e.isInstanced),e.instanceCount&&this.setInstanceCount(e.instanceCount),e.vertexCount&&this.setVertexCount(e.vertexCount),e.indexBuffer&&this.setIndexBuffer(e.indexBuffer),e.attributes&&this.setAttributes(e.attributes),e.constantAttributes&&this.setConstantAttributes(e.constantAttributes),e.bindings&&this.setBindings(e.bindings),e.transformFeedback&&(this.transformFeedback=e.transformFeedback)}destroy(){this._destroyed||(this.pipeline&&(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs)),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.material?.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e){if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return S.log.info(ee,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;let t=this._areBindingsLoading();if(t)return S.log.info(ee,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),this.device.type==="webgpu"?(this.updateShaderInputs(),this.material?.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}finally{e.popDebugGroup()}let n,r=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),r=this.pipeline.isErrored,r)S.log.info(ee,`>>> DRAWING ABORTED ${this.id}: ${Vi}`)(),n=!1;else{let s=this.vertexArray.getDrawValidationError();if(s)S.log.info(ee,`>>> DRAWING ABORTED ${this.id}: ${s}`)(),this._drawBlockedReason=s,n=!1;else{let o=this._getCurrentShaderLayout(),a=this._getBindings(o),c=this._getBindGroups(o,a),{indexBuffer:h}=this.vertexArray,u=h?this.indexCount??(this._vertexCountSet?this.vertexCount:h.byteLength/(h.indexType==="uint32"?4:2)):void 0;e.setPipeline(this.pipeline),e.setBindings(c,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=this.isInstanced===!0&&this.instanceCount===0?!0:e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:u,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):r?(this._needsRedraw=Vi,this._drawBlockedReason=Vi):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){this._gpuGeometry?.destroy();let t=e&&mr(this.device,e);if(t){this.setTopology(t.topology||"triangle-list");let n=new De(this.bufferLayout);this.bufferLayout=n.mergeBufferLayouts(t.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(t)}this._gpuGeometry=t}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){let t=new De(this.bufferLayout),n=this._gpuGeometry?t.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e;Fe(n,this.bufferLayout,-1)||(this.bufferLayout=n,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry))}setParameters(e){Fe(e,this.parameters,2)||(this.parameters=e,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this._vertexCountSet=!0,this.setNeedsRedraw("vertexCount")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new S.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(Ie(n)&&!this.material?.ownsModule(t)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())),this.setNeedsRedraw("shaderInputs")}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){let t=e instanceof G?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof G?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){this._drawBlockedReason=!1;let n=t?.disableWarnings??this.props.disableWarnings;e.indices&&S.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=vr(this.pipeline.shaderLayout,this.bufferLayout);let r=new De(this.bufferLayout);for(let[s,o]of Object.entries(e)){let a=o instanceof G?o.buffer:o,c=r.getBufferLayout(s);if(!c){n||S.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let h=r.getAttributeNamesForBuffer(c),u=!1;for(let l of h){let d=this._attributeInfos[l];if(d){let f=this.device.type==="webgpu"?this.vertexArray.getBufferSlot(d.bufferName):d.location;if(f===null){n||S.log.warn(`Model(${this.id}): Missing vertex array slot for buffer "${d.bufferName}".`)();continue}let p=t?.byteOffsets?.[s]??0;this.vertexArray.setBuffer(f,a,p),o instanceof G?this._dynamicAttributeBufferSources[f]={source:o,generation:o.generation,byteOffset:p}:delete this._dynamicAttributeBufferSources[f],u=!0}}!u&&!n&&S.log.warn(`Model(${this.id}): Ignoring buffer "${a.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(let[n,r]of Object.entries(e)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,r):(t?.disableWarnings??this.props.disableWarnings)||S.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(se(e)&&!e.isReady)return e.id;for(let e of Object.values(this.material?.bindings||{}))if(se(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){let t={};for(let[n,r]of Object.entries(this.bindings)){let s=Ro(n,r,e);s&&(t[n]=s)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){let n=e.bindings.length?(0,S.normalizeBindingsByGroup)(e,t):{0:t};if(!this.material)return n;for(let[r,s]of Object.entries(this.material.getBindingsByGroup(e))){let o=Number(r);n[o]={...n[o]||{},...s}}return n}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(let t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(let t of Object.values(this.bindings))t instanceof S.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof S.Buffer||t instanceof S.Texture||t instanceof S.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):se(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:Me(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){let t={...e.attributes};for(let[n]of Object.entries(t))!this.pipeline.shaderLayout.attributes.find(r=>r.name===n)&&n!=="positions"&&delete t[n];this.vertexCount=e.vertexCount,this._vertexCountSet=!0,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(t,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){let e=this._preparePipelineUpdate();return e&&(this.pipeline=this.pipelineFactory.createRenderPipeline(e.props),this._finishPipelineUpdate(e)),this.pipeline}async _updatePipelineAsync(){let e=this._preparePipelineUpdate();if(e){try{this.pipeline=await this.pipelineFactory.createRenderPipelineAsync(e.props)}catch(t){throw this._releasePipelineShaders(e.vertexShader,e.fragmentShader),this._pipelineNeedsUpdate="asynchronous pipeline creation failed",t}this._finishPipelineUpdate(e)}return this.pipeline}_preparePipelineUpdate(){if(!this._pipelineNeedsUpdate)return null;let e=this.pipeline?.vs??null,t=this.pipeline?.fs??null;this.pipeline&&S.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),this._pipelineNeedsUpdate=!1;let n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),r=null;return this.source?r=n:this.fs&&(r=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fs,debugShaders:this.props.debugShaders})),{props:{...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:r},vertexShader:n,fragmentShader:r,previousVertexShader:e,previousFragmentShader:t}}_finishPipelineUpdate(e){this._attributeInfos=(0,S.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),this._releasePipelineShaders(e.previousVertexShader,e.previousFragmentShader)}_releasePipelineShaders(e,t){e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=S.log.level>3?0:Eo;S.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,S.log.group(ee,`>>> DRAWING MODEL ${this.id}`,{collapsed:S.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=gr(this.pipeline.shaderLayout,this.id);S.log.table(ee,e)();let t=this.shaderInputs.getDebugTable();S.log.table(ee,t)();let n=this._getAttributeDebugTable();S.log.table(ee,this._attributeInfos)(),S.log.table(ee,n)(),S.log.groupEnd(ee)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;let n=e.props.framebuffer;br(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[t,n]of Object.entries(this._attributeInfos)){let r=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:r?this._getBufferOrConstantValues(r,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:t}=this.vertexArray,n=t.indexType==="uint32"?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){let n=S.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof S.Buffer?new n(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;let t={};for(let[n,r]of Object.entries(e))this.material.ownsBinding(n)||(t[n]=r);return t}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){let e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(let[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer,t.byteOffset),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if(this.device.type!=="webgpu")return;let t=e.framebuffer||e.props.framebuffer,n=e.props,r=n.colorAttachmentFormats??t?.colorAttachments?.map(o=>ko(o?.texture?.format)),s=n.depthStencilAttachmentFormat===!1?void 0:n.depthStencilAttachmentFormat??No(t?.depthStencilAttachment?.texture?.format);(!Fe(this._colorAttachmentFormats,r,1)||this._depthStencilAttachmentFormat!==s)&&(this._colorAttachmentFormats=r,this._depthStencilAttachmentFormat=s,this._setPipelineNeedsUpdate("attachment formats"))}};function Xi(i,e){return i.shaderLanguage!==void 0&&i.shaderLanguage!==e?!1:e==="glsl"?"assembleGLSLShaderPair"in i&&typeof i.assembleGLSLShaderPair=="function":"assembleWGSLShader"in i&&typeof i.assembleWGSLShader=="function"}function Oo(i,e){return!i||Object.keys(e).length===0?i:{...i,attributes:i.attributes.map(t=>{let n=t.name.startsWith("_luma_")?t.name.slice(6):null;return n&&e[n]?{...t,name:n}:t})}}function Ro(i,e,t){if(se(e)){let n=qt(t,i,{fallbackGroup:0});return n?e.resolveTextureBinding(n):null}return e instanceof G?e.buffer:Me(e)?Ht(e):e}function ko(i){return i&&!Er(i)?i:null}function No(i){return i&&Er(i)?i:void 0}function Er(i){return Lo.includes(i)}function Fo(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}var te=L(R(),1);var je=3,ze=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(e,t={}){this.device=e,this.modules=t.modules||[];let n=new X(Object.fromEntries(this.modules.map(r=>[r.name,r])));this._materialBindingNames=Do(n),this._materialModuleNames=Bo(n)}createMaterial(e={}){return new Ge(this.device,{...e,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(e){if(this._materialBindingNames.has(e))return!0;let t=Yi(e);return t?this._materialModuleNames.has(t):!1}ownsModule(e){return this._materialModuleNames.has(e)}getBindingsByGroup(e){return Object.keys(e).length>0?{[je]:e}:{}}};function Yi(i){return i.endsWith("Uniforms")?i.slice(0,-8):null}function Do(i){let e=new Set;for(let t of Object.values(i.modules))for(let n of t.bindingLayout||[])n.group===je&&e.add(n.name);return e}function Bo(i){let e=new Set;for(let t of Object.values(i.modules))t.name&&t.bindingLayout?.some(n=>n.group===je&&n.name===t.name)&&e.add(t.name);return e}var Ge=class{id;device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};_dynamicResourceGenerations={};constructor(e,t={}){this.id=t.id||z("material"),this.device=e,this.factory=t.factory||new ze(e,{modules:t.modules||t.shaderInputs?.getModules()||[]});let n=Object.fromEntries((t.shaderInputs?.getModules()||this.factory.modules).map(r=>[r.name,r]));this.shaderInputs=t.shaderInputs||new X(n),this._uniformStore=new te.UniformStore(this.device,this.shaderInputs.modules);for(let[r,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(r)&&Ie(s)){let o=this._uniformStore.getManagedUniformBuffer(r);this.bindings[`${r}Uniforms`]=o}this.updateShaderInputs(),t.bindings&&this._replaceOwnedBindings(t.bindings)}destroy(){this._uniformStore.destroy()}clone(e={}){let t=this.factory.createMaterial({id:e.id,shaderInputs:e.shaderInputs,bindings:{...this.getResourceBindings(),...e.bindings}});return e.shaderInputs||t.setProps(this.shaderInputs.getUniformValues()),e.moduleProps&&t.setProps(e.moduleProps),t.updateShaderInputs(),t}ownsBinding(e){return this.factory.ownsBinding(e)}ownsModule(e){return this.factory.ownsModule(e)}setProps(e){this.shaderInputs.setProps(e)}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this._setOwnedBindings(this.shaderInputs.getBindingValues())&&(this._bindGroupCacheToken={})}getResourceBindings(){let e={};for(let[t,n]of Object.entries(this.bindings))Yi(t)||(e[t]=n);return e}getBindings(e={bindings:[]}){this._syncDynamicResourceGenerations();let t={},n=t;for(let[r,s]of Object.entries(this.bindings))if(se(s)){let o=qt(e,r,{fallbackGroup:je}),a=o?s.resolveTextureBinding(o):null;a&&(n[r]=a)}else s instanceof G?n[r]=s.buffer:Me(s)?n[r]=Ht(s):n[r]=s;return this._syncDynamicResourceGenerations(),t}getBindingsByGroup(e={bindings:[]}){return this.factory.getBindingsByGroup(this.getBindings(e))}getBindGroupCacheKey(e){return this._syncDynamicResourceGenerations(),e===je?this._bindGroupCacheToken:null}getBindingsUpdateTimestamp(){let e=0;for(let t of Object.values(this.bindings))t instanceof te.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof te.Buffer||t instanceof te.Texture||t instanceof te.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):se(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:Me(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return e}_replaceOwnedBindings(e){this._setOwnedBindings(e)&&(this._bindGroupCacheToken={})}_setOwnedBindings(e){let t=!1;for(let[n,r]of Object.entries(e))r!==void 0&&this.ownsBinding(n)&&this.bindings[n]!==r&&(this.bindings[n]=r,t=!0);return t}_syncDynamicResourceGenerations(){let e={},t=!1;for(let[n,r]of Object.entries(this.bindings)){let s=zo(r);s!==null&&(e[n]=s,this._dynamicResourceGenerations[n]!==s&&(t=!0))}Object.keys(e).length!==Object.keys(this._dynamicResourceGenerations).length&&(t=!0),this._dynamicResourceGenerations=e,t&&(this._bindGroupCacheToken={})}};function zo(i){return se(i)?i.generation:Sr(i)?.generation??null}var Lr=L(R(),1),Or=L(re(),1);var jo=35980,Go=35981,Kt=class i{device;model;transformFeedback;static defaultProps={...W.defaultProps,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,t=i.defaultProps){if(!i.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.model=new W(this.device,{id:t.id||"buffer-transform-model",fs:t.fs||(0,Or.getPassthroughFS)(),topology:t.topology||"point-list",varyings:t.outputs||t.varyings,...t,bufferMode:t.bufferMode||(t.feedbackBufferMode==="interleaved"?jo:Go)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:t.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){e?.inputBuffers&&this.model.setAttributes(e.inputBuffers),e?.outputBuffers&&this.transformFeedback.setBuffers(e.outputBuffers);let t=this.device.beginRenderPass({discard:!0,...e});this.model.draw(t),t.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof Lr.Buffer)return t.readAsync();let{buffer:n,byteOffset:r=0,byteLength:s=n.byteLength}=t;return n.readAsync(r,s)}};var Rr=L(re(),1);var Uo="transform_output",Zt=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(e,t){this.device=e,this.sampler=e.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new W(this.device,{id:t.id||z("texture-transform-model"),fs:t.fs||(0,Rr.getPassthroughFS)({input:t.targetTextureVarying,inputChannels:t.targetTextureChannels,output:Uo}),vertexCount:t.vertexCount,...t}),this._initialize(t),Object.seal(this)}destroy(){this.model.destroy();for(let e of this.bindings)e.framebuffer?.destroy()}delete(){this.destroy()}run(e){let{framebuffer:t}=this.bindings[this.currentIndex],n=this.device.beginRenderPass({framebuffer:t,...e});this.model.draw(n),n.end(),this.device.submit()}getTargetTexture(){let{targetTexture:e}=this.bindings[this.currentIndex];return e}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(e){this._updateBindings(e)}_updateBindings(e){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],e)}_updateBinding(e,{sourceBuffers:t,sourceTextures:n,targetTexture:r}){if(e||(e={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(e.sourceTextures,n),Object.assign(e.sourceBuffers,t),r){e.targetTexture=r;let{width:s,height:o}=r;e.framebuffer&&e.framebuffer.destroy(),e.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:s,height:o,colorAttachments:[r]}),e.framebuffer.resize({width:s,height:o})}return e}_setSourceTextureParameters(){let e=this.currentIndex,{sourceTextures:t}=this.bindings[e];for(let n in t)t[n].sampler=this.sampler}};var $o=`struct VertexInputs {
|
|
7
|
+
"use strict";var __exports__=(()=>{var iu=Object.create;var Sr=Object.defineProperty;var su=Object.getOwnPropertyDescriptor;var ou=Object.getOwnPropertyNames;var au=Object.getPrototypeOf,cu=Object.prototype.hasOwnProperty;var Ns=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},uu=(r,e)=>{for(var t in e)Sr(r,t,{get:e[t],enumerable:!0})},Pr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ou(e))!cu.call(r,i)&&i!==t&&Sr(r,i,{get:()=>e[i],enumerable:!(n=su(e,i))||n.enumerable});return r},Cr=(r,e,t)=>(Pr(r,e,"default"),t&&Pr(t,e,"default")),B=(r,e,t)=>(t=r!=null?iu(au(r)):{},Pr(e||!r||!r.__esModule?Sr(t,"default",{value:r,enumerable:!0}):t,r)),hu=r=>Pr(Sr({},"__esModule",{value:!0}),r);var D=Ns((Hd,zs)=>{zs.exports=globalThis.luma});var Ie=Ns((Em,sa)=>{sa.exports=globalThis.luma});var Ar={};uu(Ar,{AnimationAction:()=>Zt,AnimationClip:()=>Br,AnimationClipController:()=>lt,AnimationLoop:()=>_t,AnimationLoopTemplate:()=>Zr,AnimationMixer:()=>pt,AnimationTrack:()=>Lr,Animator:()=>dt,AreaLightController:()=>Hn,AsyncTexture:()=>qd,AudioController:()=>Zn,AudioGraph:()=>Yt,AudioReverbBus:()=>Xt,BackgroundTextureModel:()=>Nt,BillboardController:()=>Wn,BufferTransform:()=>vn,ClipSpace:()=>We,Computation:()=>$t,ConeGeometry:()=>He,CubeGeometry:()=>Mn,CylinderGeometry:()=>An,DirectionalLightModel:()=>En,DynamicBuffer:()=>G,DynamicTexture:()=>ce,GPUGeometry:()=>Bt,GPUVectorGeometry:()=>he,GPUVectorModel:()=>ue,Geometry:()=>z,GroupNode:()=>re,IcoSphereGeometry:()=>_n,Interactivity:()=>Yn,JointController:()=>ei,KeyFrames:()=>Kr,LegacyPickingManager:()=>Qn,Material:()=>kt,MaterialFactory:()=>Ot,MaterialVariants:()=>$n,MixerAnimationClip:()=>ni,Model:()=>qe,ModelNode:()=>Vt,OrbitControls:()=>en,PickingManager:()=>Gn,PlaneGeometry:()=>In,PointLightModel:()=>Sn,RingGeometry:()=>Jn,ScenegraphAnimator:()=>ri,ScenegraphNode:()=>Ee,ShaderInputs:()=>K,ShaderPassRenderer:()=>zn,SkinController:()=>jn,SphereGeometry:()=>zt,SpotLightModel:()=>Cn,Swap:()=>Ut,SwapBuffers:()=>Nn,SwapFramebuffers:()=>jt,TextureTransform:()=>Tn,Timeline:()=>Xr,TorusGeometry:()=>wn,TruncatedConeGeometry:()=>Gt,VideoTexture:()=>Fn,_resolveLoadFileUrl:()=>kn,applyMorphTargets:()=>ir,cancelAnimationFramePolyfill:()=>Jr,colorPicking:()=>Tr,createParametricAudioResponse:()=>Kn,createSkinJointPaletteResource:()=>zc,decodeMorphTargetAttribute:()=>_i,decomposePhysicsTransform:()=>_r,deformPositions:()=>nu,evaluateAnimationSampler:()=>Er,getGPUVectorModelBatches:()=>Ne,getIndexPickingModule:()=>Nc,getPlatformInfo:()=>Pt,getTextureTransformDeltaMatrix:()=>si,getTextureTransformMatrix:()=>ii,indexColorPicking:()=>Un,indexPicking:()=>wr,legacyColorPicking:()=>qc,loadImage:()=>vc,loadImageBitmap:()=>bc,makeAdapterAnimationBinding:()=>ru,makeAnimationLoop:()=>ia,makeEdgeGeometry:()=>Ts,makeEdgeGeometryFromGeometries:()=>cc,makeInterleavedGeometry:()=>wt,makeMaterialAnimationBinding:()=>Jc,makeNodeAnimationBinding:()=>Qc,makePropertyAnimationBinding:()=>tu,makeRandomGenerator:()=>mc,makeStrokeGeometry:()=>hc,makeTextureTransformAnimationBinding:()=>eu,picking:()=>Fc,publishedTransforms:()=>Kc,readPhysicsRotation:()=>Yc,readPhysicsVector:()=>Hc,requestAnimationFramePolyfill:()=>Qr,resolvePickingBackend:()=>kc,resolvePickingMode:()=>Vn,selectAudioEnvironmentZone:()=>Mr,setMorphWeights:()=>ti,setPathPrefix:()=>xc,simplifyMesh:()=>pc,supportsIndexPicking:()=>vr,transformPhysicsVector:()=>Xc,updateMorphTargetBuffers:()=>Hr,updateSkinJointMatrices:()=>Yr,validateGPUVectorBatchStructure:()=>Pe});Cr(Ar,B(D(),1));var Gs=B(D(),1),lt=class{name;playing=!0;speed=1;startTime=0;constructor(e={}){this.name=e.name||"unnamed",Object.assign(this,e)}setTime(e){if(!this.playing)return;let n=(e/1e3-this.startTime)*this.speed;this.applyTime(n)}},dt=class{clips;animations;constructor(e){this.clips=e,this.animations=e}animate(e){Gs.log.warn(`${this.constructor.name}#animate is deprecated. Use ${this.constructor.name}#setTime instead`)(),this.setTime(e)}setTime(e){this.clips.forEach(t=>t.setTime(e))}getAnimations(){return this.clips}};function Er(r,e,t="vector"){let{input:n,output:i,interpolation:s="LINEAR"}=e;if(!n.length||!i.length||!Number.isFinite(r))return null;let o=n.length-1;if(r<=n[0]||o===0)return oi(i,s,0,t);if(r>=n[o])return oi(i,s,o,t);let a=0,c=o;for(;c-a>1;){let p=Math.floor((a+c)/2);n[p]<=r?a=p:c=p}let u=n[a],l=n[c]-u;if(l<=0||s==="STEP")return oi(i,s,a,t);let d=(r-u)/l;switch(s){case"LINEAR":{let p=i[a],f=i[c];return!p||!f?null:t==="quaternion"?Rr(p,f,d):lu(p,f,d)}case"CUBICSPLINE":{let p=i[a*3+1],f=i[a*3+2],m=i[c*3],g=i[c*3+1];if(!p||!f||!m||!g)return null;let x=du(p,f,m,g,l,d);return t==="quaternion"?ft(x):x}default:return null}}function Rr(r,e,t){let n=ft(r),i=ft(e),s=n.reduce((l,d,p)=>l+d*i[p],0),o=s<0?-1:1;if(s=Math.min(Math.abs(s),1),s>.9995)return ft(n.map((l,d)=>l+t*(i[d]*o-l)));let a=Math.acos(s),c=Math.sin(a),u=Math.sin((1-t)*a)/c,h=Math.sin(t*a)/c*o;return ft(n.map((l,d)=>l*u+i[d]*h))}function oi(r,e,t,n){let i=r[e==="CUBICSPLINE"?t*3+1:t];return i?n==="quaternion"?ft(i):[...i]:null}function lu(r,e,t){return r.map((n,i)=>(1-t)*n+t*e[i])}function du(r,e,t,n,i,s){let o=s*s,a=o*s;return r.map((c,u)=>(2*a-3*o+1)*c+(a-2*o+s)*e[u]*i+(-2*a+3*o)*n[u]+(a-o)*t[u]*i)}function ft(r){let e=Math.hypot(...r);return e>0?r.map(t=>t/e):[0,0,0,1]}var Lr=class{name;times;values;interpolation;valueType;binding;constructor(e){this.name=e.name||e.binding.id||"unnamed",this.times=e.times,this.values=e.values,this.interpolation=e.interpolation||"LINEAR",this.valueType=e.valueType||"vector",this.binding=e.binding}get duration(){return this.times[this.times.length-1]||0}get sampler(){return{input:this.times,output:this.values,interpolation:this.interpolation}}evaluate(e){return Er(e,this.sampler,this.valueType)}};var Br=class{name;tracks;duration;constructor(e){this.name=e.name||"unnamed",this.tracks=e.tracks,this.duration=e.duration??Math.max(0,...e.tracks.map(t=>t.duration))}};var Zt=class{clip;mixer;time=0;timeScale;weight;loop;repetitions;paused=!1;playing=!1;elapsedTime=0;fade=null;constructor(e,t,n={}){this.mixer=e,this.clip=t,this.loop=n.loop||"repeat",this.repetitions=n.repetitions??Number.POSITIVE_INFINITY,this.timeScale=n.timeScale??1,this.weight=n.weight??1}play(){return this.playing=!0,this.paused=!1,this}pause(){return this.paused=!0,this}resume(){return this.playing=!0,this.paused=!1,this}stop(){return this.playing=!1,this.paused=!1,this.fade=null,this.reset()}reset(){return this.elapsedTime=0,this.time=0,this}setTime(e){return this.elapsedTime=e,this.time=this.resolveLocalTime(e),this}setLoop(e,t=Number.POSITIVE_INFINITY){return this.loop=e,this.repetitions=t,this.time=this.resolveLocalTime(this.elapsedTime),this}setEffectiveWeight(e){return this.weight=Math.max(0,e),this.fade=null,this}setEffectiveTimeScale(e){return this.timeScale=e,this}fadeIn(e){return this.scheduleFade(1,e)}fadeOut(e){return this.scheduleFade(0,e)}crossFadeTo(e,t){return e.weight=0,e.play().fadeIn(t),this.fadeOut(t)}crossFadeFrom(e,t){return e.crossFadeTo(this,t),this}advance(e){!this.playing||this.paused||(this.advanceFade(Math.abs(e)),this.elapsedTime+=e*this.timeScale,this.time=this.resolveLocalTime(this.elapsedTime),this.hasFinished()&&(this.playing=!1))}get shouldApply(){return(this.playing||this.hasFinished())&&this.weight>0}scheduleFade(e,t){return t<=0?(this.weight=e,this.fade=null,this):(this.fade={duration:t,elapsedTime:0,startWeight:this.weight,endWeight:e},this)}advanceFade(e){if(!this.fade)return;this.fade.elapsedTime+=e;let t=Math.min(this.fade.elapsedTime/this.fade.duration,1);this.weight=this.fade.startWeight+(this.fade.endWeight-this.fade.startWeight)*t,t===1&&(this.fade=null)}hasFinished(){let e=this.clip.duration;return e<=0?this.loop==="once":this.loop==="once"?this.elapsedTime>=e||this.elapsedTime<0:Number.isFinite(this.repetitions)&&Math.abs(this.elapsedTime)>=e*this.repetitions}resolveLocalTime(e){let t=this.clip.duration;if(t<=0)return 0;if(this.loop==="once")return Math.min(Math.max(e,0),t);if(Number.isFinite(this.repetitions)&&Math.abs(e)>=t*this.repetitions)return this.loop==="ping-pong"&&this.repetitions%2===0||e<0?0:t;let n=e>=0&&e<t?e:(e%t+t)%t;if(this.loop==="repeat")return n;let i=Math.floor(e/t);return Math.abs(i%2)===0?n:t-n}},pt=class{time=0;timeScale=1;clips=new Map;actions=new Map;initialValues=new Map;constructor(e=[]){e.forEach(t=>this.addClip(t))}addClip(e){return this.clips.set(e.name,e),this}clipAction(e,t){let n=typeof e=="string"?this.clips.get(e):e;if(!n)throw new Error(`Unknown animation clip: ${e}`);this.addClip(n);let i=this.actions.get(n);return i||(i=new Zt(this,n,t),this.actions.set(n,i)),i}getAction(e){let t=this.clips.get(e);return t?this.actions.get(t):void 0}update(e){return this.advance(e),this.applyValues(),this}advance(e){let t=e*this.timeScale;return this.time+=t,this.actions.forEach(n=>n.advance(t)),this}setTime(e){return this.time=e,this.actions.forEach(t=>{t.paused||t.setTime(e*t.timeScale)}),this.applyValues(),this}stopAllAction(){return this.actions.forEach(e=>e.stop()),this}applyValues(){let e=new Map;this.actions.forEach(t=>{!t.shouldApply&&!(t.playing&&t.weight===0)||t.clip.tracks.forEach(n=>{let i=n.evaluate(t.time);if(!i)return;let s=n.binding.id||n.binding;if(!this.initialValues.has(s)){let u=n.binding.getValue?.();u&&this.initialValues.set(s,[...u])}if(t.weight===0&&!this.initialValues.has(s))return;let o=e.get(s);if(!o){e.set(s,{binding:n.binding,value:[...i],valueType:n.valueType,weight:t.weight});return}if(t.weight===0)return;let a=o.weight+t.weight,c=t.weight/a;o.value=n.valueType==="quaternion"?Rr(o.value,i,c):o.value.map((u,h)=>u+(i[h]-u)*c),o.weight=a})}),e.forEach(({binding:t,value:n,valueType:i,weight:s},o)=>{let a=s<1?this.initialValues.get(o):void 0;a&&a.length===n.length&&(n=i==="quaternion"?Rr(a,n,s):n.map((c,u)=>a[u]+(c-a[u])*s)),t.setValue(n)})}};var fu=0,j=class{constructor(e){this.userData={},this.id=e.id||`geometry-${++fu}`,this.topology=e.topology,this.attributes={};let t=e.indices?Vs(e.indices):void 0;for(let[n,i]of Object.entries(e.attributes||{})){let s=Vs(i);if((n==="POSITION"||n==="positions")&&(s.size||(s.size=3)),n==="indices"){if(t)throw new Error("Geometry has multiple index attributes");t=s}else this.attributes[n]=s}if(t){if(!(t.value instanceof Uint16Array||t.value instanceof Uint32Array))throw new Error("Geometry indices must be a Uint16Array or Uint32Array");t.size=1,this.indices=t,pu(t,this.attributes)}if(this.vertexCount=e.vertexCount??mu(this.attributes,this.indices),!Number.isInteger(this.vertexCount)||this.vertexCount<0)throw new Error("Geometry vertexCount must be a non-negative integer")}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}};function Vs(r){let e=Us(r)?{value:r}:{...r};if(!Us(e.value))throw new Error("Geometry attributes must contain a typed-array value");if(e.size!==void 0&&(!Number.isInteger(e.size)||e.size<1))throw new Error("Geometry attribute size must be a positive integer");if(e.size&&e.value.length%e.size!==0)throw new Error("Geometry attribute length must be divisible by its size");return e}function Us(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function pu(r,e){let t=-1;for(let n of r.value)t=Math.max(t,Number(n));for(let[n,i]of Object.entries(e))if(!i.constant&&i.size){let s=i.value.length/i.size;if(t>=s)throw new Error(`Geometry index ${t} exceeds ${n} vertex count ${s}`)}}function mu(r,e){if(e)return e.value.length;let t=1/0;for(let n of Object.values(r))!n.constant&&n.size&&(t=Math.min(t,n.value.length/n.size));if(!Number.isFinite(t))throw new Error("Geometry has no countable attributes");return t}var rf=1/Math.PI*180,nf=1/180*Math.PI,gu={EPSILON:1e-12,debug:!1,precision:4,printTypes:!1,printDegrees:!1,printRowMajor:!0,_cartographicRadians:!1};globalThis.mathgl=globalThis.mathgl||{config:{...gu}};var W=globalThis.mathgl.config;function js(r,{precision:e=W.precision}={}){return r=yu(r),`${parseFloat(r.toPrecision(e))}`}function mt(r){return Array.isArray(r)||ArrayBuffer.isView(r)&&!(r instanceof DataView)}function ai(r,e,t){let n=W.EPSILON;t&&(W.EPSILON=t);try{if(r===e)return!0;if(mt(r)&&mt(e)){if(r.length!==e.length)return!1;for(let i=0;i<r.length;++i)if(!ai(r[i],e[i]))return!1;return!0}return r&&r.equals?r.equals(e):e&&e.equals?e.equals(r):typeof r=="number"&&typeof e=="number"?Math.abs(r-e)<=W.EPSILON*Math.max(1,Math.abs(r),Math.abs(e)):!1}finally{W.EPSILON=n}}function yu(r){return Math.round(r/W.EPSILON)*W.EPSILON}var ke=class extends Array{clone(){return new this.constructor().copy(this)}fromArray(e,t=0){for(let n=0;n<this.ELEMENTS;++n)this[n]=e[n+t];return this.check()}toArray(e=[],t=0){for(let n=0;n<this.ELEMENTS;++n)e[t+n]=this[n];return e}toObject(e){return e}from(e){return Array.isArray(e)?this.copy(e):this.fromObject(e)}to(e){return e===this?this:mt(e)?this.toArray(e):this.toObject(e)}toTarget(e){return e?this.to(e):this}toString(){return this.formatString(W)}formatString(e){let t="";for(let n=0;n<this.ELEMENTS;++n)t+=(n>0?", ":"")+js(this[n],e);return`${e.printTypes?this.constructor.name:""}[${t}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(!ai(this[t],e[t]))return!1;return!0}exactEquals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(this[t]!==e[t])return!1;return!0}negate(){for(let e=0;e<this.ELEMENTS;++e)this[e]=-this[e];return this.check()}lerp(e,t,n){if(n===void 0)return this.lerp(this,e,t);for(let i=0;i<this.ELEMENTS;++i){let s=e[i],o=typeof t=="number"?t:t[i];this[i]=s+n*(o-s)}return this.check()}min(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.min(e[t],this[t]);return this.check()}max(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.max(e[t],this[t]);return this.check()}clamp(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e[n]),t[n]);return this.check()}add(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]+=t[n];return this.check()}subtract(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]-=t[n];return this.check()}scale(e){if(typeof e=="number")for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;else for(let t=0;t<this.ELEMENTS&&t<e.length;++t)this[t]*=e[t];return this.check()}multiplyByScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}check(){if(W.debug&&!this.validate())throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);return this}validate(){let e=this.length===this.ELEMENTS;for(let t=0;t<this.ELEMENTS;++t)e=e&&Number.isFinite(this[t]);return e}};function xu(r,e){if(r.length!==e)return!1;for(let t=0;t<r.length;++t)if(!Number.isFinite(r[t]))return!1;return!0}function V(r){if(!Number.isFinite(r))throw new Error(`Invalid number ${JSON.stringify(r)}`);return r}function gt(r,e,t=""){if(W.debug&&!xu(r,e))throw new Error(`math.gl: ${t} some fields set to invalid numbers'`);return r}var yt=class extends ke{toString(){let e="[";if(W.printRowMajor){e+="row-major:";for(let t=0;t<this.RANK;++t)for(let n=0;n<this.RANK;++n)e+=` ${this[n*this.RANK+t]}`}else{e+="column-major:";for(let t=0;t<this.ELEMENTS;++t)e+=` ${this[t]}`}return e+="]",e}getElementIndex(e,t){return t*this.RANK+e}getElement(e,t){return this[t*this.RANK+e]}setElement(e,t,n){return this[t*this.RANK+e]=V(n),this}getColumn(e,t=new Array(this.RANK).fill(-0)){let n=e*this.RANK;for(let i=0;i<this.RANK;++i)t[i]=this[n+i];return t}setColumn(e,t){let n=e*this.RANK;for(let i=0;i<this.RANK;++i)this[n+i]=t[i];return this}};function ci(r,e){if(!r)throw new Error(`math.gl assertion ${e}`)}var Or=class extends ke{get x(){return this[0]}set x(e){this[0]=V(e)}get y(){return this[1]}set y(e){this[1]=V(e)}len(){return Math.sqrt(this.lengthSquared())}magnitude(){return this.len()}lengthSquared(){let e=0;for(let t=0;t<this.ELEMENTS;++t)e+=this[t]*this[t];return e}magnitudeSquared(){return this.lengthSquared()}distance(e){return Math.sqrt(this.distanceSquared(e))}distanceSquared(e){let t=0;for(let n=0;n<this.ELEMENTS;++n){let i=this[n]-e[n];t+=i*i}return V(t)}dot(e){let t=0;for(let n=0;n<this.ELEMENTS;++n)t+=this[n]*e[n];return V(t)}normalize(){let e=this.magnitude();if(e!==0)for(let t=0;t<this.ELEMENTS;++t)this[t]/=e;return this.check()}multiply(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]*=t[n];return this.check()}divide(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]/=t[n];return this.check()}lengthSq(){return this.lengthSquared()}distanceTo(e){return this.distance(e)}distanceToSquared(e){return this.distanceSquared(e)}getComponent(e){return ci(e>=0&&e<this.ELEMENTS,"index is out of range"),V(this[e])}setComponent(e,t){return ci(e>=0&&e<this.ELEMENTS,"index is out of range"),this[e]=t,this.check()}addVectors(e,t){return this.copy(e).add(t)}subVectors(e,t){return this.copy(e).subtract(t)}multiplyVectors(e,t){return this.copy(e).multiply(t)}addScaledVector(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]+=e[n]*t;return this.check()}};var Dr=typeof Float32Array<"u"?Float32Array:Array;var bf=Math.PI/180;function $s(r,e,t){let n=e[0],i=e[1];return r[0]=t[0]*n+t[3]*i+t[6],r[1]=t[1]*n+t[4]*i+t[7],r}function qs(r,e,t){let n=e[0],i=e[1];return r[0]=t[0]*n+t[4]*i+t[12],r[1]=t[1]*n+t[5]*i+t[13],r}function Ws(r,e,t){let n=e[0],i=e[1],s=t[3]*n+t[7]*i||1;return r[0]=(t[0]*n+t[4]*i)/s,r[1]=(t[1]*n+t[5]*i)/s,r}function kr(r,e,t){let n=e[0],i=e[1],s=e[2],o=t[3]*n+t[7]*i+t[11]*s||1;return r[0]=(t[0]*n+t[4]*i+t[8]*s)/o,r[1]=(t[1]*n+t[5]*i+t[9]*s)/o,r[2]=(t[2]*n+t[6]*i+t[10]*s)/o,r}function Hs(r,e,t){let n=e[0],i=e[1];return r[0]=t[0]*n+t[2]*i,r[1]=t[1]*n+t[3]*i,r[2]=e[2],r}function Ys(r,e,t){let n=e[0],i=e[1],s=e[2];return r[0]=t[0]*n+t[3]*i+t[6]*s,r[1]=t[1]*n+t[4]*i+t[7]*s,r[2]=t[2]*n+t[5]*i+t[8]*s,r[3]=e[3],r}function Xs(){let r=new Dr(3);return Dr!==Float32Array&&(r[0]=0,r[1]=0,r[2]=0),r}function vu(r){let e=r[0],t=r[1],n=r[2];return Math.sqrt(e*e+t*t+n*n)}function ui(r,e,t){let n=new Dr(3);return n[0]=r,n[1]=e,n[2]=t,n}function Ks(r,e){let t=e[0],n=e[1],i=e[2],s=t*t+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),r[0]=e[0]*s,r[1]=e[1]*s,r[2]=e[2]*s,r}function hi(r,e){return r[0]*e[0]+r[1]*e[1]+r[2]*e[2]}function xt(r,e,t){let n=e[0],i=e[1],s=e[2],o=t[0],a=t[1],c=t[2];return r[0]=i*c-s*a,r[1]=s*o-n*c,r[2]=n*a-i*o,r}function Fr(r,e,t){let n=e[0],i=e[1],s=e[2],o=t[3]*n+t[7]*i+t[11]*s+t[15];return o=o||1,r[0]=(t[0]*n+t[4]*i+t[8]*s+t[12])/o,r[1]=(t[1]*n+t[5]*i+t[9]*s+t[13])/o,r[2]=(t[2]*n+t[6]*i+t[10]*s+t[14])/o,r}function Nr(r,e,t){let n=e[0],i=e[1],s=e[2];return r[0]=n*t[0]+i*t[3]+s*t[6],r[1]=n*t[1]+i*t[4]+s*t[7],r[2]=n*t[2]+i*t[5]+s*t[8],r}function Zs(r,e,t){let n=t[0],i=t[1],s=t[2],o=t[3],a=e[0],c=e[1],u=e[2],h=i*u-s*c,l=s*a-n*u,d=n*c-i*a,p=i*d-s*l,f=s*h-n*d,m=n*l-i*h,g=o*2;return h*=g,l*=g,d*=g,p*=2,f*=2,m*=2,r[0]=a+h+p,r[1]=c+l+f,r[2]=u+d+m,r}function Qs(r,e,t,n){let i=[],s=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),r[0]=s[0]+t[0],r[1]=s[1]+t[1],r[2]=s[2]+t[2],r}function Js(r,e,t,n){let i=[],s=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),r[0]=s[0]+t[0],r[1]=s[1]+t[1],r[2]=s[2]+t[2],r}function eo(r,e,t,n){let i=[],s=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],r[0]=s[0]+t[0],r[1]=s[1]+t[1],r[2]=s[2]+t[2],r}function to(r,e){let t=r[0],n=r[1],i=r[2],s=e[0],o=e[1],a=e[2],c=Math.sqrt((t*t+n*n+i*i)*(s*s+o*o+a*a)),u=c&&hi(r,e)/c;return Math.acos(Math.min(Math.max(u,-1),1))}var ro=vu;var li=[0,0,0],zr,R=class r extends Or{static get ZERO(){return zr||(zr=new r(0,0,0),Object.freeze(zr)),zr}constructor(e=0,t=0,n=0){super(-0,-0,-0),arguments.length===1&&mt(e)?this.copy(e):(W.debug&&(V(e),V(t),V(n)),this[0]=e,this[1]=t,this[2]=n)}set(e,t,n){return this[0]=e,this[1]=t,this[2]=n,this.check()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this.check()}fromObject(e){return W.debug&&(V(e.x),V(e.y),V(e.z)),this[0]=e.x,this[1]=e.y,this[2]=e.z,this.check()}toObject(e){return e.x=this[0],e.y=this[1],e.z=this[2],e}get ELEMENTS(){return 3}get z(){return this[2]}set z(e){this[2]=V(e)}angle(e){return to(this,e)}cross(e){return xt(this,this,e),this.check()}rotateX({radians:e,origin:t=li}){return Qs(this,this,t,e),this.check()}rotateY({radians:e,origin:t=li}){return Js(this,this,t,e),this.check()}rotateZ({radians:e,origin:t=li}){return eo(this,this,t,e),this.check()}transform(e){return this.transformAsPoint(e)}transformAsPoint(e){return Fr(this,this,e),this.check()}transformAsVector(e){return kr(this,this,e),this.check()}transformByMatrix3(e){return Nr(this,this,e),this.check()}transformByMatrix2(e){return Hs(this,this,e),this.check()}transformByQuaternion(e){return Zs(this,this,e),this.check()}};function no(r,e){if(r===e){let t=e[1],n=e[2],i=e[5];r[1]=e[3],r[2]=e[6],r[3]=t,r[5]=e[7],r[6]=n,r[7]=i}else r[0]=e[0],r[1]=e[3],r[2]=e[6],r[3]=e[1],r[4]=e[4],r[5]=e[7],r[6]=e[2],r[7]=e[5],r[8]=e[8];return r}function io(r,e){let t=e[0],n=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],u=e[7],h=e[8],l=h*o-a*u,d=-h*s+a*c,p=u*s-o*c,f=t*l+n*d+i*p;return f?(f=1/f,r[0]=l*f,r[1]=(-h*n+i*u)*f,r[2]=(a*n-i*o)*f,r[3]=d*f,r[4]=(h*t-i*c)*f,r[5]=(-a*t+i*s)*f,r[6]=p*f,r[7]=(-u*t+n*c)*f,r[8]=(o*t-n*s)*f,r):null}function so(r){let e=r[0],t=r[1],n=r[2],i=r[3],s=r[4],o=r[5],a=r[6],c=r[7],u=r[8];return e*(u*s-o*c)+t*(-u*i+o*a)+n*(c*i-s*a)}function di(r,e,t){let n=e[0],i=e[1],s=e[2],o=e[3],a=e[4],c=e[5],u=e[6],h=e[7],l=e[8],d=t[0],p=t[1],f=t[2],m=t[3],g=t[4],x=t[5],T=t[6],v=t[7],w=t[8];return r[0]=d*n+p*o+f*u,r[1]=d*i+p*a+f*h,r[2]=d*s+p*c+f*l,r[3]=m*n+g*o+x*u,r[4]=m*i+g*a+x*h,r[5]=m*s+g*c+x*l,r[6]=T*n+v*o+w*u,r[7]=T*i+v*a+w*h,r[8]=T*s+v*c+w*l,r}function oo(r,e,t){let n=e[0],i=e[1],s=e[2],o=e[3],a=e[4],c=e[5],u=e[6],h=e[7],l=e[8],d=t[0],p=t[1];return r[0]=n,r[1]=i,r[2]=s,r[3]=o,r[4]=a,r[5]=c,r[6]=d*n+p*o+u,r[7]=d*i+p*a+h,r[8]=d*s+p*c+l,r}function ao(r,e,t){let n=e[0],i=e[1],s=e[2],o=e[3],a=e[4],c=e[5],u=e[6],h=e[7],l=e[8],d=Math.sin(t),p=Math.cos(t);return r[0]=p*n+d*o,r[1]=p*i+d*a,r[2]=p*s+d*c,r[3]=p*o-d*n,r[4]=p*a-d*i,r[5]=p*c-d*s,r[6]=u,r[7]=h,r[8]=l,r}function fi(r,e,t){let n=t[0],i=t[1];return r[0]=n*e[0],r[1]=n*e[1],r[2]=n*e[2],r[3]=i*e[3],r[4]=i*e[4],r[5]=i*e[5],r[6]=e[6],r[7]=e[7],r[8]=e[8],r}function co(r,e){let t=e[0],n=e[1],i=e[2],s=e[3],o=t+t,a=n+n,c=i+i,u=t*o,h=n*o,l=n*a,d=i*o,p=i*a,f=i*c,m=s*o,g=s*a,x=s*c;return r[0]=1-l-f,r[3]=h-x,r[6]=d+g,r[1]=h+x,r[4]=1-u-f,r[7]=p-m,r[2]=d-g,r[5]=p+m,r[8]=1-u-l,r}var pi;(function(r){r[r.COL0ROW0=0]="COL0ROW0",r[r.COL0ROW1=1]="COL0ROW1",r[r.COL0ROW2=2]="COL0ROW2",r[r.COL1ROW0=3]="COL1ROW0",r[r.COL1ROW1=4]="COL1ROW1",r[r.COL1ROW2=5]="COL1ROW2",r[r.COL2ROW0=6]="COL2ROW0",r[r.COL2ROW1=7]="COL2ROW1",r[r.COL2ROW2=8]="COL2ROW2"})(pi||(pi={}));var wu=Object.freeze([1,0,0,0,1,0,0,0,1]),ie=class extends yt{static get IDENTITY(){return _u()}static get ZERO(){return Mu()}get ELEMENTS(){return 9}get RANK(){return 3}get INDICES(){return pi}constructor(e){super(-0,-0,-0,-0,-0,-0,-0,-0,-0),arguments.length===1&&Array.isArray(e)?this.copy(e):this.identity()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this[4]=e[4],this[5]=e[5],this[6]=e[6],this[7]=e[7],this[8]=e[8],this.check()}identity(){return this.copy(wu)}fromObject(e){return this.check()}fromQuaternion(e){return co(this,e),this.check()}fromMatrix4(e){return this.set(e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10])}set(e,t,n,i,s,o,a,c,u){return this[0]=e,this[1]=t,this[2]=n,this[3]=i,this[4]=s,this[5]=o,this[6]=a,this[7]=c,this[8]=u,this.check()}setRowMajor(e,t,n,i,s,o,a,c,u){return this[0]=e,this[1]=i,this[2]=a,this[3]=t,this[4]=s,this[5]=c,this[6]=n,this[7]=o,this[8]=u,this.check()}determinant(){return so(this)}transpose(){return no(this,this),this.check()}invert(){return io(this,this),this.check()}multiplyLeft(e){return di(this,e,this),this.check()}multiplyRight(e){return di(this,this,e),this.check()}rotate(e){return ao(this,this,e),this.check()}scale(e){return Array.isArray(e)?fi(this,this,e):fi(this,this,[e,e]),this.check()}translate(e){return oo(this,this,e),this.check()}transform(e,t){let n;switch(e.length){case 2:n=$s(t||[-0,-0],e,this);break;case 3:n=Nr(t||[-0,-0,-0],e,this);break;case 4:n=Ys(t||[-0,-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return gt(n,e.length),n}},Gr,Vr=null;function Mu(){return Gr||(Gr=new ie([0,0,0,0,0,0,0,0,0]),Object.freeze(Gr)),Gr}function _u(){return Vr||(Vr=new ie,Object.freeze(Vr)),Vr}function Au(r){return r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,r}function uo(r,e){if(r===e){let t=e[1],n=e[2],i=e[3],s=e[6],o=e[7],a=e[11];r[1]=e[4],r[2]=e[8],r[3]=e[12],r[4]=t,r[6]=e[9],r[7]=e[13],r[8]=n,r[9]=s,r[11]=e[14],r[12]=i,r[13]=o,r[14]=a}else r[0]=e[0],r[1]=e[4],r[2]=e[8],r[3]=e[12],r[4]=e[1],r[5]=e[5],r[6]=e[9],r[7]=e[13],r[8]=e[2],r[9]=e[6],r[10]=e[10],r[11]=e[14],r[12]=e[3],r[13]=e[7],r[14]=e[11],r[15]=e[15];return r}function ho(r,e){let t=e[0],n=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],u=e[7],h=e[8],l=e[9],d=e[10],p=e[11],f=e[12],m=e[13],g=e[14],x=e[15],T=t*a-n*o,v=t*c-i*o,w=t*u-s*o,y=n*c-i*a,b=n*u-s*a,M=i*u-s*c,_=h*m-l*f,A=h*g-d*f,S=h*x-p*f,L=l*g-d*m,I=l*x-p*m,O=d*x-p*g,E=T*O-v*I+w*L+y*S-b*A+M*_;return E?(E=1/E,r[0]=(a*O-c*I+u*L)*E,r[1]=(i*I-n*O-s*L)*E,r[2]=(m*M-g*b+x*y)*E,r[3]=(d*b-l*M-p*y)*E,r[4]=(c*S-o*O-u*A)*E,r[5]=(t*O-i*S+s*A)*E,r[6]=(g*w-f*M-x*v)*E,r[7]=(h*M-d*w+p*v)*E,r[8]=(o*I-a*S+u*_)*E,r[9]=(n*S-t*I-s*_)*E,r[10]=(f*b-m*w+x*T)*E,r[11]=(l*w-h*b-p*T)*E,r[12]=(a*A-o*L-c*_)*E,r[13]=(t*L-n*A+i*_)*E,r[14]=(m*v-f*y-g*T)*E,r[15]=(h*y-l*v+d*T)*E,r):null}function lo(r){let e=r[0],t=r[1],n=r[2],i=r[3],s=r[4],o=r[5],a=r[6],c=r[7],u=r[8],h=r[9],l=r[10],d=r[11],p=r[12],f=r[13],m=r[14],g=r[15],x=e*o-t*s,T=e*a-n*s,v=t*a-n*o,w=u*f-h*p,y=u*m-l*p,b=h*m-l*f,M=e*b-t*y+n*w,_=s*b-o*y+a*w,A=u*v-h*T+l*x,S=p*v-f*T+m*x;return c*M-i*_+g*A-d*S}function mi(r,e,t){let n=e[0],i=e[1],s=e[2],o=e[3],a=e[4],c=e[5],u=e[6],h=e[7],l=e[8],d=e[9],p=e[10],f=e[11],m=e[12],g=e[13],x=e[14],T=e[15],v=t[0],w=t[1],y=t[2],b=t[3];return r[0]=v*n+w*a+y*l+b*m,r[1]=v*i+w*c+y*d+b*g,r[2]=v*s+w*u+y*p+b*x,r[3]=v*o+w*h+y*f+b*T,v=t[4],w=t[5],y=t[6],b=t[7],r[4]=v*n+w*a+y*l+b*m,r[5]=v*i+w*c+y*d+b*g,r[6]=v*s+w*u+y*p+b*x,r[7]=v*o+w*h+y*f+b*T,v=t[8],w=t[9],y=t[10],b=t[11],r[8]=v*n+w*a+y*l+b*m,r[9]=v*i+w*c+y*d+b*g,r[10]=v*s+w*u+y*p+b*x,r[11]=v*o+w*h+y*f+b*T,v=t[12],w=t[13],y=t[14],b=t[15],r[12]=v*n+w*a+y*l+b*m,r[13]=v*i+w*c+y*d+b*g,r[14]=v*s+w*u+y*p+b*x,r[15]=v*o+w*h+y*f+b*T,r}function fo(r,e,t){let n=t[0],i=t[1],s=t[2],o,a,c,u,h,l,d,p,f,m,g,x;return e===r?(r[12]=e[0]*n+e[4]*i+e[8]*s+e[12],r[13]=e[1]*n+e[5]*i+e[9]*s+e[13],r[14]=e[2]*n+e[6]*i+e[10]*s+e[14],r[15]=e[3]*n+e[7]*i+e[11]*s+e[15]):(o=e[0],a=e[1],c=e[2],u=e[3],h=e[4],l=e[5],d=e[6],p=e[7],f=e[8],m=e[9],g=e[10],x=e[11],r[0]=o,r[1]=a,r[2]=c,r[3]=u,r[4]=h,r[5]=l,r[6]=d,r[7]=p,r[8]=f,r[9]=m,r[10]=g,r[11]=x,r[12]=o*n+h*i+f*s+e[12],r[13]=a*n+l*i+m*s+e[13],r[14]=c*n+d*i+g*s+e[14],r[15]=u*n+p*i+x*s+e[15]),r}function po(r,e,t){let n=t[0],i=t[1],s=t[2];return r[0]=e[0]*n,r[1]=e[1]*n,r[2]=e[2]*n,r[3]=e[3]*n,r[4]=e[4]*i,r[5]=e[5]*i,r[6]=e[6]*i,r[7]=e[7]*i,r[8]=e[8]*s,r[9]=e[9]*s,r[10]=e[10]*s,r[11]=e[11]*s,r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15],r}function mo(r,e,t,n){let i=n[0],s=n[1],o=n[2],a=Math.sqrt(i*i+s*s+o*o),c,u,h,l,d,p,f,m,g,x,T,v,w,y,b,M,_,A,S,L,I,O,E,k;return a<1e-6?null:(a=1/a,i*=a,s*=a,o*=a,u=Math.sin(t),c=Math.cos(t),h=1-c,l=e[0],d=e[1],p=e[2],f=e[3],m=e[4],g=e[5],x=e[6],T=e[7],v=e[8],w=e[9],y=e[10],b=e[11],M=i*i*h+c,_=s*i*h+o*u,A=o*i*h-s*u,S=i*s*h-o*u,L=s*s*h+c,I=o*s*h+i*u,O=i*o*h+s*u,E=s*o*h-i*u,k=o*o*h+c,r[0]=l*M+m*_+v*A,r[1]=d*M+g*_+w*A,r[2]=p*M+x*_+y*A,r[3]=f*M+T*_+b*A,r[4]=l*S+m*L+v*I,r[5]=d*S+g*L+w*I,r[6]=p*S+x*L+y*I,r[7]=f*S+T*L+b*I,r[8]=l*O+m*E+v*k,r[9]=d*O+g*E+w*k,r[10]=p*O+x*E+y*k,r[11]=f*O+T*E+b*k,e!==r&&(r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15]),r)}function go(r,e,t){let n=Math.sin(t),i=Math.cos(t),s=e[4],o=e[5],a=e[6],c=e[7],u=e[8],h=e[9],l=e[10],d=e[11];return e!==r&&(r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=e[3],r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15]),r[4]=s*i+u*n,r[5]=o*i+h*n,r[6]=a*i+l*n,r[7]=c*i+d*n,r[8]=u*i-s*n,r[9]=h*i-o*n,r[10]=l*i-a*n,r[11]=d*i-c*n,r}function yo(r,e,t){let n=Math.sin(t),i=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],u=e[8],h=e[9],l=e[10],d=e[11];return e!==r&&(r[4]=e[4],r[5]=e[5],r[6]=e[6],r[7]=e[7],r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15]),r[0]=s*i-u*n,r[1]=o*i-h*n,r[2]=a*i-l*n,r[3]=c*i-d*n,r[8]=s*n+u*i,r[9]=o*n+h*i,r[10]=a*n+l*i,r[11]=c*n+d*i,r}function xo(r,e,t){let n=Math.sin(t),i=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],u=e[4],h=e[5],l=e[6],d=e[7];return e!==r&&(r[8]=e[8],r[9]=e[9],r[10]=e[10],r[11]=e[11],r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15]),r[0]=s*i+u*n,r[1]=o*i+h*n,r[2]=a*i+l*n,r[3]=c*i+d*n,r[4]=u*i-s*n,r[5]=h*i-o*n,r[6]=l*i-a*n,r[7]=d*i-c*n,r}function bo(r,e){let t=e[0],n=e[1],i=e[2],s=e[3],o=t+t,a=n+n,c=i+i,u=t*o,h=n*o,l=n*a,d=i*o,p=i*a,f=i*c,m=s*o,g=s*a,x=s*c;return r[0]=1-l-f,r[1]=h+x,r[2]=d-g,r[3]=0,r[4]=h-x,r[5]=1-u-f,r[6]=p+m,r[7]=0,r[8]=d+g,r[9]=p-m,r[10]=1-u-l,r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,r}function vo(r,e,t,n,i,s,o){let a=1/(t-e),c=1/(i-n),u=1/(s-o);return r[0]=s*2*a,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=s*2*c,r[6]=0,r[7]=0,r[8]=(t+e)*a,r[9]=(i+n)*c,r[10]=(o+s)*u,r[11]=-1,r[12]=0,r[13]=0,r[14]=o*s*2*u,r[15]=0,r}function Iu(r,e,t,n,i){let s=1/Math.tan(e/2);if(r[0]=s/t,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=s,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[11]=-1,r[12]=0,r[13]=0,r[15]=0,i!=null&&i!==1/0){let o=1/(n-i);r[10]=(i+n)*o,r[14]=2*i*n*o}else r[10]=-1,r[14]=-2*n;return r}var To=Iu;function Pu(r,e,t,n,i,s,o){let a=1/(e-t),c=1/(n-i),u=1/(s-o);return r[0]=-2*a,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=-2*c,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=2*u,r[11]=0,r[12]=(e+t)*a,r[13]=(i+n)*c,r[14]=(o+s)*u,r[15]=1,r}var wo=Pu;function Mo(r,e,t,n){let i,s,o,a,c,u,h,l,d,p,f=e[0],m=e[1],g=e[2],x=n[0],T=n[1],v=n[2],w=t[0],y=t[1],b=t[2];return Math.abs(f-w)<1e-6&&Math.abs(m-y)<1e-6&&Math.abs(g-b)<1e-6?Au(r):(l=f-w,d=m-y,p=g-b,i=1/Math.sqrt(l*l+d*d+p*p),l*=i,d*=i,p*=i,s=T*p-v*d,o=v*l-x*p,a=x*d-T*l,i=Math.sqrt(s*s+o*o+a*a),i?(i=1/i,s*=i,o*=i,a*=i):(s=0,o=0,a=0),c=d*a-p*o,u=p*s-l*a,h=l*o-d*s,i=Math.sqrt(c*c+u*u+h*h),i?(i=1/i,c*=i,u*=i,h*=i):(c=0,u=0,h=0),r[0]=s,r[1]=c,r[2]=l,r[3]=0,r[4]=o,r[5]=u,r[6]=d,r[7]=0,r[8]=a,r[9]=h,r[10]=p,r[11]=0,r[12]=-(s*f+o*m+a*g),r[13]=-(c*f+u*m+h*g),r[14]=-(l*f+d*m+p*g),r[15]=1,r)}function _o(r,e,t){return r[0]=e[0]+t[0],r[1]=e[1]+t[1],r[2]=e[2]+t[2],r[3]=e[3]+t[3],r}function Ao(r,e,t){return r[0]=e[0]*t,r[1]=e[1]*t,r[2]=e[2]*t,r[3]=e[3]*t,r}function Io(r){let e=r[0],t=r[1],n=r[2],i=r[3];return Math.sqrt(e*e+t*t+n*n+i*i)}function Po(r){let e=r[0],t=r[1],n=r[2],i=r[3];return e*e+t*t+n*n+i*i}function So(r,e){let t=e[0],n=e[1],i=e[2],s=e[3],o=t*t+n*n+i*i+s*s;return o>0&&(o=1/Math.sqrt(o)),r[0]=t*o,r[1]=n*o,r[2]=i*o,r[3]=s*o,r}function Co(r,e){return r[0]*e[0]+r[1]*e[1]+r[2]*e[2]+r[3]*e[3]}function Eo(r,e,t,n){let i=e[0],s=e[1],o=e[2],a=e[3];return r[0]=i+n*(t[0]-i),r[1]=s+n*(t[1]-s),r[2]=o+n*(t[2]-o),r[3]=a+n*(t[3]-a),r}function Ro(r,e,t){let n=e[0],i=e[1],s=e[2],o=e[3];return r[0]=t[0]*n+t[4]*i+t[8]*s+t[12]*o,r[1]=t[1]*n+t[5]*i+t[9]*s+t[13]*o,r[2]=t[2]*n+t[6]*i+t[10]*s+t[14]*o,r[3]=t[3]*n+t[7]*i+t[11]*s+t[15]*o,r}var xi;(function(r){r[r.COL0ROW0=0]="COL0ROW0",r[r.COL0ROW1=1]="COL0ROW1",r[r.COL0ROW2=2]="COL0ROW2",r[r.COL0ROW3=3]="COL0ROW3",r[r.COL1ROW0=4]="COL1ROW0",r[r.COL1ROW1=5]="COL1ROW1",r[r.COL1ROW2=6]="COL1ROW2",r[r.COL1ROW3=7]="COL1ROW3",r[r.COL2ROW0=8]="COL2ROW0",r[r.COL2ROW1=9]="COL2ROW1",r[r.COL2ROW2=10]="COL2ROW2",r[r.COL2ROW3=11]="COL2ROW3",r[r.COL3ROW0=12]="COL3ROW0",r[r.COL3ROW1=13]="COL3ROW1",r[r.COL3ROW2=14]="COL3ROW2",r[r.COL3ROW3=15]="COL3ROW3"})(xi||(xi={}));var Cu=45*Math.PI/180,Eu=1,gi=.1,yi=500,Ru=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),C=class extends yt{static get IDENTITY(){return Bu()}static get ZERO(){return Lu()}get ELEMENTS(){return 16}get RANK(){return 4}get INDICES(){return xi}constructor(e){super(-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0),arguments.length===1&&Array.isArray(e)?this.copy(e):this.identity()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this[4]=e[4],this[5]=e[5],this[6]=e[6],this[7]=e[7],this[8]=e[8],this[9]=e[9],this[10]=e[10],this[11]=e[11],this[12]=e[12],this[13]=e[13],this[14]=e[14],this[15]=e[15],this.check()}set(e,t,n,i,s,o,a,c,u,h,l,d,p,f,m,g){return this[0]=e,this[1]=t,this[2]=n,this[3]=i,this[4]=s,this[5]=o,this[6]=a,this[7]=c,this[8]=u,this[9]=h,this[10]=l,this[11]=d,this[12]=p,this[13]=f,this[14]=m,this[15]=g,this.check()}setRowMajor(e,t,n,i,s,o,a,c,u,h,l,d,p,f,m,g){return this[0]=e,this[1]=s,this[2]=u,this[3]=p,this[4]=t,this[5]=o,this[6]=h,this[7]=f,this[8]=n,this[9]=a,this[10]=l,this[11]=m,this[12]=i,this[13]=c,this[14]=d,this[15]=g,this.check()}toRowMajor(e){return e[0]=this[0],e[1]=this[4],e[2]=this[8],e[3]=this[12],e[4]=this[1],e[5]=this[5],e[6]=this[9],e[7]=this[13],e[8]=this[2],e[9]=this[6],e[10]=this[10],e[11]=this[14],e[12]=this[3],e[13]=this[7],e[14]=this[11],e[15]=this[15],e}identity(){return this.copy(Ru)}fromObject(e){return this.check()}fromQuaternion(e){return bo(this,e),this.check()}fromMatrix3(e){return this.set(e[0],e[1],e[2],0,e[3],e[4],e[5],0,e[6],e[7],e[8],0,0,0,0,1)}frustum(e){let{left:t,right:n,bottom:i,top:s,near:o=gi,far:a=yi}=e;return a===1/0?Ou(this,t,n,i,s,o):vo(this,t,n,i,s,o,a),this.check()}lookAt(e){let{eye:t,center:n=[0,0,0],up:i=[0,1,0]}=e;return Mo(this,t,n,i),this.check()}ortho(e){let{left:t,right:n,bottom:i,top:s,near:o=gi,far:a=yi}=e;return wo(this,t,n,i,s,o,a),this.check()}orthographic(e){let{fovy:t=Cu,aspect:n=Eu,focalDistance:i=1,near:s=gi,far:o=yi}=e;Lo(t);let a=t/2,c=i*Math.tan(a),u=c*n;return this.ortho({left:-u,right:u,bottom:-c,top:c,near:s,far:o})}perspective(e){let{fovy:t=45*Math.PI/180,aspect:n=1,near:i=.1,far:s=500}=e;return Lo(t),To(this,t,n,i,s),this.check()}determinant(){return lo(this)}getScale(e=[-0,-0,-0]){return e[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]),e[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]),e[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]),e}getTranslation(e=[-0,-0,-0]){return e[0]=this[12],e[1]=this[13],e[2]=this[14],e}getRotation(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),i=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*i,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=0,e[4]=this[4]*i,e[5]=this[5]*s,e[6]=this[6]*o,e[7]=0,e[8]=this[8]*i,e[9]=this[9]*s,e[10]=this[10]*o,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}getRotationMatrix3(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),i=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*i,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=this[4]*i,e[4]=this[5]*s,e[5]=this[6]*o,e[6]=this[8]*i,e[7]=this[9]*s,e[8]=this[10]*o,e}transpose(){return uo(this,this),this.check()}invert(){return ho(this,this),this.check()}multiplyLeft(e){return mi(this,e,this),this.check()}multiplyRight(e){return mi(this,this,e),this.check()}rotateX(e){return go(this,this,e),this.check()}rotateY(e){return yo(this,this,e),this.check()}rotateZ(e){return xo(this,this,e),this.check()}rotateXYZ(e){return this.rotateX(e[0]).rotateY(e[1]).rotateZ(e[2])}rotateAxis(e,t){return mo(this,this,e,t),this.check()}scale(e){return po(this,this,Array.isArray(e)?e:[e,e,e]),this.check()}translate(e){return fo(this,this,e),this.check()}transform(e,t){return e.length===4?(t=Ro(t||[-0,-0,-0,-0],e,this),gt(t,4),t):this.transformAsPoint(e,t)}transformAsPoint(e,t){let{length:n}=e,i;switch(n){case 2:i=qs(t||[-0,-0],e,this);break;case 3:i=Fr(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return gt(i,e.length),i}transformAsVector(e,t){let n;switch(e.length){case 2:n=Ws(t||[-0,-0],e,this);break;case 3:n=kr(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return gt(n,e.length),n}makeRotationX(e){return this.identity().rotateX(e)}makeTranslation(e,t,n){return this.identity().translate([e,t,n])}},Ur,jr;function Lu(){return Ur||(Ur=new C([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Object.freeze(Ur)),Ur}function Bu(){return jr||(jr=new C,Object.freeze(jr)),jr}function Lo(r){if(r>Math.PI*2)throw Error("expected radians")}function Ou(r,e,t,n,i,s){let o=2*s/(t-e),a=2*s/(i-n),c=(t+e)/(t-e),u=(i+n)/(i-n),h=-1,l=-1,d=-2*s;return r[0]=o,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=a,r[6]=0,r[7]=0,r[8]=c,r[9]=u,r[10]=h,r[11]=l,r[12]=0,r[13]=0,r[14]=d,r[15]=0,r}function Bo(r){return r[0]=0,r[1]=0,r[2]=0,r[3]=1,r}function bi(r,e,t){t=t*.5;let n=Math.sin(t);return r[0]=n*e[0],r[1]=n*e[1],r[2]=n*e[2],r[3]=Math.cos(t),r}function vi(r,e,t){let n=e[0],i=e[1],s=e[2],o=e[3],a=t[0],c=t[1],u=t[2],h=t[3];return r[0]=n*h+o*a+i*u-s*c,r[1]=i*h+o*c+s*a-n*u,r[2]=s*h+o*u+n*c-i*a,r[3]=o*h-n*a-i*c-s*u,r}function Oo(r,e,t){t*=.5;let n=e[0],i=e[1],s=e[2],o=e[3],a=Math.sin(t),c=Math.cos(t);return r[0]=n*c+o*a,r[1]=i*c+s*a,r[2]=s*c-i*a,r[3]=o*c-n*a,r}function Do(r,e,t){t*=.5;let n=e[0],i=e[1],s=e[2],o=e[3],a=Math.sin(t),c=Math.cos(t);return r[0]=n*c-s*a,r[1]=i*c+o*a,r[2]=s*c+n*a,r[3]=o*c-i*a,r}function ko(r,e,t){t*=.5;let n=e[0],i=e[1],s=e[2],o=e[3],a=Math.sin(t),c=Math.cos(t);return r[0]=n*c+i*a,r[1]=i*c-n*a,r[2]=s*c+o*a,r[3]=o*c-s*a,r}function Fo(r,e){let t=e[0],n=e[1],i=e[2];return r[0]=t,r[1]=n,r[2]=i,r[3]=Math.sqrt(Math.abs(1-t*t-n*n-i*i)),r}function No(r,e,t,n){let i=e[0],s=e[1],o=e[2],a=e[3],c=t[0],u=t[1],h=t[2],l=t[3],d,p,f,m,g;return d=i*c+s*u+o*h+a*l,d<0&&(d=-d,c=-c,u=-u,h=-h,l=-l),1-d>1e-6?(p=Math.acos(d),g=Math.sin(p),f=Math.sin((1-n)*p)/g,m=Math.sin(n*p)/g):(f=1-n,m=n),r[0]=f*i+m*c,r[1]=f*s+m*u,r[2]=f*o+m*h,r[3]=f*a+m*l,r}function zo(r,e){let t=e[0],n=e[1],i=e[2],s=e[3],o=t*t+n*n+i*i+s*s,a=o?1/o:0;return r[0]=-t*a,r[1]=-n*a,r[2]=-i*a,r[3]=s*a,r}function Go(r,e){return r[0]=-e[0],r[1]=-e[1],r[2]=-e[2],r[3]=e[3],r}function Vo(r,e){let t=e[0]+e[4]+e[8],n;if(t>0)n=Math.sqrt(t+1),r[3]=.5*n,n=.5/n,r[0]=(e[5]-e[7])*n,r[1]=(e[6]-e[2])*n,r[2]=(e[1]-e[3])*n;else{let i=0;e[4]>e[0]&&(i=1),e[8]>e[i*3+i]&&(i=2);let s=(i+1)%3,o=(i+2)%3;n=Math.sqrt(e[i*3+i]-e[s*3+s]-e[o*3+o]+1),r[i]=.5*n,n=.5/n,r[3]=(e[s*3+o]-e[o*3+s])*n,r[s]=(e[s*3+i]+e[i*3+s])*n,r[o]=(e[o*3+i]+e[i*3+o])*n}return r}var Uo=_o;var jo=Ao,$o=Co,qo=Eo,Wo=Io;var Ho=Po;var Du=So;var Yo=(function(){let r=Xs(),e=ui(1,0,0),t=ui(0,1,0);return function(n,i,s){let o=hi(i,s);return o<-.999999?(xt(r,e,i),ro(r)<1e-6&&xt(r,t,i),Ks(r,r),bi(n,r,Math.PI),n):o>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(xt(r,i,s),n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=1+o,Du(n,n))}})();var Jt=class extends ke{constructor(e=0,t=0,n=0,i=1){super(-0,-0,-0,-0),Array.isArray(e)&&arguments.length===1?this.copy(e):this.set(e,t,n,i)}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this.check()}set(e,t,n,i){return this[0]=e,this[1]=t,this[2]=n,this[3]=i,this.check()}fromObject(e){return this[0]=e.x,this[1]=e.y,this[2]=e.z,this[3]=e.w,this.check()}fromMatrix3(e){return Vo(this,e),this.check()}fromEuler(e){switch(this.identity(),e.order){case"xyz":return this.rotateX(e.x).rotateY(e.y).rotateZ(e.z);case"yxz":return this.rotateY(e.y).rotateX(e.x).rotateZ(e.z);case"zxy":return this.rotateZ(e.z).rotateX(e.x).rotateY(e.y);case"zyx":return this.rotateZ(e.z).rotateY(e.y).rotateX(e.x);case"yzx":return this.rotateY(e.y).rotateZ(e.z).rotateX(e.x);case"xzy":return this.rotateX(e.x).rotateZ(e.z).rotateY(e.y);default:throw new Error("Unknown Euler angle order")}}fromAxisRotation(e,t){return bi(this,e,t),this.check()}identity(){return Bo(this),this.check()}setAxisAngle(e,t){return this.fromAxisRotation(e,t)}get ELEMENTS(){return 4}get x(){return this[0]}set x(e){this[0]=V(e)}get y(){return this[1]}set y(e){this[1]=V(e)}get z(){return this[2]}set z(e){this[2]=V(e)}get w(){return this[3]}set w(e){this[3]=V(e)}len(){return Wo(this)}lengthSquared(){return Ho(this)}dot(e){return $o(this,e)}rotationTo(e,t){return Yo(this,e,t),this.check()}add(e){return Uo(this,this,e),this.check()}calculateW(){return Fo(this,this),this.check()}conjugate(){return Go(this,this),this.check()}invert(){return zo(this,this),this.check()}lerp(e,t,n){return n===void 0?this.lerp(this,e,t):(qo(this,e,t,n),this.check())}multiplyRight(e){return vi(this,this,e),this.check()}multiplyLeft(e){return vi(this,e,this),this.check()}normalize(){let e=this.len(),t=e>0?1/e:0;return this[0]=this[0]*t,this[1]=this[1]*t,this[2]=this[2]*t,this[3]=this[3]*t,e===0&&(this[3]=1),this.check()}rotateX(e){return Oo(this,this,e),this.check()}rotateY(e){return Do(this,this,e),this.check()}rotateZ(e){return ko(this,this,e),this.check()}scale(e){return jo(this,this,e),this.check()}slerp(e,t,n){let i,s,o;return arguments.length===2?(i=this,s=e,o=t):(i=e,s=t,o=n),No(this,i,s,o),this.check()}lengthSq(){return this.lengthSquared()}setFromAxisAngle(e,t){return this.setAxisAngle(e,t)}premultiply(e){return this.multiplyLeft(e)}multiply(e){return this.multiplyRight(e)}};function $r(r){if(!r.indices)return r;let e=r.indices.value,t={};for(let[n,i]of Object.entries(r.attributes)){if(!i)continue;if(i.constant||!i.size){t[n]=i;continue}let s=i.value.constructor,o=new s(e.length*i.size);for(let a=0;a<e.length;a++)for(let c=0;c<i.size;c++)o[a*i.size+c]=i.value[Number(e[a])*i.size+c];t[n]={...i,value:o}}return{attributes:t}}function Y(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`${e} must be greater than zero`)}function Ti(r,e){if(!Number.isFinite(r)||r<0)throw new Error(`${e} must be non-negative`)}function H(r,e,t=1){if(!Number.isInteger(r)||r<t)throw new Error(`${e} must be an integer >= ${t}`)}function me(r,e){return r>65535?new Uint32Array(e):new Uint16Array(e)}var qr=class extends j{constructor(e={}){let t=e.size||[1,1,1];Y(t[0],"size[0]"),Y(t[1],"size[1]"),Y(t[2],"size[2]");let n=[t[0]/2,t[1]/2,t[2]/2],i=[],s=[],o=[],a=[],c=[{n:[1,0,0],u:[0,0,-1],v:[0,1,0],h1:n[2],h2:n[1]},{n:[-1,0,0],u:[0,0,1],v:[0,1,0],h1:n[2],h2:n[1]},{n:[0,1,0],u:[1,0,0],v:[0,0,-1],h1:n[0],h2:n[2]},{n:[0,-1,0],u:[1,0,0],v:[0,0,1],h1:n[0],h2:n[2]},{n:[0,0,1],u:[1,0,0],v:[0,1,0],h1:n[0],h2:n[1]},{n:[0,0,-1],u:[-1,0,0],v:[0,1,0],h1:n[0],h2:n[1]}];for(let u of c){let h=i.length/3;for(let[l,d,p,f]of[[-1,-1,0,0],[1,-1,1,0],[1,1,1,1],[-1,1,0,1]])i.push(u.n[0]*n[0]+u.u[0]*u.h1*l+u.v[0]*u.h2*d,u.n[1]*n[1]+u.u[1]*u.h1*l+u.v[1]*u.h2*d,u.n[2]*n[2]+u.u[2]*u.h1*l+u.v[2]*u.h2*d),s.push(...u.n),o.push(p,f);a.push(h,h+1,h+2,h,h+2,h+3)}super({id:e.id,topology:"triangle-list",indices:me(24,a),attributes:{POSITION:{size:3,value:new Float32Array(i)},NORMAL:{size:3,value:new Float32Array(s)},TEXCOORD_0:{size:2,value:new Float32Array(o)},...e.attributes}})}},er=class extends qr{constructor(e={}){let t=e.size??1;super({...e,size:[t,t,t]})}};function Xo(r,e){let t=[],n=[],i=[],s=[],o=e+1;for(let a=0;a<r.length;a++){let c=r[a];for(let u=0;u<=e;u++){let h=u/e,l=h*Math.PI*2,d=Math.sin(l),p=Math.cos(l);t.push(d*c.radius,c.y,p*c.radius),n.push(d*c.normalRadius,c.normalY,p*c.normalRadius),i.push(h,a/(r.length-1))}}for(let a=0;a<r.length-1;a++)for(let c=0;c<e;c++){let u=a*o+c,h=u+1,l=u+o,d=l+1;s.push(u,h,d,u,d,l)}return{positions:t,normals:n,texCoords:i,indices:s,indexArray:me(t.length/3,s)}}var tr=class extends j{constructor(e={}){let{topRadius:t=0,bottomRadius:n=0,topCap:i=!1,bottomCap:s=!1,height:o=1,nradial:a=10,nvertical:c=1,verticalAxis:u="y"}=e;if(Ti(t,"topRadius"),Ti(n,"bottomRadius"),t===0&&n===0)throw new Error("At least one radius must be greater than zero");Y(o,"height"),H(a,"nradial",3),H(c,"nvertical");let h=[],l=[],d=[],p=[],f=a+1,m=(n-t)/o,g=1/Math.hypot(1,m),x=(y,b,M,_,A)=>{let S=h.length/3/f;for(let L=0;L<=a;L++){let I=L/a,O=I*Math.PI*2,E=Math.sin(O),k=Math.cos(O),fe=Ko([E*y,b,k*y],u),ne=Ko([E*M,_,k*M],u);h.push(...fe),l.push(...ne),d.push(I,A)}return S},T=(y,b)=>{for(let M=0;M<a;M++){let _=y*f+M,A=_+1,S=b*f+M,L=S+1;p.push(_,A,L,_,L,S)}},v;if(s){let y=x(0,-o/2,0,-1,0),b=x(n,-o/2,0,-1,1);T(y,b),v=x(n,-o/2,g,m*g,0)}for(let y=0;y<=c;y++){let b=y/c,M=n+(t-n)*b,_=x(M,(b-.5)*o,g,m*g,b);v!==void 0&&!(s&&y===0)&&T(v,_),v=_}if(i&&v!==void 0){let y=x(t,o/2,0,1,1),b=x(0,o/2,0,1,0);T(y,b)}let w=h.length/3;super({id:e.id,topology:"triangle-list",indices:me(w,p),attributes:{POSITION:{size:3,value:new Float32Array(h)},NORMAL:{size:3,value:new Float32Array(l)},TEXCOORD_0:{size:2,value:new Float32Array(d)},...e.attributes}})}};function Ko(r,e){switch(e){case"x":return[r[1],r[2],r[0]];case"z":return[r[2],r[0],r[1]];default:return[r[0],r[1],r[2]]}}var Ze=class extends j{constructor(e){let{sizeX:t,sizeZ:n,nx:i=1,nz:s=1}=e;Y(t,"sizeX"),Y(n,"sizeZ"),H(i,"nx"),H(s,"nz");let o=[],a=[],c=[],u=[];for(let d=0;d<=s;d++){let p=d/s;for(let f=0;f<=i;f++){let m=f/i;o.push((m-.5)*t,0,(.5-p)*n),a.push(0,1,0),c.push(m,p)}}let h=i+1;for(let d=0;d<s;d++)for(let p=0;p<i;p++){let f=d*h+p,m=f+1,g=f+h,x=g+1;u.push(f,m,x,f,x,g)}let l=o.length/3;super({id:e.id,topology:"triangle-list",indices:me(l,u),attributes:{POSITION:{size:3,value:new Float32Array(o)},NORMAL:{size:3,value:new Float32Array(a)},TEXCOORD_0:{size:2,value:new Float32Array(c)},...e.attributes}})}};var rr=class extends j{constructor(e={}){let{radius:t=.5,nlat:n=10,nlong:i=10}=e;Y(t,"radius"),H(n,"nlat",2),H(i,"nlong",3);let s=[];for(let a=0;a<=n;a++){let c=-Math.PI/2+a/n*Math.PI,u=Math.cos(c),h=Math.sin(c);s.push({radius:t*u,y:t*h,normalRadius:u,normalY:h})}let o=Xo(s,i);super({id:e.id,topology:"triangle-list",indices:o.indexArray,attributes:{POSITION:{size:3,value:new Float32Array(o.positions)},NORMAL:{size:3,value:new Float32Array(o.normals)},TEXCOORD_0:{size:2,value:new Float32Array(o.texCoords)},...e.attributes}})}};var nr=class extends j{constructor(e={}){let{radius:t=.5,iterations:n=0}=e;if(Y(t,"radius"),H(n,"iterations",0),n>8)throw new Error("iterations must be <= 8");let i=(1+Math.sqrt(5))/2,s=[[-1,i,0],[1,i,0],[-1,-i,0],[1,-i,0],[0,-1,i],[0,1,i],[0,-1,-i],[0,1,-i],[i,0,-1],[i,0,1],[-i,0,-1],[-i,0,1]].map(Wr),o=[[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,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]].map(h=>h.map(l=>s[l]));for(let h=0;h<n;h++){let l=[];for(let[d,p,f]of o){let m=Wr([d[0]+p[0],d[1]+p[1],d[2]+p[2]]),g=Wr([p[0]+f[0],p[1]+f[1],p[2]+f[2]]),x=Wr([f[0]+d[0],f[1]+d[1],f[2]+d[2]]);l.push([d,m,x],[p,g,m],[f,x,g],[m,g,x])}o=l}let a=[],c=[],u=[];for(let h of o)for(let l of h)a.push(l[0]*t,l[1]*t,l[2]*t),c.push(...l),u.push(.5+Math.atan2(l[0],l[2])/(2*Math.PI),.5-Math.asin(l[1])/Math.PI);super({id:e.id,topology:"triangle-list",attributes:{POSITION:{size:3,value:new Float32Array(a)},NORMAL:{size:3,value:new Float32Array(c)},TEXCOORD_0:{size:2,value:new Float32Array(u)},...e.attributes}})}};function Wr(r){let e=Math.hypot(...r);return r.map(t=>t/e)}var Qe=class extends j{constructor(e){let{sample:t,normal:n,uSegments:i=32,vSegments:s=32,periodicU:o=!1,periodicV:a=!1}=e;H(i,"uSegments"),H(s,"vSegments");let c=(i+1)*(s+1),u=i*s*6;if(!Number.isSafeInteger(u)||u>4294967295)throw new RangeError("Surface exceeds 32-bit index-buffer length");if(!Number.isSafeInteger(c)||c>4294967295)throw new RangeError("Surface exceeds 32-bit indexing");let h=new Float32Array(c*3),l=new Float32Array(c*3),d=new Float32Array(c*2),p=(w,y)=>y?(w%1+1)%1:Math.max(0,Math.min(1,w)),f=(w,y)=>Zo(t(p(w,o),p(y,a))),m=1e-5,g=0;for(let w=0;w<=s;w++)for(let y=0;y<=i;y++,g++){let b=y/i,M=w/s,_=p(b,o),A=p(M,a);h.set(f(_,A),g*3);let S;if(n)S=Zo(n(_,A));else{let L=f(_-m,A),I=f(_+m,A),O=f(_,A-m),E=f(_,A+m),k=bt(I.map((ne,De)=>ne-L[De])),fe=bt(E.map((ne,De)=>ne-O[De]));S=[k[1]*fe[2]-k[2]*fe[1],k[2]*fe[0]-k[0]*fe[2],k[0]*fe[1]-k[1]*fe[0]]}l.set(bt(S),g*3),d.set([b,M],g*2)}for(let w of h)if(!Number.isFinite(w))throw new RangeError("Positions must be representable as Float32");let x=c>65535?new Uint32Array(u):new Uint16Array(u),T=i+1,v=0;for(let w=0;w<s;w++)for(let y=0;y<i;y++){let b=w*T+y,M=b+1,_=b+T,A=_+1;x[v++]=b,x[v++]=M,x[v++]=A,x[v++]=b,x[v++]=A,x[v++]=_}super({id:e.id,topology:"triangle-list",indices:x,attributes:{POSITION:{size:3,value:h},NORMAL:{size:3,value:l},TEXCOORD_0:{size:2,value:d},...e.attributes}})}};function Zo(r){if(!r||r.length!==3||!Array.from(r).every(Number.isFinite))throw new RangeError("Surface samples and normals must be finite triples");return Array.from(r)}function bt(r){let e=Math.max(...r.map(Math.abs));if(!e)return[0,0,0];let t=r.map(i=>i/e),n=Math.hypot(...t);return t.map(i=>i===0?0:i/n)}var vt=class extends Qe{constructor(e={}){let{majorRadius:t=1,minorRadius:n=.3,majorSegments:i=48,minorSegments:s=24,arc:o=Math.PI*2,startAngle:a=0,cap:c=!1}=e;if(Y(t,"majorRadius"),Y(n,"minorRadius"),n>=t)throw new RangeError("Ring torus requires minorRadius < majorRadius");if(!Number.isFinite(o)||o<=0||o>Math.PI*2)throw new RangeError("arc must be in (0, 2\u03C0]");if(H(i,"majorSegments",3),H(s,"minorSegments",3),!Number.isFinite(a))throw new RangeError("startAngle must be finite");let u=c&&o<Math.PI*2;if(super({...e,attributes:u?void 0:e.attributes,uSegments:i,vSegments:s,periodicU:o===Math.PI*2,periodicV:!0,sample:(h,l)=>{let d=a+h*o,p=l*Math.PI*2,f=t+n*Math.cos(p);return[f*Math.cos(d),n*Math.sin(p),-f*Math.sin(d)]},normal:(h,l)=>[Math.cos(l*Math.PI*2)*Math.cos(a+h*o),Math.sin(l*Math.PI*2),-Math.cos(l*Math.PI*2)*Math.sin(a+h*o)]}),u){let h=this.attributes.POSITION.value,l=Array.from(h),d=Array.from(this.attributes.NORMAL.value),p=Array.from(this.attributes.TEXCOORD_0.value),f=Array.from(this.indices.value);for(let[g,x]of[[a,-1],[a+o,1]]){let T=[-Math.sin(g)*x,0,-Math.cos(g)*x],v=l.length/3;l.push(t*Math.cos(g),0,-t*Math.sin(g)),d.push(...T),p.push(.5,.5);for(let w=0;w<=s;w++){let y=w%s*Math.PI*2/s,b=(w*(i+1)+(x<0?0:i))*3;if(l.push(...h.slice(b,b+3)),d.push(...T),p.push((Math.cos(y)+1)/2,(Math.sin(y)+1)/2),w<s){let M=v+w+1,_=M+1;f.push(v,...x>0?[_,M]:[M,_])}}}let m=new j({id:this.id,topology:this.topology,indices:me(l.length/3,f),attributes:{POSITION:{size:3,value:new Float32Array(l)},NORMAL:{size:3,value:new Float32Array(d)},TEXCOORD_0:{size:2,value:new Float32Array(p)},...e.attributes}});Object.assign(this,{attributes:m.attributes,indices:m.indices,vertexCount:m.vertexCount})}}};var Tt=class extends Qe{constructor(e){let{points:t,segments:n=48,phiStart:i=0,phiLength:s=Math.PI*2}=e;if(!t||t.length<2||t.some(h=>h.length!==2||!h.every(Number.isFinite)||h[0]<0))throw new RangeError("Lathe needs at least two finite [nonnegative radius, height] points");if(!Number.isFinite(i)||!Number.isFinite(s)||s<=0||s>Math.PI*2)throw new RangeError("Invalid lathe angular sweep");if(n<3)throw new RangeError("Lathe requires at least three angular segments");let o=t.map(h=>[...h]),a=o.slice(1).map((h,l)=>{let d=h[0]-o[l][0],p=h[1]-o[l][1];if(d===0&&p===0)throw new RangeError("Consecutive profile points must differ");return bt([p,-d,0])}),c=o.map((h,l)=>{let d=a[Math.max(0,l-1)],p=a[Math.min(l,a.length-1)];return bt(d.map((f,m)=>f+p[m]))}),u=h=>{let l=h*(o.length-1),d=Math.min(o.length-2,Math.floor(l));return{i:d,t:l-d}};super({...e,uSegments:n,vSegments:o.length-1,periodicU:s===Math.PI*2,sample:(h,l)=>{let{i:d,t:p}=u(l),f=o[d][0]*(1-p)+o[d+1][0]*p,m=o[d][1]*(1-p)+o[d+1][1]*p,g=i+h*s;return[f*Math.cos(g),m,-f*Math.sin(g)]},normal:(h,l)=>{let{i:d,t:p}=u(l),f=c[d].map((g,x)=>g*(1-p)+c[d+1][x]*p),m=i+h*s;return[f[0]*Math.cos(m),f[1],-f[0]*Math.sin(m)]}})}};var Qo=B(D(),1),z=class extends j{bufferLayout;constructor(e){let t={},n=new Map;for(let[o,a]of Object.entries(e.attributes)){let c=Je(o),u=n.get(c);u&&delete t[u],n.set(c,o),t[o]=a}let i=e.indices,s=i instanceof Uint8Array?new Uint16Array(i):i&&!ArrayBuffer.isView(i)&&i.value instanceof Uint8Array?{...i,value:new Uint16Array(i.value)}:i;super({...e,attributes:t,indices:s});for(let[o,a]of Object.entries(t))!ArrayBuffer.isView(a)&&Object.isExtensible(a)&&o!=="indices"&&(Object.assign(a,this.attributes[o]),this.attributes[o]=a);this.bufferLayout=e.bufferLayout||wi(this.attributes)}};function Je(r){switch(r){case"POSITION":return"positions";case"NORMAL":return"normals";case"TEXCOORD_0":return"texCoords";case"TEXCOORD_1":return"texCoords1";case"COLOR_0":return"colors";default:return r}}function wi(r){let e=[];for(let[t,n]of Object.entries(r)){if(!n)continue;let{value:i,size:s,normalized:o}=n;if(s===void 0)throw new Error(`Attribute ${t} is missing a size`);e.push({name:Je(t),format:Qo.vertexFormatDecoder.getVertexFormatFromAttribute(i,s,o)})}return e}var Mi=B(D(),1);function wt(r,e={}){let t=e.bufferName||"geometry";if(ku(r,t))return r;let n=e.minAttributeAlignment||4,i=Fu(r,e.attributes),s=[],o=0,a=1/0;for(let[h,l]of i){if(!l)continue;if(l.constant)throw new Error(`Attribute ${h} is constant`);let{value:d,size:p,normalized:f}=l;if(!ArrayBuffer.isView(d))throw new Error(`Attribute ${h} is missing typed array data`);if(p===void 0)throw new Error(`Attribute ${h} is missing a size`);let m=Mi.vertexFormatDecoder.getVertexFormatFromAttribute(d,p,f),g=Mi.vertexFormatDecoder.getVertexFormatInfo(m);o=Jo(o,n),s.push({sourceName:h,attributeName:Je(h),value:d,size:p,format:m,byteOffset:o,byteLength:g.byteLength}),o+=g.byteLength;let x=d.length/p;if(!Number.isInteger(x))throw new Error(`Attribute ${h} length is not divisible by size`);a=Math.min(a,x)}if(s.length===0||!Number.isFinite(a))throw new Error(`Geometry ${r.id} has no interleavable attributes`);let c=Jo(o,n),u=new ArrayBuffer(a*c);for(let h of s)Nu(u,a,c,h);return new z({id:r.id,topology:r.topology||"triangle-list",vertexCount:r.vertexCount,indices:r.indices,attributes:{[t]:{value:new Uint8Array(u),size:c,byteStride:c}},bufferLayout:[{name:t,stepMode:"vertex",byteStride:c,attributes:s.map(h=>({attribute:h.attributeName,format:h.format,byteOffset:h.byteOffset}))}]})}function ku(r,e){if(r.bufferLayout?.length!==1)return!1;let t=r.bufferLayout[0];return t.name===e&&!!t.attributes?.length&&!!r.attributes[e]}function Fu(r,e){let t=new Map,n=e||Object.keys(r.attributes);for(let i of n){let s=r.attributes[i];s&&t.set(Je(i),[i,s])}return Array.from(t.values())}function Nu(r,e,t,n){let i=n.value.constructor,s=i.BYTES_PER_ELEMENT;if(n.byteOffset%s!==0||t%s!==0)throw new Error(`Attribute ${n.sourceName} is not aligned to its component type`);let o=new i(r),a=n.value,c=n.byteOffset/s,u=t/s;for(let h=0;h<e;h++){let l=h*n.size,d=h*u+c;for(let p=0;p<n.size;p++)o[d+p]=a[l+p]}}function Jo(r,e){return Math.ceil(r/e)*e}function _i(r){let e=r.value;if(e instanceof Float32Array)return e;let t=new Float32Array(e.length),n=ea(e),i=e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array;for(let s=0;s<e.length;s++){let o=Number(e[s]);t[s]=r.normalized&&n?i?Math.max(o/n,-1):o/n:o}return t}function ir(r,e,t){let n={};for(let i of["POSITION","NORMAL","TANGENT"]){let s=r[i];if(!s)continue;let o=new Float32Array(s),a=i==="TANGENT"?4:3,c=Math.floor(s.length/a);for(let u=0;u<Math.min(e.length,t.length);u++){let h=t[u],l=e[u][i];if(!h||!l)continue;let d=i==="TANGENT"&&l.length===c*4?4:3;for(let p=0;p<c;p++){let f=p*a,m=p*d;for(let g=0;g<3;g++)o[f+g]+=(l[m+g]||0)*h}}i!=="POSITION"&&Gu(o,a),n[i]=o}return n}function Hr(r,e,t,n){let i={};for(let l of["POSITION","NORMAL","TANGENT"]){let d=e.attributes[l];d&&(i[l]=_i(d))}let s=ir(i,t,n),o={};for(let[l,d]of Object.entries(e.attributes))d&&(o[l]=d);for(let l of["POSITION","NORMAL","TANGENT"]){let d=s[l],p=o[l];d&&p&&(o[l]={...p,value:zu(p,d)})}let a=new z({id:e.id,topology:e.topology||"triangle-list",vertexCount:e.vertexCount,indices:e.indices,attributes:o,bufferLayout:e.bufferLayout}),u=wt(a).attributes.geometry?.value,h=r._gpuGeometry?.attributes.geometry||r.bufferAttributes.geometry;if(u&&h){h.write(u);return}for(let l of["POSITION","NORMAL","TANGENT"]){let d=s[l];if(d){let p=l==="POSITION"?"positions":l==="NORMAL"?"normals":"TANGENT";r.bufferAttributes[p]?.write(d)}}}function zu(r,e){if(r.value instanceof Float32Array)return e;let t=r.value.slice(),n=ea(t),i=t instanceof Int8Array||t instanceof Int16Array||t instanceof Int32Array;for(let s=0;s<e.length;s++){let o=e[s];t[s]=r.normalized&&n?Math.round(Math.max(i?-1:0,Math.min(1,o))*n):o}return t}function ea(r){return r instanceof Int8Array?127:r instanceof Uint8Array||r instanceof Uint8ClampedArray?255:r instanceof Int16Array?32767:r instanceof Uint16Array?65535:r instanceof Int32Array?2147483647:r instanceof Uint32Array?4294967295:0}function Gu(r,e){for(let t=0;t<r.length;t+=e){let n=Math.hypot(r[t],r[t+1],r[t+2]);n>0&&(r[t]/=n,r[t+1]/=n,r[t+2]/=n)}}function Yr(r){let{joints:e,meshNode:t,worldMatrices:n,inverseBindMatrices:i,target:s}=r,o=e.length,a=s&&s.length===o*16?s:new Float32Array(o*16),c=t?n.get(t)||t.matrix:void 0,u=c?new C(c).invert():null;for(let h=0;h<o;h++){let l=e[h],d=n.get(l)||l.matrix,p=u?new C(u).multiplyRight(d):new C(d),f=h*16;if(i&&i.length>=f+16){let m=new C;for(let g=0;g<16;g++)m[g]=i[f+g];p.multiplyRight(m)}a.set(p,f)}return a}var Vu=1,Uu=1,Xr=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(e){let{delay:t=0,duration:n=Number.POSITIVE_INFINITY,rate:i=1,repeat:s=1}=e,o=Vu++,a={time:0,delay:t,duration:n,rate:i,repeat:s};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(e){this.channels.delete(e);for(let[t,n]of this.animations)n.channel===e&&this.detachAnimation(t)}isFinished(e){let t=this.channels.get(e);return t===void 0?!1:this.time>=t.delay+t.duration*t.repeat}getTime(e){if(e===void 0)return this.time;let t=this.channels.get(e);return t===void 0?-1:t.time}setTime(e){this.time=Math.max(0,e);let t=this.channels.values();for(let i of t)this._setChannelTime(i,this.time);let n=this.animations.values();for(let i of n){let{animation:s,channel:o}=i;s.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(e,t){let n=Uu++;return this.animations.set(n,{animation:e,channel:t}),e.setTime(this.getTime(t)),n}detachAnimation(e){this.animations.delete(e)}update(e){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=e),this.setTime(this.time+(e-this.lastEngineTime)),this.lastEngineTime=e)}_setChannelTime(e,t){let n=t-e.delay,i=e.duration*e.repeat;n>=i?e.time=e.duration*e.rate:(e.time=Math.max(0,n)%e.duration,e.time*=e.rate)}};var Kr=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(e){this.setKeyFrames(e),this.setTime(0)}setKeyFrames(e){let t=e.length;this.times.length=t,this.values.length=t;for(let n=0;n<t;++n)this.times[n]=e[n][0],this.values[n]=e[n][1];this._calculateKeys(this._lastTime)}setTime(e){e=Math.max(0,e),e!==this._lastTime&&(this._calculateKeys(e),this._lastTime=e)}getStartTime(){return this.times[this.startIndex]}getEndTime(){return this.times[this.endIndex]}getStartData(){return this.values[this.startIndex]}getEndData(){return this.values[this.endIndex]}_calculateKeys(e){let t=0,n=this.times.length;for(t=0;t<n-2&&!(this.times[t+1]>e);++t);this.startIndex=t,this.endIndex=t+1;let i=this.times[this.startIndex],s=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(e-i)/(s-i)),1)}};var Zr=class{constructor(e){}async onInitialize(e){return null}};var ra=B(D(),1);function Qr(r){let e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,r):setTimeout(()=>r(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function Jr(r){let e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,r);return}clearTimeout(r)}function sr(){let r;if(typeof window<"u"&&window.performance)r=window.performance.now();else if(typeof process<"u"&&process.hrtime){let e=process.hrtime();r=e[0]*1e3+e[1]/1e6}else r=Date.now();return r}var et=class{constructor(e,t){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=e,this.type=t,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(e){return this.sampleSize=e,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(e){return this._count+=e,this._samples++,this._checkSampling(),this}subtractCount(e){return this._count-=e,this._samples++,this._checkSampling(),this}addTime(e){return this._time+=e,this.lastTiming=e,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=sr(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(sr()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var Mt=class{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,t="count"){return this._getOrCreate({name:e,type:t})}get size(){return Object.keys(this.stats).length}reset(){for(let e of Object.values(this.stats))e.reset();return this}forEach(e){for(let t of Object.values(this.stats))e(t)}getTable(){let e={};return this.forEach(t=>{e[t.name]={time:t.time||0,count:t.count||0,average:t.getAverageTime()||0,hz:t.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(t=>this._getOrCreate(t))}_getOrCreate(e){let{name:t,type:n}=e,i=this.stats[t];return i||(e instanceof et?i=e:i=new et(t,n),this.stats[t]=i),i}};var ju=0,$u="Animation Loop",ta={requestAnimationFrame:r=>Qr(r),cancelAnimationFrame:r=>Jr(r)},_t=class r{static defaultAnimationLoopProps={device:null,mobileQuality:void 0,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>{console.error(e)},stats:void 0,autoResizeViewport:!1,animationFrameProvider:ta};device=null;canvas=null;props;animationProps=null;timeline=null;stats;sharedStats;cpuTime;gpuTime;frameRate;display;_needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;_lastFrameTime=0;constructor(e){if(this.props={...r.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new Mt({id:`animation-loop-${ju++}`}),this.sharedStats=ra.luma.stats.get($u),this.frameRate=this.stats.get("Frame Rate"),this.frameRate.setSampleSize(1),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.setProps({autoResizeViewport:e.autoResizeViewport,animationFrameProvider:e.animationFrameProvider}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null),this._stopEventHandling(),this.device?._disableDebugGPUTime()}delete(){this.destroy()}reportError(e){this._error=e,this.props.onError(e),this.props.onError===r.defaultAnimationLoopProps.onError&&typeof window<"u"&&typeof ErrorEvent<"u"&&window.dispatchEvent(new ErrorEvent("error",{error:e,message:e.message}))}setNeedsRedraw(e){return this._needsRedraw=this._needsRedraw||e,this}needsRedraw(){let e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){if("autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),"animationFrameProvider"in e){let t=e.animationFrameProvider||ta;if(t!==this.props.animationFrameProvider){let n=this._animationFrameId!==null;n&&this._cancelAnimationFrame(),this.props.animationFrameProvider=t,n&&this._requestAnimationFrame()}}return this}async start(){if(this._running)return this;this._running=!0;try{let e;if(!this._initialized){if(this._initialized=!0,await this._initDevice(),this._initialize(),!this._running)return null;await this.props.onInitialize(this._getAnimationProps())}return this._running?(e!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(e){let t=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(t),t}}stop(){if(this._running){let e=this.animationProps;this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1,this._lastFrameTime=0,e&&this.props.onFinalize(e)}return this}redraw(e,t=null){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),this._setupFrame(),this.animationProps&&(this.animationProps.animationFrame=t),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(e){return this.timeline=e,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(e=>{this._resolveNextFrame=e})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeViewport(),this.device?._enableDebugGPUTime()}_setDisplay(e){this.display&&(this.display.destroy(),this.display.animationLoop=null),e&&(e.animationLoop=this),this.display=e}_requestAnimationFrame(){this._running&&(this._animationFrameId=this.props.animationFrameProvider.requestAnimationFrame(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(this.props.animationFrameProvider.cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e,t){if(this._running)try{this.redraw(e,t??null),this._requestAnimationFrame()}catch(n){let i=n instanceof Error?n:new Error(String(n));this.reportError(i),this.stop()}}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}let t=this.props.onRender(this._getAnimationProps());this.device&&t!==!1&&this.device.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){let e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");let t=e?.canvas,n=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:t,useDevicePixels:n,timeline:this.timeline,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,animationFrame:null,_mousePosition:null,mobileQuality:this.props.mobileQuality}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:e,height:t,aspect:n}=this._getSizeAndAspect();(e!==this.animationProps.width||t!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),n!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=e,this.animationProps.height=t,this.animationProps.aspect=n,this.animationProps.needsRedraw=this._needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.getDefaultCanvasContext().canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";let t=document.createElement("div");t.style.position="absolute",t.style.left="10px",t.style.bottom="10px",t.style.width="300px",t.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(t);let n=this.props.onAddHTML(t);n&&(t.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[e,t]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),n=e>0&&t>0?e/t:1;return{width:e,height:t,aspect:n}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(e){let t=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let n=t-this._lastFrameTime;n>0&&this.frameRate.addTime(n)}this._lastFrameTime=t,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let e=this.device.commandEncoder._gpuTimeMs;e!==void 0&&(this.gpuTime.addTime(e),this.device.commandEncoder._gpuTimeMs=void 0)}_updateSharedStats(){if(this.stats!==this.sharedStats){for(let e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{let t=this.sharedStats.get(e.name,e.type);t.sampleSize=e.sampleSize,t.time=e.time,t.count=e.count,t.samples=e.samples,t.lastTiming=e.lastTiming,t.lastSampleTime=e.lastSampleTime,t.lastSampleCount=e.lastSampleCount,t._count=e._count,t._time=e._time,t._samples=e._samples,t._startTime=e._startTime,t._timerPending=e._timerPending})}}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove),this.canvas.addEventListener("mouseleave",this._onMouseleave))}_stopEventHandling(){this.canvas?.removeEventListener("mousemove",this._onMousemove),this.canvas?.removeEventListener("mouseleave",this._onMouseleave)}_onMousemove(e){e instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[e.offsetX,e.offsetY])}_onMouseleave(e){this._getAnimationProps()._mousePosition=null}};var na=B(D(),1);function ia(r,e){let t=null,n=e?.device||na.luma.createDevice({id:"animation-loop",adapters:e?.adapters,createCanvasContext:!0}),i=new _t({...e,device:n,async onInitialize(o){Wu(o.animationLoop.device);try{return t=new r(o),await t?.onInitialize(o)}catch(a){console.error(a),t=null;let c=a instanceof Error?a:new Error(String(a));return qu(o.animationLoop.device,c),o.animationLoop.reportError(c),o.animationLoop.stop(),null}},onRender(o){let a=t?.onRender(o),c=e?.onAfterRender?.(o,t);return e?.onAfterRender?a!==!1||c!==!1:a},onFinalize(o){try{t?.onFinalize(o)}finally{t=null}}}),s=i;return s.getAnimationLoopTemplate=()=>t,i.getInfo=()=>this.AnimationLoopTemplateCtor.info,s}function qu(r,e){if(!r)return;let t=r.getDefaultCanvasContext().canvas;if(t instanceof HTMLCanvasElement){t.style.overflow="visible";let n=document.getElementById("animation-loop-error");n?.remove(),n=document.createElement("h1"),n.id="animation-loop-error",n.innerHTML=e.message,n.style.position="absolute",n.style.top="10px",n.style.left="10px",n.style.color="black",n.style.backgroundColor="red",t.parentElement?.appendChild(n)}}function Wu(r){if(!r)return;let e=document.getElementById("animation-loop-error");e&&e.remove()}var Hu={target:[0,0,0],distance:10,yaw:0,pitch:.25,roll:0,minDistance:1,maxDistance:100,minPitch:-Math.PI/2+.01,maxPitch:Math.PI/2-.01,rotateSpeed:.006,zoomSpeed:.001,enabled:!0,enableRotate:!1,enableZoom:!0,enablePan:!1,panModifier:"shift",panSpeed:.0018,autoRotate:!1,autoRotateSpeed:.1},en=class{canvas;props;yaw;pitch;roll;distance;dragging=!1;activePointers=new Map;lastPointer=[0,0];previousPinchDistance=null;previousPinchAngle=null;previousTimeMilliseconds=null;previousCursor;previousTouchAction;constructor(e,t={}){this.canvas=e,this.props={...Hu,...t},this.props.target=[...this.props.target],this.yaw=this.props.yaw,this.pitch=ge(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.roll=this.props.roll,this.distance=ge(this.props.distance,this.props.minDistance,this.props.maxDistance),this.previousCursor=e.style.cursor,this.previousTouchAction=e.style.touchAction,e.style.cursor="grab",e.style.touchAction="none",e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("pointerup",this.handlePointerUp),e.addEventListener("pointercancel",this.handlePointerUp),e.addEventListener("wheel",this.handleWheel,{passive:!1})}update(e){if(this.previousTimeMilliseconds!==null&&this.props.enabled&&this.props.autoRotate&&!this.dragging){let t=Math.min(Math.max(e-this.previousTimeMilliseconds,0)/1e3,.1);this.yaw+=this.props.autoRotateSpeed*t}this.previousTimeMilliseconds=e}getEyePosition(){let e=this.distance*Math.cos(this.pitch);return[this.props.target[0]+e*Math.sin(this.yaw),this.props.target[1]+this.distance*Math.sin(this.pitch),this.props.target[2]+e*Math.cos(this.yaw)]}getUpDirection(){return this.getCameraFrame().up}getCameraFrame(){let e=Math.sin(this.yaw),t=Math.cos(this.yaw),n=Math.sin(this.pitch),i=Math.cos(this.pitch),s=Math.sin(this.roll),o=Math.cos(this.roll),a=[t,0,-e],c=[-n*e,i,-n*t];return{right:[a[0]*o-c[0]*s,a[1]*o-c[1]*s,a[2]*o-c[2]*s],up:[c[0]*o+a[0]*s,c[1]*o+a[1]*s,c[2]*o+a[2]*s]}}setAutoRotate(e){this.props.autoRotate=e}setProps(e){Object.assign(this.props,e),e.enabled===!1&&this.dragging&&this.endPointerInteraction(),e.target&&(this.props.target=[...e.target]),e.yaw!==void 0&&(this.yaw=e.yaw),(e.pitch!==void 0||e.minPitch!==void 0||e.maxPitch!==void 0)&&(this.pitch=ge(e.pitch??this.pitch,this.props.minPitch,this.props.maxPitch)),e.roll!==void 0&&(this.roll=e.roll),(e.distance!==void 0||e.minDistance!==void 0||e.maxDistance!==void 0)&&(this.distance=ge(e.distance??this.distance,this.props.minDistance,this.props.maxDistance))}reset(){this.yaw=this.props.yaw,this.pitch=ge(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.roll=this.props.roll,this.distance=ge(this.props.distance,this.props.minDistance,this.props.maxDistance)}destroy(){this.canvas.removeEventListener("pointerdown",this.handlePointerDown),this.canvas.removeEventListener("pointermove",this.handlePointerMove),this.canvas.removeEventListener("pointerup",this.handlePointerUp),this.canvas.removeEventListener("pointercancel",this.handlePointerUp),this.canvas.removeEventListener("wheel",this.handleWheel),this.endPointerInteraction(),this.canvas.style.cursor=this.previousCursor,this.canvas.style.touchAction=this.previousTouchAction}handlePointerDown=e=>{if(!(!this.props.enabled||e.button!==0||this.activePointers.has(e.pointerId)||this.activePointers.size>=2||this.activePointers.size>0&&e.pointerType!=="touch")){if(this.activePointers.size===0&&this.props.onInteractionStart?.(),this.dragging=!0,this.activePointers.set(e.pointerId,[e.clientX,e.clientY]),this.activePointers.size===1)this.lastPointer=[e.clientX,e.clientY];else{let{center:t,distance:n,angle:i}=this.getMultiPointerState();this.lastPointer=t,this.previousPinchDistance=n,this.previousPinchAngle=n>0?i:null}this.canvas.setPointerCapture(e.pointerId),this.canvas.style.cursor="grabbing"}};handlePointerMove=e=>{if(!this.props.enabled||!this.dragging||!this.activePointers.has(e.pointerId))return;if(this.activePointers.set(e.pointerId,[e.clientX,e.clientY]),this.activePointers.size>1){let{center:i,distance:s,angle:o}=this.getMultiPointerState();this.props.enablePan&&this.panTarget(i[0]-this.lastPointer[0],i[1]-this.lastPointer[1]),this.props.enableZoom&&this.previousPinchDistance&&s>0&&(this.distance=ge(this.distance*this.previousPinchDistance/s,this.props.minDistance,this.props.maxDistance)),this.props.enableRotate&&this.previousPinchAngle!==null&&s>0&&(this.roll+=Yu(o-this.previousPinchAngle)),this.lastPointer=i,this.previousPinchDistance=s,this.previousPinchAngle=s>0?o:null;return}let t=e.clientX-this.lastPointer[0],n=e.clientY-this.lastPointer[1];this.lastPointer=[e.clientX,e.clientY],this.props.enablePan&&e[`${this.props.panModifier}Key`]?this.panTarget(t,n):(this.yaw-=t*this.props.rotateSpeed,this.pitch=ge(this.pitch-n*(this.props.pitchSpeed??this.props.rotateSpeed),this.props.minPitch,this.props.maxPitch))};handlePointerUp=e=>{if(!this.activePointers.has(e.pointerId))return;this.canvas.hasPointerCapture(e.pointerId)&&this.canvas.releasePointerCapture(e.pointerId),this.activePointers.delete(e.pointerId),this.previousPinchDistance=null,this.previousPinchAngle=null;let t=this.activePointers.entries().next().value;if(t){this.lastPointer=t[1];return}this.endPointerInteraction()};endPointerInteraction(){this.dragging=!1;for(let e of this.activePointers.keys())this.canvas.hasPointerCapture(e)&&this.canvas.releasePointerCapture(e);this.activePointers.clear(),this.previousPinchDistance=null,this.previousPinchAngle=null,this.canvas.style.cursor="grab"}getMultiPointerState(){let[e,t]=this.activePointers.values(),n=t[0]-e[0],i=t[1]-e[1];return{center:[(e[0]+t[0])/2,(e[1]+t[1])/2],distance:Math.hypot(n,i),angle:Math.atan2(i,n)}}panTarget(e,t){let n=this.distance*this.props.panSpeed,{right:i,up:s}=this.getCameraFrame();this.props.target=[this.props.target[0]+(-i[0]*e+s[0]*t)*n,this.props.target[1]+(-i[1]*e+s[1]*t)*n,this.props.target[2]+(-i[2]*e+s[2]*t)*n]}handleWheel=e=>{if(!this.props.enabled||!this.props.enableZoom)return;e.preventDefault(),this.props.onInteractionStart?.();let t=ge(e.deltaY,-240,240);this.distance=ge(this.distance*Math.exp(t*this.props.zoomSpeed),this.props.minDistance,this.props.maxDistance)}};function ge(r,e,t){return Math.min(Math.max(r,e),t)}function Yu(r){return Math.atan2(Math.sin(r),Math.cos(r))}var P=B(D(),1),st=B(Ie(),1);function oa(r,e){let t={},n="Values";if(r.attributes.length===0&&!r.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let i of r.attributes)if(i){let s=`${i.location} ${i.name}: ${i.type}`;t[`in ${s}`]={[n]:i.stepMode||"vertex"}}for(let i of r.varyings||[]){let s=`${i.location} ${i.name}`;t[`out ${s}`]={[n]:JSON.stringify(i)}}return t}var aa="__debugFramebufferState";function ua(r,e,t){if(r.device.type!=="webgl")return;let n=Zu(r.device);if(!n.flushing){if(Ju(r)){Xu(r,t,n);return}e&&Qu(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function Xu(r,e,t){if(t.queuedFramebuffers.length===0)return;let n=r.device,{gl:i}=n,s=i.getParameter(36010),o=i.getParameter(36006),[a,c]=r.device.getDefaultCanvasContext().getDrawingBufferSize(),u=ca(e.top,8),h=ca(e.left,8);t.flushing=!0;try{for(let l of t.queuedFramebuffers){let[d,p,f,m,g]=Ku({framebuffer:l,targetWidth:a,targetHeight:c,topPx:u,leftPx:h,minimap:e.minimap});i.bindFramebuffer(36008,l.handle),i.bindFramebuffer(36009,null),i.blitFramebuffer(0,0,l.width,l.height,d,p,f,m,16384,9728),u+=g+8}}finally{i.bindFramebuffer(36008,s),i.bindFramebuffer(36009,o),t.flushing=!1}}function Ku(r){let{framebuffer:e,targetWidth:t,targetHeight:n,topPx:i,leftPx:s,minimap:o}=r,a=o?Math.max(Math.floor(t/4),1):t,c=o?Math.max(Math.floor(n/4),1):n,u=Math.min(a/e.width,c/e.height),h=Math.max(Math.floor(e.width*u),1),l=Math.max(Math.floor(e.height*u),1),d=s,p=Math.max(n-i-l,0),f=d+h,m=p+l;return[d,p,f,m,l]}function Zu(r){return r.userData[aa]||={flushing:!1,queuedFramebuffers:[]},r.userData[aa]}function Qu(r){return"colorAttachments"in r}function Ju(r){let e=r.props.framebuffer;return!e||e.handle===null}function ca(r,e){if(!r)return e;let t=Number.parseInt(r,10);return Number.isFinite(t)?t:e}function At(r,e,t){if(r===e)return!0;if(!t||!r||!e)return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!At(r[n],e[n],t-1))return!1;return!0}if(Array.isArray(e))return!1;if(typeof r=="object"&&typeof e=="object"){let n=Object.keys(r),i=Object.keys(e);if(n.length!==i.length)return!1;for(let s of n)if(!e.hasOwnProperty(s)||!At(r[s],e[s],t-1))return!1;return!0}return!1}var ha=B(D(),1),tn=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return(0,ha.getBufferLayoutAttributeNames)(e)}mergeBufferLayouts(e,t){let n=[...e];for(let i of t){let s=n.findIndex(o=>o.name===i.name);s<0?n.push(i):n[s]=i}return n}};var Fe=B(D(),1);function Ai(r,e){let t=(0,Fe.getShaderAttributeLocationMap)(r),n=e.slice();return n.sort((i,s)=>{let o=(0,Fe.getMinimumAttributeLocation)((0,Fe.getBufferLayoutAttributeNames)(i).map(c=>t[c])),a=(0,Fe.getMinimumAttributeLocation)((0,Fe.getBufferLayoutAttributeNames)(s).map(c=>t[c]));return o-a}),n}var rn=B(Ie(),1);function It(r,e){if(!r||!e.some(n=>n.bindingLayout?.length))return r;let t={...r,bindings:r.bindings.map(n=>({...n}))};"attributes"in(r||{})&&(t.attributes=r?.attributes||[]);for(let n of e)for(let i of n.bindingLayout||[])for(let s of eh(i.name)){let o=t.bindings.find(a=>a.name===s);o?.group===0&&(o.group=i.group),o&&i.visibility!==void 0&&(o.visibility=i.visibility)}return t}function la(r,e,t=[]){return r?e?{...r,attributes:r.attributes.length?nh(r.attributes,e.attributes.filter(n=>t.includes(n.name))):e.attributes,bindings:rh(r.bindings,e.bindings)}:r:e}function tt(r){return!!(r.uniformTypes&&!th(r.uniformTypes))}function da(r){let e=[];for(let t of r){let n=(0,rn.getShaderModuleUniformBlockName)(t),i=new Set([t.vs,t.fs].flatMap(o=>o?(0,rn.getGLSLUniformBlocks)(o).filter(a=>a.isStd140).map(a=>a.blockName):[])),s=i.has(n)?n:i.size===1?i.values().next().value:void 0;tt(t)&&s&&e.push({name:s,uniformTypes:t.uniformTypes})}return e}function nn(r,e){let t=[],n=new Set;for(let i of[...r||[],...e||[]])n.has(i.name)||(n.add(i.name),t.push(i));return t}function eh(r){let e=new Set([r,`${r}Uniforms`]);return r.endsWith("Uniforms")||e.add(`${r}Sampler`),[...e]}function th(r){for(let e in r)return!1;return!0}function rh(r,e){let t=r.map(s=>({...s})),n=new Set(r.map(s=>s.name)),i=new Set(r.map(s=>`${s.group}:${s.location}`));for(let s of e){let o=`${s.group}:${s.location}`;!n.has(s.name)&&!i.has(o)&&t.push({...s})}return t}function nh(r,e){let t=r.map(s=>({...s})),n=new Map(r.map(s=>[s.name,s])),i=new Map(r.map(s=>[s.location,s]));for(let s of e){let o=n.get(s.name);if(o){if(o.type!==s.type||o.location!==s.location)throw new Error(`Shader attribute "${s.name}" conflicts with its inferred type or location`);continue}let a=i.get(s.location);if(a)throw new Error(`Shader attributes "${a.name}" and "${s.name}" both use location ${s.location}`);t.push({...s})}return t}function Pt(r){return{type:r.type,shaderLanguage:r.info.shadingLanguage,shaderLanguageVersion:r.info.shadingLanguageVersion,gpu:r.info.gpu,limits:r.limits,features:r.features}}var Ii={};function X(r="id"){Ii[r]=Ii[r]||1;let e=Ii[r]++;return`${r}-${e}`}var fa=B(D(),1);function Pi(r,e,t){for(let[n,i]of Object.entries(e)){if(!i)continue;if(!i.format)throw new Error(`${r} GPUVector "${n}" requires a format`);let s=t.find(l=>l.name===n);if(!s)throw new Error(`${r} GPUVector "${n}" requires a Model buffer layout`);let o=s.attributes??[];if(o.length>1)throw new Error(`${r} GPUVector "${n}" does not support interleaved layouts`);let a=o[0],c=s.format??a?.format,u=pa(r,n,i.format),h=s.byteStride??u.byteLength;if(c!==i.format||h!==i.byteStride||i.rowByteLength!==u.byteLength)throw new Error(`${r} GPUVector "${n}" must match its Model buffer layout`)}}function Ne(r,e){let t=Object.entries(e).filter(o=>o[1]!==void 0);if(t.length===0)return[];let[n,i]=t[0];for(let[o,a]of t){if(!a.format)throw new Error(`${r} GPUVector "${o}" requires a format`);if(pa(r,o,a.format),a.length!==i.length)throw new Error(`${r} GPUVector "${o}" rows must match "${n}" rows`);if(a.data.length!==i.data.length)throw new Error(`${r} GPUVector chunk counts must align`)}let s=0;return i.data.map((o,a)=>{let c={};for(let[h,l]of t){let d=l.data[a];if(!d||d.length!==o.length)throw new Error(`${r} GPUVector chunk ${a} row counts must align`);if(d.format!==l.format||d.byteStride!==l.byteStride||d.rowByteLength!==l.rowByteLength)throw new Error(`${r} GPUVector "${h}" chunk layout must be stable`);c[h]=d}let u={batchIndex:a,rowIndexOffset:s,rowCount:o.length,data:c};return s+=o.length,u})}function pa(r,e,t){if(t.includes("<"))throw new Error(`${r} GPUVector "${e}" requires a fixed-width scalar format`);return fa.vertexFormatDecoder.getVertexFormatInfo(t)}var sn=B(D(),1);function Pe(r){let e;for(let t of Object.values(r)){if(!t||"isConstant"in t)continue;let n=0;for(let i of t.data)n+=i.length;if((0,sn.assert)(n===t.length),e){(0,sn.assert)(t.length===e.length&&t.data.length===e.data.length);for(let i=0;i<t.data.length;i++)(0,sn.assert)(t.data[i].length===e.data[i].length)}else e=t}}function ga(r,e,t,n,i){let s=e.inputs,o=t.inputs,a=e.sourceLayouts,c=t.sourceLayouts,u=t.stepMode,h=e.batchCount,l=t.batchCount,d=Array.from({length:h},(v,w)=>e.getBatch(w)),p=Array.from({length:l},(v,w)=>t.getBatch(w)),f=ma(d),m=ma(p),g=r.vertexCount,x=r.instanceCount,T=!0;try{let v=r.isInstanced&&t.vertexCount===void 0,w=v?h*l:Math.max(h,l);if(h===0||l===0)return!0;for(let y=0;y<w;y++){let b=v?Math.floor(y/l):Math.min(y,h-1),M=v?y%l:Math.min(y,l-1);e.setInputs(d[b],a,"vertex"),t.setInputs(p[M],c,u),n();let _=e.rowCount!==void 0?f[b]:t.vertexCount!==void 0?m[M]:0;r.setVertexCount(Math.max(0,Math.min(e.rowCount??t.vertexCount??g,g-_))),t.instanceCount!==void 0&&r.setInstanceCount(Math.max(0,Math.min(t.instanceCount,x-m[M]))),!(!r.indexBuffer&&r.vertexCount===0||r.isInstanced&&r.instanceCount===0)&&(T=i()&&T)}}finally{e.setInputs(s,a,"vertex"),t.setInputs(o,c,u),n(),r.setVertexCount(g),r.setInstanceCount(x)}return T}function ma(r){let e=0;return r.map(t=>{let n=e;for(let i of Object.values(t))if(i&&"data"in i){e+=i.length;break}return n})}var se=B(D(),1);var or=class{device;id;inputs={};sourceLayouts;stepMode="vertex";claimedNames=new Set;layouts=[];buffers={};byteOffsets={};constants={};rowCount;vertexCount;instanceCount;constantBuffers={};constructor(e,t){this.device=e,this.id=t}setInputs(e,t,n){Pe(e),this.claimedNames.clear(),this.inputs=e,this.sourceLayouts=t,this.stepMode=n,this.rowCount=void 0,this.vertexCount=void 0,this.instanceCount=void 0;let i=t??Object.entries(e).flatMap(([a,c])=>c&&!ee(c)&&c.bufferLayout?[{...c.bufferLayout,name:a}]:[]),s=[...i,...Object.entries(e).flatMap(([a,c])=>{if(!c||i.some(l=>l.name===a||l.attributes?.some(d=>d.attribute===a)))return[];(0,se.assert)(c.format);let u=c.format,h=ee(c)?0:c.byteStride;return[{name:a,stepMode:n,byteStride:h,attributes:[{attribute:a,format:u,byteOffset:0}]}]})];for(let[a,c]of Object.entries(e))if(c){if(!ee(c)&&!Array.isArray(c.data))throw new TypeError(`Expected a GPU vector or constant for ${a}`);ee(c)||((s.find(l=>l.name===a||l.attributes?.some(d=>d.attribute===a))?.stepMode??n)==="instance"?((0,se.assert)(this.instanceCount===void 0||this.instanceCount===c.length),this.instanceCount=c.length):((0,se.assert)(this.vertexCount===void 0||this.vertexCount===c.length),this.vertexCount=c.length),this.rowCount=n==="instance"?this.instanceCount:this.vertexCount),this.claimedNames.add(a)}this.layouts=s.flatMap(a=>{let c=e[a.name],u=a.attributes??(a.format?[{attribute:a.name,format:a.format,byteOffset:0}]:[]),h=u.filter(d=>ee(e[d.attribute])),l={...a,stepMode:a.stepMode??n};return this.device.type!=="webgpu"||c&&!ee(c)&&c.bufferLayout||!h.length||h.length===u.length?[{...l,byteStride:h.length===u.length&&h.length?0:l.byteStride}]:[{...l,attributes:u.filter(d=>!ee(e[d.attribute]))},{...l,name:`${a.name}-constants`,byteStride:0,attributes:h}]}),this.buffers={},this.byteOffsets={},this.constants={};let o=new Set;for(let a of this.layouts){this.claimedNames.add(a.name);let c=a.attributes??(a.format?[{attribute:a.name,format:a.format,byteOffset:0}]:[]);for(let l of c)this.claimedNames.add(l.attribute);let u=e[a.name];if(u&&!ee(u)){let l=u.bufferLayout||!u.format?0:(c.find(d=>d.attribute===a.name)??c[0])?.byteOffset??0;this.bindVector(a.name,u,l)}let h=0;for(let l of c){let d=e[l.attribute]??(l.attribute===a.name?e[a.name]:void 0);d&&((0,se.assert)(d.format===void 0||d.format===l.format),ee(d)?(this.constants[l.attribute]=ih(d),h=Math.max(h,(l.byteOffset??0)+d.byteLength)):this.buffers[a.name]||this.bindVector(a.name,d,l.byteOffset??0))}if(this.device.type==="webgpu"&&h&&!this.buffers[a.name]){let l=new Uint8Array(Math.ceil(h/4)*4);for(let p of c){let f=e[p.attribute];ee(f)&&l.set(new Uint8Array(f.value.buffer,f.value.byteOffset,f.byteLength),p.byteOffset??0)}let d=this.constantBuffers[a.name];(!d||d.byteLength<l.byteLength)&&(d?.destroy(),d=this.device.createBuffer({id:`${this.id}-${a.name}-constant`,byteLength:l.byteLength,usage:se.Buffer.VERTEX|se.Buffer.COPY_DST|se.Buffer.COPY_SRC}),this.constantBuffers[a.name]=d),d.write(l),this.buffers[a.name]=d,o.add(a.name)}}for(let[a,c]of Object.entries(this.constantBuffers))o.has(a)||(c.destroy(),delete this.constantBuffers[a])}get batchCount(){let e=Object.values(this.inputs).find(t=>t&&!ee(t));return e&&!ee(e)?e.data.length:1}getBatch(e){return Object.fromEntries(Object.entries(this.inputs).map(([t,n])=>{if(!n||ee(n))return[t,n];let i=n.data[e];return[t,{...n,length:i?.length??0,data:i?[i]:[]}]}))}destroy(){for(let e of Object.values(this.constantBuffers))e.destroy();this.constantBuffers={}}bindVector(e,t,n){let i=t.data[0];if(!i)return;let s=i.byteOffset-n;(0,se.assert)(s>=0),this.buffers[e]=i.buffer,this.byteOffsets[e]=s}};function ee(r){return!!(r&&"isConstant"in r&&r.isConstant)}function ih(r){let e=se.vertexFormatDecoder.getVertexFormatInfo(r.format);if(r.format==="unorm10-10-10-2"){let n=r.value[0];return new Float32Array([(n&1023)/1023,(n>>>10&1023)/1023,(n>>>20&1023)/1023,(n>>>30)/3])}let t=Array.from(r.value);if(r.format==="unorm8x4-bgra"&&([t[0],t[2]]=[t[2],t[0]]),e.normalized){let n=r.value.BYTES_PER_ELEMENT*8,i=2**n-1;return new Float32Array(t.map(s=>e.signed?(s+2**(n-1))/i*2-1:s/i))}return e.integer?e.signed?new Int32Array(t):new Uint32Array(t):new Float32Array(t)}var on=B(D(),1),Ci=B(Ie(),1);function Si(r){return(Array.isArray(r)?r.length===0||typeof r[0]=="number":ArrayBuffer.isView(r)&&!(r instanceof DataView))||typeof r=="number"||typeof r=="boolean"}function ya(r,e={}){let t={bindings:{},uniforms:{}};return Object.keys(r).forEach(n=>{let i=r[n];Object.prototype.hasOwnProperty.call(e,n)||Si(i)?t.uniforms[n]=i:t.bindings[n]=i}),t}var K=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;directBindings={};constructor(e,t){Object.assign(this.options,t);let n=(0,Ci.getShaderModuleDependencies)(Object.values(e).filter(sh));for(let i of n)e[i.name]=i;on.log.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[i,s]of Object.entries(e))s&&(this._addModule(s),s.name&&i!==s.name&&!this.options.disableWarnings&&on.log.warn(`Module name: ${i} vs ${s.name}`)())}destroy(){}setProps(e){e.bindings&&Object.assign(this.directBindings,e.bindings);for(let t of Object.keys(e)){if(t==="bindings")continue;let n=t,i=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||on.log.warn(`Module ${t} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(i,o)||i,{uniforms:u,bindings:h}=ya(c,s.uniformTypes);this.moduleUniforms[n]=xa(o,u,s.uniformTypes),this.moduleBindings[n]={...a,...h}}}}getModules(){return Object.values(this.modules)}addModules(e){let t=(0,Ci.getShaderModuleDependencies)(e);for(let n of t){let i=n.name;this.modules[i]||(this.modules[i]=n,this._addModule(n))}}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let t of Object.values(this.moduleBindings))Object.assign(e,t);return Object.assign(e,this.directBindings),e}getModuleBindingValues(e){let t=this.moduleBindings[e];return t?{...t}:{}}getDebugTable(){let e={};for(let[t,n]of Object.entries(this.moduleUniforms))for(let[i,s]of Object.entries(n))e[`${t}.${i}`]={type:this.modules[t].uniformTypes?.[i],value:String(s)};return e}_addModule(e){let t=e.name;this.moduleUniforms[t]=xa({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[t]={}}};function xa(r={},e={},t={}){let n={...r};for(let[i,s]of Object.entries(e))s!==void 0&&(n[i]=Ei(r[i],s,t[i]));return n}function Ei(r,e,t){if(!t||typeof t=="string")return ar(e);if(Array.isArray(t)){if(Ri(e)||!Array.isArray(e))return ar(e);let o=Array.isArray(r)&&!Ri(r)?[...r]:[],a=o.slice();for(let c=0;c<e.length;c++){let u=e[c];u!==void 0&&(a[c]=Ei(o[c],u,t[0]))}return a}if(!Li(e))return ar(e);let n=t,i=Li(r)?r:{},s={...i};for(let[o,a]of Object.entries(e))a!==void 0&&(s[o]=Ei(i[o],a,n[o]));return s}function ar(r){return ArrayBuffer.isView(r)?Array.prototype.slice.call(r):Array.isArray(r)?Ri(r)?r.slice():r.map(t=>t===void 0?void 0:ar(t)):Li(r)?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t===void 0?void 0:ar(t)])):r}function Ri(r){return ArrayBuffer.isView(r)||Array.isArray(r)&&(r.length===0||typeof r[0]=="number")}function Li(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&!ArrayBuffer.isView(r)}function sh(r){return!!r?.dependencies}var cr=globalThis,oh=globalThis.document||{},an=globalThis.process||{},ah=globalThis.console,ch=globalThis.navigator||{};function cn(r){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,t=r||e;return!!(t&&t.indexOf("Electron")>=0)}function ze(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||cn()}var Bi="5.0.0";function St(r,e){if(!r)throw new Error(e||"Assertion failed")}function un(r){if(!r)return 0;let e;switch(typeof r){case"number":e=r;break;case"object":e=r.logLevel||r.priority||0;break;default:return 0}return St(Number.isFinite(e)&&e>=0),e}function Oi(r){let{logLevel:e,message:t}=r;r.logLevel=un(e);let n=r.args?Array.from(r.args):[];for(;n.length&&n.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&n.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let i=typeof r.message;return St(i==="string"||i==="object"),Object.assign(r,{args:n},r.opts)}var Ge=()=>{},rt=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...t){return this._log("warn",0,e,t,{once:!0})}error(e,...t){return this._log("error",0,e,t)}log(e,t,...n){return this._log("log",e,t,n)}info(e,t,...n){return this._log("info",e,t,n)}once(e,t,...n){return this._log("once",e,t,n,{once:!0})}_log(e,t,n,i,s={}){let o=Oi({logLevel:t,message:n,args:this._buildArgs(t,n,i),opts:s});return this._createLogFunction(e,o,s)}_buildArgs(e,t,n){return[e,t,...n]}_createLogFunction(e,t,n){if(!this._shouldLog(t.logLevel))return Ge;let i=this._getOnceTag(n.tag??t.tag??t.message);if((n.once||t.once)&&i!==void 0){if(this._onceCache.has(i))return Ge;this._onceCache.add(i)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=un(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}};function hh(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var ur=class{constructor(e,t,n="sessionStorage"){this.storage=hh(n),this.id=e,this.config=t,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}}_loadConfiguration(){let e={};if(this.storage){let t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}};function ba(r){let e;return r<10?e=`${r.toFixed(2)}ms`:r<100?e=`${r.toFixed(1)}ms`:r<1e3?e=`${r.toFixed(0)}ms`:e=`${(r/1e3).toFixed(2)}s`,e}function Di(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var hr;(function(r){r[r.BLACK=30]="BLACK",r[r.RED=31]="RED",r[r.GREEN=32]="GREEN",r[r.YELLOW=33]="YELLOW",r[r.BLUE=34]="BLUE",r[r.MAGENTA=35]="MAGENTA",r[r.CYAN=36]="CYAN",r[r.WHITE=37]="WHITE",r[r.BRIGHT_BLACK=90]="BRIGHT_BLACK",r[r.BRIGHT_RED=91]="BRIGHT_RED",r[r.BRIGHT_GREEN=92]="BRIGHT_GREEN",r[r.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",r[r.BRIGHT_BLUE=94]="BRIGHT_BLUE",r[r.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",r[r.BRIGHT_CYAN=96]="BRIGHT_CYAN",r[r.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(hr||(hr={}));var lh=10;function va(r){return typeof r!="string"?r:(r=r.toUpperCase(),hr[r]||hr.WHITE)}function ki(r,e,t){return!ze&&typeof r=="string"&&(e&&(r=`\x1B[${va(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${va(t)+lh}m${r}\x1B[49m`)),r}function Fi(r,e=["constructor"]){let t=Object.getPrototypeOf(r),n=Object.getOwnPropertyNames(t),i=r;for(let s of n){let o=i[s];typeof o=="function"&&(e.find(a=>s===a)||(i[s]=o.bind(r)))}}var hn=class{getHighResolutionTimer(){let e;if(ze()&&cr.performance)e=cr?.performance?.now?.();else if("hrtime"in an){let t=an?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=cr?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},oe=new hn;globalThis.Probe=hn;globalThis.probe=oe;var Ct={debug:ze()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Ni={enabled:!0,level:0},Se=class extends rt{constructor({id:e}={id:""}){super({level:0}),this.VERSION=Bi,this._startTs=oe.getHighResolutionTimer(),this._deltaTs=oe.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new ur(`__probe-${this.id}__`,{[this.id]:Ni}),this.timeStamp(`${this.id} started`),Fi(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((oe.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((oe.getHighResolutionTimer()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,t){this._updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){if(!e)throw new Error(t||"Assertion failed")}warn(e,...t){return this._log("warn",0,e,t,{method:Ct.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:Ct.error})}deprecated(e,t){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${t}\` instead`)}removed(e,t){return this.error(`\`${e}\` has been removed. Use \`${t}\` instead`)}probe(e,t,...n){let i=oe.getMemoryUsageMB();if(i!==null){let s=`${i}MB `;typeof t=="function"?t=()=>`${s}${t()}`:typeof t=="string"&&(t=`${s}${t}`)}return this._log("log",e,t,n,{method:Ct.log,time:!0,once:!0})}log(e,t,...n){return this._log("log",e,t,n,{method:Ct.debug})}info(e,t,...n){return this._log("info",e,t,n,{method:console.info})}once(e,t,...n){return this._log("once",e,t,n,{method:Ct.debug||Ct.info,once:!0})}table(e,t,n){return t?this._log("table",e,t,n&&[n]||[],{method:console.table||Ge,tag:fh(t)}):Ge}time(e,t){return this._log("time",e,t,[],{method:console.time?console.time:console.info})}timeEnd(e,t){return this._log("time",e,t,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,t){return this._log("time",e,t,[],{method:console.timeStamp||Ge})}group(e,t,n={collapsed:!1}){let i=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:i})}groupCollapsed(e,t,n={}){return this.group(e,t,Object.assign({},n,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||Ge})}withGroup(e,t,n){this.group(e,t)();try{n()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let n=t.method;St(n),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=oe.getHighResolutionTimer();let i=dh(this.id,t.message,t);return n.bind(console,i,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(Ni),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...Ni};this._storage.setConfiguration({[this.id]:{...t,...e}})}};Se.VERSION=Bi;function dh(r,e,t){if(typeof e=="string"){let n=t.time?Di(ba(t.total)):"";e=t.time?`${r}: ${n} ${e}`:`${r}: ${e}`,e=ki(e,t.color,t.background)}return e}function fh(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}globalThis.probe||(globalThis.probe=oe);var Wg=new Se({id:"@probe.gl/log"});var te=new Se({id:"luma.gl"});var zi={};function Et(r="id"){zi[r]=zi[r]||1;let e=zi[r]++;return`${r}-${e}`}var ph="cpu-hotspot-profiler",Ta="GPU Resource Counts",wa="Resource Counts",Ma="GPU Time and Memory",mh=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],gh=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],yh=mh.flatMap(r=>[`${r} Created`,`${r} Active`]),xh=gh.flatMap(r=>[`${r} Created`,`${r} Active`]),_a=new WeakMap,Aa=new WeakMap,ae=class{static defaultProps={id:"undefined",handle:void 0,_isHandleBorrowed:!1,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}toJSON(){return this.toString()}id;props;userData={};_device;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,n){if(!e)throw new Error("no device");this._device=e,this.props=bh(t,n);let i=this.props.id!=="undefined"?this.props.id:Et(this[Symbol.toStringTag]);this.props.id=i,this.id=i,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=lr(this._device),t=e?Ve():0,n=[this._device.statsManager.getStats(Ta),this._device.statsManager.getStats(wa)],i=Pa(this._device);for(let o of n)Ia(o,i);let s=this.getStatsName();for(let o of n)o.get("Resources Active").decrementCount(),o.get(`${s}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(Ve()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let n=lr(this._device),i=n?Ve():0,s=this._device.statsManager.getStats(Ma);this.allocatedBytes>0&&this.allocatedBytesName&&(s.get("GPU Memory").subtractCount(this.allocatedBytes),s.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),s.get("GPU Memory").addCount(e),s.get(`${t} Memory`).addCount(e),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(Ve()-i)),this.allocatedBytes=e,this.allocatedBytesName=t}trackReferencedMemory(e,t=this.getStatsName()){this.trackAllocatedMemory(e,`External ${t}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let t=lr(this._device),n=t?Ve():0,i=this._device.statsManager.getStats(Ma);i.get("GPU Memory").subtractCount(this.allocatedBytes),i.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(Ve()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=lr(this._device),n=t?Ve():0,i=[this._device.statsManager.getStats(Ta),this._device.statsManager.getStats(wa)],s=Pa(this._device);for(let o of i)Ia(o,s);for(let o of i)o.get("Resources Created").incrementCount(),o.get("Resources Active").incrementCount(),o.get(`${e}s Created`).incrementCount(),o.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(Ve()-n)),vh(this._device,e)}getStatsName(){return Th(this)}};function bh(r,e){let t={...e};for(let n in r)r[n]!==void 0&&(t[n]=r[n]);return t}function Ia(r,e){let t=r.stats,n=!1;for(let c of e)t[c]||(r.get(c),n=!0);let i=Object.keys(t).length,s=_a.get(r);if(!n&&s?.orderedStatNames===e&&s.statCount===i)return;let o={},a=Aa.get(e);a||(a=new Set(e),Aa.set(e,a));for(let c of e)t[c]&&(o[c]=t[c]);for(let[c,u]of Object.entries(t))a.has(c)||(o[c]=u);for(let c of Object.keys(t))delete t[c];Object.assign(t,o),_a.set(r,{orderedStatNames:e,statCount:i})}function Pa(r){return r.type==="webgl"?xh:yh}function lr(r){let e=r.userData[ph];return e?.enabled?e:null}function Ve(){return globalThis.performance?.now?.()??Date.now()}function vh(r,e){let t=lr(r);if(!(!t||!t.activeDefaultFramebufferAcquireDepth))switch(t.transientCanvasResourceCreates=(t.transientCanvasResourceCreates||0)+1,e){case"Texture":t.transientCanvasTextureCreates=(t.transientCanvasTextureCreates||0)+1;break;case"TextureView":t.transientCanvasTextureViewCreates=(t.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":t.transientCanvasSamplerCreates=(t.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":t.transientCanvasFramebufferCreates=(t.transientCanvasFramebufferCreates||0)+1;break;default:break}}function Th(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===ae.prototype)return wh(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function wh(r){let e=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(r):typeof e?.value=="string"?e.value:null}var ye=class r extends ae{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,t){let n={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?n.indexType="uint32":t.data instanceof Uint16Array?n.indexType="uint16":t.data instanceof Uint8Array&&(n.indexType="uint8")),delete n.data,super(e,n,r.defaultProps),this.usage=n.usage||0,this.indexType=n.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,t,n){if(!this.device.props.debug)return;let i=null,s;ArrayBuffer.isView(e)?(i=e,s=e.buffer):s=e;let o=Math.min(e?e.byteLength:n,r.DEBUG_DATA_MAX_LENGTH);if(s===null)this.debugData=new ArrayBuffer(o);else{let a=Math.min(i?.byteOffset||0,s.byteLength),c=Math.max(0,s.byteLength-a),u=Math.min(o,c);this.debugData=new Uint8Array(s,a,u).slice().buffer}}static defaultProps={...ae.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}};var Gi=globalThis.Float16Array;function Sa(){return Gi??Uint16Array}function Ca(r){return!!(Gi&&r===Gi)}function Ea(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),n=r.startsWith("s"),i=Vi[r],[s,o,a]=i||["uint8 ","i32",1];return{signedType:s,primitiveType:o,byteLength:a,normalized:e,integer:t,signed:n}}function Ra(r){let e=r;switch(e){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return e}}function La(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}function Mh(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(Ca(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(Vi).find(n=>e===n[4]);if(!t)throw new Error(e.name);return t[0]}function Ba(r){return Mh(r)}function _h(r){if(r==="float16")return Sa();let e=Vi[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function Oa(r){return _h(r)}var Vi={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]};var Ui=class{getDataTypeInfo(e){return Ea(e)}getNormalizedDataType(e){return Ra(e)}alignTo(e,t){return La(e,t)}getDataType(e){return Ba(e)}getTypedArrayConstructor(e){return Oa(e)}},Da=new Ui;var Z="texture-compression-bc",F="texture-compression-astc",xe="texture-compression-etc2",Ah="texture-compression-etc1-webgl",ln="texture-compression-pvrtc-webgl",ji="texture-compression-atc-webgl",dn="float32-renderable-webgl",$i="float16-renderable-webgl",Ih="rgb9e5ufloat-renderable-webgl",qi="snorm8-renderable-webgl",Ue="norm16-webgl",Wi="norm16-renderable-webgl",Hi="snorm16-renderable-webgl",fn="float32-filterable",ka="float16-filterable-webgl",dr=1,fr=2,Ki=4,Zi=8,Lt=16,mn=5,Na=10,$=dr|fr,pn=dr|Ki,Ce=dr|fr|Ki|Zi,be=dr|fr|Lt,Ph=dr|Ki|Lt,Xi=Ce|Lt,Fa=(fr|Zi|Lt)<<mn,Sh=(fr|Zi)<<mn,J=Lt<<mn,Rt=Xi<<mn,Ch=Ce<<Na,Yi=Lt<<Na;function gn(r){let e=Lh[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var Eh={r8unorm:{webgpu:Ce|J},rg8unorm:{webgpu:Ce|J},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:Xi},"rgba8unorm-srgb":{webgpu:Ce},r8snorm:{render:qi,webgpu:pn|Fa},rg8snorm:{render:qi,webgpu:pn|Fa},"rgb8snorm-webgl":{},rgba8snorm:{render:qi,webgpu:Ph|Sh},r8uint:{webgpu:$|J},rg8uint:{webgpu:$|J},rgba8uint:{webgpu:be},r8sint:{webgpu:$|J},rg8sint:{webgpu:$|J},rgba8sint:{webgpu:be},bgra8unorm:{webgpu:Ce},"bgra8unorm-srgb":{webgpu:Ch},r16unorm:{f:Ue,render:Wi,webgpu:Rt},rg16unorm:{f:Ue,render:Wi,webgpu:Rt},"rgb16unorm-webgl":{f:Ue,render:!1},rgba16unorm:{f:Ue,render:Wi,webgpu:Rt},r16snorm:{f:Ue,render:Hi,webgpu:Rt},rg16snorm:{f:Ue,render:Hi,webgpu:Rt},"rgb16snorm-webgl":{f:Ue,render:!1},rgba16snorm:{f:Ue,render:Hi,webgpu:Rt},r16uint:{webgpu:$|J},rg16uint:{webgpu:$|J},rgba16uint:{webgpu:be},r16sint:{webgpu:$|J},rg16sint:{webgpu:$|J},rgba16sint:{webgpu:be},r16float:{render:$i,filter:"float16-filterable-webgl",webgpu:Ce|J},rg16float:{render:$i,filter:ka,webgpu:Ce|J},rgba16float:{render:$i,filter:ka,webgpu:Xi},r32uint:{webgpu:be},rg32uint:{webgpu:$|Yi},rgba32uint:{webgpu:be},r32sint:{webgpu:be},rg32sint:{webgpu:$|Yi},rgba32sint:{webgpu:be},r32float:{render:dn,filter:fn,webgpu:be},rg32float:{render:!1,filter:fn,webgpu:$|Yi},"rgb32float-webgl":{render:dn,filter:fn},rgba32float:{render:dn,filter:fn,webgpu:be},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:Ih,webgpu:pn},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:dn,webgpu:pn|J},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:Ce|J},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:$|J},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:$},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:$},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:$},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:$},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:$},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:$}},Rh={"bc1-rgb-unorm-webgl":{f:Z},"bc1-rgb-unorm-srgb-webgl":{f:Z},"bc1-rgba-unorm":{f:Z},"bc1-rgba-unorm-srgb":{f:Z},"bc2-rgba-unorm":{f:Z},"bc2-rgba-unorm-srgb":{f:Z},"bc3-rgba-unorm":{f:Z},"bc3-rgba-unorm-srgb":{f:Z},"bc4-r-unorm":{f:Z},"bc4-r-snorm":{f:Z},"bc5-rg-unorm":{f:Z},"bc5-rg-snorm":{f:Z},"bc6h-rgb-ufloat":{f:Z},"bc6h-rgb-float":{f:Z},"bc7-rgba-unorm":{f:Z},"bc7-rgba-unorm-srgb":{f:Z},"etc2-rgb8unorm":{f:xe},"etc2-rgb8unorm-srgb":{f:xe},"etc2-rgb8a1unorm":{f:xe},"etc2-rgb8a1unorm-srgb":{f:xe},"etc2-rgba8unorm":{f:xe},"etc2-rgba8unorm-srgb":{f:xe},"eac-r11unorm":{f:xe},"eac-r11snorm":{f:xe},"eac-rg11unorm":{f:xe},"eac-rg11snorm":{f:xe},"astc-4x4-unorm":{f:F},"astc-4x4-unorm-srgb":{f:F},"astc-5x4-unorm":{f:F},"astc-5x4-unorm-srgb":{f:F},"astc-5x5-unorm":{f:F},"astc-5x5-unorm-srgb":{f:F},"astc-6x5-unorm":{f:F},"astc-6x5-unorm-srgb":{f:F},"astc-6x6-unorm":{f:F},"astc-6x6-unorm-srgb":{f:F},"astc-8x5-unorm":{f:F},"astc-8x5-unorm-srgb":{f:F},"astc-8x6-unorm":{f:F},"astc-8x6-unorm-srgb":{f:F},"astc-8x8-unorm":{f:F},"astc-8x8-unorm-srgb":{f:F},"astc-10x5-unorm":{f:F},"astc-10x5-unorm-srgb":{f:F},"astc-10x6-unorm":{f:F},"astc-10x6-unorm-srgb":{f:F},"astc-10x8-unorm":{f:F},"astc-10x8-unorm-srgb":{f:F},"astc-10x10-unorm":{f:F},"astc-10x10-unorm-srgb":{f:F},"astc-12x10-unorm":{f:F},"astc-12x10-unorm-srgb":{f:F},"astc-12x12-unorm":{f:F},"astc-12x12-unorm-srgb":{f:F},"pvrtc-rgb4unorm-webgl":{f:ln},"pvrtc-rgba4unorm-webgl":{f:ln},"pvrtc-rgb2unorm-webgl":{f:ln},"pvrtc-rgba2unorm-webgl":{f:ln},"etc1-rbg-unorm-webgl":{f:Ah},"atc-rgb-unorm-webgl":{f:ji},"atc-rgba-unorm-webgl":{f:ji},"atc-rgbai-unorm-webgl":{f:ji}},Lh={...Eh,...Rh};var Bh=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,Oh=["rgb","rgba","bgra"],Dh=["depth","stencil"],kh=5,Fh=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Qi=class{isColor(e){return Oh.some(t=>e.startsWith(t))}isDepthStencil(e){return Dh.some(t=>e.startsWith(t))}isCompressed(e){return Fh.some(t=>e.startsWith(t))}getInfo(e){return za(e)}getCapabilities(e){return zh(e)}getWebGPUCapabilities(e){let t=gn(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?kh:0}computeMemoryLayout(e){return Nh(e)}},nt=new Qi;function Nh({format:r,width:e,height:t,depth:n,byteAlignment:i}){let s=nt.getInfo(r),{bytesPerPixel:o,bytesPerBlock:a=o,blockWidth:c=1,blockHeight:u=1,compressed:h=!1}=s,l=h?Math.ceil(e/c):e,d=h?Math.ceil(t/u):t,p=l*a,f=Math.ceil(p/i)*i,m=d,g=f*m*n;return{bytesPerPixel:o,bytesPerRow:f,rowsPerImage:m,depthOrArrayLayers:n,bytesPerImage:f*m,byteLength:g}}function zh(r){let e=gn(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},n=za(r),i=r.startsWith("depth")||r.startsWith("stencil"),s=n?.signed,o=n?.integer,a=n?.webgl,c=!!n?.compressed;return t.render&&=!i&&!c,t.filter&&=!i&&!s&&!o&&!a,t}function za(r){let e=Gh(r);if(nt.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=Uh(r);let n=Vh(r);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}let t=e.packed?null:Bh.exec(r);if(t){let[,n,i,s,o,a]=t,c=`${s}${i}`,u=Da.getDataTypeInfo(c),h=u.byteLength*8,l=n?.length??1,d=[h,l>=2?h:0,l>=3?h:0,l>=4?h:0];e={format:r,attachment:e.attachment,dataType:u.signedType,components:l,channels:n,integer:u.integer,signed:u.signed,normalized:u.normalized,bitsPerChannel:d,bytesPerPixel:u.byteLength*l,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),o==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function Gh(r){let e={...gn(r)},t=e.bytesPerPixel||1,n=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,delete e.webgpu,{...e,format:r,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:t,bitsPerChannel:n,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function Vh(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,n,i]=t;return{blockWidth:Number(n),blockHeight:Number(i)}}return r.startsWith("bc")||r.startsWith("etc1")||r.startsWith("etc2")||r.startsWith("eac")||r.startsWith("atc")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb4")||r.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb2")||r.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function Uh(r){return r.startsWith("bc1")||r.startsWith("bc4")||r.startsWith("etc1")||r.startsWith("etc2-rgb8")||r.startsWith("etc2-rgb8a1")||r.startsWith("eac-r11")||r==="atc-rgb-unorm-webgl"?8:r.startsWith("bc2")||r.startsWith("bc3")||r.startsWith("bc5")||r.startsWith("bc6h")||r.startsWith("bc7")||r.startsWith("etc2-rgba8")||r.startsWith("eac-rg11")||r.startsWith("astc")||r==="atc-rgba-unorm-webgl"||r==="atc-rgbai-unorm-webgl"?16:r.startsWith("pvrtc")?8:16}function pr(r){return typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof VideoFrame<"u"&&r instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas}function yn(r){if(typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas)return{width:r.width,height:r.height};if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return{width:r.naturalWidth,height:r.naturalHeight};if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return{width:r.videoWidth,height:r.videoHeight};if(typeof VideoFrame<"u"&&r instanceof VideoFrame)return{width:r.displayWidth,height:r.displayHeight};throw new Error("Unknown image type")}var je=class r extends ae{static defaultProps={...ae.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,t){t=r.normalizeProps(e,t),super(e,t,r.defaultProps)}static normalizeProps(e,t){return t}};var jh={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},Q=class r extends ae{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,t,n){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=jh[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(t.data)){let i=e.getExternalImageSize(t.data);this.width=i?.width||1,this.height=i?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&te.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=n?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){this.sampler=e instanceof je?e:this.device.createSampler(e)}copyImageData(e){let{data:t,depth:n,...i}=e;this.writeData(t,{...i,depthOrArrayLayers:i.depthOrArrayLayers??n})}computeMemoryLayout(e={}){let t=this._normalizeTextureReadOptions(e),{width:n=this.width,height:i=this.height,depthOrArrayLayers:s=this.depth}=t,{format:o,byteAlignment:a}=this;return nt.computeMemoryLayout({format:o,width:n,height:i,depth:s,byteAlignment:a})}readBuffer(e,t){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,t){throw new Error("readBuffer not implemented")}writeData(e,t){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,t){let n={...t},{width:i,height:s}=n;return typeof i=="number"&&(n.width=Math.max(1,Math.ceil(i))),typeof s=="number"&&(n.height=Math.max(1,Math.ceil(s))),n}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e){let{data:t,depth:n,...i}=e,s=this._normalizeTextureWriteOptions({...i,depthOrArrayLayers:i.depthOrArrayLayers??n});return{data:t,depth:s.depthOrArrayLayers,...s}}_normalizeCopyExternalImageOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),s=this.device.getExternalImageSize(e.image),o={...r.defaultCopyExternalImageOptions,...i,...s,...t};return o.width=Math.min(o.width,i.width-o.x),o.height=Math.min(o.height,i.height-o.y),o.depth=Math.min(o.depth,i.depthOrArrayLayers-o.z),o}_normalizeCopyElementImageOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),s={...r.defaultCopyElementImageOptions,...i,...t};return s.width=Math.min(s.width,i.width-s.x),s.height=Math.min(s.height,i.height-s.y),s.depth=Math.min(s.depth,i.depthOrArrayLayers-s.z),s}_normalizeTextureReadOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),s={...r.defaultTextureReadOptions,...i,...t};return s.width=Math.min(s.width,i.width-s.x),s.height=Math.min(s.height,i.height-s.y),s.depthOrArrayLayers=Math.min(s.depthOrArrayLayers,i.depthOrArrayLayers-s.z),s}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),n=nt.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(n),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return t;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),s={...r.defaultTextureWriteOptions,...i,...t};s.width=Math.min(s.width,i.width-s.x),s.height=Math.min(s.height,i.height-s.y),s.depthOrArrayLayers=Math.min(s.depthOrArrayLayers,i.depthOrArrayLayers-s.z);let o=nt.computeMemoryLayout({format:this.format,width:s.width,height:s.height,depth:s.depthOrArrayLayers,byteAlignment:this.byteAlignment}),a=o.bytesPerPixel*s.width;if(s.bytesPerRow=t.bytesPerRow??o.bytesPerRow,s.rowsPerImage=t.rowsPerImage??s.height,s.bytesPerRow<a)throw new Error(`bytesPerRow (${s.bytesPerRow}) must be at least ${a} for ${this.format}`);if(s.rowsPerImage<s.height)throw new Error(`rowsPerImage (${s.rowsPerImage}) must be at least ${s.height} for ${this.format}`);let c=this.device.getTextureFormatInfo(this.format).bytesPerPixel;if(c&&s.bytesPerRow%c!==0)throw new Error(`bytesPerRow (${s.bytesPerRow}) must be a multiple of bytesPerPixel (${c}) for ${this.format}`);return s}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),n=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),i=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:n,depthOrArrayLayers:i}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:n,height:i,depthOrArrayLayers:s}=this._getMipLevelSize(t);e+=nt.computeMemoryLayout({format:this.format,width:n,height:i,depth:s,byteAlignment:1}).byteLength}return e*this.samples}static _omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}static defaultProps={...ae.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:r.SAMPLE|r.RENDER|r.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultCopyElementImageOptions={element:void 0,width:void 0,height:void 0,sourceX:0,sourceY:0,sourceWidth:void 0,sourceHeight:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}};function xn(r,e,t){let n=r.bindings.find(i=>i.name===e||`${i.name.toLocaleLowerCase()}uniforms`===e.toLocaleLowerCase());return!n&&!t?.ignoreWarnings&&te.warn(`Binding ${e} not set: Not found in shader layout.`)(),n||null}var Wh=ye.DEBUG_DATA_MAX_LENGTH,G=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:i,ownsBuffer:s=!0,...o}=t;if(i&&i.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(i&&(o.byteLength!==void 0||o.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||i?.id||Et("dynamic-buffer"),c={...o,id:a,usage:o.usage??i?.usage,indexType:o.indexType??i?.indexType};(c.usage||0)&ye.INDEX&&!c.indexType&&(o.data instanceof Uint32Array?c.indexType="uint32":o.data instanceof Uint16Array?c.indexType="uint16":o.data instanceof Uint8Array&&(c.indexType="uint8")),delete c.data,delete c.byteOffset,this.device=e,this.id=a,this.props=c,this.usage=c.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:Wh,this._ownsBuffer=s,this._buffer=i??this.device.createBuffer({...o,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),o.data&&this._writeDebugData(o.data,o.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let i=null;await this._buffer.mapAndWriteAsync(async(s,o)=>{await e(s,o),i=new Uint8Array(s.slice(0,n))},t,n),this._touch(),i&&this._writeDebugData(i,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let i=null,s=await this._buffer.mapAndReadAsync(async(o,a)=>(i=new Uint8Array(o.slice(0)),await e(o,a)),t,n);return i&&this._writeDebugData(i,t)&&this._touch(),s}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let i=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),s=this._buffer,o=this.debugData.slice(0),{data:a,byteOffset:c,...u}=this.props,h=this.device.createBuffer({...u,byteLength:t});return n&&i>0&&this._copyBufferContents(s,h,i),this._buffer=h,this._resetDebugData(t),n&&o.byteLength>0&&this._writeDebugData(o,0),this._ownsBuffer&&s.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let i=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,s=this.device.createCommandEncoder();s.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:i}),this.device.submit(s.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),i=new Uint8Array(this.debugData),s=Math.min(n.byteLength,i.byteLength-t);return i.set(n.subarray(0,s),t),s>0}};function $e(r){return r!==null&&typeof r=="object"&&"buffer"in r}function Ji(r){return r instanceof G?r:$e(r)&&r.buffer instanceof G?r.buffer:null}function Ga(r){return r instanceof G?r.buffer:r}function mr(r){return{buffer:Ga(r.buffer),offset:r.offset,size:r.size}}var es={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function gr(r){return r?Array.isArray(r)?r[0]??null:r:null}function Va(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let n=gr(t);if(!n)return null;let{width:i}=yr(n);return{width:i,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=gr(t);return n?yr(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=gr(t[0]);return n?yr(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let i=t[n],s=gr(i);return s?yr(s):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],i=Object.keys(n)[0]??null;if(!i)return null;let s=gr(n[i]);return s?yr(s):null}default:return null}}function yr(r){if(pr(r))return yn(r);if(typeof r=="object"&&"width"in r&&"height"in r)return{width:r.width,height:r.height};throw new Error("Unsupported mip-level data")}function Hh(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function Yh(r){return ArrayBuffer.isView(r)}function ts(r){let{textureFormat:e,format:t}=r;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function Ua(r){let e=es[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function Xh(r,e){return 6*r+Ua(e)}function rs(r){throw new Error("setTexture1DData not supported in WebGL.")}function Kh(r){return Array.isArray(r)?r:[r]}function it(r,e,t,n){let i=Kh(e),s=r,o=[];for(let a=0;a<i.length;a++){let c=i[a];if(pr(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(Hh(c))o.push({type:"texture-data",data:c,textureFormat:ts(c),z:s,mipLevel:a});else if(Yh(c)&&t)o.push({type:"texture-data",data:{data:c,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function ns(r){let e=[];for(let t=0;t<r.length;t++)e.push(...it(t,r[t]));return e}function is(r){let e=[];for(let t=0;t<r.length;t++)e.push(...it(t,r[t]));return e}function ss(r){let e=[];for(let[t,n]of Object.entries(r)){let i=Ua(t);e.push(...it(i,n))}return e}function os(r){let e=[];return r.forEach((t,n)=>{for(let[i,s]of Object.entries(t)){let o=Xh(n,i);e.push(...it(o,s))}}),e}var ce=class r{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=Et("dynamic-texture"),i=t;this.props={...r.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(i)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?Zh({...t,width:e.width,height:e.height,format:e.format}):[],i="format"in e&&e.format!==void 0,s="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let m=Va(t);return m||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=Qh(this.device,n,a,{format:i?e.format:void 0}),u=c.format??this.props.format,h={...this.props,...a,format:u,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(u)&&!s&&(h.usage=Q.SAMPLE|Q.COPY_DST);let l=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(u);if(this.device.type==="webgpu"&&l){let m=this.props.dimension==="3d"?Q.SAMPLE|Q.STORAGE|Q.COPY_DST|Q.COPY_SRC:Q.SAMPLE|Q.RENDER|Q.COPY_DST|Q.COPY_SRC;h.usage|=m}let d=this.device.getMipLevelCount(h.width,h.height),p=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?d:Math.max(1,Math.min(d,this.props.mipLevels??1)),f={...h,mipLevels:p};this._texture=this.device.createTexture(f),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!l&&te.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),l&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),te.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):te.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof je?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,i=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),o=this.device.createBuffer({byteLength:s.byteLength,usage:ye.COPY_DST|ye.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:i},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,i=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),te.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=es[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=rs(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=it(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=ns(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=is(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=ss(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=os(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:i}=t;switch(t.type){case"external-image":let{image:s,flipY:o}=t;this.texture.copyExternalImage({image:s,z:n,mipLevel:i,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=t;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${i} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:i});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await as(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&te.warn(`${this} already destroyed`)}_checkReady(){this.isReady||te.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...Q.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function Zh(r){if(!r.data)return[];let e=r.width&&r.height?{width:r.width,height:r.height}:void 0,t="format"in r?r.format:void 0;switch(r.dimension){case"1d":return rs(r.data);case"2d":return it(0,r.data,e,t);case"3d":return ns(r.data);case"2d-array":return is(r.data);case"cube":return ss(r.data);case"cube-array":return os(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function Qh(r,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let i=new Map;for(let h of e){let l=i.get(h.z)??[];l.push(h),i.set(h.z,l)}let s=e.some(h=>h.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[h,l]of i){let d=[...l].sort((T,v)=>T.mipLevel-v.mipLevel),p=d[0];if(!p||p.mipLevel!==0)throw new Error(`DynamicTexture: slice ${h} is missing mip level 0`);let f=$a(r,p);if(f.width!==t.width||f.height!==t.height)throw new Error(`DynamicTexture: slice ${h} base level dimensions ${f.width}x${f.height} do not match expected ${t.width}x${t.height}`);let m=ja(p);if(m){if(o&&o!==m)throw new Error(`DynamicTexture: slice ${h} base level format "${m}" does not match texture format "${o}"`);o=m}let g=o&&r.isTextureFormatCompressed(o)?Jh(r,f.width,f.height,o):r.getMipLevelCount(f.width,f.height),x=0;for(let T=0;T<d.length;T++){let v=d[T];if(!v||v.mipLevel!==T||T>=g)break;let w=$a(r,v),y=Math.max(1,f.width>>T),b=Math.max(1,f.height>>T);if(w.width!==y||w.height!==b)break;let M=ja(v);if(M&&(o||(o=M),M!==o))break;x++,c.push(v)}a=Math.min(a,x)}let u=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(h=>h.mipLevel<u),mipLevels:u,format:o,hasExplicitMipChain:s}}function ja(r){if(r.type==="texture-data")return r.textureFormat??ts(r.data)}function $a(r,e){switch(e.type){case"external-image":return r.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function Jh(r,e,t,n){let{blockWidth:i=1,blockHeight:s=1}=r.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,e>>a),u=Math.max(1,t>>a);if(c<i||u<s)break;o++}return o}async function as(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(as));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(as)),n=Object.keys(e),i={};for(let s=0;s<n.length;s++)i[n[s]]=t[s];return i}return r}function ve(r){return r!==null&&typeof r=="object"&&"resolveTextureBinding"in r&&typeof r.resolveTextureBinding=="function"}function el(r){return r?.type==="texture"||r?.type==="external-texture"}function bn(r,e,t){let n=xn(r,e,{ignoreWarnings:!0});return el(n)?n:r.bindings.length===0&&t?.fallbackGroup!==void 0?{type:"texture",name:e,group:t.fallbackGroup,location:0}:null}var Te=2,tl=1e4,cs="render pipeline initialization failed",rl=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],ue=class r{static async createAsync(e,t){let n=!P.PipelineFactory.getAsyncCompilation(e),i=n?P.PipelineFactory.beginAsyncCompilation(e):P.PipelineFactory.getAsyncCompilation(e),s;try{s=new this(e,t)}finally{n&&P.PipelineFactory.endAsyncCompilation(e,i)}try{return n?await Promise.all(i):await s._pipelineInitialization,s}catch(o){throw s.destroy(),o}}static defaultProps={...P.RenderPipeline.defaultProps,gpuVectorCount:"instance",geometry:null,attributeVectors:void 0,source:void 0,sourceLanguage:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:st.ShaderAssembler.getDefaultShaderAssembler("glsl"),debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;_uniformStore;_attributeInfos={};props;geometryVectorBindings;attributeVectorBindings;explicitBufferLayout=[];constructorDrawCounts;constructorDrawOffsets;drawingVectorBatches=!1;indexVector=null;currentAttributes={};currentAttributeByteOffsets={};_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_vertexCountSet=!1;_lastDrawTimestamp=-1;_bindingTable=[];_pipelineInitialization;get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(e,t){this.constructorDrawOffsets={firstVertex:t.firstVertex,firstIndex:t.firstIndex};let n=this.constructor.defaultProps;this.constructorDrawCounts={vertexCount:t.vertexCount??(n.vertexCount||void 0),instanceCount:t.instanceCount??(n.instanceCount||void 0)};let i=n.shaderAssembler,s=Object.hasOwn(t,"vertexCount");this.props={...n,...t,shaderAssembler:t.shaderAssembler??(us(i,e.info.shadingLanguage)?i:st.ShaderAssembler.getDefaultShaderAssembler(e.info.shadingLanguage))},this._vertexCountSet=s,t=this.props,this.id=t.id||X("model"),this.device=e,Object.assign(this.userData,t.userData),this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,this.isInstanced=t.isInstanced??(t.instanceCount?!0:void 0),this.explicitBufferLayout=this.bufferLayout,this.geometryVectorBindings=new or(e,`${this.id}-geometry`),this.attributeVectorBindings=new or(e,`${this.id}-attributes`),this._initializeProps(t);let o=Pt(e),a=(0,st.resolveShaderPlugins)(this.props.plugins,o.shaderLanguage),c=(0,st.mergeShaderPluginModules)(this.props.modules,a.modules),u=Object.fromEntries(c.map(m=>[m.name,m])),h=t.shaderInputs||new K(u,{disableWarnings:this.props.disableWarnings});t.shaderInputs&&a.modules.length>0&&h.addModules(a.modules),this.setShaderInputs(h);let l=nn(this.props.modules,h.getModules()),d={...a.defines,...this.props.defines};if(this.device.type==="webgl"&&(this.props._uniformBlockLayouts=da(l)),this.props.shaderLayout=It(this.props.shaderLayout,l)||null,this.device.type==="webgpu"&&this.props.source){let m=this.props.shaderAssembler;(0,P.assert)(us(m,"wgsl"));let{source:g,getUniforms:x,bindingTable:T,entryPoints:v={},shaderLayout:w}=m.assembleWGSLShader({platformInfo:o,...this.props,modules:l,defines:d,pluginInjections:a.injections,pluginVertexInputs:a.vertexInputs,pluginVaryings:a.varyings});this.source=g,this.props.vertexEntryPoint=v.vertex||this.props.vertexEntryPoint,this.props.fragmentEntryPoint=v.fragment||this.props.fragmentEntryPoint,this._getModuleUniforms=x,this._bindingTable=T;let y=w??e.getShaderLayout?.(this.source),b=nl(y,a.vertexInputs),M=la(this.props.shaderLayout,b,Object.keys(a.vertexInputs));this.props.shaderLayout=It(M||null,l)||null}else{let m=this.props.shaderAssembler;(0,P.assert)(us(m,"glsl"));let{vs:g,fs:x,getUniforms:T}=m.assembleGLSLShaderPair({platformInfo:o,...this.props,modules:l,defines:d,pluginInjections:a.injections,pluginVertexInputs:a.vertexInputs,pluginVaryings:a.varyings});this.vs=g,this.fs=x,this._getModuleUniforms=T,this._bindingTable=[]}this.pipelineFactory=t.pipelineFactory||P.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||P.ShaderFactory.getDefaultShaderFactory(this.device);let f=P.PipelineFactory.getAsyncCompilation(this.device);f?(this._pipelineInitialization=this._initializePipelineAsync(t),f.push(this._pipelineInitialization)):(this.pipeline=this._updatePipeline(),this._initializePipelineResources(t))}_initializeProps(e){e.geometry&&this.setGeometry(e.geometry),e.attributeVectors&&this.setAttributeVectors(e.attributeVectors)}_usesManagedUniformBuffer(e){return!0}async _initializePipelineAsync(e){await this._updatePipelineAsync(),this._initializePipelineResources(e)}_initializeAttributes(){this.applyVectorAttributes(),this.indexVector&&this.bindIndexVector()}_initializePipelineResources(e){this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._initializeAttributes(),e.indexBuffer&&this.setIndexBuffer(e.indexBuffer),e.indexCount!==void 0&&this.setIndexCount(e.indexCount),this.constructorDrawOffsets.firstVertex!==void 0&&(this.firstVertex=this.constructorDrawOffsets.firstVertex),this.constructorDrawOffsets.firstIndex!==void 0&&(this.firstIndex=this.constructorDrawOffsets.firstIndex),e.isInstanced!==void 0&&(this.isInstanced=e.isInstanced),this.constructorDrawCounts.instanceCount!==void 0&&this.setInstanceCount(this.constructorDrawCounts.instanceCount),this.constructorDrawCounts.vertexCount!==void 0&&this.setVertexCount(this.constructorDrawCounts.vertexCount),e.attributes&&this.setAttributes(e.attributes),e.constantAttributes&&this.setConstantAttributes(e.constantAttributes),e.bindings&&this.setBindings(e.bindings),e.transformFeedback&&(this.transformFeedback=e.transformFeedback)}destroy(){this._destroyed||(this.pipeline&&(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs)),this.geometryVectorBindings.destroy(),this.attributeVectorBindings.destroy(),this._uniformStore.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e){if(this.indexVector?.length===0)return this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1,!0;if(!this.drawingVectorBatches&&(this.geometryVectorBindings.batchCount!==1||this.attributeVectorBindings.batchCount!==1))return this.drawVectorGroups(e);if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return P.log.info(Te,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;let t=this._areBindingsLoading();if(t)return P.log.info(Te,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),this.device.type==="webgpu"?(this.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}finally{e.popDebugGroup()}let n,i=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),i=this.pipeline.isErrored,i)P.log.info(Te,`>>> DRAWING ABORTED ${this.id}: ${cs}`)(),n=!1;else{let s=this.vertexArray.getDrawValidationError();if(s)P.log.info(Te,`>>> DRAWING ABORTED ${this.id}: ${s}`)(),this._drawBlockedReason=s,n=!1;else{let o=this._getCurrentShaderLayout(),a=this._getBindings(o),c=this._getBindGroups(o,a),{indexBuffer:u}=this.vertexArray,h=u?this.indexCount??(this._vertexCountSet?this.vertexCount:u.byteLength/(u.indexType==="uint32"?4:2)):void 0;e.setPipeline(this.pipeline),e.setBindings(c,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=this.isInstanced===!0&&this.instanceCount===0?!0:e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:h,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):i?(this._needsRedraw=cs,this._drawBlockedReason=cs):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){e&&this.setTopology(e.topology),this.setGeometryVectors(e?.attributes??{},e?.bufferLayout),this.setIndexVector(e?.indices??null),e?.vertexCount!==void 0&&this.setVertexCount(e.vertexCount)}setGeometryVectors(e,t){t??=this.getExplicitVectorLayouts(e)??this.getExplicitVectorLayouts(e,this.geometryVectorBindings.sourceLayouts),Pe(e),(!this.isInstanced||this.attributeVectorBindings.vertexCount!==void 0)&&Pe([...Object.values(e),...Object.values(this.attributeVectorBindings.inputs)]),this.geometryVectorBindings.setInputs(e,t,"vertex"),this.claimVectorLayouts(this.geometryVectorBindings),this.syncVectorBindings();let n=this.geometryVectorBindings.rowCount;(0,P.assert)(n===void 0||this.attributeVectorBindings.vertexCount===void 0||n===this.attributeVectorBindings.vertexCount),this.setVertexCount(n??this.attributeVectorBindings.vertexCount??0)}setAttributeVectors(e,t){t??=this.getExplicitVectorLayouts(e)??this.getExplicitVectorLayouts(e,this.attributeVectorBindings.sourceLayouts),this.isInstanced===void 0&&(t?.some(s=>s.stepMode==="instance")||Object.values(e).some(s=>s&&"data"in s&&s.bufferLayout?.stepMode==="instance"))&&(this.isInstanced=!0),(!this.isInstanced||Object.entries(e).some(([s,o])=>o&&"data"in o&&(t?.find(a=>a.name===s||a.attributes?.some(c=>c.attribute===s))?.stepMode??o.bufferLayout?.stepMode)==="vertex"))&&Pe([...Object.values(this.geometryVectorBindings.inputs),...Object.values(e)]),this.attributeVectorBindings.setInputs(e,t,this.isInstanced?"instance":"vertex"),this.claimVectorLayouts(this.attributeVectorBindings),this.syncVectorBindings(),this.attributeVectorBindings.instanceCount!==void 0&&this.setInstanceCount(this.attributeVectorBindings.instanceCount);let i=this.attributeVectorBindings.vertexCount;if(i!==void 0){let s=this.geometryVectorBindings.rowCount;(0,P.assert)(s===void 0||s===i),s===void 0&&this.setVertexCount(i)}}setGPUAttributes(e,t){this.setAttributeVectors(e,t)}setIndexVector(e){e&&((0,P.assert)(e.format==="uint8"||e.format==="uint16"||e.format==="uint32"),(0,P.assert)(e.data.length<=1),(0,P.assert)(e.byteStride===(e.format==="uint32"?4:e.format==="uint16"?2:1))),this.indexVector=e,this.vertexArray&&this.bindIndexVector()}bindIndexVector(){let e=this.indexVector,t=e?.data[0];if(t&&this.indexVector){let n=t.buffer instanceof G?t.buffer.buffer:t.buffer;(0,P.assert)(n.indexType===this.indexVector.format&&t.byteOffset%this.indexVector.byteStride===0)}this.indexVector=null,this.setIndexBuffer(t?.buffer??null),this.indexVector=e,this.indexCount=e?.length,this.setDrawOffsets({firstVertex:t?.byteOffset??0,firstIndex:t?t.byteOffset/this.indexVector.byteStride:0})}claimVectorLayouts(e){this.explicitBufferLayout=this.explicitBufferLayout.filter(t=>!e.claimedNames.has(t.name)&&!t.attributes?.some(n=>e.claimedNames.has(n.attribute)))}getExplicitVectorLayouts(e,t=this.explicitBufferLayout){let n=new Set(Object.keys(e)),i=t.filter(s=>n.has(s.name)||s.attributes?.some(o=>n.has(o.attribute)));return i.length?i:void 0}getVectorBufferLayout(){let e=[this.geometryVectorBindings,this.attributeVectorBindings];return[...this.explicitBufferLayout.filter(n=>!e.some(i=>i.claimedNames.has(n.name)||n.attributes?.some(s=>i.claimedNames.has(s.attribute)))),...this.geometryVectorBindings.layouts,...this.attributeVectorBindings.layouts]}syncVectorBindings(){let e=this.getVectorBufferLayout();this.vertexArray?(this.applyBufferLayout(e),this.applyVectorAttributes()):this.bufferLayout=e}applyVectorAttributes(){let e=new Set(this.bufferLayout.map(t=>t.name));for(let t of Object.keys(this.currentAttributes))e.has(t)||delete this.currentAttributes[t];this.setAttributes({...this.currentAttributes,...this.geometryVectorBindings.buffers,...this.attributeVectorBindings.buffers},{byteOffsets:{...this.currentAttributeByteOffsets,...this.geometryVectorBindings.byteOffsets,...this.attributeVectorBindings.byteOffsets},disableWarnings:!0}),this.device.type==="webgl"&&this.setConstantAttributes({...this.geometryVectorBindings.constants,...this.attributeVectorBindings.constants})}setGPUVectors(e,t){let n=Ne(this.id,e);(0,P.assert)(n.length<=1),Pi(this.id,e,this.bufferLayout),n[0]&&this.setGPUData(n[0].data),this.setBatchDrawCount(n[0]?.rowCount??0,t?.count)}drawVectorGroups(e){let t=this.drawingVectorBatches,n=this._vertexCountSet;this.drawingVectorBatches=!0;try{let i=ga(this,this.geometryVectorBindings,this.attributeVectorBindings,()=>this.syncVectorBindings(),()=>r.prototype.draw.call(this,e));return i&&(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1),i}finally{this._vertexCountSet=n,this.drawingVectorBatches=t}}drawBatches(e,{vectors:t,onBatch:n}){let i=Ne(this.id,t);Pi(this.id,t,this.bufferLayout);for(let f of Object.keys(t))(0,P.assert)(!t[f]||this.currentAttributes[f]);let s={...this.currentAttributes},o={...this.currentAttributeByteOffsets},a={...this.bindings},c=this.instanceCount,u=this.vertexCount,h=this.isInstanced,l=this._vertexCountSet,d=this.drawingVectorBatches;this.drawingVectorBatches=!0;let p=!0;try{for(let f of i)this.setGPUData(f.data),this.setBatchDrawCount(f.rowCount),n?.(f),p=r.prototype.draw.call(this,e)&&p}finally{this.setAttributes(s,{byteOffsets:o});for(let f of Object.keys(this.bindings))f in a||delete this.bindings[f];this.setBindings(a),this.setInstanceCount(c),this.setVertexCount(u),this.isInstanced=h,this._vertexCountSet=l,this.drawingVectorBatches=d}return p}setGPUData(e){this.setAttributes(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.buffer])),{byteOffsets:Object.fromEntries(Object.entries(e).map(([t,n])=>{let i=this.bufferLayout.find(o=>o.name===t),s=n.byteOffset-(i?.attributes?.[0]?.byteOffset??0);return(0,P.assert)(s>=0),[t,s]}))})}setBatchDrawCount(e,t=this.props.gpuVectorCount){t==="instance"?this.setInstanceCount(e):t==="vertex"&&this.setVertexCount(e)}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){this.explicitBufferLayout=e;let t=this.geometryVectorBindings,n=this.attributeVectorBindings,i=this.getExplicitVectorLayouts(t.inputs)??t.sourceLayouts,s=this.getExplicitVectorLayouts(n.inputs)??n.sourceLayouts;t.setInputs(t.inputs,i,"vertex"),n.setInputs(n.inputs,s,this.isInstanced?"instance":"vertex"),(!this.isInstanced||n.vertexCount!==void 0)&&Pe([...Object.values(t.inputs),...Object.values(n.inputs)]),this.claimVectorLayouts(t),this.claimVectorLayouts(n),this.applyBufferLayout(this.getVectorBufferLayout())}applyBufferLayout(e){e=Ai(this.pipeline.shaderLayout,e),!At(e,this.bufferLayout,-1)&&(this.bufferLayout=e,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._dynamicAttributeBufferSources={},this.applyVectorAttributes(),this.indexBuffer&&this.vertexArray.setIndexBuffer(this.indexBuffer))}setParameters(e){At(e,this.parameters,2)||(this.parameters=e,this.device.type==="webgl"?this.setNeedsRedraw("parameters"):this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this._vertexCountSet=!0,this.setNeedsRedraw("vertexCount")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new P.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(tt(n)&&this._usesManagedUniformBuffer(t)){let i=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=i}this.setNeedsRedraw("shaderInputs")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this.setBindings(this._getShaderInputBindings()),this.setNeedsRedraw("shaderInputs")}_getShaderInputBindings(){return this.shaderInputs.getBindingValues()}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){this.indexVector&&(this.indexCount=void 0,this.firstVertex=0,this.firstIndex=0),this.indexVector=null;let t=e instanceof G?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof G?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){Object.assign(this.currentAttributes,e);for(let s of Object.keys(e))this.currentAttributeByteOffsets[s]=t?.byteOffsets?.[s]??0;this._drawBlockedReason=!1;let n=t?.disableWarnings??this.props.disableWarnings;e.indices&&P.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=Ai(this.pipeline.shaderLayout,this.bufferLayout);let i=new tn(this.bufferLayout);for(let[s,o]of Object.entries(e)){let a=o instanceof G?o.buffer:o,c=i.getBufferLayout(s);if(!c){n||P.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let u=i.getAttributeNamesForBuffer(c),h=!1;for(let l of u){let d=this._attributeInfos[l];if(d){let p=this.device.type==="webgpu"?this.vertexArray.getBufferSlot(d.bufferName):d.location;if(p===null){n||P.log.warn(`Model(${this.id}): Missing vertex array slot for buffer "${d.bufferName}".`)();continue}let f=t?.byteOffsets?.[s]??0;this.vertexArray.setBuffer(p,a,f),o instanceof G?this._dynamicAttributeBufferSources[p]={source:o,generation:o.generation,byteOffset:f}:delete this._dynamicAttributeBufferSources[p],h=!0}}!h&&!n&&P.log.warn(`Model(${this.id}): Ignoring buffer "${a.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(let[n,i]of Object.entries(e)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,i):(t?.disableWarnings??this.props.disableWarnings)||P.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(ve(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){let t={};for(let[n,i]of Object.entries(this.bindings)){let s=il(n,i,e);s&&(t[n]=s)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){return e.bindings.length?(0,P.normalizeBindingsByGroup)(e,t):{0:t}}_getBindGroupCacheKeys(){return{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(let t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(let t of Object.values(this.bindings))t instanceof P.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof P.Buffer||t instanceof P.Texture||t instanceof P.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):ve(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:$e(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return e}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){let e=this._preparePipelineUpdate();return e&&(this.pipeline=this.pipelineFactory.createRenderPipeline(e.props),this._finishPipelineUpdate(e)),this.pipeline}async _updatePipelineAsync(){let e=this._preparePipelineUpdate();if(e){try{this.pipeline=await this.pipelineFactory.createRenderPipelineAsync(e.props)}catch(t){throw this._releasePipelineShaders(e.vertexShader,e.fragmentShader),this._pipelineNeedsUpdate="asynchronous pipeline creation failed",t}this._finishPipelineUpdate(e)}return this.pipeline}_preparePipelineUpdate(){if(!this._pipelineNeedsUpdate)return null;let e=this.pipeline?.vs??null,t=this.pipeline?.fs??null;this.pipeline&&P.log.log(1,`GPUVectorModel ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),this._pipelineNeedsUpdate=!1;let n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),i=null;return this.source?i=n:this.fs&&(i=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fs,debugShaders:this.props.debugShaders})),{props:{...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:i},vertexShader:n,fragmentShader:i,previousVertexShader:e,previousFragmentShader:t}}_finishPipelineUpdate(e){this._attributeInfos=(0,P.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),this._releasePipelineShaders(e.previousVertexShader,e.previousFragmentShader)}_releasePipelineShaders(e,t){e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=P.log.level>3?0:tl;P.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,P.log.group(Te,`>>> DRAWING MODEL ${this.id}`,{collapsed:P.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=oa(this.pipeline.shaderLayout,this.id);P.log.table(Te,e)();let t=this.shaderInputs.getDebugTable();P.log.table(Te,t)();let n=this._getAttributeDebugTable();P.log.table(Te,this._attributeInfos)(),P.log.table(Te,n)(),P.log.groupEnd(Te)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;let n=e.props.framebuffer;ua(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[t,n]of Object.entries(this._attributeInfos)){let i=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:i?this._getBufferOrConstantValues(i,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:t}=this.vertexArray,n=t.indexType==="uint32"?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){let n=P.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof P.Buffer?new n(e.debugData):e).toString()}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){let e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(let[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer,t.byteOffset),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if(this.device.type!=="webgpu")return;let t=e.framebuffer||e.props.framebuffer,n=e.props,i=n.colorAttachmentFormats??t?.colorAttachments?.map(o=>sl(o?.texture?.format)),s=n.depthStencilAttachmentFormat===!1?void 0:n.depthStencilAttachmentFormat??ol(t?.depthStencilAttachment?.texture?.format);(!At(this._colorAttachmentFormats,i,1)||this._depthStencilAttachmentFormat!==s)&&(this._colorAttachmentFormats=i,this._depthStencilAttachmentFormat=s,this._setPipelineNeedsUpdate("attachment formats"))}};function us(r,e){return r.shaderLanguage!==void 0&&r.shaderLanguage!==e?!1:e==="glsl"?"assembleGLSLShaderPair"in r&&typeof r.assembleGLSLShaderPair=="function":"assembleWGSLShader"in r&&typeof r.assembleWGSLShader=="function"}function nl(r,e){return!r||Object.keys(e).length===0?r:{...r,attributes:r.attributes.map(t=>{let n=t.name.startsWith("_luma_")?t.name.slice(6):null;return n&&e[n]?{...t,name:n}:t})}}function il(r,e,t){if(ve(e)){let n=bn(t,r,{fallbackGroup:0});return n?e.resolveTextureBinding(n):null}return e instanceof G?e.buffer:$e(e)?mr(e):e}function sl(r){return r&&!qa(r)?r:null}function ol(r){return r&&qa(r)?r:void 0}function qa(r){return rl.includes(r)}var hs=B(D(),1);var Bt=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||X("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&hs.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function ls(r,e){if(e instanceof Bt)return e;let t=wt(e),n=al(r,t),{attributes:i,bufferLayout:s}=cl(r,t);return new Bt({topology:t.topology||"triangle-list",bufferLayout:s,vertexCount:t.vertexCount,indices:n,attributes:i})}function al(r,e){if(!e.indices)return;let t=e.indices.value;return r.createBuffer({usage:hs.Buffer.INDEX,data:t})}function cl(r,e){let t={};for(let[n,i]of Object.entries(e.attributes)){let s=e.bufferLayout?.find(o=>o.name===n)?.name||Je(n);i&&(t[s]=r.createBuffer({data:i.value,id:`${n}-buffer`}))}return{attributes:t,bufferLayout:e.bufferLayout||wi(e.attributes),vertexCount:e.vertexCount}}var he=class{attributes;indices;topology;vertexCount;bufferLayout;constructor(e){this.attributes=e.attributes,this.indices=e.indices??null,this.topology=e.topology??"triangle-list",this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout}};var Wa=B(D(),1);function ds(r){let e={};for(let[o,a]of Object.entries(r.attributes)){let c=r.bufferLayout.find(d=>d.name===o),u=c?.format,h=c?.byteStride??(u?Wa.vertexFormatDecoder.getVertexFormatInfo(u).byteLength:0),l=r.indices&&h?Math.floor(a.byteLength/h):r.vertexCount;e[o]={name:o,format:u,length:l,byteStride:h,rowByteLength:h,bufferLayout:c,data:[{buffer:a,byteOffset:0,length:l,format:u,byteStride:h,rowByteLength:h}]}}if(r.indices){let o=Math.min(...Object.values(e).map(a=>a.length));for(let[a,c]of Object.entries(e))e[a]={...c,length:o,data:c.data.map(u=>({...u,length:o}))}}let t=r.indices,n=t?.indexType==="uint32"?4:t?.indexType==="uint8"?1:2,i=t?t.byteLength/n:0,s=t?{name:"indices",format:t.indexType,length:i,byteStride:n,rowByteLength:n,data:[{buffer:t,byteOffset:0,length:i,format:t.indexType,byteStride:n,rowByteLength:n}]}:null;return new he({attributes:e,indices:s,topology:r.topology,vertexCount:r.vertexCount,bufferLayout:r.bufferLayout})}var qe=class extends ue{static defaultProps={...ue.defaultProps,material:void 0};constructor(e,t){let n=t.geometry===void 0?new.target.defaultProps.geometry:t.geometry,i=n&&!(n instanceof he)?ls(e,n):null,s=i?ds(i):n,o={...t,geometry:s instanceof he?s:null};try{super(e,o)}catch(a){throw i?.destroy(),a}this._gpuGeometry=i,i&&this.setIndexCount(this.props.indexCount)}_initializeProps(e){this.material=e.material||null,this._gpuGeometry=null,super._initializeProps(e)}_initializeAttributes(){super._initializeAttributes(),this._gpuGeometry&&super.setIndexCount(this.indexCountOverride)}destroy(){super.destroy(),this._gpuGeometry?.destroy(),this._gpuGeometry=null}setGeometry(e){this._gpuGeometry?.destroy(),this._gpuGeometry=e&&!(e instanceof he)?ls(this.device,e):null;let t=this._gpuGeometry?ds(this._gpuGeometry):e;super.setGeometry(t instanceof he?t:null),e instanceof he||super.setIndexCount(this.indexCountOverride)}setIndexCount(e){this.indexCountOverride=e,super.setIndexCount(e)}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}_usesManagedUniformBuffer(e){return!this.material?.ownsModule(e)}updateShaderInputs(e){super.updateShaderInputs(e),this.material?.updateShaderInputs(e)}_getShaderInputBindings(){let e=super._getShaderInputBindings(),t=this.material;return t?Object.fromEntries(Object.entries(e).filter(([n])=>!t.ownsBinding(n))):e}_areBindingsLoading(){let e=super._areBindingsLoading();if(e)return e;for(let t of Object.values(this.material?.bindings||{}))if(ve(t)&&!t.isReady)return t.id;return!1}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){let n=super._getBindGroups(e,t);for(let[i,s]of Object.entries(this.material?.getBindingsByGroup(e)||{})){let o=Number(i);n[o]={...n[o]||{},...s}}return n}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){return Math.max(super._getBindingsUpdateTimestamp(),this.material?.getBindingsUpdateTimestamp()||0)}};var we=B(D(),1);var Dt=3,Ot=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(e,t={}){this.device=e,this.modules=t.modules||[];let n=new K(Object.fromEntries(this.modules.map(i=>[i.name,i])));this._materialBindingNames=ul(n),this._materialModuleNames=hl(n)}createMaterial(e={}){return new kt(this.device,{...e,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(e){if(this._materialBindingNames.has(e))return!0;let t=fs(e);return t?this._materialModuleNames.has(t):!1}ownsModule(e){return this._materialModuleNames.has(e)}getBindingsByGroup(e){return Object.keys(e).length>0?{[Dt]:e}:{}}};function fs(r){return r.endsWith("Uniforms")?r.slice(0,-8):null}function ul(r){let e=new Set;for(let t of Object.values(r.modules))for(let n of t.bindingLayout||[])n.group===Dt&&e.add(n.name);return e}function hl(r){let e=new Set;for(let t of Object.values(r.modules))t.name&&t.bindingLayout?.some(n=>n.group===Dt&&n.name===t.name)&&e.add(t.name);return e}var kt=class{id;device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};_dynamicResourceGenerations={};constructor(e,t={}){this.id=t.id||X("material"),this.device=e,this.factory=t.factory||new Ot(e,{modules:t.modules||t.shaderInputs?.getModules()||[]});let n=Object.fromEntries((t.shaderInputs?.getModules()||this.factory.modules).map(i=>[i.name,i]));this.shaderInputs=t.shaderInputs||new K(n),this._uniformStore=new we.UniformStore(this.device,this.shaderInputs.modules);for(let[i,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(i)&&tt(s)){let o=this._uniformStore.getManagedUniformBuffer(i);this.bindings[`${i}Uniforms`]=o}this.updateShaderInputs(),t.bindings&&this._replaceOwnedBindings(t.bindings)}destroy(){this._uniformStore.destroy()}clone(e={}){let t=this.factory.createMaterial({id:e.id,shaderInputs:e.shaderInputs,bindings:{...this.getResourceBindings(),...e.bindings}});return e.shaderInputs||t.setProps(this.shaderInputs.getUniformValues()),e.moduleProps&&t.setProps(e.moduleProps),t.updateShaderInputs(),t}ownsBinding(e){return this.factory.ownsBinding(e)}ownsModule(e){return this.factory.ownsModule(e)}setProps(e){this.shaderInputs.setProps(e)}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this._setOwnedBindings(this.shaderInputs.getBindingValues())&&(this._bindGroupCacheToken={})}getResourceBindings(){let e={};for(let[t,n]of Object.entries(this.bindings))fs(t)||(e[t]=n);return e}getBindings(e={bindings:[]}){this._syncDynamicResourceGenerations();let t={},n=t;for(let[i,s]of Object.entries(this.bindings))if(ve(s)){let o=bn(e,i,{fallbackGroup:Dt}),a=o?s.resolveTextureBinding(o):null;a&&(n[i]=a)}else s instanceof G?n[i]=s.buffer:$e(s)?n[i]=mr(s):n[i]=s;return this._syncDynamicResourceGenerations(),t}getBindingsByGroup(e={bindings:[]}){return this.factory.getBindingsByGroup(this.getBindings(e))}getBindGroupCacheKey(e){return this._syncDynamicResourceGenerations(),e===Dt?this._bindGroupCacheToken:null}getBindingsUpdateTimestamp(){let e=0;for(let t of Object.values(this.bindings))t instanceof we.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof we.Buffer||t instanceof we.Texture||t instanceof we.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):ve(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:$e(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return e}_replaceOwnedBindings(e){this._setOwnedBindings(e)&&(this._bindGroupCacheToken={})}_setOwnedBindings(e){let t=!1;for(let[n,i]of Object.entries(e))i!==void 0&&this.ownsBinding(n)&&this.bindings[n]!==i&&(this.bindings[n]=i,t=!0);return t}_syncDynamicResourceGenerations(){let e={},t=!1;for(let[n,i]of Object.entries(this.bindings)){let s=ll(i);s!==null&&(e[n]=s,this._dynamicResourceGenerations[n]!==s&&(t=!0))}Object.keys(e).length!==Object.keys(this._dynamicResourceGenerations).length&&(t=!0),this._dynamicResourceGenerations=e,t&&(this._bindGroupCacheToken={})}};function ll(r){return ve(r)?r.generation:Ji(r)?.generation??null}var Ft=B(D(),1),Ya=B(Ie(),1);var Ha=35980,dl=35981,vn=class r{device;model;transformFeedback;outputVectorBindings={};outputBuffers={};static defaultProps={...ue.defaultProps,inputVectors:void 0,outputVectors:void 0,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,t=r.defaultProps){if(!r.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.outputBuffers=t.feedbackBuffers||{};let{inputVectors:n,outputVectors:i,...s}=t;this.model=new ue(this.device,{id:t.id||"buffer-transform-model",fs:t.fs||(0,Ya.getPassthroughFS)(),topology:t.topology||"point-list",varyings:t.outputs||t.varyings,...s,bufferMode:t.bufferMode||(t.feedbackBufferMode==="interleaved"?Ha:dl)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:t.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),n&&this.model.setGPUVectors(n,{count:"vertex"}),i&&this.setOutputVectors(i)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){let{inputVectors:t,outputVectors:n,inputBuffers:i,outputBuffers:s,...o}=e??{};i&&this.model.setAttributes(i),t&&this.model.setGPUVectors(t,{count:"vertex"}),s&&(this.outputBuffers=s),(s||n||Object.keys(this.outputVectorBindings).length>0)&&this.setOutputVectors(n??this.outputVectorBindings);let a=this.device.beginRenderPass({discard:!0,...o});try{this.model.draw(a)}finally{a.end()}}setOutputVectors(e){let t=Ne(this.model.id,e);(0,Ft.assert)(t.length===0||this.model.pipeline.props.bufferMode!==Ha),(0,Ft.assert)(t.length<=1),this.outputVectorBindings=e,this.transformFeedback.setBuffers({...this.outputBuffers,...Object.fromEntries(Object.entries(t[0]?.data??{}).map(([n,i])=>((0,Ft.assert)(i.byteStride===i.rowByteLength),[n,{buffer:i.buffer instanceof G?i.buffer.buffer:i.buffer,byteOffset:i.byteOffset,byteLength:i.length*i.byteStride}])))})}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof Ft.Buffer)return t.readAsync();let{buffer:n,byteOffset:i=0,byteLength:s=n.byteLength}=t;return n.readAsync(i,s)}};var Xa=B(Ie(),1);var fl="transform_output",Tn=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(e,t){this.device=e;let{inputVectors:n,...i}=t;this.sampler=e.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new ue(this.device,{id:t.id||X("texture-transform-model"),fs:t.fs||(0,Xa.getPassthroughFS)({input:t.targetTextureVarying,inputChannels:t.targetTextureChannels,output:fl}),vertexCount:t.vertexCount,...i}),n&&this.model.setGPUVectors(n,{count:"vertex"}),this._initialize(t),Object.seal(this)}destroy(){this.model.destroy();for(let e of this.bindings)e.framebuffer?.destroy()}delete(){this.destroy()}run(e){let{inputVectors:t,...n}=e??{};t&&this.model.setGPUVectors(t,{count:"vertex"});let{framebuffer:i}=this.bindings[this.currentIndex],s=this.device.beginRenderPass({framebuffer:i,...n});try{this.model.draw(s)}finally{s.end()}this.device.submit()}getTargetTexture(){let{targetTexture:e}=this.bindings[this.currentIndex];return e}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(e){this._updateBindings(e)}_updateBindings(e){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],e)}_updateBinding(e,{sourceBuffers:t,sourceTextures:n,targetTexture:i}){if(e||(e={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(e.sourceTextures,n),Object.assign(e.sourceBuffers,t),i){e.targetTexture=i;let{width:s,height:o}=i;e.framebuffer&&e.framebuffer.destroy(),e.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:s,height:o,colorAttachments:[i]}),e.framebuffer.resize({width:s,height:o})}return e}_setSourceTextureParameters(){let e=this.currentIndex,{sourceTextures:t}=this.bindings[e];for(let n in t)t[n].sampler=this.sampler}};var pl=`struct VertexInputs {
|
|
8
8
|
@location(0) clipSpacePositions: vec2<f32>,
|
|
9
9
|
@location(1) texCoords: vec2<f32>,
|
|
10
10
|
@location(2) coordinates: vec2<f32>
|
|
@@ -26,7 +26,7 @@ fn vertexMain(inputs: VertexInputs) -> FragmentInputs {
|
|
|
26
26
|
outputs.uv = inputs.texCoords;
|
|
27
27
|
return outputs;
|
|
28
28
|
}
|
|
29
|
-
`,
|
|
29
|
+
`,ml=`#version 300 es
|
|
30
30
|
in vec2 clipSpacePositions;
|
|
31
31
|
in vec2 texCoords;
|
|
32
32
|
in vec2 coordinates;
|
|
@@ -41,8 +41,8 @@ void main(void) {
|
|
|
41
41
|
coordinate = coordinates;
|
|
42
42
|
uv = texCoords;
|
|
43
43
|
}
|
|
44
|
-
`,
|
|
45
|
-
${r.source}`),super(e,{id:r.id||z("clip-space"),...r,vs:Vo,vertexCount:a,geometry:new B({topology:n==="triangle"?"triangle-list":"triangle-strip",vertexCount:a,attributes:{clipSpacePositions:{size:2,value:new Float32Array(s)},texCoords:{size:2,value:new Float32Array(o)},coordinates:{size:2,value:new Float32Array(o)}}})})}};var F=L(R(),1);var ct=L(R(),1);var Wi={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function ot(i){return i?Array.isArray(i)?i[0]??null:i:null}function kr(i){let{dimension:e,data:t}=i;if(!t)return null;switch(e){case"1d":{let n=ot(t);if(!n)return null;let{width:r}=at(n);return{width:r,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=ot(t);return n?at(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=ot(t[0]);return n?at(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let r=t[n],s=ot(r);return s?at(s):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],r=Object.keys(n)[0]??null;if(!r)return null;let s=ot(n[r]);return s?at(s):null}default:return null}}function at(i){if((0,ct.isExternalImage)(i))return(0,ct.getExternalImageSize)(i);if(typeof i=="object"&&"width"in i&&"height"in i)return{width:i.width,height:i.height};throw new Error("Unsupported mip-level data")}function Wo(i){return typeof i=="object"&&i!==null&&"data"in i&&"width"in i&&"height"in i}function Ho(i){return ArrayBuffer.isView(i)}function Hi(i){let{textureFormat:e,format:t}=i;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function Nr(i){let e=Wi[i];if(e===void 0)throw new Error(`Invalid cube face: ${i}`);return e}function qo(i,e){return 6*i+Nr(e)}function qi(i){throw new Error("setTexture1DData not supported in WebGL.")}function Ko(i){return Array.isArray(i)?i:[i]}function Te(i,e,t,n){let r=Ko(e),s=i,o=[];for(let a=0;a<r.length;a++){let c=r[a];if((0,ct.isExternalImage)(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(Wo(c))o.push({type:"texture-data",data:c,textureFormat:Hi(c),z:s,mipLevel:a});else if(Ho(c)&&t)o.push({type:"texture-data",data:{data:c,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function Ki(i){let e=[];for(let t=0;t<i.length;t++)e.push(...Te(t,i[t]));return e}function Zi(i){let e=[];for(let t=0;t<i.length;t++)e.push(...Te(t,i[t]));return e}function Qi(i){let e=[];for(let[t,n]of Object.entries(i)){let r=Nr(t);e.push(...Te(r,n))}return e}function Ji(i){let e=[];return i.forEach((t,n)=>{for(let[r,s]of Object.entries(t)){let o=qo(n,r);e.push(...Te(o,s))}}),e}var Z=class i{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=z("dynamic-texture"),r=t;this.props={...i.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(r)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?Zo({...t,width:e.width,height:e.height,format:e.format}):[],r="format"in e&&e.format!==void 0,s="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let b=kr(t);return b||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=Qo(this.device,n,a,{format:r?e.format:void 0}),h=c.format??this.props.format,u={...this.props,...a,format:h,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(h)&&!s&&(u.usage=F.Texture.SAMPLE|F.Texture.COPY_DST);let l=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(h);if(this.device.type==="webgpu"&&l){let b=this.props.dimension==="3d"?F.Texture.SAMPLE|F.Texture.STORAGE|F.Texture.COPY_DST|F.Texture.COPY_SRC:F.Texture.SAMPLE|F.Texture.RENDER|F.Texture.COPY_DST|F.Texture.COPY_SRC;u.usage|=b}let d=this.device.getMipLevelCount(u.width,u.height),f=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?d:Math.max(1,Math.min(d,this.props.mipLevels??1)),p={...u,mipLevels:f};this._texture=this.device.createTexture(p),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!l&&F.log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),l&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),F.log.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):F.log.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof F.Sampler?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=this.device.createBuffer({byteLength:s.byteLength,usage:F.Buffer.COPY_DST|F.Buffer.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:r},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),F.log.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Wi[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=qi(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=Te(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=Ki(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=Zi(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=Qi(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=Ji(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:r}=t;switch(t.type){case"external-image":let{image:s,flipY:o}=t;this.texture.copyExternalImage({image:s,z:n,mipLevel:r,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=t;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${r} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:r});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await en(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&F.log.warn(`${this} already destroyed`)}_checkReady(){this.isReady||F.log.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...F.Texture.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function Zo(i){if(!i.data)return[];let e=i.width&&i.height?{width:i.width,height:i.height}:void 0,t="format"in i?i.format:void 0;switch(i.dimension){case"1d":return qi(i.data);case"2d":return Te(0,i.data,e,t);case"3d":return Ki(i.data);case"2d-array":return Zi(i.data);case"cube":return Qi(i.data);case"cube-array":return Ji(i.data);default:throw new Error(`Unhandled dimension ${i.dimension}`)}}function Qo(i,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let r=new Map;for(let u of e){let l=r.get(u.z)??[];l.push(u),r.set(u.z,l)}let s=e.some(u=>u.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[u,l]of r){let d=[...l].sort((v,y)=>v.mipLevel-y.mipLevel),f=d[0];if(!f||f.mipLevel!==0)throw new Error(`DynamicTexture: slice ${u} is missing mip level 0`);let p=Dr(i,f);if(p.width!==t.width||p.height!==t.height)throw new Error(`DynamicTexture: slice ${u} base level dimensions ${p.width}x${p.height} do not match expected ${t.width}x${t.height}`);let b=Fr(f);if(b){if(o&&o!==b)throw new Error(`DynamicTexture: slice ${u} base level format "${b}" does not match texture format "${o}"`);o=b}let g=o&&i.isTextureFormatCompressed(o)?Jo(i,p.width,p.height,o):i.getMipLevelCount(p.width,p.height),_=0;for(let v=0;v<d.length;v++){let y=d[v];if(!y||y.mipLevel!==v||v>=g)break;let I=Dr(i,y),m=Math.max(1,p.width>>v),x=Math.max(1,p.height>>v);if(I.width!==m||I.height!==x)break;let M=Fr(y);if(M&&(o||(o=M),M!==o))break;_++,c.push(y)}a=Math.min(a,_)}let h=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(u=>u.mipLevel<h),mipLevels:h,format:o,hasExplicitMipChain:s}}function Fr(i){if(i.type==="texture-data")return i.textureFormat??Hi(i.data)}function Dr(i,e){switch(e.type){case"external-image":return i.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function Jo(i,e,t,n){let{blockWidth:r=1,blockHeight:s=1}=i.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,e>>a),h=Math.max(1,t>>a);if(c<r||h<s)break;o++}return o}async function en(i){if(i=await i,Array.isArray(i))return await Promise.all(i.map(en));if(i&&typeof i=="object"&&i.constructor===Object){let e=i,t=await Promise.all(Object.values(e).map(en)),n=Object.keys(e),r={};for(let s=0;s<n.length;s++)r[n[s]]=t[s];return r}return i}var ea={name:"background",uniformTypes:{scale:"vec2<f32>",flipY:"i32"}},ta=`@group(0) @binding(auto) var backgroundTexture: texture_2d<f32>;
|
|
44
|
+
`,gl=[-1,-1,1,-1,-1,1,1,1],yl=[-1,-1,3,-1,-1,3],We=class extends qe{constructor(e,t){let{geometryType:n="quad",...i}=t,s=n==="triangle"?yl:gl,o=s.map(c=>(c+1)/2),a=s.length/2;i.source&&(i.source=`${pl}
|
|
45
|
+
${i.source}`),super(e,{id:i.id||X("clip-space"),...i,vs:ml,vertexCount:a,geometry:new z({topology:n==="triangle"?"triangle-list":"triangle-strip",vertexCount:a,attributes:{clipSpacePositions:{size:2,value:new Float32Array(s)},texCoords:{size:2,value:new Float32Array(o)},coordinates:{size:2,value:new Float32Array(o)}}})})}};var xl={name:"background",uniformTypes:{scale:"vec2<f32>",flipY:"i32"}},bl=`@group(0) @binding(auto) var backgroundTexture: texture_2d<f32>;
|
|
46
46
|
@group(0) @binding(auto) var backgroundTextureSampler: sampler;
|
|
47
47
|
struct backgroundUniforms {
|
|
48
48
|
scale: vec2<f32>,
|
|
@@ -64,7 +64,7 @@ fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4<f32> {
|
|
|
64
64
|
let position: vec2<f32> = billboardTexture_getTextureUV(inputs.uv);
|
|
65
65
|
return textureSample(backgroundTexture, backgroundTextureSampler, position);
|
|
66
66
|
}
|
|
67
|
-
`,
|
|
67
|
+
`,vl=`#version 300 es
|
|
68
68
|
precision highp float;
|
|
69
69
|
|
|
70
70
|
uniform sampler2D backgroundTexture;
|
|
@@ -89,7 +89,7 @@ void main(void) {
|
|
|
89
89
|
vec2 position = billboardTexture_getTextureUV(coordinate);
|
|
90
90
|
fragColor = texture(backgroundTexture, position);
|
|
91
91
|
}
|
|
92
|
-
`,
|
|
92
|
+
`,Nt=class extends We{backgroundTexture=null;flipY=!1;constructor(e,t){if(super(e,{...t,id:t.id||"background-texture-model",source:bl,fs:vl,modules:[...t.modules||[],xl],parameters:{depthWriteEnabled:!1,...t.parameters||{},...t.blend?{blend:!0,blendColorOperation:"add",blendAlphaOperation:"add",blendColorSrcFactor:"one-minus-dst-alpha",blendColorDstFactor:"one",blendAlphaSrcFactor:"one-minus-dst-alpha",blendAlphaDstFactor:"one"}:{}}}),!t.backgroundTexture)throw new Error("BackgroundTextureModel requires a backgroundTexture prop");this.setProps(t)}setProps(e){let{backgroundTexture:t}=e;if(e.flipY!==void 0&&(this.flipY=e.flipY,this.backgroundTexture&&this.updateScale(this.backgroundTexture)),t)if(this.setBindings({backgroundTexture:t}),t.isReady){let n=t instanceof ce?t.texture:t;this.backgroundTexture=n,this.updateScale(n)}else t.ready.then(n=>{this.backgroundTexture=n,this.updateScale(n)})}predraw(e){super.predraw(e)}updateScale(e){if(!e){this.shaderInputs.setProps({background:{scale:[1,1],flipY:0}});return}let[t,n]=this.device.getCanvasContext().getDrawingBufferSize(),i=e.width,s=e.height,o=t/n,a=i/s,c=1,u=1;o>a?u=o/a:c=a/o,this.shaderInputs.setProps({background:{scale:[c,u],flipY:this.flipY?1:0}})}};var wn=class extends z{constructor(e={}){let t=new vt(e);super({...t,attributes:t.attributes})}},Mn=class extends z{constructor(e={}){let t=new er({size:2}),n=new Uint32Array(24),i=[4,5,2,3,0,1];for(let o=0;o<n.length;o++)n[o]=i[Math.floor(o/4)];t.attributes.faceIndex={size:1,value:n},e.indices===!1&&(t.attributes.COLOR_0={size:3,value:new Float32Array(Array.from(t.attributes.POSITION.value,o=>(o+1)/2))});let s=e.indices===!1?$r(t):t;super({id:e.id,topology:t.topology,indices:e.indices===!1?void 0:t.indices,attributes:Ka(s.attributes,e.attributes)})}},zt=class extends z{constructor(e={}){let t=new rr({...e,attributes:void 0,radius:e.radius??1});for(let i of["POSITION","NORMAL"]){let s=t.attributes[i].value;for(let o=0;o<s.length;o+=3){let a=s[o];s[o]=s[o+2],s[o+2]=a}}let n=t.indices?.value;if(n)for(let i=0;i<n.length;i+=3){let s=n[i+1];n[i+1]=n[i+2],n[i+2]=s}super({...t,attributes:{...t.attributes,...e.attributes}})}},_n=class extends z{constructor(e={}){let t=new nr({...e,radius:e.radius??1});super({...t,attributes:t.attributes})}},Gt=class extends z{constructor(e={}){let t=new tr({...e,bottomRadius:e.bottomRadius??1});super({...t,attributes:t.attributes})}},An=class extends Gt{constructor(e={}){let t=e.radius??1;super({...e,topRadius:t,bottomRadius:t})}},He=class extends Gt{constructor(e={}){let t=e.cap??!0;super({...e,topRadius:0,bottomRadius:e.radius??1,topCap:t,bottomCap:t})}},In=class extends z{constructor(e={}){let{type:t="x,y",offset:n=0,flipCull:i=!1}=e,s={"x,y":{sizeX:e.xlen,sizeZ:e.ylen,nx:e.nx,nz:e.ny},"x,z":{sizeX:e.xlen,sizeZ:e.zlen,nx:e.nx,nz:e.nz},"y,z":{sizeX:e.ylen,sizeZ:e.zlen,nx:e.ny,nz:e.nz}}[t];if(!s)throw new Error("Invalid plane axes");let o=new Ze({sizeX:s.sizeX||1,sizeZ:s.sizeZ||1,nx:s.nx||1,nz:s.nz||1});Tl(o,t,n,i);let a=e.unpack?$r(o):o;super({id:e.id,topology:o.topology,indices:e.unpack?void 0:o.indices,attributes:Ka(a.attributes,e.attributes)})}};function Tl(r,e,t,n){let i=r.attributes.POSITION.value,s=r.attributes.NORMAL.value,o=r.attributes.TEXCOORD_0.value;for(let a=0;a<i.length/3;a++){let c=a*3,u=Number(i[c])*(n?-1:1),h=-Number(i[c+2]),l=n?1:-1;e==="x,y"?(i.set([u,h,t],c),s.set([0,0,l],c)):e==="x,z"?(i.set([u,t,h],c),s.set([0,l,0],c)):(i.set([t,u,h],c),s.set([l,0,0],c)),n&&(o[a*2]=1-Number(o[a*2]))}if(e!=="x,z"&&r.indices){let a=r.indices.value;for(let c=0;c<a.length;c+=3){let u=a[c+1];a[c+1]=a[c+2],a[c+2]=u}}}function Ka(r,e={}){let t={};for(let[n,i]of Object.entries(r))i&&(t[n]=i);return{...t,...e}}var wl=.02,Ml=.12,_l=.15,Al=.2,gs=[0,1,0],Il=[255,255,255],Pl=1,ps=.35,ms=255,Sl=1,Cl=.01,El={depthCompare:"less-equal",depthWriteEnabled:!1,cullMode:"none"},Rl=[{name:"instancePosition",format:"float32x3",stepMode:"instance"},{name:"instanceDirection",format:"float32x3",stepMode:"instance"},{name:"instanceScale",format:"float32x3",stepMode:"instance"},{name:"instanceColor",format:"float32x4",stepMode:"instance"}],Ll={name:"lightMarker",props:{},uniforms:{},uniformTypes:{viewProjectionMatrix:"mat4x4<f32>"}},Bl="inputs.positions * inputs.instanceScale",Ol="vec3<f32>(inputs.positions.x * inputs.instanceScale.x, (inputs.positions.y - 0.5) * inputs.instanceScale.y, inputs.positions.z * inputs.instanceScale.z)",Dl="positions * instanceScale",kl="vec3(positions.x * instanceScale.x, (positions.y - 0.5) * instanceScale.y, positions.z * instanceScale.z)",Ye=class extends qe{lightModelProps;_instanceData;_managedBuffers;buildInstanceData;sizePropNames;constructor(e,t,n){let i=n.buildInstanceData(t),s=Za(e,t.id||n.idPrefix,i),o=new K({lightMarker:Ll});o.setProps({lightMarker:{viewProjectionMatrix:Ja(t)}});let{source:a,vs:c,fs:u}=Vl(n.anchorMode),h=t;super(e,{...h,id:t.id||n.idPrefix,source:a,vs:c,fs:u,geometry:n.geometry,shaderInputs:o,bufferLayout:[...Rl],attributes:s,instanceCount:i.instanceCount,parameters:ec(t.parameters)}),this.lightModelProps=t,this._instanceData=i,this._managedBuffers=s,this.buildInstanceData=n.buildInstanceData,this.sizePropNames=n.sizePropNames}destroy(){super.destroy(),Qa(this._managedBuffers),this._managedBuffers={}}draw(e){return this.instanceCount===0?!0:super.draw(e)}setProps(e){this.lightModelProps={...this.lightModelProps,...e},e.parameters&&this.setParameters(ec(this.lightModelProps.parameters)),("viewMatrix"in e||"projectionMatrix"in e)&&(this.shaderInputs.setProps({lightMarker:{viewProjectionMatrix:Ja(this.lightModelProps)}}),this.setNeedsRedraw("lightMarker camera")),Gl(e,this.sizePropNames)&&this.rebuildInstanceData()}rebuildInstanceData(){let e=this.buildInstanceData(this.lightModelProps),t=Za(this.device,this.id,e);this.setAttributes(t),this.setInstanceCount(e.instanceCount),Qa(this._managedBuffers),this._managedBuffers=t,this._instanceData=e}};function tc(r){let e=ic(r.lights),t=ys(r),n=r.pointLightRadius??wl*t.sceneScale*t.markerScale;return bs(e.length,(i,s)=>({color:xs(i),direction:gs,position:i.position,scale:[n,n,n]}),e)}function rc(r){let e=sc(r.lights),t=ys(r),n=r.spotLightLength??Ml*t.sceneScale*t.markerScale;return bs(e.length,(i,s)=>{let o=xr(i.outerConeAngle??Math.PI/4,0,Math.PI/2-Cl),a=Math.tan(o)*n;return{color:xs(i),direction:oc(i.direction),position:i.position,scale:[a,n,a]}},e)}function nc(r){let e=Fl(r.lights),t=ys(r),n=r.directionalLightLength??_l*t.sceneScale*t.markerScale,i=n*Al;return bs(e.length,(s,o)=>{let a=oc(s.direction),c=[t.sceneCenter[0]-a[0]*t.sceneScale*ps,t.sceneCenter[1]-a[1]*t.sceneScale*ps,t.sceneCenter[2]-a[2]*t.sceneScale*ps];return{color:xs(s),direction:a,position:c,scale:[i,n,i]}},e)}function ic(r){return r.filter(e=>e.type==="point")}function sc(r){return r.filter(e=>e.type==="spot")}function Fl(r){return r.filter(e=>e.type==="directional")}function ys(r){let e=Nl(r.lights,r.bounds),t=[(e[0][0]+e[1][0])/2,(e[0][1]+e[1][1])/2,(e[0][2]+e[1][2])/2],n=Math.max(Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1],e[1][2]-e[0][2]),Sl);return{bounds:e,markerScale:Math.max(r.markerScale??Pl,0),sceneCenter:t,sceneScale:n}}function xs(r){let e=r.color||Il,t=Math.max(r.intensity??1,0),n=xr(.35+.3*Math.log10(t+1),.35,1);return[xr(e[0]/ms,0,1)*n,xr(e[1]/ms,0,1)*n,xr(e[2]/ms,0,1)*n,1]}function oc(r){let[e,t,n]=r||gs,i=Math.hypot(e,t,n);return i===0?[...gs]:[e/i,t/i,n/i]}function bs(r,e,t=[]){let n=new Float32Array(r*3),i=new Float32Array(r*3),s=new Float32Array(r*3),o=new Float32Array(r*4);for(let[a,c]of t.entries()){let u=e(c,a);n.set(u.position,a*3),i.set(u.direction,a*3),s.set(u.scale,a*3),o.set(u.color,a*4)}return{instanceCount:r,instancePositions:n,instanceDirections:i,instanceScales:s,instanceColors:o}}function Nl(r,e){if(e)return zl(e);let t=[...ic(r).map(s=>s.position),...sc(r).map(s=>s.position)];if(t.length===0)return[[-.5,-.5,-.5],[.5,.5,.5]];let n=[...t[0]],i=[...t[0]];for(let s of t.slice(1))n[0]=Math.min(n[0],s[0]),n[1]=Math.min(n[1],s[1]),n[2]=Math.min(n[2],s[2]),i[0]=Math.max(i[0],s[0]),i[1]=Math.max(i[1],s[1]),i[2]=Math.max(i[2],s[2]);return[n,i]}function zl(r){return[[...r[0]],[...r[1]]]}function Za(r,e,t){return{instancePosition:r.createBuffer({id:`${e}-instance-position`,data:Pn(t.instancePositions,3)}),instanceDirection:r.createBuffer({id:`${e}-instance-direction`,data:Pn(t.instanceDirections,3)}),instanceScale:r.createBuffer({id:`${e}-instance-scale`,data:Pn(t.instanceScales,3)}),instanceColor:r.createBuffer({id:`${e}-instance-color`,data:Pn(t.instanceColors,4)})}}function Pn(r,e){return r.length>0?r:new Float32Array(e)}function Qa(r){for(let e of Object.values(r))e?.destroy()}function Ja(r){return new C(r.projectionMatrix).multiplyRight(r.viewMatrix)}function Gl(r,e){return"lights"in r||"bounds"in r||"markerScale"in r?!0:e.some(t=>t in r)}function ec(r){return{...El,...r||{}}}function Vl(r){let e=r==="apex"?Ol:Bl,t=r==="apex"?kl:Dl;return{source:`struct lightMarkerUniforms {
|
|
93
93
|
viewProjectionMatrix: mat4x4<f32>,
|
|
94
94
|
};
|
|
95
95
|
|
|
@@ -171,7 +171,7 @@ out vec4 fragColor;
|
|
|
171
171
|
void main(void) {
|
|
172
172
|
fragColor = vColor;
|
|
173
173
|
}
|
|
174
|
-
`}}function ht(i,e,t){return Math.min(t,Math.max(e,i))}var wa=new $e({nlat:8,nlong:12,radius:1}),ni=class extends xe{constructor(e,t){super(e,t,{anchorMode:"centered",buildInstanceData:$r,geometry:wa,idPrefix:"point-light-model",sizePropNames:["pointLightRadius"]})}};var Ta=new ge({cap:!0,nradial:16,nvertical:1,radius:1}),ri=class extends xe{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:Vr,geometry:Ta,idPrefix:"spot-light-model",sizePropNames:["spotLightLength"]})}};var Aa=new ge({cap:!0,nradial:12,nvertical:1,radius:1}),si=class extends xe{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:Xr,geometry:Aa,idPrefix:"directional-light-model",sizePropNames:["directionalLightLength"]})}};function cn(i,e){if(!i)throw new Error(e)}var oe=class{id;matrix=new k;display=!0;position=new q;rotation=new q;scale=new q(1,1,1);userData={};props={};constructor(e={}){let{id:t}=e;this.id=t||z(this.constructor.name),this._setScenegraphNodeProps(e)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(e){return this._setScenegraphNodeProps(e),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(e){return cn(e.length===3,"setPosition requires vector argument"),this.position=e,this}setRotation(e){return cn(e.length===3||e.length===4,"setRotation requires vector argument"),this.rotation=e,this}setScale(e){return cn(e.length===3,"setScale requires vector argument"),this.scale=e,this}setMatrix(e,t=!0){t?this.matrix.copy(e):this.matrix=e}setMatrixComponents(e){let{position:t,rotation:n,scale:r,update:s=!0}=e;return t&&this.setPosition(t),n&&this.setRotation(n),r&&this.setScale(r),s&&this.updateMatrix(),this}updateMatrix(){if(this.matrix.identity(),this.matrix.translate(this.position),this.rotation.length===4){let e=new k().fromQuaternion(this.rotation);this.matrix.multiplyRight(e)}else this.matrix.rotateXYZ(this.rotation);return this.matrix.scale(this.scale),this}update({position:e,rotation:t,scale:n}={}){return e&&this.setPosition(e),t&&this.setRotation(t),n&&this.setScale(n),this.updateMatrix(),this}getCoordinateUniforms(e,t){t=t||this.matrix;let n=new k(e).multiplyRight(t),r=n.invert(),s=r.transpose();return{viewMatrix:e,modelMatrix:t,objectMatrix:t,worldMatrix:n,worldInverseMatrix:r,worldInverseTransposeMatrix:s}}_setScenegraphNodeProps(e){e.display!==void 0&&(this.display=e.display),e?.position&&this.setPosition(e.position),e?.rotation&&this.setRotation(e.rotation),e?.scale&&this.setScale(e.scale),this.updateMatrix(),e?.matrix&&this.setMatrix(e.matrix),Object.assign(this.props,e)}};var qr=L(R(),1);function oi(){return[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]]}function ai(i,e,t){let n=new k(t);for(let r=0;r<8;r++){let s=new q(e[r&1?1:0][0],e[r&2?1:0][1],e[r&4?1:0][2]);n.transformAsPoint(s,s);for(let o=0;o<3;o++)i[0][o]=Math.min(i[0][o],s[o]),i[1][o]=Math.max(i[1][o],s[o])}}function ci(i){return Number.isFinite(i[0][0])}var hi=class i extends oe{children;constructor(e={}){e=Array.isArray(e)?{children:e}:e;let{children:t=[]}=e;qr.log.assert(t.every(n=>n instanceof oe),"every child must an instance of ScenegraphNode"),super(e),this.children=t}getBounds(){let e=oi();return this.traverse((t,{worldMatrix:n})=>{let r=t.getBounds();if(!r)return;let s=new k(n).multiplyRight(t.matrix);ai(e,r,s)}),ci(e)?e:null}destroy(){this.children.forEach(e=>e.destroy()),this.removeAll(),super.destroy()}add(...e){for(let t of e)Array.isArray(t)?this.add(...t):this.children.push(t);return this}remove(e){let t=this.children,n=t.indexOf(e);return n>-1&&t.splice(n,1),this}removeAll(){return this.children=[],this}traverse(e,{worldMatrix:t=new k}={}){if(!this.display)return;let n=new k(t).multiplyRight(this.matrix);for(let r of this.children)r.display&&(r instanceof i?r.traverse(e,{worldMatrix:n}):e(r,{worldMatrix:n}))}traverseDepthSorted(e,{viewMatrix:t,worldMatrix:n=new k,order:r="back-to-front"}){let s=new k(t),o=[];this.traverse((c,h)=>{let u=c.getBounds(),l=u?new q(u[0]).add(u[1]).divide([2,2,2]):new q,d=new k(h.worldMatrix).multiplyRight(c.matrix);d.transformAsPoint(l,l),s.transformAsPoint(l,l),o.push({node:c,context:{worldMatrix:d,bounds:u,depth:-l[2]},index:o.length})},{worldMatrix:new k(n)});let a=r==="back-to-front"?-1:1;o.sort((c,h)=>a*(c.context.depth-h.context.depth)||c.index-h.index);for(let{node:c,context:h}of o)e(c,h)}preorderTraversal(e,{worldMatrix:t=new k}={}){let n=new k(t).multiplyRight(this.matrix);e(this,{worldMatrix:n});for(let r of this.children)r instanceof i?r.preorderTraversal(e,{worldMatrix:n}):e(r,{worldMatrix:n})}};var ui=class extends oe{model;instanceMatrices;bounds=null;managedResources;constructor(e){super(e),this.model=e.model,this.managedResources=e.managedResources||[],this.instanceMatrices=e.instanceMatrices||null,this.bounds=e.bounds?this.instanceMatrices?Pa(e.bounds,this.instanceMatrices):e.bounds:null,this.setProps(e)}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach(e=>e.destroy()),this.managedResources=[]}getBounds(){return this.bounds}draw(e){return this.model.draw(e)}};function Pa(i,e){let t=oi();for(let n of e)ai(t,i,n);return ci(t)?t:null}var K=L(R(),1);function hn(i,e={}){let{angleThreshold:t=30,weldTolerance:n=0,positionAttribute:r="POSITION"}=e,s=Zr(i,r);(0,K.assert)(Number.isFinite(n)&&n>=0),(0,K.assert)(Number.isFinite(t)&&t>=0&&t<=180);let o=i.indices?.value,a=s.value.length/3,c=new Map,h=new Map,u=new Set,l=new Map,d=Math.cos(t*Math.PI/180),f=n*n;function p(v){return[s.value[v*3],s.value[v*3+1],s.value[v*3+2]]}function b(v){let y=c.get(v);if(y!==void 0)return y;(0,K.assert)(Number.isInteger(v)&&v>=0&&v<a);let I=p(v);(0,K.assert)(I.every(Number.isFinite));let m=n>0?I.map(T=>Math.floor(T/n)):I,x=n>0?1:0;for(let T=-x;T<=x;T++)for(let P=-x;P<=x;P++)for(let E=-x;E<=x;E++){let A=h.get(`${m[0]+T},${m[1]+P},${m[2]+E}`);for(let O of A||[]){let C=p(O);if((I[0]-C[0])**2+(I[1]-C[1])**2+(I[2]-C[2])**2<=f)return c.set(v,O),O}}let M=m.join(","),w=h.get(M)||[];return w.push(v),h.set(M,w),c.set(v,v),v}function g(v,y,I){let m=Math.min(v,y),x=Math.max(v,y),M=`${m},${x}`,w=l.get(M);if(w){w.faceCount++;let T=I[0]*w.normal[0]+I[1]*w.normal[1]+I[2]*w.normal[2];w.crease||=T<1-1e-7&&T<=d+1e-7}else l.set(M,{start:m,end:x,normal:I,faceCount:1,crease:!1})}for(let v=0;v<i.vertexCount;v+=3){let y=b(o?.[v]??v),I=b(o?.[v+1]??v+1),m=b(o?.[v+2]??v+2);if(y===I||I===m||m===y)continue;let x=[y,I,m].sort((C,D)=>C-D).join(",");if(u.has(x))continue;u.add(x);let M=p(y),w=p(I),T=p(m),P=w.map((C,D)=>C-M[D]),E=T.map((C,D)=>C-M[D]),A=[P[1]*E[2]-P[2]*E[1],P[2]*E[0]-P[0]*E[2],P[0]*E[1]-P[1]*E[0]],O=Math.hypot(...A);O!==0&&(A[0]/=O,A[1]/=O,A[2]/=O,g(y,I,A),g(I,m,A),g(m,y,A))}let _=[...l.values()].filter(v=>e.includeCoplanarEdges||v.faceCount!==2||v.crease).sort((v,y)=>v.start-y.start||v.end-y.end);return new B({id:`${i.id}-edges`,topology:"line-list",attributes:{[r]:s},indices:new Uint32Array(_.flatMap(v=>[v.start,v.end]))})}function Kr(i,e={}){(0,K.assert)(i.length>0);let t=e.positionAttribute??"POSITION",n=i.map(u=>Zr(u,t)),r=n[0];(0,K.assert)(n.every(u=>u.value.constructor===r.value.constructor&&!!u.normalized==!!r.normalized));let s=r.value.constructor,o=new s(n.reduce((u,l)=>u+l.value.length,0)),a=new Uint32Array(i.reduce((u,l)=>u+l.vertexCount,0)),c=0,h=0;for(let[u,l]of i.entries()){let d=n[u];o.set(d.value,c);for(let f=0;f<l.vertexCount;f++){let p=l.indices?.value[f]??f;(0,K.assert)(Number.isInteger(p)&&p>=0&&p<d.value.length/3),a[h++]=p+c/3}c+=d.value.length}return hn(new B({id:`${i[0].id}-batch`,topology:"triangle-list",attributes:{[t]:{...r,value:o}},indices:a}),e)}function Zr(i,e){let t=i.attributes[e];return(0,K.assert)(i.topology==="triangle-list"&&t?.size===3),(0,K.assert)(t.value.length%3===0&&i.vertexCount%3===0),(0,K.assert)(!t.byteStride||t.byteStride===t.value.BYTES_PER_ELEMENT*3),(0,K.assert)(i.vertexCount>=0&&i.vertexCount<=(i.indices?.value.length??t.value.length/3)),t}var li=L(R(),1);function Qr(i,e={}){let{width:t=1,cap:n="butt",join:r="miter",miterLimit:s=4,roundSegments:o=16}=e;(0,li.assert)(Number.isFinite(t)&&t>=0&&Number.isFinite(s)&&s>=1),(0,li.assert)(Number.isInteger(o)&&o>=2&&o<=256);let a=[];for(let g of i){(0,li.assert)(Number.isFinite(g[0])&&Number.isFinite(g[1])&&Number.isFinite(g[2]??0));let _=a.at(-1);(!_||_[0]!==g[0]||_[1]!==g[1])&&a.push([g[0],g[1],g[2]??0])}e.closed&&a.length>1&&a[0][0]===a.at(-1)[0]&&a[0][1]===a.at(-1)[1]&&a.pop();let c=!!(e.closed&&a.length>2),h=[],u=[],l=t/2;if(a.length>1&&t>0){let g=[],_=[0];for(let y=0;y<a.length-(c?0:1);y++){let I=a[y],m=a[(y+1)%a.length],x=m[0]-I[0],M=m[1]-I[1],w=Math.hypot(x,M);g.push({direction:[x/w,M/w],length:w}),_.push(_.at(-1)+w)}let v=a.map((y,I)=>{let m=g[(I-1+g.length)%g.length],x=g[I%g.length],M=_[I];if(!c&&(I===0||I===a.length-1)){let ie=I===0?x.direction:m.direction,ne=n==="square"?I===0?-l:l:0,Pe=p(y,ie,l,ne,M+ne),Ke=p(y,ie,-l,ne,M+ne);return n==="round"&&b(y,ie,M,I===0),{incomingLeft:Pe,outgoingLeft:Pe,incomingRight:Ke,outgoingRight:Ke}}let w=m.direction,T=x.direction,P=w[0]*T[1]-w[1]*T[0],E=w[0]*T[0]+w[1]*T[1],A={incomingLeft:p(y,w,l,0,M),incomingRight:p(y,w,-l,0,M),outgoingLeft:p(y,T,l,0,M),outgoingRight:p(y,T,-l,0,M)};if(1+E<1e-8)return r==="round"&&(b(y,w,M,!1),b(y,T,M,!0)),A;let O=[-(w[1]+T[1])*l/(1+E),(w[0]+T[0])*l/(1+E)],C=Math.hypot(...O);if(Math.abs(P)<1e-8||r==="miter"&&C<=s*l){let ie=f(y,O,M,l),ne=f(y,[-O[0],-O[1]],M,-l);return{incomingLeft:ie,outgoingLeft:ie,incomingRight:ne,outgoingRight:ne}}let D=Math.sign(P),mt=Math.min(1,Math.min(m.length,x.length)/(2*C)),de=f(y,[O[0]*D*mt,O[1]*D*mt],M,l*D);D>0?(A.incomingLeft=de,A.outgoingLeft=de):(A.incomingRight=de,A.outgoingRight=de);let gt=D>0?A.incomingRight:A.incomingLeft,Mn=D>0?A.outgoingRight:A.outgoingLeft;if(r==="round"){let ie=Math.atan2(P,E),ne=Math.atan2(gt.position[1]-y[1],gt.position[0]-y[0]),Pe=Math.max(1,Math.ceil(Math.abs(ie)/Math.PI*o)),Ke=gt;for(let xt=1;xt<=Pe;xt++){let wn=ne+ie*xt/Pe,Tn=xt===Pe?Mn:f(y,[Math.cos(wn)*l,Math.sin(wn)*l],M,-l*D);d(de,Ke,Tn),Ke=Tn}}else d(de,gt,Mn);return A});g.forEach((y,I)=>{let m=v[I],x=v[(I+1)%v.length],M=c&&I===g.length-1,w=M?{...x.incomingLeft,distance:_.at(-1)}:x.incomingLeft,T=M?{...x.incomingRight,distance:_.at(-1)}:x.incomingRight;d(m.outgoingLeft,m.outgoingRight,w),d(m.outgoingRight,T,w)})}return new B({id:e.id,topology:"triangle-list",attributes:{POSITION:{size:3,value:new Float32Array(h)},TEXCOORD_0:{size:2,value:new Float32Array(u)}}});function d(g,_,v){let y=(_.position[0]-g.position[0])*(v.position[1]-g.position[1])-(_.position[1]-g.position[1])*(v.position[0]-g.position[0]);if(y!==0)for(let I of y>0?[g,_,v]:[g,v,_])h.push(...I.position),u.push(I.distance,I.across)}function f(g,_,v,y){return{position:[g[0]+_[0],g[1]+_[1],g[2]],distance:v,across:y}}function p(g,_,v,y,I){return f(g,[-_[1]*v+_[0]*y,_[0]*v+_[1]*y],I,v)}function b(g,_,v,y){let I={position:g,distance:v,across:0},m=Math.atan2(_[1],_[0])+(y?-Math.PI/2:Math.PI/2),x;for(let M=0;M<=o;M++){let w=m-Math.PI*M/o,T=[Math.cos(w)*l,Math.sin(w)*l],P=f(g,T,v+T[0]*_[0]+T[1]*_[1],-T[0]*_[1]+T[1]*_[0]);x&&d(I,x,P),x=P}}}var dn=L(R(),1),Jr=10,Sa=1e-10;function is(i){let{positions:e,indices:t,attributes:n=[],preserveBoundary:r=!0}=i;(0,dn.assert)(t.length%3===0&&e.length%3===0);let s=Math.max(0,Math.min(t.length,Math.floor((i.targetIndexCount??t.length*(i.targetRatio??.5))/3)*3));if(t.length===0||s>=t.length)return{indices:t.slice(),geometricError:0};let o=e.length/3,a=Array.from({length:o},()=>({quadric:new Float64Array(Jr),neighbors:new Set,boundaryNeighbors:new Set,triangles:new Set,active:!1,version:0})),c=[],h=new Map,u=new Map,l=new pn,d=0,f=0,p=(m,x,M)=>{let w=Math.min(m,x),T=Math.max(m,x),P=w*o+T,A=(h.get(P)||0)+M;A<=0?(h.delete(P),a[m].neighbors.delete(x),a[x].neighbors.delete(m)):(h.set(P,A),a[m].neighbors.add(x),a[x].neighbors.add(m)),A===1?(a[m].boundaryNeighbors.add(x),a[x].boundaryNeighbors.add(m)):(a[m].boundaryNeighbors.delete(x),a[x].boundaryNeighbors.delete(m))},b=m=>{let x=c[m];if(!x.active)return;let[M,w,T]=x.vertices;u.delete(ts(M,w,T)),p(M,w,-1),p(w,T,-1),p(T,M,-1),a[M].triangles.delete(m),a[w].triangles.delete(m),a[T].triangles.delete(m),x.active=!1,d--},g=m=>{let x=c[m],[M,w,T]=x.vertices;if(M===w||w===T||T===M)return!1;let P=ts(M,w,T);return u.has(P)?!1:(u.set(P,m),p(M,w,1),p(w,T,1),p(T,M,1),a[M].triangles.add(m),a[w].triangles.add(m),a[T].triangles.add(m),a[M].active=!0,a[w].active=!0,a[T].active=!0,x.active=!0,d++,!0)};for(let m=0;m<t.length;m+=3){let x=t[m],M=t[m+1],w=t[m+2];(0,dn.assert)(x<o&&M<o&&w<o);let T={vertices:[x,M,w],active:!1},P=c.push(T)-1;g(P)&&Ca(a,e,x,M,w)}let _=(m,x)=>{if(!a[m].active||!a[x].active)return;let M=La(n,m,x);if(Number.isFinite(M))for(let[w,T]of[[m,x],[x,m]]){if(r&&!es(a,e,w,T))continue;let P=Math.max(0,Ea(a,e,m,x,w));l.add({retainedVertex:w,removedVertex:T,retainedVersion:a[w].version,removedVersion:a[T].version,geometricCost:P,cost:P+M})}};for(let m=0;m<a.length;m++)for(let x of a[m].neighbors)m<x&&_(m,x);for(;d*3>s;){let m=l.remove();if(!m)break;let{retainedVertex:x,removedVertex:M}=m,w=a[x],T=a[M];if(!w.active||!T.active||w.version!==m.retainedVersion||T.version!==m.removedVersion||!w.neighbors.has(M)||r&&!es(a,e,x,M)||!Oa(c,a,e,x,M))continue;let P=new Set([x,M,...w.neighbors,...T.neighbors]),E=[...T.triangles];for(let A of E)b(A);for(let A of E){let O=c[A];for(let C=0;C<3;C++)O.vertices[C]===M&&(O.vertices[C]=x);g(A)}for(let A=0;A<Jr;A++)w.quadric[A]+=T.quadric[A];T.active=!1,f=Math.max(f,m.geometricCost);for(let A of P)a[A].version++;for(let A of P)if(a[A].active)for(let O of a[A].neighbors)_(A,O)}let v=t.constructor,y=new v(d*3),I=0;for(let m of c)m.active&&(y[I++]=m.vertices[0],y[I++]=m.vertices[1],y[I++]=m.vertices[2]);return{indices:y,geometricError:Math.sqrt(f)}}function Ca(i,e,t,n,r){let s=fn(e,t,n,r),o=Math.hypot(s[0],s[1],s[2]);if(o===0)return;let a=s[0]/o,c=s[1]/o,h=s[2]/o,u=-(a*e[t*3]+c*e[t*3+1]+h*e[t*3+2]),l=[a,c,h,u];for(let d of[t,n,r]){let f=0;for(let p=0;p<4;p++)for(let b=p;b<4;b++)i[d].quadric[f++]+=l[p]*l[b]}}function Ea(i,e,t,n,r){let s=[e[r*3],e[r*3+1],e[r*3+2],1],o=0,a=0;for(let c=0;c<4;c++)for(let h=c;h<4;h++){let u=i[t].quadric[o]+i[n].quadric[o];a+=u*s[c]*s[h]*(c===h?1:2),o++}return a}function La(i,e,t){let n=0;for(let r of i){let s=r.weight??1;if(s===0)continue;let o=r.values instanceof Uint8Array||r.values instanceof Uint16Array||r.values instanceof Uint32Array;for(let a=0;a<r.size;a++){let c=r.values[e*r.size+a]-r.values[t*r.size+a];if(o&&c!==0)return 1/0;n+=c*c*s}}return n}function es(i,e,t,n){let r=i[t].boundaryNeighbors.size>0,s=i[n].boundaryNeighbors.size>0;if(r!==s)return!1;if(!s)return!0;let o=i[n].boundaryNeighbors;if(o.size!==2||!o.has(t))return!1;let a=[...o].find(p=>p!==t);if(a===void 0)return!1;let c=di(e,t,n),h=di(e,a,n),u=un(c),l=un(h),d=[c[1]*h[2]-c[2]*h[1],c[2]*h[0]-c[0]*h[2],c[0]*h[1]-c[1]*h[0]];return c[0]*h[0]+c[1]*h[1]+c[2]*h[2]<=0&&un(d)<=Sa*u*l}function Oa(i,e,t,n,r){for(let s of e[r].triangles){let o=i[s];if(o.vertices.includes(n))continue;let a=fn(t,...o.vertices),c=o.vertices.map(l=>l===r?n:l),h=fn(t,...c);if(a[0]*h[0]+a[1]*h[1]+a[2]*h[2]<=0)return!1}return!0}function fn(i,e,t,n){let r=di(i,t,e),s=di(i,n,e);return[r[1]*s[2]-r[2]*s[1],r[2]*s[0]-r[0]*s[2],r[0]*s[1]-r[1]*s[0]]}function di(i,e,t){return[i[e*3]-i[t*3],i[e*3+1]-i[t*3+1],i[e*3+2]-i[t*3+2]]}function un(i){return i[0]*i[0]+i[1]*i[1]+i[2]*i[2]}function ts(i,e,t){return[i,e,t].sort((n,r)=>n-r).join(":")}var pn=class{entries=[];add(e){this.entries.push(e);let t=this.entries.length-1;for(;t>0;){let n=t-1>>1;if(ln(this.entries[n],e)<=0)break;this.entries[t]=this.entries[n],this.entries[n]=e,t=n}}remove(){let e=this.entries[0],t=this.entries.pop();if(!e||!t||this.entries.length===0)return e;this.entries[0]=t;let n=0;for(;;){let r=n*2+1;if(r>=this.entries.length)break;let s=r+1,o=s<this.entries.length&&ln(this.entries[s],this.entries[r])<0?s:r;if(ln(this.entries[n],this.entries[o])<=0)break;[this.entries[n],this.entries[o]]=[this.entries[o],this.entries[n]],n=o}return e}};function ln(i,e){return i.cost-e.cost||i.retainedVertex-e.retainedVertex||i.removedVertex-e.removedVertex}function ns(){let i=1,e=1;return()=>(i=Math.sin(e*17.23),e=Math.cos(i*27.92),Ra(Math.abs(i*e)*1432.71))}function Ra(i){return i-Math.floor(i)}var ss="";function os(i){ss=i}function fi(i){return ka(i)?i:ss+i}async function as(i,e){let t=new Image,n=fi(i);t.crossOrigin=e?.crossOrigin||"anonymous",t.src=n;try{await t.decode()}catch(r){throw rs("decode",n,r)}try{return e?await createImageBitmap(t,e):await createImageBitmap(t)}catch(r){throw rs("create",n,r)}}async function cs(i,e){return await new Promise((t,n)=>{try{let r=new Image,s=fi(i);r.onload=()=>t(r),r.onerror=()=>n(new Error(`Could not load image ${s}.`)),r.crossOrigin=e?.crossOrigin||"anonymous",r.src=s}catch(r){n(r)}})}function rs(i,e,t){let n=t instanceof Error?t.message:String(t),r=i==="decode"?`Could not decode source image "${e}": ${n}`:`Could not create ImageBitmap from decoded image "${e}": ${n}`;return new Error(r,{cause:t})}function ka(i){return i.startsWith("/")||/^[a-z][a-z\d+\-.]*:/i.test(i)}var Ae=L(R(),1);var pi=class{device;id;destroyed=!1;generation=0;_source;_colorSpace;_sampler;_isReady=!1;_updateTimestamp;_sourceVersion=0;_sourceFrameToken=null;_texture=null;_textureFrameToken=void 0;_externalTexture=null;get source(){return this._source}get isReady(){return this._observeSource(),this._isReady}get updateTimestamp(){return this._observeSource(),this._updateTimestamp}get[Symbol.toStringTag](){return"VideoTexture"}toString(){let e=mn(this._source);return`VideoTexture:"${this.id}":${e.width}x${e.height}px:(${this._isReady?"ready":"loading..."})`}constructor(e,t){(0,Ae.assert)(ut(t?.source)||hs(t?.source)),this.device=e,this.id=t.id||z("video-texture"),this._source=t.source,this._colorSpace=t.colorSpace??"srgb",this._sampler=t.sampler??{},this._updateTimestamp=this.device.incrementTimestamp(),this.setSource(t.source)}setSource(e){(0,Ae.assert)(ut(e)||hs(e)),this._destroyExternalTexture(),this._source=e,this._sourceVersion++,this._sourceFrameToken=null,this._textureFrameToken=void 0,this._observeSource(),this._touchGeneration()}resolveTextureBinding(e){return this._observeSource(),!this._isReady||this.destroyed?null:e.type==="external-texture"&&this.device.type==="webgpu"?this._createNativeExternalTexture():this._resolveCopiedTexture()}setSampler(e){this._sampler=e,this._texture?.setSampler(e),this._externalTexture?.setSampler?.(e),this._touchGeneration()}destroy(){this.destroyed||(this._destroyExternalTexture(),this._texture?.destroy(),this._texture=null,this._textureFrameToken=void 0,this._isReady=!1,this.destroyed=!0,this._touchGeneration())}_resolveCopiedTexture(){let e=this._getOrCreateCopiedTexture();return Object.is(this._textureFrameToken,this._sourceFrameToken)||(e.copyExternalImage({image:this._source,colorSpace:this._colorSpace}),this._textureFrameToken=this._sourceFrameToken),e}_getOrCreateCopiedTexture(){let e=this._getResolvedSize(),t=this._texture;if(t&&t.width===e.width&&t.height===e.height)return t;t?.destroy();let n=this.device.createTexture({id:`${this.id}-texture`,width:e.width,height:e.height,format:"rgba8unorm",usage:Ae.Texture.SAMPLE|Ae.Texture.COPY_DST,mipLevels:1,sampler:this._sampler});return this._texture=n,this._textureFrameToken=void 0,this._touchGeneration(),n}_createNativeExternalTexture(){return this._destroyExternalTexture(),this._externalTexture=this.device.createExternalTexture({id:`${this.id}-external`,source:this._source,colorSpace:this._colorSpace,sampler:this._sampler}),this.generation++,this._externalTexture}_destroyExternalTexture(){this._externalTexture?.destroy(),this._externalTexture=null}_getResolvedSize(){let e=mn(this._source);return(0,Ae.assert)(e.width>0&&e.height>0),e}_observeSource(){if(this.destroyed)return;let e=Na(this._source);if(e!==this._isReady&&(this._isReady=e,this._touch()),!e)return;let t=Fa(this._source,this._sourceVersion);Object.is(t,this._sourceFrameToken)||(this._sourceFrameToken=t,this._touch())}_touch(){this._updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}};function ut(i){return!i||typeof i!="object"?!1:typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement||"videoWidth"in i&&"videoHeight"in i&&"readyState"in i&&"currentTime"in i}function hs(i){return!i||typeof i!="object"?!1:typeof VideoFrame<"u"&&i instanceof VideoFrame||"displayWidth"in i&&"displayHeight"in i&&"timestamp"in i&&!("videoWidth"in i)}function Na(i){let e=mn(i);return e.width<=0||e.height<=0?!1:ut(i)?i.readyState>=2:!0}function mn(i){return ut(i)?{width:i.videoWidth,height:i.videoHeight}:{width:i.displayWidth,height:i.displayHeight}}function Fa(i,e){return ut(i)?`${e}:${i.currentTime}:${i.videoWidth}x${i.videoHeight}`:`${e}:${i.timestamp}:${i.displayWidth}x${i.displayHeight}`}var ce=L(R(),1),xs=L(re(),1);var ae=L(R(),1),Xe=class{id;current;next;constructor(e){this.id=e.id||"swap",this.current=e.current,this.next=e.next}destroy(){this.current?.destroy(),this.next?.destroy()}swap(){let e=this.current;this.current=this.next,this.next=e}},Ye=class extends Xe{constructor(e,t){t={...t};let{width:n=1,height:r=1}=t,s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-0`,format:c,usage:ae.Texture.SAMPLE|ae.Texture.RENDER|ae.Texture.COPY_SRC|ae.Texture.COPY_DST,width:n,height:r})),o=e.createFramebuffer({...t,colorAttachments:s});s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-1`,format:c,usage:ae.Texture.SAMPLE|ae.Texture.RENDER|ae.Texture.COPY_SRC|ae.Texture.COPY_DST,width:n,height:r}));let a=e.createFramebuffer({...t,colorAttachments:s});super({current:o,next:a});for(let[c,h]of(t.colorAttachments||[]).entries())typeof h=="string"&&(o.attachResource(o.colorAttachments[c].texture),a.attachResource(a.colorAttachments[c].texture))}resize(e){if(e.width===this.current.width&&e.height===this.current.height)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),us(this.current),t.destroy(),this.next=n.clone(e),us(this.next),n.destroy(),!0}};function us(i){for(let e of i.colorAttachments)i.attachResource(e.texture);i.depthStencilAttachment&&i.attachResource(i.depthStencilAttachment.texture)}var mi=class extends Xe{constructor(e,t){super({current:e.createBuffer(t),next:e.createBuffer(t)})}resize(e){if(e.byteLength===this.current.byteLength)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),t.destroy(),this.next=n.clone(e),n.destroy(),!0}};var N=L(R(),1),ye=L(re(),1);var gn=2,Da=1e4,We=class i{static async createAsync(e,t){let n=!N.PipelineFactory.getAsyncCompilation(e),r=n?N.PipelineFactory.beginAsyncCompilation(e):N.PipelineFactory.getAsyncCompilation(e),s;try{s=new i(e,t)}finally{n&&N.PipelineFactory.endAsyncCompilation(e,r)}try{return n?await Promise.all(r):await s._pipelineInitialization,s}catch(o){throw s.destroy(),o}}static defaultProps={...N.ComputePipeline.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",sourceLanguage:void 0,modules:[],defines:{},plugins:[],bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:ye.ShaderAssembler.getDefaultShaderAssembler("wgsl"),debugShaders:void 0};device;id;pipelineFactory;shaderFactory;userData={};bindings={};pipeline;source;shader;shaderInputs;_uniformStore;_pipelineNeedsUpdate="newly created";_getModuleUniforms;props;_destroyed=!1;_pipelineInitialization;constructor(e,t){if(e.type!=="webgpu")throw new Error("Computation is only supported in WebGPU");this.props={...i.defaultProps,...t},t=this.props,this.id=t.id||z("model"),this.device=e,Object.assign(this.userData,t.userData);let n=Ba(e),r=(0,ye.resolveShaderPlugins)(this.props.plugins,n.shaderLanguage);if(Object.keys(r.vertexInputs).length>0||Object.keys(r.varyings).length>0)throw new Error("Computation does not support ShaderPlugin vertex inputs or varyings");let s=(0,ye.mergeShaderPluginModules)(this.props.modules,r.modules),o=Object.fromEntries(s.map(g=>[g.name,g]));this.shaderInputs=t.shaderInputs||new X(o),t.shaderInputs&&r.modules.length>0&&this.shaderInputs.addModules(r.modules),this.setShaderInputs(this.shaderInputs);let a=Yt(this.props.modules,this.shaderInputs?.getModules()),c={...r.defines,...this.props.defines};this.props.shaderLayout=Be(this.props.shaderLayout,a)||null,this.pipelineFactory=t.pipelineFactory||N.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||N.ShaderFactory.getDefaultShaderFactory(this.device);let h=this.props.shaderAssembler;(0,N.assert)(h instanceof ye.WGSLShaderAssembler);let{source:u,getUniforms:l,entryPoints:d={},shaderLayout:f}=h.assembleWGSLShader({platformInfo:n,...this.props,modules:a,defines:c,shaderStage:"compute",computeEntryPoint:this.props.entryPoint,scanVertexAttributes:!1,pluginInjections:r.injections});this.source=u,this.props.entryPoint=d.compute||this.props.entryPoint,this._getModuleUniforms=l;let p=f??e.getShaderLayout?.(this.source,{scanVertexAttributes:!1});this.props.shaderLayout=Be(this.props.shaderLayout||p||null,a)||null;let b=N.PipelineFactory.getAsyncCompilation(this.device);b?(this._pipelineInitialization=this._updatePipelineAsync(),b.push(this._pipelineInitialization)):this.pipeline=this._updatePipeline(),t.bindings&&this.setBindings(t.bindings)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shader&&this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(e){this.updateShaderInputs(e)}dispatch(e,t,n,r){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatch(t,n,r)}finally{this._logDrawCallEnd()}}dispatchIndirect(e,t,n=0){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatchIndirect(t,n)}finally{this._logDrawCallEnd()}}_setPipeline(e){this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),e.setPipeline(this.pipeline),e.setBindings({})}setVertexCount(e){}setInstanceCount(e){}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new N.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(Ie(n)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}}setShaderModuleProps(e){let t=this._getModuleUniforms(e),n=Object.keys(t).filter(s=>{let o=t[s];return!rt(o)&&typeof o!="number"&&typeof o!="boolean"}),r={};for(let s of n)r[s]=t[s],delete t[s]}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e)}setBindings(e){Object.assign(this.bindings,e)}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||e}_updatePipeline(){let e=this._preparePipelineUpdate();return e&&(this.pipeline=this.pipelineFactory.createComputePipeline(e.props),this._finishPipelineUpdate(e.previousShader)),this.pipeline}async _updatePipelineAsync(){let e=this._preparePipelineUpdate();if(e){try{this.pipeline=await this.pipelineFactory.createComputePipelineAsync(e.props)}catch(t){throw this.shaderFactory.release(this.shader),this.shader=e.previousShader,this._pipelineNeedsUpdate="asynchronous pipeline creation failed",t}this._finishPipelineUpdate(e.previousShader)}return this.pipeline}_preparePipelineUpdate(){if(!this._pipelineNeedsUpdate)return null;let e=this.pipeline?this.shader:null;return this.pipeline&&N.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debugShaders:this.props.debugShaders}),{props:{...this.props,shader:this.shader},previousShader:e}}_finishPipelineUpdate(e){e&&this.shaderFactory.release(e)}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=N.log.level>3?0:Da;N.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,N.log.group(gn,`>>> DRAWING MODEL ${this.id}`,{collapsed:N.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=this.shaderInputs.getDebugTable();N.log.table(gn,e)(),N.log.groupEnd(gn)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(e,t){let n=N.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof N.Buffer?new n(e.debugData):e).toString()}};function Ba(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}function ls(i){let{shaderPass:e,action:t,shadingLanguage:n}=i;switch(t){case"filter":let r=`${e.name}_filterColor_ext`;return n==="wgsl"?za(r):Ga(r);case"sample":let s=`${e.name}_sampleColor`;return n==="wgsl"?ja(s):Ua(s);default:throw new Error(`${e.name} no fragment shader generated for shader pass`)}}function za(i){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
|
|
174
|
+
`}}function xr(r,e,t){return Math.min(t,Math.max(e,r))}var Ul=new zt({nlat:8,nlong:12,radius:1}),Sn=class extends Ye{constructor(e,t){super(e,t,{anchorMode:"centered",buildInstanceData:tc,geometry:Ul,idPrefix:"point-light-model",sizePropNames:["pointLightRadius"]})}};var jl=new He({cap:!0,nradial:16,nvertical:1,radius:1}),Cn=class extends Ye{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:rc,geometry:jl,idPrefix:"spot-light-model",sizePropNames:["spotLightLength"]})}};var $l=new He({cap:!0,nradial:12,nvertical:1,radius:1}),En=class extends Ye{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:nc,geometry:$l,idPrefix:"directional-light-model",sizePropNames:["directionalLightLength"]})}};function vs(r,e){if(!r)throw new Error(e)}var Ee=class{id;matrix=new C;display=!0;position=new R;rotation=new R;scale=new R(1,1,1);userData={};props={};constructor(e={}){let{id:t}=e;this.id=t||X(this.constructor.name),this._setScenegraphNodeProps(e)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(e){return this._setScenegraphNodeProps(e),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(e){return vs(e.length===3,"setPosition requires vector argument"),this.position=e,this}setRotation(e){return vs(e.length===3||e.length===4,"setRotation requires vector argument"),this.rotation=e,this}setScale(e){return vs(e.length===3,"setScale requires vector argument"),this.scale=e,this}setMatrix(e,t=!0){t?this.matrix.copy(e):this.matrix=e}setMatrixComponents(e){let{position:t,rotation:n,scale:i,update:s=!0}=e;return t&&this.setPosition(t),n&&this.setRotation(n),i&&this.setScale(i),s&&this.updateMatrix(),this}updateMatrix(){if(this.matrix.identity(),this.matrix.translate(this.position),this.rotation.length===4){let e=new C().fromQuaternion(this.rotation);this.matrix.multiplyRight(e)}else this.matrix.rotateXYZ(this.rotation);return this.matrix.scale(this.scale),this}update({position:e,rotation:t,scale:n}={}){return e&&this.setPosition(e),t&&this.setRotation(t),n&&this.setScale(n),this.updateMatrix(),this}getCoordinateUniforms(e,t){t=t||this.matrix;let n=new C(e).multiplyRight(t),i=n.invert(),s=i.transpose();return{viewMatrix:e,modelMatrix:t,objectMatrix:t,worldMatrix:n,worldInverseMatrix:i,worldInverseTransposeMatrix:s}}_setScenegraphNodeProps(e){e.display!==void 0&&(this.display=e.display),e?.position&&this.setPosition(e.position),e?.rotation&&this.setRotation(e.rotation),e?.scale&&this.setScale(e.scale),this.updateMatrix(),e?.matrix&&this.setMatrix(e.matrix),Object.assign(this.props,e)}};var ac=B(D(),1);function Rn(){return[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]]}function Ln(r,e,t){let n=new C(t);for(let i=0;i<8;i++){let s=new R(e[i&1?1:0][0],e[i&2?1:0][1],e[i&4?1:0][2]);n.transformAsPoint(s,s);for(let o=0;o<3;o++)r[0][o]=Math.min(r[0][o],s[o]),r[1][o]=Math.max(r[1][o],s[o])}}function Bn(r){return Number.isFinite(r[0][0])}var re=class r extends Ee{children;constructor(e={}){e=Array.isArray(e)?{children:e}:e;let{children:t=[]}=e;ac.log.assert(t.every(n=>n instanceof Ee),"every child must an instance of ScenegraphNode"),super(e),this.children=t}getBounds(){let e=Rn();return this.traverse((t,{worldMatrix:n})=>{let i=t.getBounds();if(!i)return;let s=new C(n).multiplyRight(t.matrix);Ln(e,i,s)}),Bn(e)?e:null}destroy(){this.children.forEach(e=>e.destroy()),this.removeAll(),super.destroy()}add(...e){for(let t of e)Array.isArray(t)?this.add(...t):this.children.push(t);return this}remove(e){let t=this.children,n=t.indexOf(e);return n>-1&&t.splice(n,1),this}removeAll(){return this.children=[],this}traverse(e,{worldMatrix:t=new C}={}){if(!this.display)return;let n=new C(t).multiplyRight(this.matrix);for(let i of this.children)i.display&&(i instanceof r?i.traverse(e,{worldMatrix:n}):e(i,{worldMatrix:n}))}traverseDepthSorted(e,{viewMatrix:t,worldMatrix:n=new C,order:i="back-to-front"}){let s=new C(t),o=[];this.traverse((c,u)=>{let h=c.getBounds(),l=h?new R(h[0]).add(h[1]).divide([2,2,2]):new R,d=new C(u.worldMatrix).multiplyRight(c.matrix);d.transformAsPoint(l,l),s.transformAsPoint(l,l),o.push({node:c,context:{worldMatrix:d,bounds:h,depth:-l[2]},index:o.length})},{worldMatrix:new C(n)});let a=i==="back-to-front"?-1:1;o.sort((c,u)=>a*(c.context.depth-u.context.depth)||c.index-u.index);for(let{node:c,context:u}of o)e(c,u)}preorderTraversal(e,{worldMatrix:t=new C}={}){let n=new C(t).multiplyRight(this.matrix);e(this,{worldMatrix:n});for(let i of this.children)i instanceof r?i.preorderTraversal(e,{worldMatrix:n}):e(i,{worldMatrix:n})}};var Vt=class extends Ee{model;instanceMatrices;bounds=null;managedResources;constructor(e){super(e),this.model=e.model,this.managedResources=e.managedResources||[],this.instanceMatrices=e.instanceMatrices||null,this.bounds=e.bounds?this.instanceMatrices?ql(e.bounds,this.instanceMatrices):e.bounds:null,this.setProps(e)}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach(e=>e.destroy()),this.managedResources=[]}getBounds(){return this.bounds}draw(e){return this.model.draw(e)}};function ql(r,e){let t=Rn();for(let n of e)Ln(t,r,n);return Bn(t)?t:null}var le=B(D(),1);function Ts(r,e={}){let{angleThreshold:t=30,weldTolerance:n=0,positionAttribute:i="POSITION"}=e,s=uc(r,i);(0,le.assert)(Number.isFinite(n)&&n>=0),(0,le.assert)(Number.isFinite(t)&&t>=0&&t<=180);let o=r.indices?.value,a=s.value.length/3,c=new Map,u=new Map,h=new Set,l=new Map,d=Math.cos(t*Math.PI/180),p=n*n;function f(T){return[s.value[T*3],s.value[T*3+1],s.value[T*3+2]]}function m(T){let v=c.get(T);if(v!==void 0)return v;(0,le.assert)(Number.isInteger(T)&&T>=0&&T<a);let w=f(T);(0,le.assert)(w.every(Number.isFinite));let y=n>0?w.map(A=>Math.floor(A/n)):w,b=n>0?1:0;for(let A=-b;A<=b;A++)for(let S=-b;S<=b;S++)for(let L=-b;L<=b;L++){let I=u.get(`${y[0]+A},${y[1]+S},${y[2]+L}`);for(let O of I||[]){let E=f(O);if((w[0]-E[0])**2+(w[1]-E[1])**2+(w[2]-E[2])**2<=p)return c.set(T,O),O}}let M=y.join(","),_=u.get(M)||[];return _.push(T),u.set(M,_),c.set(T,T),T}function g(T,v,w){let y=Math.min(T,v),b=Math.max(T,v),M=`${y},${b}`,_=l.get(M);if(_){_.faceCount++;let A=w[0]*_.normal[0]+w[1]*_.normal[1]+w[2]*_.normal[2];_.crease||=A<1-1e-7&&A<=d+1e-7}else l.set(M,{start:y,end:b,normal:w,faceCount:1,crease:!1})}for(let T=0;T<r.vertexCount;T+=3){let v=m(o?.[T]??T),w=m(o?.[T+1]??T+1),y=m(o?.[T+2]??T+2);if(v===w||w===y||y===v)continue;let b=[v,w,y].sort((E,k)=>E-k).join(",");if(h.has(b))continue;h.add(b);let M=f(v),_=f(w),A=f(y),S=_.map((E,k)=>E-M[k]),L=A.map((E,k)=>E-M[k]),I=[S[1]*L[2]-S[2]*L[1],S[2]*L[0]-S[0]*L[2],S[0]*L[1]-S[1]*L[0]],O=Math.hypot(...I);O!==0&&(I[0]/=O,I[1]/=O,I[2]/=O,g(v,w,I),g(w,y,I),g(y,v,I))}let x=[...l.values()].filter(T=>e.includeCoplanarEdges||T.faceCount!==2||T.crease).sort((T,v)=>T.start-v.start||T.end-v.end);return new z({id:`${r.id}-edges`,topology:"line-list",attributes:{[i]:s},indices:new Uint32Array(x.flatMap(T=>[T.start,T.end]))})}function cc(r,e={}){(0,le.assert)(r.length>0);let t=e.positionAttribute??"POSITION",n=r.map(h=>uc(h,t)),i=n[0];(0,le.assert)(n.every(h=>h.value.constructor===i.value.constructor&&!!h.normalized==!!i.normalized));let s=i.value.constructor,o=new s(n.reduce((h,l)=>h+l.value.length,0)),a=new Uint32Array(r.reduce((h,l)=>h+l.vertexCount,0)),c=0,u=0;for(let[h,l]of r.entries()){let d=n[h];o.set(d.value,c);for(let p=0;p<l.vertexCount;p++){let f=l.indices?.value[p]??p;(0,le.assert)(Number.isInteger(f)&&f>=0&&f<d.value.length/3),a[u++]=f+c/3}c+=d.value.length}return Ts(new z({id:`${r[0].id}-batch`,topology:"triangle-list",attributes:{[t]:{...i,value:o}},indices:a}),e)}function uc(r,e){let t=r.attributes[e];return(0,le.assert)(r.topology==="triangle-list"&&t?.size===3),(0,le.assert)(t.value.length%3===0&&r.vertexCount%3===0),(0,le.assert)(!t.byteStride||t.byteStride===t.value.BYTES_PER_ELEMENT*3),(0,le.assert)(r.vertexCount>=0&&r.vertexCount<=(r.indices?.value.length??t.value.length/3)),t}var On=B(D(),1);function hc(r,e={}){let{width:t=1,cap:n="butt",join:i="miter",miterLimit:s=4,roundSegments:o=16}=e;(0,On.assert)(Number.isFinite(t)&&t>=0&&Number.isFinite(s)&&s>=1),(0,On.assert)(Number.isInteger(o)&&o>=2&&o<=256);let a=[];for(let g of r){(0,On.assert)(Number.isFinite(g[0])&&Number.isFinite(g[1])&&Number.isFinite(g[2]??0));let x=a.at(-1);(!x||x[0]!==g[0]||x[1]!==g[1])&&a.push([g[0],g[1],g[2]??0])}e.closed&&a.length>1&&a[0][0]===a.at(-1)[0]&&a[0][1]===a.at(-1)[1]&&a.pop();let c=!!(e.closed&&a.length>2),u=[],h=[],l=t/2;if(a.length>1&&t>0){let g=[],x=[0];for(let v=0;v<a.length-(c?0:1);v++){let w=a[v],y=a[(v+1)%a.length],b=y[0]-w[0],M=y[1]-w[1],_=Math.hypot(b,M);g.push({direction:[b/_,M/_],length:_}),x.push(x.at(-1)+_)}let T=a.map((v,w)=>{let y=g[(w-1+g.length)%g.length],b=g[w%g.length],M=x[w];if(!c&&(w===0||w===a.length-1)){let _e=w===0?b.direction:y.direction,Ae=n==="square"?w===0?-l:l:0,ht=f(v,_e,l,Ae,M+Ae),Kt=f(v,_e,-l,Ae,M+Ae);return n==="round"&&m(v,_e,M,w===0),{incomingLeft:ht,outgoingLeft:ht,incomingRight:Kt,outgoingRight:Kt}}let _=y.direction,A=b.direction,S=_[0]*A[1]-_[1]*A[0],L=_[0]*A[0]+_[1]*A[1],I={incomingLeft:f(v,_,l,0,M),incomingRight:f(v,_,-l,0,M),outgoingLeft:f(v,A,l,0,M),outgoingRight:f(v,A,-l,0,M)};if(1+L<1e-8)return i==="round"&&(m(v,_,M,!1),m(v,A,M,!0)),I;let O=[-(_[1]+A[1])*l/(1+L),(_[0]+A[0])*l/(1+L)],E=Math.hypot(...O);if(Math.abs(S)<1e-8||i==="miter"&&E<=s*l){let _e=p(v,O,M,l),Ae=p(v,[-O[0],-O[1]],M,-l);return{incomingLeft:_e,outgoingLeft:_e,incomingRight:Ae,outgoingRight:Ae}}let k=Math.sign(S),fe=Math.min(1,Math.min(y.length,b.length)/(2*E)),ne=p(v,[O[0]*k*fe,O[1]*k*fe],M,l*k);k>0?(I.incomingLeft=ne,I.outgoingLeft=ne):(I.incomingRight=ne,I.outgoingRight=ne);let De=k>0?I.incomingRight:I.incomingLeft,Ds=k>0?I.outgoingRight:I.outgoingLeft;if(i==="round"){let _e=Math.atan2(S,L),Ae=Math.atan2(De.position[1]-v[1],De.position[0]-v[0]),ht=Math.max(1,Math.ceil(Math.abs(_e)/Math.PI*o)),Kt=De;for(let Ir=1;Ir<=ht;Ir++){let ks=Ae+_e*Ir/ht,Fs=Ir===ht?Ds:p(v,[Math.cos(ks)*l,Math.sin(ks)*l],M,-l*k);d(ne,Kt,Fs),Kt=Fs}}else d(ne,De,Ds);return I});g.forEach((v,w)=>{let y=T[w],b=T[(w+1)%T.length],M=c&&w===g.length-1,_=M?{...b.incomingLeft,distance:x.at(-1)}:b.incomingLeft,A=M?{...b.incomingRight,distance:x.at(-1)}:b.incomingRight;d(y.outgoingLeft,y.outgoingRight,_),d(y.outgoingRight,A,_)})}return new z({id:e.id,topology:"triangle-list",attributes:{POSITION:{size:3,value:new Float32Array(u)},TEXCOORD_0:{size:2,value:new Float32Array(h)}}});function d(g,x,T){let v=(x.position[0]-g.position[0])*(T.position[1]-g.position[1])-(x.position[1]-g.position[1])*(T.position[0]-g.position[0]);if(v!==0)for(let w of v>0?[g,x,T]:[g,T,x])u.push(...w.position),h.push(w.distance,w.across)}function p(g,x,T,v){return{position:[g[0]+x[0],g[1]+x[1],g[2]],distance:T,across:v}}function f(g,x,T,v,w){return p(g,[-x[1]*T+x[0]*v,x[0]*T+x[1]*v],w,T)}function m(g,x,T,v){let w={position:g,distance:T,across:0},y=Math.atan2(x[1],x[0])+(v?-Math.PI/2:Math.PI/2),b;for(let M=0;M<=o;M++){let _=y-Math.PI*M/o,A=[Math.cos(_)*l,Math.sin(_)*l],S=p(g,A,T+A[0]*x[0]+A[1]*x[1],-A[0]*x[1]+A[1]*x[0]);b&&d(w,b,S),b=S}}}var _s=B(D(),1),lc=10,Wl=1e-10;function pc(r){let{positions:e,indices:t,attributes:n=[],preserveBoundary:i=!0}=r;(0,_s.assert)(t.length%3===0&&e.length%3===0);let s=Math.max(0,Math.min(t.length,Math.floor((r.targetIndexCount??t.length*(r.targetRatio??.5))/3)*3));if(t.length===0||s>=t.length)return{indices:t.slice(),geometricError:0};let o=e.length/3,a=Array.from({length:o},()=>({quadric:new Float64Array(lc),neighbors:new Set,boundaryNeighbors:new Set,triangles:new Set,active:!1,version:0})),c=[],u=new Map,h=new Map,l=new Is,d=0,p=0,f=(y,b,M)=>{let _=Math.min(y,b),A=Math.max(y,b),S=_*o+A,I=(u.get(S)||0)+M;I<=0?(u.delete(S),a[y].neighbors.delete(b),a[b].neighbors.delete(y)):(u.set(S,I),a[y].neighbors.add(b),a[b].neighbors.add(y)),I===1?(a[y].boundaryNeighbors.add(b),a[b].boundaryNeighbors.add(y)):(a[y].boundaryNeighbors.delete(b),a[b].boundaryNeighbors.delete(y))},m=y=>{let b=c[y];if(!b.active)return;let[M,_,A]=b.vertices;h.delete(fc(M,_,A)),f(M,_,-1),f(_,A,-1),f(A,M,-1),a[M].triangles.delete(y),a[_].triangles.delete(y),a[A].triangles.delete(y),b.active=!1,d--},g=y=>{let b=c[y],[M,_,A]=b.vertices;if(M===_||_===A||A===M)return!1;let S=fc(M,_,A);return h.has(S)?!1:(h.set(S,y),f(M,_,1),f(_,A,1),f(A,M,1),a[M].triangles.add(y),a[_].triangles.add(y),a[A].triangles.add(y),a[M].active=!0,a[_].active=!0,a[A].active=!0,b.active=!0,d++,!0)};for(let y=0;y<t.length;y+=3){let b=t[y],M=t[y+1],_=t[y+2];(0,_s.assert)(b<o&&M<o&&_<o);let A={vertices:[b,M,_],active:!1},S=c.push(A)-1;g(S)&&Hl(a,e,b,M,_)}let x=(y,b)=>{if(!a[y].active||!a[b].active)return;let M=Xl(n,y,b);if(Number.isFinite(M))for(let[_,A]of[[y,b],[b,y]]){if(i&&!dc(a,e,_,A))continue;let S=Math.max(0,Yl(a,e,y,b,_));l.add({retainedVertex:_,removedVertex:A,retainedVersion:a[_].version,removedVersion:a[A].version,geometricCost:S,cost:S+M})}};for(let y=0;y<a.length;y++)for(let b of a[y].neighbors)y<b&&x(y,b);for(;d*3>s;){let y=l.remove();if(!y)break;let{retainedVertex:b,removedVertex:M}=y,_=a[b],A=a[M];if(!_.active||!A.active||_.version!==y.retainedVersion||A.version!==y.removedVersion||!_.neighbors.has(M)||i&&!dc(a,e,b,M)||!Kl(c,a,e,b,M))continue;let S=new Set([b,M,..._.neighbors,...A.neighbors]),L=[...A.triangles];for(let I of L)m(I);for(let I of L){let O=c[I];for(let E=0;E<3;E++)O.vertices[E]===M&&(O.vertices[E]=b);g(I)}for(let I=0;I<lc;I++)_.quadric[I]+=A.quadric[I];A.active=!1,p=Math.max(p,y.geometricCost);for(let I of S)a[I].version++;for(let I of S)if(a[I].active)for(let O of a[I].neighbors)x(I,O)}let T=t.constructor,v=new T(d*3),w=0;for(let y of c)y.active&&(v[w++]=y.vertices[0],v[w++]=y.vertices[1],v[w++]=y.vertices[2]);return{indices:v,geometricError:Math.sqrt(p)}}function Hl(r,e,t,n,i){let s=As(e,t,n,i),o=Math.hypot(s[0],s[1],s[2]);if(o===0)return;let a=s[0]/o,c=s[1]/o,u=s[2]/o,h=-(a*e[t*3]+c*e[t*3+1]+u*e[t*3+2]),l=[a,c,u,h];for(let d of[t,n,i]){let p=0;for(let f=0;f<4;f++)for(let m=f;m<4;m++)r[d].quadric[p++]+=l[f]*l[m]}}function Yl(r,e,t,n,i){let s=[e[i*3],e[i*3+1],e[i*3+2],1],o=0,a=0;for(let c=0;c<4;c++)for(let u=c;u<4;u++){let h=r[t].quadric[o]+r[n].quadric[o];a+=h*s[c]*s[u]*(c===u?1:2),o++}return a}function Xl(r,e,t){let n=0;for(let i of r){let s=i.weight??1;if(s===0)continue;let o=i.values instanceof Uint8Array||i.values instanceof Uint16Array||i.values instanceof Uint32Array;for(let a=0;a<i.size;a++){let c=i.values[e*i.size+a]-i.values[t*i.size+a];if(o&&c!==0)return 1/0;n+=c*c*s}}return n}function dc(r,e,t,n){let i=r[t].boundaryNeighbors.size>0,s=r[n].boundaryNeighbors.size>0;if(i!==s)return!1;if(!s)return!0;let o=r[n].boundaryNeighbors;if(o.size!==2||!o.has(t))return!1;let a=[...o].find(f=>f!==t);if(a===void 0)return!1;let c=Dn(e,t,n),u=Dn(e,a,n),h=ws(c),l=ws(u),d=[c[1]*u[2]-c[2]*u[1],c[2]*u[0]-c[0]*u[2],c[0]*u[1]-c[1]*u[0]];return c[0]*u[0]+c[1]*u[1]+c[2]*u[2]<=0&&ws(d)<=Wl*h*l}function Kl(r,e,t,n,i){for(let s of e[i].triangles){let o=r[s];if(o.vertices.includes(n))continue;let a=As(t,...o.vertices),c=o.vertices.map(l=>l===i?n:l),u=As(t,...c);if(a[0]*u[0]+a[1]*u[1]+a[2]*u[2]<=0)return!1}return!0}function As(r,e,t,n){let i=Dn(r,t,e),s=Dn(r,n,e);return[i[1]*s[2]-i[2]*s[1],i[2]*s[0]-i[0]*s[2],i[0]*s[1]-i[1]*s[0]]}function Dn(r,e,t){return[r[e*3]-r[t*3],r[e*3+1]-r[t*3+1],r[e*3+2]-r[t*3+2]]}function ws(r){return r[0]*r[0]+r[1]*r[1]+r[2]*r[2]}function fc(r,e,t){return[r,e,t].sort((n,i)=>n-i).join(":")}var Is=class{entries=[];add(e){this.entries.push(e);let t=this.entries.length-1;for(;t>0;){let n=t-1>>1;if(Ms(this.entries[n],e)<=0)break;this.entries[t]=this.entries[n],this.entries[n]=e,t=n}}remove(){let e=this.entries[0],t=this.entries.pop();if(!e||!t||this.entries.length===0)return e;this.entries[0]=t;let n=0;for(;;){let i=n*2+1;if(i>=this.entries.length)break;let s=i+1,o=s<this.entries.length&&Ms(this.entries[s],this.entries[i])<0?s:i;if(Ms(this.entries[n],this.entries[o])<=0)break;[this.entries[n],this.entries[o]]=[this.entries[o],this.entries[n]],n=o}return e}};function Ms(r,e){return r.cost-e.cost||r.retainedVertex-e.retainedVertex||r.removedVertex-e.removedVertex}function mc(){let r=1,e=1;return()=>(r=Math.sin(e*17.23),e=Math.cos(r*27.92),Zl(Math.abs(r*e)*1432.71))}function Zl(r){return r-Math.floor(r)}var yc="";function xc(r){yc=r}function kn(r){return Ql(r)?r:yc+r}async function bc(r,e){let t=new Image,n=kn(r);t.crossOrigin=e?.crossOrigin||"anonymous",t.src=n;try{await t.decode()}catch(i){throw gc("decode",n,i)}try{return e?await createImageBitmap(t,e):await createImageBitmap(t)}catch(i){throw gc("create",n,i)}}async function vc(r,e){return await new Promise((t,n)=>{try{let i=new Image,s=kn(r);i.onload=()=>t(i),i.onerror=()=>n(new Error(`Could not load image ${s}.`)),i.crossOrigin=e?.crossOrigin||"anonymous",i.src=s}catch(i){n(i)}})}function gc(r,e,t){let n=t instanceof Error?t.message:String(t),i=r==="decode"?`Could not decode source image "${e}": ${n}`:`Could not create ImageBitmap from decoded image "${e}": ${n}`;return new Error(i,{cause:t})}function Ql(r){return r.startsWith("/")||/^[a-z][a-z\d+\-.]*:/i.test(r)}var ot=B(D(),1);var Fn=class{device;id;destroyed=!1;generation=0;_source;_colorSpace;_sampler;_isReady=!1;_updateTimestamp;_sourceVersion=0;_sourceFrameToken=null;_texture=null;_textureFrameToken=void 0;_externalTexture=null;get source(){return this._source}get isReady(){return this._observeSource(),this._isReady}get updateTimestamp(){return this._observeSource(),this._updateTimestamp}get[Symbol.toStringTag](){return"VideoTexture"}toString(){let e=Ps(this._source);return`VideoTexture:"${this.id}":${e.width}x${e.height}px:(${this._isReady?"ready":"loading..."})`}constructor(e,t){(0,ot.assert)(br(t?.source)||Tc(t?.source)),this.device=e,this.id=t.id||X("video-texture"),this._source=t.source,this._colorSpace=t.colorSpace??"srgb",this._sampler=t.sampler??{},this._updateTimestamp=this.device.incrementTimestamp(),this.setSource(t.source)}setSource(e){(0,ot.assert)(br(e)||Tc(e)),this._destroyExternalTexture(),this._source=e,this._sourceVersion++,this._sourceFrameToken=null,this._textureFrameToken=void 0,this._observeSource(),this._touchGeneration()}resolveTextureBinding(e){return this._observeSource(),!this._isReady||this.destroyed?null:e.type==="external-texture"&&this.device.type==="webgpu"?this._createNativeExternalTexture():this._resolveCopiedTexture()}setSampler(e){this._sampler=e,this._texture?.setSampler(e),this._externalTexture?.setSampler?.(e),this._touchGeneration()}destroy(){this.destroyed||(this._destroyExternalTexture(),this._texture?.destroy(),this._texture=null,this._textureFrameToken=void 0,this._isReady=!1,this.destroyed=!0,this._touchGeneration())}_resolveCopiedTexture(){let e=this._getOrCreateCopiedTexture();return Object.is(this._textureFrameToken,this._sourceFrameToken)||(e.copyExternalImage({image:this._source,colorSpace:this._colorSpace}),this._textureFrameToken=this._sourceFrameToken),e}_getOrCreateCopiedTexture(){let e=this._getResolvedSize(),t=this._texture;if(t&&t.width===e.width&&t.height===e.height)return t;t?.destroy();let n=this.device.createTexture({id:`${this.id}-texture`,width:e.width,height:e.height,format:"rgba8unorm",usage:ot.Texture.SAMPLE|ot.Texture.COPY_DST,mipLevels:1,sampler:this._sampler});return this._texture=n,this._textureFrameToken=void 0,this._touchGeneration(),n}_createNativeExternalTexture(){return this._destroyExternalTexture(),this._externalTexture=this.device.createExternalTexture({id:`${this.id}-external`,source:this._source,colorSpace:this._colorSpace,sampler:this._sampler}),this.generation++,this._externalTexture}_destroyExternalTexture(){this._externalTexture?.destroy(),this._externalTexture=null}_getResolvedSize(){let e=Ps(this._source);return(0,ot.assert)(e.width>0&&e.height>0),e}_observeSource(){if(this.destroyed)return;let e=Jl(this._source);if(e!==this._isReady&&(this._isReady=e,this._touch()),!e)return;let t=ed(this._source,this._sourceVersion);Object.is(t,this._sourceFrameToken)||(this._sourceFrameToken=t,this._touch())}_touch(){this._updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}};function br(r){return!r||typeof r!="object"?!1:typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||"videoWidth"in r&&"videoHeight"in r&&"readyState"in r&&"currentTime"in r}function Tc(r){return!r||typeof r!="object"?!1:typeof VideoFrame<"u"&&r instanceof VideoFrame||"displayWidth"in r&&"displayHeight"in r&&"timestamp"in r&&!("videoWidth"in r)}function Jl(r){let e=Ps(r);return e.width<=0||e.height<=0?!1:br(r)?r.readyState>=2:!0}function Ps(r){return br(r)?{width:r.videoWidth,height:r.videoHeight}:{width:r.displayWidth,height:r.displayHeight}}function ed(r,e){return br(r)?`${e}:${r.currentTime}:${r.videoWidth}x${r.videoHeight}`:`${e}:${r.timestamp}:${r.displayWidth}x${r.displayHeight}`}var Le=B(D(),1),Cc=B(Ie(),1);var Re=B(D(),1),Ut=class{id;current;next;constructor(e){this.id=e.id||"swap",this.current=e.current,this.next=e.next}destroy(){this.current?.destroy(),this.next?.destroy()}swap(){let e=this.current;this.current=this.next,this.next=e}},jt=class extends Ut{constructor(e,t){t={...t};let{width:n=1,height:i=1}=t,s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-0`,format:c,usage:Re.Texture.SAMPLE|Re.Texture.RENDER|Re.Texture.COPY_SRC|Re.Texture.COPY_DST,width:n,height:i})),o=e.createFramebuffer({...t,colorAttachments:s});s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-1`,format:c,usage:Re.Texture.SAMPLE|Re.Texture.RENDER|Re.Texture.COPY_SRC|Re.Texture.COPY_DST,width:n,height:i}));let a=e.createFramebuffer({...t,colorAttachments:s});super({current:o,next:a});for(let[c,u]of(t.colorAttachments||[]).entries())typeof u=="string"&&(o.attachResource(o.colorAttachments[c].texture),a.attachResource(a.colorAttachments[c].texture))}resize(e){if(e.width===this.current.width&&e.height===this.current.height)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),wc(this.current),t.destroy(),this.next=n.clone(e),wc(this.next),n.destroy(),!0}};function wc(r){for(let e of r.colorAttachments)r.attachResource(e.texture);r.depthStencilAttachment&&r.attachResource(r.depthStencilAttachment.texture)}var Nn=class extends Ut{constructor(e,t){super({current:e.createBuffer(t),next:e.createBuffer(t)})}resize(e){if(e.byteLength===this.current.byteLength)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),t.destroy(),this.next=n.clone(e),n.destroy(),!0}};var N=B(D(),1),Xe=B(Ie(),1);var Ss=2,td=1e4,$t=class r{static async createAsync(e,t){let n=!N.PipelineFactory.getAsyncCompilation(e),i=n?N.PipelineFactory.beginAsyncCompilation(e):N.PipelineFactory.getAsyncCompilation(e),s;try{s=new r(e,t)}finally{n&&N.PipelineFactory.endAsyncCompilation(e,i)}try{return n?await Promise.all(i):await s._pipelineInitialization,s}catch(o){throw s.destroy(),o}}static defaultProps={...N.ComputePipeline.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",sourceLanguage:void 0,modules:[],defines:{},plugins:[],bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:Xe.ShaderAssembler.getDefaultShaderAssembler("wgsl"),debugShaders:void 0};device;id;pipelineFactory;shaderFactory;userData={};bindings={};pipeline;source;shader;shaderInputs;_uniformStore;_pipelineNeedsUpdate="newly created";_getModuleUniforms;props;_destroyed=!1;_pipelineInitialization;constructor(e,t){if(e.type!=="webgpu")throw new Error("Computation is only supported in WebGPU");this.props={...r.defaultProps,...t},t=this.props,this.id=t.id||X("model"),this.device=e,Object.assign(this.userData,t.userData);let n=Pt(e),i=(0,Xe.resolveShaderPlugins)(this.props.plugins,n.shaderLanguage);if(Object.keys(i.vertexInputs).length>0||Object.keys(i.varyings).length>0)throw new Error("Computation does not support ShaderPlugin vertex inputs or varyings");let s=(0,Xe.mergeShaderPluginModules)(this.props.modules,i.modules),o=Object.fromEntries(s.map(g=>[g.name,g]));this.shaderInputs=t.shaderInputs||new K(o),t.shaderInputs&&i.modules.length>0&&this.shaderInputs.addModules(i.modules),this.setShaderInputs(this.shaderInputs);let a=nn(this.props.modules,this.shaderInputs?.getModules()),c={...i.defines,...this.props.defines};this.props.shaderLayout=It(this.props.shaderLayout,a)||null,this.pipelineFactory=t.pipelineFactory||N.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||N.ShaderFactory.getDefaultShaderFactory(this.device);let u=this.props.shaderAssembler;(0,N.assert)(u instanceof Xe.WGSLShaderAssembler);let{source:h,getUniforms:l,entryPoints:d={},shaderLayout:p}=u.assembleWGSLShader({platformInfo:n,...this.props,modules:a,defines:c,shaderStage:"compute",computeEntryPoint:this.props.entryPoint,scanVertexAttributes:!1,pluginInjections:i.injections});this.source=h,this.props.entryPoint=d.compute||this.props.entryPoint,this._getModuleUniforms=l;let f=p??e.getShaderLayout?.(this.source,{scanVertexAttributes:!1});this.props.shaderLayout=It(this.props.shaderLayout||f||null,a)||null;let m=N.PipelineFactory.getAsyncCompilation(this.device);m?(this._pipelineInitialization=this._updatePipelineAsync(),m.push(this._pipelineInitialization)):this.pipeline=this._updatePipeline(),t.bindings&&this.setBindings(t.bindings)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shader&&this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(e){this.updateShaderInputs(e)}dispatch(e,t,n,i){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatch(t,n,i)}finally{this._logDrawCallEnd()}}dispatchIndirect(e,t,n=0){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatchIndirect(t,n)}finally{this._logDrawCallEnd()}}_setPipeline(e){this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),e.setPipeline(this.pipeline),e.setBindings({})}setVertexCount(e){}setInstanceCount(e){}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new N.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(tt(n)){let i=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=i}}setShaderModuleProps(e){let t=this._getModuleUniforms(e),n=Object.keys(t).filter(s=>{let o=t[s];return!Si(o)}),i={};for(let s of n)i[s]=t[s],delete t[s]}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e)}setBindings(e){Object.assign(this.bindings,e)}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||e}_updatePipeline(){let e=this._preparePipelineUpdate();return e&&(this.pipeline=this.pipelineFactory.createComputePipeline(e.props),this._finishPipelineUpdate(e.previousShader)),this.pipeline}async _updatePipelineAsync(){let e=this._preparePipelineUpdate();if(e){try{this.pipeline=await this.pipelineFactory.createComputePipelineAsync(e.props)}catch(t){throw this.shaderFactory.release(this.shader),this.shader=e.previousShader,this._pipelineNeedsUpdate="asynchronous pipeline creation failed",t}this._finishPipelineUpdate(e.previousShader)}return this.pipeline}_preparePipelineUpdate(){if(!this._pipelineNeedsUpdate)return null;let e=this.pipeline?this.shader:null;return this.pipeline&&N.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debugShaders:this.props.debugShaders}),{props:{...this.props,shader:this.shader},previousShader:e}}_finishPipelineUpdate(e){e&&this.shaderFactory.release(e)}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=N.log.level>3?0:td;N.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,N.log.group(Ss,`>>> DRAWING MODEL ${this.id}`,{collapsed:N.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=this.shaderInputs.getDebugTable();N.log.table(Ss,e)(),N.log.groupEnd(Ss)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(e,t){let n=N.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof N.Buffer?new n(e.debugData):e).toString()}};function Mc(r){let{shaderPass:e,action:t,shadingLanguage:n}=r;switch(t){case"filter":let i=`${e.name}_filterColor_ext`;return n==="wgsl"?rd(i):id(i);case"sample":let s=`${e.name}_sampleColor`;return n==="wgsl"?nd(s):sd(s);default:throw new Error(`${e.name} no fragment shader generated for shader pass`)}}function rd(r){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
|
|
175
175
|
@group(0) @binding(auto) var sourceTextureSampler: sampler;
|
|
176
176
|
|
|
177
177
|
@fragment
|
|
@@ -180,19 +180,19 @@ fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {
|
|
|
180
180
|
let texSize = vec2f(textureDimensions(sourceTexture));
|
|
181
181
|
|
|
182
182
|
var fragColor = textureSample(sourceTexture, sourceTextureSampler, texCoord);
|
|
183
|
-
fragColor = ${
|
|
183
|
+
fragColor = ${r}(fragColor, texSize, texCoord);
|
|
184
184
|
return fragColor;
|
|
185
185
|
}
|
|
186
|
-
`}function
|
|
186
|
+
`}function nd(r){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
|
|
187
187
|
@group(0) @binding(auto) var sourceTextureSampler: sampler;
|
|
188
188
|
|
|
189
189
|
@fragment
|
|
190
190
|
fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {
|
|
191
191
|
let texCoord = shaderPassRenderer_getTextureUV(inputs.coordinate);
|
|
192
192
|
let texSize = vec2f(textureDimensions(sourceTexture));
|
|
193
|
-
return ${
|
|
193
|
+
return ${r}(sourceTexture, sourceTextureSampler, texSize, texCoord);
|
|
194
194
|
}
|
|
195
|
-
`}function
|
|
195
|
+
`}function id(r){return`#version 300 es
|
|
196
196
|
|
|
197
197
|
uniform sampler2D sourceTexture;
|
|
198
198
|
|
|
@@ -208,9 +208,9 @@ void main() {
|
|
|
208
208
|
vec2 texSize = vec2(float(iTexSize.x), float(iTexSize.y));
|
|
209
209
|
|
|
210
210
|
fragColor = texture(sourceTexture, texCoord);
|
|
211
|
-
fragColor = ${
|
|
211
|
+
fragColor = ${r}(fragColor, texSize, texCoord);
|
|
212
212
|
}
|
|
213
|
-
`}function
|
|
213
|
+
`}function sd(r){return`#version 300 es
|
|
214
214
|
|
|
215
215
|
uniform sampler2D sourceTexture;
|
|
216
216
|
|
|
@@ -225,9 +225,9 @@ void main() {
|
|
|
225
225
|
ivec2 iTexSize = textureSize(sourceTexture, 0);
|
|
226
226
|
vec2 texSize = vec2(float(iTexSize.x), float(iTexSize.y));
|
|
227
227
|
|
|
228
|
-
fragColor = ${
|
|
228
|
+
fragColor = ${r}(sourceTexture, texSize, texCoord);
|
|
229
229
|
}
|
|
230
|
-
`}var
|
|
230
|
+
`}var _c={name:"textureTransform",source:`
|
|
231
231
|
struct textureTransformUniforms {
|
|
232
232
|
scale: vec2<f32>,
|
|
233
233
|
flipY: i32,
|
|
@@ -264,7 +264,7 @@ vec2 shaderPassRenderer_getRenderTargetUV(vec2 textureUV) {
|
|
|
264
264
|
vec2 unscaledCoord = (textureUV - 0.5) * textureTransform.scale + 0.5;
|
|
265
265
|
return textureTransform.flipY != 0 ? unscaledCoord : vec2(unscaledCoord.x, 1.0 - unscaledCoord.y);
|
|
266
266
|
}
|
|
267
|
-
`,uniformTypes:{scale:"vec2<f32>",flipY:"i32"}};var $a=new Set(["original","previous"]),gi=class{device;shaderInputs;passRenderers;swapFramebuffers;textureModel;constructor(e,t){this.device=e;let n=Va(t.shaderPasses);n.map(a=>(0,xs.initializeShaderModule)(a));let r=n.reduce((a,c)=>({...a,[c.name]:c}),{});this.shaderInputs=t.shaderInputs||new X(r);let s=e.getCanvasContext().getDrawingBufferSize();this.swapFramebuffers=new Ye(e,{colorAttachments:[t.colorFormat||e.preferredColorFormat],width:s[0],height:s[1]}),this.textureModel=new Ue(e,{backgroundTexture:this.swapFramebuffers.current.colorAttachments[0].texture,flipY:t.flipY??e.type==="webgpu"});let o=t.flipY??e.type==="webgpu";this.passRenderers=t.shaderPasses.map(a=>new xn(e,a,this.shaderInputs,o))}destroy(){for(let e of this.passRenderers)e.destroy();this.swapFramebuffers.destroy(),this.textureModel.destroy()}resize(e){e||=this.device.getCanvasContext().getDrawingBufferSize(),this.swapFramebuffers.resize({width:e[0],height:e[1]});for(let t of this.passRenderers)t.resize(e)}resetHistory(){for(let e of this.passRenderers)e.resetHistory()}renderToScreen(e){return this.encodeToScreen(this.device.commandEncoder,e)}encodeToScreen(e,t){let n=this.encodeToTexture(e,t);if(!n)return!1;let r=this.device.getDefaultCanvasContext().getCurrentFramebuffer({depthStencilFormat:!1});this.textureModel.setProps({backgroundTexture:n}),this.textureModel.predraw(e);let s=e.beginRenderPass({id:"shader-pass-renderer-to-screen",framebuffer:r,clearDepth:!1});return this.textureModel.draw(s),s.end(),!0}renderToTexture(e){return this.encodeToTexture(this.device.commandEncoder,e)}encodeToTexture(e,t){if(e.device!==this.device)throw new Error("ShaderPassRenderer command encoder must belong to the renderer device");let{sourceTexture:n}=t;if(n instanceof Z&&!n.isReady)return null;let r=n instanceof Z?n.texture:n;if(this.passRenderers.length===0)return r;t.resetHistory&&this.resetHistory(),this.textureModel.setProps({backgroundTexture:r}),this.textureModel.predraw(e);let s=tc(this.swapFramebuffers,r),o=e.beginRenderPass({id:"shader-pass-renderer-seed-source",framebuffer:s,clearColor:[0,0,0,1],clearDepth:!1});this.textureModel.draw(o),o.end();let a=s,c=vn(s),h=!1;try{for(let u of this.passRenderers){u.initializeHistoryTargets(r,this.textureModel,e),u.runComputeOptimization({commandEncoder:e,originalTexture:r,previousTexture:c,runtimeUniforms:t.uniforms||{}});for(let l of u.subPassExecutions){let d=l.output||"previous",f=d==="previous"?ec(this.swapFramebuffers,a):u.getOutputFramebuffer(d),p=vn(f),b=u.resolveBindings({execution:l,originalTexture:r,previousTexture:c,outputTexture:p,externalBindings:t.bindings||{}}),g=Ha(this.shaderInputs,l,t.uniforms||{});l.subPassRenderer.prepare({commandEncoder:e,bindings:b,textureScale:ic(b.sourceTexture||c,p),uniforms:g});let _=e.beginRenderPass({id:"shader-pass-renderer-run-pass",framebuffer:f,clearColor:[0,0,0,1],clearDepth:1});l.subPassRenderer.draw(_),_.end(),d==="previous"?(c=p,a=f):u.markTargetWritten(d)}}h=!0}finally{for(let u of this.passRenderers)u.finishFrame(h)}return c}},xn=class{device;shaderInputs;passDefinition;renderTargets;subPassExecutions;computeRenderer;constructor(e,t,n,r){if(this.device=e,this.shaderInputs=n,this.passDefinition=t,ys(t)){Ya(t.name,t.renderTargets||{}),this.renderTargets=qa(e,t.renderTargets||{}),Xa(e,t)&&(this.computeRenderer=new yn(e,t.compute,this.renderTargets,n));let s=this.computeRenderer?t.steps.filter(o=>!t.compute.replacedPasses.includes(o.shaderPass.name)):t.steps;this.subPassExecutions=s.flatMap(o=>this.createStepExecutions(t,o,r));return}fs(t,t.name),this.renderTargets={},this.subPassExecutions=this.createPassExecutions(t,{ownerName:t.name,flipY:r})}destroy(){this.computeRenderer?.destroy();for(let e of this.subPassExecutions)e.subPassRenderer.destroy();Qa(this.renderTargets)}resize(e){Ja(this.device,this.renderTargets,e)}runComputeOptimization(e){if(!this.computeRenderer)return;let t=this.resolveInputTexture(this.computeRenderer.optimization.input,e.originalTexture,e.previousTexture);this.computeRenderer.encode(e.commandEncoder,t,e.runtimeUniforms);for(let n of Object.values(this.computeRenderer.optimization.outputs))this.markTargetWritten(n)}resetHistory(){for(let e of Object.values(this.renderTargets))e.historyInitialized=!1,e.writtenThisFrame=!1}initializeHistoryTargets(e,t,n){for(let r of Object.values(this.renderTargets)){if(r.spec.lifetime!=="history"||r.historyInitialized)continue;let s=gs(r),o=r.spec.initialize||{clearColor:[0,0,0,0]};if(o==="original"){t.setProps({backgroundTexture:e}),t.predraw(n);let a=n.beginRenderPass({id:`${r.name}-initialize-history`,framebuffer:s,clearColor:[0,0,0,0],clearDepth:!1});t.draw(a),a.end()}else n.beginRenderPass({id:`${r.name}-clear-history`,framebuffer:s,clearColor:o.clearColor,clearDepth:!1}).end();r.historyInitialized=!0}}getOutputFramebuffer(e){return this.getRenderTarget(e).framebuffer}markTargetWritten(e){this.getRenderTarget(e).writtenThisFrame=!0}finishFrame(e){for(let t of Object.values(this.renderTargets)){if(e&&t.spec.lifetime==="history"&&t.writtenThisFrame){let n=ms(t),r=gs(t);t.historyTexture=t.texture,t.historyFramebuffer=t.framebuffer,t.texture=n,t.framebuffer=r,t.historyInitialized=!0}t.writtenThisFrame=!1}}getRenderTarget(e){let t=this.renderTargets[e];if(!t)throw new Error(`${this.getOwnerName()}: unknown render target "${e}"`);return t}resolveBindings(e){let{execution:t,originalTexture:n,previousTexture:r,outputTexture:s,externalBindings:o}=e,a=t.inputs||{sourceTexture:"previous"},c=this.shaderInputs.getModuleBindingValues(t.shaderPass.name),h=Object.fromEntries(Object.entries(o).filter(([d])=>t.shaderPass.bindingLayout?.some(f=>f.name===d))),u={...c,...h},l=t.output||"previous";for(let[d,f]of Object.entries(a)){if(!f)continue;let p=this.resolveInputTexture(f,n,r),b=f in this.renderTargets?this.renderTargets[f]:null;if(l!=="previous"&&f===l&&b?.spec.lifetime!=="history")throw new Error(`${t.ownerName}: subpass cannot read and write render target "${l}" in the same draw`);if(p===s)throw new Error(`${t.ownerName}: subpass cannot sample from the render target it is writing to`);u[d]=p}return"sourceTexture"in u||(u.sourceTexture=r),u}createStepExecutions(e,t,n){return fs(t.shaderPass,`${e.name}/${t.shaderPass.name}`),this.createPassExecutions(t.shaderPass,{ownerName:`${e.name}/${t.shaderPass.name}`,firstInputs:t.inputs,lastOutput:t.output,uniformOverrides:t.uniforms,flipY:n})}createPassExecutions(e,t){let n=e.passes||[];return n.map((r,s)=>{let o=s===0,a=s===n.length-1,c=o&&t.firstInputs!==void 0?t.firstInputs:r.inputs,h=a&&t.lastOutput!==void 0?t.lastOutput:r.output;return Wa(t.ownerName,c,h,this.renderTargets),{ownerName:t.ownerName,shaderPass:e,subPassRenderer:new bn(this.device,e,r,t.flipY),inputs:c,output:h,uniforms:_n(t.uniformOverrides,r.uniforms)}})}resolveInputTexture(e,t,n){switch(e){case"original":return t;case"previous":return n;default:{let r=this.getRenderTarget(e);return r.spec.lifetime==="history"&&!r.writtenThisFrame?ms(r):r.texture}}}getOwnerName(){return this.passDefinition.name}},yn=class{optimization;renderTargets;shaderInputs;computation;parameterBuffer;constructor(e,t,n,r){this.optimization=t,this.renderTargets=n,this.shaderInputs=r,this.parameterBuffer=e.createBuffer({id:`${t.name}-parameters`,byteLength:Math.max(Math.ceil(t.uniformNames.length/4)*16,16),usage:ce.Buffer.UNIFORM|ce.Buffer.COPY_DST});let s=Object.entries(t.outputs).map(([o,a],c)=>({name:o,type:"storage",group:0,location:c+2,access:"write-only",format:n[a].texture.format}));try{this.computation=new We(e,{id:t.name,source:t.source,shaderLayout:{bindings:[{name:t.uniformBinding,type:"uniform",group:0,location:0},{name:"sourceTexture",type:"texture",group:0,location:1,sampleType:"unfilterable-float"},...s]}})}catch(o){throw this.parameterBuffer.destroy(),o}}encode(e,t,n){let r={...this.shaderInputs.getUniformValues()[this.optimization.uniformModule]||{},...this.optimization.uniforms,...n[this.optimization.uniformModule]||{}},s=new Float32Array(Math.max(Math.ceil(this.optimization.uniformNames.length/4)*4,4));for(let[u,l]of this.optimization.uniformNames.entries()){let d=r[l];s[u]=typeof d=="number"?d:0}this.parameterBuffer.write(s);let o=Object.entries(this.optimization.outputs),a={[this.optimization.uniformBinding]:this.parameterBuffer,sourceTexture:t.view};for(let[u,l]of o)a[u]=this.renderTargets[l].texture.view;this.computation.setBindings(a),this.computation.predraw(e);let c=this.renderTargets[o[0][1]].texture,h=e.beginComputePass({id:this.optimization.name});this.computation.dispatch(h,Math.ceil(c.width/this.optimization.workgroupSize[0]),Math.ceil(c.height/this.optimization.workgroupSize[1]),1),h.end()}destroy(){this.computation.destroy(),this.parameterBuffer.destroy()}},bn=class{model;shaderPass;subPass;flipY;constructor(e,t,n,r){this.shaderPass=t,this.subPass=n,this.flipY=r;let s=n.action||n.filter&&"filter"||n.sampler&&"sample"||"filter",o=ls({shaderPass:t,action:s,shadingLanguage:e.info.shadingLanguage});this.model=new me(e,{id:`${t.name}-subpass`,source:o,fs:o,modules:[ds,t],parameters:{depthWriteEnabled:!1}})}destroy(){this.model.destroy()}prepare(e){let{commandEncoder:t,bindings:n,textureScale:r,uniforms:s}=e;this.model.shaderInputs.setProps({textureTransform:{scale:r,flipY:this.flipY?1:0}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:this.shaderPass.uniforms||{}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:s||{}}),this.model.setBindings(n||{}),this.model.predraw(t)}draw(e){this.model.draw(e)}};function Va(i){return i.flatMap(e=>ys(e)?e.steps.map(t=>t.shaderPass):[e])}function ys(i){return"steps"in i}function Xa(i,e){let t=e.compute;if(!t||i.type!=="webgpu")return!1;let n=Object.values(t.outputs);return n.length===0||n.length>i.limits.maxStorageTexturesPerShaderStage||t.workgroupSize[0]>i.limits.maxComputeWorkgroupSizeX||t.workgroupSize[1]>i.limits.maxComputeWorkgroupSizeY||t.workgroupSize[0]*t.workgroupSize[1]>i.limits.maxComputeInvocationsPerWorkgroup?!1:n.every(r=>{let s=e.renderTargets?.[r];if(!s?.storage)return!1;let o=s.format||i.preferredColorFormat;return i.getTextureFormatCapabilities(o).store})}function fs(i,e){let t=i.renderTargets;if(t&&Object.keys(t).length>0)throw new Error(`${e}: ShaderPass.renderTargets is not supported; use CompositeShaderPass.renderTargets instead`)}function Ya(i,e){for(let t of Object.keys(e))if($a.has(t))throw new Error(`${i}: render target name "${t}" is reserved`)}function Wa(i,e,t,n){let r=e||{sourceTexture:"previous"};for(let s of Object.values(r))if(s&&s!=="original"&&s!=="previous"&&!(s in n))throw new Error(`${i}: unknown input source "${s}"`);if(t&&t!=="previous"&&!(t in n))throw new Error(`${i}: unknown output target "${t}"`)}function _n(i,e){if(!(!i&&!e))return{...i||{},...e||{}}}function Ha(i,e,t){return _n(_n(i.getUniformValues()[e.shaderPass.name],e.uniforms),t[e.shaderPass.name])}function qa(i,e){let t=i.getCanvasContext().getDrawingBufferSize(),n={};for(let[r,s]of Object.entries(e)){if(s.aliasFor){let o=n[s.aliasFor];if(!o)throw new Error(`${r}: target alias references an unknown earlier target`);let a=In(t,s.scale),c=s.format||i.preferredColorFormat;if(s.lifetime==="history"||o.spec.lifetime==="history"||!Ka(s,o.spec)||o.texture.width!==a[0]||o.texture.height!==a[1]||o.texture.format!==c||s.storage&&!o.spec.storage||!Za(s,o.spec))throw new Error(`${r}: target alias must match a transient target's size, format, and sampler`);n[r]=o;continue}n[r]=bs(i,r,s,t)}return n}function Ka(i,e){let t=i.scale||[1,1],n=e.scale||[1,1];return t[0]===n[0]&&t[1]===n[1]}function Za(i,e){let t=i.sampler||{},n=e.sampler||{},r=Object.entries(t);return r.length===Object.keys(n).length&&r.every(([s,o])=>n[s]===o)}function Qa(i){for(let e of new Set(Object.values(i)))e.framebuffer.destroy(),e.texture.destroy(),e.historyFramebuffer?.destroy(),e.historyTexture?.destroy()}function Ja(i,e,t){for(let n of new Set(Object.values(e))){let r=In(t,n.spec.scale);if(n.texture.width===r[0]&&n.texture.height===r[1])continue;n.framebuffer.destroy(),n.texture.destroy(),n.historyFramebuffer?.destroy(),n.historyTexture?.destroy();let s=bs(i,n.name,n.spec,t);n.texture=s.texture,n.framebuffer=s.framebuffer,n.historyTexture=s.historyTexture,n.historyFramebuffer=s.historyFramebuffer,n.historyInitialized=!1,n.writtenThisFrame=!1}}function bs(i,e,t,n){let r=In(n,t.scale),{texture:s,framebuffer:o}=ps(i,e,t,r),a,c;if(t.lifetime==="history"){let h=ps(i,`${e}-history`,t,r);a=h.texture,c=h.framebuffer}return{name:e,spec:t,texture:s,framebuffer:o,historyTexture:a,historyFramebuffer:c,historyInitialized:!1,writtenThisFrame:!1}}function ps(i,e,t,n){let r=i.createTexture({id:`${e}-texture`,width:n[0],height:n[1],format:t.format||i.preferredColorFormat,usage:ce.Texture.SAMPLE|ce.Texture.RENDER|ce.Texture.COPY_SRC|ce.Texture.COPY_DST|(t.storage&&i.type==="webgpu"&&i.getTextureFormatCapabilities(t.format||i.preferredColorFormat).store?ce.Texture.STORAGE:0),...t.sampler?{sampler:t.sampler}:{}}),s=i.createFramebuffer({id:`${e}-framebuffer`,width:n[0],height:n[1],colorAttachments:[r]});return{texture:r,framebuffer:s}}function ms(i){if(!i.historyTexture)throw new Error(`${i.name}: transient render target has no history texture`);return i.historyTexture}function gs(i){if(!i.historyFramebuffer)throw new Error(`${i.name}: transient render target has no history framebuffer`);return i.historyFramebuffer}function In(i,e=[1,1]){return[Math.max(1,Math.round(i[0]*e[0])),Math.max(1,Math.round(i[1]*e[1]))]}function vn(i){let e=i.colorAttachments[0]?.texture;if(!e)throw new Error("ShaderPassRenderer: framebuffer is missing a color attachment texture");return e}function ec(i,e){return e===i.current?i.next:i.current}function tc(i,e){return vn(i.current)===e?i.next:i.current}function ic(i,e){let t=i.width/i.height,n=e.width/e.height;return n>t?[1,n/t]:[t/n,1]}var he=L(R(),1),xi=class i{static async createAsync(e,t){let n=!he.PipelineFactory.getAsyncCompilation(e),r=n?he.PipelineFactory.beginAsyncCompilation(e):he.PipelineFactory.getAsyncCompilation(e),s;try{s=new i(e,t)}finally{n&&he.PipelineFactory.endAsyncCompilation(e,r)}try{return n?await Promise.all(r):await s._pipelineInitialization,s}catch(o){throw s.destroy(),o}}device;id;source;pipelineFactory;shaderFactory;shader;pipeline;_pipelineInitialization;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Kernel is only supported in WebGPU");let{source:n,pipelineFactory:r,shaderFactory:s,debugShaders:o,...a}=t;this.device=e,this.id=t.id??"kernel",this.source=n,this.pipelineFactory=r??he.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=s??he.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:o});let c={...a,shader:this.shader},h=he.PipelineFactory.getAsyncCompilation(e);if(h){let u=this.pipelineFactory.createComputePipelineAsync(c);this._pipelineInitialization=u,h.push(u.then(l=>(this.pipeline=l,l)))}else this.pipeline=this.pipelineFactory.createComputePipeline(c)}dispatch(e,t){this._setPipeline(e,t.bindings),e.dispatch(t.x,t.y,t.z)}dispatchIndirect(e,t){this._setPipeline(e,t.bindings),e.dispatchIndirect(t.indirectBuffer,t.indirectOffset??0)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._destroyed=!0)}_setPipeline(e,t={}){e.setPipeline(this.pipeline),e.setBindings(t)}};var ue=L(R(),1),yi=class i{static async createAsync(e,t){let n=!ue.PipelineFactory.getAsyncCompilation(e),r=n?ue.PipelineFactory.beginAsyncCompilation(e):ue.PipelineFactory.getAsyncCompilation(e),s;try{s=new i(e,t)}finally{n&&ue.PipelineFactory.endAsyncCompilation(e,r)}try{return n?await Promise.all(r):await s._pipelineInitialization,s}catch(o){throw s.destroy(),o}}device;id;vertexSource;fragmentSource;pipelineFactory;shaderFactory;vertexShader;fragmentShader;pipeline;_pipelineInitialization;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("RenderKernel is only supported in WebGPU");let{vertexSource:n,fragmentSource:r,pipelineFactory:s,shaderFactory:o,debugShaders:a,...c}=t;this.device=e,this.id=t.id??"render-kernel",this.vertexSource=n,this.fragmentSource=r,this.pipelineFactory=s??ue.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=o??ue.ShaderFactory.getDefaultShaderFactory(e),this.vertexShader=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.vertexSource,debugShaders:a}),this.fragmentShader=this.fragmentSource?this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fragmentSource,debugShaders:a}):null;let h={...c,vs:this.vertexShader,fs:this.fragmentShader},u=ue.PipelineFactory.getAsyncCompilation(e);if(u){let l=this.pipelineFactory.createRenderPipelineAsync(h);this._pipelineInitialization=l,u.push(l.then(d=>(this.pipeline=d,d)))}else this.pipeline=this.pipelineFactory.createRenderPipeline(h)}draw(e,t){let{bindings:n={},vertexArray:r,...s}=t;return this._setPipeline(e,n,r),e.draw(s)}drawIndirect(e,t){let{bindings:n={},vertexArray:r,indirectBuffer:s,indirectOffset:o=0}=t;this._setPipeline(e,n,r),e.drawIndirect(s,o)}drawIndexedIndirect(e,t){let{bindings:n={},vertexArray:r,indirectBuffer:s,indirectOffset:o=0}=t;this._setPipeline(e,n,r),e.drawIndexedIndirect(s,o)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.vertexShader),this.fragmentShader&&this.shaderFactory.release(this.fragmentShader),this._destroyed=!0)}_setPipeline(e,t,n){e.setPipeline(this.pipeline),e.setBindings(t),e.setVertexArray(n)}};var Q=L(R(),1);var nc=[0,1,1,1],j=-1,rc={isActive:"i32",indexMode:"i32",batchIndex:"i32",isHighlightActive:"i32",highlightedBatchIndex:"i32",highlightedObjectIndex:"i32",highlightColor:"vec4<f32>"},le=`precision highp float;
|
|
267
|
+
`,uniformTypes:{scale:"vec2<f32>",flipY:"i32"}};var od=new Set(["original","previous"]),zn=class{device;shaderInputs;passRenderers;swapFramebuffers;textureModel;constructor(e,t){this.device=e;let n=ad(t.shaderPasses);n.map(a=>(0,Cc.initializeShaderModule)(a));let i=n.reduce((a,c)=>({...a,[c.name]:c}),{});this.shaderInputs=t.shaderInputs||new K(i);let s=e.getCanvasContext().getDrawingBufferSize();this.swapFramebuffers=new jt(e,{colorAttachments:[t.colorFormat||e.preferredColorFormat],width:s[0],height:s[1]}),this.textureModel=new Nt(e,{backgroundTexture:this.swapFramebuffers.current.colorAttachments[0].texture,flipY:t.flipY??e.type==="webgpu"});let o=t.flipY??e.type==="webgpu";this.passRenderers=t.shaderPasses.map(a=>new Cs(e,a,this.shaderInputs,o))}destroy(){for(let e of this.passRenderers)e.destroy();this.swapFramebuffers.destroy(),this.textureModel.destroy()}resize(e){e||=this.device.getCanvasContext().getDrawingBufferSize(),this.swapFramebuffers.resize({width:e[0],height:e[1]});for(let t of this.passRenderers)t.resize(e)}resetHistory(){for(let e of this.passRenderers)e.resetHistory()}renderToScreen(e){return this.encodeToScreen(this.device.commandEncoder,e)}encodeToScreen(e,t){let n=this.encodeToTexture(e,t);if(!n)return!1;let i=this.device.getDefaultCanvasContext().getCurrentFramebuffer({depthStencilFormat:!1});this.textureModel.setProps({backgroundTexture:n}),this.textureModel.predraw(e);let s=e.beginRenderPass({id:"shader-pass-renderer-to-screen",framebuffer:i,clearDepth:!1});return this.textureModel.draw(s),s.end(),!0}renderToTexture(e){return this.encodeToTexture(this.device.commandEncoder,e)}encodeToTexture(e,t){if(e.device!==this.device)throw new Error("ShaderPassRenderer command encoder must belong to the renderer device");let{sourceTexture:n}=t;if(n instanceof ce&&!n.isReady)return null;let i=n instanceof ce?n.texture:n;if(this.passRenderers.length===0)return i;t.resetHistory&&this.resetHistory(),this.textureModel.setProps({backgroundTexture:i}),this.textureModel.predraw(e);let s=xd(this.swapFramebuffers,i),o=e.beginRenderPass({id:"shader-pass-renderer-seed-source",framebuffer:s,clearColor:[0,0,0,1],clearDepth:!1});this.textureModel.draw(o),o.end();let a=s,c=Bs(s),u=!1;try{for(let h of this.passRenderers){h.initializeHistoryTargets(i,this.textureModel,e),h.runComputeOptimization({commandEncoder:e,originalTexture:i,previousTexture:c,runtimeUniforms:t.uniforms||{}});for(let l of h.subPassExecutions){let d=l.output||"previous",p=d==="previous"?yd(this.swapFramebuffers,a):h.getOutputFramebuffer(d),f=Bs(p),m=h.resolveBindings({execution:l,originalTexture:i,previousTexture:c,outputTexture:f,externalBindings:t.bindings||{}}),g=ld(this.shaderInputs,l,t.uniforms||{});l.subPassRenderer.prepare({commandEncoder:e,bindings:m,textureScale:bd(m.sourceTexture||c,f),uniforms:g});let x=e.beginRenderPass({id:"shader-pass-renderer-run-pass",framebuffer:p,clearColor:[0,0,0,1],clearDepth:1});l.subPassRenderer.draw(x),x.end(),d==="previous"?(c=f,a=p):h.markTargetWritten(d)}}u=!0}finally{for(let h of this.passRenderers)h.finishFrame(u)}return c}},Cs=class{device;shaderInputs;passDefinition;renderTargets;subPassExecutions;computeRenderer;constructor(e,t,n,i){if(this.device=e,this.shaderInputs=n,this.passDefinition=t,Ec(t)){ud(t.name,t.renderTargets||{}),this.renderTargets=dd(e,t.renderTargets||{}),cd(e,t)&&(this.computeRenderer=new Es(e,t.compute,this.renderTargets,n));let s=this.computeRenderer?t.steps.filter(o=>!t.compute.replacedPasses.includes(o.shaderPass.name)):t.steps;this.subPassExecutions=s.flatMap(o=>this.createStepExecutions(t,o,i));return}Ac(t,t.name),this.renderTargets={},this.subPassExecutions=this.createPassExecutions(t,{ownerName:t.name,flipY:i})}destroy(){this.computeRenderer?.destroy();for(let e of this.subPassExecutions)e.subPassRenderer.destroy();md(this.renderTargets)}resize(e){gd(this.device,this.renderTargets,e)}runComputeOptimization(e){if(!this.computeRenderer)return;let t=this.resolveInputTexture(this.computeRenderer.optimization.input,e.originalTexture,e.previousTexture);this.computeRenderer.encode(e.commandEncoder,t,e.runtimeUniforms);for(let n of Object.values(this.computeRenderer.optimization.outputs))this.markTargetWritten(n)}resetHistory(){for(let e of Object.values(this.renderTargets))e.historyInitialized=!1,e.writtenThisFrame=!1}initializeHistoryTargets(e,t,n){for(let i of Object.values(this.renderTargets)){if(i.spec.lifetime!=="history"||i.historyInitialized)continue;let s=Sc(i),o=i.spec.initialize||{clearColor:[0,0,0,0]};if(o==="original"){t.setProps({backgroundTexture:e}),t.predraw(n);let a=n.beginRenderPass({id:`${i.name}-initialize-history`,framebuffer:s,clearColor:[0,0,0,0],clearDepth:!1});t.draw(a),a.end()}else n.beginRenderPass({id:`${i.name}-clear-history`,framebuffer:s,clearColor:o.clearColor,clearDepth:!1}).end();i.historyInitialized=!0}}getOutputFramebuffer(e){return this.getRenderTarget(e).framebuffer}markTargetWritten(e){this.getRenderTarget(e).writtenThisFrame=!0}finishFrame(e){for(let t of Object.values(this.renderTargets)){if(e&&t.spec.lifetime==="history"&&t.writtenThisFrame){let n=Pc(t),i=Sc(t);t.historyTexture=t.texture,t.historyFramebuffer=t.framebuffer,t.texture=n,t.framebuffer=i,t.historyInitialized=!0}t.writtenThisFrame=!1}}getRenderTarget(e){let t=this.renderTargets[e];if(!t)throw new Error(`${this.getOwnerName()}: unknown render target "${e}"`);return t}resolveBindings(e){let{execution:t,originalTexture:n,previousTexture:i,outputTexture:s,externalBindings:o}=e,a=t.inputs||{sourceTexture:"previous"},c=this.shaderInputs.getModuleBindingValues(t.shaderPass.name),u=Object.fromEntries(Object.entries(o).filter(([d])=>t.shaderPass.bindingLayout?.some(p=>p.name===d))),h={...c,...u},l=t.output||"previous";for(let[d,p]of Object.entries(a)){if(!p)continue;let f=this.resolveInputTexture(p,n,i),m=p in this.renderTargets?this.renderTargets[p]:null;if(l!=="previous"&&p===l&&m?.spec.lifetime!=="history")throw new Error(`${t.ownerName}: subpass cannot read and write render target "${l}" in the same draw`);if(f===s)throw new Error(`${t.ownerName}: subpass cannot sample from the render target it is writing to`);h[d]=f}return"sourceTexture"in h||(h.sourceTexture=i),h}createStepExecutions(e,t,n){return Ac(t.shaderPass,`${e.name}/${t.shaderPass.name}`),this.createPassExecutions(t.shaderPass,{ownerName:`${e.name}/${t.shaderPass.name}`,firstInputs:t.inputs,lastOutput:t.output,uniformOverrides:t.uniforms,flipY:n})}createPassExecutions(e,t){let n=e.passes||[];return n.map((i,s)=>{let o=s===0,a=s===n.length-1,c=o&&t.firstInputs!==void 0?t.firstInputs:i.inputs,u=a&&t.lastOutput!==void 0?t.lastOutput:i.output;return hd(t.ownerName,c,u,this.renderTargets),{ownerName:t.ownerName,shaderPass:e,subPassRenderer:new Rs(this.device,e,i,t.flipY),inputs:c,output:u,uniforms:Ls(t.uniformOverrides,i.uniforms)}})}resolveInputTexture(e,t,n){switch(e){case"original":return t;case"previous":return n;default:{let i=this.getRenderTarget(e);return i.spec.lifetime==="history"&&!i.writtenThisFrame?Pc(i):i.texture}}}getOwnerName(){return this.passDefinition.name}},Es=class{optimization;renderTargets;shaderInputs;computation;parameterBuffer;constructor(e,t,n,i){this.optimization=t,this.renderTargets=n,this.shaderInputs=i,this.parameterBuffer=e.createBuffer({id:`${t.name}-parameters`,byteLength:Math.max(Math.ceil(t.uniformNames.length/4)*16,16),usage:Le.Buffer.UNIFORM|Le.Buffer.COPY_DST});let s=Object.entries(t.outputs).map(([o,a],c)=>({name:o,type:"storage",group:0,location:c+2,access:"write-only",format:n[a].texture.format}));try{this.computation=new $t(e,{id:t.name,source:t.source,shaderLayout:{bindings:[{name:t.uniformBinding,type:"uniform",group:0,location:0},{name:"sourceTexture",type:"texture",group:0,location:1,sampleType:"unfilterable-float"},...s]}})}catch(o){throw this.parameterBuffer.destroy(),o}}encode(e,t,n){let i={...this.shaderInputs.getUniformValues()[this.optimization.uniformModule]||{},...this.optimization.uniforms,...n[this.optimization.uniformModule]||{}},s=new Float32Array(Math.max(Math.ceil(this.optimization.uniformNames.length/4)*4,4));for(let[h,l]of this.optimization.uniformNames.entries()){let d=i[l];s[h]=typeof d=="number"?d:0}this.parameterBuffer.write(s);let o=Object.entries(this.optimization.outputs),a={[this.optimization.uniformBinding]:this.parameterBuffer,sourceTexture:t.view};for(let[h,l]of o)a[h]=this.renderTargets[l].texture.view;this.computation.setBindings(a),this.computation.predraw(e);let c=this.renderTargets[o[0][1]].texture,u=e.beginComputePass({id:this.optimization.name});this.computation.dispatch(u,Math.ceil(c.width/this.optimization.workgroupSize[0]),Math.ceil(c.height/this.optimization.workgroupSize[1]),1),u.end()}destroy(){this.computation.destroy(),this.parameterBuffer.destroy()}},Rs=class{model;shaderPass;subPass;flipY;constructor(e,t,n,i){this.shaderPass=t,this.subPass=n,this.flipY=i;let s=n.action||n.filter&&"filter"||n.sampler&&"sample"||"filter",o=Mc({shaderPass:t,action:s,shadingLanguage:e.info.shadingLanguage});this.model=new We(e,{id:`${t.name}-subpass`,source:o,fs:o,modules:[_c,t],parameters:{depthWriteEnabled:!1}})}destroy(){this.model.destroy()}prepare(e){let{commandEncoder:t,bindings:n,textureScale:i,uniforms:s}=e;this.model.shaderInputs.setProps({textureTransform:{scale:i,flipY:this.flipY?1:0}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:this.shaderPass.uniforms||{}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:s||{}}),this.model.setBindings(n||{}),this.model.predraw(t)}draw(e){this.model.draw(e)}};function ad(r){return r.flatMap(e=>Ec(e)?e.steps.map(t=>t.shaderPass):[e])}function Ec(r){return"steps"in r}function cd(r,e){let t=e.compute;if(!t||r.type!=="webgpu")return!1;let n=Object.values(t.outputs);return n.length===0||n.length>r.limits.maxStorageTexturesPerShaderStage||t.workgroupSize[0]>r.limits.maxComputeWorkgroupSizeX||t.workgroupSize[1]>r.limits.maxComputeWorkgroupSizeY||t.workgroupSize[0]*t.workgroupSize[1]>r.limits.maxComputeInvocationsPerWorkgroup?!1:n.every(i=>{let s=e.renderTargets?.[i];if(!s?.storage)return!1;let o=s.format||r.preferredColorFormat;return r.getTextureFormatCapabilities(o).store})}function Ac(r,e){let t=r.renderTargets;if(t&&Object.keys(t).length>0)throw new Error(`${e}: ShaderPass.renderTargets is not supported; use CompositeShaderPass.renderTargets instead`)}function ud(r,e){for(let t of Object.keys(e))if(od.has(t))throw new Error(`${r}: render target name "${t}" is reserved`)}function hd(r,e,t,n){let i=e||{sourceTexture:"previous"};for(let s of Object.values(i))if(s&&s!=="original"&&s!=="previous"&&!(s in n))throw new Error(`${r}: unknown input source "${s}"`);if(t&&t!=="previous"&&!(t in n))throw new Error(`${r}: unknown output target "${t}"`)}function Ls(r,e){if(!(!r&&!e))return{...r||{},...e||{}}}function ld(r,e,t){return Ls(Ls(r.getUniformValues()[e.shaderPass.name],e.uniforms),t[e.shaderPass.name])}function dd(r,e){let t=r.getCanvasContext().getDrawingBufferSize(),n={};for(let[i,s]of Object.entries(e)){if(s.aliasFor){let o=n[s.aliasFor];if(!o)throw new Error(`${i}: target alias references an unknown earlier target`);let a=Os(t,s.scale),c=s.format||r.preferredColorFormat;if(s.lifetime==="history"||o.spec.lifetime==="history"||!fd(s,o.spec)||o.texture.width!==a[0]||o.texture.height!==a[1]||o.texture.format!==c||s.storage&&!o.spec.storage||!pd(s,o.spec))throw new Error(`${i}: target alias must match a transient target's size, format, and sampler`);n[i]=o;continue}n[i]=Rc(r,i,s,t)}return n}function fd(r,e){let t=r.scale||[1,1],n=e.scale||[1,1];return t[0]===n[0]&&t[1]===n[1]}function pd(r,e){let t=r.sampler||{},n=e.sampler||{},i=Object.entries(t);return i.length===Object.keys(n).length&&i.every(([s,o])=>n[s]===o)}function md(r){for(let e of new Set(Object.values(r)))e.framebuffer.destroy(),e.texture.destroy(),e.historyFramebuffer?.destroy(),e.historyTexture?.destroy()}function gd(r,e,t){for(let n of new Set(Object.values(e))){let i=Os(t,n.spec.scale);if(n.texture.width===i[0]&&n.texture.height===i[1])continue;n.framebuffer.destroy(),n.texture.destroy(),n.historyFramebuffer?.destroy(),n.historyTexture?.destroy();let s=Rc(r,n.name,n.spec,t);n.texture=s.texture,n.framebuffer=s.framebuffer,n.historyTexture=s.historyTexture,n.historyFramebuffer=s.historyFramebuffer,n.historyInitialized=!1,n.writtenThisFrame=!1}}function Rc(r,e,t,n){let i=Os(n,t.scale),{texture:s,framebuffer:o}=Ic(r,e,t,i),a,c;if(t.lifetime==="history"){let u=Ic(r,`${e}-history`,t,i);a=u.texture,c=u.framebuffer}return{name:e,spec:t,texture:s,framebuffer:o,historyTexture:a,historyFramebuffer:c,historyInitialized:!1,writtenThisFrame:!1}}function Ic(r,e,t,n){let i=r.createTexture({id:`${e}-texture`,width:n[0],height:n[1],format:t.format||r.preferredColorFormat,usage:Le.Texture.SAMPLE|Le.Texture.RENDER|Le.Texture.COPY_SRC|Le.Texture.COPY_DST|(t.storage&&r.type==="webgpu"&&r.getTextureFormatCapabilities(t.format||r.preferredColorFormat).store?Le.Texture.STORAGE:0),...t.sampler?{sampler:t.sampler}:{}}),s=r.createFramebuffer({id:`${e}-framebuffer`,width:n[0],height:n[1],colorAttachments:[i]});return{texture:i,framebuffer:s}}function Pc(r){if(!r.historyTexture)throw new Error(`${r.name}: transient render target has no history texture`);return r.historyTexture}function Sc(r){if(!r.historyFramebuffer)throw new Error(`${r.name}: transient render target has no history framebuffer`);return r.historyFramebuffer}function Os(r,e=[1,1]){return[Math.max(1,Math.round(r[0]*e[0])),Math.max(1,Math.round(r[1]*e[1]))]}function Bs(r){let e=r.colorAttachments[0]?.texture;if(!e)throw new Error("ShaderPassRenderer: framebuffer is missing a color attachment texture");return e}function yd(r,e){return e===r.current?r.next:r.current}function xd(r,e){return Bs(r.current)===e?r.next:r.current}function bd(r,e){let t=r.width/r.height,n=e.width/e.height;return n>t?[1,n/t]:[t/n,1]}var pe=B(D(),1);var vd=[0,1,1,1],U=-1,Td={isActive:"i32",indexMode:"i32",batchIndex:"i32",isHighlightActive:"i32",highlightedBatchIndex:"i32",highlightedObjectIndex:"i32",highlightColor:"vec4<f32>"},Be=`precision highp float;
|
|
268
268
|
precision highp int;
|
|
269
269
|
|
|
270
270
|
layout(std140) uniform pickingUniforms {
|
|
@@ -277,7 +277,7 @@ layout(std140) uniform pickingUniforms {
|
|
|
277
277
|
int highlightedObjectIndex;
|
|
278
278
|
vec4 highlightColor;
|
|
279
279
|
} picking;
|
|
280
|
-
`,
|
|
280
|
+
`,qt=`struct pickingUniforms {
|
|
281
281
|
isActive: i32,
|
|
282
282
|
indexMode: i32,
|
|
283
283
|
batchIndex: i32,
|
|
@@ -289,9 +289,9 @@ layout(std140) uniform pickingUniforms {
|
|
|
289
289
|
};
|
|
290
290
|
|
|
291
291
|
@group(0) @binding(auto) var<uniform> picking: pickingUniforms;
|
|
292
|
-
`;function
|
|
292
|
+
`;function wd(r={},e){let t={...e};switch(r.isActive!==void 0&&(t.isActive=!!r.isActive),r.indexMode){case"instance":t.indexMode=0;break;case"attribute":t.indexMode=1;break;case"vertex":t.indexMode=2;break;case void 0:break}switch(typeof r.batchIndex=="number"&&(t.batchIndex=r.batchIndex),r.highlightedObjectIndex){case void 0:break;case null:t.isHighlightActive=!1,t.highlightedObjectIndex=U;break;default:t.isHighlightActive=!0,t.highlightedObjectIndex=r.highlightedObjectIndex}switch(r.highlightedBatchIndex){case void 0:break;case null:t.isHighlightActive=!1,t.highlightedBatchIndex=U;break;default:t.isHighlightActive=!0,t.highlightedBatchIndex=r.highlightedBatchIndex}return r.highlightColor&&(t.highlightColor=r.highlightColor),t}var Ke={props:{},uniforms:{},name:"picking",uniformTypes:Td,defaultUniforms:{isActive:!1,indexMode:0,batchIndex:0,isHighlightActive:!1,highlightedBatchIndex:U,highlightedObjectIndex:U,highlightColor:vd},getUniforms:wd};var Lc=1,Md=new Int32Array([U,U,0,0]);var Bc=14,Wt=8;function Vn(r,e="color",t=r==="webgpu"){if(e==="auto")return t?"index":"color";if(e==="index"&&!t)throw new Error(`Picking mode "${e}" requires WebGPU or a WebGL device that supports renderable rg32sint textures.`);return e}function vr(r){return r.type==="webgpu"||r.type==="webgl"&&r.isTextureFormatRenderable("rg32sint")}var kc=Vn;function Oc(r){return{objectIndex:r[0]===U?null:r[0],batchIndex:r[1]===U?null:r[1]}}function Dc(r){let e=r[0]+r[1]*256+r[2]*65536;if(e===0)return{objectIndex:null,batchIndex:null};let t=r[3]>0?r[3]-1:0;return{objectIndex:e-1,batchIndex:t}}var Gn=class r{device;props;mode;pickInfo={batchIndex:null,objectIndex:null};framebuffer=null;lastMousePosition=null;tooltipElement=null;static defaultProps={shaderInputs:void 0,onObjectPicked:()=>{},getTooltip:()=>null,mode:"color",backend:"color"};constructor(e,t){this.device=e,this.props={...r.defaultProps,...t};let n=t.mode??t.backend??r.defaultProps.mode;this.props.mode=n,this.props.backend=n,this.mode=Vn(this.device.type,n,vr(this.device))}destroy(){this.framebuffer?.destroy(),this.tooltipElement?.remove(),this.tooltipElement=null}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.mode==="index"?this.createIndexFramebuffer():this.createColorFramebuffer()),this.framebuffer}clearPickState(){this.lastMousePosition=null,this.setPickingProps({highlightedBatchIndex:null,highlightedObjectIndex:null}),this.hideTooltip()}shouldPick(e,t={}){if(!e)return this.lastMousePosition&&this.clearPickState(),!1;let[n,i]=e;return!t.force&&this.lastMousePosition&&this.lastMousePosition[0]===n&&this.lastMousePosition[1]===i?!1:(this.lastMousePosition=[n,i],!0)}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getDefaultCanvasContext().getDevicePixelSize()),this.setPickingProps({isActive:!0}),this.mode==="index"?this.device.beginRenderPass({framebuffer:e,clearColors:[new Float32Array([0,0,0,0]),Md],clearDepth:1}):this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}async updatePickInfo(e){let t=this.getFramebuffer(),n=this.getPickPosition(e),i=await this.readPickInfo(t,n);return i?(this.hasPickInfoChanged(i)&&(this.pickInfo=i,this.props.onObjectPicked(i)),this.updateTooltip(i,e),this.setPickingProps({isActive:!1,highlightedBatchIndex:i.batchIndex,highlightedObjectIndex:i.objectIndex}),this.pickInfo):null}getPickPosition(e){let t=this.device.type!=="webgpu",n=this.device.getDefaultCanvasContext().cssToDevicePixels(e,t),i=n.x+Math.floor(n.width/2),s=n.y+Math.floor(n.height/2);return[i,s]}createIndexFramebuffer(){let e=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:pe.Texture.RENDER_ATTACHMENT}),t=this.device.createTexture({format:"rg32sint",width:1,height:1,usage:pe.Texture.RENDER_ATTACHMENT|pe.Texture.COPY_SRC});return this.device.createFramebuffer({colorAttachments:[e,t],depthStencilAttachment:"depth24plus"})}createColorFramebuffer(){let e=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:pe.Texture.RENDER_ATTACHMENT|pe.Texture.COPY_SRC});return this.device.createFramebuffer({colorAttachments:[e],depthStencilAttachment:"depth24plus"})}setPickingProps(e){this.props.shaderInputs?.setProps({picking:e})}async readPickInfo(e,t){return this.mode==="index"?this.readIndexPickInfo(e,t):this.readColorPickInfo(e,t)}async readIndexPickInfo(e,[t,n]){if(this.device.type==="webgpu"){let s=e.colorAttachments[Lc]?.texture;if(!s)return null;let o=s.computeMemoryLayout({width:1,height:1}),a=this.device.createBuffer({byteLength:o.byteLength,usage:pe.Buffer.COPY_DST|pe.Buffer.MAP_READ});try{s.readBuffer({x:t,y:n,width:1,height:1},a);let c=await a.readAsync(0,o.byteLength);return Oc(new Int32Array(c.buffer,c.byteOffset,2))}finally{a.destroy()}}let i=this.device.readPixelsToArrayWebGL(e,{sourceX:t,sourceY:n,sourceWidth:1,sourceHeight:1,sourceAttachment:Lc});return i?Oc(new Int32Array(i.buffer,i.byteOffset,2)):null}async readColorPickInfo(e,[t,n]){if(this.device.type==="webgpu"){let s=e.colorAttachments[0]?.texture;if(!s)return null;let o=s.computeMemoryLayout({width:1,height:1}),a=this.device.createBuffer({byteLength:o.byteLength,usage:pe.Buffer.COPY_DST|pe.Buffer.MAP_READ});try{s.readBuffer({x:t,y:n,width:1,height:1},a);let c=await a.readAsync(0,o.byteLength);return Dc(new Uint8Array(c.buffer,c.byteOffset,4))}finally{a.destroy()}}let i=this.device.readPixelsToArrayWebGL(e,{sourceX:t,sourceY:n,sourceWidth:1,sourceHeight:1,sourceAttachment:0});return i?Dc(new Uint8Array(i.buffer,i.byteOffset,4)):null}hasPickInfoChanged(e){return e.objectIndex!==this.pickInfo.objectIndex||e.batchIndex!==this.pickInfo.batchIndex}updateTooltip(e,t){let n=this.props.getTooltip(e);if(!n){this.hideTooltip();return}let i=this.getOrCreateTooltipElement();i&&(i.textContent=n,i.style.display="block",this.positionTooltip(i,t))}hideTooltip(){this.tooltipElement&&(this.tooltipElement.style.display="none")}getOrCreateTooltipElement(){if(this.tooltipElement)return this.tooltipElement;if(typeof document>"u"||typeof window>"u"||typeof HTMLCanvasElement>"u"||typeof this.device.getDefaultCanvasContext!="function")return null;let e=this.device.getDefaultCanvasContext().canvas;if(!(e instanceof HTMLCanvasElement)||!e.parentElement)return null;let t=document.createElement("div");t.style.position="absolute",t.style.zIndex="12",t.style.display="none",t.style.maxWidth="220px",t.style.padding="8px 10px",t.style.borderRadius="6px",t.style.background="rgba(15, 23, 42, 0.92)",t.style.color="#f8fafc",t.style.font="600 13px/1.35 system-ui, sans-serif",t.style.pointerEvents="none",t.style.whiteSpace="nowrap",t.style.boxShadow="0 10px 24px rgba(15, 23, 42, 0.22)";let n=e.parentElement;return window.getComputedStyle(n).position==="static"&&(n.style.position="relative"),n.appendChild(t),this.tooltipElement=t,t}positionTooltip(e,t){if(typeof HTMLCanvasElement>"u"||typeof this.device.getDefaultCanvasContext!="function")return;let n=this.device.getDefaultCanvasContext().canvas;if(!(n instanceof HTMLCanvasElement))return;let i=Math.max(Wt,n.clientWidth-e.offsetWidth-Wt),s=Math.max(Wt,n.clientHeight-e.offsetHeight-Wt),o=Math.min(t[0]+Bc,i),a=Math.min(t[1]+Bc,s);e.style.left=`${Math.max(Wt,o)}px`,e.style.top=`${Math.max(Wt,a)}px`}};var _d=`${qt}
|
|
293
293
|
|
|
294
|
-
const COLOR_PICKING_INVALID_INDEX = ${
|
|
294
|
+
const COLOR_PICKING_INVALID_INDEX = ${U};
|
|
295
295
|
const COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
|
|
296
296
|
const COLOR_PICKING_MAX_BATCH_INDEX = 254;
|
|
297
297
|
|
|
@@ -360,12 +360,12 @@ fn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {
|
|
|
360
360
|
|
|
361
361
|
return color;
|
|
362
362
|
}
|
|
363
|
-
`,
|
|
363
|
+
`,Ad=`${Be}
|
|
364
364
|
|
|
365
365
|
const int INDEX_PICKING_MODE_INSTANCE = 0;
|
|
366
366
|
const int INDEX_PICKING_MODE_CUSTOM = 1;
|
|
367
367
|
|
|
368
|
-
const int COLOR_PICKING_INVALID_INDEX = ${
|
|
368
|
+
const int COLOR_PICKING_INVALID_INDEX = ${U};
|
|
369
369
|
|
|
370
370
|
flat out int picking_objectIndex;
|
|
371
371
|
|
|
@@ -379,9 +379,9 @@ void picking_setObjectIndex(int objectIndex) {
|
|
|
379
379
|
break;
|
|
380
380
|
}
|
|
381
381
|
}
|
|
382
|
-
`,
|
|
382
|
+
`,Id=`${Be}
|
|
383
383
|
|
|
384
|
-
const int COLOR_PICKING_INVALID_INDEX = ${
|
|
384
|
+
const int COLOR_PICKING_INVALID_INDEX = ${U};
|
|
385
385
|
const int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
|
|
386
386
|
const int COLOR_PICKING_MAX_BATCH_INDEX = 254;
|
|
387
387
|
|
|
@@ -452,9 +452,9 @@ vec4 picking_filterColor(vec4 color) {
|
|
|
452
452
|
outColor = picking_filterPickingColor(outColor);
|
|
453
453
|
return outColor;
|
|
454
454
|
}
|
|
455
|
-
`,
|
|
455
|
+
`,Tr={...Ke,name:"picking",source:_d,vs:Ad,fs:Id};var Pd=`${qt}
|
|
456
456
|
|
|
457
|
-
const COLOR_PICKING_INVALID_INDEX = ${
|
|
457
|
+
const COLOR_PICKING_INVALID_INDEX = ${U};
|
|
458
458
|
const COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
|
|
459
459
|
const COLOR_PICKING_MAX_BATCH_INDEX = 254;
|
|
460
460
|
|
|
@@ -542,7 +542,7 @@ fn picking_filterColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {
|
|
|
542
542
|
outColor = picking_filterPickingColor(outColor, objectIndex);
|
|
543
543
|
return outColor;
|
|
544
544
|
}
|
|
545
|
-
`,
|
|
545
|
+
`,Sd=`${Be}
|
|
546
546
|
|
|
547
547
|
const int INDEX_PICKING_MODE_INSTANCE = 0;
|
|
548
548
|
const int INDEX_PICKING_MODE_ATTRIBUTE = 1;
|
|
@@ -563,9 +563,9 @@ void picking_setObjectIndex(int objectIndex) {
|
|
|
563
563
|
break;
|
|
564
564
|
}
|
|
565
565
|
}
|
|
566
|
-
`,
|
|
566
|
+
`,Cd=`${Be}
|
|
567
567
|
|
|
568
|
-
const int COLOR_PICKING_INVALID_INDEX = ${
|
|
568
|
+
const int COLOR_PICKING_INVALID_INDEX = ${U};
|
|
569
569
|
const int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
|
|
570
570
|
const int COLOR_PICKING_MAX_BATCH_INDEX = 254;
|
|
571
571
|
|
|
@@ -636,12 +636,12 @@ vec4 picking_filterColor(vec4 color) {
|
|
|
636
636
|
outColor = picking_filterPickingColor(outColor);
|
|
637
637
|
return outColor;
|
|
638
638
|
}
|
|
639
|
-
`,
|
|
639
|
+
`,Un={...Ke,name:"picking",source:Pd,vs:Sd,fs:Cd};var Ed=`${qt}
|
|
640
640
|
|
|
641
641
|
const INDEX_PICKING_MODE_INSTANCE = 0;
|
|
642
642
|
const INDEX_PICKING_MODE_ATTRIBUTE = 1;
|
|
643
643
|
const INDEX_PICKING_MODE_VERTEX = 2;
|
|
644
|
-
const INDEX_PICKING_INVALID_INDEX = ${
|
|
644
|
+
const INDEX_PICKING_INVALID_INDEX = ${U}; // 2^32 - 1
|
|
645
645
|
|
|
646
646
|
/**
|
|
647
647
|
* WGSL shaders need to carry the returned object index through their own stage outputs.
|
|
@@ -696,13 +696,13 @@ fn picking_getPickingColor(objectIndex: i32) -> vec2<i32> {
|
|
|
696
696
|
return vec2<i32>(objectIndex, picking.batchIndex);
|
|
697
697
|
}
|
|
698
698
|
|
|
699
|
-
`,
|
|
699
|
+
`,Rd=`${Be}
|
|
700
700
|
|
|
701
701
|
const int INDEX_PICKING_MODE_INSTANCE = 0;
|
|
702
702
|
const int INDEX_PICKING_MODE_ATTRIBUTE = 1;
|
|
703
703
|
const int INDEX_PICKING_MODE_VERTEX = 2;
|
|
704
704
|
|
|
705
|
-
const int INDEX_PICKING_INVALID_INDEX = ${
|
|
705
|
+
const int INDEX_PICKING_INVALID_INDEX = ${U}; // 2^32 - 1
|
|
706
706
|
|
|
707
707
|
flat out int picking_objectIndex;
|
|
708
708
|
|
|
@@ -723,9 +723,9 @@ void picking_setObjectIndex(int objectIndex) {
|
|
|
723
723
|
break;
|
|
724
724
|
}
|
|
725
725
|
}
|
|
726
|
-
`,
|
|
726
|
+
`,Ld=`${Be}
|
|
727
727
|
|
|
728
|
-
const int INDEX_PICKING_INVALID_INDEX = ${
|
|
728
|
+
const int INDEX_PICKING_INVALID_INDEX = ${U}; // 2^32 - 1
|
|
729
729
|
|
|
730
730
|
flat in int picking_objectIndex;
|
|
731
731
|
|
|
@@ -791,6 +791,10 @@ vec4 picking_filterColor(vec4 color) {
|
|
|
791
791
|
outColor = picking_filterPickingColor(outColor);
|
|
792
792
|
return outColor;
|
|
793
793
|
}
|
|
794
|
-
`,ft={...be,name:"picking",source:fc,vs:pc,fs:mc};var Ts={...be,name:"picking",source:ft.source,vs:dt.vs,fs:dt.fs};function As(i){return lt(i)?ft:vi}var Ii=class{device;framebuffer=null;shaderInputs;constructor(e,t){this.device=e,this.shaderInputs=t}destroy(){this.framebuffer?.destroy()}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.device.createFramebuffer({colorAttachments:["rgba8unorm"],depthStencilAttachment:"depth24plus"})),this.framebuffer}clearPickState(){this.shaderInputs.setProps({picking:{highlightedObjectColor:null}})}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getCanvasContext().getDevicePixelSize()),this.shaderInputs.setProps({picking:{isActive:!0}}),this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}updatePickState(e){let t=this.getFramebuffer(),[n,r]=this.getPickPosition(e),o=[...this.device.readPixelsToArrayWebGL(t,{sourceX:n,sourceY:r,sourceWidth:1,sourceHeight:1})].map(c=>c/255);o[0]+o[1]+o[2]>0||(o=null),this.shaderInputs.setProps({picking:{isActive:!1,highlightedObjectColor:o}})}getPickPosition(e){let t=this.device.getCanvasContext().cssToDevicePixels(e),n=t.x+Math.floor(t.width/2),r=t.y+Math.floor(t.height/2);return[n,r]}};var Ps=L(re(),1),Ss=Ps.picking;var gc=Z;return Ns(pt);})();
|
|
794
|
+
`,wr={...Ke,name:"picking",source:Ed,vs:Rd,fs:Ld};var Fc={...Ke,name:"picking",source:wr.source,vs:Tr.vs,fs:Tr.fs};function Nc(r){return vr(r)?wr:Un}var at=B(D(),1);var jn=class{bindings;scenes;constructor(e){this.scenes=e.scenes,this.bindings=e.bindings,this.update()}update(){if(this.bindings.length===0)return;let e=new Map;for(let t of this.scenes)t.preorderTraversal((n,{worldMatrix:i})=>{n instanceof re&&e.set(n,new C(i))});for(let t of this.bindings){Yr({joints:t.joints,meshNode:t.node,worldMatrices:e,inverseBindMatrices:t.inverseBindMatrices,target:t.jointMatrices}),t.skinJointMatrices&&(t.skinJointMatrices instanceof at.Buffer?t.skinJointMatrices.write(t.jointMatrices):t.skinJointMatrices.writeData(t.jointMatrices,{width:t.joints.length*4,height:1}));for(let n of t.models)n.model.shaderInputs.setProps({skin:t.skinJointMatrices?{jointMatrices:[],skinJointMatrices:t.skinJointMatrices}:{jointMatrices:t.jointMatrices}})}}getBinding(e){return this.bindings.find(t=>t.node===e)}destroy(){for(let e of this.bindings)e.skinJointMatrices?.destroy()}};function zc(r,e,t){if(r.type==="webgpu")return r.createBuffer({id:`${e}-skin-joint-matrices`,byteLength:t.byteLength,usage:at.Buffer.STORAGE|at.Buffer.COPY_DST});let n=t.length/4;if(n>r.limits.maxTextureDimension2D)throw new Error("Skin palette exceeds the device texture width limit");return r.createTexture({id:`${e}-skin-joint-matrices`,format:"rgba32float",width:n,height:1,usage:at.Texture.SAMPLE|at.Texture.COPY_DST,sampler:{minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}})}var $n=class{variants;names;activeVariant=null;bindings;constructor(e){this.variants=e.variants,this.names=this.variants.map(t=>t.name),this.bindings=e.bindings}selectVariant(e){let t=this.variants.find(n=>n.name===e);if(!t)throw new Error(`Unknown material variant: ${e}`);for(let{modelNode:n,...i}of this.bindings){let s=i.mappings.get(t.index);n.model.setMaterial(s?.material||i.defaultMaterial),n.model.setParameters(s?.parameters||i.defaultParameters)}this.activeVariant=e}resetVariant(){for(let{modelNode:e,...t}of this.bindings)e.model.setMaterial(t.defaultMaterial),e.model.setParameters(t.defaultParameters);this.activeVariant=null}};var qn=B(D(),1);var Wn=class{scenes;bindings=new Map;cameraDepths=new Map;constructor(e){this.scenes=e.scenes;for(let t of e.bindings){let{definition:n}=t,i=new R(n.viewDirection||[0,0,1]),s=new R(n.up||[0,1,0]);(0,qn.assert)(i.magnitude()>0&&s.magnitude()>0),(0,qn.assert)(new R(i).normalize().cross(new R(s).normalize()).magnitude()>1e-6),this.bindings.set(t.node,t)}}getDrawEntries(e){let{sceneIndex:t=0,cameraId:n="default"}=e,i=this.scenes[t];(0,qn.assert)(i);let s=new C(e.viewMatrix),o=new C(s).invert(),a=new R(o.getTranslation()),c=new R(1,0,0).transformAsVector(o).normalize(),u=new R(0,1,0).transformAsVector(o).normalize(),h=this.cameraDepths.get(n);h||(h=new Map,this.cameraDepths.set(n,h));let l=new Set,d=[],p=(f,m,g,x=0)=>{if(!f.display)return;let T=new C(m).multiplyRight(f.matrix),v=this.bindings.get(f),w=g||!!v?.definition.overlay;if(v?.definition.overlay&&(x=new R(T.getTranslation()).distance(a)),v){l.add(f);let y=new R(T.getTranslation()),b=new R(a).subtract(y);b.magnitude()<1e-8&&b.copy([o[8],o[9],o[10]]),v.definition.rotationAxis==="y"&&(b[1]=0,b.magnitude()<1e-8&&b.copy([0,0,1])),b.normalize();let M=v.definition.rotationAxis==="y"?new R(0,1,0):new R(b).cross(c);M.magnitude()<1e-8&&(M=new R(u).subtract(new R(b).scale(u.dot(b)))),M.normalize();let _=Gc(b,M),A=v.matrixAuthored?new R(f.matrix.getScale()):new R(f.scale);v.matrixAuthored&&f.matrix.determinant()<0&&(A[0]=-A[0]);let S=new R(v.definition.viewDirection||[0,0,1]).multiply(A),L=new R(v.definition.up||[0,1,0]).multiply(A),I=S.magnitude()>1e-8&&L.magnitude()>1e-8&&new R(S).normalize().cross(new R(L).normalize()).magnitude()>1e-8,O=Gc(I?S:new R(v.definition.viewDirection||[0,0,1]),I?L:new R(v.definition.up||[0,1,0]));if(v.definition.scaleWithDistance){let E=Math.abs(new R(y).transformAsPoint(s)[2]);!h.has(f)&&E>1e-8&&h.set(f,E);let k=h.get(f);k!==void 0&&A.scale(E/k)}T=new C().translate(y).multiplyRight(_).multiplyRight(O.transpose()).scale(A)}if(f instanceof re)for(let y of f.children)p(y,T,w,x);else d.push({node:f,modelMatrix:T,overlay:w,distance:x,depth:-new R(T.getTranslation()).transformAsPoint(s)[2]})};p(i,new C,!1);for(let f of h.keys())l.has(f)||h.delete(f);return d.sort((f,m)=>Number(f.overlay)-Number(m.overlay)||(f.overlay?m.distance-f.distance||m.depth-f.depth:0)),d}resetCamera(e="default"){this.cameraDepths.delete(e)}destroy(){this.bindings.clear(),this.cameraDepths.clear()}};function Gc(r,e){r=new R(r).normalize();let t=new R(e).cross(r).normalize();return e=new R(r).cross(t).normalize(),new C([t[0],t[1],t[2],0,e[0],e[1],e[2],0,r[0],r[1],r[2],0,0,0,0,1])}var Me=B(D(),1);var Hn=class{scenes;matrixAuthoredNodes=new Set;definitions=new Map;constructor({scenes:e,bindings:t,matrixNodes:n=[]}){this.scenes=e;for(let i of n)this.matrixAuthoredNodes.add(i);for(let{node:i,definition:s,matrixAuthored:o}of t)o&&this.matrixAuthoredNodes.add(i),(0,Me.assert)(s&&(s.type==="rect"||s.type==="disk")),(0,Me.assert)(Number.isFinite(s.height??1)&&(s.height??1)>0),(0,Me.assert)(Number.isFinite(s.intensity??1e3)&&(s.intensity??1e3)>0),(0,Me.assert)(Number.isFinite(s.width??1)&&(s.width??1)>0),(0,Me.assert)((s.color||[1,1,1]).every(a=>Number.isFinite(a)&&a>=0)),this.definitions.set(i,s)}getLights(e=0){let t=this.scenes[e];if(!t)return[];let n=[],i=new Set,s=a=>{let c=this.definitions.has(a);for(let u of a.children)u instanceof re&&s(u)&&(c=!0);return c&&i.add(a),c};s(t);let o=(a,c,u)=>{if(!a.display||!i.has(a))return;let h=new C(c).multiplyRight(a.matrix),l=this.matrixAuthoredNodes.has(a)?Bd(a.matrix):a.rotation.length===4?new C().fromQuaternion(a.rotation):new C().rotateXYZ(a.rotation),d=new C(u).multiplyRight(l),p=this.definitions.get(a);if(p){let f=Math.max(...h.getScale().map(Math.abs)),m=(p.height??1)*f,g=p.type==="rect"?(p.width??1)*f:m;n.push({type:p.type,position:[h[12],h[13],h[14]],halfAxisX:[d[0]*g/2,d[1]*g/2,d[2]*g/2],halfAxisY:[d[4]*m/2,d[5]*m/2,d[6]*m/2],normal:[-d[8],-d[9],-d[10]],color:p.color||[1,1,1],intensity:p.intensity??1e3})}for(let f of a.children)f instanceof re&&o(f,h,d)};return o(t,new C,new C),n}destroy(){this.scenes=[],this.matrixAuthoredNodes.clear(),this.definitions.clear()}};function Bd(r){let e=new R(r[0],r[1],r[2]),t=new R(r[4],r[5],r[6]);(0,Me.assert)(e.magnitude()>0&&t.magnitude()>0),e.normalize(),t.normalize(),t.subtract(new R(e).scale(t.dot(e))),(0,Me.assert)(t.magnitude()>1e-8),t.normalize();let n=new R(e).cross(t).normalize(),i=new R(r[8],r[9],r[10]);return(0,Me.assert)(i.magnitude()>0),i.normalize(),(0,Me.assert)(Math.abs(n.dot(i))>1e-8),n.dot(i)<0&&n.negate(),new C([e[0],e[1],e[2],0,t[0],t[1],t[2],0,n[0],n[1],n[2],0,0,0,0,1])}var Od=new Set(["variable/get","pointer/get","math/and","math/add","math/sub","math/mul","math/div","math/rem","math/min","math/max","math/eq","math/lt","math/le","math/gt","math/ge","math/select","math/switch","math/neg","math/abs","math/clamp","type/intToFloat","type/floatToInt"]),Ht="KHR_physics_rigid_bodies:",Vc=new Set(["rigid_body/applyImpulse","rigid_body/applyPointImpulse","rigid_body/rayCast","event/rigid_body_triggerEntered","event/rigid_body_triggerExited"].map(r=>Ht+r)),Dd=new Set(["event/onStart","event/onTick","event/send","debug/log","flow/sequence","flow/branch","flow/switch","variable/set","pointer/set","flow/setDelay","KHR_node_selectability:event/onSelect"]);function ct(r){return r.slice()}function Uc(r){if(!Array.isArray(r))throw new Error("KHR_interactivity: expected component array");return r}function ut(r){return r[0]}function q(r){let e=ut(r);if(typeof e!="number")throw new Error("KHR_interactivity: expected numeric value");return e}function jc(r){if(r==="bool")return[!1];if(r==="int")return[0];if(r==="ref")return[null];let e=r?.match(/^float(?:([234])(?:x([234]))?)?$/);if(e&&(!e[2]||e[1]===e[2]))return Array(Number(e[1]??1)*Number(e[2]??1)).fill(NaN);throw new Error("KHR_interactivity: unsupported default value type")}var Yn=class{physics;physicsPending=new Set;physicsErrors=[];definition;graph;variables;properties;maxSteps;onEvent;onLog;started=!1;currentTimeSeconds=0;nextDelayIdentifier=0;pendingDelays=[];startTime=0;lastTick;eventOutputs=new Map;constructor(e,t={}){this.physics=t.physics,this.definition=e;let n=t.graph??e.graph??0,i=e.graphs[n];if(!i)throw new Error(`KHR_interactivity: graph ${n} does not exist`);if(this.graph=i,this.properties=t.properties,this.onEvent=t.onEvent,this.onLog=t.onLog,this.maxSteps=t.maxSteps??1e4,!Number.isSafeInteger(this.maxSteps)||this.maxSteps<1)throw new Error("KHR_interactivity: maxSteps must be a positive safe integer");this.variables=(i.variables??[]).map(s=>ct(s.value??[0]));for(let[s,o]of(i.nodes??[]).entries()){let a=this.getOperation(n,s);if(!Od.has(a)&&!Dd.has(a)&&!(this.physics&&Vc.has(a)))throw new Error(`KHR_interactivity: unsupported operation ${a}`);if(a.startsWith(Ht+"event/")){let c=q(this.config(o,"nodeIndex"));if(!this.physics?.isTriggerNode(c)||(i.nodes??[]).slice(0,s).some((u,h)=>this.getOperation(n,h)===a&&u.configuration?.nodeIndex?.value[0]===c))throw new Error("Invalid or duplicate physics trigger event")}if(a==="event/send"){let c=q(this.config(o,"event"));if(!Number.isInteger(c)||!i.events?.[c])throw new Error("KHR_interactivity: invalid custom event index")}for(let c of Object.values(o.flows??{}))if(!Number.isInteger(c.node)||!(i.nodes??[])[c.node])throw new Error(`KHR_interactivity: invalid flow target ${c.node}`)}}get graphCount(){return this.definition.graphs.length}getGraph(e){let t=this.definition.graphs[e];if(!t)throw new Error(`KHR_interactivity: graph index ${e} is out of range`);return t}getOperation(e,t){let n=this.getGraph(e),i=n.nodes?.[t];if(!i)throw new Error(`KHR_interactivity: node index ${t} is out of range`);let s=n.declarations?.[i.declaration];if(!s)throw new Error(`KHR_interactivity: declaration index ${i.declaration} is out of range`);return s.extension?`${s.extension}:${s.op}`:s.op}op(e){let t=this.graph.nodes?.[e],n=t&&this.graph.declarations?.[t.declaration];if(!n)throw new Error(`KHR_interactivity: invalid declaration for node ${e}`);return n.extension?`${n.extension}:${n.op}`:n.op}config(e,t){let n=e.configuration?.[t]?.value;if(!n)throw new Error(`KHR_interactivity: missing configuration ${t}`);return Uc(n)}getSwitchCases(e){let t=e.configuration?.cases?.value;return Array.isArray(t)&&t.every(n=>typeof n=="number"&&Number.isInteger(n)&&n>=-2147483648&&n<=2147483647)?t:[]}input(e,t,n){let i=this.graph.nodes?.[e]?.values?.[t];if(!i)throw new Error(`KHR_interactivity: missing input ${t} on node ${e}`);if(i.node!==void 0){if(!i.socket)throw new Error("KHR_interactivity: connected input missing socket");return this.evaluate(i.node,i.socket,n)}return i.value?ct(Uc(i.value)):jc(i.type===void 0?void 0:this.graph.types?.[i.type]?.signature)}pointer(e,t){let n=this.graph.nodes[e],i=ut(this.config(n,"pointer"));if(typeof i!="string"||!i.startsWith("/"))throw new Error("KHR_interactivity: invalid pointer template");return i.replace(/\[([^\]]+)\]|\{([^}]+)\}/g,(s,o,a)=>{let c=o??a,u=ut(this.input(e,c,t));if(a&&typeof u=="string"&&/^\/(?:[^/~]|~[01])+(?:\/(?:[^/~]|~[01])+)*$/.test(u))return u.split("/").at(-1);if(!Number.isSafeInteger(u)||u<0)throw new Error("KHR_interactivity: invalid pointer parameter");return String(u)})}evaluate(e,t="value",n=new Set){let i=this.graph.nodes?.[e];if(!i)throw new Error(`KHR_interactivity: invalid node ${e}`);if(n.has(e))throw new Error("KHR_interactivity: cyclic value dependency");n.add(e);try{let s=this.op(e),o=this.eventOutputs.get(e)?.[t];if(o)return ct(o);if(s==="flow/setDelay"&&t==="lastDelay")return[null];if(s==="variable/get"){let h=q(this.config(i,"variable")),l=this.variables[h];if(!l)throw new Error("KHR_interactivity: invalid variable index");return ct(l)}if(s==="pointer/get"){let h=this.properties?.get(this.pointer(e,n));return t==="isValid"?[h!==void 0]:ct(h??[0])}if(t!=="value")throw new Error(`KHR_interactivity: unsupported output socket ${t}`);let a=()=>this.input(e,"a",n),c=()=>this.input(e,"b",n),u=h=>{let l=a().map(Number),d=c().map(Number);if(l.length!==d.length)throw new Error("KHR_interactivity: mismatched component lengths");return l.map((p,f)=>h(p,d[f]))};switch(s){case"type/intToFloat":return a().map(Number);case"type/floatToInt":return a().map(h=>Number(h)|0);case"math/clamp":{let h=c().map(Number),l=this.input(e,"c",n).map(Number);return a().map((d,p)=>Math.min(l[p],Math.max(h[p],Number(d))))}case"math/and":{let h=ut(a()),l=ut(c());if(typeof h=="boolean"&&typeof l=="boolean")return[h&&l];if(typeof h=="number"&&typeof l=="number")return[h&l];throw new Error("KHR_interactivity: incompatible AND arguments")}case"math/add":return u((h,l)=>h+l);case"math/sub":return u((h,l)=>h-l);case"math/mul":return u((h,l)=>h*l);case"math/div":return u((h,l)=>h/l);case"math/rem":return u((h,l)=>h%l);case"math/min":return u(Math.min);case"math/max":return u(Math.max);case"math/neg":return a().map(h=>-Number(h));case"math/abs":return a().map(h=>Math.abs(Number(h)));case"math/eq":return[JSON.stringify(a())===JSON.stringify(c())];case"math/lt":return[q(a())<q(c())];case"math/le":return[q(a())<=q(c())];case"math/gt":return[q(a())>q(c())];case"math/ge":return[q(a())>=q(c())];case"math/select":return this.input(e,ut(this.input(e,"condition",n))?"a":"b",n);case"math/switch":{let h=q(this.input(e,"selection",n)),l=this.getSwitchCases(i);return this.input(e,l.includes(h)?String(h):"default",n)}default:throw new Error(`KHR_interactivity: ${s} is not a value operation`)}}finally{n.delete(e)}}dispatch(e,t,n){let i=0,s=(a,c)=>{if(++i>this.maxSteps)throw new Error("KHR_interactivity: flow step limit exceeded");let u=this.graph.nodes[a],h=this.op(a);if(h==="flow/setDelay"&&c==="cancel"){this.pendingDelays=this.pendingDelays.filter(p=>p.nodeIndex!==a),this.eventOutputs.set(a,{lastDelay:[null]});return}if(c!=="in")throw new Error(`KHR_interactivity: unsupported input flow ${c}`);let l=new Set,d=p=>{let f=u.flows?.[p];f&&s(f.node,f.socket??"in")};if(Vc.has(h)&&this.physics){let p=(m,g)=>u.values?.[m]?this.input(a,m,l):g??this.input(a,m,l),f=(m,g)=>{let x=p(m,g);if(x.length!==3||!x.every(T=>typeof T=="number"&&Number.isFinite(T)))throw new Error("Invalid physics vector");return x};if(h===Ht+"rigid_body/applyImpulse")this.physics.applyImpulse(q(p("nodeIndex")),f("linearImpulse",[0,0,0]),f("angularImpulse",[0,0,0])),d("out");else if(h===Ht+"rigid_body/applyPointImpulse")this.physics.applyPointImpulse(q(p("nodeIndex")),f("impulse"),f("position")),d("out");else if(h===Ht+"rigid_body/rayCast"){let m=new Map(this.eventOutputs),g=this.physics.rayCast(f("rayStart"),f("rayEnd"),q(p("collisionFilterIndex",[-1]))).then(x=>{let T=this.eventOutputs;this.eventOutputs=m;try{i=0,this.eventOutputs.delete(a),x&&this.eventOutputs.set(a,{hitNodeIndex:[x.node],hitFraction:[x.fraction],hitNormal:[...x.normal]}),d(x?"hit":"miss")}finally{this.eventOutputs=T}}).catch(x=>{this.physicsErrors.push(x)}).finally(()=>{this.physicsPending.delete(g)});this.physicsPending.add(g)}else throw new Error("Physics event is not an input flow");return}switch(h){case"flow/setDelay":{let p=q(this.input(a,"duration",l)),f=this.currentTimeSeconds+p;if(!Number.isFinite(f)||!Number.isFinite(p)||p<0||this.pendingDelays.length>=1024){d("err");break}let m=`delay:${++this.nextDelayIdentifier}`;this.eventOutputs.set(a,{lastDelay:[m]}),this.pendingDelays.push({nodeIndex:a,reference:m,timeSeconds:f,activate:()=>{i=0,d("done")}}),d("out");break}case"flow/sequence":for(let p of Object.keys(u.flows??{}).sort())d(p);break;case"flow/branch":d(ut(this.input(a,"condition",l))?"true":"false");break;case"flow/switch":{let p=q(this.input(a,"selection",l)),f=this.getSwitchCases(u);d(f.includes(p)?String(p):"default");break}case"variable/set":{let p=this.config(u,"variables").map(Number),f=p.map(m=>this.input(a,String(m),l));p.forEach((m,g)=>{if(!this.variables[m])throw new Error("KHR_interactivity: invalid variable index");this.variables[m]=ct(f[g])}),d("out");break}case"event/send":{let p=q(this.config(u,"event")),f=this.graph.events[p],m=Object.fromEntries(Object.entries(f.values??{}).map(([g,x])=>[g,u.values?.[g]?this.input(a,g,l):x.value?ct(x.value):jc(this.graph.types?.[x.type]?.signature)]));this.onEvent?.(f.id,m),d("out");break}case"debug/log":{let p=u.configuration?.severity?.value[0],f=u.configuration?.message?.value[0],m=typeof f=="string"?f.match(/\{\{|\}\}|\{[^{}]+\}|[^{}]+/g):null,x=typeof f=="string"&&(m??[]).join("")===f?(m??[]).map(T=>T==="{{"?"{":T==="}}"?"}":T.startsWith("{")?JSON.stringify(this.input(a,T.slice(1,-1),l)):T).join(""):"";this.onLog?.(x,typeof p=="number"&&p===(p|0)?p:0),d("out");break}case"pointer/set":{let p=this.pointer(a,l),f=this.input(a,"value",l);d(this.properties?.set(p,f)?"out":"err");break}default:throw new Error(`KHR_interactivity: ${h} is not an executable flow operation`)}},o=this.graph.nodes??[];for(let a=0;a<o.length;a++)if(this.op(a)===e&&(n===void 0||o[a].configuration?.nodeIndex?.value[0]===n)){this.eventOutputs.set(a,t);let c=o[a].flows?.out;c&&s(c.node,c.socket??"in")}}async flushPhysics(){let e=0;for(;this.physicsPending.size;){if(++e>this.maxSteps)throw new Error("Physics continuation limit exceeded");await Promise.all(this.physicsPending)}if(this.physicsErrors.length)throw this.physicsErrors.shift()}notifyPhysicsTrigger(e,t,n,i){if(!this.physics?.isTriggerNode(t))throw new Error("Invalid physics trigger node");this.dispatch(Ht+(e==="enter"?"event/rigid_body_triggerEntered":"event/rigid_body_triggerExited"),{colliderNodeIndex:[n],motionNodeIndex:[i]},t)}start(){this.started||(this.started=!0,this.dispatch("event/onStart",{event:[null]}))}selectNode(e){this.start(),this.dispatch("KHR_node_selectability:event/onSelect",{selectedNode:[`/nodes/${e}`],selectionRayOrigin:[0,0,0],selectionPoint:[0,0,0],controllerIndex:[0],event:[null]},e)}tick(e){if(!Number.isFinite(e))throw new Error("KHR_interactivity: invalid tick time");if(this.lastTick!==void 0&&e<this.lastTick)throw new Error("KHR_interactivity: tick time must be monotonic");if(this.lastTick===void 0){this.startTime=e;let i=e-this.currentTimeSeconds;for(let s of this.pendingDelays)s.timeSeconds+=i}let t=this.lastTick===void 0?NaN:e-this.lastTick;this.lastTick=e,this.currentTimeSeconds=e,this.start();let n=this.pendingDelays.filter(i=>i.timeSeconds<=e).sort((i,s)=>i.timeSeconds-s.timeSeconds);for(let i of n)this.pendingDelays.includes(i)&&(this.pendingDelays=this.pendingDelays.filter(s=>s!==i),i.activate());this.dispatch("event/onTick",{timeSinceStart:[e-this.startTime],timeSinceLastTick:[t],event:[null]})}};var Oe=B(D(),1),Yt=class{definition;nodes=[];constructor(e,t,n,i){this.definition=e;for(let u of e.nodes)(0,Oe.assert)(!u.bypass||u.kind!=="splitter"&&u.kind!=="channelmerger");let s=(u,h=0)=>{(0,Oe.assert)(Number.isInteger(u)&&!!e.nodes[u]),(0,Oe.assert)(Number.isInteger(h)&&h>=0)};for(let u of e.connections)s(u.from.node,u.from.output),s(u.to.node,u.to.input);for(let u of e.inputs||[])s(u.node,u.input),(0,Oe.assert)(Number.isInteger(u.source)&&u.source>=0);for(let u of e.outputs||[])s(u.node,u.output),(0,Oe.assert)(Number.isInteger(u.emitter)&&u.emitter>=0);let o=new Set,a=new Set,c=u=>{if((0,Oe.assert)(e.nodes[u]&&!o.has(u)),!a.has(u)){o.add(u);for(let h of e.connections)h.from.node===u&&c(h.to.node);o.delete(u),a.add(u)}};e.nodes.forEach((u,h)=>c(h));try{e.nodes.forEach((u,h)=>this.nodes.push(kd(t,u,Math.max(1,...e.connections.filter(l=>l.from.node===h).map(l=>(l.from.output??0)+1),...(e.outputs||[]).filter(l=>l.node===h).map(l=>(l.output??0)+1)),Math.max(1,...e.connections.filter(l=>l.to.node===h).map(l=>(l.to.input??0)+1),...(e.inputs||[]).filter(l=>l.node===h).map(l=>(l.input??0)+1)))));for(let u of e.connections)this.nodes[u.from.node].connect(this.nodes[u.to.node],u.from.output??0,this.getInputPort(u.to.node,u.to.input??0));if(e.outputs)for(let u of e.outputs)for(let h of i(u.emitter))this.nodes[u.node].connect(h,u.output??0);else e.nodes.forEach((u,h)=>{e.connections.some(l=>l.from.node===h)||this.nodes[h].connect(n)})}catch(u){throw this.destroy(),u}}connectSource(e,t){for(let n of this.definition.inputs||[])n.source===e&&t.connect(this.nodes[n.node],0,this.getInputPort(n.node,n.input??0))}setGain(e,t,n=this.nodes[e].context.currentTime){let i=this.definition.nodes[e];(0,Oe.assert)(i.kind==="gain"&&!i.bypass&&t>=0);let s=this.nodes[e].gain,o=i.params.duration??0,a=s.value;if(s.cancelAndHoldAtTime(n),s.setValueAtTime(a,n),o<=0)s.setValueAtTime(t,n);else if(i.params.interpolation==="custom"){let c=i.params.curve;(0,Oe.assert)(c&&c.length>=2&&c.every(u=>u>=0&&u<=1)),s.setValueCurveAtTime(Float32Array.from(c,u=>u*t),n,o)}else s.linearRampToValueAtTime(t,n+o)}destroy(){for(let e of this.nodes)e.disconnect();this.nodes.length=0}getInputPort(e,t){return this.definition.nodes[e].kind==="audiomixer"?0:t}};function kd(r,e,t,n){let i=e.params;if(e.bypass)return r.createGain();switch(e.kind){case"gain":{let s=r.createGain();return s.gain.value=i.gain??1,s}case"delay":{let s=r.createDelay(i.maxDelayTime??1);return s.delayTime.value=i.delayTime??0,s}case"compressor":{let s=r.createDynamicsCompressor();return s.threshold.value=i.threshold??-24,s.knee.value=i.knee??30,s.ratio.value=i.ratio??12,s.attack.value=i.attack??.003,s.release.value=i.release??.25,s}case"waveshaper":{let s=r.createWaveShaper(),o=1+20*(i.amount??0);return s.curve=i.curve?new Float32Array(i.curve):Float32Array.from({length:4097},(a,c)=>Math.tanh((c/2048-1)*o)/Math.tanh(o)),s.oversample=i.oversample??"none",s}case"splitter":{let s=r.createChannelSplitter(t);return s.channelInterpretation=i.channelInterpretation??"discrete",s}case"channelmerger":{let s=r.createChannelMerger(n);return s.channelInterpretation=i.channelInterpretation??"discrete",s}case"channelmixer":{let s=r.createGain();return s.channelCountMode="explicit",s.channelCount=i.outputChannels,s.channelInterpretation=i.channelInterpretation??"speakers",s}case"audiomixer":{let s=r.createGain();return s.channelInterpretation=i.channelInterpretation??"speakers",s}default:{let s=r.createBiquadFilter();return s.type=e.kind,s.frequency.value=i.frequency,s.Q.value=i.qualityFactor??1,s.gain.value=i.gain??0,s}}}var Xn=B(D(),1);function Mr(r,e){let t;for(let s of r){let o=s.worldMatrix.getScale(),a,c,u;if(s.shape.type==="sphere"){let h=s.worldMatrix.getTranslation(),l=s.shape.radius*Math.max(...o);a=l-Math.hypot(...h.map((f,m)=>f-e[m])),c=4/3*Math.PI*l**3;let d=h.map((f,m)=>e[m]-f),p=Math.hypot(...d);u=Array.from(h).map((f,m)=>f+(p?d[m]/p:+(m===0))*(l+1e-5))}else{let h=new C(s.worldMatrix).invert().transformAsPoint(Array.from(e)),l=s.shape.size.map((p,f)=>(p/2-Math.abs(h[f]))*o[f]);a=Math.min(...l);let d=l.indexOf(a);h[d]=(Math.sign(h[d])||1)*(s.shape.size[d]/2+1e-5/o[d]),u=Array.from(s.worldMatrix.transformAsPoint(h)),c=s.shape.size.reduce((p,f,m)=>p*f*o[m],1)}a<0||(!t||(s.priority??0)>(t.zone.priority??0)||(s.priority??0)===(t.zone.priority??0)&&c<t.volume)&&(t={zone:s,volume:c,distance:a,boundary:u})}if(!t)return;let n=t.zone.blendDistance?Math.min(1,t.distance/t.zone.blendDistance):1,i=n<1?Mr(r.filter(s=>s!==t.zone),t.boundary):void 0;return{environment:t.zone.environment,weight:n,...i?{outsideEnvironment:i.environment}:{}}}var Xt=class{input;convolver;output;sends=[];constructor(e,t,n,i={}){this.input=e.createGain(),this.convolver=e.createConvolver(),this.output=e.createGain(),this.convolver.normalize=i.normalize??!0,this.convolver.buffer=t,this.output.gain.value=i.mix??.5,this.input.connect(this.convolver),this.convolver.connect(this.output),this.output.connect(n)}connectSend(e,t){let n=e.context.createGain();return n.gain.value=t,e.connect(n),n.connect(this.input),this.sends.push(n),n}reset(){let e=this.convolver;this.input.disconnect(e),e.disconnect(),this.convolver=e.context.createConvolver(),this.convolver.normalize=e.normalize,this.convolver.buffer=e.buffer,this.input.connect(this.convolver),this.convolver.connect(this.output)}destroy(){for(let e of this.sends)e.disconnect();this.sends.length=0,this.input.disconnect(),this.convolver.disconnect(),this.output.disconnect()}};function Kn(r,e){(0,Xn.assert)((e.density??1)===1&&(e.diffusion??1)===1);let t={generic:[1.49,.83,.007,.011],smallRoom:[.4,.83,.002,.003],mediumRoom:[1.1,.83,.01,.011],largeRoom:[4.32,.59,.02,.03],bathroom:[1.49,.54,.007,.011],concertHall:[3.92,.7,.02,.029],cathedral:[5.5,.6,.025,.04],cave:[2.91,1.3,.015,.022],arena:[7.24,.33,.02,.03],hangar:[10.05,.23,.02,.03],corridor:[1.79,.59,.007,.011],forest:[1.49,.54,.162,.088],underwater:[1.49,.1,.007,.011]},n=e.preset?t[e.preset]:void 0;(0,Xn.assert)(!e.preset||n);let i=e.decayTime??n?.[0]??1.5,s=i*(e.decayHFRatio??n?.[1]??.83),o=e.reflectionsDelay??n?.[2]??.02,a=o+(e.reverbDelay??n?.[3]??.04);(0,Xn.assert)(i>0&&s>0&&o>=0&&a>=o);let c=r.createBuffer(2,Math.ceil((a+Math.max(i,s))*r.sampleRate),r.sampleRate);for(let u=0;u<2;u++){let h=c.getChannelData(u),l=12345+u*98765,d=0,p=1/Math.sqrt(r.sampleRate*i);for(let f=Math.ceil(a*r.sampleRate);f<h.length;f++){l=Math.imul(l,1664525)+1013904223|0;let m=l/2147483648;d+=.15*(m-d);let g=f/r.sampleRate-a;h[f]=(e.reverbGain??1)*p*(d*Math.exp(-Math.log(1e3)*g/i)+(m-d)*Math.exp(-Math.log(1e3)*g/s))}h[Math.round(o*r.sampleRate)]+=e.reflectionsGain??1}return c}var de=B(D(),1);var Zn=class{gain;definition;options;scene;nodeBindings=new Map;listenerGain;emitters=[];graphs=new Map;reverbBuses=new Map;directGains=[];environmentSends=[];graphSources=new Set;graphEmitters=new Set;playing=new Map;buffers=new Map;initialization;abortController=new AbortController;destroyed=!1;playbackGeneration=0;audioClockStart;constructor(e){this.options=e;let{audioContext:t}=e;this.scene=e.scene,this.definition=e.definition;let n=e.graphs;this.gain=t.createGain(),this.listenerGain=t.createGain(),this.gain.connect(this.listenerGain),this.listenerGain.connect(t.destination);let i=new Set;this.scene.preorderTraversal(a=>i.add(a));let s=new Set(e.emitterIndices);for(let a of e.nodes||[])if(i.has(a.node))for(let c of a.emitterIndices||[])s.add(c);let o=new Map;n?.forEach((a,c)=>{if(a.outputs?.some(u=>s.has(u.emitter))){o.set(c,a);for(let u of a.inputs||[])this.graphSources.add(u.source);for(let u of a.outputs||[])this.graphEmitters.add(u.emitter)}});try{for(let a of e.nodes||[])if(i.has(a.node)){this.nodeBindings.set(a.node,a);for(let c of a.emitterIndices||[])this.addEmitter(c,a.node)}for(let a of e.emitterIndices||[])this.addEmitter(a);for(let[a,c]of o)this.graphs.set(a,new Yt(c,t,this.gain,u=>this.emitters.filter(h=>h.index===u).map(h=>h.panner||h.gain)))}catch(a){throw this.destroy(),a}}initialize(){return this.destroyed?Promise.reject(new Error("Audio controller destroyed")):(this.initialization||=this.loadBuffers().catch(e=>{throw this.initialization=void 0,e}),this.initialization)}async play(e={}){e.restart!==!1&&this.stop();let t=this.playbackGeneration;if(await this.initialize(),this.destroyed||t!==this.playbackGeneration)return;let n=this.options.audioContext.currentTime;(e.restart!==!1||this.audioClockStart===void 0)&&(this.audioClockStart=n);for(let i of this.emitters)if(!this.graphEmitters.has(i.index))for(let s of i.definition.sources||[])e.sourceIndices&&!e.sourceIndices.includes(s)||this.startSource(s,n,e.autoplayOnly,o=>o.connect(i.panner||i.gain));for(let i of this.graphSources)e.sourceIndices&&!e.sourceIndices.includes(i)||this.startSource(i,n,e.autoplayOnly,s=>{for(let o of this.graphs.values())o.connectSource(i,s)})}setGraphGain(e,t,n){let i=this.graphs.get(e);(0,de.assert)(!this.destroyed&&i),i.setGain(t,n)}startSource(e,t,n,i){let s=this.definition.sources[e];if((0,de.assert)(s),n&&!s.autoPlay)return;let o=this.options.audioContext,a=s.graph,c=a?.oscillator;(0,de.assert)(!(s.audio!==void 0&&c));let u;if(c){let d=o.createOscillator();d.frequency.value=c.frequency??440,d.detune.value=c.detune??0,(0,de.assert)(c.pulseWidth===void 0||c.pulseWidth===.5),c.type==="custom"?((0,de.assert)(c.periodicWave),d.setPeriodicWave(o.createPeriodicWave(new Float32Array(c.periodicWave.real),new Float32Array(c.periodicWave.imag)))):d.type=c.type,u=d}else{let d=o.createBufferSource();(0,de.assert)(s.audio!==void 0),d.buffer=this.buffers.get(s.audio),d.loop=s.loop??!1,d.loopStart=a?.loopStart??0,d.loopEnd=a?.loopEnd??0,d.playbackRate.value=s.playbackRate??1,u=d}a?.channelInterpretation&&(u.channelInterpretation=a.channelInterpretation);let h=this.options.audioContext.createGain();h.gain.value=s.gain??1,u.connect(h),i(h),u.onended=()=>{u.disconnect(),h.disconnect(),this.playing.delete(u)},this.playing.set(u,h);let l=a?.when===void 0?t:Math.max(t,this.audioClockStart+a.when);u instanceof AudioBufferSourceNode?a?.duration===void 0?u.start(l,a?.offset??0):u.start(l,a.offset??0,a.duration):(u.start(l),a?.duration!==void 0&&u.stop(l+a.duration))}stop(){this.playbackGeneration++;for(let[e,t]of this.playing)e.onended=null,e.stop(),e.disconnect(),t.disconnect();this.playing.clear();for(let e of this.reverbBuses.values())e.reset()}update(e){if(this.destroyed)return;let t=this.options.environment;if(t){let h=[];this.scene.preorderTraversal((p,{worldMatrix:f})=>{let m=this.nodeBindings.get(p);m?.listener!==void 0&&h.push({index:m.listener,node:m.node,matrix:new C(f)})});let l=h.find(p=>p.index===this.options.activeListener)??h.find(p=>p.node===this.options.activeCameraNode)??h[0],d=l?t.listeners?.[l.index]:void 0;l&&d&&this.options.listenerPose!=="viewer"&&(e=l.matrix),this.listenerGain.gain.value=d?.gain??1;for(let p of this.emitters)p.panner&&(p.panner.panningModel=d?.spatializationModel==="HRTF"?"HRTF":"equalpower")}let n=e.getTranslation(),i=[];this.scene.preorderTraversal((h,{worldMatrix:l})=>{let d=this.nodeBindings.get(h)?.zone;d?.shape&&i.push({...d,worldMatrix:new C(l)})});let s=Mr(i,n),o=this.options.defaultEnvironment;for(let h of this.environmentSends){let l=h.forced??s?.environment??o,d=h.forced!==void 0?1:s?.weight??1,p=s?.outsideEnvironment??o;h.gain.gain.value=h.level*((h.environment===l?d:0)+(h.forced===void 0&&h.environment===p?1-d:0))}let a=new R(0,0,-1).transformAsVector(e).normalize(),c=new R(0,1,0).transformAsVector(e).normalize(),u=this.options.audioContext.listener;u.positionX.value=n[0],u.positionY.value=n[1],u.positionZ.value=n[2],u.forwardX.value=a[0],u.forwardY.value=a[1],u.forwardZ.value=a[2],u.upX.value=c[0],u.upY.value=c[1],u.upZ.value=c[2],this.scene.preorderTraversal((h,{worldMatrix:l})=>{for(let d of this.emitters){if(d.node!==h||!d.panner)continue;let p=l.getTranslation(),f=new R(0,0,-1).transformAsVector(l).normalize(),m=d.panner;m.positionX.value=p[0],m.positionY.value=p[1],m.positionZ.value=p[2],m.orientationX.value=f[0],m.orientationY.value=f[1],m.orientationZ.value=f[2];let g=Math.hypot(...p.map((x,T)=>x-n[T]));if(d.airFilter){let x=d.definition.positional,T=Math.min(1,Math.max(0,(g-(x.refDistance??1))/(x.maxDistance-(x.refDistance??1)))),v=x.airAbsorption?.cutoffAtMaxDistance??5e3;d.airFilter.frequency.value=Math.exp(Math.log(2e4)+T*(Math.log(Math.max(1,v))-Math.log(2e4)))}d.gain.gain.value=(d.definition.gain??1)*Fd(d.definition.positional,g)}})}destroy(){if(!this.destroyed){this.destroyed=!0,this.abortController.abort(),this.stop();for(let e of this.emitters)e.panner?.disconnect(),e.airFilter?.disconnect(),e.gain.disconnect();for(let e of this.graphs.values())e.destroy();for(let e of this.reverbBuses.values())e.destroy();this.reverbBuses.clear();for(let e of this.directGains)e.disconnect();this.gain.disconnect(),this.listenerGain.disconnect(),this.buffers.clear()}}addEmitter(e,t){let n=this.definition.emitters[e];(0,de.assert)(n&&(n.type==="global"||n.type==="positional"&&t)),(0,de.assert)(!n.positional?.shapeType||["cone","omnidirectional"].includes(n.positional.shapeType));for(let a of this.graphEmitters.has(e)?[]:n.sources||[]){let c=this.definition.sources[a];(0,de.assert)(c&&(c.audio!==void 0?this.definition.audio[c.audio]:c.graph?.oscillator))}let i=this.options.audioContext.createGain();i.gain.value=n.gain??1;let s=this.options.audioContext.createGain();s.gain.value=n.environment?.directLevel??1,i.connect(s),s.connect(this.gain),this.directGains.push(s);let o={index:e,definition:n,node:t,gain:i};if(this.emitters.push(o),n.type==="positional"){let a=this.options.audioContext.createPanner();o.panner=a,a.panningModel="HRTF",a.rolloffFactor=0;let c=n.positional;if(c?.shapeType==="cone"&&(a.coneInnerAngle=(c.coneInnerAngle??Math.PI*2)*180/Math.PI,a.coneOuterAngle=(c.coneOuterAngle??Math.PI*2)*180/Math.PI,a.coneOuterGain=c.coneOuterGain??0),c?.airAbsorption?.enabled&&(c?.maxDistance??0)>(c?.refDistance??1)){let h=this.options.audioContext.createBiquadFilter();h.type="lowpass",h.Q.value=Math.SQRT1_2,h.frequency.value=2e4,o.airFilter=h,a.connect(h),h.connect(i)}else a.connect(i)}}async loadBuffers(){let{audioContext:e,baseUrl:t}=this.options,n=new Set([...this.graphSources,...this.emitters.filter(a=>!this.graphEmitters.has(a.index)).flatMap(a=>a.definition.sources||[])]),i=new Set([...n].map(a=>{let c=this.definition.sources[a];return(0,de.assert)(c&&(c.audio!==void 0?this.definition.audio[c.audio]:c.graph?.oscillator)),c.audio})),s=this.options.environment?.environments;for(let a of s||[])a.reverb?.type==="impulseResponse"&&a.reverb.audio!==void 0&&i.add(a.reverb.audio);let o=await Promise.all([...i].filter(a=>a!==void 0).map(async a=>{let c=this.definition.audio[a],u;if(c.data!==void 0){let h=c.data;u=ArrayBuffer.isView(h)?new Uint8Array(h.buffer,h.byteOffset,h.byteLength).slice().buffer:h.slice(0)}else{let h=await(this.options.fetch||fetch)(new URL(c.uri,t),{signal:this.abortController.signal});if(!h.ok)throw new Error(`Audio fetch failed: ${h.status}`);u=await h.arrayBuffer()}return[a,await e.decodeAudioData(u)]}));this.destroyed||(this.buffers=new Map(o),s?.forEach((a,c)=>{let u=a.reverb;if(!u)return;let h=u.type==="impulseResponse"?this.buffers.get(u.audio):Kn(e,u);(0,de.assert)(h);let l=new Xt(e,h,this.gain,{...u,normalize:u.type==="impulseResponse"?u.normalize:!1});this.reverbBuses.set(c,l);let d=this.options.defaultEnvironment;for(let p of this.emitters){let f=p.definition.environment,m=f?.reverbLevel??(p.definition.type==="positional"?1:0),g=l.connectSend(p.gain,(f?.environment??d)===c?m:0);this.environmentSends.push({gain:g,environment:c,forced:f?.environment,level:m})}}))}};function Fd(r={},e){let t=r.refDistance??1,n=r.maxDistance||1/0,i=Math.max(t,Math.min(e,n)),s=r.rolloffFactor??1;switch(r.distanceModel){case"linear":return n<=t?e<=t?1:0:Math.max(0,1-s*(i-t)/(n-t));case"exponential":return(i/t)**-s;default:return t/(t+s*(i-t))}}var Qn=class{device;framebuffer=null;shaderInputs;constructor(e,t){this.device=e,this.shaderInputs=t}destroy(){this.framebuffer?.destroy()}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.device.createFramebuffer({colorAttachments:["rgba8unorm"],depthStencilAttachment:"depth24plus"})),this.framebuffer}clearPickState(){this.shaderInputs.setProps({picking:{highlightedObjectColor:null}})}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getCanvasContext().getDevicePixelSize()),this.shaderInputs.setProps({picking:{isActive:!0}}),this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}updatePickState(e){let t=this.getFramebuffer(),[n,i]=this.getPickPosition(e),o=[...this.device.readPixelsToArrayWebGL(t,{sourceX:n,sourceY:i,sourceWidth:1,sourceHeight:1})].map(c=>c/255);o[0]+o[1]+o[2]>0||(o=null),this.shaderInputs.setProps({picking:{isActive:!1,highlightedObjectColor:o}})}getPickPosition(e){let t=this.device.getCanvasContext().cssToDevicePixels(e),n=t.x+Math.floor(t.width/2),i=t.y+Math.floor(t.height/2);return[n,i]}};var $c=B(Ie(),1),qc=$c.picking;var Wc=B(D(),1);var Jn=class extends z{constructor(e={}){let{innerRadius:t=.5,outerRadius:n=1,height:i=.2,segments:s=48,startAngle:o=0,angle:a=Math.PI*2}=e;(0,Wc.assert)(Number.isFinite(t)&&t>=0&&Number.isFinite(n)&&n>t&&Number.isFinite(i)&&i>0&&Number.isFinite(o)&&Number.isFinite(a)&&a>0&&a<=Math.PI*2&&Number.isInteger(s)&&s>=3);let c=i/2,u=[[[n,-c],[n,c]],[[n,c],[t,c]],[[t,-c],[n,-c]]];t>0&&u.push([[t,c],[t,-c]]);let h=u.map(m=>new Tt({points:m,segments:s,phiStart:o,phiLength:a}));if(a<Math.PI*2)for(let[m,g]of[o,o+a].entries()){let x=new Ze({sizeX:n-t,sizeZ:i}),T=x.attributes.POSITION.value,v=x.attributes.NORMAL.value,w=Math.cos(g),y=Math.sin(g),b=m===0?1:-1;for(let M=0;M<T.length;M+=3){let _=Number(T[M])+(t+n)/2,A=-b*Number(T[M+2]);T[M]=_*w,T[M+1]=A,T[M+2]=-_*y,v[M]=b*y,v[M+1]=0,v[M+2]=b*w}h.push(x)}let l=[],d=[],p=[],f=[];for(let m of h){let g=l.length/3;for(let x of m.attributes.POSITION.value)l.push(x);for(let x of m.attributes.NORMAL.value)d.push(x);for(let x of m.attributes.TEXCOORD_0.value)p.push(x);for(let x of m.indices.value)f.push(Number(x)+g)}super({id:e.id,topology:"triangle-list",indices:new Uint32Array(f),attributes:{POSITION:{size:3,value:new Float32Array(l)},NORMAL:{size:3,value:new Float32Array(d)},TEXCOORD_0:{size:2,value:new Float32Array(p)},...e.attributes}})}};function Hc(r,e){if(r===void 0)return[...e];if(!Array.isArray(r)||r.length!==3||!r.every(Number.isFinite))throw new Error("Expected a finite three-component vector");return[r[0],r[1],r[2]]}function Yc(r){if(r===void 0)return[0,0,0,1];if(!Array.isArray(r)||r.length!==4||!r.every(Number.isFinite))throw new Error("Expected a finite quaternion");let e=Math.hypot(...r);if(e===0)throw new Error("Quaternion must be nonzero");return[r[0]/e,r[1]/e,r[2]/e,r[3]/e]}function Xc(r,e,t=!1){let n=t?r.transformAsPoint(e):r.transformAsVector(e);return[n[0],n[1],n[2]]}function _r(r){if(!r.every(Number.isFinite)||Math.abs(r[3])+Math.abs(r[7])+Math.abs(r[11])>1e-7||Math.abs(r[15]-1)>1e-7)throw new Error("Expected an affine transform");let e=[Math.hypot(r[0],r[1],r[2]),Math.hypot(r[4],r[5],r[6]),Math.hypot(r[8],r[9],r[10])];if(e.every(i=>i===0))return{position:[r[12],r[13],r[14]],rotation:[0,0,0,1],scale:e};if(e.some(i=>i<1e-10))throw new Error("Singular collider transforms are unsupported");r.determinant()<0&&(e[0]=-e[0]);let t=[r[0]/e[0],r[1]/e[0],r[2]/e[0],r[4]/e[1],r[5]/e[1],r[6]/e[1],r[8]/e[2],r[9]/e[2],r[10]/e[2]];for(let[i,s]of[[0,1],[0,2],[1,2]]){let o=t[i*3]*t[s*3]+t[i*3+1]*t[s*3+1]+t[i*3+2]*t[s*3+2];if(Math.abs(o)>1e-5)throw new Error("Sheared collider transforms are unsupported")}let n=new Jt().fromMatrix3(t).normalize();return{position:[r[12],r[13],r[14]],rotation:[n[0],n[1],n[2],n[3]],scale:e}}var ei=class{joints;constructor(e){this.joints=e}resolve(e,t){let n=new Map,i=new Map,s=(a,c,u)=>{if(n.has(a))throw new Error("Joint scene must be a tree");let h=new C(c).multiplyRight(a.matrix),l=t.has(a)?a:u;if(n.set(a,h),i.set(a,l),a instanceof re)for(let d of a.children)s(d,h,l)};for(let a of e)s(a,new C,null);let o=a=>{let c=n.get(a);if(!c)throw new Error("Joint attachment is outside the scene");let u=i.get(a)??null,h=new C(c);if(u){let d=_r(n.get(u));h=new C().translate(d.position).multiplyRight(new C().fromQuaternion(d.rotation)).invert().multiplyRight(h)}let l=_r(h);return{body:u,position:l.position,orientation:l.rotation}};return this.joints.map(a=>({joint:a,first:o(a.first),second:o(a.second)}))}};var Kc={name:"publishedTransforms",uniformTypes:{bodyIndex:"i32",viewProjection:"mat4x4<f32>"},defaultUniforms:{bodyIndex:-1},source:`
|
|
795
|
+
struct PublishedTransforms {bodyIndex:i32,viewProjection:mat4x4f}
|
|
796
|
+
@group(0) @binding(auto) var<uniform> publishedTransforms:PublishedTransforms;
|
|
797
|
+
@group(0) @binding(auto) var<storage,read> publishedBodyMatrices:array<mat4x4f>;
|
|
798
|
+
`,bindingLayout:[{name:"publishedBodyMatrices",group:0}]};var Zc=B(D(),1);function ti(r,e){r.userData.morphWeights=[...e];let t=r.userData.morphMeshes||[];for(let n of t)n.preorderTraversal(i=>{if(!(i instanceof Vt))return;let s=i.userData.morphTargets;if(!s)return;let o=i.userData.morphWeightTransport;if(o){Nd(o,e),i.userData.morphWeights=[...e];return}Hr(i.model,s.geometry,s.targets,e),i.userData.morphWeights=[...e]})}function Nd(r,e){r.values.fill(0),r.values.set(e.slice(0,r.values.length)),r.data instanceof Zc.Buffer?r.data.write(r.values):r.data.writeData(r.values,{width:r.packedTargetCount,height:1})}function Qc(r,e,t={}){return{id:t.id,getValue:()=>{switch(e){case"translation":return Array.from(r.position);case"rotation":return Array.from(r.rotation);case"scale":return Array.from(r.scale);case"weights":return Array.from(r.userData.morphWeights??[]);case"visibility":return[r.display?1:0]}},setValue:n=>{switch(e){case"translation":r.setPosition(n).updateMatrix();break;case"rotation":r.setRotation(n).updateMatrix();break;case"scale":r.setScale(n).updateMatrix();break;case"weights":ti(r,n);break;case"visibility":r.setProps({display:n[0]!==0}),t.onVisibilityChange?.();break}}}}var ri=class extends dt{mixer;activeClip;onUpdate;previousTimeSeconds;constructor(e,t,n={}){if(super(e),this.mixer=t,this.onUpdate=n.onUpdate,this.activeClip=e[0]?.name,n.autoplay===!1)for(let i of e)i.playing=!1,i.action.stop();else n.autoplay==="first"&&this.activeClip&&this.selectClip(this.activeClip)}setUpdateHandler(e){return this.onUpdate=e,this}setTime(e){let t=e/1e3,n=this.previousTimeSeconds===void 0?0:t-this.previousTimeSeconds;this.previousTimeSeconds=t;let i=n*this.mixer.timeScale;this.clips.forEach(s=>{if(!s.playing){s.action.stop();return}if(s.action.paused)return;s.action.resume();let o=Math.max(0,t-s.startTime)*s.speed;s.action.setTime(o-i*s.action.timeScale)}),this.mixer.update(n),this.onUpdate?.()}update(e){this.mixer.update(e),this.onUpdate?.()}selectClip(e,t={}){let n=this.clips.find(o=>o.name===e);if(!n)throw new Error(`Unknown animation clip: ${e}`);let i=this.clips.find(o=>o.name===this.activeClip),s=t.crossFadeDuration||0;for(let o of this.clips)o!==n&&!(s>0&&o===i)&&(o.playing=!1,o.action.stop());return n.playing=!0,s>0&&i&&i!==n?(i.playing=!0,i.action.crossFadeTo(n.action,s)):n.action.reset().setEffectiveWeight(1).play(),this.activeClip=e,n}},ni=class extends lt{clip;mixer;action;constructor(e,t=new pt){super({name:e.name}),this.clip=e,this.mixer=t,this.action=t.clipAction(e).play()}applyTime(e){this.action.setTime(e),this.mixer.update(0)}};function ii(r){let e=new ie().set(1,0,0,0,1,0,r.offset[0],r.offset[1],1),t=new ie().set(Math.cos(r.rotation),Math.sin(r.rotation),0,-Math.sin(r.rotation),Math.cos(r.rotation),0,0,0,1),n=new ie().set(r.scale[0],0,0,0,r.scale[1],0,0,0,1);return Array.from(e.multiplyRight(t).multiplyRight(n))}function si(r,e){let t=new ie(ii(r)),n=new ie(ii(e)),i=new ie(t).invert();return Array.from(n.multiplyRight(i))}function Jc(r,e,t){return{id:t,getValue:()=>zd(r[0],e),setValue:n=>{for(let i of r)Gd(i,e,n)}}}function eu(r,e,t=new Map,n){return{id:n,setValue:i=>{for(let s of r)jd(s,e,i,t)}}}function tu(r,e,t={}){return{id:t.id,getValue:()=>{let n=r[e];return Array.isArray(n)?t.component===void 0?[...n]:[n[t.component]]:typeof n=="number"?[n]:[]},setValue:n=>{if(t.component!==void 0){let i=[...r[e]||[1,1,1]];i[t.component]=n[0],r[e]=i}else r[e]=n.length===1?n[0]:[...n];t.onChange?.()}}}function zd(r,e){let n=r.shaderInputs.getUniformValues().pbrMaterial?.[e.property];return Array.isArray(n)?e.component===void 0?[...n]:[n[e.component]]:typeof n=="number"?[n]:[]}function Gd(r,e,t){let n=e.component!==void 0?{[e.property]:Ud(Vd(r,e.property),e.component,t[0])}:{[e.property]:t.length===1?t[0]:t};r.setProps({pbrMaterial:n})}function Vd(r,e){let n=r.shaderInputs.getUniformValues().pbrMaterial?.[e];return Array.isArray(n)?[...n]:[]}function Ud(r,e,t){let n=[...r];return n[e]=t,n}function jd(r,e,t,n){let i=$d(n,r,e);switch(e.path){case"offset":e.component!==void 0?i.offset[e.component]=t[0]:i.offset=[t[0],t[1]];break;case"rotation":i.rotation=t[0];break;case"scale":e.component!==void 0?i.scale[e.component]=t[0]:i.scale=[t[0],t[1]];break}r.setProps({pbrMaterial:{[e.uniform]:si(e.baseTransform,i)}})}function $d(r,e,t){let n=r.get(e)||{},i=n[t.textureSlot];return i||(i={offset:[...t.baseTransform.offset],rotation:t.baseTransform.rotation,scale:[...t.baseTransform.scale]},n[t.textureSlot]=i,r.set(e,n)),i}function ru(r,e){let t=()=>{let i=r.get(e);if(!i||!i.every(s=>typeof s=="number"||typeof s=="boolean"))throw new Error("Missing numeric animation property");return i},n=typeof t()[0]=="boolean";return{id:e,getValue:()=>t().map(Number),setValue:i=>{if(!r.set(e,n?[i[0]!==0]:[...i]))throw new Error("Animation property is not writable")}}}function nu(r){let{positions:e,targets:t=[],weights:n=[],jointMatrices:i,influences:s=[]}=r;if(e.length%3||t.some(a=>a.length!==e.length)||!n.every(Number.isFinite))throw new Error("Invalid position deformation");let o=ir({POSITION:e},t.map(a=>({POSITION:a})),n).POSITION;if(!i){if(!o.every(Number.isFinite))throw new Error("Nonfinite deformation");return o}if(!s.length||s.some(a=>a.joints.length!==e.length/3*4||a.weights.length!==a.joints.length))throw new Error("Invalid skin influences");for(let a=0;a<o.length/3;a++){let c=Array.from(o.subarray(a*3,a*3+3)),u=[0,0,0],h=0;for(let l of s)for(let d=0;d<4;d++){let p=a*4+d,f=l.weights[p];if(!Number.isFinite(f)||f<0)throw new Error("Invalid skin weight");if(!f)continue;let m=l.joints[p],g=i[m];if(!Number.isInteger(m)||!g)throw new Error("Invalid skin joint");let x=g.transformAsPoint(c);for(let T=0;T<3;T++)u[T]+=f*x[T];h+=f}if(!(h>0))throw new Error("Empty skin weights");for(let l=0;l<3;l++)o[a*3+l]=u[l]/h}if(!o.every(Number.isFinite))throw new Error("Nonfinite deformation");return o}var qd=ce;return hu(Ar);})();
|
|
795
799
|
return __exports__;
|
|
796
800
|
});
|