From 126220ba653807c66de03946857ca9c8d8ff195c Mon Sep 17 00:00:00 2001 From: martinlaxenaire Date: Wed, 28 Feb 2024 10:04:53 +0100 Subject: [PATCH] - fixed core targets/targetFormat refactoring --- dist/esm/core/materials/RenderMaterial.mjs | 4 +- dist/esm/core/meshes/FullscreenPlane.mjs | 1 + dist/esm/core/meshes/mixins/MeshBaseMixin.mjs | 20 +- .../core/pipelines/RenderPipelineEntry.mjs | 39 +-- dist/esm/core/renderPasses/RenderPass.mjs | 54 ++-- dist/esm/core/renderPasses/RenderTarget.mjs | 8 +- dist/esm/core/renderPasses/ShaderPass.mjs | 2 +- dist/esm/core/renderers/GPURenderer.mjs | 4 +- dist/esm/curtains/meshes/PingPongPlane.mjs | 9 +- dist/gpu-curtains.umd.js | 141 +++++---- dist/gpu-curtains.umd.min.js | 14 +- dist/gpu-curtains.umd.min.js.map | 2 +- .../core/meshes/mixins/MeshBaseMixin.d.ts | 2 +- .../meshes/mixins/ProjectedMeshBaseMixin.d.ts | 4 +- dist/types/core/renderPasses/RenderPass.d.ts | 10 +- dist/types/types/Materials.d.ts | 19 +- docs/assets/search.js | 2 +- .../core_DOM_DOMElement.DOMElement.html | 30 +- .../core_DOM_DOMFrustum.DOMFrustum.html | 30 +- .../core_bindGroups_BindGroup.BindGroup.html | 66 ++--- ...ups_TextureBindGroup.TextureBindGroup.html | 76 ++--- .../core_bindings_Binding.Binding.html | 18 +- ..._bindings_BufferBinding.BufferBinding.html | 54 ++-- ...indings_SamplerBinding.SamplerBinding.html | 30 +- ...indings_TextureBinding.TextureBinding.html | 32 +- ...leBufferBinding.WritableBufferBinding.html | 58 ++-- ...BufferArrayElement.BufferArrayElement.html | 58 ++-- ...rElements_BufferElement.BufferElement.html | 50 ++-- ...Element.BufferInterleavedArrayElement.html | 60 ++-- docs/classes/core_camera_Camera.Camera.html | 118 ++++---- ...computePasses_ComputePass.ComputePass.html | 92 +++--- .../core_geometries_Geometry.Geometry.html | 46 +-- ...tries_IndexedGeometry.IndexedGeometry.html | 52 ++-- ...eometries_PlaneGeometry.PlaneGeometry.html | 58 ++-- ...rials_ComputeMaterial.ComputeMaterial.html | 110 +++---- .../core_materials_Material.Material.html | 96 +++--- ...terials_RenderMaterial.RenderMaterial.html | 106 +++---- ...eshes_FullscreenPlane.FullscreenPlane.html | 118 ++++---- docs/classes/core_meshes_Mesh.Mesh.html | 214 +++++++------- ...es_mixins_MeshBaseMixin.MeshBaseClass.html | 114 +++---- ...dMeshBaseMixin.ProjectedMeshBaseClass.html | 134 ++++----- .../core_objects3D_Object3D.Object3D.html | 72 ++--- ...D_ProjectedObject3D.ProjectedObject3D.html | 88 +++--- ...utePipelineEntry.ComputePipelineEntry.html | 50 ++-- ...pipelines_PipelineEntry.PipelineEntry.html | 38 +-- ...lines_PipelineManager.PipelineManager.html | 24 +- ...nderPipelineEntry.RenderPipelineEntry.html | 54 ++-- ...re_renderPasses_RenderPass.RenderPass.html | 36 +-- ...enderPasses_RenderTarget.RenderTarget.html | 28 +- ...re_renderPasses_ShaderPass.ShaderPass.html | 124 ++++---- ...s_GPUCameraRenderer.GPUCameraRenderer.html | 196 ++++++------ ...ers_GPUDeviceManager.GPUDeviceManager.html | 82 +++--- ...ore_renderers_GPURenderer.GPURenderer.html | 174 +++++------ .../core_samplers_Sampler.Sampler.html | 24 +- docs/classes/core_scenes_Scene.Scene.html | 40 +-- ..._textures_RenderTexture.RenderTexture.html | 34 +-- .../core_textures_Texture.Texture.html | 164 +++++------ .../curtains_GPUCurtains.GPUCurtains.html | 94 +++--- .../curtains_meshes_DOMMesh.DOMMesh.html | 276 ++++++++--------- ...ns_meshes_PingPongPlane.PingPongPlane.html | 120 ++++---- docs/classes/curtains_meshes_Plane.Plane.html | 278 +++++++++--------- ...ins_objects3D_DOMObject3D.DOMObject3D.html | 138 ++++----- ...UCurtainsRenderer.GPUCurtainsRenderer.html | 198 ++++++------- ...as_geometries_BoxGeometry.BoxGeometry.html | 52 ++-- ...metries_SphereGeometry.SphereGeometry.html | 52 ++-- docs/classes/math_Box3.Box3.html | 18 +- docs/classes/math_Mat4.Mat4.html | 54 ++-- docs/classes/math_Quat.Quat.html | 26 +- docs/classes/math_Vec2.Vec2.html | 62 ++-- docs/classes/math_Vec3.Vec3.html | 82 +++--- .../utils_CacheManager.CacheManager.html | 14 +- .../utils_ResizeManager.ResizeManager.html | 18 +- .../utils_ScrollManager.ScrollManager.html | 18 +- ...s_TasksQueueManager.TasksQueueManager.html | 14 +- ...s_utils.getBindGroupLayoutBindingType.html | 2 +- ....getBindGroupLayoutTextureBindingType.html | 2 +- ..._bindings_utils.getBindingWGSLVarType.html | 2 +- .../core_bindings_utils.getBufferLayout.html | 2 +- ...gs_utils.getTextureBindingWGSLVarType.html | 2 +- ...es_mixins_MeshBaseMixin.MeshBaseMixin.html | 2 +- ...dMeshBaseMixin.ProjectedMeshBaseMixin.html | 2 +- .../core_renderers_utils.generateMips.html | 2 +- ...core_renderers_utils.isCameraRenderer.html | 2 +- ...re_renderers_utils.isCurtainsRenderer.html | 2 +- .../core_renderers_utils.isRenderer.html | 2 +- .../utils_debug.logSceneCommands.html | 2 +- docs/functions/utils_utils.generateUUID.html | 2 +- docs/functions/utils_utils.throwError.html | 2 +- docs/functions/utils_utils.throwWarning.html | 2 +- docs/functions/utils_utils.toCamelCase.html | 2 +- docs/functions/utils_utils.toKebabCase.html | 2 +- docs/hierarchy.html | 2 +- ...DOM_DOMElement.DOMElementBoundingRect.html | 18 +- .../core_DOM_DOMElement.DOMElementParams.html | 10 +- .../core_DOM_DOMElement.DOMPosition.html | 6 +- .../core_DOM_DOMElement.RectBBox.html | 10 +- .../core_DOM_DOMElement.RectCoords.html | 10 +- .../core_DOM_DOMElement.RectSize.html | 6 +- .../core_DOM_DOMFrustum.DOMFrustumParams.html | 14 +- ...xtureBindGroup.TextureBindGroupParams.html | 16 +- .../core_bindings_Binding.BindingParams.html | 10 +- ...BufferBinding.BufferBindingBaseParams.html | 8 +- ...ings_BufferBinding.BufferBindingInput.html | 16 +- ...ngs_BufferBinding.BufferBindingParams.html | 16 +- ...s_SamplerBinding.SamplerBindingParams.html | 14 +- ...s_TextureBinding.TextureBindingParams.html | 20 +- ...erBinding.WritableBufferBindingParams.html | 18 +- ...ArrayElement.BufferArrayElementParams.html | 10 +- ..._BufferElement.BufferElementAlignment.html | 6 +- ...lement.BufferElementAlignmentPosition.html | 6 +- ...nts_BufferElement.BufferElementParams.html | 8 +- ...a_Camera.CameraBasePerspectiveOptions.html | 8 +- .../core_camera_Camera.CameraParams.html | 16 +- ...amera_Camera.CameraPerspectiveOptions.html | 14 +- ...Passes_ComputePass.ComputePassOptions.html | 16 +- ...ePasses_ComputePass.ComputePassParams.html | 30 +- ...eometries_IndexedGeometry.IndexBuffer.html | 10 +- ...try.IndexedGeometryIndexBufferOptions.html | 6 +- ...ies_PlaneGeometry.PlaneGeometryParams.html | 12 +- ..._mixins_MeshBaseMixin.MeshBaseOptions.html | 53 +++- ...s_mixins_MeshBaseMixin.MeshBaseParams.html | 67 ++--- ...ns_MeshBaseMixin.MeshBaseRenderParams.html | 65 ++-- ...eshBaseMixin.ProjectedMeshBaseOptions.html | 57 +++- ...MeshBaseMixin.ProjectedMeshBaseParams.html | 6 +- ...MeshBaseMixin.ProjectedMeshParameters.html | 71 +++-- ...seMixin.ProjectedRenderMaterialParams.html | 59 ++-- ...ts3D_Object3D.Object3DTransformMatrix.html | 8 +- ...objects3D_Object3D.Object3DTransforms.html | 12 +- ...sses_RenderPass.ColorAttachmentParams.html | 10 +- ...derPasses_RenderPass.RenderPassParams.html | 34 +-- ...asses_RenderTarget.RenderTargetParams.html | 36 +-- ...erPasses_ShaderPass.ShaderPassOptions.html | 55 +++- ...derPasses_ShaderPass.ShaderPassParams.html | 69 +++-- ...ameraRenderer.GPUCameraRendererParams.html | 16 +- ...UDeviceManager.GPUDeviceManagerParams.html | 10 +- ...nderers_GPURenderer.GPURendererParams.html | 14 +- .../core_samplers_Sampler.SamplerOptions.html | 2 +- .../core_samplers_Sampler.SamplerParams.html | 4 +- .../core_scenes_Scene.ProjectionStack.html | 6 +- .../core_scenes_Scene.RenderPassEntry.html | 14 +- ...RenderTexture.RenderTextureBaseParams.html | 20 +- ...res_RenderTexture.RenderTextureParams.html | 22 +- ...rtains_GPUCurtains.GPUCurtainsOptions.html | 22 +- ...urtains_GPUCurtains.GPUCurtainsParams.html | 22 +- ...ains_meshes_DOMMesh.DOMMeshBaseParams.html | 69 +++-- ...curtains_meshes_DOMMesh.DOMMeshParams.html | 71 +++-- .../curtains_meshes_Plane.PlaneParams.html | 79 +++-- ...jects3D_DOMObject3D.DOMObject3DParams.html | 4 +- ...objects3D_DOMObject3D.DOMObject3DSize.html | 6 +- ...s3D_DOMObject3D.DOMObject3DTransforms.html | 12 +- ...metries_BoxGeometry.BoxGeometryParams.html | 14 +- ...s_SphereGeometry.SphereGeometryParams.html | 20 +- .../types_BindGroups.BindGroupEntries.html | 6 +- .../types_BindGroups.BindGroupInputs.html | 8 +- .../types_BindGroups.BindGroupParams.html | 12 +- docs/interfaces/types_BindGroups.Input.html | 10 +- .../types_BindGroups.InputBase.html | 8 +- .../types_Geometries.GeometryOptions.html | 10 +- .../types_Geometries.VertexBuffer.html | 16 +- ...ypes_Geometries.VertexBufferAttribute.html | 22 +- ...eometries.VertexBufferAttributeParams.html | 16 +- .../types_Geometries.VertexBufferParams.html | 8 +- ...ypes_Materials.ComputeMaterialOptions.html | 24 +- ...types_Materials.ComputeMaterialParams.html | 24 +- .../types_Materials.MaterialBaseParams.html | 8 +- ...Materials.MaterialInputBindingsParams.html | 16 +- .../types_Materials.MaterialOptions.html | 22 +- .../types_Materials.MaterialParams.html | 22 +- .../types_Materials.MaterialShaders.html | 8 +- ...es_Materials.RenderMaterialAttributes.html | 6 +- ...es_Materials.RenderMaterialBaseParams.html | 49 ++- ...ls.RenderMaterialBaseRenderingOptions.html | 31 +- ...types_Materials.RenderMaterialOptions.html | 24 +- .../types_Materials.RenderMaterialParams.html | 55 ++-- ...erials.RenderMaterialRenderingOptions.html | 35 +-- .../types_Materials.ShaderOptions.html | 6 +- ..._PipelineEntries.PipelineEntryOptions.html | 8 +- ...s_PipelineEntries.PipelineEntryParams.html | 10 +- ...Entries.PipelineEntryPropertiesParams.html | 4 +- ...s_PipelineEntries.PipelineEntryShader.html | 8 +- ..._PipelineEntries.PipelineEntryShaders.html | 10 +- ...s_PipelineEntries.PipelineEntryStatus.html | 8 +- ...Entries.RenderPipelineEntryBaseParams.html | 10 +- ...ineEntries.RenderPipelineEntryOptions.html | 10 +- ...lineEntries.RenderPipelineEntryParams.html | 12 +- ...s.RenderPipelineEntryPropertiesParams.html | 6 +- ...Entries.RenderPipelineRenderingParams.html | 4 +- .../types_Textures.ExternalTextureParams.html | 18 +- .../types_Textures.TextureBaseParams.html | 22 +- .../types_Textures.TextureOptions.html | 28 +- .../types_Textures.TextureParams.html | 24 +- .../types_Textures.TextureSize.html | 8 +- ...tils_ResizeManager.ResizeManagerEntry.html | 8 +- ...ils_ScrollManager.ScrollManagerParams.html | 10 +- ...utils_TasksQueueManager.TaskQueueItem.html | 10 +- docs/modules/core_DOM_DOMElement.html | 2 +- docs/modules/core_DOM_DOMFrustum.html | 2 +- docs/modules/core_bindGroups_BindGroup.html | 2 +- .../core_bindGroups_TextureBindGroup.html | 2 +- docs/modules/core_bindings_Binding.html | 2 +- docs/modules/core_bindings_BufferBinding.html | 2 +- .../modules/core_bindings_SamplerBinding.html | 2 +- .../modules/core_bindings_TextureBinding.html | 2 +- .../core_bindings_WritableBufferBinding.html | 2 +- ...ngs_bufferElements_BufferArrayElement.html | 2 +- ...bindings_bufferElements_BufferElement.html | 2 +- ...lements_BufferInterleavedArrayElement.html | 2 +- docs/modules/core_bindings_utils.html | 2 +- docs/modules/core_camera_Camera.html | 2 +- .../core_computePasses_ComputePass.html | 2 +- docs/modules/core_geometries_Geometry.html | 2 +- .../core_geometries_IndexedGeometry.html | 2 +- .../core_geometries_PlaneGeometry.html | 2 +- .../core_materials_ComputeMaterial.html | 2 +- docs/modules/core_materials_Material.html | 2 +- .../core_materials_RenderMaterial.html | 2 +- docs/modules/core_meshes_FullscreenPlane.html | 2 +- docs/modules/core_meshes_Mesh.html | 2 +- .../core_meshes_mixins_MeshBaseMixin.html | 2 +- ..._meshes_mixins_ProjectedMeshBaseMixin.html | 2 +- docs/modules/core_objects3D_Object3D.html | 2 +- .../core_objects3D_ProjectedObject3D.html | 2 +- .../core_pipelines_ComputePipelineEntry.html | 2 +- .../modules/core_pipelines_PipelineEntry.html | 2 +- .../core_pipelines_PipelineManager.html | 2 +- .../core_pipelines_RenderPipelineEntry.html | 2 +- .../modules/core_renderPasses_RenderPass.html | 2 +- .../core_renderPasses_RenderTarget.html | 2 +- .../modules/core_renderPasses_ShaderPass.html | 2 +- .../core_renderers_GPUCameraRenderer.html | 2 +- .../core_renderers_GPUDeviceManager.html | 2 +- docs/modules/core_renderers_GPURenderer.html | 2 +- docs/modules/core_renderers_utils.html | 2 +- docs/modules/core_samplers_Sampler.html | 2 +- docs/modules/core_scenes_Scene.html | 2 +- docs/modules/core_shaders_ShaderChunks.html | 2 +- docs/modules/core_textures_RenderTexture.html | 2 +- docs/modules/core_textures_Texture.html | 2 +- docs/modules/curtains_GPUCurtains.html | 2 +- docs/modules/curtains_meshes_DOMMesh.html | 2 +- .../curtains_meshes_PingPongPlane.html | 2 +- docs/modules/curtains_meshes_Plane.html | 2 +- .../curtains_objects3D_DOMObject3D.html | 2 +- ...urtains_renderers_GPUCurtainsRenderer.html | 2 +- .../extras_geometries_BoxGeometry.html | 2 +- .../extras_geometries_SphereGeometry.html | 2 +- docs/modules/math_Box3.html | 2 +- docs/modules/math_Mat4.html | 2 +- docs/modules/math_Quat.html | 2 +- docs/modules/math_Vec2.html | 2 +- docs/modules/math_Vec3.html | 2 +- docs/modules/types_BindGroups.html | 2 +- docs/modules/types_Geometries.html | 2 +- docs/modules/types_Materials.html | 2 +- docs/modules/types_PipelineEntries.html | 2 +- docs/modules/types_Textures.html | 2 +- docs/modules/utils_CacheManager.html | 2 +- docs/modules/utils_ResizeManager.html | 2 +- docs/modules/utils_ScrollManager.html | 2 +- docs/modules/utils_TasksQueueManager.html | 2 +- docs/modules/utils_debug.html | 2 +- docs/modules/utils_utils.html | 2 +- ...dings_Binding.BindingMemoryAccessType.html | 2 +- .../core_bindings_Binding.BindingType.html | 2 +- ...Binding.BufferBindingMemoryAccessType.html | 2 +- ...e_bindings_Binding.TextureBindingType.html | 2 +- ...ndings_Binding.TextureSamplerBindings.html | 2 +- ...gs_BufferBinding.AllowedBufferElement.html | 2 +- ...SamplerBinding.SamplerBindingResource.html | 2 +- ...TextureBinding.TextureBindingResource.html | 2 +- .../core_bindings_utils.BufferLayout.html | 2 +- .../types/core_bindings_utils.TypedArray.html | 2 +- ..._bindings_utils.TypedArrayConstructor.html | 2 +- .../core_bindings_utils.WGSLVariableType.html | 2 +- ..._camera_Camera.CameraObject3DMatrices.html | 2 +- ...era_Camera.CameraObject3DMatricesType.html | 2 +- ...mixins_MeshBaseMixin.MixinConstructor.html | 2 +- ...e_objects3D_Object3D.Object3DMatrices.html | 2 +- ...jects3D_Object3D.Object3DMatricesType.html | 2 +- ...tedObject3D.ProjectedObject3DMatrices.html | 2 +- ...bject3D.ProjectedObject3DMatricesType.html | 2 +- ...ipelineManager.AllowedPipelineEntries.html | 2 +- ...enderers_GPURenderer.DOMProjectedMesh.html | 2 +- ...e_renderers_GPURenderer.ProjectedMesh.html | 2 +- ...re_renderers_GPURenderer.RenderedMesh.html | 2 +- ...ore_renderers_GPURenderer.SceneObject.html | 2 +- .../core_renderers_utils.CameraRenderer.html | 2 +- docs/types/core_renderers_utils.Renderer.html | 2 +- .../core_scenes_Scene.ProjectionType.html | 2 +- .../core_scenes_Scene.RenderPassEntries.html | 2 +- ...re_scenes_Scene.RenderPassEntriesType.html | 2 +- docs/types/core_scenes_Scene.Stack.html | 2 +- ..._ShaderChunks.ProjectedShaderChunks-1.html | 2 +- ...e_shaders_ShaderChunks.ShaderChunks-1.html | 2 +- ...enderTexture.RenderTextureBindingType.html | 2 +- docs/types/math_Quat.AxisOrder.html | 2 +- .../types_BindGroups.AllowedBindGroups.html | 2 +- ...es_BindGroups.BindGroupBindingElement.html | 2 +- ...dGroups.BindGroupBufferBindingElement.html | 2 +- ...Groups.BindGroupTextureSamplerElement.html | 2 +- docs/types/types_BindGroups.InputValue.html | 2 +- ...ypes_BindGroups.ReadOnlyInputBindings.html | 2 +- ...pes_BindGroups.ReadWriteInputBindings.html | 2 +- .../types_Geometries.GeometryBaseParams.html | 2 +- .../types_Geometries.GeometryParams.html | 2 +- .../types_Materials.AllowedGeometries.html | 2 +- ..._Materials.ComputeMaterialShadersType.html | 2 +- .../types_Materials.FullShadersType.html | 2 +- .../types_Materials.MaterialBindGroups.html | 2 +- .../types_Materials.MaterialShadersType.html | 2 +- .../types_Materials.MaterialTexture.html | 2 +- ...s_Materials.RenderMaterialShadersType.html | 2 +- ...pelineEntries.PipelineEntryBaseParams.html | 2 +- docs/types/types_Textures.TextureParent.html | 2 +- docs/types/types_Textures.TextureSource.html | 2 +- .../types_Textures.TextureSourceType.html | 2 +- ...TasksQueueManager.TaskQueueItemParams.html | 2 +- ...ferElements_BufferElement.bytesPerRow.html | 2 +- ...erElements_BufferElement.bytesPerSlot.html | 2 +- ...ferElements_BufferElement.slotsPerRow.html | 2 +- ...rs_ShaderChunks.ProjectedShaderChunks.html | 2 +- ...ore_shaders_ShaderChunks.ShaderChunks.html | 2 +- .../utils_CacheManager.cacheManager-1.html | 2 +- .../utils_ResizeManager.resizeManager-1.html | 2 +- src/core/materials/RenderMaterial.ts | 13 +- src/core/meshes/FullscreenPlane.ts | 3 + src/core/meshes/mixins/MeshBaseMixin.ts | 42 +-- src/core/pipelines/RenderPipelineEntry.ts | 28 -- src/core/renderPasses/RenderPass.ts | 72 ++--- src/core/renderPasses/RenderTarget.ts | 11 +- src/core/renderPasses/ShaderPass.ts | 5 +- src/core/renderers/GPURenderer.ts | 2 - src/curtains/meshes/PingPongPlane.ts | 14 +- src/types/Materials.ts | 19 +- tests/objects-removal/TestPingPong.js | 1 - tests/order-independent-transparency/main.js | 32 +- 336 files changed, 3745 insertions(+), 3715 deletions(-) diff --git a/dist/esm/core/materials/RenderMaterial.mjs b/dist/esm/core/materials/RenderMaterial.mjs index 636e4e054..6d2731c6f 100644 --- a/dist/esm/core/materials/RenderMaterial.mjs +++ b/dist/esm/core/materials/RenderMaterial.mjs @@ -22,7 +22,9 @@ class RenderMaterial extends Material { if (shaders.fragment && !shaders.fragment.entryPoint) { shaders.fragment.entryPoint = "main"; } - renderingOptions.targetFormat = renderingOptions.targetFormat ?? this.renderer.options.preferredFormat; + if (!renderingOptions.targets || !renderingOptions.targets.length || !renderingOptions.targets[0].format) { + renderingOptions.targets[0].format = this.renderer.options.preferredFormat; + } this.options = { ...this.options, shaders, diff --git a/dist/esm/core/meshes/FullscreenPlane.mjs b/dist/esm/core/meshes/FullscreenPlane.mjs index f6eaf19cf..52a458c35 100644 --- a/dist/esm/core/meshes/FullscreenPlane.mjs +++ b/dist/esm/core/meshes/FullscreenPlane.mjs @@ -26,6 +26,7 @@ class FullscreenPlane extends MeshBaseMixin(class { ); }); } + parameters.depthWriteEnabled = false; super(renderer, null, { geometry, ...parameters }); this.size = { document: { diff --git a/dist/esm/core/meshes/mixins/MeshBaseMixin.mjs b/dist/esm/core/meshes/mixins/MeshBaseMixin.mjs index 4fa8628d6..73da193f9 100644 --- a/dist/esm/core/meshes/mixins/MeshBaseMixin.mjs +++ b/dist/esm/core/meshes/mixins/MeshBaseMixin.mjs @@ -311,18 +311,20 @@ function MeshBaseMixin(Base) { */ setRenderingOptionsForRenderPass(renderPass) { const renderingOptions = { + // sample count sampleCount: renderPass.options.sampleCount, // color attachments ...renderPass.options.colorAttachments.length && { - targetFormat: renderPass.options.colorAttachments[0].targetFormat, - // multiple render targets? - ...renderPass.options.colorAttachments.length > 1 && { - additionalTargets: renderPass.options.colorAttachments.filter((c, i) => i > 0).map((colorAttachment) => { - return { - format: colorAttachment.targetFormat - }; - }) - } + targets: renderPass.options.colorAttachments.map((colorAttachment, index) => { + return { + // patch format... + format: colorAttachment.targetFormat, + // ...but keep original blend values if any + ...this.options.targets?.length && this.options.targets[index] && this.options.targets[index].blend && { + blend: this.options.targets[index].blend + } + }; + }) }, // depth depth: renderPass.options.useDepth, diff --git a/dist/esm/core/pipelines/RenderPipelineEntry.mjs b/dist/esm/core/pipelines/RenderPipelineEntry.mjs index 8d948fd8f..dee531f4e 100644 --- a/dist/esm/core/pipelines/RenderPipelineEntry.mjs +++ b/dist/esm/core/pipelines/RenderPipelineEntry.mjs @@ -208,16 +208,26 @@ ${this.shaders.full.head}`; if (!this.shadersModulesReady) return; let vertexLocationIndex = -1; - const blend = this.options.rendering.blend ?? (this.options.rendering.transparent && { - color: { - srcFactor: "src-alpha", - dstFactor: "one-minus-src-alpha" - }, - alpha: { - srcFactor: "one", - dstFactor: "one-minus-src-alpha" + if (this.options.rendering.targets.length) { + if (this.options.rendering.transparent) { + this.options.rendering.targets[0].blend = this.options.rendering.targets[0].blend ? this.options.rendering.targets[0].blend : { + color: { + srcFactor: "src-alpha", + dstFactor: "one-minus-src-alpha" + }, + alpha: { + srcFactor: "one", + dstFactor: "one-minus-src-alpha" + } + }; } - }); + } else { + this.options.rendering.targets = [ + { + format: this.renderer.options.preferredFormat + } + ]; + } this.descriptor = { label: this.options.label, layout: this.layout, @@ -245,16 +255,7 @@ ${this.shaders.full.head}`; fragment: { module: this.shaders.fragment.module, entryPoint: this.options.shaders.fragment.entryPoint, - targets: [ - { - format: this.options.rendering.targetFormat ?? this.renderer.options.preferredFormat, - ...blend && { - blend - } - }, - ...this.options.rendering.additionalTargets ?? [] - // merge with additional targets if any - ] + targets: this.options.rendering.targets } }, primitive: { diff --git a/dist/esm/core/renderPasses/RenderPass.mjs b/dist/esm/core/renderPasses/RenderPass.mjs index 01158eac2..da69e5334 100644 --- a/dist/esm/core/renderPasses/RenderPass.mjs +++ b/dist/esm/core/renderPasses/RenderPass.mjs @@ -15,10 +15,6 @@ class RenderPass { // color useColorAttachments = true, shouldUpdateView = true, - loadOp = "clear", - storeOp = "store", - clearValue = [0, 0, 0, 0], - targetFormat, colorAttachments = [], // depth useDepth = true, @@ -35,10 +31,10 @@ class RenderPass { this.renderer = renderer; if (useColorAttachments) { const defaultColorAttachment = { - loadOp, - storeOp, - clearValue, - targetFormat: targetFormat ?? this.renderer.options.preferredFormat + loadOp: "clear", + storeOp: "store", + clearValue: [0, 0, 0, 0], + targetFormat: this.renderer.options.preferredFormat }; if (!colorAttachments.length) { colorAttachments = [defaultColorAttachment]; @@ -55,10 +51,6 @@ class RenderPass { // color useColorAttachments, shouldUpdateView, - loadOp, - storeOp, - clearValue, - targetFormat: targetFormat ?? this.renderer.options.preferredFormat, colorAttachments, // depth useDepth, @@ -68,7 +60,6 @@ class RenderPass { depthClearValue, depthFormat }; - this.setClearValue(clearValue); if (this.options.useDepth) { this.createDepthTexture(); } @@ -169,10 +160,14 @@ class RenderPass { * @param colorAttachmentIndex - index of the color attachment for which to use this load operation */ setLoadOp(loadOp = "clear", colorAttachmentIndex = 0) { - this.options.loadOp = loadOp; - if (this.options.useColorAttachments && this.descriptor) { - if (this.descriptor.colorAttachments && this.descriptor.colorAttachments[colorAttachmentIndex]) { - this.descriptor.colorAttachments[colorAttachmentIndex].loadOp = loadOp; + if (this.options.useColorAttachments) { + if (this.options.colorAttachments[colorAttachmentIndex]) { + this.options.colorAttachments[colorAttachmentIndex].loadOp = loadOp; + } + if (this.descriptor) { + if (this.descriptor.colorAttachments && this.descriptor.colorAttachments[colorAttachmentIndex]) { + this.descriptor.colorAttachments[colorAttachmentIndex].loadOp = loadOp; + } } } } @@ -193,16 +188,21 @@ class RenderPass { * @param colorAttachmentIndex - index of the color attachment for which to use this clear value */ setClearValue(clearValue = [0, 0, 0, 0], colorAttachmentIndex = 0) { - if (this.renderer.alphaMode === "premultiplied") { - const alpha = clearValue[3]; - clearValue[0] = Math.min(clearValue[0], alpha); - clearValue[1] = Math.min(clearValue[1], alpha); - clearValue[2] = Math.min(clearValue[2], alpha); - } else { - this.options.clearValue = clearValue; - } - if (this.descriptor && this.descriptor.colorAttachments && this.descriptor.colorAttachments[colorAttachmentIndex]) { - this.descriptor.colorAttachments[colorAttachmentIndex].clearValue = clearValue; + if (this.options.useColorAttachments) { + if (this.renderer.alphaMode === "premultiplied") { + const alpha = clearValue[3]; + clearValue[0] = Math.min(clearValue[0], alpha); + clearValue[1] = Math.min(clearValue[1], alpha); + clearValue[2] = Math.min(clearValue[2], alpha); + } + if (this.options.colorAttachments[colorAttachmentIndex]) { + this.options.colorAttachments[colorAttachmentIndex].clearValue = clearValue; + } + if (this.descriptor) { + if (this.descriptor.colorAttachments && this.descriptor.colorAttachments[colorAttachmentIndex]) { + this.descriptor.colorAttachments[colorAttachmentIndex].clearValue = clearValue; + } + } } } /** diff --git a/dist/esm/core/renderPasses/RenderTarget.mjs b/dist/esm/core/renderPasses/RenderTarget.mjs index 01678cf90..d5a2d9ac4 100644 --- a/dist/esm/core/renderPasses/RenderTarget.mjs +++ b/dist/esm/core/renderPasses/RenderTarget.mjs @@ -36,12 +36,12 @@ class RenderTarget { this.type = "RenderTarget"; this.renderer = renderer; this.uuid = generateUUID(); - const { label, targetFormat, depthTexture, autoRender, ...renderPassParams } = parameters; + const { label, colorAttachments, depthTexture, autoRender, ...renderPassParams } = parameters; this.options = { label, ...renderPassParams, ...depthTexture && { depthTexture }, - targetFormat: targetFormat ?? this.renderer.options.preferredFormat, + ...colorAttachments && { colorAttachments }, autoRender: autoRender === void 0 ? true : autoRender }; if (autoRender !== void 0) { @@ -49,7 +49,7 @@ class RenderTarget { } this.renderPass = new RenderPass(this.renderer, { label: this.options.label ? `${this.options.label} Render Pass` : "Render Target Render Pass", - targetFormat: this.options.targetFormat, + ...colorAttachments && { colorAttachments }, depthTexture: this.options.depthTexture ?? this.renderer.renderPass.depthTexture, // reuse renderer depth texture for every pass ...renderPassParams @@ -58,7 +58,7 @@ class RenderTarget { this.renderTexture = new RenderTexture(this.renderer, { label: this.options.label ? `${this.options.label} Render Texture` : "Render Target render texture", name: "renderTexture", - format: this.options.targetFormat, + format: colorAttachments && colorAttachments.length && colorAttachments[0].targetFormat ? colorAttachments[0].targetFormat : this.renderer.options.preferredFormat, ...this.options.qualityRatio !== void 0 && { qualityRatio: this.options.qualityRatio } }); } diff --git a/dist/esm/core/renderPasses/ShaderPass.mjs b/dist/esm/core/renderPasses/ShaderPass.mjs index 155f526d1..d1cd7520b 100644 --- a/dist/esm/core/renderPasses/ShaderPass.mjs +++ b/dist/esm/core/renderPasses/ShaderPass.mjs @@ -12,7 +12,7 @@ class ShaderPass extends FullscreenPlane { constructor(renderer, parameters = {}) { renderer = renderer && renderer.renderer || renderer; isRenderer(renderer, parameters.label ? parameters.label + " ShaderPass" : "ShaderPass"); - parameters.transparent = true; + parameters.depth = false; parameters.label = parameters.label ?? "ShaderPass " + renderer.shaderPasses?.length; parameters.sampleCount = !!parameters.sampleCount ? parameters.sampleCount : renderer && renderer.postProcessingPass ? renderer && renderer.postProcessingPass.options.sampleCount : 1; if (!parameters.shaders) { diff --git a/dist/esm/core/renderers/GPURenderer.mjs b/dist/esm/core/renderers/GPURenderer.mjs index bb6d3e2a9..20f1314ab 100644 --- a/dist/esm/core/renderers/GPURenderer.mjs +++ b/dist/esm/core/renderers/GPURenderer.mjs @@ -274,12 +274,12 @@ class GPURenderer { setMainRenderPasses() { this.renderPass = new RenderPass(this, { label: "Main render pass", - targetFormat: this.options.preferredFormat, + //targetFormat: this.options.preferredFormat, ...this.options.renderPass }); this.postProcessingPass = new RenderPass(this, { label: "Post processing render pass", - targetFormat: this.options.preferredFormat, + //targetFormat: this.options.preferredFormat, // no need to handle depth or perform MSAA on a fullscreen quad useDepth: false, sampleCount: 1 diff --git a/dist/esm/curtains/meshes/PingPongPlane.mjs b/dist/esm/curtains/meshes/PingPongPlane.mjs index b13fdea5d..00b197cc8 100644 --- a/dist/esm/curtains/meshes/PingPongPlane.mjs +++ b/dist/esm/curtains/meshes/PingPongPlane.mjs @@ -11,10 +11,15 @@ class PingPongPlane extends FullscreenPlane { constructor(renderer, parameters = {}) { renderer = renderer && renderer.renderer || renderer; isRenderer(renderer, parameters.label ? parameters.label + " PingPongPlane" : "PingPongPlane"); + const colorAttachments = parameters.targets && parameters.targets.length && parameters.targets.map((target) => { + return { + targetFormat: target.format + }; + }); parameters.outputTarget = new RenderTarget(renderer, { label: parameters.label ? parameters.label + " render target" : "Ping Pong render target", useDepth: false, - ...parameters.targetFormat && { targetFormat: parameters.targetFormat } + ...colorAttachments && { colorAttachments } }); parameters.transparent = false; parameters.depth = false; @@ -24,7 +29,7 @@ class PingPongPlane extends FullscreenPlane { this.createRenderTexture({ label: parameters.label ? `${parameters.label} render texture` : "PingPongPlane render texture", name: "renderTexture", - ...parameters.targetFormat && { format: parameters.targetFormat } + ...parameters.targets && parameters.targets.length && { format: parameters.targets[0].format } }); } /** diff --git a/dist/gpu-curtains.umd.js b/dist/gpu-curtains.umd.js index a92271ecb..90f981429 100644 --- a/dist/gpu-curtains.umd.js +++ b/dist/gpu-curtains.umd.js @@ -5910,7 +5910,9 @@ if (shaders.fragment && !shaders.fragment.entryPoint) { shaders.fragment.entryPoint = "main"; } - renderingOptions.targetFormat = renderingOptions.targetFormat ?? this.renderer.options.preferredFormat; + if (!renderingOptions.targets || !renderingOptions.targets.length || !renderingOptions.targets[0].format) { + renderingOptions.targets[0].format = this.renderer.options.preferredFormat; + } this.options = { ...this.options, shaders, @@ -6337,18 +6339,20 @@ struct VertexOutput { */ setRenderingOptionsForRenderPass(renderPass) { const renderingOptions = { + // sample count sampleCount: renderPass.options.sampleCount, // color attachments ...renderPass.options.colorAttachments.length && { - targetFormat: renderPass.options.colorAttachments[0].targetFormat, - // multiple render targets? - ...renderPass.options.colorAttachments.length > 1 && { - additionalTargets: renderPass.options.colorAttachments.filter((c, i) => i > 0).map((colorAttachment) => { - return { - format: colorAttachment.targetFormat - }; - }) - } + targets: renderPass.options.colorAttachments.map((colorAttachment, index) => { + return { + // patch format... + format: colorAttachment.targetFormat, + // ...but keep original blend values if any + ...this.options.targets?.length && this.options.targets[index] && this.options.targets[index].blend && { + blend: this.options.targets[index].blend + } + }; + }) }, // depth depth: renderPass.options.useDepth, @@ -6696,6 +6700,7 @@ struct VertexOutput { ); }); } + parameters.depthWriteEnabled = false; super(renderer, null, { geometry, ...parameters }); this.size = { document: { @@ -7553,16 +7558,26 @@ ${this.shaders.full.head}`; if (!this.shadersModulesReady) return; let vertexLocationIndex = -1; - const blend = this.options.rendering.blend ?? (this.options.rendering.transparent && { - color: { - srcFactor: "src-alpha", - dstFactor: "one-minus-src-alpha" - }, - alpha: { - srcFactor: "one", - dstFactor: "one-minus-src-alpha" + if (this.options.rendering.targets.length) { + if (this.options.rendering.transparent) { + this.options.rendering.targets[0].blend = this.options.rendering.targets[0].blend ? this.options.rendering.targets[0].blend : { + color: { + srcFactor: "src-alpha", + dstFactor: "one-minus-src-alpha" + }, + alpha: { + srcFactor: "one", + dstFactor: "one-minus-src-alpha" + } + }; } - }); + } else { + this.options.rendering.targets = [ + { + format: this.renderer.options.preferredFormat + } + ]; + } this.descriptor = { label: this.options.label, layout: this.layout, @@ -7590,16 +7605,7 @@ ${this.shaders.full.head}`; fragment: { module: this.shaders.fragment.module, entryPoint: this.options.shaders.fragment.entryPoint, - targets: [ - { - format: this.options.rendering.targetFormat ?? this.renderer.options.preferredFormat, - ...blend && { - blend - } - }, - ...this.options.rendering.additionalTargets ?? [] - // merge with additional targets if any - ] + targets: this.options.rendering.targets } }, primitive: { @@ -8442,10 +8448,6 @@ ${this.shaders.compute.head}`; // color useColorAttachments = true, shouldUpdateView = true, - loadOp = "clear", - storeOp = "store", - clearValue = [0, 0, 0, 0], - targetFormat, colorAttachments = [], // depth useDepth = true, @@ -8462,10 +8464,10 @@ ${this.shaders.compute.head}`; this.renderer = renderer; if (useColorAttachments) { const defaultColorAttachment = { - loadOp, - storeOp, - clearValue, - targetFormat: targetFormat ?? this.renderer.options.preferredFormat + loadOp: "clear", + storeOp: "store", + clearValue: [0, 0, 0, 0], + targetFormat: this.renderer.options.preferredFormat }; if (!colorAttachments.length) { colorAttachments = [defaultColorAttachment]; @@ -8482,10 +8484,6 @@ ${this.shaders.compute.head}`; // color useColorAttachments, shouldUpdateView, - loadOp, - storeOp, - clearValue, - targetFormat: targetFormat ?? this.renderer.options.preferredFormat, colorAttachments, // depth useDepth, @@ -8495,7 +8493,6 @@ ${this.shaders.compute.head}`; depthClearValue, depthFormat }; - this.setClearValue(clearValue); if (this.options.useDepth) { this.createDepthTexture(); } @@ -8596,10 +8593,14 @@ ${this.shaders.compute.head}`; * @param colorAttachmentIndex - index of the color attachment for which to use this load operation */ setLoadOp(loadOp = "clear", colorAttachmentIndex = 0) { - this.options.loadOp = loadOp; - if (this.options.useColorAttachments && this.descriptor) { - if (this.descriptor.colorAttachments && this.descriptor.colorAttachments[colorAttachmentIndex]) { - this.descriptor.colorAttachments[colorAttachmentIndex].loadOp = loadOp; + if (this.options.useColorAttachments) { + if (this.options.colorAttachments[colorAttachmentIndex]) { + this.options.colorAttachments[colorAttachmentIndex].loadOp = loadOp; + } + if (this.descriptor) { + if (this.descriptor.colorAttachments && this.descriptor.colorAttachments[colorAttachmentIndex]) { + this.descriptor.colorAttachments[colorAttachmentIndex].loadOp = loadOp; + } } } } @@ -8620,16 +8621,21 @@ ${this.shaders.compute.head}`; * @param colorAttachmentIndex - index of the color attachment for which to use this clear value */ setClearValue(clearValue = [0, 0, 0, 0], colorAttachmentIndex = 0) { - if (this.renderer.alphaMode === "premultiplied") { - const alpha = clearValue[3]; - clearValue[0] = Math.min(clearValue[0], alpha); - clearValue[1] = Math.min(clearValue[1], alpha); - clearValue[2] = Math.min(clearValue[2], alpha); - } else { - this.options.clearValue = clearValue; - } - if (this.descriptor && this.descriptor.colorAttachments && this.descriptor.colorAttachments[colorAttachmentIndex]) { - this.descriptor.colorAttachments[colorAttachmentIndex].clearValue = clearValue; + if (this.options.useColorAttachments) { + if (this.renderer.alphaMode === "premultiplied") { + const alpha = clearValue[3]; + clearValue[0] = Math.min(clearValue[0], alpha); + clearValue[1] = Math.min(clearValue[1], alpha); + clearValue[2] = Math.min(clearValue[2], alpha); + } + if (this.options.colorAttachments[colorAttachmentIndex]) { + this.options.colorAttachments[colorAttachmentIndex].clearValue = clearValue; + } + if (this.descriptor) { + if (this.descriptor.colorAttachments && this.descriptor.colorAttachments[colorAttachmentIndex]) { + this.descriptor.colorAttachments[colorAttachmentIndex].clearValue = clearValue; + } + } } } /** @@ -9018,12 +9024,12 @@ ${this.shaders.compute.head}`; setMainRenderPasses() { this.renderPass = new RenderPass(this, { label: "Main render pass", - targetFormat: this.options.preferredFormat, + //targetFormat: this.options.preferredFormat, ...this.options.renderPass }); this.postProcessingPass = new RenderPass(this, { label: "Post processing render pass", - targetFormat: this.options.preferredFormat, + //targetFormat: this.options.preferredFormat, // no need to handle depth or perform MSAA on a fullscreen quad useDepth: false, sampleCount: 1 @@ -10016,12 +10022,12 @@ ${this.shaders.compute.head}`; this.type = "RenderTarget"; this.renderer = renderer; this.uuid = generateUUID(); - const { label, targetFormat, depthTexture, autoRender, ...renderPassParams } = parameters; + const { label, colorAttachments, depthTexture, autoRender, ...renderPassParams } = parameters; this.options = { label, ...renderPassParams, ...depthTexture && { depthTexture }, - targetFormat: targetFormat ?? this.renderer.options.preferredFormat, + ...colorAttachments && { colorAttachments }, autoRender: autoRender === void 0 ? true : autoRender }; if (autoRender !== void 0) { @@ -10029,7 +10035,7 @@ ${this.shaders.compute.head}`; } this.renderPass = new RenderPass(this.renderer, { label: this.options.label ? `${this.options.label} Render Pass` : "Render Target Render Pass", - targetFormat: this.options.targetFormat, + ...colorAttachments && { colorAttachments }, depthTexture: this.options.depthTexture ?? this.renderer.renderPass.depthTexture, // reuse renderer depth texture for every pass ...renderPassParams @@ -10038,7 +10044,7 @@ ${this.shaders.compute.head}`; this.renderTexture = new RenderTexture(this.renderer, { label: this.options.label ? `${this.options.label} Render Texture` : "Render Target render texture", name: "renderTexture", - format: this.options.targetFormat, + format: colorAttachments && colorAttachments.length && colorAttachments[0].targetFormat ? colorAttachments[0].targetFormat : this.renderer.options.preferredFormat, ...this.options.qualityRatio !== void 0 && { qualityRatio: this.options.qualityRatio } }); } @@ -10119,7 +10125,7 @@ struct VSOutput { constructor(renderer, parameters = {}) { renderer = renderer && renderer.renderer || renderer; isRenderer(renderer, parameters.label ? parameters.label + " ShaderPass" : "ShaderPass"); - parameters.transparent = true; + parameters.depth = false; parameters.label = parameters.label ?? "ShaderPass " + renderer.shaderPasses?.length; parameters.sampleCount = !!parameters.sampleCount ? parameters.sampleCount : renderer && renderer.postProcessingPass ? renderer && renderer.postProcessingPass.options.sampleCount : 1; if (!parameters.shaders) { @@ -10691,10 +10697,15 @@ struct VSOutput { constructor(renderer, parameters = {}) { renderer = renderer && renderer.renderer || renderer; isRenderer(renderer, parameters.label ? parameters.label + " PingPongPlane" : "PingPongPlane"); + const colorAttachments = parameters.targets && parameters.targets.length && parameters.targets.map((target) => { + return { + targetFormat: target.format + }; + }); parameters.outputTarget = new RenderTarget(renderer, { label: parameters.label ? parameters.label + " render target" : "Ping Pong render target", useDepth: false, - ...parameters.targetFormat && { targetFormat: parameters.targetFormat } + ...colorAttachments && { colorAttachments } }); parameters.transparent = false; parameters.depth = false; @@ -10704,7 +10715,7 @@ struct VSOutput { this.createRenderTexture({ label: parameters.label ? `${parameters.label} render texture` : "PingPongPlane render texture", name: "renderTexture", - ...parameters.targetFormat && { format: parameters.targetFormat } + ...parameters.targets && parameters.targets.length && { format: parameters.targets[0].format } }); } /** diff --git a/dist/gpu-curtains.umd.min.js b/dist/gpu-curtains.umd.min.js index d9ab459c7..cea577347 100644 --- a/dist/gpu-curtains.umd.min.js +++ b/dist/gpu-curtains.umd.min.js @@ -47,7 +47,7 @@ };`;const r=fe(this);this.wgslGroupFragment=[`${r} ${this.name}: array<${e}${i}>;`]}}else{this.wgslStructFragment=`struct ${e} { ${this.bufferElements.map(r=>{const n=this.bindingType==="uniform"&&"numElements"in r?`array<${r.type.replace("array","").replace("<","").replace(">","")}, ${r.numElements}>`:r.type;return r.name+": "+n}).join(`, `)} -};`;const i=fe(this);this.wgslGroupFragment=[`${i} ${this.name}: ${e};`]}}else this.wgslStructFragment="",this.wgslGroupFragment=this.bufferElements.map(t=>`${fe(this)} ${t.name}: ${t.type};`)}shouldUpdateBinding(e=""){const t=Object.keys(this.inputs).find(s=>this.inputs[s].name===e);t&&(this.inputs[t].shouldUpdate=!0)}update(){Object.keys(this.inputs).forEach(e=>{const t=this.inputs[e],s=this.bufferElements.find(i=>i.key===e);t.shouldUpdate&&s&&(t.onBeforeUpdate&&t.onBeforeUpdate(),s.update(t.value),this.shouldUpdate=!0,t.shouldUpdate=!1)})}extractBufferElementDataFromBufferResult({result:e,bufferElementName:t}){const s=this.bufferElements.find(i=>i.name===t);return s?s.extractDataFromBufferResult(e):e}}class Ve extends ne{constructor({label:e="Work",name:t="work",bindingType:s,useStruct:i=!0,struct:r={},visibility:n,access:a="read_write",shouldCopyResult:h=!1}){s="storage",n="compute",super({label:e,name:t,bindingType:s,useStruct:i,struct:r,visibility:n,access:a}),this.options={...this.options,shouldCopyResult:h},this.shouldCopyResult=h,this.resultBuffer=null}}class ge{constructor(e,{label:t="BindGroup",index:s=0,bindings:i=[],uniforms:r,storages:n}={}){this.type="BindGroup",e=e&&e.renderer||e,z(e,this.type),this.renderer=e,this.options={label:t,index:s,bindings:i,...r&&{uniforms:r},...n&&{storages:n}},this.index=s,this.uuid=D(),this.bindings=[],i.length&&this.addBindings(i),(this.options.uniforms||this.options.storages)&&this.setInputBindings(),this.resetEntries(),this.bindGroupLayout=null,this.bindGroup=null,this.needsPipelineFlush=!1,this.renderer.addBindGroup(this)}setIndex(e){this.index=e}addBindings(e=[]){this.bindings=[...this.bindings,...e]}addBinding(e){this.bindings.push(e)}createInputBindings(e="uniform",t={}){return[...Object.keys(t).map(s=>{const i=t[s],r={label:Ue(i.label||s),name:s,bindingType:e,useStruct:!0,visibility:i.access==="read_write"?"compute":i.visibility,access:i.access??"read",struct:i.struct,...i.shouldCopyResult!==void 0&&{shouldCopyResult:i.shouldCopyResult}},n=r.access==="read_write"?Ve:ne;return i.useStruct!==!1?new n(r):Object.keys(i.struct).map(a=>(r.label=Ue(i.label?i.label+a:s+a),r.name=s+a,r.useStruct=!1,r.struct={[a]:i.struct[a]},new n(r)))})].flat()}setInputBindings(){this.addBindings([...this.createInputBindings("uniform",this.options.uniforms),...this.createInputBindings("storage",this.options.storages)])}get shouldCreateBindGroup(){return!this.bindGroup&&!!this.bindings.length}resetEntries(){this.entries={bindGroupLayout:[],bindGroup:[]}}createBindGroup(){this.fillEntries(),this.setBindGroupLayout(),this.setBindGroup()}resetBindGroup(){this.entries.bindGroup=[],this.bindings.forEach(e=>{this.entries.bindGroup.push({binding:this.entries.bindGroup.length,resource:e.resource})}),this.setBindGroup()}resetBindGroupLayout(){this.entries.bindGroupLayout=[],this.bindings.forEach(e=>{this.entries.bindGroupLayout.push({binding:this.entries.bindGroupLayout.length,...e.resourceLayout,visibility:e.visibility})}),this.setBindGroupLayout()}loseContext(){this.resetEntries(),this.bufferBindings.forEach(e=>{e.buffer=null,"resultBuffer"in e&&(e.resultBuffer=null)}),this.bindGroup=null,this.bindGroupLayout=null,this.needsPipelineFlush=!0}get bufferBindings(){return this.bindings.filter(e=>e instanceof ne||e instanceof Ve)}createBindingBuffer(e){e.buffer=this.renderer.createBuffer({label:this.options.label+": "+e.bindingType+" buffer from: "+e.label,size:e.arrayBuffer.byteLength,usage:e.bindingType==="uniform"?GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC|GPUBufferUsage.VERTEX:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC|GPUBufferUsage.VERTEX}),"resultBuffer"in e&&(e.resultBuffer=this.renderer.createBuffer({label:this.options.label+": Result buffer from: "+e.label,size:e.arrayBuffer.byteLength,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}))}fillEntries(){this.bindings.forEach(e=>{e.visibility||(e.visibility=GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT|GPUShaderStage.COMPUTE),"buffer"in e&&!e.buffer&&this.createBindingBuffer(e),this.entries.bindGroupLayout.push({binding:this.entries.bindGroupLayout.length,...e.resourceLayout,visibility:e.visibility}),this.entries.bindGroup.push({binding:this.entries.bindGroup.length,resource:e.resource})})}getBindingByName(e=""){return this.bindings.find(t=>t.name===e)}setBindGroupLayout(){this.bindGroupLayout=this.renderer.createBindGroupLayout({label:this.options.label+" layout",entries:this.entries.bindGroupLayout})}setBindGroup(){this.bindGroup=this.renderer.createBindGroup({label:this.options.label,layout:this.bindGroupLayout,entries:this.entries.bindGroup})}updateBufferBindings(){this.bufferBindings.forEach((e,t)=>{e.update(),e.shouldUpdate&&(!e.useStruct&&e.bufferElements.length>1?this.renderer.queueWriteBuffer(e.buffer,0,e.bufferElements[t].view):this.renderer.queueWriteBuffer(e.buffer,0,e.arrayBuffer)),e.shouldUpdate=!1})}update(){this.updateBufferBindings();const e=this.bindings.some(s=>s.shouldResetBindGroup),t=this.bindings.some(s=>s.shouldResetBindGroupLayout);(e||t)&&this.renderer.onAfterCommandEncoderSubmission.add(()=>{this.bindings.forEach(s=>{s.shouldResetBindGroup=!1,s.shouldResetBindGroupLayout=!1})},{once:!0}),t&&(this.resetBindGroupLayout(),this.needsPipelineFlush=!0),e&&this.resetBindGroup()}clone({bindings:e=[],keepLayout:t=!1}={}){const s={...this.options};s.label+=" (copy)";const i=new this.constructor(this.renderer,{label:s.label});return i.setIndex(this.index),i.options=s,(e.length?e:this.bindings).forEach((n,a)=>{i.addBinding(n),"buffer"in n&&!n.buffer&&i.createBindingBuffer(n),t||i.entries.bindGroupLayout.push({binding:i.entries.bindGroupLayout.length,...n.resourceLayout,visibility:n.visibility}),i.entries.bindGroup.push({binding:i.entries.bindGroup.length,resource:n.resource})}),t&&(i.entries.bindGroupLayout=[...this.entries.bindGroupLayout]),i.setBindGroupLayout(),i.setBindGroup(),i}destroy(){this.renderer.removeBindGroup(this),this.bufferBindings.forEach(e=>{"buffer"in e&&(this.renderer.removeBuffer(e.buffer),e.buffer?.destroy(),e.buffer=null),"resultBuffer"in e&&(this.renderer.removeBuffer(e.resultBuffer),e.resultBuffer?.destroy(),e.resultBuffer=null)}),this.bindings=[],this.bindGroupLayout=null,this.bindGroup=null,this.resetEntries()}}class Ie extends pe{constructor({label:e="Texture",name:t="texture",bindingType:s,visibility:i,texture:r,format:n="rgba8unorm",access:a="write",viewDimension:h="2d",multisampled:u=!1}){s=s??"texture",s==="storage"&&(i="compute"),super({label:e,name:t,bindingType:s,visibility:i}),this.options={...this.options,texture:r,format:n,access:a,viewDimension:h,multisampled:u},this.resource=r,this.setWGSLFragment()}get resourceLayout(){return Yt(this)}get resource(){return this.texture instanceof GPUTexture?this.texture.createView({label:this.options.label+" view",dimension:this.options.viewDimension}):this.texture instanceof GPUExternalTexture?this.texture:null}set resource(e){(e||this.texture)&&(this.shouldResetBindGroup=!0),this.texture=e}setBindingType(e){e!==this.bindingType&&(e&&(this.shouldResetBindGroupLayout=!0),this.bindingType=e,this.setWGSLFragment())}setWGSLFragment(){this.wgslGroupFragment=[`${qt(this)}`]}}const _=new f,Y=new f,B=new f;class O{constructor(e=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])){this.type="Mat4",this.elements=e}set(e,t,s,i,r,n,a,h,u,d,l,c,p,m,b,x){const g=this.elements;return g[0]=e,g[1]=t,g[2]=s,g[3]=i,g[4]=r,g[5]=n,g[6]=a,g[7]=h,g[8]=u,g[9]=d,g[10]=l,g[11]=c,g[12]=p,g[13]=m,g[14]=b,g[15]=x,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}setFromArray(e=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])){for(let t=0;tt.object3DIndex!==this.object3DIndex)),this._parent=e,this._parent?.children.push(this)}setTransforms(){this.transforms={origin:{model:new f},quaternion:new N,rotation:new f,position:{world:new f},scale:new f(1)},this.rotation.onChange(()=>this.applyRotation()),this.position.onChange(()=>this.applyPosition()),this.scale.onChange(()=>this.applyScale()),this.transformOrigin.onChange(()=>this.applyTransformOrigin())}get rotation(){return this.transforms.rotation}set rotation(e){this.transforms.rotation=e,this.applyRotation()}get quaternion(){return this.transforms.quaternion}set quaternion(e){this.transforms.quaternion=e}get position(){return this.transforms.position.world}set position(e){this.transforms.position.world=e}get scale(){return this.transforms.scale}set scale(e){this.transforms.scale=e,this.applyScale()}get transformOrigin(){return this.transforms.origin.model}set transformOrigin(e){this.transforms.origin.model=e}applyRotation(){this.quaternion.setFromVec3(this.rotation),this.shouldUpdateModelMatrix()}applyPosition(){this.shouldUpdateModelMatrix()}applyScale(){this.shouldUpdateModelMatrix()}applyTransformOrigin(){this.shouldUpdateModelMatrix()}setMatrices(){this.matrices={model:{matrix:new O,shouldUpdate:!1,onUpdate:()=>this.updateModelMatrix()},world:{matrix:new O,shouldUpdate:!1,onUpdate:()=>this.updateWorldMatrix()}}}get modelMatrix(){return this.matrices.model.matrix}set modelMatrix(e){this.matrices.model.matrix=e,this.shouldUpdateModelMatrix()}shouldUpdateModelMatrix(){this.matrices.model.shouldUpdate=!0,this.shouldUpdateWorldMatrix()}get worldMatrix(){return this.matrices.world.matrix}set worldMatrix(e){this.matrices.world.matrix=e,this.shouldUpdateWorldMatrix()}shouldUpdateWorldMatrix(){this.matrices.world.shouldUpdate=!0}lookAt(e=new f){const t=new O().lookAt(e,this.position);this.quaternion.setFromRotationMatrix(t),this.shouldUpdateModelMatrix()}updateModelMatrix(){this.modelMatrix=this.modelMatrix.composeFromOrigin(this.position,this.quaternion,this.scale,this.transformOrigin),this.shouldUpdateWorldMatrix()}updateWorldMatrix(){this.parent?this.worldMatrix.multiplyMatrices(this.parent.worldMatrix,this.modelMatrix):this.worldMatrix.copy(this.modelMatrix),this.children.forEach(e=>{e.shouldUpdateWorldMatrix()})}onAfterMatrixStackUpdate(){}updateMatrixStack(){if(this.parent&&this.parent.constructor.name==="Object3D"&&this.parent.updateMatrixStack(),!!Object.keys(this.matrices).find(t=>this.matrices[t].shouldUpdate)){for(const t in this.matrices)this.matrices[t].shouldUpdate&&(this.matrices[t].onUpdate(),this.matrices[t].shouldUpdate=!1);this.onAfterMatrixStackUpdate()}}}var Zt=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},$=(o,e,t)=>(Zt(o,e,"read from private field"),t?t.call(o):e.get(o)),xe=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},K,ee,be,we;const at={name:"texture",generateMips:!1,flipY:!1,format:"rgba8unorm",premultipliedAlpha:!0,placeholderColor:[0,0,0,255],useExternalTextures:!0,fromTexture:null,viewDimension:"2d",cache:!0};class te extends ye{constructor(e,t=at){super(),xe(this,K,new f(1)),xe(this,ee,new f(1)),xe(this,be,new f(1)),xe(this,we,new O),this._onSourceLoadedCallback=()=>{},this._onSourceUploadedCallback=()=>{},this.type="Texture",e=e&&e.renderer||e,z(e,t.label?t.label+" "+this.type:this.type),this.renderer=e,this.uuid=D();const s={...at,source:t.fromTexture?t.fromTexture.options.source:null,sourceType:t.fromTexture?t.fromTexture.options.sourceType:null};this.options={...s,...t},this.options.label=this.options.label??this.options.name,this.texture=null,this.externalTexture=null,this.source=null,this.size={width:1,height:1,depth:1},this.textureMatrix=new ne({label:this.options.label+": model matrix",name:this.options.name+"Matrix",useStruct:!1,struct:{matrix:{name:this.options.name+"Matrix",type:"mat4x4f",value:this.modelMatrix}}}),this.setBindings(),this._parentMesh=null,this.sourceLoaded=!1,this.sourceUploaded=!1,this.shouldUpdate=!1,this.renderer.addTexture(this),this.createTexture()}setBindings(){this.bindings=[new Ie({label:this.options.label+": texture",name:this.options.name,texture:this.options.sourceType==="externalVideo"?this.externalTexture:this.texture,bindingType:this.options.sourceType==="externalVideo"?"externalTexture":"texture",viewDimension:this.options.viewDimension}),this.textureMatrix]}get textureBinding(){return this.bindings[0]}get parentMesh(){return this._parentMesh}set parentMesh(e){this._parentMesh=e,this.resize()}get sourceLoaded(){return this._sourceLoaded}set sourceLoaded(e){e&&!this.sourceLoaded&&this._onSourceLoadedCallback&&this._onSourceLoadedCallback(),this._sourceLoaded=e}get sourceUploaded(){return this._sourceUploaded}set sourceUploaded(e){e&&!this.sourceUploaded&&this._onSourceUploadedCallback&&this._onSourceUploadedCallback(),this._sourceUploaded=e}setTransforms(){super.setTransforms(),this.transforms.quaternion.setAxisOrder("ZXY"),this.transforms.origin.model.set(.5,.5,0)}updateModelMatrix(){if(!this.parentMesh)return;const e=this.parentMesh.scale?this.parentMesh.scale:new f(1,1,1),t=this.parentMesh.boundingRect?this.parentMesh.boundingRect.width*e.x:this.size.width,s=this.parentMesh.boundingRect?this.parentMesh.boundingRect.height*e.y:this.size.height,i=t/s,r=this.size.width/this.size.height;t>s?($(this,K).set(i,1,1),$(this,ee).set(1/r,1,1)):($(this,K).set(1,1/i,1),$(this,ee).set(1,r,1));const n=i>r!=t>s?1:t>s?$(this,K).x*$(this,ee).x:$(this,ee).y*$(this,K).y;$(this,be).set(1/(n*this.scale.x),1/(n*this.scale.y),1),$(this,we).rotateFromQuaternion(this.quaternion),this.modelMatrix.identity().premultiplyTranslate(this.transformOrigin.clone().multiplyScalar(-1)).premultiplyScale($(this,be)).premultiplyScale($(this,K)).premultiply($(this,we)).premultiplyScale($(this,ee)).premultiplyTranslate(this.transformOrigin).translate(this.position)}onAfterMatrixStackUpdate(){this.textureMatrix.shouldUpdateBinding(this.options.name+"Matrix")}resize(){this.source&&this.source instanceof HTMLCanvasElement&&(this.source.width!==this.size.width||this.source.height!==this.size.height)&&(this.setSourceSize(),this.createTexture()),this.shouldUpdateModelMatrix()}getNumMipLevels(...e){const t=Math.max(...e);return 1+Math.log2(t)|0}uploadTexture(){this.renderer.uploadTexture(this),this.shouldUpdate=!1}uploadVideoTexture(){this.externalTexture=this.renderer.importExternalTexture(this.source),this.textureBinding.resource=this.externalTexture,this.textureBinding.setBindingType("externalTexture"),this.shouldUpdate=!1,this.sourceUploaded=!0}copy(e){if(this.options.sourceType==="externalVideo"&&e.options.sourceType!=="externalVideo"){U(`${this.options.label}: cannot copy a GPUTexture to a GPUExternalTexture`);return}else if(this.options.sourceType!=="externalVideo"&&e.options.sourceType==="externalVideo"){U(`${this.options.label}: cannot copy a GPUExternalTexture to a GPUTexture`);return}this.options.fromTexture=e,this.options.sourceType=e.options.sourceType,this.options.generateMips=e.options.generateMips,this.options.flipY=e.options.flipY,this.options.format=e.options.format,this.options.premultipliedAlpha=e.options.premultipliedAlpha,this.options.placeholderColor=e.options.placeholderColor,this.options.useExternalTextures=e.options.useExternalTextures,this.sourceLoaded=e.sourceLoaded,this.sourceUploaded=e.sourceUploaded,e.texture&&(e.sourceLoaded&&(this.size=e.size,this.source=e.source,this.resize()),e.sourceUploaded?(this.texture=e.texture,this.textureBinding.resource=this.texture):this.createTexture())}createTexture(){const e={label:this.options.label,format:this.options.format,size:[this.size.width,this.size.height,this.size.depth],dimensions:this.options.viewDimension==="1d"?"1d":this.options.viewDimension==="3d"?"3d":"2d",usage:this.source?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST};this.options.sourceType!=="externalVideo"&&(e.mipLevelCount=this.options.generateMips?this.getNumMipLevels(this.size.width,this.size.height):1,this.texture?.destroy(),this.texture=this.renderer.createTexture(e),this.textureBinding.resource=this.texture),this.shouldUpdate=!0}setSourceSize(){this.size={width:this.source.naturalWidth||this.source.width||this.source.videoWidth,height:this.source.naturalHeight||this.source.height||this.source.videoHeight,depth:1}}async loadImageBitmap(e){const s=await(await fetch(e)).blob();return await createImageBitmap(s,{colorSpaceConversion:"none"})}async loadImage(e){const t=typeof e=="string"?e:e.getAttribute("src");this.options.source=t,this.options.sourceType="image";const s=this.renderer.textures.find(i=>i.options.source===t);if(s&&s.texture&&s.sourceUploaded){this.copy(s);return}this.sourceLoaded=!1,this.sourceUploaded=!1,this.source=await this.loadImageBitmap(this.options.source),this.setSourceSize(),this.resize(),this.sourceLoaded=!0,this.createTexture()}onVideoFrameCallback(){this.videoFrameCallbackId&&(this.shouldUpdate=!0,this.source.requestVideoFrameCallback(this.onVideoFrameCallback.bind(this)))}onVideoLoaded(e){this.sourceLoaded||(this.source=e,this.setSourceSize(),this.resize(),this.options.useExternalTextures?(this.options.sourceType="externalVideo",this.texture?.destroy()):(this.options.sourceType="video",this.createTexture()),"requestVideoFrameCallback"in HTMLVideoElement.prototype&&(this.videoFrameCallbackId=this.source.requestVideoFrameCallback(this.onVideoFrameCallback.bind(this))),this.sourceLoaded=!0)}get isVideoSource(){return this.source&&(this.options.sourceType==="video"||this.options.sourceType==="externalVideo")}loadVideo(e){let t;typeof e=="string"?(t=document.createElement("video"),t.src=e):t=e,t.preload="auto",t.muted=!0,t.loop=!0,t.crossOrigin="anonymous",t.setAttribute("playsinline",""),this.options.source=t.src,this.sourceLoaded=!1,this.sourceUploaded=!1,t.readyState>=t.HAVE_ENOUGH_DATA?this.onVideoLoaded(t):t.addEventListener("canplaythrough",this.onVideoLoaded.bind(this,t),{once:!0}),isNaN(t.duration)&&t.load()}loadCanvas(e){this.options.source=e,this.options.sourceType="canvas",this.sourceLoaded=!1,this.sourceUploaded=!1,this.source=e,this.setSourceSize(),this.resize(),this.sourceLoaded=!0,this.createTexture()}onSourceLoaded(e){return e&&(this._onSourceLoadedCallback=e),this}onSourceUploaded(e){return e&&(this._onSourceUploadedCallback=e),this}render(){this.updateMatrixStack(),this.textureMatrix.update(),this.options.sourceType==="externalVideo"&&(this.shouldUpdate=!0),this.isVideoSource&&!this.videoFrameCallbackId&&this.source.readyState>=this.source.HAVE_CURRENT_DATA&&!this.source.paused&&(this.shouldUpdate=!0),this.shouldUpdate&&this.options.sourceType&&this.options.sourceType!=="externalVideo"&&this.uploadTexture()}destroy(){this.videoFrameCallbackId&&this.source.cancelVideoFrameCallback(this.videoFrameCallbackId),this.isVideoSource&&this.source.removeEventListener("canplaythrough",this.onVideoLoaded.bind(this,this.source),{once:!0}),this.renderer.removeTexture(this),this.texture?.destroy(),this.texture=null}}K=new WeakMap,ee=new WeakMap,be=new WeakMap,we=new WeakMap;class je extends ge{constructor(e,{label:t,index:s=0,bindings:i=[],uniforms:r,storages:n,textures:a=[],samplers:h=[]}={}){const u="TextureBindGroup";e=e&&e.renderer||e,z(e,u),super(e,{label:t,index:s,bindings:i,uniforms:r,storages:n}),this.options={...this.options,textures:[],samplers:[]},a.length&&a.forEach(d=>this.addTexture(d)),h.length&&h.forEach(d=>this.addSampler(d)),this.type=u}addTexture(e){this.textures.push(e),this.addBindings([...e.bindings])}get textures(){return this.options.textures}addSampler(e){this.samplers.push(e),this.addBindings([e.binding])}get samplers(){return this.options.samplers}get shouldCreateBindGroup(){return!this.bindGroup&&!!this.bindings.length&&!this.textures.find(e=>!(e.texture||e.externalTexture))&&!this.samplers.find(e=>!e.sampler)}updateTextures(){this.textures.forEach(e=>{e instanceof te&&(e.options.fromTexture&&e.options.fromTexture.sourceUploaded&&!e.sourceUploaded&&e.copy(e.options.fromTexture),e.shouldUpdate&&e.options.sourceType&&e.options.sourceType==="externalVideo"&&e.uploadVideoTexture())})}update(){this.updateTextures(),super.update()}destroy(){super.destroy(),this.options.textures=[],this.options.samplers=[]}}class ht extends pe{constructor({label:e="Sampler",name:t="sampler",bindingType:s,visibility:i,sampler:r,type:n="filtering"}){s=s??"sampler",super({label:e,name:t,bindingType:s,visibility:i}),this.options={...this.options,sampler:r,type:n},this.resource=r,this.setWGSLFragment()}get resourceLayout(){return{sampler:{type:this.options.type}}}get resource(){return this.sampler}set resource(e){e&&this.sampler&&(this.shouldResetBindGroup=!0),this.sampler=e}setWGSLFragment(){this.wgslGroupFragment=[`var ${this.name}: ${this.options.type==="comparison"?`${this.bindingType}_comparison`:this.bindingType};`]}}var ut=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},ve=(o,e,t)=>(ut(o,e,"read from private field"),t?t.call(o):e.get(o)),Pe=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},Me=(o,e,t,s)=>(ut(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),Te,Re,Ce,Be;class dt extends ye{constructor({fov:e=50,near:t=.1,far:s=150,width:i=1,height:r=1,pixelRatio:n=1,onMatricesChanged:a=()=>{}}={}){super(),Pe(this,Te,void 0),Pe(this,Re,void 0),Pe(this,Ce,void 0),Pe(this,Be,void 0),this.position.set(0,0,10),this.onMatricesChanged=a,this.size={width:1,height:1},this.setPerspective({fov:e,near:t,far:s,width:i,height:r,pixelRatio:n})}setMatrices(){super.setMatrices(),this.matrices={...this.matrices,view:{matrix:new O,shouldUpdate:!1,onUpdate:()=>{this.viewMatrix.copy(this.worldMatrix).invert()}},projection:{matrix:new O,shouldUpdate:!1,onUpdate:()=>this.updateProjectionMatrix()}}}get viewMatrix(){return this.matrices.view.matrix}set viewMatrix(e){this.matrices.view.matrix=e,this.matrices.view.shouldUpdate=!0}get projectionMatrix(){return this.matrices.projection.matrix}set projectionMatrix(e){this.matrices.projection.matrix=e,this.shouldUpdateProjectionMatrix()}shouldUpdateProjectionMatrix(){this.matrices.projection.shouldUpdate=!0}updateModelMatrix(){super.updateModelMatrix(),this.setScreenRatios(),this.matrices.view.shouldUpdate=!0}updateWorldMatrix(){super.updateWorldMatrix(),this.matrices.view.shouldUpdate=!0}get fov(){return ve(this,Te)}set fov(e){e=Math.max(1,Math.min(e??this.fov,179)),e!==this.fov&&(Me(this,Te,e),this.shouldUpdateProjectionMatrix()),this.setScreenRatios(),this.setCSSPerspective()}get near(){return ve(this,Re)}set near(e){e=Math.max(e??this.near,.01),e!==this.near&&(Me(this,Re,e),this.shouldUpdateProjectionMatrix())}get far(){return ve(this,Ce)}set far(e){e=Math.max(e??this.far,this.near+1),e!==this.far&&(Me(this,Ce,e),this.shouldUpdateProjectionMatrix())}get pixelRatio(){return ve(this,Be)}set pixelRatio(e){Me(this,Be,e??this.pixelRatio),this.setCSSPerspective()}setSize({width:e,height:t}){(e!==this.size.width||t!==this.size.height)&&this.shouldUpdateProjectionMatrix(),this.size.width=e,this.size.height=t,this.setScreenRatios(),this.setCSSPerspective()}setPerspective({fov:e=this.fov,near:t=this.near,far:s=this.far,width:i=this.size.width,height:r=this.size.height,pixelRatio:n=this.pixelRatio}={}){this.setSize({width:i,height:r}),this.pixelRatio=n,this.fov=e,this.near=t,this.far=s}onAfterMatrixStackUpdate(){this.onMatricesChanged()}setCSSPerspective(){this.CSSPerspective=Math.pow(Math.pow(this.size.width/(2*this.pixelRatio),2)+Math.pow(this.size.height/(2*this.pixelRatio),2),.5)/Math.tan(this.fov*.5*Math.PI/180)}setScreenRatios(e=0){const t=this.position.z;e{if(!e.has(o))throw TypeError("Cannot "+t)},Qt=(o,e,t)=>(ct(o,e,"read from private field"),t?t.call(o):e.get(o)),Jt=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},Kt=(o,e,t,s)=>(ct(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),Se;const pt={label:"RenderTexture",name:"renderTexture",usage:"texture",access:"write",fromTexture:null,viewDimension:"2d",sampleCount:1,qualityRatio:1};class J{constructor(e,t=pt){Jt(this,Se,!0),e=e&&e.renderer||e,z(e,t.label?t.label+" RenderTexture":"RenderTexture"),this.type="RenderTexture",this.renderer=e,this.uuid=D(),this.options={...pt,...t},this.options.format||(this.options.format=this.renderer.options.preferredFormat),this.size=this.options.fixedSize?{width:this.options.fixedSize.width*this.options.qualityRatio,height:this.options.fixedSize.height*this.options.qualityRatio,depth:this.options.fixedSize.depth??this.options.viewDimension.indexOf("cube")!==-1?6:1}:{width:Math.floor(this.renderer.displayBoundingRect.width*this.options.qualityRatio),height:Math.floor(this.renderer.displayBoundingRect.height*this.options.qualityRatio),depth:this.options.viewDimension.indexOf("cube")!==-1?6:1},this.options.fixedSize&&Kt(this,Se,!1),this.setBindings(),this.renderer.addRenderTexture(this),this.createTexture()}copy(e){this.options.fromTexture=e,this.createTexture()}copyGPUTexture(e){this.size={width:e.width,height:e.height,depth:e.depthOrArrayLayers},this.texture=e,this.textureBinding.resource=this.texture}createTexture(){if(this.options.fromTexture){this.options.format=this.options.fromTexture.options.format,this.copyGPUTexture(this.options.fromTexture.texture);return}this.texture?.destroy(),this.texture=this.renderer.createTexture({label:this.options.label,format:this.options.format,size:[this.size.width,this.size.height,this.size.depth??1],dimensions:this.options.viewDimension,sampleCount:this.options.sampleCount,usage:this.options.usage!=="storage"?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST}),this.textureBinding.resource=this.texture}setBindings(){this.bindings=[new Ie({label:this.options.label+": "+this.options.name+" render texture",name:this.options.name,texture:this.texture,bindingType:this.options.usage,format:this.options.format,viewDimension:this.options.viewDimension,multisampled:this.options.sampleCount>1})]}get textureBinding(){return this.bindings[0]}resize(e=null){Qt(this,Se)&&(e||(e={width:Math.floor(this.renderer.displayBoundingRect.width*this.options.qualityRatio),height:Math.floor(this.renderer.displayBoundingRect.height*this.options.qualityRatio),depth:1}),!(e.width===this.size.width&&e.height===this.size.height&&e.depth===this.size.depth)&&(this.size=e,this.createTexture()))}destroy(){this.renderer.removeRenderTexture(this),this.options.fromTexture||this.texture?.destroy(),this.texture=null}}Se=new WeakMap;class We{constructor(e,t){this.type="Material",e=e&&e.renderer||e,z(e,this.type),this.renderer=e,this.uuid=D();const{shaders:s,label:i,useAsyncPipeline:r,uniforms:n,storages:a,bindings:h,bindGroups:u,samplers:d,textures:l,renderTextures:c}=t;this.options={shaders:s,label:i,useAsyncPipeline:r===void 0?!0:r,...n!==void 0&&{uniforms:n},...a!==void 0&&{storages:a},...h!==void 0&&{bindings:h},...u!==void 0&&{bindGroups:u},...d!==void 0&&{samplers:d},...l!==void 0&&{textures:l},...c!==void 0&&{renderTextures:c}},this.bindGroups=[],this.texturesBindGroups=[],this.clonedBindGroups=[],this.setBindGroups(),this.setTextures(),this.setSamplers()}compileMaterial(){const e=this.texturesBindGroup.bindings.length?1:0;this.bindGroups.length>=this.inputsBindGroups.length+e||this.createBindGroups()}get ready(){return!!(this.renderer.ready&&this.pipelineEntry&&this.pipelineEntry.pipeline&&this.pipelineEntry.ready)}loseContext(){this.textures.forEach(e=>{e.texture=null,e.sourceUploaded=!1}),this.renderTextures.forEach(e=>{e.texture=null}),[...this.bindGroups,...this.clonedBindGroups,...this.inputsBindGroups].forEach(e=>e.loseContext()),this.pipelineEntry.pipeline=null}restoreContext(){this.samplers.forEach(e=>{e.createSampler(),e.binding.resource=e.sampler}),this.textures.forEach(e=>{e.createTexture(),e.resize()}),this.renderTextures.forEach(e=>{e.resize(e.size)}),[...this.bindGroups,...this.clonedBindGroups,...this.inputsBindGroups].forEach(e=>{e.shouldCreateBindGroup&&e.createBindGroup(),e.bufferBindings.forEach(t=>t.shouldUpdate=!0)})}getShaderCode(e="full"){return this.pipelineEntry?(e=(()=>{switch(e){case"vertex":case"fragment":case"compute":case"full":return e;default:return"full"}})(),this.pipelineEntry.shaders[e].code):""}getAddedShaderCode(e="vertex"){return this.pipelineEntry?(e=(()=>{switch(e){case"vertex":case"fragment":case"compute":return e;default:return"vertex"}})(),this.pipelineEntry.shaders[e].head):""}setBindGroups(){if(this.uniforms={},this.storages={},this.inputsBindGroups=[],this.inputsBindings=[],this.options.uniforms||this.options.storages||this.options.bindings){const e=new ge(this.renderer,{label:this.options.label+": Bindings bind group",uniforms:this.options.uniforms,storages:this.options.storages,bindings:this.options.bindings});this.processBindGroupBindings(e),this.inputsBindGroups.push(e)}this.options.bindGroups?.forEach(e=>{this.processBindGroupBindings(e),this.inputsBindGroups.push(e)})}get texturesBindGroup(){return this.texturesBindGroups[0]}processBindGroupBindings(e){e.bindings.forEach(t=>{t.bindingType==="uniform"&&(this.uniforms={...this.uniforms,[t.name]:t.inputs}),t.bindingType==="storage"&&(this.storages={...this.storages,[t.name]:t.inputs}),this.inputsBindings.push(t)})}createBindGroups(){this.texturesBindGroup.shouldCreateBindGroup&&(this.texturesBindGroup.setIndex(this.bindGroups.length),this.texturesBindGroup.createBindGroup(),this.bindGroups.push(this.texturesBindGroup)),this.inputsBindGroups.forEach(e=>{e.shouldCreateBindGroup&&(e.setIndex(this.bindGroups.length),e.createBindGroup(),this.bindGroups.push(e))}),this.options.bindGroups?.forEach(e=>{!e.shouldCreateBindGroup&&!this.bindGroups.find(t=>t.uuid===e.uuid)&&(e.setIndex(this.bindGroups.length),this.bindGroups.push(e)),e instanceof je&&!this.texturesBindGroups.find(t=>t.uuid===e.uuid)&&(this.texturesBindGroups.push(e),e.textures.forEach(t=>{t instanceof te&&!this.textures.find(s=>s.uuid===t.uuid)?this.textures.push(t):t instanceof J&&!this.renderTextures.find(s=>s.uuid===t.uuid)&&this.renderTextures.push(t)}))})}cloneBindGroup({bindGroup:e,bindings:t=[],keepLayout:s=!0}){if(!e)return null;const i=e.clone({bindings:t,keepLayout:s});return this.clonedBindGroups.push(i),i}getBindGroupByBindingName(e=""){return(this.ready?this.bindGroups:this.inputsBindGroups).find(t=>t.bindings.find(s=>s.name===e))}destroyBindGroup(e){const t=this.renderer.getObjectsByBindGroup(e);(!t||!t.find(i=>i.material.uuid!==this.uuid))&&e.destroy()}destroyBindGroups(){this.bindGroups.forEach(e=>this.destroyBindGroup(e)),this.clonedBindGroups.forEach(e=>this.destroyBindGroup(e)),this.texturesBindGroups.forEach(e=>this.destroyBindGroup(e)),this.texturesBindGroups=[],this.inputsBindGroups=[],this.bindGroups=[],this.clonedBindGroups=[]}updateBindGroups(){this.bindGroups.forEach(e=>{e.update(),e.needsPipelineFlush&&this.pipelineEntry.ready&&(this.pipelineEntry.flushPipelineEntry(this.bindGroups),e.needsPipelineFlush=!1)})}getBindingByName(e=""){return this.inputsBindings.find(t=>t.name===e)}getBufferBindingByName(e=""){return this.inputsBindings.find(t=>t.name===e&&"buffer"in t)}shouldUpdateInputsBindings(e,t){if(!e)return;const s=this.getBindingByName(e);s&&(t?s.shouldUpdateBinding(t):Object.keys(s.inputs).forEach(i=>s.shouldUpdateBinding(i)))}setTextures(){this.textures=[],this.renderTextures=[],this.texturesBindGroups.push(new je(this.renderer,{label:this.options.label+": Textures bind group"})),this.options.textures?.forEach(e=>{this.addTexture(e)}),this.options.renderTextures?.forEach(e=>{this.addTexture(e)})}addTexture(e){e instanceof te?this.textures.push(e):e instanceof J&&this.renderTextures.push(e),(this.options.shaders.vertex&&this.options.shaders.vertex.code.indexOf(e.options.name)!==-1||this.options.shaders.fragment&&this.options.shaders.fragment.code.indexOf(e.options.name)!==-1||this.options.shaders.compute&&this.options.shaders.compute.code.indexOf(e.options.name)!==-1)&&this.texturesBindGroup.addTexture(e)}destroyTexture(e){if(e.options.cache)return;const t=this.renderer.getObjectsByTexture(e);(!t||!t.some(i=>i.material.uuid!==this.uuid))&&e.destroy()}destroyTextures(){this.textures?.forEach(e=>this.destroyTexture(e)),this.renderTextures?.forEach(e=>this.destroyTexture(e)),this.textures=[],this.renderTextures=[]}setSamplers(){if(this.samplers=[],this.options.samplers?.forEach(t=>{this.addSampler(t)}),!this.samplers.find(t=>t.name==="defaultSampler")){const t=new lt(this.renderer,{name:"defaultSampler"});this.addSampler(t)}}addSampler(e){this.samplers.push(e),(this.options.shaders.vertex&&this.options.shaders.vertex.code.indexOf(e.name)!==-1||this.options.shaders.fragment&&this.options.shaders.fragment.code.indexOf(e.name)!==-1||this.options.shaders.compute&&this.options.shaders.compute.code.indexOf(e.name)!==-1)&&this.texturesBindGroup.addSampler(e)}async getBufferResult(e){await e.mapAsync(GPUMapMode.READ);const t=new Float32Array(e.getMappedRange().slice(0));return e.unmap(),t}async getBufferBindingResultByBindingName(e=""){const t=this.getBufferBindingByName(e);if(t&&"buffer"in t){const s=this.renderer.copyBufferToBuffer({srcBuffer:t.buffer});return await this.getBufferResult(s)}else return new Float32Array(0)}async getBufferElementResultByNames({bindingName:e,bufferElementName:t}){const s=await this.getBufferBindingResultByBindingName(e);if(!t||s.length)return s;{const i=this.getBufferBindingByName(e);return i?i.extractBufferElementDataFromBufferResult({result:s,bufferElementName:t}):s}}onBeforeRender(){this.compileMaterial(),this.textures.forEach(e=>{e.render()}),this.updateBindGroups()}setPipeline(e){this.renderer.pipelineManager.setCurrentPipeline(e,this.pipelineEntry)}render(e){this.ready&&(this.setPipeline(e),this.bindGroups.forEach(t=>{e.setBindGroup(t.index,t.bindGroup)}))}destroy(){this.destroyBindGroups(),this.destroyTextures()}}class ft extends We{constructor(e,t){e=e&&e.renderer||e;const s="ComputeMaterial";z(e,s),super(e,t),this.type=s,this.renderer=e;let{shaders:i,dispatchSize:r}=t;(!i||!i.compute)&&(i={compute:{code:"",entryPoint:"main"}}),i.compute.code||(i.compute.code="@compute @workgroup_size(1) fn main(){}"),i.compute.entryPoint||(i.compute.entryPoint="main"),this.options={...this.options,shaders:i,...t.dispatchSize!==void 0&&{dispatchSize:t.dispatchSize}},r||(r=1),Array.isArray(r)?(r[0]=Math.ceil(r[0]??1),r[1]=Math.ceil(r[1]??1),r[2]=Math.ceil(r[2]??1)):isNaN(r)||(r=[Math.ceil(r),1,1]),this.dispatchSize=r,this.pipelineEntry=this.renderer.pipelineManager.createComputePipeline({renderer:this.renderer,label:this.options.label+" compute pipeline",shaders:this.options.shaders,useAsync:this.options.useAsyncPipeline})}setPipelineEntryProperties(){this.pipelineEntry.setPipelineEntryProperties({bindGroups:this.bindGroups})}async compilePipelineEntry(){await this.pipelineEntry.compilePipelineEntry()}async compileMaterial(){super.compileMaterial(),this.pipelineEntry&&this.pipelineEntry.canCompile&&(this.setPipelineEntryProperties(),await this.compilePipelineEntry())}getShaderCode(e="compute"){return super.getShaderCode(e)}getAddedShaderCode(e="compute"){return super.getAddedShaderCode(e)}useCustomRender(e){e&&(this._useCustomRenderCallback=e)}render(e){this.ready&&(this.setPipeline(e),this._useCustomRenderCallback!==void 0?this._useCustomRenderCallback(e):(this.bindGroups.forEach(t=>{e.setBindGroup(t.index,t.bindGroup)}),e.dispatchWorkgroups(this.dispatchSize[0],this.dispatchSize[1],this.dispatchSize[2])))}copyBufferToResult(e){this.bindGroups.forEach(t=>{t.bufferBindings.forEach(s=>{s.shouldCopyResult&&s.resultBuffer.mapState==="unmapped"&&e.copyBufferToBuffer(s.buffer,0,s.resultBuffer,0,s.resultBuffer.size)})})}async getComputeResult({bindingName:e="",bufferElementName:t=""}){const s=this.getBufferBindingByName(e);if(s&&"resultBuffer"in s&&s.resultBuffer.mapState==="unmapped"){const i=await this.getBufferResult(s.resultBuffer);return t?s.extractBufferElementDataFromBufferResult({result:i,bufferElementName:t}):i}else return new Float32Array(0)}}var mt=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},gt=(o,e,t)=>(mt(o,e,"read from private field"),t?t.call(o):e.get(o)),es=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},ts=(o,e,t,s)=>(mt(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),ue;let ss=0;class is{constructor(e,t={}){es(this,ue,!0),this._onReadyCallback=()=>{},this._onBeforeRenderCallback=()=>{},this._onRenderCallback=()=>{},this._onAfterRenderCallback=()=>{},this._onAfterResizeCallback=()=>{};const s="ComputePass";e=e&&e.renderer||e,z(e,t.label?`${t.label} ${s}`:s),t.label=t.label??"ComputePass "+e.computePasses?.length,this.renderer=e,this.type=s,this.uuid=D(),Object.defineProperty(this,"index",{value:ss++});const{label:i,shaders:r,renderOrder:n,uniforms:a,storages:h,bindGroups:u,samplers:d,textures:l,renderTextures:c,autoRender:p,useAsyncPipeline:m,texturesOptions:b,dispatchSize:x}=t;this.options={label:i,shaders:r,...p!==void 0&&{autoRender:p},...n!==void 0&&{renderOrder:n},...x!==void 0&&{dispatchSize:x},useAsyncPipeline:m===void 0?!0:m,texturesOptions:b},this.renderOrder=n??0,p!==void 0&&ts(this,ue,p),this.userData={},this.ready=!1,this.setComputeMaterial({label:this.options.label,shaders:this.options.shaders,uniforms:a,storages:h,bindGroups:u,samplers:d,textures:l,renderTextures:c,useAsyncPipeline:m,dispatchSize:x}),this.addToScene()}get ready(){return this._ready}set ready(e){e&&this._onReadyCallback&&this._onReadyCallback(),this._ready=e}addToScene(){this.renderer.computePasses.push(this),gt(this,ue)&&this.renderer.scene.addComputePass(this)}removeFromScene(){gt(this,ue)&&this.renderer.scene.removeComputePass(this),this.renderer.computePasses=this.renderer.computePasses.filter(e=>e.uuid!==this.uuid)}setComputeMaterial(e){this.material=new ft(this.renderer,e)}loseContext(){this.material.loseContext()}restoreContext(){this.material.restoreContext()}get textures(){return this.material?.textures||[]}get renderTextures(){return this.material?.renderTextures||[]}createTexture(e){e.name||(e.name="texture"+this.textures.length),e.label||(e.label=this.options.label+" "+e.name);const t=new te(this.renderer,{...e,...this.options.texturesOptions});return this.addTexture(t),t}addTexture(e){this.material.addTexture(e)}createRenderTexture(e){e.name||(e.name="renderTexture"+this.renderTextures.length);const t=new J(this.renderer,e);return this.addRenderTexture(t),t}addRenderTexture(e){this.material.addTexture(e)}get uniforms(){return this.material?.uniforms}get storages(){return this.material?.storages}resize(){this._onAfterResizeCallback&&this._onAfterResizeCallback()}onReady(e){return e&&(this._onReadyCallback=e),this}onBeforeRender(e){return e&&(this._onBeforeRenderCallback=e),this}onRender(e){return e&&(this._onRenderCallback=e),this}onAfterRender(e){return e&&(this._onAfterRenderCallback=e),this}useCustomRender(e){return this.material.useCustomRender(e),this}onAfterResize(e){return e&&(this._onAfterResizeCallback=e),this}onBeforeRenderPass(){this.renderer.ready&&(this.material&&this.material.ready&&!this.ready&&(this.ready=!0),this._onBeforeRenderCallback&&this._onBeforeRenderCallback(),this.material.onBeforeRender())}onRenderPass(e){this.material.ready&&(this._onRenderCallback&&this._onRenderCallback(),this.material.render(e))}onAfterRenderPass(){this._onAfterRenderCallback&&this._onAfterRenderCallback()}render(e){this.onBeforeRenderPass(),this.renderer.ready&&(!this.renderer.production&&e.pushDebugGroup(this.options.label),this.onRenderPass(e),!this.renderer.production&&e.popDebugGroup(),this.onAfterRenderPass())}copyBufferToResult(e){this.material?.copyBufferToResult(e)}async getComputeResult({bindingName:e,bufferElementName:t}){return await this.material?.getComputeResult({bindingName:e,bufferElementName:t})}remove(){this.removeFromScene(),this.destroy()}destroy(){this.material?.destroy()}}ue=new WeakMap;const W=[new f,new f,new f,new f,new f,new f,new f,new f];class oe{constructor(e=new f(1/0),t=new f(-1/0)){this.min=e,this.max=t}set(e=new f(1/0),t=new f(-1/0)){return this.min.copy(e),this.max.copy(t),this}clone(){return new oe().set(this.min,this.max)}getCenter(){return this.max.clone().add(this.min).multiplyScalar(.5)}getSize(){return this.max.clone().sub(this.min)}applyMat4(e=new O){const t=[];this.min.z===this.max.z?(t[0]=W[0].set(this.min.x,this.min.y,this.min.z).applyMat4(e),t[1]=W[2].set(this.min.x,this.max.y,this.min.z).applyMat4(e),t[2]=W[4].set(this.max.x,this.min.y,this.min.z).applyMat4(e),t[3]=W[6].set(this.max.x,this.max.y,this.min.z).applyMat4(e)):(t[0]=W[0].set(this.min.x,this.min.y,this.min.z).applyMat4(e),t[1]=W[1].set(this.min.x,this.min.y,this.max.z).applyMat4(e),t[2]=W[2].set(this.min.x,this.max.y,this.min.z).applyMat4(e),t[3]=W[3].set(this.min.x,this.max.y,this.max.z).applyMat4(e),t[4]=W[4].set(this.max.x,this.min.y,this.min.z).applyMat4(e),t[5]=W[5].set(this.max.x,this.min.y,this.max.z).applyMat4(e),t[6]=W[6].set(this.max.x,this.max.y,this.min.z).applyMat4(e),t[7]=W[7].set(this.max.x,this.max.y,this.max.z).applyMat4(e));const s=new oe;for(let i=0,r=t.length;i{},onLeaveView:n=()=>{}}){this.boundingBox=e,this.modelViewProjectionMatrix=t,this.containerBoundingRect=s,this.DOMFrustumMargins={...yt,...i},this.projectedBoundingRect={top:0,right:0,bottom:0,left:0,width:0,height:0,x:0,y:0},this.onReEnterView=r,this.onLeaveView=n,this.isIntersecting=!1,this.shouldUpdate=!1}setContainerBoundingRect(e){this.containerBoundingRect=e}get DOMFrustumBoundingRect(){return{top:this.projectedBoundingRect.top-this.DOMFrustumMargins.top,right:this.projectedBoundingRect.right+this.DOMFrustumMargins.right,bottom:this.projectedBoundingRect.bottom+this.DOMFrustumMargins.bottom,left:this.projectedBoundingRect.left-this.DOMFrustumMargins.left}}computeProjectedToDocumentCoords(){const e=this.boundingBox.applyMat4(this.modelViewProjectionMatrix);e.min.x=(e.min.x+1)*.5,e.max.x=(e.max.x+1)*.5,e.min.y=1-(e.min.y+1)*.5,e.max.y=1-(e.max.y+1)*.5;const{width:t,height:s,top:i,left:r}=this.containerBoundingRect;this.projectedBoundingRect={left:e.min.x*t+r,x:e.min.x*t+r,top:e.max.y*s+i,y:e.max.y*s+i,right:e.max.x*t+r,bottom:e.min.y*s+i,width:e.max.x*t+r-(e.min.x*t+r),height:e.min.y*s+i-(e.max.y*s+i)},this.intersectsContainer()}intersectsContainer(){Math.round(this.DOMFrustumBoundingRect.right)<=this.containerBoundingRect.left||Math.round(this.DOMFrustumBoundingRect.left)>=this.containerBoundingRect.left+this.containerBoundingRect.width||Math.round(this.DOMFrustumBoundingRect.bottom)<=this.containerBoundingRect.top||Math.round(this.DOMFrustumBoundingRect.top)>=this.containerBoundingRect.top+this.containerBoundingRect.height?(this.isIntersecting&&this.onLeaveView(),this.isIntersecting=!1):(this.isIntersecting||this.onReEnterView(),this.isIntersecting=!0)}}var rs=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},ns=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},os=(o,e,t)=>(rs(o,e,"access private method"),t),qe,bt;class Ne{constructor({verticesOrder:e="ccw",topology:t="triangle-list",instancesCount:s=1,vertexBuffers:i=[]}={}){ns(this,qe),this.verticesCount=0,this.verticesOrder=e,this.topology=t,this.instancesCount=s,this.boundingBox=new oe,this.type="Geometry",this.vertexBuffers=[],this.addVertexBuffer({name:"attributes"}),this.options={verticesOrder:e,instancesCount:s,vertexBuffers:i,topology:t},i.forEach(r=>{this.addVertexBuffer({stepMode:r.stepMode??"vertex",name:r.name,attributes:r.attributes})})}get shouldCompute(){return this.vertexBuffers.length&&!this.vertexBuffers[0].array}get ready(){return!this.shouldCompute&&!this.vertexBuffers.find(e=>!e.buffer)}addVertexBuffer({stepMode:e="vertex",name:t,attributes:s=[]}={}){const i={name:t??"attributes"+this.vertexBuffers.length,stepMode:e,arrayStride:0,bufferLength:0,attributes:[],buffer:null};return s?.forEach(r=>{this.setAttribute({vertexBuffer:i,...r})}),this.vertexBuffers.push(i),i}getVertexBufferByName(e=""){return this.vertexBuffers.find(t=>t.name===e)}setAttribute({vertexBuffer:e=this.vertexBuffers[0],name:t,type:s="vec3f",bufferFormat:i="float32x3",size:r=3,array:n=new Float32Array(this.verticesCount*r),verticesStride:a=1}){const h=e.attributes,u=h.length;t||(t="geometryAttribute"+u),t==="position"&&(s!=="vec3f"||i!=="float32x3"||r!==3)&&(U(`Geometry 'position' attribute must have this exact properties set: +};`;const i=fe(this);this.wgslGroupFragment=[`${i} ${this.name}: ${e};`]}}else this.wgslStructFragment="",this.wgslGroupFragment=this.bufferElements.map(t=>`${fe(this)} ${t.name}: ${t.type};`)}shouldUpdateBinding(e=""){const t=Object.keys(this.inputs).find(s=>this.inputs[s].name===e);t&&(this.inputs[t].shouldUpdate=!0)}update(){Object.keys(this.inputs).forEach(e=>{const t=this.inputs[e],s=this.bufferElements.find(i=>i.key===e);t.shouldUpdate&&s&&(t.onBeforeUpdate&&t.onBeforeUpdate(),s.update(t.value),this.shouldUpdate=!0,t.shouldUpdate=!1)})}extractBufferElementDataFromBufferResult({result:e,bufferElementName:t}){const s=this.bufferElements.find(i=>i.name===t);return s?s.extractDataFromBufferResult(e):e}}class Ve extends ne{constructor({label:e="Work",name:t="work",bindingType:s,useStruct:i=!0,struct:r={},visibility:n,access:a="read_write",shouldCopyResult:h=!1}){s="storage",n="compute",super({label:e,name:t,bindingType:s,useStruct:i,struct:r,visibility:n,access:a}),this.options={...this.options,shouldCopyResult:h},this.shouldCopyResult=h,this.resultBuffer=null}}class ge{constructor(e,{label:t="BindGroup",index:s=0,bindings:i=[],uniforms:r,storages:n}={}){this.type="BindGroup",e=e&&e.renderer||e,z(e,this.type),this.renderer=e,this.options={label:t,index:s,bindings:i,...r&&{uniforms:r},...n&&{storages:n}},this.index=s,this.uuid=D(),this.bindings=[],i.length&&this.addBindings(i),(this.options.uniforms||this.options.storages)&&this.setInputBindings(),this.resetEntries(),this.bindGroupLayout=null,this.bindGroup=null,this.needsPipelineFlush=!1,this.renderer.addBindGroup(this)}setIndex(e){this.index=e}addBindings(e=[]){this.bindings=[...this.bindings,...e]}addBinding(e){this.bindings.push(e)}createInputBindings(e="uniform",t={}){return[...Object.keys(t).map(s=>{const i=t[s],r={label:Ue(i.label||s),name:s,bindingType:e,useStruct:!0,visibility:i.access==="read_write"?"compute":i.visibility,access:i.access??"read",struct:i.struct,...i.shouldCopyResult!==void 0&&{shouldCopyResult:i.shouldCopyResult}},n=r.access==="read_write"?Ve:ne;return i.useStruct!==!1?new n(r):Object.keys(i.struct).map(a=>(r.label=Ue(i.label?i.label+a:s+a),r.name=s+a,r.useStruct=!1,r.struct={[a]:i.struct[a]},new n(r)))})].flat()}setInputBindings(){this.addBindings([...this.createInputBindings("uniform",this.options.uniforms),...this.createInputBindings("storage",this.options.storages)])}get shouldCreateBindGroup(){return!this.bindGroup&&!!this.bindings.length}resetEntries(){this.entries={bindGroupLayout:[],bindGroup:[]}}createBindGroup(){this.fillEntries(),this.setBindGroupLayout(),this.setBindGroup()}resetBindGroup(){this.entries.bindGroup=[],this.bindings.forEach(e=>{this.entries.bindGroup.push({binding:this.entries.bindGroup.length,resource:e.resource})}),this.setBindGroup()}resetBindGroupLayout(){this.entries.bindGroupLayout=[],this.bindings.forEach(e=>{this.entries.bindGroupLayout.push({binding:this.entries.bindGroupLayout.length,...e.resourceLayout,visibility:e.visibility})}),this.setBindGroupLayout()}loseContext(){this.resetEntries(),this.bufferBindings.forEach(e=>{e.buffer=null,"resultBuffer"in e&&(e.resultBuffer=null)}),this.bindGroup=null,this.bindGroupLayout=null,this.needsPipelineFlush=!0}get bufferBindings(){return this.bindings.filter(e=>e instanceof ne||e instanceof Ve)}createBindingBuffer(e){e.buffer=this.renderer.createBuffer({label:this.options.label+": "+e.bindingType+" buffer from: "+e.label,size:e.arrayBuffer.byteLength,usage:e.bindingType==="uniform"?GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC|GPUBufferUsage.VERTEX:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC|GPUBufferUsage.VERTEX}),"resultBuffer"in e&&(e.resultBuffer=this.renderer.createBuffer({label:this.options.label+": Result buffer from: "+e.label,size:e.arrayBuffer.byteLength,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}))}fillEntries(){this.bindings.forEach(e=>{e.visibility||(e.visibility=GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT|GPUShaderStage.COMPUTE),"buffer"in e&&!e.buffer&&this.createBindingBuffer(e),this.entries.bindGroupLayout.push({binding:this.entries.bindGroupLayout.length,...e.resourceLayout,visibility:e.visibility}),this.entries.bindGroup.push({binding:this.entries.bindGroup.length,resource:e.resource})})}getBindingByName(e=""){return this.bindings.find(t=>t.name===e)}setBindGroupLayout(){this.bindGroupLayout=this.renderer.createBindGroupLayout({label:this.options.label+" layout",entries:this.entries.bindGroupLayout})}setBindGroup(){this.bindGroup=this.renderer.createBindGroup({label:this.options.label,layout:this.bindGroupLayout,entries:this.entries.bindGroup})}updateBufferBindings(){this.bufferBindings.forEach((e,t)=>{e.update(),e.shouldUpdate&&(!e.useStruct&&e.bufferElements.length>1?this.renderer.queueWriteBuffer(e.buffer,0,e.bufferElements[t].view):this.renderer.queueWriteBuffer(e.buffer,0,e.arrayBuffer)),e.shouldUpdate=!1})}update(){this.updateBufferBindings();const e=this.bindings.some(s=>s.shouldResetBindGroup),t=this.bindings.some(s=>s.shouldResetBindGroupLayout);(e||t)&&this.renderer.onAfterCommandEncoderSubmission.add(()=>{this.bindings.forEach(s=>{s.shouldResetBindGroup=!1,s.shouldResetBindGroupLayout=!1})},{once:!0}),t&&(this.resetBindGroupLayout(),this.needsPipelineFlush=!0),e&&this.resetBindGroup()}clone({bindings:e=[],keepLayout:t=!1}={}){const s={...this.options};s.label+=" (copy)";const i=new this.constructor(this.renderer,{label:s.label});return i.setIndex(this.index),i.options=s,(e.length?e:this.bindings).forEach((n,a)=>{i.addBinding(n),"buffer"in n&&!n.buffer&&i.createBindingBuffer(n),t||i.entries.bindGroupLayout.push({binding:i.entries.bindGroupLayout.length,...n.resourceLayout,visibility:n.visibility}),i.entries.bindGroup.push({binding:i.entries.bindGroup.length,resource:n.resource})}),t&&(i.entries.bindGroupLayout=[...this.entries.bindGroupLayout]),i.setBindGroupLayout(),i.setBindGroup(),i}destroy(){this.renderer.removeBindGroup(this),this.bufferBindings.forEach(e=>{"buffer"in e&&(this.renderer.removeBuffer(e.buffer),e.buffer?.destroy(),e.buffer=null),"resultBuffer"in e&&(this.renderer.removeBuffer(e.resultBuffer),e.resultBuffer?.destroy(),e.resultBuffer=null)}),this.bindings=[],this.bindGroupLayout=null,this.bindGroup=null,this.resetEntries()}}class Ie extends pe{constructor({label:e="Texture",name:t="texture",bindingType:s,visibility:i,texture:r,format:n="rgba8unorm",access:a="write",viewDimension:h="2d",multisampled:u=!1}){s=s??"texture",s==="storage"&&(i="compute"),super({label:e,name:t,bindingType:s,visibility:i}),this.options={...this.options,texture:r,format:n,access:a,viewDimension:h,multisampled:u},this.resource=r,this.setWGSLFragment()}get resourceLayout(){return Yt(this)}get resource(){return this.texture instanceof GPUTexture?this.texture.createView({label:this.options.label+" view",dimension:this.options.viewDimension}):this.texture instanceof GPUExternalTexture?this.texture:null}set resource(e){(e||this.texture)&&(this.shouldResetBindGroup=!0),this.texture=e}setBindingType(e){e!==this.bindingType&&(e&&(this.shouldResetBindGroupLayout=!0),this.bindingType=e,this.setWGSLFragment())}setWGSLFragment(){this.wgslGroupFragment=[`${qt(this)}`]}}const _=new f,Y=new f,B=new f;class O{constructor(e=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])){this.type="Mat4",this.elements=e}set(e,t,s,i,r,n,a,h,u,d,l,c,p,m,x,b){const g=this.elements;return g[0]=e,g[1]=t,g[2]=s,g[3]=i,g[4]=r,g[5]=n,g[6]=a,g[7]=h,g[8]=u,g[9]=d,g[10]=l,g[11]=c,g[12]=p,g[13]=m,g[14]=x,g[15]=b,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}setFromArray(e=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])){for(let t=0;tt.object3DIndex!==this.object3DIndex)),this._parent=e,this._parent?.children.push(this)}setTransforms(){this.transforms={origin:{model:new f},quaternion:new N,rotation:new f,position:{world:new f},scale:new f(1)},this.rotation.onChange(()=>this.applyRotation()),this.position.onChange(()=>this.applyPosition()),this.scale.onChange(()=>this.applyScale()),this.transformOrigin.onChange(()=>this.applyTransformOrigin())}get rotation(){return this.transforms.rotation}set rotation(e){this.transforms.rotation=e,this.applyRotation()}get quaternion(){return this.transforms.quaternion}set quaternion(e){this.transforms.quaternion=e}get position(){return this.transforms.position.world}set position(e){this.transforms.position.world=e}get scale(){return this.transforms.scale}set scale(e){this.transforms.scale=e,this.applyScale()}get transformOrigin(){return this.transforms.origin.model}set transformOrigin(e){this.transforms.origin.model=e}applyRotation(){this.quaternion.setFromVec3(this.rotation),this.shouldUpdateModelMatrix()}applyPosition(){this.shouldUpdateModelMatrix()}applyScale(){this.shouldUpdateModelMatrix()}applyTransformOrigin(){this.shouldUpdateModelMatrix()}setMatrices(){this.matrices={model:{matrix:new O,shouldUpdate:!1,onUpdate:()=>this.updateModelMatrix()},world:{matrix:new O,shouldUpdate:!1,onUpdate:()=>this.updateWorldMatrix()}}}get modelMatrix(){return this.matrices.model.matrix}set modelMatrix(e){this.matrices.model.matrix=e,this.shouldUpdateModelMatrix()}shouldUpdateModelMatrix(){this.matrices.model.shouldUpdate=!0,this.shouldUpdateWorldMatrix()}get worldMatrix(){return this.matrices.world.matrix}set worldMatrix(e){this.matrices.world.matrix=e,this.shouldUpdateWorldMatrix()}shouldUpdateWorldMatrix(){this.matrices.world.shouldUpdate=!0}lookAt(e=new f){const t=new O().lookAt(e,this.position);this.quaternion.setFromRotationMatrix(t),this.shouldUpdateModelMatrix()}updateModelMatrix(){this.modelMatrix=this.modelMatrix.composeFromOrigin(this.position,this.quaternion,this.scale,this.transformOrigin),this.shouldUpdateWorldMatrix()}updateWorldMatrix(){this.parent?this.worldMatrix.multiplyMatrices(this.parent.worldMatrix,this.modelMatrix):this.worldMatrix.copy(this.modelMatrix),this.children.forEach(e=>{e.shouldUpdateWorldMatrix()})}onAfterMatrixStackUpdate(){}updateMatrixStack(){if(this.parent&&this.parent.constructor.name==="Object3D"&&this.parent.updateMatrixStack(),!!Object.keys(this.matrices).find(t=>this.matrices[t].shouldUpdate)){for(const t in this.matrices)this.matrices[t].shouldUpdate&&(this.matrices[t].onUpdate(),this.matrices[t].shouldUpdate=!1);this.onAfterMatrixStackUpdate()}}}var Zt=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},$=(o,e,t)=>(Zt(o,e,"read from private field"),t?t.call(o):e.get(o)),xe=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},K,ee,be,we;const at={name:"texture",generateMips:!1,flipY:!1,format:"rgba8unorm",premultipliedAlpha:!0,placeholderColor:[0,0,0,255],useExternalTextures:!0,fromTexture:null,viewDimension:"2d",cache:!0};class te extends ye{constructor(e,t=at){super(),xe(this,K,new f(1)),xe(this,ee,new f(1)),xe(this,be,new f(1)),xe(this,we,new O),this._onSourceLoadedCallback=()=>{},this._onSourceUploadedCallback=()=>{},this.type="Texture",e=e&&e.renderer||e,z(e,t.label?t.label+" "+this.type:this.type),this.renderer=e,this.uuid=D();const s={...at,source:t.fromTexture?t.fromTexture.options.source:null,sourceType:t.fromTexture?t.fromTexture.options.sourceType:null};this.options={...s,...t},this.options.label=this.options.label??this.options.name,this.texture=null,this.externalTexture=null,this.source=null,this.size={width:1,height:1,depth:1},this.textureMatrix=new ne({label:this.options.label+": model matrix",name:this.options.name+"Matrix",useStruct:!1,struct:{matrix:{name:this.options.name+"Matrix",type:"mat4x4f",value:this.modelMatrix}}}),this.setBindings(),this._parentMesh=null,this.sourceLoaded=!1,this.sourceUploaded=!1,this.shouldUpdate=!1,this.renderer.addTexture(this),this.createTexture()}setBindings(){this.bindings=[new Ie({label:this.options.label+": texture",name:this.options.name,texture:this.options.sourceType==="externalVideo"?this.externalTexture:this.texture,bindingType:this.options.sourceType==="externalVideo"?"externalTexture":"texture",viewDimension:this.options.viewDimension}),this.textureMatrix]}get textureBinding(){return this.bindings[0]}get parentMesh(){return this._parentMesh}set parentMesh(e){this._parentMesh=e,this.resize()}get sourceLoaded(){return this._sourceLoaded}set sourceLoaded(e){e&&!this.sourceLoaded&&this._onSourceLoadedCallback&&this._onSourceLoadedCallback(),this._sourceLoaded=e}get sourceUploaded(){return this._sourceUploaded}set sourceUploaded(e){e&&!this.sourceUploaded&&this._onSourceUploadedCallback&&this._onSourceUploadedCallback(),this._sourceUploaded=e}setTransforms(){super.setTransforms(),this.transforms.quaternion.setAxisOrder("ZXY"),this.transforms.origin.model.set(.5,.5,0)}updateModelMatrix(){if(!this.parentMesh)return;const e=this.parentMesh.scale?this.parentMesh.scale:new f(1,1,1),t=this.parentMesh.boundingRect?this.parentMesh.boundingRect.width*e.x:this.size.width,s=this.parentMesh.boundingRect?this.parentMesh.boundingRect.height*e.y:this.size.height,i=t/s,r=this.size.width/this.size.height;t>s?($(this,K).set(i,1,1),$(this,ee).set(1/r,1,1)):($(this,K).set(1,1/i,1),$(this,ee).set(1,r,1));const n=i>r!=t>s?1:t>s?$(this,K).x*$(this,ee).x:$(this,ee).y*$(this,K).y;$(this,be).set(1/(n*this.scale.x),1/(n*this.scale.y),1),$(this,we).rotateFromQuaternion(this.quaternion),this.modelMatrix.identity().premultiplyTranslate(this.transformOrigin.clone().multiplyScalar(-1)).premultiplyScale($(this,be)).premultiplyScale($(this,K)).premultiply($(this,we)).premultiplyScale($(this,ee)).premultiplyTranslate(this.transformOrigin).translate(this.position)}onAfterMatrixStackUpdate(){this.textureMatrix.shouldUpdateBinding(this.options.name+"Matrix")}resize(){this.source&&this.source instanceof HTMLCanvasElement&&(this.source.width!==this.size.width||this.source.height!==this.size.height)&&(this.setSourceSize(),this.createTexture()),this.shouldUpdateModelMatrix()}getNumMipLevels(...e){const t=Math.max(...e);return 1+Math.log2(t)|0}uploadTexture(){this.renderer.uploadTexture(this),this.shouldUpdate=!1}uploadVideoTexture(){this.externalTexture=this.renderer.importExternalTexture(this.source),this.textureBinding.resource=this.externalTexture,this.textureBinding.setBindingType("externalTexture"),this.shouldUpdate=!1,this.sourceUploaded=!0}copy(e){if(this.options.sourceType==="externalVideo"&&e.options.sourceType!=="externalVideo"){U(`${this.options.label}: cannot copy a GPUTexture to a GPUExternalTexture`);return}else if(this.options.sourceType!=="externalVideo"&&e.options.sourceType==="externalVideo"){U(`${this.options.label}: cannot copy a GPUExternalTexture to a GPUTexture`);return}this.options.fromTexture=e,this.options.sourceType=e.options.sourceType,this.options.generateMips=e.options.generateMips,this.options.flipY=e.options.flipY,this.options.format=e.options.format,this.options.premultipliedAlpha=e.options.premultipliedAlpha,this.options.placeholderColor=e.options.placeholderColor,this.options.useExternalTextures=e.options.useExternalTextures,this.sourceLoaded=e.sourceLoaded,this.sourceUploaded=e.sourceUploaded,e.texture&&(e.sourceLoaded&&(this.size=e.size,this.source=e.source,this.resize()),e.sourceUploaded?(this.texture=e.texture,this.textureBinding.resource=this.texture):this.createTexture())}createTexture(){const e={label:this.options.label,format:this.options.format,size:[this.size.width,this.size.height,this.size.depth],dimensions:this.options.viewDimension==="1d"?"1d":this.options.viewDimension==="3d"?"3d":"2d",usage:this.source?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST};this.options.sourceType!=="externalVideo"&&(e.mipLevelCount=this.options.generateMips?this.getNumMipLevels(this.size.width,this.size.height):1,this.texture?.destroy(),this.texture=this.renderer.createTexture(e),this.textureBinding.resource=this.texture),this.shouldUpdate=!0}setSourceSize(){this.size={width:this.source.naturalWidth||this.source.width||this.source.videoWidth,height:this.source.naturalHeight||this.source.height||this.source.videoHeight,depth:1}}async loadImageBitmap(e){const s=await(await fetch(e)).blob();return await createImageBitmap(s,{colorSpaceConversion:"none"})}async loadImage(e){const t=typeof e=="string"?e:e.getAttribute("src");this.options.source=t,this.options.sourceType="image";const s=this.renderer.textures.find(i=>i.options.source===t);if(s&&s.texture&&s.sourceUploaded){this.copy(s);return}this.sourceLoaded=!1,this.sourceUploaded=!1,this.source=await this.loadImageBitmap(this.options.source),this.setSourceSize(),this.resize(),this.sourceLoaded=!0,this.createTexture()}onVideoFrameCallback(){this.videoFrameCallbackId&&(this.shouldUpdate=!0,this.source.requestVideoFrameCallback(this.onVideoFrameCallback.bind(this)))}onVideoLoaded(e){this.sourceLoaded||(this.source=e,this.setSourceSize(),this.resize(),this.options.useExternalTextures?(this.options.sourceType="externalVideo",this.texture?.destroy()):(this.options.sourceType="video",this.createTexture()),"requestVideoFrameCallback"in HTMLVideoElement.prototype&&(this.videoFrameCallbackId=this.source.requestVideoFrameCallback(this.onVideoFrameCallback.bind(this))),this.sourceLoaded=!0)}get isVideoSource(){return this.source&&(this.options.sourceType==="video"||this.options.sourceType==="externalVideo")}loadVideo(e){let t;typeof e=="string"?(t=document.createElement("video"),t.src=e):t=e,t.preload="auto",t.muted=!0,t.loop=!0,t.crossOrigin="anonymous",t.setAttribute("playsinline",""),this.options.source=t.src,this.sourceLoaded=!1,this.sourceUploaded=!1,t.readyState>=t.HAVE_ENOUGH_DATA?this.onVideoLoaded(t):t.addEventListener("canplaythrough",this.onVideoLoaded.bind(this,t),{once:!0}),isNaN(t.duration)&&t.load()}loadCanvas(e){this.options.source=e,this.options.sourceType="canvas",this.sourceLoaded=!1,this.sourceUploaded=!1,this.source=e,this.setSourceSize(),this.resize(),this.sourceLoaded=!0,this.createTexture()}onSourceLoaded(e){return e&&(this._onSourceLoadedCallback=e),this}onSourceUploaded(e){return e&&(this._onSourceUploadedCallback=e),this}render(){this.updateMatrixStack(),this.textureMatrix.update(),this.options.sourceType==="externalVideo"&&(this.shouldUpdate=!0),this.isVideoSource&&!this.videoFrameCallbackId&&this.source.readyState>=this.source.HAVE_CURRENT_DATA&&!this.source.paused&&(this.shouldUpdate=!0),this.shouldUpdate&&this.options.sourceType&&this.options.sourceType!=="externalVideo"&&this.uploadTexture()}destroy(){this.videoFrameCallbackId&&this.source.cancelVideoFrameCallback(this.videoFrameCallbackId),this.isVideoSource&&this.source.removeEventListener("canplaythrough",this.onVideoLoaded.bind(this,this.source),{once:!0}),this.renderer.removeTexture(this),this.texture?.destroy(),this.texture=null}}K=new WeakMap,ee=new WeakMap,be=new WeakMap,we=new WeakMap;class je extends ge{constructor(e,{label:t,index:s=0,bindings:i=[],uniforms:r,storages:n,textures:a=[],samplers:h=[]}={}){const u="TextureBindGroup";e=e&&e.renderer||e,z(e,u),super(e,{label:t,index:s,bindings:i,uniforms:r,storages:n}),this.options={...this.options,textures:[],samplers:[]},a.length&&a.forEach(d=>this.addTexture(d)),h.length&&h.forEach(d=>this.addSampler(d)),this.type=u}addTexture(e){this.textures.push(e),this.addBindings([...e.bindings])}get textures(){return this.options.textures}addSampler(e){this.samplers.push(e),this.addBindings([e.binding])}get samplers(){return this.options.samplers}get shouldCreateBindGroup(){return!this.bindGroup&&!!this.bindings.length&&!this.textures.find(e=>!(e.texture||e.externalTexture))&&!this.samplers.find(e=>!e.sampler)}updateTextures(){this.textures.forEach(e=>{e instanceof te&&(e.options.fromTexture&&e.options.fromTexture.sourceUploaded&&!e.sourceUploaded&&e.copy(e.options.fromTexture),e.shouldUpdate&&e.options.sourceType&&e.options.sourceType==="externalVideo"&&e.uploadVideoTexture())})}update(){this.updateTextures(),super.update()}destroy(){super.destroy(),this.options.textures=[],this.options.samplers=[]}}class ht extends pe{constructor({label:e="Sampler",name:t="sampler",bindingType:s,visibility:i,sampler:r,type:n="filtering"}){s=s??"sampler",super({label:e,name:t,bindingType:s,visibility:i}),this.options={...this.options,sampler:r,type:n},this.resource=r,this.setWGSLFragment()}get resourceLayout(){return{sampler:{type:this.options.type}}}get resource(){return this.sampler}set resource(e){e&&this.sampler&&(this.shouldResetBindGroup=!0),this.sampler=e}setWGSLFragment(){this.wgslGroupFragment=[`var ${this.name}: ${this.options.type==="comparison"?`${this.bindingType}_comparison`:this.bindingType};`]}}var ut=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},ve=(o,e,t)=>(ut(o,e,"read from private field"),t?t.call(o):e.get(o)),Pe=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},Me=(o,e,t,s)=>(ut(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),Re,Te,Ce,Be;class dt extends ye{constructor({fov:e=50,near:t=.1,far:s=150,width:i=1,height:r=1,pixelRatio:n=1,onMatricesChanged:a=()=>{}}={}){super(),Pe(this,Re,void 0),Pe(this,Te,void 0),Pe(this,Ce,void 0),Pe(this,Be,void 0),this.position.set(0,0,10),this.onMatricesChanged=a,this.size={width:1,height:1},this.setPerspective({fov:e,near:t,far:s,width:i,height:r,pixelRatio:n})}setMatrices(){super.setMatrices(),this.matrices={...this.matrices,view:{matrix:new O,shouldUpdate:!1,onUpdate:()=>{this.viewMatrix.copy(this.worldMatrix).invert()}},projection:{matrix:new O,shouldUpdate:!1,onUpdate:()=>this.updateProjectionMatrix()}}}get viewMatrix(){return this.matrices.view.matrix}set viewMatrix(e){this.matrices.view.matrix=e,this.matrices.view.shouldUpdate=!0}get projectionMatrix(){return this.matrices.projection.matrix}set projectionMatrix(e){this.matrices.projection.matrix=e,this.shouldUpdateProjectionMatrix()}shouldUpdateProjectionMatrix(){this.matrices.projection.shouldUpdate=!0}updateModelMatrix(){super.updateModelMatrix(),this.setScreenRatios(),this.matrices.view.shouldUpdate=!0}updateWorldMatrix(){super.updateWorldMatrix(),this.matrices.view.shouldUpdate=!0}get fov(){return ve(this,Re)}set fov(e){e=Math.max(1,Math.min(e??this.fov,179)),e!==this.fov&&(Me(this,Re,e),this.shouldUpdateProjectionMatrix()),this.setScreenRatios(),this.setCSSPerspective()}get near(){return ve(this,Te)}set near(e){e=Math.max(e??this.near,.01),e!==this.near&&(Me(this,Te,e),this.shouldUpdateProjectionMatrix())}get far(){return ve(this,Ce)}set far(e){e=Math.max(e??this.far,this.near+1),e!==this.far&&(Me(this,Ce,e),this.shouldUpdateProjectionMatrix())}get pixelRatio(){return ve(this,Be)}set pixelRatio(e){Me(this,Be,e??this.pixelRatio),this.setCSSPerspective()}setSize({width:e,height:t}){(e!==this.size.width||t!==this.size.height)&&this.shouldUpdateProjectionMatrix(),this.size.width=e,this.size.height=t,this.setScreenRatios(),this.setCSSPerspective()}setPerspective({fov:e=this.fov,near:t=this.near,far:s=this.far,width:i=this.size.width,height:r=this.size.height,pixelRatio:n=this.pixelRatio}={}){this.setSize({width:i,height:r}),this.pixelRatio=n,this.fov=e,this.near=t,this.far=s}onAfterMatrixStackUpdate(){this.onMatricesChanged()}setCSSPerspective(){this.CSSPerspective=Math.pow(Math.pow(this.size.width/(2*this.pixelRatio),2)+Math.pow(this.size.height/(2*this.pixelRatio),2),.5)/Math.tan(this.fov*.5*Math.PI/180)}setScreenRatios(e=0){const t=this.position.z;e{if(!e.has(o))throw TypeError("Cannot "+t)},Qt=(o,e,t)=>(ct(o,e,"read from private field"),t?t.call(o):e.get(o)),Jt=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},Kt=(o,e,t,s)=>(ct(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),Se;const pt={label:"RenderTexture",name:"renderTexture",usage:"texture",access:"write",fromTexture:null,viewDimension:"2d",sampleCount:1,qualityRatio:1};class J{constructor(e,t=pt){Jt(this,Se,!0),e=e&&e.renderer||e,z(e,t.label?t.label+" RenderTexture":"RenderTexture"),this.type="RenderTexture",this.renderer=e,this.uuid=D(),this.options={...pt,...t},this.options.format||(this.options.format=this.renderer.options.preferredFormat),this.size=this.options.fixedSize?{width:this.options.fixedSize.width*this.options.qualityRatio,height:this.options.fixedSize.height*this.options.qualityRatio,depth:this.options.fixedSize.depth??this.options.viewDimension.indexOf("cube")!==-1?6:1}:{width:Math.floor(this.renderer.displayBoundingRect.width*this.options.qualityRatio),height:Math.floor(this.renderer.displayBoundingRect.height*this.options.qualityRatio),depth:this.options.viewDimension.indexOf("cube")!==-1?6:1},this.options.fixedSize&&Kt(this,Se,!1),this.setBindings(),this.renderer.addRenderTexture(this),this.createTexture()}copy(e){this.options.fromTexture=e,this.createTexture()}copyGPUTexture(e){this.size={width:e.width,height:e.height,depth:e.depthOrArrayLayers},this.texture=e,this.textureBinding.resource=this.texture}createTexture(){if(this.options.fromTexture){this.options.format=this.options.fromTexture.options.format,this.copyGPUTexture(this.options.fromTexture.texture);return}this.texture?.destroy(),this.texture=this.renderer.createTexture({label:this.options.label,format:this.options.format,size:[this.size.width,this.size.height,this.size.depth??1],dimensions:this.options.viewDimension,sampleCount:this.options.sampleCount,usage:this.options.usage!=="storage"?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST}),this.textureBinding.resource=this.texture}setBindings(){this.bindings=[new Ie({label:this.options.label+": "+this.options.name+" render texture",name:this.options.name,texture:this.texture,bindingType:this.options.usage,format:this.options.format,viewDimension:this.options.viewDimension,multisampled:this.options.sampleCount>1})]}get textureBinding(){return this.bindings[0]}resize(e=null){Qt(this,Se)&&(e||(e={width:Math.floor(this.renderer.displayBoundingRect.width*this.options.qualityRatio),height:Math.floor(this.renderer.displayBoundingRect.height*this.options.qualityRatio),depth:1}),!(e.width===this.size.width&&e.height===this.size.height&&e.depth===this.size.depth)&&(this.size=e,this.createTexture()))}destroy(){this.renderer.removeRenderTexture(this),this.options.fromTexture||this.texture?.destroy(),this.texture=null}}Se=new WeakMap;class We{constructor(e,t){this.type="Material",e=e&&e.renderer||e,z(e,this.type),this.renderer=e,this.uuid=D();const{shaders:s,label:i,useAsyncPipeline:r,uniforms:n,storages:a,bindings:h,bindGroups:u,samplers:d,textures:l,renderTextures:c}=t;this.options={shaders:s,label:i,useAsyncPipeline:r===void 0?!0:r,...n!==void 0&&{uniforms:n},...a!==void 0&&{storages:a},...h!==void 0&&{bindings:h},...u!==void 0&&{bindGroups:u},...d!==void 0&&{samplers:d},...l!==void 0&&{textures:l},...c!==void 0&&{renderTextures:c}},this.bindGroups=[],this.texturesBindGroups=[],this.clonedBindGroups=[],this.setBindGroups(),this.setTextures(),this.setSamplers()}compileMaterial(){const e=this.texturesBindGroup.bindings.length?1:0;this.bindGroups.length>=this.inputsBindGroups.length+e||this.createBindGroups()}get ready(){return!!(this.renderer.ready&&this.pipelineEntry&&this.pipelineEntry.pipeline&&this.pipelineEntry.ready)}loseContext(){this.textures.forEach(e=>{e.texture=null,e.sourceUploaded=!1}),this.renderTextures.forEach(e=>{e.texture=null}),[...this.bindGroups,...this.clonedBindGroups,...this.inputsBindGroups].forEach(e=>e.loseContext()),this.pipelineEntry.pipeline=null}restoreContext(){this.samplers.forEach(e=>{e.createSampler(),e.binding.resource=e.sampler}),this.textures.forEach(e=>{e.createTexture(),e.resize()}),this.renderTextures.forEach(e=>{e.resize(e.size)}),[...this.bindGroups,...this.clonedBindGroups,...this.inputsBindGroups].forEach(e=>{e.shouldCreateBindGroup&&e.createBindGroup(),e.bufferBindings.forEach(t=>t.shouldUpdate=!0)})}getShaderCode(e="full"){return this.pipelineEntry?(e=(()=>{switch(e){case"vertex":case"fragment":case"compute":case"full":return e;default:return"full"}})(),this.pipelineEntry.shaders[e].code):""}getAddedShaderCode(e="vertex"){return this.pipelineEntry?(e=(()=>{switch(e){case"vertex":case"fragment":case"compute":return e;default:return"vertex"}})(),this.pipelineEntry.shaders[e].head):""}setBindGroups(){if(this.uniforms={},this.storages={},this.inputsBindGroups=[],this.inputsBindings=[],this.options.uniforms||this.options.storages||this.options.bindings){const e=new ge(this.renderer,{label:this.options.label+": Bindings bind group",uniforms:this.options.uniforms,storages:this.options.storages,bindings:this.options.bindings});this.processBindGroupBindings(e),this.inputsBindGroups.push(e)}this.options.bindGroups?.forEach(e=>{this.processBindGroupBindings(e),this.inputsBindGroups.push(e)})}get texturesBindGroup(){return this.texturesBindGroups[0]}processBindGroupBindings(e){e.bindings.forEach(t=>{t.bindingType==="uniform"&&(this.uniforms={...this.uniforms,[t.name]:t.inputs}),t.bindingType==="storage"&&(this.storages={...this.storages,[t.name]:t.inputs}),this.inputsBindings.push(t)})}createBindGroups(){this.texturesBindGroup.shouldCreateBindGroup&&(this.texturesBindGroup.setIndex(this.bindGroups.length),this.texturesBindGroup.createBindGroup(),this.bindGroups.push(this.texturesBindGroup)),this.inputsBindGroups.forEach(e=>{e.shouldCreateBindGroup&&(e.setIndex(this.bindGroups.length),e.createBindGroup(),this.bindGroups.push(e))}),this.options.bindGroups?.forEach(e=>{!e.shouldCreateBindGroup&&!this.bindGroups.find(t=>t.uuid===e.uuid)&&(e.setIndex(this.bindGroups.length),this.bindGroups.push(e)),e instanceof je&&!this.texturesBindGroups.find(t=>t.uuid===e.uuid)&&(this.texturesBindGroups.push(e),e.textures.forEach(t=>{t instanceof te&&!this.textures.find(s=>s.uuid===t.uuid)?this.textures.push(t):t instanceof J&&!this.renderTextures.find(s=>s.uuid===t.uuid)&&this.renderTextures.push(t)}))})}cloneBindGroup({bindGroup:e,bindings:t=[],keepLayout:s=!0}){if(!e)return null;const i=e.clone({bindings:t,keepLayout:s});return this.clonedBindGroups.push(i),i}getBindGroupByBindingName(e=""){return(this.ready?this.bindGroups:this.inputsBindGroups).find(t=>t.bindings.find(s=>s.name===e))}destroyBindGroup(e){const t=this.renderer.getObjectsByBindGroup(e);(!t||!t.find(i=>i.material.uuid!==this.uuid))&&e.destroy()}destroyBindGroups(){this.bindGroups.forEach(e=>this.destroyBindGroup(e)),this.clonedBindGroups.forEach(e=>this.destroyBindGroup(e)),this.texturesBindGroups.forEach(e=>this.destroyBindGroup(e)),this.texturesBindGroups=[],this.inputsBindGroups=[],this.bindGroups=[],this.clonedBindGroups=[]}updateBindGroups(){this.bindGroups.forEach(e=>{e.update(),e.needsPipelineFlush&&this.pipelineEntry.ready&&(this.pipelineEntry.flushPipelineEntry(this.bindGroups),e.needsPipelineFlush=!1)})}getBindingByName(e=""){return this.inputsBindings.find(t=>t.name===e)}getBufferBindingByName(e=""){return this.inputsBindings.find(t=>t.name===e&&"buffer"in t)}shouldUpdateInputsBindings(e,t){if(!e)return;const s=this.getBindingByName(e);s&&(t?s.shouldUpdateBinding(t):Object.keys(s.inputs).forEach(i=>s.shouldUpdateBinding(i)))}setTextures(){this.textures=[],this.renderTextures=[],this.texturesBindGroups.push(new je(this.renderer,{label:this.options.label+": Textures bind group"})),this.options.textures?.forEach(e=>{this.addTexture(e)}),this.options.renderTextures?.forEach(e=>{this.addTexture(e)})}addTexture(e){e instanceof te?this.textures.push(e):e instanceof J&&this.renderTextures.push(e),(this.options.shaders.vertex&&this.options.shaders.vertex.code.indexOf(e.options.name)!==-1||this.options.shaders.fragment&&this.options.shaders.fragment.code.indexOf(e.options.name)!==-1||this.options.shaders.compute&&this.options.shaders.compute.code.indexOf(e.options.name)!==-1)&&this.texturesBindGroup.addTexture(e)}destroyTexture(e){if(e.options.cache)return;const t=this.renderer.getObjectsByTexture(e);(!t||!t.some(i=>i.material.uuid!==this.uuid))&&e.destroy()}destroyTextures(){this.textures?.forEach(e=>this.destroyTexture(e)),this.renderTextures?.forEach(e=>this.destroyTexture(e)),this.textures=[],this.renderTextures=[]}setSamplers(){if(this.samplers=[],this.options.samplers?.forEach(t=>{this.addSampler(t)}),!this.samplers.find(t=>t.name==="defaultSampler")){const t=new lt(this.renderer,{name:"defaultSampler"});this.addSampler(t)}}addSampler(e){this.samplers.push(e),(this.options.shaders.vertex&&this.options.shaders.vertex.code.indexOf(e.name)!==-1||this.options.shaders.fragment&&this.options.shaders.fragment.code.indexOf(e.name)!==-1||this.options.shaders.compute&&this.options.shaders.compute.code.indexOf(e.name)!==-1)&&this.texturesBindGroup.addSampler(e)}async getBufferResult(e){await e.mapAsync(GPUMapMode.READ);const t=new Float32Array(e.getMappedRange().slice(0));return e.unmap(),t}async getBufferBindingResultByBindingName(e=""){const t=this.getBufferBindingByName(e);if(t&&"buffer"in t){const s=this.renderer.copyBufferToBuffer({srcBuffer:t.buffer});return await this.getBufferResult(s)}else return new Float32Array(0)}async getBufferElementResultByNames({bindingName:e,bufferElementName:t}){const s=await this.getBufferBindingResultByBindingName(e);if(!t||s.length)return s;{const i=this.getBufferBindingByName(e);return i?i.extractBufferElementDataFromBufferResult({result:s,bufferElementName:t}):s}}onBeforeRender(){this.compileMaterial(),this.textures.forEach(e=>{e.render()}),this.updateBindGroups()}setPipeline(e){this.renderer.pipelineManager.setCurrentPipeline(e,this.pipelineEntry)}render(e){this.ready&&(this.setPipeline(e),this.bindGroups.forEach(t=>{e.setBindGroup(t.index,t.bindGroup)}))}destroy(){this.destroyBindGroups(),this.destroyTextures()}}class ft extends We{constructor(e,t){e=e&&e.renderer||e;const s="ComputeMaterial";z(e,s),super(e,t),this.type=s,this.renderer=e;let{shaders:i,dispatchSize:r}=t;(!i||!i.compute)&&(i={compute:{code:"",entryPoint:"main"}}),i.compute.code||(i.compute.code="@compute @workgroup_size(1) fn main(){}"),i.compute.entryPoint||(i.compute.entryPoint="main"),this.options={...this.options,shaders:i,...t.dispatchSize!==void 0&&{dispatchSize:t.dispatchSize}},r||(r=1),Array.isArray(r)?(r[0]=Math.ceil(r[0]??1),r[1]=Math.ceil(r[1]??1),r[2]=Math.ceil(r[2]??1)):isNaN(r)||(r=[Math.ceil(r),1,1]),this.dispatchSize=r,this.pipelineEntry=this.renderer.pipelineManager.createComputePipeline({renderer:this.renderer,label:this.options.label+" compute pipeline",shaders:this.options.shaders,useAsync:this.options.useAsyncPipeline})}setPipelineEntryProperties(){this.pipelineEntry.setPipelineEntryProperties({bindGroups:this.bindGroups})}async compilePipelineEntry(){await this.pipelineEntry.compilePipelineEntry()}async compileMaterial(){super.compileMaterial(),this.pipelineEntry&&this.pipelineEntry.canCompile&&(this.setPipelineEntryProperties(),await this.compilePipelineEntry())}getShaderCode(e="compute"){return super.getShaderCode(e)}getAddedShaderCode(e="compute"){return super.getAddedShaderCode(e)}useCustomRender(e){e&&(this._useCustomRenderCallback=e)}render(e){this.ready&&(this.setPipeline(e),this._useCustomRenderCallback!==void 0?this._useCustomRenderCallback(e):(this.bindGroups.forEach(t=>{e.setBindGroup(t.index,t.bindGroup)}),e.dispatchWorkgroups(this.dispatchSize[0],this.dispatchSize[1],this.dispatchSize[2])))}copyBufferToResult(e){this.bindGroups.forEach(t=>{t.bufferBindings.forEach(s=>{s.shouldCopyResult&&s.resultBuffer.mapState==="unmapped"&&e.copyBufferToBuffer(s.buffer,0,s.resultBuffer,0,s.resultBuffer.size)})})}async getComputeResult({bindingName:e="",bufferElementName:t=""}){const s=this.getBufferBindingByName(e);if(s&&"resultBuffer"in s&&s.resultBuffer.mapState==="unmapped"){const i=await this.getBufferResult(s.resultBuffer);return t?s.extractBufferElementDataFromBufferResult({result:i,bufferElementName:t}):i}else return new Float32Array(0)}}var mt=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},gt=(o,e,t)=>(mt(o,e,"read from private field"),t?t.call(o):e.get(o)),es=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},ts=(o,e,t,s)=>(mt(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),ue;let ss=0;class is{constructor(e,t={}){es(this,ue,!0),this._onReadyCallback=()=>{},this._onBeforeRenderCallback=()=>{},this._onRenderCallback=()=>{},this._onAfterRenderCallback=()=>{},this._onAfterResizeCallback=()=>{};const s="ComputePass";e=e&&e.renderer||e,z(e,t.label?`${t.label} ${s}`:s),t.label=t.label??"ComputePass "+e.computePasses?.length,this.renderer=e,this.type=s,this.uuid=D(),Object.defineProperty(this,"index",{value:ss++});const{label:i,shaders:r,renderOrder:n,uniforms:a,storages:h,bindGroups:u,samplers:d,textures:l,renderTextures:c,autoRender:p,useAsyncPipeline:m,texturesOptions:x,dispatchSize:b}=t;this.options={label:i,shaders:r,...p!==void 0&&{autoRender:p},...n!==void 0&&{renderOrder:n},...b!==void 0&&{dispatchSize:b},useAsyncPipeline:m===void 0?!0:m,texturesOptions:x},this.renderOrder=n??0,p!==void 0&&ts(this,ue,p),this.userData={},this.ready=!1,this.setComputeMaterial({label:this.options.label,shaders:this.options.shaders,uniforms:a,storages:h,bindGroups:u,samplers:d,textures:l,renderTextures:c,useAsyncPipeline:m,dispatchSize:b}),this.addToScene()}get ready(){return this._ready}set ready(e){e&&this._onReadyCallback&&this._onReadyCallback(),this._ready=e}addToScene(){this.renderer.computePasses.push(this),gt(this,ue)&&this.renderer.scene.addComputePass(this)}removeFromScene(){gt(this,ue)&&this.renderer.scene.removeComputePass(this),this.renderer.computePasses=this.renderer.computePasses.filter(e=>e.uuid!==this.uuid)}setComputeMaterial(e){this.material=new ft(this.renderer,e)}loseContext(){this.material.loseContext()}restoreContext(){this.material.restoreContext()}get textures(){return this.material?.textures||[]}get renderTextures(){return this.material?.renderTextures||[]}createTexture(e){e.name||(e.name="texture"+this.textures.length),e.label||(e.label=this.options.label+" "+e.name);const t=new te(this.renderer,{...e,...this.options.texturesOptions});return this.addTexture(t),t}addTexture(e){this.material.addTexture(e)}createRenderTexture(e){e.name||(e.name="renderTexture"+this.renderTextures.length);const t=new J(this.renderer,e);return this.addRenderTexture(t),t}addRenderTexture(e){this.material.addTexture(e)}get uniforms(){return this.material?.uniforms}get storages(){return this.material?.storages}resize(){this._onAfterResizeCallback&&this._onAfterResizeCallback()}onReady(e){return e&&(this._onReadyCallback=e),this}onBeforeRender(e){return e&&(this._onBeforeRenderCallback=e),this}onRender(e){return e&&(this._onRenderCallback=e),this}onAfterRender(e){return e&&(this._onAfterRenderCallback=e),this}useCustomRender(e){return this.material.useCustomRender(e),this}onAfterResize(e){return e&&(this._onAfterResizeCallback=e),this}onBeforeRenderPass(){this.renderer.ready&&(this.material&&this.material.ready&&!this.ready&&(this.ready=!0),this._onBeforeRenderCallback&&this._onBeforeRenderCallback(),this.material.onBeforeRender())}onRenderPass(e){this.material.ready&&(this._onRenderCallback&&this._onRenderCallback(),this.material.render(e))}onAfterRenderPass(){this._onAfterRenderCallback&&this._onAfterRenderCallback()}render(e){this.onBeforeRenderPass(),this.renderer.ready&&(!this.renderer.production&&e.pushDebugGroup(this.options.label),this.onRenderPass(e),!this.renderer.production&&e.popDebugGroup(),this.onAfterRenderPass())}copyBufferToResult(e){this.material?.copyBufferToResult(e)}async getComputeResult({bindingName:e,bufferElementName:t}){return await this.material?.getComputeResult({bindingName:e,bufferElementName:t})}remove(){this.removeFromScene(),this.destroy()}destroy(){this.material?.destroy()}}ue=new WeakMap;const W=[new f,new f,new f,new f,new f,new f,new f,new f];class oe{constructor(e=new f(1/0),t=new f(-1/0)){this.min=e,this.max=t}set(e=new f(1/0),t=new f(-1/0)){return this.min.copy(e),this.max.copy(t),this}clone(){return new oe().set(this.min,this.max)}getCenter(){return this.max.clone().add(this.min).multiplyScalar(.5)}getSize(){return this.max.clone().sub(this.min)}applyMat4(e=new O){const t=[];this.min.z===this.max.z?(t[0]=W[0].set(this.min.x,this.min.y,this.min.z).applyMat4(e),t[1]=W[2].set(this.min.x,this.max.y,this.min.z).applyMat4(e),t[2]=W[4].set(this.max.x,this.min.y,this.min.z).applyMat4(e),t[3]=W[6].set(this.max.x,this.max.y,this.min.z).applyMat4(e)):(t[0]=W[0].set(this.min.x,this.min.y,this.min.z).applyMat4(e),t[1]=W[1].set(this.min.x,this.min.y,this.max.z).applyMat4(e),t[2]=W[2].set(this.min.x,this.max.y,this.min.z).applyMat4(e),t[3]=W[3].set(this.min.x,this.max.y,this.max.z).applyMat4(e),t[4]=W[4].set(this.max.x,this.min.y,this.min.z).applyMat4(e),t[5]=W[5].set(this.max.x,this.min.y,this.max.z).applyMat4(e),t[6]=W[6].set(this.max.x,this.max.y,this.min.z).applyMat4(e),t[7]=W[7].set(this.max.x,this.max.y,this.max.z).applyMat4(e));const s=new oe;for(let i=0,r=t.length;i{},onLeaveView:n=()=>{}}){this.boundingBox=e,this.modelViewProjectionMatrix=t,this.containerBoundingRect=s,this.DOMFrustumMargins={...yt,...i},this.projectedBoundingRect={top:0,right:0,bottom:0,left:0,width:0,height:0,x:0,y:0},this.onReEnterView=r,this.onLeaveView=n,this.isIntersecting=!1,this.shouldUpdate=!1}setContainerBoundingRect(e){this.containerBoundingRect=e}get DOMFrustumBoundingRect(){return{top:this.projectedBoundingRect.top-this.DOMFrustumMargins.top,right:this.projectedBoundingRect.right+this.DOMFrustumMargins.right,bottom:this.projectedBoundingRect.bottom+this.DOMFrustumMargins.bottom,left:this.projectedBoundingRect.left-this.DOMFrustumMargins.left}}computeProjectedToDocumentCoords(){const e=this.boundingBox.applyMat4(this.modelViewProjectionMatrix);e.min.x=(e.min.x+1)*.5,e.max.x=(e.max.x+1)*.5,e.min.y=1-(e.min.y+1)*.5,e.max.y=1-(e.max.y+1)*.5;const{width:t,height:s,top:i,left:r}=this.containerBoundingRect;this.projectedBoundingRect={left:e.min.x*t+r,x:e.min.x*t+r,top:e.max.y*s+i,y:e.max.y*s+i,right:e.max.x*t+r,bottom:e.min.y*s+i,width:e.max.x*t+r-(e.min.x*t+r),height:e.min.y*s+i-(e.max.y*s+i)},this.intersectsContainer()}intersectsContainer(){Math.round(this.DOMFrustumBoundingRect.right)<=this.containerBoundingRect.left||Math.round(this.DOMFrustumBoundingRect.left)>=this.containerBoundingRect.left+this.containerBoundingRect.width||Math.round(this.DOMFrustumBoundingRect.bottom)<=this.containerBoundingRect.top||Math.round(this.DOMFrustumBoundingRect.top)>=this.containerBoundingRect.top+this.containerBoundingRect.height?(this.isIntersecting&&this.onLeaveView(),this.isIntersecting=!1):(this.isIntersecting||this.onReEnterView(),this.isIntersecting=!0)}}var rs=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},ns=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},os=(o,e,t)=>(rs(o,e,"access private method"),t),qe,bt;class Ne{constructor({verticesOrder:e="ccw",topology:t="triangle-list",instancesCount:s=1,vertexBuffers:i=[]}={}){ns(this,qe),this.verticesCount=0,this.verticesOrder=e,this.topology=t,this.instancesCount=s,this.boundingBox=new oe,this.type="Geometry",this.vertexBuffers=[],this.addVertexBuffer({name:"attributes"}),this.options={verticesOrder:e,instancesCount:s,vertexBuffers:i,topology:t},i.forEach(r=>{this.addVertexBuffer({stepMode:r.stepMode??"vertex",name:r.name,attributes:r.attributes})})}get shouldCompute(){return this.vertexBuffers.length&&!this.vertexBuffers[0].array}get ready(){return!this.shouldCompute&&!this.vertexBuffers.find(e=>!e.buffer)}addVertexBuffer({stepMode:e="vertex",name:t,attributes:s=[]}={}){const i={name:t??"attributes"+this.vertexBuffers.length,stepMode:e,arrayStride:0,bufferLength:0,attributes:[],buffer:null};return s?.forEach(r=>{this.setAttribute({vertexBuffer:i,...r})}),this.vertexBuffers.push(i),i}getVertexBufferByName(e=""){return this.vertexBuffers.find(t=>t.name===e)}setAttribute({vertexBuffer:e=this.vertexBuffers[0],name:t,type:s="vec3f",bufferFormat:i="float32x3",size:r=3,array:n=new Float32Array(this.verticesCount*r),verticesStride:a=1}){const h=e.attributes,u=h.length;t||(t="geometryAttribute"+u),t==="position"&&(s!=="vec3f"||i!=="float32x3"||r!==3)&&(U(`Geometry 'position' attribute must have this exact properties set: type: 'vec3f', bufferFormat: 'float32x3', size: 3`),s="vec3f",i="float32x3",r=3);const d=n.length/r;t==="position"&&(this.verticesCount=d),e.stepMode==="vertex"&&this.verticesCount&&this.verticesCount!==d*a?V(`Geometry vertex attribute error. Attribute array of size ${r} must be of length: ${this.verticesCount*r}, current given: ${n.length}. (${this.verticesCount} vertices).`):e.stepMode==="instance"&&d!==this.instancesCount&&V(`Geometry instance attribute error. Attribute array of size ${r} must be of length: ${this.instancesCount*r}, current given: ${n.length}. (${this.instancesCount} instances).`);const l={name:t,type:s,bufferFormat:i,size:r,bufferLength:n.length,offset:u?h.reduce((c,p)=>c+p.bufferLength,0):0,bufferOffset:u?h[u-1].bufferOffset+h[u-1].size*4:0,array:n,verticesStride:a};e.bufferLength+=l.bufferLength*a,e.arrayStride+=l.size,e.attributes.push(l)}getAttributeByName(e){let t;return this.vertexBuffers.forEach(s=>{t=s.attributes.find(i=>i.name===e)}),t}computeGeometry(){this.shouldCompute&&(this.vertexBuffers.forEach((e,t)=>{if(t===0){const r=e.attributes.find(n=>n.name==="position");r||V("Geometry must have a 'position' attribute"),(r.type!=="vec3f"||r.bufferFormat!=="float32x3"||r.size!==3)&&(U(`Geometry 'position' attribute must have this exact properties set: @@ -57,7 +57,7 @@ @builtin(vertex_index) vertexIndex : u32, @builtin(instance_index) instanceIndex : u32,${this.vertexBuffers.map(e=>e.attributes.map(t=>(o++,` @location(${o}) ${t.name}: ${t.type}`))).join(",")} -};`};class Ee extends Ne{constructor({verticesOrder:e="ccw",topology:t="triangle-list",instancesCount:s=1,vertexBuffers:i=[]}={}){super({verticesOrder:e,topology:t,instancesCount:s,vertexBuffers:i}),this.type="IndexedGeometry"}get ready(){return!this.shouldCompute&&!this.vertexBuffers.find(e=>!e.buffer)&&this.indexBuffer&&!!this.indexBuffer.buffer}get useUint16IndexArray(){return this.verticesCount<256*256}setIndexBuffer({bufferFormat:e="uint32",array:t=new Uint32Array(0)}){this.indexBuffer={array:t,bufferFormat:e,bufferLength:t.length,buffer:null}}setGeometryBuffers(e){super.setGeometryBuffers(e),e.setIndexBuffer(this.indexBuffer.buffer,this.indexBuffer.bufferFormat)}drawGeometry(e){e.drawIndexed(this.indexBuffer.bufferLength,this.instancesCount)}destroy(){super.destroy(),this.indexBuffer?.buffer?.destroy(),this.indexBuffer.buffer=null}}class Ye extends Ee{constructor({widthSegments:e=1,heightSegments:t=1,instancesCount:s=1,vertexBuffers:i=[],topology:r}={}){super({verticesOrder:"cw",topology:r,instancesCount:s,vertexBuffers:i}),this.type="PlaneGeometry",e=Math.floor(e),t=Math.floor(t),this.definition={id:e*t+e,width:e,height:t,count:e*t};const n=(this.definition.width+1)*(this.definition.height+1),a=this.getIndexedVerticesAndUVs(n);Object.keys(a).forEach(h=>{this.setAttribute(a[h])}),this.setIndexArray()}setIndexArray(){const e=this.useUint16IndexArray?new Uint16Array(this.definition.count*6):new Uint32Array(this.definition.count*6);let t=0;for(let s=0;se[s]!==this.options.rendering[s]);this.options.rendering={...this.options.rendering,...e},this.pipelineEntry&&(this.pipelineEntry.options.rendering={...this.pipelineEntry.options.rendering,...this.options.rendering},this.pipelineEntry.ready&&t.length&&(U(`${this.options.label}: the change of rendering options is causing this RenderMaterial pipeline to be flushed and recompiled. This should be avoided. Rendering options that caused this: { ${t.map(s=>`"${s}": ${Array.isArray(e[s])?e[s].map(i=>`${JSON.stringify(i)}`).join(", "):e[s]}`).join(", ")} }`),this.pipelineEntry.flushPipelineEntry(this.bindGroups)))}setAttributesFromGeometry(e){this.attributes={wgslStructFragment:e.wgslStructFragment,vertexBuffers:e.vertexBuffers}}createBindGroups(){const e=this.options.rendering.useProjection?1:0;this.texturesBindGroup.shouldCreateBindGroup&&(this.texturesBindGroup.setIndex(this.bindGroups.length+e),this.texturesBindGroup.createBindGroup(),this.bindGroups.push(this.texturesBindGroup)),this.inputsBindGroups.forEach(t=>{t.shouldCreateBindGroup&&(t.setIndex(this.bindGroups.length+e),t.createBindGroup(),this.bindGroups.push(t))})}}var vt=` +};`};class Ee extends Ne{constructor({verticesOrder:e="ccw",topology:t="triangle-list",instancesCount:s=1,vertexBuffers:i=[]}={}){super({verticesOrder:e,topology:t,instancesCount:s,vertexBuffers:i}),this.type="IndexedGeometry"}get ready(){return!this.shouldCompute&&!this.vertexBuffers.find(e=>!e.buffer)&&this.indexBuffer&&!!this.indexBuffer.buffer}get useUint16IndexArray(){return this.verticesCount<256*256}setIndexBuffer({bufferFormat:e="uint32",array:t=new Uint32Array(0)}){this.indexBuffer={array:t,bufferFormat:e,bufferLength:t.length,buffer:null}}setGeometryBuffers(e){super.setGeometryBuffers(e),e.setIndexBuffer(this.indexBuffer.buffer,this.indexBuffer.bufferFormat)}drawGeometry(e){e.drawIndexed(this.indexBuffer.bufferLength,this.instancesCount)}destroy(){super.destroy(),this.indexBuffer?.buffer?.destroy(),this.indexBuffer.buffer=null}}class Ye extends Ee{constructor({widthSegments:e=1,heightSegments:t=1,instancesCount:s=1,vertexBuffers:i=[],topology:r}={}){super({verticesOrder:"cw",topology:r,instancesCount:s,vertexBuffers:i}),this.type="PlaneGeometry",e=Math.floor(e),t=Math.floor(t),this.definition={id:e*t+e,width:e,height:t,count:e*t};const n=(this.definition.width+1)*(this.definition.height+1),a=this.getIndexedVerticesAndUVs(n);Object.keys(a).forEach(h=>{this.setAttribute(a[h])}),this.setIndexArray()}setIndexArray(){const e=this.useUint16IndexArray?new Uint16Array(this.definition.count*6):new Uint32Array(this.definition.count*6);let t=0;for(let s=0;se[s]!==this.options.rendering[s]);this.options.rendering={...this.options.rendering,...e},this.pipelineEntry&&(this.pipelineEntry.options.rendering={...this.pipelineEntry.options.rendering,...this.options.rendering},this.pipelineEntry.ready&&t.length&&(U(`${this.options.label}: the change of rendering options is causing this RenderMaterial pipeline to be flushed and recompiled. This should be avoided. Rendering options that caused this: { ${t.map(s=>`"${s}": ${Array.isArray(e[s])?e[s].map(i=>`${JSON.stringify(i)}`).join(", "):e[s]}`).join(", ")} }`),this.pipelineEntry.flushPipelineEntry(this.bindGroups)))}setAttributesFromGeometry(e){this.attributes={wgslStructFragment:e.wgslStructFragment,vertexBuffers:e.vertexBuffers}}createBindGroups(){const e=this.options.rendering.useProjection?1:0;this.texturesBindGroup.shouldCreateBindGroup&&(this.texturesBindGroup.setIndex(this.bindGroups.length+e),this.texturesBindGroup.createBindGroup(),this.bindGroups.push(this.texturesBindGroup)),this.inputsBindGroups.forEach(t=>{t.shouldCreateBindGroup&&(t.setIndex(this.bindGroups.length+e),t.createBindGroup(),this.bindGroups.push(t))})}}var vt=` struct VertexOutput { @builtin(position) position: vec4f, @location(0) uv: vec2f, @@ -75,7 +75,7 @@ struct VertexOutput { }`,Pt=` @fragment fn main() -> @location(0) vec4f { return vec4(0.0, 0.0, 0.0, 1.0); -}`,Mt=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},Xe=(o,e,t)=>(Mt(o,e,"read from private field"),t?t.call(o):e.get(o)),as=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},hs=(o,e,t,s)=>(Mt(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t);let us=0;const Tt={geometry:new Ne,shaders:{},autoRender:!0,useProjection:!1,useAsyncPipeline:!0,cullMode:"back",depth:!0,depthWriteEnabled:!0,depthCompare:"less",depthFormat:"depth24plus",transparent:!1,visible:!0,renderOrder:0,texturesOptions:{}};function Rt(o){var e,t;return t=class extends o{constructor(...s){super(s[0],s[1],{...Tt,...s[2]}),as(this,e,!0),this._onReadyCallback=()=>{},this._onBeforeRenderCallback=()=>{},this._onRenderCallback=()=>{},this._onAfterRenderCallback=()=>{},this._onAfterResizeCallback=()=>{};let i=s[0];const r={...Tt,...s[2]};this.type="MeshBase",this.uuid=D(),Object.defineProperty(this,"index",{value:us++}),i=i&&i.renderer||i,z(i,r.label?r.label+" "+this.type:this.type),this.renderer=i;const{label:n,shaders:a,geometry:h,visible:u,renderOrder:d,outputTarget:l,texturesOptions:c,autoRender:p,...m}=r;this.outputTarget=l??null,m.sampleCount=m.sampleCount?m.sampleCount:this.outputTarget?this.outputTarget.renderPass.options.sampleCount:this.renderer&&this.renderer.renderPass?this.renderer.renderPass.options.sampleCount:1,this.options={...this.options??{},label:n??"Mesh "+this.renderer.meshes.length,shaders:a,texturesOptions:c,...l!==void 0&&{outputTarget:l},...p!==void 0&&{autoRender:p},...m},this.geometry=h,p!==void 0&&hs(this,e,p),this.visible=u,this.renderOrder=d,this.ready=!1,this.userData={},this.computeGeometry(),this.setMaterial({...this.cleanupRenderMaterialParameters({...this.options}),verticesOrder:h.verticesOrder,topology:h.topology}),this.addToScene()}get autoRender(){return Xe(this,e)}get ready(){return this._ready}set ready(s){s&&this._onReadyCallback&&this._onReadyCallback(),this._ready=s}addToScene(){this.renderer.meshes.push(this),this.setRenderingOptionsForRenderPass(this.outputTarget?this.outputTarget.renderPass:this.renderer.renderPass),Xe(this,e)&&this.renderer.scene.addMesh(this)}removeFromScene(){Xe(this,e)&&this.renderer.scene.removeMesh(this),this.renderer.meshes=this.renderer.meshes.filter(s=>s.uuid!==this.uuid)}setRenderer(s){if(s=s&&s.renderer||s,!s||!(s.type==="GPURenderer"||s.type==="GPUCameraRenderer"||s.type==="GPUCurtainsRenderer")){U(`${this.options.label}: Cannot set ${s} as a renderer because it is not of a valid Renderer type.`);return}const i=this.renderer;this.removeFromScene(),this.renderer=s,this.addToScene(),i.meshes.length||i.onBeforeRenderScene.add(r=>{i.forceClear(r)},{once:!0})}setOutputTarget(s){if(s&&s.type!=="RenderTarget"){U(`${this.options.label??this.type}: outputTarget is not a RenderTarget: ${s}`);return}this.removeFromScene(),this.outputTarget=s,this.addToScene()}loseContext(){this.geometry.vertexBuffers.forEach(s=>{s.buffer=null}),"indexBuffer"in this.geometry&&(this.geometry.indexBuffer.buffer=null),this.material.loseContext()}restoreContext(){this.material.restoreContext()}setShaders(){let{shaders:s}=this.options;s?((!s.vertex||!s.vertex.code)&&(s.vertex={code:vt,entryPoint:"main"}),(s.fragment===void 0||s.fragment&&!s.fragment.code)&&(s.fragment={code:Pt,entryPoint:"main"})):s={vertex:{code:vt,entryPoint:"main"},fragment:{code:Pt,entryPoint:"main"}}}computeGeometry(){this.geometry.shouldCompute&&this.geometry.computeGeometry()}createGeometryBuffers(){this.geometry.ready||(this.geometry.vertexBuffers.forEach(s=>{s.buffer||(s.buffer=this.renderer.createBuffer({label:this.options.label+" geometry: "+s.name+" buffer",size:s.array.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.renderer.queueWriteBuffer(s.buffer,0,s.array))}),"indexBuffer"in this.geometry&&this.geometry.indexBuffer&&!this.geometry.indexBuffer.buffer&&(this.geometry.indexBuffer.buffer=this.renderer.createBuffer({label:this.options.label+" geometry: index buffer",size:this.geometry.indexBuffer.array.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this.renderer.queueWriteBuffer(this.geometry.indexBuffer.buffer,0,this.geometry.indexBuffer.array)))}setGeometry(){this.geometry&&this.renderer.ready&&(this.createGeometryBuffers(),this.setMaterialGeometryAttributes())}setRenderingOptionsForRenderPass(s){const i={sampleCount:s.options.sampleCount,...s.options.colorAttachments.length&&{targetFormat:s.options.colorAttachments[0].targetFormat,...s.options.colorAttachments.length>1&&{additionalTargets:s.options.colorAttachments.filter((r,n)=>n>0).map(r=>({format:r.targetFormat}))}},depth:s.options.useDepth,...s.options.useDepth&&{depthFormat:s.options.depthFormat}};this.material?.setRenderingOptions(i)}cleanupRenderMaterialParameters(s){return delete s.texturesOptions,delete s.outputTarget,delete s.autoRender,s}setMaterial(s){this.transparent=s.transparent,this.setShaders(),this.material=new wt(this.renderer,s),this.material.options.textures?.filter(i=>i instanceof te).forEach(i=>this.onTextureAdded(i))}setMaterialGeometryAttributes(){this.material&&!this.material.attributes&&this.material.setAttributesFromGeometry(this.geometry)}get textures(){return this.material?.textures||[]}get renderTextures(){return this.material?.renderTextures||[]}createTexture(s){s.name||(s.name="texture"+this.textures.length),s.label||(s.label=this.options.label+" "+s.name);const i=new te(this.renderer,{...s,...this.options.texturesOptions});return this.addTexture(i),i}addTexture(s){this.material.addTexture(s),this.onTextureAdded(s)}onTextureAdded(s){s.parentMesh=this}createRenderTexture(s){s.name||(s.name="renderTexture"+this.renderTextures.length);const i=new J(this.renderer,s);return this.addRenderTexture(i),i}addRenderTexture(s){this.material.addTexture(s)}get uniforms(){return this.material?.uniforms}get storages(){return this.material?.storages}resize(s){super.resize&&super.resize(s),this.renderTextures?.forEach(i=>{i.options.fromTexture&&i.copy(i.options.fromTexture)}),this.textures?.forEach(i=>{i.resize()}),this._onAfterResizeCallback&&this._onAfterResizeCallback()}onReady(s){return s&&(this._onReadyCallback=s),this}onBeforeRender(s){return s&&(this._onBeforeRenderCallback=s),this}onRender(s){return s&&(this._onRenderCallback=s),this}onAfterRender(s){return s&&(this._onAfterRenderCallback=s),this}onAfterResize(s){return s&&(this._onAfterResizeCallback=s),this}onBeforeRenderPass(){this.renderer.ready&&(this.material&&this.material.ready&&this.geometry&&this.geometry.ready&&!this.ready&&(this.ready=!0),this.setGeometry(),this._onBeforeRenderCallback&&this._onBeforeRenderCallback(),this.material.onBeforeRender())}onRenderPass(s){this.material.ready&&(this._onRenderCallback&&this._onRenderCallback(),this.material.render(s),this.geometry.render(s))}onAfterRenderPass(){this._onAfterRenderCallback&&this._onAfterRenderCallback()}render(s){this.onBeforeRenderPass(),!(!this.renderer.ready||!this.visible)&&(super.render&&super.render(),!this.renderer.production&&s.pushDebugGroup(this.options.label),this.onRenderPass(s),!this.renderer.production&&s.popDebugGroup(),this.onAfterRenderPass())}remove(){this.removeFromScene(),this.destroy(),this.renderer.meshes.length||this.renderer.onBeforeRenderScene.add(s=>{this.renderer.forceClear(s)},{once:!0})}destroy(){super.destroy&&super.destroy(),this.material?.destroy(),this.geometry.vertexBuffers.forEach(s=>{this.renderer.removeBuffer(s.buffer,this.options.label+" geometry: "+s.name+" buffer")}),"indexBuffer"in this.geometry&&this.renderer.removeBuffer(this.geometry.indexBuffer.buffer),this.geometry?.destroy()}},e=new WeakMap,t}class ds{constructor(){this.planeGeometries=[]}getPlaneGeometry(e){return this.planeGeometries.find(t=>t.definition.id===e.definition.id)}getPlaneGeometryByID(e){return this.planeGeometries.find(t=>t.definition.id===e)}addPlaneGeometry(e){this.planeGeometries.push(e)}destroy(){this.planeGeometries=[]}}const Ge=new ds;class He extends Rt(class{}){constructor(e,t={}){e=e&&e.renderer||e,z(e,t.label?t.label+" FullscreenQuadMesh":"FullscreenQuadMesh");let s=Ge.getPlaneGeometryByID(2);s||(s=new Ye({widthSegments:1,heightSegments:1}),Ge.addPlaneGeometry(s)),(!t.shaders||!t.shaders.vertex)&&["uniforms","storages"].forEach(i=>{Object.keys(t[i]??{}).forEach(r=>t[i][r].visibility="fragment")}),super(e,null,{geometry:s,...t}),this.size={document:{width:this.renderer.boundingRect.width,height:this.renderer.boundingRect.height,top:this.renderer.boundingRect.top,left:this.renderer.boundingRect.left}},this.type="FullscreenQuadMesh"}resize(e=null){this.size.document=e??this.renderer.boundingRect,super.resize(e)}mouseToPlaneCoords(e=new E){return new E((e.x-this.size.document.left)/this.size.document.width*2-1,1-(e.y-this.size.document.top)/this.size.document.height*2)}}class Ze extends ye{constructor(e){super(),e=e&&e.renderer||e,ke(e,"ProjectedObject3D"),this.camera=e.camera}applyPosition(){super.applyPosition(),this.shouldUpdateProjectionMatrixStack()}applyRotation(){super.applyRotation(),this.shouldUpdateProjectionMatrixStack()}applyScale(){super.applyScale(),this.shouldUpdateProjectionMatrixStack()}applyTransformOrigin(){super.applyTransformOrigin(),this.shouldUpdateProjectionMatrixStack()}setMatrices(){super.setMatrices(),this.matrices={...this.matrices,modelView:{matrix:new O,shouldUpdate:!1,onUpdate:()=>{this.modelViewMatrix.multiplyMatrices(this.viewMatrix,this.worldMatrix)}},modelViewProjection:{matrix:new O,shouldUpdate:!1,onUpdate:()=>{this.modelViewProjectionMatrix.multiplyMatrices(this.projectionMatrix,this.modelViewMatrix)}}}}get modelViewMatrix(){return this.matrices.modelView.matrix}set modelViewMatrix(e){this.matrices.modelView.matrix=e,this.matrices.modelView.shouldUpdate=!0}get viewMatrix(){return this.camera.viewMatrix}get projectionMatrix(){return this.camera.projectionMatrix}get modelViewProjectionMatrix(){return this.matrices.modelViewProjection.matrix}set modelViewProjectionMatrix(e){this.matrices.modelViewProjection.matrix=e,this.matrices.modelViewProjection.shouldUpdate=!0}shouldUpdateProjectionMatrixStack(){this.matrices.modelView.shouldUpdate=!0,this.matrices.modelViewProjection.shouldUpdate=!0}shouldUpdateWorldMatrix(){super.shouldUpdateWorldMatrix(),this.shouldUpdateProjectionMatrixStack()}shouldUpdateMatrixStack(){this.shouldUpdateModelMatrix(),this.shouldUpdateProjectionMatrixStack()}}var Ct=` +}`,Mt=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},Xe=(o,e,t)=>(Mt(o,e,"read from private field"),t?t.call(o):e.get(o)),as=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},hs=(o,e,t,s)=>(Mt(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t);let us=0;const Rt={geometry:new Ne,shaders:{},autoRender:!0,useProjection:!1,useAsyncPipeline:!0,cullMode:"back",depth:!0,depthWriteEnabled:!0,depthCompare:"less",depthFormat:"depth24plus",transparent:!1,visible:!0,renderOrder:0,texturesOptions:{}};function Tt(o){var e,t;return t=class extends o{constructor(...s){super(s[0],s[1],{...Rt,...s[2]}),as(this,e,!0),this._onReadyCallback=()=>{},this._onBeforeRenderCallback=()=>{},this._onRenderCallback=()=>{},this._onAfterRenderCallback=()=>{},this._onAfterResizeCallback=()=>{};let i=s[0];const r={...Rt,...s[2]};this.type="MeshBase",this.uuid=D(),Object.defineProperty(this,"index",{value:us++}),i=i&&i.renderer||i,z(i,r.label?r.label+" "+this.type:this.type),this.renderer=i;const{label:n,shaders:a,geometry:h,visible:u,renderOrder:d,outputTarget:l,texturesOptions:c,autoRender:p,...m}=r;this.outputTarget=l??null,m.sampleCount=m.sampleCount?m.sampleCount:this.outputTarget?this.outputTarget.renderPass.options.sampleCount:this.renderer&&this.renderer.renderPass?this.renderer.renderPass.options.sampleCount:1,this.options={...this.options??{},label:n??"Mesh "+this.renderer.meshes.length,shaders:a,texturesOptions:c,...l!==void 0&&{outputTarget:l},...p!==void 0&&{autoRender:p},...m},this.geometry=h,p!==void 0&&hs(this,e,p),this.visible=u,this.renderOrder=d,this.ready=!1,this.userData={},this.computeGeometry(),this.setMaterial({...this.cleanupRenderMaterialParameters({...this.options}),verticesOrder:h.verticesOrder,topology:h.topology}),this.addToScene()}get autoRender(){return Xe(this,e)}get ready(){return this._ready}set ready(s){s&&this._onReadyCallback&&this._onReadyCallback(),this._ready=s}addToScene(){this.renderer.meshes.push(this),this.setRenderingOptionsForRenderPass(this.outputTarget?this.outputTarget.renderPass:this.renderer.renderPass),Xe(this,e)&&this.renderer.scene.addMesh(this)}removeFromScene(){Xe(this,e)&&this.renderer.scene.removeMesh(this),this.renderer.meshes=this.renderer.meshes.filter(s=>s.uuid!==this.uuid)}setRenderer(s){if(s=s&&s.renderer||s,!s||!(s.type==="GPURenderer"||s.type==="GPUCameraRenderer"||s.type==="GPUCurtainsRenderer")){U(`${this.options.label}: Cannot set ${s} as a renderer because it is not of a valid Renderer type.`);return}const i=this.renderer;this.removeFromScene(),this.renderer=s,this.addToScene(),i.meshes.length||i.onBeforeRenderScene.add(r=>{i.forceClear(r)},{once:!0})}setOutputTarget(s){if(s&&s.type!=="RenderTarget"){U(`${this.options.label??this.type}: outputTarget is not a RenderTarget: ${s}`);return}this.removeFromScene(),this.outputTarget=s,this.addToScene()}loseContext(){this.geometry.vertexBuffers.forEach(s=>{s.buffer=null}),"indexBuffer"in this.geometry&&(this.geometry.indexBuffer.buffer=null),this.material.loseContext()}restoreContext(){this.material.restoreContext()}setShaders(){let{shaders:s}=this.options;s?((!s.vertex||!s.vertex.code)&&(s.vertex={code:vt,entryPoint:"main"}),(s.fragment===void 0||s.fragment&&!s.fragment.code)&&(s.fragment={code:Pt,entryPoint:"main"})):s={vertex:{code:vt,entryPoint:"main"},fragment:{code:Pt,entryPoint:"main"}}}computeGeometry(){this.geometry.shouldCompute&&this.geometry.computeGeometry()}createGeometryBuffers(){this.geometry.ready||(this.geometry.vertexBuffers.forEach(s=>{s.buffer||(s.buffer=this.renderer.createBuffer({label:this.options.label+" geometry: "+s.name+" buffer",size:s.array.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.renderer.queueWriteBuffer(s.buffer,0,s.array))}),"indexBuffer"in this.geometry&&this.geometry.indexBuffer&&!this.geometry.indexBuffer.buffer&&(this.geometry.indexBuffer.buffer=this.renderer.createBuffer({label:this.options.label+" geometry: index buffer",size:this.geometry.indexBuffer.array.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this.renderer.queueWriteBuffer(this.geometry.indexBuffer.buffer,0,this.geometry.indexBuffer.array)))}setGeometry(){this.geometry&&this.renderer.ready&&(this.createGeometryBuffers(),this.setMaterialGeometryAttributes())}setRenderingOptionsForRenderPass(s){const i={sampleCount:s.options.sampleCount,...s.options.colorAttachments.length&&{targets:s.options.colorAttachments.map((r,n)=>({format:r.targetFormat,...this.options.targets?.length&&this.options.targets[n]&&this.options.targets[n].blend&&{blend:this.options.targets[n].blend}}))},depth:s.options.useDepth,...s.options.useDepth&&{depthFormat:s.options.depthFormat}};this.material?.setRenderingOptions(i)}cleanupRenderMaterialParameters(s){return delete s.texturesOptions,delete s.outputTarget,delete s.autoRender,s}setMaterial(s){this.transparent=s.transparent,this.setShaders(),this.material=new wt(this.renderer,s),this.material.options.textures?.filter(i=>i instanceof te).forEach(i=>this.onTextureAdded(i))}setMaterialGeometryAttributes(){this.material&&!this.material.attributes&&this.material.setAttributesFromGeometry(this.geometry)}get textures(){return this.material?.textures||[]}get renderTextures(){return this.material?.renderTextures||[]}createTexture(s){s.name||(s.name="texture"+this.textures.length),s.label||(s.label=this.options.label+" "+s.name);const i=new te(this.renderer,{...s,...this.options.texturesOptions});return this.addTexture(i),i}addTexture(s){this.material.addTexture(s),this.onTextureAdded(s)}onTextureAdded(s){s.parentMesh=this}createRenderTexture(s){s.name||(s.name="renderTexture"+this.renderTextures.length);const i=new J(this.renderer,s);return this.addRenderTexture(i),i}addRenderTexture(s){this.material.addTexture(s)}get uniforms(){return this.material?.uniforms}get storages(){return this.material?.storages}resize(s){super.resize&&super.resize(s),this.renderTextures?.forEach(i=>{i.options.fromTexture&&i.copy(i.options.fromTexture)}),this.textures?.forEach(i=>{i.resize()}),this._onAfterResizeCallback&&this._onAfterResizeCallback()}onReady(s){return s&&(this._onReadyCallback=s),this}onBeforeRender(s){return s&&(this._onBeforeRenderCallback=s),this}onRender(s){return s&&(this._onRenderCallback=s),this}onAfterRender(s){return s&&(this._onAfterRenderCallback=s),this}onAfterResize(s){return s&&(this._onAfterResizeCallback=s),this}onBeforeRenderPass(){this.renderer.ready&&(this.material&&this.material.ready&&this.geometry&&this.geometry.ready&&!this.ready&&(this.ready=!0),this.setGeometry(),this._onBeforeRenderCallback&&this._onBeforeRenderCallback(),this.material.onBeforeRender())}onRenderPass(s){this.material.ready&&(this._onRenderCallback&&this._onRenderCallback(),this.material.render(s),this.geometry.render(s))}onAfterRenderPass(){this._onAfterRenderCallback&&this._onAfterRenderCallback()}render(s){this.onBeforeRenderPass(),!(!this.renderer.ready||!this.visible)&&(super.render&&super.render(),!this.renderer.production&&s.pushDebugGroup(this.options.label),this.onRenderPass(s),!this.renderer.production&&s.popDebugGroup(),this.onAfterRenderPass())}remove(){this.removeFromScene(),this.destroy(),this.renderer.meshes.length||this.renderer.onBeforeRenderScene.add(s=>{this.renderer.forceClear(s)},{once:!0})}destroy(){super.destroy&&super.destroy(),this.material?.destroy(),this.geometry.vertexBuffers.forEach(s=>{this.renderer.removeBuffer(s.buffer,this.options.label+" geometry: "+s.name+" buffer")}),"indexBuffer"in this.geometry&&this.renderer.removeBuffer(this.geometry.indexBuffer.buffer),this.geometry?.destroy()}},e=new WeakMap,t}class ds{constructor(){this.planeGeometries=[]}getPlaneGeometry(e){return this.planeGeometries.find(t=>t.definition.id===e.definition.id)}getPlaneGeometryByID(e){return this.planeGeometries.find(t=>t.definition.id===e)}addPlaneGeometry(e){this.planeGeometries.push(e)}destroy(){this.planeGeometries=[]}}const Ge=new ds;class He extends Tt(class{}){constructor(e,t={}){e=e&&e.renderer||e,z(e,t.label?t.label+" FullscreenQuadMesh":"FullscreenQuadMesh");let s=Ge.getPlaneGeometryByID(2);s||(s=new Ye({widthSegments:1,heightSegments:1}),Ge.addPlaneGeometry(s)),(!t.shaders||!t.shaders.vertex)&&["uniforms","storages"].forEach(i=>{Object.keys(t[i]??{}).forEach(r=>t[i][r].visibility="fragment")}),t.depthWriteEnabled=!1,super(e,null,{geometry:s,...t}),this.size={document:{width:this.renderer.boundingRect.width,height:this.renderer.boundingRect.height,top:this.renderer.boundingRect.top,left:this.renderer.boundingRect.left}},this.type="FullscreenQuadMesh"}resize(e=null){this.size.document=e??this.renderer.boundingRect,super.resize(e)}mouseToPlaneCoords(e=new E){return new E((e.x-this.size.document.left)/this.size.document.width*2-1,1-(e.y-this.size.document.top)/this.size.document.height*2)}}class Ze extends ye{constructor(e){super(),e=e&&e.renderer||e,ke(e,"ProjectedObject3D"),this.camera=e.camera}applyPosition(){super.applyPosition(),this.shouldUpdateProjectionMatrixStack()}applyRotation(){super.applyRotation(),this.shouldUpdateProjectionMatrixStack()}applyScale(){super.applyScale(),this.shouldUpdateProjectionMatrixStack()}applyTransformOrigin(){super.applyTransformOrigin(),this.shouldUpdateProjectionMatrixStack()}setMatrices(){super.setMatrices(),this.matrices={...this.matrices,modelView:{matrix:new O,shouldUpdate:!1,onUpdate:()=>{this.modelViewMatrix.multiplyMatrices(this.viewMatrix,this.worldMatrix)}},modelViewProjection:{matrix:new O,shouldUpdate:!1,onUpdate:()=>{this.modelViewProjectionMatrix.multiplyMatrices(this.projectionMatrix,this.modelViewMatrix)}}}}get modelViewMatrix(){return this.matrices.modelView.matrix}set modelViewMatrix(e){this.matrices.modelView.matrix=e,this.matrices.modelView.shouldUpdate=!0}get viewMatrix(){return this.camera.viewMatrix}get projectionMatrix(){return this.camera.projectionMatrix}get modelViewProjectionMatrix(){return this.matrices.modelViewProjection.matrix}set modelViewProjectionMatrix(e){this.matrices.modelViewProjection.matrix=e,this.matrices.modelViewProjection.shouldUpdate=!0}shouldUpdateProjectionMatrixStack(){this.matrices.modelView.shouldUpdate=!0,this.matrices.modelViewProjection.shouldUpdate=!0}shouldUpdateWorldMatrix(){super.shouldUpdateWorldMatrix(),this.shouldUpdateProjectionMatrixStack()}shouldUpdateMatrixStack(){this.shouldUpdateModelMatrix(),this.shouldUpdateProjectionMatrixStack()}}var Ct=` struct VertexOutput { @builtin(position) position: vec4f, @location(0) uv: vec2f, @@ -102,7 +102,7 @@ struct VSOutput { @fragment fn main(fsInput: VSOutput) -> @location(0) vec4f { // normals return vec4(normalize(fsInput.normal) * 0.5 + 0.5, 1.0); -}`;const St={frustumCulled:!0,DOMFrustumMargins:{top:0,right:0,bottom:0,left:0}};function Et(o){return class extends Rt(o){constructor(...t){super(t[0],t[1],{...St,...t[2],useProjection:!0}),this._onReEnterViewCallback=()=>{},this._onLeaveViewCallback=()=>{};let s=t[0];const i={...St,...t[2],useProjection:!0};this.type="MeshTransformed",s=s&&s.renderer||s,ke(s,i.label?i.label+" "+this.type:this.type),this.renderer=s;const{geometry:r,frustumCulled:n,DOMFrustumMargins:a}=i;this.options={...this.options??{},frustumCulled:n,DOMFrustumMargins:a},this.setDOMFrustum(),this.geometry=r,this.shouldUpdateMatrixStack()}setShaders(){let{shaders:t}=this.options;t?((!t.vertex||!t.vertex.code)&&(t.vertex={code:Ct,entryPoint:"main"}),(t.fragment===void 0||t.fragment&&!t.fragment.code)&&(t.fragment={code:Bt,entryPoint:"main"})):t={vertex:{code:Ct,entryPoint:"main"},fragment:{code:Bt,entryPoint:"main"}}}setDOMFrustum(){this.domFrustum=new xt({boundingBox:this.geometry.boundingBox,modelViewProjectionMatrix:this.modelViewProjectionMatrix,containerBoundingRect:this.renderer.boundingRect,DOMFrustumMargins:this.options.DOMFrustumMargins,onReEnterView:()=>{this._onReEnterViewCallback&&this._onReEnterViewCallback()},onLeaveView:()=>{this._onLeaveViewCallback&&this._onLeaveViewCallback()}}),this.DOMFrustumMargins=this.domFrustum.DOMFrustumMargins,this.frustumCulled=this.options.frustumCulled,this.domFrustum.shouldUpdate=this.frustumCulled}cleanupRenderMaterialParameters(t){return delete t.frustumCulled,delete t.DOMFrustumMargins,super.cleanupRenderMaterialParameters(t),t}setMaterial(t){const s={label:"Matrices",struct:{model:{name:"model",type:"mat4x4f",value:this.modelMatrix},world:{name:"world",type:"mat4x4f",value:this.worldMatrix},modelView:{name:"modelView",type:"mat4x4f",value:this.modelViewMatrix},modelViewProjection:{name:"modelViewProjection",type:"mat4x4f",value:this.modelViewProjectionMatrix}}};t.uniforms||(t.uniforms={}),t.uniforms.matrices=s,super.setMaterial(t)}resize(t){this.domFrustum&&this.domFrustum.setContainerBoundingRect(this.renderer.boundingRect),super.resize(t)}applyScale(){super.applyScale(),this.textures.forEach(t=>t.resize())}get projectedBoundingRect(){return this.domFrustum?.projectedBoundingRect}onAfterMatrixStackUpdate(){this.material&&this.material.shouldUpdateInputsBindings("matrices"),this.domFrustum&&(this.domFrustum.shouldUpdate=!0)}onReEnterView(t){return t&&(this._onReEnterViewCallback=t),this}onLeaveView(t){return t&&(this._onLeaveViewCallback=t),this}onBeforeRenderPass(){this.updateMatrixStack(),this.domFrustum&&this.domFrustum.shouldUpdate&&this.frustumCulled&&(this.domFrustum.computeProjectedToDocumentCoords(),this.domFrustum.shouldUpdate=!1),super.onBeforeRenderPass()}onRenderPass(t){this.material.ready&&(this._onRenderCallback&&this._onRenderCallback(),(this.domFrustum&&this.domFrustum.isIntersecting||!this.frustumCulled)&&(this.material.render(t),this.geometry.render(t)))}}}class ls extends Et(Ze){constructor(e,t){e=e&&e.renderer||e,ke(e,t.label?t.label+" Mesh":"Mesh"),super(e,null,t),this.type="Mesh"}}let cs=0;class Qe{constructor(e){this.type="PipelineEntry";let{renderer:t}=e;const{label:s,shaders:i,useAsync:r}=e;t=t&&t.renderer||t,z(t,s?s+" "+this.type:this.type),this.renderer=t,Object.defineProperty(this,"index",{value:cs++}),this.layout=null,this.pipeline=null,this.status={compiling:!1,compiled:!1,error:null},this.options={label:s,shaders:i,useAsync:r!==void 0?r:!0}}get ready(){return!this.status.compiling&&this.status.compiled&&!this.status.error}get canCompile(){return!this.status.compiling&&!this.status.compiled&&!this.status.error}setPipelineEntryBindGroups(e){this.bindGroups=e}createShaderModule({code:e="",type:t="vertex"}){const s=this.renderer.createShaderModule({label:this.options.label+": "+t+" shader module",code:e});return"getCompilationInfo"in s&&!this.renderer.production&&s.getCompilationInfo().then(i=>{for(const r of i.messages){let n="";switch(r.lineNum&&(n+=`Line ${r.lineNum}:${r.linePos} - ${e.substring(r.offset,r.offset+r.length)} +}`;const St={frustumCulled:!0,DOMFrustumMargins:{top:0,right:0,bottom:0,left:0}};function Et(o){return class extends Tt(o){constructor(...t){super(t[0],t[1],{...St,...t[2],useProjection:!0}),this._onReEnterViewCallback=()=>{},this._onLeaveViewCallback=()=>{};let s=t[0];const i={...St,...t[2],useProjection:!0};this.type="MeshTransformed",s=s&&s.renderer||s,ke(s,i.label?i.label+" "+this.type:this.type),this.renderer=s;const{geometry:r,frustumCulled:n,DOMFrustumMargins:a}=i;this.options={...this.options??{},frustumCulled:n,DOMFrustumMargins:a},this.setDOMFrustum(),this.geometry=r,this.shouldUpdateMatrixStack()}setShaders(){let{shaders:t}=this.options;t?((!t.vertex||!t.vertex.code)&&(t.vertex={code:Ct,entryPoint:"main"}),(t.fragment===void 0||t.fragment&&!t.fragment.code)&&(t.fragment={code:Bt,entryPoint:"main"})):t={vertex:{code:Ct,entryPoint:"main"},fragment:{code:Bt,entryPoint:"main"}}}setDOMFrustum(){this.domFrustum=new xt({boundingBox:this.geometry.boundingBox,modelViewProjectionMatrix:this.modelViewProjectionMatrix,containerBoundingRect:this.renderer.boundingRect,DOMFrustumMargins:this.options.DOMFrustumMargins,onReEnterView:()=>{this._onReEnterViewCallback&&this._onReEnterViewCallback()},onLeaveView:()=>{this._onLeaveViewCallback&&this._onLeaveViewCallback()}}),this.DOMFrustumMargins=this.domFrustum.DOMFrustumMargins,this.frustumCulled=this.options.frustumCulled,this.domFrustum.shouldUpdate=this.frustumCulled}cleanupRenderMaterialParameters(t){return delete t.frustumCulled,delete t.DOMFrustumMargins,super.cleanupRenderMaterialParameters(t),t}setMaterial(t){const s={label:"Matrices",struct:{model:{name:"model",type:"mat4x4f",value:this.modelMatrix},world:{name:"world",type:"mat4x4f",value:this.worldMatrix},modelView:{name:"modelView",type:"mat4x4f",value:this.modelViewMatrix},modelViewProjection:{name:"modelViewProjection",type:"mat4x4f",value:this.modelViewProjectionMatrix}}};t.uniforms||(t.uniforms={}),t.uniforms.matrices=s,super.setMaterial(t)}resize(t){this.domFrustum&&this.domFrustum.setContainerBoundingRect(this.renderer.boundingRect),super.resize(t)}applyScale(){super.applyScale(),this.textures.forEach(t=>t.resize())}get projectedBoundingRect(){return this.domFrustum?.projectedBoundingRect}onAfterMatrixStackUpdate(){this.material&&this.material.shouldUpdateInputsBindings("matrices"),this.domFrustum&&(this.domFrustum.shouldUpdate=!0)}onReEnterView(t){return t&&(this._onReEnterViewCallback=t),this}onLeaveView(t){return t&&(this._onLeaveViewCallback=t),this}onBeforeRenderPass(){this.updateMatrixStack(),this.domFrustum&&this.domFrustum.shouldUpdate&&this.frustumCulled&&(this.domFrustum.computeProjectedToDocumentCoords(),this.domFrustum.shouldUpdate=!1),super.onBeforeRenderPass()}onRenderPass(t){this.material.ready&&(this._onRenderCallback&&this._onRenderCallback(),(this.domFrustum&&this.domFrustum.isIntersecting||!this.frustumCulled)&&(this.material.render(t),this.geometry.render(t)))}}}class ls extends Et(Ze){constructor(e,t){e=e&&e.renderer||e,ke(e,t.label?t.label+" Mesh":"Mesh"),super(e,null,t),this.type="Mesh"}}let cs=0;class Qe{constructor(e){this.type="PipelineEntry";let{renderer:t}=e;const{label:s,shaders:i,useAsync:r}=e;t=t&&t.renderer||t,z(t,s?s+" "+this.type:this.type),this.renderer=t,Object.defineProperty(this,"index",{value:cs++}),this.layout=null,this.pipeline=null,this.status={compiling:!1,compiled:!1,error:null},this.options={label:s,shaders:i,useAsync:r!==void 0?r:!0}}get ready(){return!this.status.compiling&&this.status.compiled&&!this.status.error}get canCompile(){return!this.status.compiling&&!this.status.compiled&&!this.status.error}setPipelineEntryBindGroups(e){this.bindGroups=e}createShaderModule({code:e="",type:t="vertex"}){const s=this.renderer.createShaderModule({label:this.options.label+": "+t+" shader module",code:e});return"getCompilationInfo"in s&&!this.renderer.production&&s.getCompilationInfo().then(i=>{for(const r of i.messages){let n="";switch(r.lineNum&&(n+=`Line ${r.lineNum}:${r.linePos} - ${e.substring(r.offset,r.offset+r.length)} `),n+=r.message,r.type){case"error":console.error(`${this.options.label} compilation error: ${n}`);break;case"warning":console.warn(`${this.options.label} compilation warning: ${n}`);break;case"info":console.log(`${this.options.label} compilation information: @@ -148,11 +148,11 @@ ${this.shaders.full.head}`),this.shaders.full.head.indexOf(t.wgslGroupFragment)= @group(${t.groupIndex}) @binding(${t.bindIndex}) ${t.wgslGroupFragment}`,t.newLine&&(this.shaders.full.head+=` `))}),this.shaders.vertex.head=`${this.attributes.wgslStructFragment} ${this.shaders.vertex.head}`,this.shaders.full.head=`${this.attributes.wgslStructFragment} -${this.shaders.full.head}`,this.shaders.vertex.code=this.shaders.vertex.head+this.options.shaders.vertex.code,typeof this.options.shaders.fragment=="object"&&(this.shaders.fragment.code=this.shaders.fragment.head+this.options.shaders.fragment.code),typeof this.options.shaders.fragment=="object"&&(this.options.shaders.vertex.entryPoint!==this.options.shaders.fragment.entryPoint&&this.options.shaders.vertex.code.localeCompare(this.options.shaders.fragment.code)===0?this.shaders.full.code=this.shaders.full.head+this.options.shaders.vertex.code:this.shaders.full.code=this.shaders.full.head+this.options.shaders.vertex.code+this.options.shaders.fragment.code)}get shadersModulesReady(){return!(!this.shaders.vertex.module||this.options.shaders.fragment&&!this.shaders.fragment.module)}createShaders(){this.patchShaders();const e=typeof this.options.shaders.fragment=="object"&&this.options.shaders.vertex.entryPoint!==this.options.shaders.fragment.entryPoint&&this.options.shaders.vertex.code.localeCompare(this.options.shaders.fragment.code)===0;this.shaders.vertex.module=this.createShaderModule({code:this.shaders[e?"full":"vertex"].code,type:"vertex"}),this.options.shaders.fragment&&(this.shaders.fragment.module=this.createShaderModule({code:this.shaders[e?"full":"fragment"].code,type:"fragment"}))}createPipelineDescriptor(){if(!this.shadersModulesReady)return;let e=-1;const t=this.options.rendering.blend??(this.options.rendering.transparent&&{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}});this.descriptor={label:this.options.label,layout:this.layout,vertex:{module:this.shaders.vertex.module,entryPoint:this.options.shaders.vertex.entryPoint,buffers:this.attributes.vertexBuffers.map(s=>({stepMode:s.stepMode,arrayStride:s.arrayStride*4,attributes:s.attributes.map(i=>(e++,{shaderLocation:e,offset:i.bufferOffset,format:i.bufferFormat}))}))},...this.options.shaders.fragment&&{fragment:{module:this.shaders.fragment.module,entryPoint:this.options.shaders.fragment.entryPoint,targets:[{format:this.options.rendering.targetFormat??this.renderer.options.preferredFormat,...t&&{blend:t}},...this.options.rendering.additionalTargets??[]]}},primitive:{topology:this.options.rendering.topology,frontFace:this.options.rendering.verticesOrder,cullMode:this.options.rendering.cullMode},...this.options.rendering.depth&&{depthStencil:{depthWriteEnabled:this.options.rendering.depthWriteEnabled,depthCompare:this.options.rendering.depthCompare,format:this.options.rendering.depthFormat}},...this.options.rendering.sampleCount>1&&{multisample:{count:this.options.rendering.sampleCount}}}}createRenderPipeline(){if(this.shadersModulesReady)try{this.pipeline=this.renderer.createRenderPipeline(this.descriptor)}catch(e){this.status.error=e,V(e)}}async createRenderPipelineAsync(){if(this.shadersModulesReady)try{this.pipeline=await this.renderer.createRenderPipelineAsync(this.descriptor),this.status.compiled=!0,this.status.compiling=!1,this.status.error=null}catch(e){this.status.error=e,V(e)}}async compilePipelineEntry(){super.compilePipelineEntry(),this.options.useAsync?await this.createRenderPipelineAsync():(this.createRenderPipeline(),this.status.compiled=!0,this.status.compiling=!1,this.status.error=null)}}class Ke extends Qe{constructor(e){let{renderer:t}=e;const{label:s}=e;t=t&&t.renderer||t;const i="ComputePipelineEntry";z(t,s?s+" "+i:i),super(e),this.type=i,this.shaders={compute:{head:"",code:"",module:null}},this.descriptor=null}setPipelineEntryProperties(e){const{bindGroups:t}=e;this.setPipelineEntryBindGroups(t)}patchShaders(){this.shaders.compute.head="",this.shaders.compute.code="";const e=[];this.bindGroups.forEach(t=>{let s=0;t.bindings.forEach((i,r)=>{i.wgslGroupFragment.forEach((n,a)=>{e.push({groupIndex:t.index,visibility:i.visibility,bindIndex:s,wgslStructFragment:i.wgslStructFragment,wgslGroupFragment:n,newLine:r===t.bindings.length-1&&a===i.wgslGroupFragment.length-1}),s++})})}),e.forEach(t=>{t.wgslStructFragment&&this.shaders.compute.head.indexOf(t.wgslStructFragment)===-1&&(this.shaders.compute.head=` +${this.shaders.full.head}`,this.shaders.vertex.code=this.shaders.vertex.head+this.options.shaders.vertex.code,typeof this.options.shaders.fragment=="object"&&(this.shaders.fragment.code=this.shaders.fragment.head+this.options.shaders.fragment.code),typeof this.options.shaders.fragment=="object"&&(this.options.shaders.vertex.entryPoint!==this.options.shaders.fragment.entryPoint&&this.options.shaders.vertex.code.localeCompare(this.options.shaders.fragment.code)===0?this.shaders.full.code=this.shaders.full.head+this.options.shaders.vertex.code:this.shaders.full.code=this.shaders.full.head+this.options.shaders.vertex.code+this.options.shaders.fragment.code)}get shadersModulesReady(){return!(!this.shaders.vertex.module||this.options.shaders.fragment&&!this.shaders.fragment.module)}createShaders(){this.patchShaders();const e=typeof this.options.shaders.fragment=="object"&&this.options.shaders.vertex.entryPoint!==this.options.shaders.fragment.entryPoint&&this.options.shaders.vertex.code.localeCompare(this.options.shaders.fragment.code)===0;this.shaders.vertex.module=this.createShaderModule({code:this.shaders[e?"full":"vertex"].code,type:"vertex"}),this.options.shaders.fragment&&(this.shaders.fragment.module=this.createShaderModule({code:this.shaders[e?"full":"fragment"].code,type:"fragment"}))}createPipelineDescriptor(){if(!this.shadersModulesReady)return;let e=-1;this.options.rendering.targets.length?this.options.rendering.transparent&&(this.options.rendering.targets[0].blend=this.options.rendering.targets[0].blend?this.options.rendering.targets[0].blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}}):this.options.rendering.targets=[{format:this.renderer.options.preferredFormat}],this.descriptor={label:this.options.label,layout:this.layout,vertex:{module:this.shaders.vertex.module,entryPoint:this.options.shaders.vertex.entryPoint,buffers:this.attributes.vertexBuffers.map(t=>({stepMode:t.stepMode,arrayStride:t.arrayStride*4,attributes:t.attributes.map(s=>(e++,{shaderLocation:e,offset:s.bufferOffset,format:s.bufferFormat}))}))},...this.options.shaders.fragment&&{fragment:{module:this.shaders.fragment.module,entryPoint:this.options.shaders.fragment.entryPoint,targets:this.options.rendering.targets}},primitive:{topology:this.options.rendering.topology,frontFace:this.options.rendering.verticesOrder,cullMode:this.options.rendering.cullMode},...this.options.rendering.depth&&{depthStencil:{depthWriteEnabled:this.options.rendering.depthWriteEnabled,depthCompare:this.options.rendering.depthCompare,format:this.options.rendering.depthFormat}},...this.options.rendering.sampleCount>1&&{multisample:{count:this.options.rendering.sampleCount}}}}createRenderPipeline(){if(this.shadersModulesReady)try{this.pipeline=this.renderer.createRenderPipeline(this.descriptor)}catch(e){this.status.error=e,V(e)}}async createRenderPipelineAsync(){if(this.shadersModulesReady)try{this.pipeline=await this.renderer.createRenderPipelineAsync(this.descriptor),this.status.compiled=!0,this.status.compiling=!1,this.status.error=null}catch(e){this.status.error=e,V(e)}}async compilePipelineEntry(){super.compilePipelineEntry(),this.options.useAsync?await this.createRenderPipelineAsync():(this.createRenderPipeline(),this.status.compiled=!0,this.status.compiling=!1,this.status.error=null)}}class Ke extends Qe{constructor(e){let{renderer:t}=e;const{label:s}=e;t=t&&t.renderer||t;const i="ComputePipelineEntry";z(t,s?s+" "+i:i),super(e),this.type=i,this.shaders={compute:{head:"",code:"",module:null}},this.descriptor=null}setPipelineEntryProperties(e){const{bindGroups:t}=e;this.setPipelineEntryBindGroups(t)}patchShaders(){this.shaders.compute.head="",this.shaders.compute.code="";const e=[];this.bindGroups.forEach(t=>{let s=0;t.bindings.forEach((i,r)=>{i.wgslGroupFragment.forEach((n,a)=>{e.push({groupIndex:t.index,visibility:i.visibility,bindIndex:s,wgslStructFragment:i.wgslStructFragment,wgslGroupFragment:n,newLine:r===t.bindings.length-1&&a===i.wgslGroupFragment.length-1}),s++})})}),e.forEach(t=>{t.wgslStructFragment&&this.shaders.compute.head.indexOf(t.wgslStructFragment)===-1&&(this.shaders.compute.head=` ${t.wgslStructFragment} ${this.shaders.compute.head}`),this.shaders.compute.head.indexOf(t.wgslGroupFragment)===-1&&(this.shaders.compute.head=`${this.shaders.compute.head} @group(${t.groupIndex}) @binding(${t.bindIndex}) ${t.wgslGroupFragment}`),t.newLine&&(this.shaders.compute.head+=` -`)}),this.shaders.compute.code=this.shaders.compute.head+this.options.shaders.compute.code}createShaders(){this.patchShaders(),this.shaders.compute.module=this.createShaderModule({code:this.shaders.compute.code,type:"compute"})}createPipelineDescriptor(){this.shaders.compute.module&&(this.descriptor={label:this.options.label,layout:this.layout,compute:{module:this.shaders.compute.module,entryPoint:this.options.shaders.compute.entryPoint}})}createComputePipeline(){if(this.shaders.compute.module)try{this.pipeline=this.renderer.createComputePipeline(this.descriptor)}catch(e){this.status.error=e,V(e)}}async createComputePipelineAsync(){if(this.shaders.compute.module)try{this.pipeline=await this.renderer.createComputePipelineAsync(this.descriptor),this.status.compiled=!0,this.status.compiling=!1,this.status.error=null}catch(e){this.status.error=e,V(e)}}async compilePipelineEntry(){super.compilePipelineEntry(),this.options.useAsync?await this.createComputePipelineAsync():(this.createComputePipeline(),this.status.compiled=!0,this.status.compiling=!1,this.status.error=null)}}class zt{constructor(){this.type="PipelineManager",this.currentPipelineIndex=null,this.pipelineEntries=[]}compareShaders(e,t){return e.code?.localeCompare(t.code)===0&&e.entryPoint===t.entryPoint}isSameRenderPipeline(e){return this.pipelineEntries.filter(t=>t instanceof Je).find(t=>{const{options:s}=t,{shaders:i,rendering:r}=e,n=this.compareShaders(i.vertex,s.shaders.vertex),a=!i.fragment&&!s.shaders.fragment||this.compareShaders(i.fragment,s.shaders.fragment);return!Object.keys(s.rendering).filter(u=>s.rendering[u]!==r[u]).length&&n&&a})}createRenderPipeline(e){const t=this.isSameRenderPipeline(e);if(t)return t;{const s=new Je(e);return this.pipelineEntries.push(s),s}}isSameComputePipeline(e){const{shaders:t}=e;return this.pipelineEntries.filter(s=>s instanceof Ke).find(s=>{const{options:i}=s;return this.compareShaders(t.compute,i.shaders.compute)})}createComputePipeline(e){const t=this.isSameComputePipeline(e);if(t)return t;{const s=new Ke(e);return this.pipelineEntries.push(s),s}}setCurrentPipeline(e,t){t.index!==this.currentPipelineIndex&&(e.setPipeline(t.pipeline),this.currentPipelineIndex=t.index)}resetCurrentPipeline(){this.currentPipelineIndex=null}}class ms{constructor(){this.shouldWatch=!0,this.entries=[],this.resizeObserver=new ResizeObserver(e=>{e.map(s=>this.entries.filter(i=>i.element.isSameNode(s.target))).flat().sort((s,i)=>i.priority-s.priority)?.forEach(s=>{s&&s.callback&&s.callback()})})}useObserver(e=!0){this.shouldWatch=e}observe({element:e,priority:t,callback:s}){if(!e||!this.shouldWatch)return;this.resizeObserver.observe(e);const i={element:e,priority:t,callback:s};this.entries.push(i)}unobserve(e){this.resizeObserver.unobserve(e),this.entries=this.entries.filter(t=>!t.element.isSameNode(e))}destroy(){this.resizeObserver.disconnect()}}const et=new ms;class tt{constructor({element:e=document.body,priority:t=1,onSizeChanged:s=(r=null)=>{},onPositionChanged:i=(r=null)=>{}}={}){if(typeof e=="string"){if(this.element=document.querySelector(e),!this.element){const r=typeof e=="string"?`'${e}' selector`:`${e} HTMLElement`;V(`DOMElement: corresponding ${r} not found.`)}}else this.element=e;this.priority=t,this.isResizing=!1,this.onSizeChanged=s,this.onPositionChanged=i,this.resizeManager=et,this.resizeManager.observe({element:this.element,priority:this.priority,callback:()=>{this.setSize()}}),this.setSize()}compareBoundingRect(e,t){return!["x","y","left","top","right","bottom","width","height"].some(s=>e[s]!==t[s])}get boundingRect(){return this._boundingRect}set boundingRect(e){const t=!!this.boundingRect&&this.compareBoundingRect(e,this.boundingRect);this._boundingRect={top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width,height:e.height,x:e.x,y:e.y},t||this.onSizeChanged(this.boundingRect)}updateScrollPosition(e={x:0,y:0}){this.isResizing||(this._boundingRect.top+=e.y,this._boundingRect.left+=e.x,(e.x||e.y)&&this.onPositionChanged(this.boundingRect))}setSize(e=null){this.element&&(this.boundingRect=e??this.element.getBoundingClientRect(),this.isResizing=!1)}destroy(){this.resizeManager.unobserve(this.element)}}class Ot{constructor({renderer:e}){e=e&&e.renderer||e,z(e,"Scene"),this.renderer=e,this.computePassEntries=[],this.renderPassEntries={pingPong:[],renderTarget:[],screen:[{renderPass:this.renderer.renderPass,renderTexture:null,onBeforeRenderPass:null,onAfterRenderPass:null,element:null,stack:{unProjected:{opaque:[],transparent:[]},projected:{opaque:[],transparent:[]}}}]}}getRenderPassEntryLength(e){return e?e.element?e.element.visible?1:0:e.stack.unProjected.opaque.length+e.stack.unProjected.transparent.length+e.stack.projected.opaque.length+e.stack.projected.transparent.length:0}addComputePass(e){this.computePassEntries.push(e),this.computePassEntries.sort((t,s)=>t.renderOrder!==s.renderOrder?t.renderOrder-s.renderOrder:t.index-s.index)}removeComputePass(e){this.computePassEntries=this.computePassEntries.filter(t=>t.uuid!==e.uuid)}addRenderTarget(e){this.renderPassEntries.renderTarget.find(t=>t.renderPass.uuid===e.renderPass.uuid)||this.renderPassEntries.renderTarget.push({renderPass:e.renderPass,renderTexture:e.renderTexture,onBeforeRenderPass:null,onAfterRenderPass:null,element:null,stack:{unProjected:{opaque:[],transparent:[]},projected:{opaque:[],transparent:[]}}})}removeRenderTarget(e){this.renderPassEntries.renderTarget=this.renderPassEntries.renderTarget.filter(t=>t.renderPass.uuid!==e.renderPass.uuid)}getMeshProjectionStack(e){const t=e.outputTarget?this.renderPassEntries.renderTarget.find(i=>i.renderPass.uuid===e.outputTarget.renderPass.uuid):this.renderPassEntries.screen[0],{stack:s}=t;return e.material.options.rendering.useProjection?s.projected:s.unProjected}addMesh(e){const t=this.getMeshProjectionStack(e),s=e.transparent?[...t.transparent]:[...t.opaque];let i=-1;for(let r=s.length-1;r>=0;r--)if(s[r].material.pipelineEntry.index===e.material.pipelineEntry.index){i=r+1;break}i=Math.max(0,i),s.splice(i,0,e),s.sort((r,n)=>r.index-n.index),(e.type==="DOMMesh"||e.type==="Plane")&&e.transparent&&s.sort((r,n)=>n.documentPosition.z-r.documentPosition.z),s.sort((r,n)=>r.renderOrder-n.renderOrder),e.transparent?t.transparent=s:t.opaque=s}removeMesh(e){const t=this.getMeshProjectionStack(e);e.transparent?t.transparent=t.transparent.filter(s=>s.uuid!==e.uuid):t.opaque=t.opaque.filter(s=>s.uuid!==e.uuid)}addShaderPass(e){const t=e.inputTarget||e.outputTarget?null:(r,n)=>{e.renderTexture&&n&&r.copyTextureToTexture({texture:n},{texture:e.renderTexture.texture},[e.renderTexture.size.width,e.renderTexture.size.height]),this.renderer.postProcessingPass.setLoadOp("clear")},s=!e.outputTarget&&e.options.copyOutputToRenderTexture?(r,n)=>{e.renderTexture&&n&&r.copyTextureToTexture({texture:n},{texture:e.renderTexture.texture},[e.renderTexture.size.width,e.renderTexture.size.height])}:null,i={renderPass:e.outputTarget?e.outputTarget.renderPass:this.renderer.postProcessingPass,renderTexture:e.outputTarget?e.outputTarget.renderTexture:null,onBeforeRenderPass:t,onAfterRenderPass:s,element:e,stack:null};this.renderPassEntries.screen.push(i),this.renderPassEntries.screen.sort((r,n)=>{const a=r.element&&!r.element.outputTarget,h=r.element?r.element.renderOrder:0,u=r.element?r.element.index:0,d=n.element&&!n.element.outputTarget,l=n.element?n.element.renderOrder:0,c=n.element?n.element.index:0;return a&&!d?1:!a&&d?-1:h!==l?h-l:u-c})}removeShaderPass(e){this.renderPassEntries.screen=this.renderPassEntries.screen.filter(t=>!t.element||t.element.uuid!==e.uuid)}addPingPongPlane(e){this.renderPassEntries.pingPong.push({renderPass:e.outputTarget.renderPass,renderTexture:e.outputTarget.renderTexture,onBeforeRenderPass:null,onAfterRenderPass:(t,s)=>{t.copyTextureToTexture({texture:s},{texture:e.renderTexture.texture},[e.renderTexture.size.width,e.renderTexture.size.height])},element:e,stack:null}),this.renderPassEntries.pingPong.sort((t,s)=>t.element.renderOrder-s.element.renderOrder)}removePingPongPlane(e){this.renderPassEntries.pingPong=this.renderPassEntries.pingPong.filter(t=>t.element.uuid!==e.uuid)}getObjectRenderPassEntry(e){if(e.type==="RenderTarget")return this.renderPassEntries.renderTarget.find(t=>t.renderPass.uuid===e.renderPass.uuid);if(e.type==="PingPongPlane")return this.renderPassEntries.pingPong.find(t=>t.element.uuid===e.uuid);if(e.type==="ShaderPass")return this.renderPassEntries.screen.find(t=>t.element?.uuid===e.uuid);{const t=e.outputTarget?"renderTarget":"screen";return this.renderPassEntries[t].find(s=>[...s.stack.unProjected.opaque,...s.stack.unProjected.transparent,...s.stack.projected.opaque,...s.stack.projected.transparent].some(i=>i.uuid===e.uuid))}}renderSinglePassEntry(e,t){const s=t.renderPass.updateView(t.renderTexture?.texture);t.onBeforeRenderPass&&t.onBeforeRenderPass(e,s);const i=e.beginRenderPass(t.renderPass.descriptor);!this.renderer.production&&i.pushDebugGroup(t.element?`${t.element.options.label} render pass using ${t.renderPass.options.label} descriptor`:`Render stack pass using ${t.renderPass.options.label}${t.renderTexture?" onto "+t.renderTexture.options.label:""}`),t.element?t.element.render(i):t.stack&&(t.stack.unProjected.opaque.forEach(r=>r.render(i)),t.stack.unProjected.transparent.forEach(r=>r.render(i)),(t.stack.projected.opaque.length||t.stack.projected.transparent.length)&&(this.renderer.cameraBindGroup&&i.setBindGroup(this.renderer.cameraBindGroup.index,this.renderer.cameraBindGroup.bindGroup),t.stack.projected.opaque.forEach(r=>r.render(i)),t.stack.projected.transparent.forEach(r=>r.render(i)))),!this.renderer.production&&i.popDebugGroup(),i.end(),t.onAfterRenderPass&&t.onAfterRenderPass(e,s),this.renderer.pipelineManager.resetCurrentPipeline()}render(e){this.computePassEntries.forEach(t=>{const s=e.beginComputePass();t.render(s),s.end(),t.copyBufferToResult(e),this.renderer.pipelineManager.resetCurrentPipeline()});for(const t in this.renderPassEntries){let s=0;this.renderPassEntries[t].forEach(i=>{this.getRenderPassEntryLength(i)&&(i.renderPass.setLoadOp(t==="screen"&&s!==0?"load":"clear"),s++,this.renderSinglePassEntry(e,i))})}}}class ze{constructor(e,{label:t="Render Pass",sampleCount:s=4,qualityRatio:i=1,useColorAttachments:r=!0,shouldUpdateView:n=!0,loadOp:a="clear",storeOp:h="store",clearValue:u=[0,0,0,0],targetFormat:d,colorAttachments:l=[],useDepth:c=!0,depthTexture:p=null,depthLoadOp:m="clear",depthStoreOp:b="store",depthClearValue:x=1,depthFormat:g="depth24plus"}={}){if(e=e&&e.renderer||e,z(e,"RenderPass"),this.type="RenderPass",this.uuid=D(),this.renderer=e,r){const T={loadOp:a,storeOp:h,clearValue:u,targetFormat:d??this.renderer.options.preferredFormat};l.length?l=l.map(R=>({...T,...R})):l=[T]}this.options={label:t,sampleCount:s,qualityRatio:i,useColorAttachments:r,shouldUpdateView:n,loadOp:a,storeOp:h,clearValue:u,targetFormat:d??this.renderer.options.preferredFormat,colorAttachments:l,useDepth:c,...p!==void 0&&{depthTexture:p},depthLoadOp:m,depthStoreOp:b,depthClearValue:x,depthFormat:g},this.setClearValue(u),this.options.useDepth&&this.createDepthTexture(),this.viewTextures=[],this.options.useColorAttachments&&(!this.options.shouldUpdateView||this.options.sampleCount>1)&&this.createViewTextures(),this.setRenderPassDescriptor()}createDepthTexture(){this.options.depthTexture?(this.depthTexture=this.options.depthTexture,this.options.depthFormat=this.options.depthTexture.options.format):this.depthTexture=new J(this.renderer,{label:this.options.label+" depth texture",name:"depthTexture",usage:"depth",format:this.options.depthFormat,sampleCount:this.options.sampleCount,qualityRatio:this.options.qualityRatio})}createViewTextures(){this.options.colorAttachments.forEach((e,t)=>{this.viewTextures.push(new J(this.renderer,{label:`${this.options.label} colorAttachment[${t}] view texture`,name:`colorAttachment${t}ViewTexture`,format:e.targetFormat,sampleCount:this.options.sampleCount,qualityRatio:this.options.qualityRatio}))})}setRenderPassDescriptor(){this.descriptor={label:this.options.label+" descriptor",colorAttachments:this.options.colorAttachments.map((e,t)=>({view:this.viewTextures[t]?.texture.createView({label:this.viewTextures[t]?.texture.label+" view"}),clearValue:e.clearValue,loadOp:e.loadOp,storeOp:e.storeOp})),...this.options.useDepth&&{depthStencilAttachment:{view:this.depthTexture.texture.createView({label:this.depthTexture.texture.label+" view"}),depthClearValue:this.options.depthClearValue,depthLoadOp:this.options.depthLoadOp,depthStoreOp:this.options.depthStoreOp}}}}resize(){this.options.useDepth&&(this.descriptor.depthStencilAttachment.view=this.depthTexture.texture.createView({label:this.depthTexture.options.label+" view"})),this.viewTextures.forEach((e,t)=>{this.descriptor.colorAttachments[t].view=e.texture.createView({label:e.options.label+" view"})})}setLoadOp(e="clear",t=0){this.options.loadOp=e,this.options.useColorAttachments&&this.descriptor&&this.descriptor.colorAttachments&&this.descriptor.colorAttachments[t]&&(this.descriptor.colorAttachments[t].loadOp=e)}setDepthLoadOp(e="clear"){this.options.depthLoadOp=e,this.options.useDepth&&this.descriptor.depthStencilAttachment&&(this.descriptor.depthStencilAttachment.depthLoadOp=e)}setClearValue(e=[0,0,0,0],t=0){if(this.renderer.alphaMode==="premultiplied"){const s=e[3];e[0]=Math.min(e[0],s),e[1]=Math.min(e[1],s),e[2]=Math.min(e[2],s)}else this.options.clearValue=e;this.descriptor&&this.descriptor.colorAttachments&&this.descriptor.colorAttachments[t]&&(this.descriptor.colorAttachments[t].clearValue=e)}updateView(e=null){return!this.options.colorAttachments.length||!this.options.shouldUpdateView||(e||(e=this.renderer.context.getCurrentTexture(),e.label=`${this.renderer.type} context current texture`),this.options.sampleCount>1?(this.descriptor.colorAttachments[0].view=this.viewTextures[0].texture.createView({label:this.viewTextures[0].options.label+" view"}),this.descriptor.colorAttachments[0].resolveTarget=e.createView({label:e.label+" resolve target view"})):this.descriptor.colorAttachments[0].view=e.createView({label:e.label+" view"})),e}destroy(){this.viewTextures.forEach(e=>e.destroy()),!this.options.depthTexture&&this.depthTexture&&this.depthTexture.destroy()}}var At=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},Ut=(o,e,t)=>(At(o,e,"read from private field"),t?t.call(o):e.get(o)),gs=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},ys=(o,e,t,s)=>(At(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),xs=(o,e,t,s)=>({set _(i){ys(o,e,i,t)},get _(){return Ut(o,e,s)}}),Oe;class Ae{constructor(){gs(this,Oe,0),this.queue=[]}add(e=i=>{},{order:t=this.queue.length,once:s=!1}={}){const i={callback:e,order:t,once:s,id:Ut(this,Oe)};return xs(this,Oe)._++,this.queue.push(i),this.queue.sort((r,n)=>r.order-n.order),i.id}remove(e=0){this.queue=this.queue.filter(t=>t.id!==e)}execute(e){this.queue.forEach(t=>{t.callback(e),t.once&&this.remove(t.id)})}}Oe=new WeakMap;class st{constructor({deviceManager:e,container:t,pixelRatio:s=1,preferredFormat:i,alphaMode:r="premultiplied",renderPass:n}){this._onBeforeRenderCallback=h=>{},this._onAfterRenderCallback=h=>{},this._onAfterResizeCallback=()=>{},this.type="GPURenderer",this.uuid=D(),this.deviceManager=e,this.deviceManager.addRenderer(this),n={useDepth:!0,sampleCount:4,clearValue:[0,0,0,0],...n},i=i??this.deviceManager.gpu?.getPreferredCanvasFormat(),this.options={deviceManager:e,container:t,pixelRatio:s,preferredFormat:i,alphaMode:r,renderPass:n},this.pixelRatio=s??window.devicePixelRatio??1,this.alphaMode=r,this.setTasksQueues(),this.setRendererObjects();const a=t instanceof HTMLCanvasElement;this.canvas=a?t:document.createElement("canvas"),this.domElement=new tt({element:t,priority:5,onSizeChanged:h=>this.resize(h)}),a||this.domElement.element.appendChild(this.canvas),this.deviceManager.device&&this.setContext()}setSize(e){this.canvas.style.width=Math.floor(e.width)+"px",this.canvas.style.height=Math.floor(e.height)+"px",this.canvas.width=this.getScaledDisplayBoundingRect(e).width,this.canvas.height=this.getScaledDisplayBoundingRect(e).height}resize(e=null){!this.domElement&&!e||(e||(e=this.domElement.element.getBoundingClientRect()),this.setSize(e),this.onResize(),this._onAfterResizeCallback&&this._onAfterResizeCallback())}onResize(){this.renderTextures.forEach(e=>{e.resize()}),this.renderPass?.resize(),this.postProcessingPass?.resize(),this.renderTargets.forEach(e=>e.resize()),this.computePasses.forEach(e=>e.resize()),this.pingPongPlanes.forEach(e=>e.resize(this.boundingRect)),this.shaderPasses.forEach(e=>e.resize(this.boundingRect)),this.meshes.forEach(e=>{"domElement"in e?this.onBeforeCommandEncoderCreation.add(()=>{e.domElement.isResizing||e.domElement.setSize()},{once:!0}):e.resize(this.boundingRect)})}get boundingRect(){if(this.domElement.boundingRect)return this.domElement.boundingRect;{const e=this.domElement.element?.getBoundingClientRect();return{top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width,height:e.height,x:e.x,y:e.y}}}get displayBoundingRect(){return this.getScaledDisplayBoundingRect(this.boundingRect)}getScaledDisplayBoundingRect(e){const t=window.devicePixelRatio??1,s=this.pixelRatio/t,i=Object.keys(e).reduce((r,n)=>({...r,[n]:e[n]*s}),{x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0});return this.device&&(i.width=Math.min(this.device.limits.maxTextureDimension2D,i.width),i.height=Math.min(this.device.limits.maxTextureDimension2D,i.height),i.right=Math.min(i.width+i.left,i.right),i.bottom=Math.min(i.height+i.top,i.bottom)),i}get device(){return this.deviceManager.device}get ready(){return this.deviceManager.ready&&!!this.context&&!!this.canvas.style.width}get production(){return this.deviceManager.production}get samplers(){return this.deviceManager.samplers}get buffers(){return this.deviceManager.buffers}get pipelineManager(){return this.deviceManager.pipelineManager}get deviceRenderedObjects(){return this.deviceManager.deviceRenderedObjects}configureContext(){this.context.configure({device:this.device,format:this.options.preferredFormat,alphaMode:this.alphaMode,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST})}setContext(){this.context=this.canvas.getContext("webgpu"),this.device&&(this.configureContext(),this.setMainRenderPasses(),this.setScene())}loseContext(){this.renderedObjects.forEach(e=>e.loseContext())}restoreContext(){this.configureContext(),this.renderTextures.forEach(e=>{e.createTexture()}),this.renderPass?.resize(),this.postProcessingPass?.resize(),this.renderTargets.forEach(e=>e.resize()),this.renderedObjects.forEach(e=>e.restoreContext())}setMainRenderPasses(){this.renderPass=new ze(this,{label:"Main render pass",targetFormat:this.options.preferredFormat,...this.options.renderPass}),this.postProcessingPass=new ze(this,{label:"Post processing render pass",targetFormat:this.options.preferredFormat,useDepth:!1,sampleCount:1})}setScene(){this.scene=new Ot({renderer:this})}createBuffer(e){const t=this.device?.createBuffer(e);return this.deviceManager.addBuffer(t),t}removeBuffer(e,t){this.deviceManager.removeBuffer(e,t)}queueWriteBuffer(e,t,s){this.device?.queue.writeBuffer(e,t,s)}copyBufferToBuffer({srcBuffer:e,dstBuffer:t,commandEncoder:s}){if(!e)return U(`${this.type}: cannot copy to buffer because the source buffer has not been provided`),null;if(t||(t=this.createBuffer({label:this.type+": destination copy buffer from: "+e.label,size:e.size,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST})),e.mapState!=="unmapped"){U(`${this.type}: Cannot copy from ${e} because it is currently mapped`);return}if(t.mapState!=="unmapped"){U(`${this.type}: Cannot copy from ${t} because it is currently mapped`);return}const i=!!s;if(i||(s=this.device?.createCommandEncoder({label:"Copy buffer command encoder"}),!this.production&&s.pushDebugGroup("Copy buffer command encoder")),s.copyBufferToBuffer(e,0,t,0,t.size),!i){!this.production&&s.popDebugGroup();const r=s.finish();this.device?.queue.submit([r])}return t}get bindGroups(){return this.deviceManager.bindGroups}addBindGroup(e){this.deviceManager.addBindGroup(e)}removeBindGroup(e){this.deviceManager.removeBindGroup(e)}createBindGroupLayout(e){return this.device?.createBindGroupLayout(e)}createBindGroup(e){return this.device?.createBindGroup(e)}createShaderModule(e){return this.device?.createShaderModule(e)}createPipelineLayout(e){return this.device?.createPipelineLayout(e)}createRenderPipeline(e){return this.device?.createRenderPipeline(e)}async createRenderPipelineAsync(e){return await this.device?.createRenderPipelineAsync(e)}createComputePipeline(e){return this.device?.createComputePipeline(e)}async createComputePipelineAsync(e){return await this.device?.createComputePipelineAsync(e)}get textures(){return this.deviceManager.textures}addTexture(e){this.deviceManager.addTexture(e)}removeTexture(e){this.deviceManager.removeTexture(e)}addRenderTexture(e){this.renderTextures.push(e)}removeRenderTexture(e){this.renderTextures=this.renderTextures.filter(t=>t.uuid!==e.uuid)}createTexture(e){return this.device?.createTexture(e)}uploadTexture(e){this.deviceManager.uploadTexture(e)}importExternalTexture(e){return this.device?.importExternalTexture({source:e})}createSampler(e){const t=this.samplers.find(s=>JSON.stringify(s.options)===JSON.stringify(e.options)&&s.sampler);if(t)return t.sampler;{const{type:s,...i}=e.options,r=this.device?.createSampler({label:e.label,...i});return this.deviceManager.addSampler(e),r}}removeSampler(e){this.deviceManager.removeSampler(e)}setTasksQueues(){this.onBeforeCommandEncoderCreation=new Ae,this.onBeforeRenderScene=new Ae,this.onAfterRenderScene=new Ae,this.onAfterCommandEncoderSubmission=new Ae}setRendererObjects(){this.computePasses=[],this.pingPongPlanes=[],this.shaderPasses=[],this.renderTargets=[],this.meshes=[],this.renderTextures=[]}get renderedObjects(){return[...this.computePasses,...this.meshes,...this.shaderPasses,...this.pingPongPlanes]}getObjectsByBindGroup(e){return this.deviceRenderedObjects.filter(t=>[...t.material.bindGroups,...t.material.inputsBindGroups,...t.material.clonedBindGroups].some(s=>s.uuid===e.uuid))}getObjectsByTexture(e){return this.deviceRenderedObjects.filter(t=>[...t.material.textures,...t.material.renderTextures].some(s=>s.uuid===e.uuid))}onBeforeRender(e){return e&&(this._onBeforeRenderCallback=e),this}onAfterRender(e){return e&&(this._onAfterRenderCallback=e),this}onAfterResize(e){return e&&(this._onAfterResizeCallback=e),this}renderSingleComputePass(e,t){const s=e.beginComputePass();t.render(s),s.end(),t.copyBufferToResult(e)}renderSingleMesh(e,t){const s=e.beginRenderPass(this.renderPass.descriptor);t.render(s),s.end()}renderOnce(e){const t=this.device?.createCommandEncoder({label:"Render once command encoder"});!this.production&&t.pushDebugGroup("Render once command encoder"),this.pipelineManager.resetCurrentPipeline(),e.forEach(i=>{i.type==="ComputePass"?this.renderSingleComputePass(t,i):this.renderSingleMesh(t,i)}),!this.production&&t.popDebugGroup();const s=t.finish();this.device?.queue.submit([s]),this.pipelineManager.resetCurrentPipeline()}forceClear(e){const t=!!e;if(t||(e=this.device?.createCommandEncoder({label:"Force clear command encoder"}),!this.production&&e.pushDebugGroup("Force clear command encoder")),this.renderPass.updateView(),e.beginRenderPass(this.renderPass.descriptor).end(),!t){!this.production&&e.popDebugGroup();const i=e.finish();this.device?.queue.submit([i])}}onBeforeCommandEncoder(){this.ready&&this.onBeforeCommandEncoderCreation.execute()}onAfterCommandEncoder(){this.ready&&this.onAfterCommandEncoderSubmission.execute()}render(e){this.ready&&(this._onBeforeRenderCallback&&this._onBeforeRenderCallback(e),this.onBeforeRenderScene.execute(e),this.scene?.render(e),this._onAfterRenderCallback&&this._onAfterRenderCallback(e),this.onAfterRenderScene.execute(e))}destroy(){this.domElement?.destroy(),this.renderPass?.destroy(),this.postProcessingPass?.destroy(),this.renderTargets.forEach(e=>e.destroy()),this.renderedObjects.forEach(e=>e.remove()),this.renderTextures.forEach(e=>e.destroy()),this.context?.unconfigure()}}class it extends st{constructor({deviceManager:e,container:t,pixelRatio:s=1,preferredFormat:i,alphaMode:r="premultiplied",renderPass:n,camera:a={}}){super({deviceManager:e,container:t,pixelRatio:s,preferredFormat:i,alphaMode:r,renderPass:n}),this.type="GPUCameraRenderer",a={fov:50,near:.1,far:150,...a},this.options={...this.options,camera:a},this.setCamera(a),this.setCameraBindGroupAndBinding()}loseContext(){super.loseContext(),this.cameraBindGroup.loseContext()}async restoreContext(){return this.cameraBufferBinding.shouldUpdate=!0,super.restoreContext()}setCamera(e){const t=this.boundingRect?this.boundingRect.width:1,s=this.boundingRect?this.boundingRect.height:1;this.camera=new dt({fov:e.fov,near:e.near,far:e.far,width:t,height:s,pixelRatio:this.pixelRatio,onMatricesChanged:()=>{this.onCameraMatricesChanged()}})}onCameraMatricesChanged(){this.updateCameraBindings(),this.meshes.forEach(e=>{"modelViewMatrix"in e&&e.shouldUpdateMatrixStack()})}setCameraBindGroupAndBinding(){this.cameraBufferBinding=new ne({label:"Camera",name:"camera",visibility:"vertex",struct:{model:{name:"model",type:"mat4x4f",value:this.camera.modelMatrix},view:{name:"view",type:"mat4x4f",value:this.camera.viewMatrix},projection:{name:"projection",type:"mat4x4f",value:this.camera.projectionMatrix}}}),this.cameraBindGroup=new ge(this,{label:"Camera Uniform bind group",bindings:[this.cameraBufferBinding]})}setCameraBindGroup(){this.cameraBindGroup&&this.cameraBindGroup.shouldCreateBindGroup&&(this.cameraBindGroup.setIndex(0),this.cameraBindGroup.createBindGroup())}updateCameraBindings(){this.cameraBufferBinding?.shouldUpdateBinding("model"),this.cameraBufferBinding?.shouldUpdateBinding("view"),this.cameraBufferBinding?.shouldUpdateBinding("projection")}getObjectsByBindGroup(e){return this.deviceRenderedObjects.filter(t=>[...t.material.bindGroups,...t.material.inputsBindGroups,...t.material.clonedBindGroups,this.cameraBindGroup].some(s=>s.uuid===e.uuid))}setPerspective({fov:e,near:t,far:s}={}){this.camera?.setPerspective({fov:e,near:t,far:s,width:this.boundingRect.width,height:this.boundingRect.height,pixelRatio:this.pixelRatio})}setCameraPosition(e=new f(0,0,1)){this.camera.position.copy(e)}onResize(){super.onResize(),this.setPerspective(),this.updateCameraBindings()}updateCamera(){this.camera?.updateMatrixStack(),this.setCameraBindGroup(),this.cameraBindGroup?.update()}renderSingleMesh(e,t){const s=e.beginRenderPass(this.renderPass.descriptor);t.material.options.rendering.useProjection&&s.setBindGroup(this.cameraBindGroup.index,this.cameraBindGroup.bindGroup),t.render(s),s.end()}render(e){this.ready&&(this.updateCamera(),super.render(e))}destroy(){this.cameraBindGroup?.destroy(),super.destroy()}}class _t{constructor({label:e,production:t=!1,onError:s=()=>{},onDeviceLost:i=r=>{}}){this.index=0,this.label=e??"GPUDeviceManager instance",this.production=t,this.ready=!1,this.onError=s,this.onDeviceLost=i,this.gpu=navigator.gpu,this.setPipelineManager(),this.setDeviceObjects()}async setAdapterAndDevice(){await this.setAdapter(),await this.setDevice()}async init(){await this.setAdapterAndDevice(),this.device&&this.renderers.forEach(e=>{e.context||e.setContext()})}async setAdapter(){this.gpu||(this.onError(),V("GPURenderer: WebGPU is not supported on your browser/OS. No 'gpu' object in 'navigator'."));try{this.adapter=await this.gpu?.requestAdapter(),this.adapter?.requestAdapterInfo().then(e=>{this.adapterInfos=e})}catch{this.onError(),V("GPUDeviceManager: WebGPU is not supported on your browser/OS. 'requestAdapter' failed.")}}async setDevice(){try{this.device=await this.adapter?.requestDevice({label:this.label+" "+this.index}),this.device&&(this.ready=!0,this.index++)}catch(e){this.onError(),V(`${this.label}: WebGPU is not supported on your browser/OS. 'requestDevice' failed: ${e}`)}this.device?.lost.then(e=>{U(`${this.label}: WebGPU device was lost: ${e.message}`),this.loseDevice(),e.reason!=="destroyed"&&this.onDeviceLost(e)})}setPipelineManager(){this.pipelineManager=new zt}loseDevice(){this.ready=!1,this.samplers.forEach(e=>e.sampler=null),this.renderers.forEach(e=>e.loseContext()),this.buffers=[]}async restoreDevice(){await this.setAdapterAndDevice(),this.device&&(this.samplers.forEach(e=>{const{type:t,...s}=e.options;e.sampler=this.device.createSampler({label:e.label,...s})}),this.renderers.forEach(e=>e.restoreContext()))}setDeviceObjects(){this.renderers=[],this.bindGroups=[],this.buffers=[],this.samplers=[],this.textures=[],this.texturesQueue=[]}addRenderer(e){this.renderers.push(e)}removeRenderer(e){this.renderers=this.renderers.filter(t=>t.uuid!==e.uuid)}get deviceRenderedObjects(){return this.renderers.map(e=>e.renderedObjects).flat()}addBindGroup(e){this.bindGroups.find(t=>t.uuid===e.uuid)||this.bindGroups.push(e)}removeBindGroup(e){this.bindGroups=this.bindGroups.filter(t=>t.uuid!==e.uuid)}addBuffer(e){this.buffers.push(e)}removeBuffer(e,t){e&&(this.buffers=this.buffers.filter(s=>!(s.label===(t??e.label)&&s.size===e.size)))}addSampler(e){this.samplers.push(e)}removeSampler(e){this.samplers=this.samplers.filter(t=>t.uuid!==e.uuid)}addTexture(e){this.textures.push(e)}uploadTexture(e){if(e.source)try{this.device?.queue.copyExternalImageToTexture({source:e.source,flipY:e.options.flipY},{texture:e.texture,premultipliedAlpha:e.options.premultipliedAlpha},{width:e.size.width,height:e.size.height}),e.texture.mipLevelCount>1&&Wt(this.device,e.texture),this.texturesQueue.push(e)}catch({message:t}){V(`GPUDeviceManager: could not upload texture: ${e.options.name} because: ${t}`)}else this.device?.queue.writeTexture({texture:e.texture},new Uint8Array(e.options.placeholderColor),{bytesPerRow:e.size.width*4},{width:e.size.width,height:e.size.height})}removeTexture(e){this.textures=this.textures.filter(t=>t.uuid!==e.uuid)}render(){if(!this.ready)return;this.renderers.forEach(s=>s.onBeforeCommandEncoder());const e=this.device?.createCommandEncoder({label:this.label+" command encoder"});!this.production&&e.pushDebugGroup(this.label+" command encoder: main render loop"),this.renderers.forEach(s=>s.render(e)),!this.production&&e.popDebugGroup();const t=e.finish();this.device?.queue.submit([t]),this.textures.filter(s=>!s.parentMesh&&s.sourceLoaded&&!s.sourceUploaded).forEach(s=>this.uploadTexture(s)),this.texturesQueue.forEach(s=>{s.sourceUploaded=!0}),this.texturesQueue=[],this.renderers.forEach(s=>s.onAfterCommandEncoder())}destroy(){this.device?.destroy(),this.device=null,this.renderers.forEach(e=>e.destroy()),this.bindGroups.forEach(e=>e.destroy()),this.buffers.forEach(e=>e?.destroy()),this.textures.forEach(e=>e.destroy()),this.setDeviceObjects()}}var Ft=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},kt=(o,e,t)=>(Ft(o,e,"read from private field"),t?t.call(o):e.get(o)),bs=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},ws=(o,e,t,s)=>(Ft(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),de;class Dt{constructor(e,t={}){bs(this,de,!0),e=e&&e.renderer||e,z(e,"RenderTarget"),this.type="RenderTarget",this.renderer=e,this.uuid=D();const{label:s,targetFormat:i,depthTexture:r,autoRender:n,...a}=t;this.options={label:s,...a,...r&&{depthTexture:r},targetFormat:i??this.renderer.options.preferredFormat,autoRender:n===void 0?!0:n},n!==void 0&&ws(this,de,n),this.renderPass=new ze(this.renderer,{label:this.options.label?`${this.options.label} Render Pass`:"Render Target Render Pass",targetFormat:this.options.targetFormat,depthTexture:this.options.depthTexture??this.renderer.renderPass.depthTexture,...a}),a.useColorAttachments!==!1&&(this.renderTexture=new J(this.renderer,{label:this.options.label?`${this.options.label} Render Texture`:"Render Target render texture",name:"renderTexture",format:this.options.targetFormat,...this.options.qualityRatio!==void 0&&{qualityRatio:this.options.qualityRatio}})),this.addToScene()}addToScene(){this.renderer.renderTargets.push(this),kt(this,de)&&this.renderer.scene.addRenderTarget(this)}removeFromScene(){kt(this,de)&&this.renderer.scene.removeRenderTarget(this),this.renderer.renderTargets=this.renderer.renderTargets.filter(e=>e.uuid!==this.uuid)}resize(){this.renderPass.options.depthTexture.texture=this.options.depthTexture?this.options.depthTexture.texture:this.renderer.renderPass.depthTexture.texture,this.renderPass?.resize()}remove(){this.destroy()}destroy(){this.renderer.meshes.forEach(e=>{e.outputTarget&&e.outputTarget.uuid===this.uuid&&e.setOutputTarget(null)}),this.renderer.shaderPasses.forEach(e=>{e.outputTarget&&e.outputTarget.uuid===this.uuid&&(e.outputTarget=null,e.setOutputTarget(null))}),this.removeFromScene(),this.renderPass?.destroy(),this.renderTexture?.destroy()}}de=new WeakMap;var vs=` +`)}),this.shaders.compute.code=this.shaders.compute.head+this.options.shaders.compute.code}createShaders(){this.patchShaders(),this.shaders.compute.module=this.createShaderModule({code:this.shaders.compute.code,type:"compute"})}createPipelineDescriptor(){this.shaders.compute.module&&(this.descriptor={label:this.options.label,layout:this.layout,compute:{module:this.shaders.compute.module,entryPoint:this.options.shaders.compute.entryPoint}})}createComputePipeline(){if(this.shaders.compute.module)try{this.pipeline=this.renderer.createComputePipeline(this.descriptor)}catch(e){this.status.error=e,V(e)}}async createComputePipelineAsync(){if(this.shaders.compute.module)try{this.pipeline=await this.renderer.createComputePipelineAsync(this.descriptor),this.status.compiled=!0,this.status.compiling=!1,this.status.error=null}catch(e){this.status.error=e,V(e)}}async compilePipelineEntry(){super.compilePipelineEntry(),this.options.useAsync?await this.createComputePipelineAsync():(this.createComputePipeline(),this.status.compiled=!0,this.status.compiling=!1,this.status.error=null)}}class zt{constructor(){this.type="PipelineManager",this.currentPipelineIndex=null,this.pipelineEntries=[]}compareShaders(e,t){return e.code?.localeCompare(t.code)===0&&e.entryPoint===t.entryPoint}isSameRenderPipeline(e){return this.pipelineEntries.filter(t=>t instanceof Je).find(t=>{const{options:s}=t,{shaders:i,rendering:r}=e,n=this.compareShaders(i.vertex,s.shaders.vertex),a=!i.fragment&&!s.shaders.fragment||this.compareShaders(i.fragment,s.shaders.fragment);return!Object.keys(s.rendering).filter(u=>s.rendering[u]!==r[u]).length&&n&&a})}createRenderPipeline(e){const t=this.isSameRenderPipeline(e);if(t)return t;{const s=new Je(e);return this.pipelineEntries.push(s),s}}isSameComputePipeline(e){const{shaders:t}=e;return this.pipelineEntries.filter(s=>s instanceof Ke).find(s=>{const{options:i}=s;return this.compareShaders(t.compute,i.shaders.compute)})}createComputePipeline(e){const t=this.isSameComputePipeline(e);if(t)return t;{const s=new Ke(e);return this.pipelineEntries.push(s),s}}setCurrentPipeline(e,t){t.index!==this.currentPipelineIndex&&(e.setPipeline(t.pipeline),this.currentPipelineIndex=t.index)}resetCurrentPipeline(){this.currentPipelineIndex=null}}class ms{constructor(){this.shouldWatch=!0,this.entries=[],this.resizeObserver=new ResizeObserver(e=>{e.map(s=>this.entries.filter(i=>i.element.isSameNode(s.target))).flat().sort((s,i)=>i.priority-s.priority)?.forEach(s=>{s&&s.callback&&s.callback()})})}useObserver(e=!0){this.shouldWatch=e}observe({element:e,priority:t,callback:s}){if(!e||!this.shouldWatch)return;this.resizeObserver.observe(e);const i={element:e,priority:t,callback:s};this.entries.push(i)}unobserve(e){this.resizeObserver.unobserve(e),this.entries=this.entries.filter(t=>!t.element.isSameNode(e))}destroy(){this.resizeObserver.disconnect()}}const et=new ms;class tt{constructor({element:e=document.body,priority:t=1,onSizeChanged:s=(r=null)=>{},onPositionChanged:i=(r=null)=>{}}={}){if(typeof e=="string"){if(this.element=document.querySelector(e),!this.element){const r=typeof e=="string"?`'${e}' selector`:`${e} HTMLElement`;V(`DOMElement: corresponding ${r} not found.`)}}else this.element=e;this.priority=t,this.isResizing=!1,this.onSizeChanged=s,this.onPositionChanged=i,this.resizeManager=et,this.resizeManager.observe({element:this.element,priority:this.priority,callback:()=>{this.setSize()}}),this.setSize()}compareBoundingRect(e,t){return!["x","y","left","top","right","bottom","width","height"].some(s=>e[s]!==t[s])}get boundingRect(){return this._boundingRect}set boundingRect(e){const t=!!this.boundingRect&&this.compareBoundingRect(e,this.boundingRect);this._boundingRect={top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width,height:e.height,x:e.x,y:e.y},t||this.onSizeChanged(this.boundingRect)}updateScrollPosition(e={x:0,y:0}){this.isResizing||(this._boundingRect.top+=e.y,this._boundingRect.left+=e.x,(e.x||e.y)&&this.onPositionChanged(this.boundingRect))}setSize(e=null){this.element&&(this.boundingRect=e??this.element.getBoundingClientRect(),this.isResizing=!1)}destroy(){this.resizeManager.unobserve(this.element)}}class Ot{constructor({renderer:e}){e=e&&e.renderer||e,z(e,"Scene"),this.renderer=e,this.computePassEntries=[],this.renderPassEntries={pingPong:[],renderTarget:[],screen:[{renderPass:this.renderer.renderPass,renderTexture:null,onBeforeRenderPass:null,onAfterRenderPass:null,element:null,stack:{unProjected:{opaque:[],transparent:[]},projected:{opaque:[],transparent:[]}}}]}}getRenderPassEntryLength(e){return e?e.element?e.element.visible?1:0:e.stack.unProjected.opaque.length+e.stack.unProjected.transparent.length+e.stack.projected.opaque.length+e.stack.projected.transparent.length:0}addComputePass(e){this.computePassEntries.push(e),this.computePassEntries.sort((t,s)=>t.renderOrder!==s.renderOrder?t.renderOrder-s.renderOrder:t.index-s.index)}removeComputePass(e){this.computePassEntries=this.computePassEntries.filter(t=>t.uuid!==e.uuid)}addRenderTarget(e){this.renderPassEntries.renderTarget.find(t=>t.renderPass.uuid===e.renderPass.uuid)||this.renderPassEntries.renderTarget.push({renderPass:e.renderPass,renderTexture:e.renderTexture,onBeforeRenderPass:null,onAfterRenderPass:null,element:null,stack:{unProjected:{opaque:[],transparent:[]},projected:{opaque:[],transparent:[]}}})}removeRenderTarget(e){this.renderPassEntries.renderTarget=this.renderPassEntries.renderTarget.filter(t=>t.renderPass.uuid!==e.renderPass.uuid)}getMeshProjectionStack(e){const t=e.outputTarget?this.renderPassEntries.renderTarget.find(i=>i.renderPass.uuid===e.outputTarget.renderPass.uuid):this.renderPassEntries.screen[0],{stack:s}=t;return e.material.options.rendering.useProjection?s.projected:s.unProjected}addMesh(e){const t=this.getMeshProjectionStack(e),s=e.transparent?[...t.transparent]:[...t.opaque];let i=-1;for(let r=s.length-1;r>=0;r--)if(s[r].material.pipelineEntry.index===e.material.pipelineEntry.index){i=r+1;break}i=Math.max(0,i),s.splice(i,0,e),s.sort((r,n)=>r.index-n.index),(e.type==="DOMMesh"||e.type==="Plane")&&e.transparent&&s.sort((r,n)=>n.documentPosition.z-r.documentPosition.z),s.sort((r,n)=>r.renderOrder-n.renderOrder),e.transparent?t.transparent=s:t.opaque=s}removeMesh(e){const t=this.getMeshProjectionStack(e);e.transparent?t.transparent=t.transparent.filter(s=>s.uuid!==e.uuid):t.opaque=t.opaque.filter(s=>s.uuid!==e.uuid)}addShaderPass(e){const t=e.inputTarget||e.outputTarget?null:(r,n)=>{e.renderTexture&&n&&r.copyTextureToTexture({texture:n},{texture:e.renderTexture.texture},[e.renderTexture.size.width,e.renderTexture.size.height]),this.renderer.postProcessingPass.setLoadOp("clear")},s=!e.outputTarget&&e.options.copyOutputToRenderTexture?(r,n)=>{e.renderTexture&&n&&r.copyTextureToTexture({texture:n},{texture:e.renderTexture.texture},[e.renderTexture.size.width,e.renderTexture.size.height])}:null,i={renderPass:e.outputTarget?e.outputTarget.renderPass:this.renderer.postProcessingPass,renderTexture:e.outputTarget?e.outputTarget.renderTexture:null,onBeforeRenderPass:t,onAfterRenderPass:s,element:e,stack:null};this.renderPassEntries.screen.push(i),this.renderPassEntries.screen.sort((r,n)=>{const a=r.element&&!r.element.outputTarget,h=r.element?r.element.renderOrder:0,u=r.element?r.element.index:0,d=n.element&&!n.element.outputTarget,l=n.element?n.element.renderOrder:0,c=n.element?n.element.index:0;return a&&!d?1:!a&&d?-1:h!==l?h-l:u-c})}removeShaderPass(e){this.renderPassEntries.screen=this.renderPassEntries.screen.filter(t=>!t.element||t.element.uuid!==e.uuid)}addPingPongPlane(e){this.renderPassEntries.pingPong.push({renderPass:e.outputTarget.renderPass,renderTexture:e.outputTarget.renderTexture,onBeforeRenderPass:null,onAfterRenderPass:(t,s)=>{t.copyTextureToTexture({texture:s},{texture:e.renderTexture.texture},[e.renderTexture.size.width,e.renderTexture.size.height])},element:e,stack:null}),this.renderPassEntries.pingPong.sort((t,s)=>t.element.renderOrder-s.element.renderOrder)}removePingPongPlane(e){this.renderPassEntries.pingPong=this.renderPassEntries.pingPong.filter(t=>t.element.uuid!==e.uuid)}getObjectRenderPassEntry(e){if(e.type==="RenderTarget")return this.renderPassEntries.renderTarget.find(t=>t.renderPass.uuid===e.renderPass.uuid);if(e.type==="PingPongPlane")return this.renderPassEntries.pingPong.find(t=>t.element.uuid===e.uuid);if(e.type==="ShaderPass")return this.renderPassEntries.screen.find(t=>t.element?.uuid===e.uuid);{const t=e.outputTarget?"renderTarget":"screen";return this.renderPassEntries[t].find(s=>[...s.stack.unProjected.opaque,...s.stack.unProjected.transparent,...s.stack.projected.opaque,...s.stack.projected.transparent].some(i=>i.uuid===e.uuid))}}renderSinglePassEntry(e,t){const s=t.renderPass.updateView(t.renderTexture?.texture);t.onBeforeRenderPass&&t.onBeforeRenderPass(e,s);const i=e.beginRenderPass(t.renderPass.descriptor);!this.renderer.production&&i.pushDebugGroup(t.element?`${t.element.options.label} render pass using ${t.renderPass.options.label} descriptor`:`Render stack pass using ${t.renderPass.options.label}${t.renderTexture?" onto "+t.renderTexture.options.label:""}`),t.element?t.element.render(i):t.stack&&(t.stack.unProjected.opaque.forEach(r=>r.render(i)),t.stack.unProjected.transparent.forEach(r=>r.render(i)),(t.stack.projected.opaque.length||t.stack.projected.transparent.length)&&(this.renderer.cameraBindGroup&&i.setBindGroup(this.renderer.cameraBindGroup.index,this.renderer.cameraBindGroup.bindGroup),t.stack.projected.opaque.forEach(r=>r.render(i)),t.stack.projected.transparent.forEach(r=>r.render(i)))),!this.renderer.production&&i.popDebugGroup(),i.end(),t.onAfterRenderPass&&t.onAfterRenderPass(e,s),this.renderer.pipelineManager.resetCurrentPipeline()}render(e){this.computePassEntries.forEach(t=>{const s=e.beginComputePass();t.render(s),s.end(),t.copyBufferToResult(e),this.renderer.pipelineManager.resetCurrentPipeline()});for(const t in this.renderPassEntries){let s=0;this.renderPassEntries[t].forEach(i=>{this.getRenderPassEntryLength(i)&&(i.renderPass.setLoadOp(t==="screen"&&s!==0?"load":"clear"),s++,this.renderSinglePassEntry(e,i))})}}}class ze{constructor(e,{label:t="Render Pass",sampleCount:s=4,qualityRatio:i=1,useColorAttachments:r=!0,shouldUpdateView:n=!0,colorAttachments:a=[],useDepth:h=!0,depthTexture:u=null,depthLoadOp:d="clear",depthStoreOp:l="store",depthClearValue:c=1,depthFormat:p="depth24plus"}={}){if(e=e&&e.renderer||e,z(e,"RenderPass"),this.type="RenderPass",this.uuid=D(),this.renderer=e,r){const m={loadOp:"clear",storeOp:"store",clearValue:[0,0,0,0],targetFormat:this.renderer.options.preferredFormat};a.length?a=a.map(x=>({...m,...x})):a=[m]}this.options={label:t,sampleCount:s,qualityRatio:i,useColorAttachments:r,shouldUpdateView:n,colorAttachments:a,useDepth:h,...u!==void 0&&{depthTexture:u},depthLoadOp:d,depthStoreOp:l,depthClearValue:c,depthFormat:p},this.options.useDepth&&this.createDepthTexture(),this.viewTextures=[],this.options.useColorAttachments&&(!this.options.shouldUpdateView||this.options.sampleCount>1)&&this.createViewTextures(),this.setRenderPassDescriptor()}createDepthTexture(){this.options.depthTexture?(this.depthTexture=this.options.depthTexture,this.options.depthFormat=this.options.depthTexture.options.format):this.depthTexture=new J(this.renderer,{label:this.options.label+" depth texture",name:"depthTexture",usage:"depth",format:this.options.depthFormat,sampleCount:this.options.sampleCount,qualityRatio:this.options.qualityRatio})}createViewTextures(){this.options.colorAttachments.forEach((e,t)=>{this.viewTextures.push(new J(this.renderer,{label:`${this.options.label} colorAttachment[${t}] view texture`,name:`colorAttachment${t}ViewTexture`,format:e.targetFormat,sampleCount:this.options.sampleCount,qualityRatio:this.options.qualityRatio}))})}setRenderPassDescriptor(){this.descriptor={label:this.options.label+" descriptor",colorAttachments:this.options.colorAttachments.map((e,t)=>({view:this.viewTextures[t]?.texture.createView({label:this.viewTextures[t]?.texture.label+" view"}),clearValue:e.clearValue,loadOp:e.loadOp,storeOp:e.storeOp})),...this.options.useDepth&&{depthStencilAttachment:{view:this.depthTexture.texture.createView({label:this.depthTexture.texture.label+" view"}),depthClearValue:this.options.depthClearValue,depthLoadOp:this.options.depthLoadOp,depthStoreOp:this.options.depthStoreOp}}}}resize(){this.options.useDepth&&(this.descriptor.depthStencilAttachment.view=this.depthTexture.texture.createView({label:this.depthTexture.options.label+" view"})),this.viewTextures.forEach((e,t)=>{this.descriptor.colorAttachments[t].view=e.texture.createView({label:e.options.label+" view"})})}setLoadOp(e="clear",t=0){this.options.useColorAttachments&&(this.options.colorAttachments[t]&&(this.options.colorAttachments[t].loadOp=e),this.descriptor&&this.descriptor.colorAttachments&&this.descriptor.colorAttachments[t]&&(this.descriptor.colorAttachments[t].loadOp=e))}setDepthLoadOp(e="clear"){this.options.depthLoadOp=e,this.options.useDepth&&this.descriptor.depthStencilAttachment&&(this.descriptor.depthStencilAttachment.depthLoadOp=e)}setClearValue(e=[0,0,0,0],t=0){if(this.options.useColorAttachments){if(this.renderer.alphaMode==="premultiplied"){const s=e[3];e[0]=Math.min(e[0],s),e[1]=Math.min(e[1],s),e[2]=Math.min(e[2],s)}this.options.colorAttachments[t]&&(this.options.colorAttachments[t].clearValue=e),this.descriptor&&this.descriptor.colorAttachments&&this.descriptor.colorAttachments[t]&&(this.descriptor.colorAttachments[t].clearValue=e)}}updateView(e=null){return!this.options.colorAttachments.length||!this.options.shouldUpdateView||(e||(e=this.renderer.context.getCurrentTexture(),e.label=`${this.renderer.type} context current texture`),this.options.sampleCount>1?(this.descriptor.colorAttachments[0].view=this.viewTextures[0].texture.createView({label:this.viewTextures[0].options.label+" view"}),this.descriptor.colorAttachments[0].resolveTarget=e.createView({label:e.label+" resolve target view"})):this.descriptor.colorAttachments[0].view=e.createView({label:e.label+" view"})),e}destroy(){this.viewTextures.forEach(e=>e.destroy()),!this.options.depthTexture&&this.depthTexture&&this.depthTexture.destroy()}}var At=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},Ut=(o,e,t)=>(At(o,e,"read from private field"),t?t.call(o):e.get(o)),gs=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},ys=(o,e,t,s)=>(At(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),xs=(o,e,t,s)=>({set _(i){ys(o,e,i,t)},get _(){return Ut(o,e,s)}}),Oe;class Ae{constructor(){gs(this,Oe,0),this.queue=[]}add(e=i=>{},{order:t=this.queue.length,once:s=!1}={}){const i={callback:e,order:t,once:s,id:Ut(this,Oe)};return xs(this,Oe)._++,this.queue.push(i),this.queue.sort((r,n)=>r.order-n.order),i.id}remove(e=0){this.queue=this.queue.filter(t=>t.id!==e)}execute(e){this.queue.forEach(t=>{t.callback(e),t.once&&this.remove(t.id)})}}Oe=new WeakMap;class st{constructor({deviceManager:e,container:t,pixelRatio:s=1,preferredFormat:i,alphaMode:r="premultiplied",renderPass:n}){this._onBeforeRenderCallback=h=>{},this._onAfterRenderCallback=h=>{},this._onAfterResizeCallback=()=>{},this.type="GPURenderer",this.uuid=D(),this.deviceManager=e,this.deviceManager.addRenderer(this),n={useDepth:!0,sampleCount:4,clearValue:[0,0,0,0],...n},i=i??this.deviceManager.gpu?.getPreferredCanvasFormat(),this.options={deviceManager:e,container:t,pixelRatio:s,preferredFormat:i,alphaMode:r,renderPass:n},this.pixelRatio=s??window.devicePixelRatio??1,this.alphaMode=r,this.setTasksQueues(),this.setRendererObjects();const a=t instanceof HTMLCanvasElement;this.canvas=a?t:document.createElement("canvas"),this.domElement=new tt({element:t,priority:5,onSizeChanged:h=>this.resize(h)}),a||this.domElement.element.appendChild(this.canvas),this.deviceManager.device&&this.setContext()}setSize(e){this.canvas.style.width=Math.floor(e.width)+"px",this.canvas.style.height=Math.floor(e.height)+"px",this.canvas.width=this.getScaledDisplayBoundingRect(e).width,this.canvas.height=this.getScaledDisplayBoundingRect(e).height}resize(e=null){!this.domElement&&!e||(e||(e=this.domElement.element.getBoundingClientRect()),this.setSize(e),this.onResize(),this._onAfterResizeCallback&&this._onAfterResizeCallback())}onResize(){this.renderTextures.forEach(e=>{e.resize()}),this.renderPass?.resize(),this.postProcessingPass?.resize(),this.renderTargets.forEach(e=>e.resize()),this.computePasses.forEach(e=>e.resize()),this.pingPongPlanes.forEach(e=>e.resize(this.boundingRect)),this.shaderPasses.forEach(e=>e.resize(this.boundingRect)),this.meshes.forEach(e=>{"domElement"in e?this.onBeforeCommandEncoderCreation.add(()=>{e.domElement.isResizing||e.domElement.setSize()},{once:!0}):e.resize(this.boundingRect)})}get boundingRect(){if(this.domElement.boundingRect)return this.domElement.boundingRect;{const e=this.domElement.element?.getBoundingClientRect();return{top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width,height:e.height,x:e.x,y:e.y}}}get displayBoundingRect(){return this.getScaledDisplayBoundingRect(this.boundingRect)}getScaledDisplayBoundingRect(e){const t=window.devicePixelRatio??1,s=this.pixelRatio/t,i=Object.keys(e).reduce((r,n)=>({...r,[n]:e[n]*s}),{x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0});return this.device&&(i.width=Math.min(this.device.limits.maxTextureDimension2D,i.width),i.height=Math.min(this.device.limits.maxTextureDimension2D,i.height),i.right=Math.min(i.width+i.left,i.right),i.bottom=Math.min(i.height+i.top,i.bottom)),i}get device(){return this.deviceManager.device}get ready(){return this.deviceManager.ready&&!!this.context&&!!this.canvas.style.width}get production(){return this.deviceManager.production}get samplers(){return this.deviceManager.samplers}get buffers(){return this.deviceManager.buffers}get pipelineManager(){return this.deviceManager.pipelineManager}get deviceRenderedObjects(){return this.deviceManager.deviceRenderedObjects}configureContext(){this.context.configure({device:this.device,format:this.options.preferredFormat,alphaMode:this.alphaMode,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST})}setContext(){this.context=this.canvas.getContext("webgpu"),this.device&&(this.configureContext(),this.setMainRenderPasses(),this.setScene())}loseContext(){this.renderedObjects.forEach(e=>e.loseContext())}restoreContext(){this.configureContext(),this.renderTextures.forEach(e=>{e.createTexture()}),this.renderPass?.resize(),this.postProcessingPass?.resize(),this.renderTargets.forEach(e=>e.resize()),this.renderedObjects.forEach(e=>e.restoreContext())}setMainRenderPasses(){this.renderPass=new ze(this,{label:"Main render pass",...this.options.renderPass}),this.postProcessingPass=new ze(this,{label:"Post processing render pass",useDepth:!1,sampleCount:1})}setScene(){this.scene=new Ot({renderer:this})}createBuffer(e){const t=this.device?.createBuffer(e);return this.deviceManager.addBuffer(t),t}removeBuffer(e,t){this.deviceManager.removeBuffer(e,t)}queueWriteBuffer(e,t,s){this.device?.queue.writeBuffer(e,t,s)}copyBufferToBuffer({srcBuffer:e,dstBuffer:t,commandEncoder:s}){if(!e)return U(`${this.type}: cannot copy to buffer because the source buffer has not been provided`),null;if(t||(t=this.createBuffer({label:this.type+": destination copy buffer from: "+e.label,size:e.size,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST})),e.mapState!=="unmapped"){U(`${this.type}: Cannot copy from ${e} because it is currently mapped`);return}if(t.mapState!=="unmapped"){U(`${this.type}: Cannot copy from ${t} because it is currently mapped`);return}const i=!!s;if(i||(s=this.device?.createCommandEncoder({label:"Copy buffer command encoder"}),!this.production&&s.pushDebugGroup("Copy buffer command encoder")),s.copyBufferToBuffer(e,0,t,0,t.size),!i){!this.production&&s.popDebugGroup();const r=s.finish();this.device?.queue.submit([r])}return t}get bindGroups(){return this.deviceManager.bindGroups}addBindGroup(e){this.deviceManager.addBindGroup(e)}removeBindGroup(e){this.deviceManager.removeBindGroup(e)}createBindGroupLayout(e){return this.device?.createBindGroupLayout(e)}createBindGroup(e){return this.device?.createBindGroup(e)}createShaderModule(e){return this.device?.createShaderModule(e)}createPipelineLayout(e){return this.device?.createPipelineLayout(e)}createRenderPipeline(e){return this.device?.createRenderPipeline(e)}async createRenderPipelineAsync(e){return await this.device?.createRenderPipelineAsync(e)}createComputePipeline(e){return this.device?.createComputePipeline(e)}async createComputePipelineAsync(e){return await this.device?.createComputePipelineAsync(e)}get textures(){return this.deviceManager.textures}addTexture(e){this.deviceManager.addTexture(e)}removeTexture(e){this.deviceManager.removeTexture(e)}addRenderTexture(e){this.renderTextures.push(e)}removeRenderTexture(e){this.renderTextures=this.renderTextures.filter(t=>t.uuid!==e.uuid)}createTexture(e){return this.device?.createTexture(e)}uploadTexture(e){this.deviceManager.uploadTexture(e)}importExternalTexture(e){return this.device?.importExternalTexture({source:e})}createSampler(e){const t=this.samplers.find(s=>JSON.stringify(s.options)===JSON.stringify(e.options)&&s.sampler);if(t)return t.sampler;{const{type:s,...i}=e.options,r=this.device?.createSampler({label:e.label,...i});return this.deviceManager.addSampler(e),r}}removeSampler(e){this.deviceManager.removeSampler(e)}setTasksQueues(){this.onBeforeCommandEncoderCreation=new Ae,this.onBeforeRenderScene=new Ae,this.onAfterRenderScene=new Ae,this.onAfterCommandEncoderSubmission=new Ae}setRendererObjects(){this.computePasses=[],this.pingPongPlanes=[],this.shaderPasses=[],this.renderTargets=[],this.meshes=[],this.renderTextures=[]}get renderedObjects(){return[...this.computePasses,...this.meshes,...this.shaderPasses,...this.pingPongPlanes]}getObjectsByBindGroup(e){return this.deviceRenderedObjects.filter(t=>[...t.material.bindGroups,...t.material.inputsBindGroups,...t.material.clonedBindGroups].some(s=>s.uuid===e.uuid))}getObjectsByTexture(e){return this.deviceRenderedObjects.filter(t=>[...t.material.textures,...t.material.renderTextures].some(s=>s.uuid===e.uuid))}onBeforeRender(e){return e&&(this._onBeforeRenderCallback=e),this}onAfterRender(e){return e&&(this._onAfterRenderCallback=e),this}onAfterResize(e){return e&&(this._onAfterResizeCallback=e),this}renderSingleComputePass(e,t){const s=e.beginComputePass();t.render(s),s.end(),t.copyBufferToResult(e)}renderSingleMesh(e,t){const s=e.beginRenderPass(this.renderPass.descriptor);t.render(s),s.end()}renderOnce(e){const t=this.device?.createCommandEncoder({label:"Render once command encoder"});!this.production&&t.pushDebugGroup("Render once command encoder"),this.pipelineManager.resetCurrentPipeline(),e.forEach(i=>{i.type==="ComputePass"?this.renderSingleComputePass(t,i):this.renderSingleMesh(t,i)}),!this.production&&t.popDebugGroup();const s=t.finish();this.device?.queue.submit([s]),this.pipelineManager.resetCurrentPipeline()}forceClear(e){const t=!!e;if(t||(e=this.device?.createCommandEncoder({label:"Force clear command encoder"}),!this.production&&e.pushDebugGroup("Force clear command encoder")),this.renderPass.updateView(),e.beginRenderPass(this.renderPass.descriptor).end(),!t){!this.production&&e.popDebugGroup();const i=e.finish();this.device?.queue.submit([i])}}onBeforeCommandEncoder(){this.ready&&this.onBeforeCommandEncoderCreation.execute()}onAfterCommandEncoder(){this.ready&&this.onAfterCommandEncoderSubmission.execute()}render(e){this.ready&&(this._onBeforeRenderCallback&&this._onBeforeRenderCallback(e),this.onBeforeRenderScene.execute(e),this.scene?.render(e),this._onAfterRenderCallback&&this._onAfterRenderCallback(e),this.onAfterRenderScene.execute(e))}destroy(){this.domElement?.destroy(),this.renderPass?.destroy(),this.postProcessingPass?.destroy(),this.renderTargets.forEach(e=>e.destroy()),this.renderedObjects.forEach(e=>e.remove()),this.renderTextures.forEach(e=>e.destroy()),this.context?.unconfigure()}}class it extends st{constructor({deviceManager:e,container:t,pixelRatio:s=1,preferredFormat:i,alphaMode:r="premultiplied",renderPass:n,camera:a={}}){super({deviceManager:e,container:t,pixelRatio:s,preferredFormat:i,alphaMode:r,renderPass:n}),this.type="GPUCameraRenderer",a={fov:50,near:.1,far:150,...a},this.options={...this.options,camera:a},this.setCamera(a),this.setCameraBindGroupAndBinding()}loseContext(){super.loseContext(),this.cameraBindGroup.loseContext()}async restoreContext(){return this.cameraBufferBinding.shouldUpdate=!0,super.restoreContext()}setCamera(e){const t=this.boundingRect?this.boundingRect.width:1,s=this.boundingRect?this.boundingRect.height:1;this.camera=new dt({fov:e.fov,near:e.near,far:e.far,width:t,height:s,pixelRatio:this.pixelRatio,onMatricesChanged:()=>{this.onCameraMatricesChanged()}})}onCameraMatricesChanged(){this.updateCameraBindings(),this.meshes.forEach(e=>{"modelViewMatrix"in e&&e.shouldUpdateMatrixStack()})}setCameraBindGroupAndBinding(){this.cameraBufferBinding=new ne({label:"Camera",name:"camera",visibility:"vertex",struct:{model:{name:"model",type:"mat4x4f",value:this.camera.modelMatrix},view:{name:"view",type:"mat4x4f",value:this.camera.viewMatrix},projection:{name:"projection",type:"mat4x4f",value:this.camera.projectionMatrix}}}),this.cameraBindGroup=new ge(this,{label:"Camera Uniform bind group",bindings:[this.cameraBufferBinding]})}setCameraBindGroup(){this.cameraBindGroup&&this.cameraBindGroup.shouldCreateBindGroup&&(this.cameraBindGroup.setIndex(0),this.cameraBindGroup.createBindGroup())}updateCameraBindings(){this.cameraBufferBinding?.shouldUpdateBinding("model"),this.cameraBufferBinding?.shouldUpdateBinding("view"),this.cameraBufferBinding?.shouldUpdateBinding("projection")}getObjectsByBindGroup(e){return this.deviceRenderedObjects.filter(t=>[...t.material.bindGroups,...t.material.inputsBindGroups,...t.material.clonedBindGroups,this.cameraBindGroup].some(s=>s.uuid===e.uuid))}setPerspective({fov:e,near:t,far:s}={}){this.camera?.setPerspective({fov:e,near:t,far:s,width:this.boundingRect.width,height:this.boundingRect.height,pixelRatio:this.pixelRatio})}setCameraPosition(e=new f(0,0,1)){this.camera.position.copy(e)}onResize(){super.onResize(),this.setPerspective(),this.updateCameraBindings()}updateCamera(){this.camera?.updateMatrixStack(),this.setCameraBindGroup(),this.cameraBindGroup?.update()}renderSingleMesh(e,t){const s=e.beginRenderPass(this.renderPass.descriptor);t.material.options.rendering.useProjection&&s.setBindGroup(this.cameraBindGroup.index,this.cameraBindGroup.bindGroup),t.render(s),s.end()}render(e){this.ready&&(this.updateCamera(),super.render(e))}destroy(){this.cameraBindGroup?.destroy(),super.destroy()}}class _t{constructor({label:e,production:t=!1,onError:s=()=>{},onDeviceLost:i=r=>{}}){this.index=0,this.label=e??"GPUDeviceManager instance",this.production=t,this.ready=!1,this.onError=s,this.onDeviceLost=i,this.gpu=navigator.gpu,this.setPipelineManager(),this.setDeviceObjects()}async setAdapterAndDevice(){await this.setAdapter(),await this.setDevice()}async init(){await this.setAdapterAndDevice(),this.device&&this.renderers.forEach(e=>{e.context||e.setContext()})}async setAdapter(){this.gpu||(this.onError(),V("GPURenderer: WebGPU is not supported on your browser/OS. No 'gpu' object in 'navigator'."));try{this.adapter=await this.gpu?.requestAdapter(),this.adapter?.requestAdapterInfo().then(e=>{this.adapterInfos=e})}catch{this.onError(),V("GPUDeviceManager: WebGPU is not supported on your browser/OS. 'requestAdapter' failed.")}}async setDevice(){try{this.device=await this.adapter?.requestDevice({label:this.label+" "+this.index}),this.device&&(this.ready=!0,this.index++)}catch(e){this.onError(),V(`${this.label}: WebGPU is not supported on your browser/OS. 'requestDevice' failed: ${e}`)}this.device?.lost.then(e=>{U(`${this.label}: WebGPU device was lost: ${e.message}`),this.loseDevice(),e.reason!=="destroyed"&&this.onDeviceLost(e)})}setPipelineManager(){this.pipelineManager=new zt}loseDevice(){this.ready=!1,this.samplers.forEach(e=>e.sampler=null),this.renderers.forEach(e=>e.loseContext()),this.buffers=[]}async restoreDevice(){await this.setAdapterAndDevice(),this.device&&(this.samplers.forEach(e=>{const{type:t,...s}=e.options;e.sampler=this.device.createSampler({label:e.label,...s})}),this.renderers.forEach(e=>e.restoreContext()))}setDeviceObjects(){this.renderers=[],this.bindGroups=[],this.buffers=[],this.samplers=[],this.textures=[],this.texturesQueue=[]}addRenderer(e){this.renderers.push(e)}removeRenderer(e){this.renderers=this.renderers.filter(t=>t.uuid!==e.uuid)}get deviceRenderedObjects(){return this.renderers.map(e=>e.renderedObjects).flat()}addBindGroup(e){this.bindGroups.find(t=>t.uuid===e.uuid)||this.bindGroups.push(e)}removeBindGroup(e){this.bindGroups=this.bindGroups.filter(t=>t.uuid!==e.uuid)}addBuffer(e){this.buffers.push(e)}removeBuffer(e,t){e&&(this.buffers=this.buffers.filter(s=>!(s.label===(t??e.label)&&s.size===e.size)))}addSampler(e){this.samplers.push(e)}removeSampler(e){this.samplers=this.samplers.filter(t=>t.uuid!==e.uuid)}addTexture(e){this.textures.push(e)}uploadTexture(e){if(e.source)try{this.device?.queue.copyExternalImageToTexture({source:e.source,flipY:e.options.flipY},{texture:e.texture,premultipliedAlpha:e.options.premultipliedAlpha},{width:e.size.width,height:e.size.height}),e.texture.mipLevelCount>1&&Wt(this.device,e.texture),this.texturesQueue.push(e)}catch({message:t}){V(`GPUDeviceManager: could not upload texture: ${e.options.name} because: ${t}`)}else this.device?.queue.writeTexture({texture:e.texture},new Uint8Array(e.options.placeholderColor),{bytesPerRow:e.size.width*4},{width:e.size.width,height:e.size.height})}removeTexture(e){this.textures=this.textures.filter(t=>t.uuid!==e.uuid)}render(){if(!this.ready)return;this.renderers.forEach(s=>s.onBeforeCommandEncoder());const e=this.device?.createCommandEncoder({label:this.label+" command encoder"});!this.production&&e.pushDebugGroup(this.label+" command encoder: main render loop"),this.renderers.forEach(s=>s.render(e)),!this.production&&e.popDebugGroup();const t=e.finish();this.device?.queue.submit([t]),this.textures.filter(s=>!s.parentMesh&&s.sourceLoaded&&!s.sourceUploaded).forEach(s=>this.uploadTexture(s)),this.texturesQueue.forEach(s=>{s.sourceUploaded=!0}),this.texturesQueue=[],this.renderers.forEach(s=>s.onAfterCommandEncoder())}destroy(){this.device?.destroy(),this.device=null,this.renderers.forEach(e=>e.destroy()),this.bindGroups.forEach(e=>e.destroy()),this.buffers.forEach(e=>e?.destroy()),this.textures.forEach(e=>e.destroy()),this.setDeviceObjects()}}var Ft=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},kt=(o,e,t)=>(Ft(o,e,"read from private field"),t?t.call(o):e.get(o)),bs=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},ws=(o,e,t,s)=>(Ft(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),de;class Dt{constructor(e,t={}){bs(this,de,!0),e=e&&e.renderer||e,z(e,"RenderTarget"),this.type="RenderTarget",this.renderer=e,this.uuid=D();const{label:s,colorAttachments:i,depthTexture:r,autoRender:n,...a}=t;this.options={label:s,...a,...r&&{depthTexture:r},...i&&{colorAttachments:i},autoRender:n===void 0?!0:n},n!==void 0&&ws(this,de,n),this.renderPass=new ze(this.renderer,{label:this.options.label?`${this.options.label} Render Pass`:"Render Target Render Pass",...i&&{colorAttachments:i},depthTexture:this.options.depthTexture??this.renderer.renderPass.depthTexture,...a}),a.useColorAttachments!==!1&&(this.renderTexture=new J(this.renderer,{label:this.options.label?`${this.options.label} Render Texture`:"Render Target render texture",name:"renderTexture",format:i&&i.length&&i[0].targetFormat?i[0].targetFormat:this.renderer.options.preferredFormat,...this.options.qualityRatio!==void 0&&{qualityRatio:this.options.qualityRatio}})),this.addToScene()}addToScene(){this.renderer.renderTargets.push(this),kt(this,de)&&this.renderer.scene.addRenderTarget(this)}removeFromScene(){kt(this,de)&&this.renderer.scene.removeRenderTarget(this),this.renderer.renderTargets=this.renderer.renderTargets.filter(e=>e.uuid!==this.uuid)}resize(){this.renderPass.options.depthTexture.texture=this.options.depthTexture?this.options.depthTexture.texture:this.renderer.renderPass.depthTexture.texture,this.renderPass?.resize()}remove(){this.destroy()}destroy(){this.renderer.meshes.forEach(e=>{e.outputTarget&&e.outputTarget.uuid===this.uuid&&e.setOutputTarget(null)}),this.renderer.shaderPasses.forEach(e=>{e.outputTarget&&e.outputTarget.uuid===this.uuid&&(e.outputTarget=null,e.setOutputTarget(null))}),this.removeFromScene(),this.renderPass?.destroy(),this.renderTexture?.destroy()}}de=new WeakMap;var vs=` struct VSOutput { @builtin(position) position: vec4f, @location(0) uv: vec2f, @@ -160,5 +160,5 @@ struct VSOutput { @fragment fn main(fsInput: VSOutput) -> @location(0) vec4f { return textureSample(renderTexture, defaultSampler, fsInput.uv); -}`;class Ps extends He{constructor(e,t={}){e=e&&e.renderer||e,z(e,t.label?t.label+" ShaderPass":"ShaderPass"),t.transparent=!0,t.label=t.label??"ShaderPass "+e.shaderPasses?.length,t.sampleCount=t.sampleCount?t.sampleCount:e&&e.postProcessingPass?e&&e.postProcessingPass.options.sampleCount:1,t.shaders||(t.shaders={}),t.shaders.fragment||(t.shaders.fragment={code:vs,entryPoint:"main"}),t.depth=!1,super(e,t),t.inputTarget&&this.setInputTarget(t.inputTarget),this.outputTarget&&this.setRenderingOptionsForRenderPass(this.outputTarget.renderPass),this.type="ShaderPass",this.createRenderTexture({label:t.label?`${t.label} render texture`:"Shader pass render texture",name:"renderTexture",fromTexture:this.inputTarget?this.inputTarget.renderTexture:null,...this.outputTarget&&this.outputTarget.options.qualityRatio&&{qualityRatio:this.outputTarget.options.qualityRatio}})}cleanupRenderMaterialParameters(e){return delete e.copyOutputToRenderTexture,delete e.inputTarget,super.cleanupRenderMaterialParameters(e),e}get renderTexture(){return this.renderTextures.find(e=>e.options.name==="renderTexture")}setInputTarget(e){if(e&&e.type!=="RenderTarget"){U(`${this.options.label??this.type}: inputTarget is not a RenderTarget: ${e}`);return}this.removeFromScene(),this.inputTarget=e,this.addToScene(),this.renderTexture&&(e?this.renderTexture.copy(this.inputTarget.renderTexture):(this.renderTexture.options.fromTexture=null,this.renderTexture.createTexture()))}addToScene(){this.renderer.shaderPasses.push(this),this.setRenderingOptionsForRenderPass(this.outputTarget?this.outputTarget.renderPass:this.renderer.postProcessingPass),this.autoRender&&this.renderer.scene.addShaderPass(this)}removeFromScene(){this.outputTarget&&this.outputTarget.destroy(),this.autoRender&&this.renderer.scene.removeShaderPass(this),this.renderer.shaderPasses=this.renderer.shaderPasses.filter(e=>e.uuid!==this.uuid)}}var Ms=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},ae=(o,e,t)=>(Ms(o,e,"read from private field"),t?t.call(o):e.get(o)),$t=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},le,ce;class Lt extends Ze{constructor(e,t,s){super(e),$t(this,le,new f),$t(this,ce,new f),e=e&&e.renderer||e,De(e,"DOM3DObject"),this.renderer=e,this.size={world:{width:0,height:0,top:0,left:0},document:{width:0,height:0,top:0,left:0}},this.watchScroll=s.watchScroll,this.camera=this.renderer.camera,this.setDOMElement(t)}setDOMElement(e){this.domElement=new tt({element:e,onSizeChanged:t=>this.resize(t),onPositionChanged:t=>this.onPositionChanged(t)})}onPositionChanged(e){this.watchScroll&&(this.size.document=e??this.domElement.element.getBoundingClientRect(),this.updateSizeAndPosition())}resetDOMElement(e){this.domElement&&this.domElement.destroy(),this.setDOMElement(e)}updateSizeAndPosition(){this.setWorldSizes(),this.applyPosition(),this.shouldUpdateModelMatrix()}shouldUpdateMatrixStack(){this.updateSizeAndPosition(),super.shouldUpdateMatrixStack()}resize(e){!e&&(!this.domElement||this.domElement?.isResizing)||(this.size.document=e??this.domElement.element.getBoundingClientRect(),this.shouldUpdateMatrixStack())}get boundingRect(){return this.domElement.boundingRect}setTransforms(){super.setTransforms(),this.transforms.origin.model.set(.5,.5,0),this.transforms.origin.world=new f,this.transforms.position.document=new f,this.documentPosition.onChange(()=>this.applyPosition()),this.transformOrigin.onChange(()=>this.setWorldTransformOrigin())}get documentPosition(){return this.transforms.position.document}set documentPosition(e){this.transforms.position.document=e,this.applyPosition()}get DOMObjectWorldScale(){return ae(this,ce).clone()}get worldScale(){return this.DOMObjectWorldScale.multiply(this.scale)}get worldPosition(){return ae(this,le).clone()}get transformOrigin(){return this.transforms.origin.model}set transformOrigin(e){this.transforms.origin.model=e,this.setWorldTransformOrigin()}get worldTransformOrigin(){return this.transforms.origin.world}set worldTransformOrigin(e){this.transforms.origin.world=e}applyPosition(){this.applyDocumentPosition(),super.applyPosition()}applyDocumentPosition(){let e=new f(0,0,0);this.documentPosition.equals(e)||(e=this.documentToWorldSpace(this.documentPosition)),ae(this,le).set(this.position.x+this.size.world.left+e.x,this.position.y+this.size.world.top+e.y,this.position.z+this.documentPosition.z/this.camera.CSSPerspective)}applyTransformOrigin(){this.size&&(this.setWorldTransformOrigin(),super.applyTransformOrigin())}updateModelMatrix(){this.modelMatrix.composeFromOrigin(ae(this,le),this.quaternion,this.scale,this.worldTransformOrigin),this.modelMatrix.scale(ae(this,ce)),this.shouldUpdateWorldMatrix()}documentToWorldSpace(e=new f){return new f(e.x*this.renderer.pixelRatio/this.renderer.boundingRect.width*this.camera.screenRatio.width,-(e.y*this.renderer.pixelRatio/this.renderer.boundingRect.height)*this.camera.screenRatio.height,e.z)}setWorldSizes(){const e=this.renderer.boundingRect,t={x:this.size.document.width/2+this.size.document.left,y:this.size.document.height/2+this.size.document.top},s={x:e.width/2+e.left,y:e.height/2+e.top};this.size.world={width:this.size.document.width/e.width*this.camera.screenRatio.width/2,height:this.size.document.height/e.height*this.camera.screenRatio.height/2,top:(s.y-t.y)/e.height*this.camera.screenRatio.height,left:(t.x-s.x)/e.width*this.camera.screenRatio.width},ae(this,ce).set(this.size.world.width,this.size.world.height,1),this.setWorldTransformOrigin()}setWorldTransformOrigin(){this.transforms.origin.world=new f((this.transformOrigin.x*2-1)*this.size.world.width,-(this.transformOrigin.y*2-1)*this.size.world.height,this.transformOrigin.z),this.shouldUpdateModelMatrix(),this.shouldUpdateProjectionMatrixStack()}updateScrollPosition(e={x:0,y:0}){(e.x||e.y)&&this.domElement.updateScrollPosition(e)}destroy(){this.domElement?.destroy()}}le=new WeakMap,ce=new WeakMap;const Vt={autoloadSources:!0,watchScroll:!0};class It extends Et(Lt){constructor(e,t,s){super(e,t,{...Vt,...s}),this._onLoadingCallback=r=>{},s={...Vt,...s},e=e&&e.renderer||e,De(e,s.label?s.label+" DOMMesh":"DOMMesh"),this.type="DOMMesh";const{autoloadSources:i}=s;this.autoloadSources=i,this.sourcesReady=!1,this.setInitSources()}get ready(){return this._ready}set ready(e){this._ready=e,this.DOMMeshReady&&this._onReadyCallback&&this._onReadyCallback()}get sourcesReady(){return this._sourcesReady}set sourcesReady(e){this._sourcesReady=e,this.DOMMeshReady&&this._onReadyCallback&&this._onReadyCallback()}get DOMMeshReady(){return this.ready&&this.sourcesReady}addToScene(){super.addToScene(),this.renderer.domMeshes.push(this)}removeFromScene(){super.removeFromScene(),this.renderer.domMeshes=this.renderer.domMeshes.filter(e=>e.uuid!==this.uuid)}setInitSources(){let e=0,t=0;if(this.autoloadSources){const s=this.domElement.element.querySelectorAll("img"),i=this.domElement.element.querySelectorAll("video"),r=this.domElement.element.querySelectorAll("canvas");e=s.length+i.length+r.length;const n=a=>{t++,this._onLoadingCallback&&this._onLoadingCallback(a),t===e&&(this.sourcesReady=!0)};e||(this.sourcesReady=!0),s.length&&s.forEach(a=>{const h=this.createTexture({name:a.getAttribute("data-texture-name")??"texture"+this.textures.length});h.onSourceUploaded(()=>n(h)).loadImage(a.src)}),i.length&&i.forEach(a=>{const h=this.createTexture({name:a.getAttribute("data-texture-name")??"texture"+this.textures.length});h.onSourceUploaded(()=>n(h)).loadVideo(a)}),r.length&&r.forEach(a=>{const h=this.createTexture({name:a.getAttribute("data-texture-name")??"texture"+this.textures.length});h.onSourceUploaded(()=>n(h)).loadCanvas(a)})}else this.sourcesReady=!0}resetDOMElement(e){e?super.resetDOMElement(e):!e&&!this.renderer.production&&U(`${this.options.label}: You are trying to reset a ${this.type} with a HTML element that does not exist. The old HTML element will be kept instead.`)}get pixelRatioBoundingRect(){const e=window.devicePixelRatio??1,t=this.renderer.pixelRatio/e;return Object.keys(this.domElement.boundingRect).reduce((s,i)=>({...s,[i]:this.domElement.boundingRect[i]*t}),{x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0})}onLoading(e){return e&&(this._onLoadingCallback=e),this}}class Ts extends He{constructor(e,t={}){e=e&&e.renderer||e,z(e,t.label?t.label+" PingPongPlane":"PingPongPlane"),t.outputTarget=new Dt(e,{label:t.label?t.label+" render target":"Ping Pong render target",useDepth:!1,...t.targetFormat&&{targetFormat:t.targetFormat}}),t.transparent=!1,t.depth=!1,t.label=t.label??"PingPongPlane "+e.pingPongPlanes?.length,super(e,t),this.type="PingPongPlane",this.createRenderTexture({label:t.label?`${t.label} render texture`:"PingPongPlane render texture",name:"renderTexture",...t.targetFormat&&{format:t.targetFormat}})}get renderTexture(){return this.renderTextures.find(e=>e.options.name==="renderTexture")}addToScene(){this.renderer.pingPongPlanes.push(this),this.autoRender&&this.renderer.scene.addPingPongPlane(this)}removeFromScene(){this.outputTarget&&this.outputTarget.destroy(),this.autoRender&&this.renderer.scene.removePingPongPlane(this),this.renderer.pingPongPlanes=this.renderer.pingPongPlanes.filter(e=>e.uuid!==this.uuid)}}const Rs={label:"Plane",instancesCount:1,vertexBuffers:[]};class jt extends It{constructor(e,t,s={}){e=e&&e.renderer||e,De(e,s.label?s.label+" Plane":"Plane");const i={...Rs,...s};let{geometry:r,widthSegments:n,heightSegments:a,...h}=i;const{instancesCount:u,vertexBuffers:d,...l}=h;if(!r||r.type!=="PlaneGeometry"){n=n??1,a=a??1;const c=n*a+n;d.length||(r=Ge.getPlaneGeometryByID(c)),r?r.instancesCount=u:(r=new Ye({widthSegments:n,heightSegments:a,instancesCount:u,vertexBuffers:d}),Ge.addPlaneGeometry(r))}super(e,t,{geometry:r,...l}),this.type="Plane"}mouseToPlaneCoords(e=new E){const t={x:2*(e.x/this.renderer.displayBoundingRect.width)-1,y:2*(1-e.y/this.renderer.displayBoundingRect.height)-1},s=this.camera.position.clone(),i=new f(t.x,t.y,-.5);i.unproject(this.camera),i.sub(s).normalize();const r=new f(0,0,1);r.applyQuat(this.quaternion).normalize();const n=new f(0,0,0),a=r.dot(i);if(Math.abs(a)>=1e-4){const h=this.modelMatrix.getInverse().premultiply(this.camera.viewMatrix),u=this.worldTransformOrigin.clone().add(this.worldPosition),d=new f(this.worldPosition.x-u.x,this.worldPosition.y-u.y,this.worldPosition.z-u.z);d.applyQuat(this.quaternion),u.add(d);const l=r.dot(u.clone().sub(s))/a;n.copy(s.add(i.multiplyScalar(l))),n.applyMat4(h)}else n.set(1/0,1/0,1/0);return new E(n.x,n.y)}}class rt extends it{constructor({deviceManager:e,container:t,pixelRatio:s=1,preferredFormat:i,alphaMode:r="premultiplied",renderPass:n,camera:a}){super({deviceManager:e,container:t,pixelRatio:s,preferredFormat:i,alphaMode:r,renderPass:n,camera:a}),this.type="GPUCurtainsRenderer"}setRendererObjects(){super.setRendererObjects(),this.domMeshes=[]}}class Cs{constructor({scroll:e={x:0,y:0},delta:t={x:0,y:0},shouldWatch:s=!0,onScroll:i=(r={x:0,y:0})=>{}}={}){this.scroll=e,this.delta=t,this.shouldWatch=s,this.onScroll=i,this.shouldWatch&&window.addEventListener("scroll",this.setScroll.bind(this),{passive:!0})}setScroll(){this.updateScrollValues({x:window.pageXOffset,y:window.pageYOffset})}updateScrollValues({x:e,y:t}){const s=this.scroll;this.scroll={x:e,y:t},this.delta={x:s.x-this.scroll.x,y:s.y-this.scroll.y},this.onScroll&&this.onScroll(this.delta)}destroy(){this.shouldWatch&&window.removeEventListener("scroll",this.setScroll.bind(this),{passive:!0})}}class Bs{constructor({container:e,pixelRatio:t=window.devicePixelRatio??1,preferredFormat:s,alphaMode:i="premultiplied",production:r=!1,renderPass:n,camera:a,autoRender:h=!0,autoResize:u=!0,watchScroll:d=!0}={}){this._onRenderCallback=()=>{},this._onScrollCallback=()=>{},this._onErrorCallback=()=>{},this._onContextLostCallback=()=>{},this.type="CurtainsGPU",this.options={container:e,pixelRatio:t,camera:a,production:r,preferredFormat:s,alphaMode:i,renderPass:n,autoRender:h,autoResize:u,watchScroll:d},this.setDeviceManager(),e&&this.setContainer(e)}setContainer(e){if(e)if(typeof e=="string")if(e=document.querySelector(e),e)this.options.container=e;else{const t=document.createElement("div");t.setAttribute("id","curtains-gpu-canvas"),document.body.appendChild(t),this.options.container=t}else e instanceof Element&&(this.options.container=e);else{const t=document.createElement("div");t.setAttribute("id","curtains-gpu-canvas"),document.body.appendChild(t),this.options.container=t}this.container=this.options.container,this.setCurtains()}setMainRenderer(){this.createCurtainsRenderer({deviceManager:this.deviceManager,container:this.options.container,pixelRatio:this.options.pixelRatio,preferredFormat:this.options.preferredFormat,alphaMode:this.options.alphaMode,renderPass:this.options.renderPass,camera:this.options.camera})}patchRendererOptions(e){return e.pixelRatio===void 0&&(e.pixelRatio=this.options.pixelRatio),e}createRenderer(e){return e=this.patchRendererOptions(e),new st({...e,deviceManager:this.deviceManager})}createCameraRenderer(e){return e=this.patchRendererOptions(e),new it({...e,deviceManager:this.deviceManager})}createCurtainsRenderer(e){return e=this.patchRendererOptions(e),new rt({...e,deviceManager:this.deviceManager})}setDeviceManager(){this.deviceManager=new _t({label:"GPUCurtains default device",production:this.options.production,onError:()=>setTimeout(()=>{this._onErrorCallback&&this._onErrorCallback()},0),onDeviceLost:e=>this._onContextLostCallback&&this._onContextLostCallback(e)})}get renderers(){return this.deviceManager.renderers}get renderer(){return this.renderers[0]}async setDevice(){await this.deviceManager.init()}async restoreContext(){await this.deviceManager.restoreDevice()}setCurtains(){this.initEvents(),this.setMainRenderer(),this.options.autoRender&&this.animate()}get pingPongPlanes(){return this.renderers?.map(e=>e.pingPongPlanes).flat()}get shaderPasses(){return this.renderers?.map(e=>e.shaderPasses).flat()}get meshes(){return this.renderers?.map(e=>e.meshes).flat()}get domMeshes(){return this.renderers?.filter(e=>e instanceof rt).map(e=>e.domMeshes).flat()}get planes(){return this.domMeshes.filter(e=>e instanceof jt)}get computePasses(){return this.renderers?.map(e=>e.computePasses).flat()}get camera(){return this.renderer?.camera}setPerspective({fov:e=50,near:t=.01,far:s=50}={}){this.renderer?.setPerspective({fov:e,near:t,far:s})}setCameraPosition(e=new f(0,0,1)){this.renderer?.setCameraPosition(e)}get boundingRect(){return this.renderer?.boundingRect}initScroll(){this.scrollManager=new Cs({scroll:{x:window.pageXOffset,y:window.pageYOffset},delta:{x:0,y:0},shouldWatch:this.options.watchScroll,onScroll:e=>this.updateScroll(e)})}updateScroll(e={x:0,y:0}){this.domMeshes.forEach(t=>{t.domElement&&t.updateScrollPosition(e)}),this._onScrollCallback&&this._onScrollCallback()}updateScrollValues(e={x:0,y:0}){this.scrollManager.updateScrollValues(e)}get scrollDelta(){return this.scrollManager.delta}get scrollValues(){return this.scrollManager.scroll}initEvents(){et.useObserver(this.options.autoResize),this.initScroll()}onRender(e){return e&&(this._onRenderCallback=e),this}onScroll(e){return e&&(this._onScrollCallback=e),this}onError(e){return e&&(this._onErrorCallback=e),this}onContextLost(e){return e&&(this._onContextLostCallback=e),this}animate(){this.render(),this.animationFrameID=window.requestAnimationFrame(this.animate.bind(this))}render(){this._onRenderCallback&&this._onRenderCallback(),this.deviceManager.render()}destroy(){this.animationFrameID&&window.cancelAnimationFrame(this.animationFrameID),this.deviceManager.destroy(),this.scrollManager?.destroy(),et.destroy()}}class Ss extends Ee{constructor({widthSegments:e=1,heightSegments:t=1,depthSegments:s=1,instancesCount:i=1,vertexBuffers:r=[],topology:n}={}){super({verticesOrder:"ccw",topology:n,instancesCount:i,vertexBuffers:r}),this.type="BoxGeometry",e=Math.floor(e),t=Math.floor(t),s=Math.floor(s);const a=[],h=[],u=[],d=[];let l=0;const c=(p,m,b,x,g,T,R,v,P,M)=>{const w=T/P,S=R/M,C=T/2,F=R/2,X=v/2,j=P+1,Z=M+1;let H=0;const G=new f;for(let A=0;A0?1:-1,u.push(G.x,G.y,G.z),h.push(L/P),h.push(A/M),H+=1}}for(let A=0;A0)&&x.push(M,w,C),(v!==t-1||l{const{scene:e}=o;if(!e)return;const t=[];e.computePassEntries.forEach(s=>{t.push({command:"Render ComputePass",content:s.options.label}),s.material.bindGroups.forEach(i=>{i.bufferBindings.forEach(r=>{r.shouldCopyResult&&t.push({command:"Copy buffer to buffer",source:`${r.name} buffer`,destination:`${r.name} result buffer`})})})});for(const s in e.renderPassEntries){let i=0;e.renderPassEntries[s].forEach(r=>{if(!e.getRenderPassEntryLength(r))return;const n=r.renderPass.options.useColorAttachments?r.renderPass.options.colorAttachments.length===0&&r.renderPass.options.useDepth?`${r.renderTexture.options.label} depth pass`:r.renderPass.options.colorAttachments.length>1?`${r.renderTexture.options.label} multiple targets`:r.renderTexture?`${r.renderTexture.options.label}`:"Context current texture":void 0;let a=r.renderPass.options.label;const h={loadOp:r.renderPass.options.useColorAttachments?s==="screen"&&i>0?"load":r.renderPass.options.loadOp:void 0,depthLoadOp:void 0,sampleCount:r.renderPass.options.sampleCount,...r.renderPass.options.qualityRatio!==1&&{qualityRatio:r.renderPass.options.qualityRatio}};if(r.renderPass.options.useDepth&&(h.depthLoadOp=r.renderPass.options.depthLoadOp),i++,r.element)r.element.type==="ShaderPass"&&!(r.element.inputTarget||r.element.outputTarget)&&(t.push({command:"Copy texture to texture",source:n,destination:`${r.element.options.label} renderTexture`}),h.loadOp="clear"),a+=" "+JSON.stringify(h),t.push({command:`Render ${r.element.type}`,source:r.element.options.label,destination:n,descriptor:a}),r.element.type==="ShaderPass"&&!r.element.outputTarget&&r.element.options.copyOutputToRenderTexture?t.push({command:"Copy texture to texture",source:n,destination:`${r.element.options.label} renderTexture`}):r.element.type==="PingPongPlane"&&t.push({command:"Copy texture to texture",source:n,destination:`${r.element.renderTexture.options.label}`});else if(r.stack){a+=" "+JSON.stringify(h);for(const u in r.stack)for(const d in r.stack[u])r.stack[u][d].length&&t.push({command:`Render stack (${u} ${d} objects)`,source:r.stack[u][d],destination:n,descriptor:a})}})}console.table(t)};y.BindGroup=ge,y.Binding=pe,y.Box3=oe,y.BoxGeometry=Ss,y.BufferBinding=ne,y.Camera=dt,y.ComputeMaterial=ft,y.ComputePass=is,y.ComputePipelineEntry=Ke,y.DOMElement=tt,y.DOMFrustum=xt,y.DOMMesh=It,y.DOMObject3D=Lt,y.FullscreenPlane=He,y.GPUCameraRenderer=it,y.GPUCurtains=Bs,y.GPUCurtainsRenderer=rt,y.GPUDeviceManager=_t,y.GPURenderer=st,y.Geometry=Ne,y.IndexedGeometry=Ee,y.Mat4=O,y.Material=We,y.Mesh=ls,y.Object3D=ye,y.PingPongPlane=Ts,y.PipelineEntry=Qe,y.PipelineManager=zt,y.Plane=jt,y.PlaneGeometry=Ye,y.ProjectedObject3D=Ze,y.Quat=N,y.RenderMaterial=wt,y.RenderPass=ze,y.RenderPipelineEntry=Je,y.RenderTarget=Dt,y.RenderTexture=J,y.Sampler=lt,y.SamplerBinding=ht,y.Scene=Ot,y.ShaderPass=Ps,y.SphereGeometry=Es,y.Texture=te,y.TextureBindGroup=je,y.TextureBinding=Ie,y.Vec2=E,y.Vec3=f,y.WritableBufferBinding=Ve,y.logSceneCommands=Gs}); +}`;class Ps extends He{constructor(e,t={}){e=e&&e.renderer||e,z(e,t.label?t.label+" ShaderPass":"ShaderPass"),t.depth=!1,t.label=t.label??"ShaderPass "+e.shaderPasses?.length,t.sampleCount=t.sampleCount?t.sampleCount:e&&e.postProcessingPass?e&&e.postProcessingPass.options.sampleCount:1,t.shaders||(t.shaders={}),t.shaders.fragment||(t.shaders.fragment={code:vs,entryPoint:"main"}),t.depth=!1,super(e,t),t.inputTarget&&this.setInputTarget(t.inputTarget),this.outputTarget&&this.setRenderingOptionsForRenderPass(this.outputTarget.renderPass),this.type="ShaderPass",this.createRenderTexture({label:t.label?`${t.label} render texture`:"Shader pass render texture",name:"renderTexture",fromTexture:this.inputTarget?this.inputTarget.renderTexture:null,...this.outputTarget&&this.outputTarget.options.qualityRatio&&{qualityRatio:this.outputTarget.options.qualityRatio}})}cleanupRenderMaterialParameters(e){return delete e.copyOutputToRenderTexture,delete e.inputTarget,super.cleanupRenderMaterialParameters(e),e}get renderTexture(){return this.renderTextures.find(e=>e.options.name==="renderTexture")}setInputTarget(e){if(e&&e.type!=="RenderTarget"){U(`${this.options.label??this.type}: inputTarget is not a RenderTarget: ${e}`);return}this.removeFromScene(),this.inputTarget=e,this.addToScene(),this.renderTexture&&(e?this.renderTexture.copy(this.inputTarget.renderTexture):(this.renderTexture.options.fromTexture=null,this.renderTexture.createTexture()))}addToScene(){this.renderer.shaderPasses.push(this),this.setRenderingOptionsForRenderPass(this.outputTarget?this.outputTarget.renderPass:this.renderer.postProcessingPass),this.autoRender&&this.renderer.scene.addShaderPass(this)}removeFromScene(){this.outputTarget&&this.outputTarget.destroy(),this.autoRender&&this.renderer.scene.removeShaderPass(this),this.renderer.shaderPasses=this.renderer.shaderPasses.filter(e=>e.uuid!==this.uuid)}}var Ms=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)},ae=(o,e,t)=>(Ms(o,e,"read from private field"),t?t.call(o):e.get(o)),$t=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},le,ce;class Lt extends Ze{constructor(e,t,s){super(e),$t(this,le,new f),$t(this,ce,new f),e=e&&e.renderer||e,De(e,"DOM3DObject"),this.renderer=e,this.size={world:{width:0,height:0,top:0,left:0},document:{width:0,height:0,top:0,left:0}},this.watchScroll=s.watchScroll,this.camera=this.renderer.camera,this.setDOMElement(t)}setDOMElement(e){this.domElement=new tt({element:e,onSizeChanged:t=>this.resize(t),onPositionChanged:t=>this.onPositionChanged(t)})}onPositionChanged(e){this.watchScroll&&(this.size.document=e??this.domElement.element.getBoundingClientRect(),this.updateSizeAndPosition())}resetDOMElement(e){this.domElement&&this.domElement.destroy(),this.setDOMElement(e)}updateSizeAndPosition(){this.setWorldSizes(),this.applyPosition(),this.shouldUpdateModelMatrix()}shouldUpdateMatrixStack(){this.updateSizeAndPosition(),super.shouldUpdateMatrixStack()}resize(e){!e&&(!this.domElement||this.domElement?.isResizing)||(this.size.document=e??this.domElement.element.getBoundingClientRect(),this.shouldUpdateMatrixStack())}get boundingRect(){return this.domElement.boundingRect}setTransforms(){super.setTransforms(),this.transforms.origin.model.set(.5,.5,0),this.transforms.origin.world=new f,this.transforms.position.document=new f,this.documentPosition.onChange(()=>this.applyPosition()),this.transformOrigin.onChange(()=>this.setWorldTransformOrigin())}get documentPosition(){return this.transforms.position.document}set documentPosition(e){this.transforms.position.document=e,this.applyPosition()}get DOMObjectWorldScale(){return ae(this,ce).clone()}get worldScale(){return this.DOMObjectWorldScale.multiply(this.scale)}get worldPosition(){return ae(this,le).clone()}get transformOrigin(){return this.transforms.origin.model}set transformOrigin(e){this.transforms.origin.model=e,this.setWorldTransformOrigin()}get worldTransformOrigin(){return this.transforms.origin.world}set worldTransformOrigin(e){this.transforms.origin.world=e}applyPosition(){this.applyDocumentPosition(),super.applyPosition()}applyDocumentPosition(){let e=new f(0,0,0);this.documentPosition.equals(e)||(e=this.documentToWorldSpace(this.documentPosition)),ae(this,le).set(this.position.x+this.size.world.left+e.x,this.position.y+this.size.world.top+e.y,this.position.z+this.documentPosition.z/this.camera.CSSPerspective)}applyTransformOrigin(){this.size&&(this.setWorldTransformOrigin(),super.applyTransformOrigin())}updateModelMatrix(){this.modelMatrix.composeFromOrigin(ae(this,le),this.quaternion,this.scale,this.worldTransformOrigin),this.modelMatrix.scale(ae(this,ce)),this.shouldUpdateWorldMatrix()}documentToWorldSpace(e=new f){return new f(e.x*this.renderer.pixelRatio/this.renderer.boundingRect.width*this.camera.screenRatio.width,-(e.y*this.renderer.pixelRatio/this.renderer.boundingRect.height)*this.camera.screenRatio.height,e.z)}setWorldSizes(){const e=this.renderer.boundingRect,t={x:this.size.document.width/2+this.size.document.left,y:this.size.document.height/2+this.size.document.top},s={x:e.width/2+e.left,y:e.height/2+e.top};this.size.world={width:this.size.document.width/e.width*this.camera.screenRatio.width/2,height:this.size.document.height/e.height*this.camera.screenRatio.height/2,top:(s.y-t.y)/e.height*this.camera.screenRatio.height,left:(t.x-s.x)/e.width*this.camera.screenRatio.width},ae(this,ce).set(this.size.world.width,this.size.world.height,1),this.setWorldTransformOrigin()}setWorldTransformOrigin(){this.transforms.origin.world=new f((this.transformOrigin.x*2-1)*this.size.world.width,-(this.transformOrigin.y*2-1)*this.size.world.height,this.transformOrigin.z),this.shouldUpdateModelMatrix(),this.shouldUpdateProjectionMatrixStack()}updateScrollPosition(e={x:0,y:0}){(e.x||e.y)&&this.domElement.updateScrollPosition(e)}destroy(){this.domElement?.destroy()}}le=new WeakMap,ce=new WeakMap;const Vt={autoloadSources:!0,watchScroll:!0};class It extends Et(Lt){constructor(e,t,s){super(e,t,{...Vt,...s}),this._onLoadingCallback=r=>{},s={...Vt,...s},e=e&&e.renderer||e,De(e,s.label?s.label+" DOMMesh":"DOMMesh"),this.type="DOMMesh";const{autoloadSources:i}=s;this.autoloadSources=i,this.sourcesReady=!1,this.setInitSources()}get ready(){return this._ready}set ready(e){this._ready=e,this.DOMMeshReady&&this._onReadyCallback&&this._onReadyCallback()}get sourcesReady(){return this._sourcesReady}set sourcesReady(e){this._sourcesReady=e,this.DOMMeshReady&&this._onReadyCallback&&this._onReadyCallback()}get DOMMeshReady(){return this.ready&&this.sourcesReady}addToScene(){super.addToScene(),this.renderer.domMeshes.push(this)}removeFromScene(){super.removeFromScene(),this.renderer.domMeshes=this.renderer.domMeshes.filter(e=>e.uuid!==this.uuid)}setInitSources(){let e=0,t=0;if(this.autoloadSources){const s=this.domElement.element.querySelectorAll("img"),i=this.domElement.element.querySelectorAll("video"),r=this.domElement.element.querySelectorAll("canvas");e=s.length+i.length+r.length;const n=a=>{t++,this._onLoadingCallback&&this._onLoadingCallback(a),t===e&&(this.sourcesReady=!0)};e||(this.sourcesReady=!0),s.length&&s.forEach(a=>{const h=this.createTexture({name:a.getAttribute("data-texture-name")??"texture"+this.textures.length});h.onSourceUploaded(()=>n(h)).loadImage(a.src)}),i.length&&i.forEach(a=>{const h=this.createTexture({name:a.getAttribute("data-texture-name")??"texture"+this.textures.length});h.onSourceUploaded(()=>n(h)).loadVideo(a)}),r.length&&r.forEach(a=>{const h=this.createTexture({name:a.getAttribute("data-texture-name")??"texture"+this.textures.length});h.onSourceUploaded(()=>n(h)).loadCanvas(a)})}else this.sourcesReady=!0}resetDOMElement(e){e?super.resetDOMElement(e):!e&&!this.renderer.production&&U(`${this.options.label}: You are trying to reset a ${this.type} with a HTML element that does not exist. The old HTML element will be kept instead.`)}get pixelRatioBoundingRect(){const e=window.devicePixelRatio??1,t=this.renderer.pixelRatio/e;return Object.keys(this.domElement.boundingRect).reduce((s,i)=>({...s,[i]:this.domElement.boundingRect[i]*t}),{x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0})}onLoading(e){return e&&(this._onLoadingCallback=e),this}}class Rs extends He{constructor(e,t={}){e=e&&e.renderer||e,z(e,t.label?t.label+" PingPongPlane":"PingPongPlane");const s=t.targets&&t.targets.length&&t.targets.map(i=>({targetFormat:i.format}));t.outputTarget=new Dt(e,{label:t.label?t.label+" render target":"Ping Pong render target",useDepth:!1,...s&&{colorAttachments:s}}),t.transparent=!1,t.depth=!1,t.label=t.label??"PingPongPlane "+e.pingPongPlanes?.length,super(e,t),this.type="PingPongPlane",this.createRenderTexture({label:t.label?`${t.label} render texture`:"PingPongPlane render texture",name:"renderTexture",...t.targets&&t.targets.length&&{format:t.targets[0].format}})}get renderTexture(){return this.renderTextures.find(e=>e.options.name==="renderTexture")}addToScene(){this.renderer.pingPongPlanes.push(this),this.autoRender&&this.renderer.scene.addPingPongPlane(this)}removeFromScene(){this.outputTarget&&this.outputTarget.destroy(),this.autoRender&&this.renderer.scene.removePingPongPlane(this),this.renderer.pingPongPlanes=this.renderer.pingPongPlanes.filter(e=>e.uuid!==this.uuid)}}const Ts={label:"Plane",instancesCount:1,vertexBuffers:[]};class jt extends It{constructor(e,t,s={}){e=e&&e.renderer||e,De(e,s.label?s.label+" Plane":"Plane");const i={...Ts,...s};let{geometry:r,widthSegments:n,heightSegments:a,...h}=i;const{instancesCount:u,vertexBuffers:d,...l}=h;if(!r||r.type!=="PlaneGeometry"){n=n??1,a=a??1;const c=n*a+n;d.length||(r=Ge.getPlaneGeometryByID(c)),r?r.instancesCount=u:(r=new Ye({widthSegments:n,heightSegments:a,instancesCount:u,vertexBuffers:d}),Ge.addPlaneGeometry(r))}super(e,t,{geometry:r,...l}),this.type="Plane"}mouseToPlaneCoords(e=new E){const t={x:2*(e.x/this.renderer.displayBoundingRect.width)-1,y:2*(1-e.y/this.renderer.displayBoundingRect.height)-1},s=this.camera.position.clone(),i=new f(t.x,t.y,-.5);i.unproject(this.camera),i.sub(s).normalize();const r=new f(0,0,1);r.applyQuat(this.quaternion).normalize();const n=new f(0,0,0),a=r.dot(i);if(Math.abs(a)>=1e-4){const h=this.modelMatrix.getInverse().premultiply(this.camera.viewMatrix),u=this.worldTransformOrigin.clone().add(this.worldPosition),d=new f(this.worldPosition.x-u.x,this.worldPosition.y-u.y,this.worldPosition.z-u.z);d.applyQuat(this.quaternion),u.add(d);const l=r.dot(u.clone().sub(s))/a;n.copy(s.add(i.multiplyScalar(l))),n.applyMat4(h)}else n.set(1/0,1/0,1/0);return new E(n.x,n.y)}}class rt extends it{constructor({deviceManager:e,container:t,pixelRatio:s=1,preferredFormat:i,alphaMode:r="premultiplied",renderPass:n,camera:a}){super({deviceManager:e,container:t,pixelRatio:s,preferredFormat:i,alphaMode:r,renderPass:n,camera:a}),this.type="GPUCurtainsRenderer"}setRendererObjects(){super.setRendererObjects(),this.domMeshes=[]}}class Cs{constructor({scroll:e={x:0,y:0},delta:t={x:0,y:0},shouldWatch:s=!0,onScroll:i=(r={x:0,y:0})=>{}}={}){this.scroll=e,this.delta=t,this.shouldWatch=s,this.onScroll=i,this.shouldWatch&&window.addEventListener("scroll",this.setScroll.bind(this),{passive:!0})}setScroll(){this.updateScrollValues({x:window.pageXOffset,y:window.pageYOffset})}updateScrollValues({x:e,y:t}){const s=this.scroll;this.scroll={x:e,y:t},this.delta={x:s.x-this.scroll.x,y:s.y-this.scroll.y},this.onScroll&&this.onScroll(this.delta)}destroy(){this.shouldWatch&&window.removeEventListener("scroll",this.setScroll.bind(this),{passive:!0})}}class Bs{constructor({container:e,pixelRatio:t=window.devicePixelRatio??1,preferredFormat:s,alphaMode:i="premultiplied",production:r=!1,renderPass:n,camera:a,autoRender:h=!0,autoResize:u=!0,watchScroll:d=!0}={}){this._onRenderCallback=()=>{},this._onScrollCallback=()=>{},this._onErrorCallback=()=>{},this._onContextLostCallback=()=>{},this.type="CurtainsGPU",this.options={container:e,pixelRatio:t,camera:a,production:r,preferredFormat:s,alphaMode:i,renderPass:n,autoRender:h,autoResize:u,watchScroll:d},this.setDeviceManager(),e&&this.setContainer(e)}setContainer(e){if(e)if(typeof e=="string")if(e=document.querySelector(e),e)this.options.container=e;else{const t=document.createElement("div");t.setAttribute("id","curtains-gpu-canvas"),document.body.appendChild(t),this.options.container=t}else e instanceof Element&&(this.options.container=e);else{const t=document.createElement("div");t.setAttribute("id","curtains-gpu-canvas"),document.body.appendChild(t),this.options.container=t}this.container=this.options.container,this.setCurtains()}setMainRenderer(){this.createCurtainsRenderer({deviceManager:this.deviceManager,container:this.options.container,pixelRatio:this.options.pixelRatio,preferredFormat:this.options.preferredFormat,alphaMode:this.options.alphaMode,renderPass:this.options.renderPass,camera:this.options.camera})}patchRendererOptions(e){return e.pixelRatio===void 0&&(e.pixelRatio=this.options.pixelRatio),e}createRenderer(e){return e=this.patchRendererOptions(e),new st({...e,deviceManager:this.deviceManager})}createCameraRenderer(e){return e=this.patchRendererOptions(e),new it({...e,deviceManager:this.deviceManager})}createCurtainsRenderer(e){return e=this.patchRendererOptions(e),new rt({...e,deviceManager:this.deviceManager})}setDeviceManager(){this.deviceManager=new _t({label:"GPUCurtains default device",production:this.options.production,onError:()=>setTimeout(()=>{this._onErrorCallback&&this._onErrorCallback()},0),onDeviceLost:e=>this._onContextLostCallback&&this._onContextLostCallback(e)})}get renderers(){return this.deviceManager.renderers}get renderer(){return this.renderers[0]}async setDevice(){await this.deviceManager.init()}async restoreContext(){await this.deviceManager.restoreDevice()}setCurtains(){this.initEvents(),this.setMainRenderer(),this.options.autoRender&&this.animate()}get pingPongPlanes(){return this.renderers?.map(e=>e.pingPongPlanes).flat()}get shaderPasses(){return this.renderers?.map(e=>e.shaderPasses).flat()}get meshes(){return this.renderers?.map(e=>e.meshes).flat()}get domMeshes(){return this.renderers?.filter(e=>e instanceof rt).map(e=>e.domMeshes).flat()}get planes(){return this.domMeshes.filter(e=>e instanceof jt)}get computePasses(){return this.renderers?.map(e=>e.computePasses).flat()}get camera(){return this.renderer?.camera}setPerspective({fov:e=50,near:t=.01,far:s=50}={}){this.renderer?.setPerspective({fov:e,near:t,far:s})}setCameraPosition(e=new f(0,0,1)){this.renderer?.setCameraPosition(e)}get boundingRect(){return this.renderer?.boundingRect}initScroll(){this.scrollManager=new Cs({scroll:{x:window.pageXOffset,y:window.pageYOffset},delta:{x:0,y:0},shouldWatch:this.options.watchScroll,onScroll:e=>this.updateScroll(e)})}updateScroll(e={x:0,y:0}){this.domMeshes.forEach(t=>{t.domElement&&t.updateScrollPosition(e)}),this._onScrollCallback&&this._onScrollCallback()}updateScrollValues(e={x:0,y:0}){this.scrollManager.updateScrollValues(e)}get scrollDelta(){return this.scrollManager.delta}get scrollValues(){return this.scrollManager.scroll}initEvents(){et.useObserver(this.options.autoResize),this.initScroll()}onRender(e){return e&&(this._onRenderCallback=e),this}onScroll(e){return e&&(this._onScrollCallback=e),this}onError(e){return e&&(this._onErrorCallback=e),this}onContextLost(e){return e&&(this._onContextLostCallback=e),this}animate(){this.render(),this.animationFrameID=window.requestAnimationFrame(this.animate.bind(this))}render(){this._onRenderCallback&&this._onRenderCallback(),this.deviceManager.render()}destroy(){this.animationFrameID&&window.cancelAnimationFrame(this.animationFrameID),this.deviceManager.destroy(),this.scrollManager?.destroy(),et.destroy()}}class Ss extends Ee{constructor({widthSegments:e=1,heightSegments:t=1,depthSegments:s=1,instancesCount:i=1,vertexBuffers:r=[],topology:n}={}){super({verticesOrder:"ccw",topology:n,instancesCount:i,vertexBuffers:r}),this.type="BoxGeometry",e=Math.floor(e),t=Math.floor(t),s=Math.floor(s);const a=[],h=[],u=[],d=[];let l=0;const c=(p,m,x,b,g,R,T,v,P,M)=>{const w=R/P,S=T/M,C=R/2,F=T/2,X=v/2,j=P+1,Z=M+1;let H=0;const G=new f;for(let A=0;A0?1:-1,u.push(G.x,G.y,G.z),h.push(L/P),h.push(A/M),H+=1}}for(let A=0;A0)&&b.push(M,w,C),(v!==t-1||l{const{scene:e}=o;if(!e)return;const t=[];e.computePassEntries.forEach(s=>{t.push({command:"Render ComputePass",content:s.options.label}),s.material.bindGroups.forEach(i=>{i.bufferBindings.forEach(r=>{r.shouldCopyResult&&t.push({command:"Copy buffer to buffer",source:`${r.name} buffer`,destination:`${r.name} result buffer`})})})});for(const s in e.renderPassEntries){let i=0;e.renderPassEntries[s].forEach(r=>{if(!e.getRenderPassEntryLength(r))return;const n=r.renderPass.options.useColorAttachments?r.renderPass.options.colorAttachments.length===0&&r.renderPass.options.useDepth?`${r.renderTexture.options.label} depth pass`:r.renderPass.options.colorAttachments.length>1?`${r.renderTexture.options.label} multiple targets`:r.renderTexture?`${r.renderTexture.options.label}`:"Context current texture":void 0;let a=r.renderPass.options.label;const h={loadOp:r.renderPass.options.useColorAttachments?s==="screen"&&i>0?"load":r.renderPass.options.loadOp:void 0,depthLoadOp:void 0,sampleCount:r.renderPass.options.sampleCount,...r.renderPass.options.qualityRatio!==1&&{qualityRatio:r.renderPass.options.qualityRatio}};if(r.renderPass.options.useDepth&&(h.depthLoadOp=r.renderPass.options.depthLoadOp),i++,r.element)r.element.type==="ShaderPass"&&!(r.element.inputTarget||r.element.outputTarget)&&(t.push({command:"Copy texture to texture",source:n,destination:`${r.element.options.label} renderTexture`}),h.loadOp="clear"),a+=" "+JSON.stringify(h),t.push({command:`Render ${r.element.type}`,source:r.element.options.label,destination:n,descriptor:a}),r.element.type==="ShaderPass"&&!r.element.outputTarget&&r.element.options.copyOutputToRenderTexture?t.push({command:"Copy texture to texture",source:n,destination:`${r.element.options.label} renderTexture`}):r.element.type==="PingPongPlane"&&t.push({command:"Copy texture to texture",source:n,destination:`${r.element.renderTexture.options.label}`});else if(r.stack){a+=" "+JSON.stringify(h);for(const u in r.stack)for(const d in r.stack[u])r.stack[u][d].length&&t.push({command:`Render stack (${u} ${d} objects)`,source:r.stack[u][d],destination:n,descriptor:a})}})}console.table(t)};y.BindGroup=ge,y.Binding=pe,y.Box3=oe,y.BoxGeometry=Ss,y.BufferBinding=ne,y.Camera=dt,y.ComputeMaterial=ft,y.ComputePass=is,y.ComputePipelineEntry=Ke,y.DOMElement=tt,y.DOMFrustum=xt,y.DOMMesh=It,y.DOMObject3D=Lt,y.FullscreenPlane=He,y.GPUCameraRenderer=it,y.GPUCurtains=Bs,y.GPUCurtainsRenderer=rt,y.GPUDeviceManager=_t,y.GPURenderer=st,y.Geometry=Ne,y.IndexedGeometry=Ee,y.Mat4=O,y.Material=We,y.Mesh=ls,y.Object3D=ye,y.PingPongPlane=Rs,y.PipelineEntry=Qe,y.PipelineManager=zt,y.Plane=jt,y.PlaneGeometry=Ye,y.ProjectedObject3D=Ze,y.Quat=N,y.RenderMaterial=wt,y.RenderPass=ze,y.RenderPipelineEntry=Je,y.RenderTarget=Dt,y.RenderTexture=J,y.Sampler=lt,y.SamplerBinding=ht,y.Scene=Ot,y.ShaderPass=Ps,y.SphereGeometry=Es,y.Texture=te,y.TextureBindGroup=je,y.TextureBinding=Ie,y.Vec2=E,y.Vec3=f,y.WritableBufferBinding=Ve,y.logSceneCommands=Gs}); //# sourceMappingURL=gpu-curtains.umd.min.js.map diff --git a/dist/gpu-curtains.umd.min.js.map b/dist/gpu-curtains.umd.min.js.map index c412f396d..54bacfc3d 100644 --- a/dist/gpu-curtains.umd.min.js.map +++ b/dist/gpu-curtains.umd.min.js.map @@ -1 +1 @@ -{"version":3,"file":"gpu-curtains.umd.min.js","sources":["../src/utils/utils.ts","../src/core/renderers/utils.ts","../src/core/bindings/Binding.ts","../src/core/bindings/utils.ts","../src/math/Vec2.ts","../src/math/Quat.ts","../src/math/Vec3.ts","../src/core/bindings/bufferElements/BufferElement.ts","../src/core/bindings/bufferElements/BufferArrayElement.ts","../src/core/bindings/bufferElements/BufferInterleavedArrayElement.ts","../src/core/bindings/BufferBinding.ts","../src/core/bindings/WritableBufferBinding.ts","../src/core/bindGroups/BindGroup.ts","../src/core/bindings/TextureBinding.ts","../src/math/Mat4.ts","../src/core/objects3D/Object3D.ts","../src/core/textures/Texture.ts","../src/core/bindGroups/TextureBindGroup.ts","../src/core/bindings/SamplerBinding.ts","../src/core/camera/Camera.ts","../src/core/samplers/Sampler.ts","../src/core/textures/RenderTexture.ts","../src/core/materials/Material.ts","../src/core/materials/ComputeMaterial.ts","../src/core/computePasses/ComputePass.ts","../src/math/Box3.ts","../src/core/DOM/DOMFrustum.ts","../src/core/geometries/Geometry.ts","../src/core/geometries/IndexedGeometry.ts","../src/core/geometries/PlaneGeometry.ts","../src/core/materials/RenderMaterial.ts","../src/core/shaders/chunks/default_vs.wgsl.js","../src/core/shaders/chunks/default_fs.wgsl.js","../src/core/meshes/mixins/MeshBaseMixin.ts","../src/utils/CacheManager.ts","../src/core/meshes/FullscreenPlane.ts","../src/core/objects3D/ProjectedObject3D.ts","../src/core/shaders/chunks/default_projected_vs.wgsl.js","../src/core/shaders/chunks/default_normal_fs.wgsl.js","../src/core/meshes/mixins/ProjectedMeshBaseMixin.ts","../src/core/meshes/Mesh.ts","../src/core/pipelines/PipelineEntry.ts","../src/core/shaders/chunks/get_output_position.wgsl.js","../src/core/shaders/chunks/get_uv_cover.wgsl.js","../src/core/shaders/chunks/get_vertex_to_uv_coords.wgsl.js","../src/core/shaders/ShaderChunks.ts","../src/core/pipelines/RenderPipelineEntry.ts","../src/core/pipelines/ComputePipelineEntry.ts","../src/core/pipelines/PipelineManager.ts","../src/utils/ResizeManager.ts","../src/core/DOM/DOMElement.ts","../src/core/scenes/Scene.ts","../src/core/renderPasses/RenderPass.ts","../src/utils/TasksQueueManager.ts","../src/core/renderers/GPURenderer.ts","../src/core/renderers/GPUCameraRenderer.ts","../src/core/renderers/GPUDeviceManager.ts","../src/core/renderPasses/RenderTarget.ts","../src/core/shaders/chunks/default_pass_fs.wgsl.js","../src/core/renderPasses/ShaderPass.ts","../src/curtains/objects3D/DOMObject3D.ts","../src/curtains/meshes/DOMMesh.ts","../src/curtains/meshes/PingPongPlane.ts","../src/curtains/meshes/Plane.ts","../src/curtains/renderers/GPUCurtainsRenderer.ts","../src/utils/ScrollManager.ts","../src/curtains/GPUCurtains.ts","../src/extras/geometries/BoxGeometry.ts","../src/extras/geometries/SphereGeometry.ts","../src/utils/debug.ts"],"sourcesContent":["/**\n * Generate a unique universal id\n * @returns - unique universal id generated\n */\nexport const generateUUID = (): string => {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0,\n v = c === 'x' ? r : (r & 0x3) | 0x8\n return v.toString(16).toUpperCase()\n })\n}\n\n/**\n * Turns a string into a camel case string\n * @param string - string to transform\n * @returns - camel case string created\n */\nexport const toCamelCase = (string: string): string => {\n return string\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, (ltr, idx) => (idx === 0 ? ltr.toLowerCase() : ltr.toUpperCase()))\n .replace(/\\s+/g, '')\n}\n\n/**\n * Turns a string into a kebab case string\n * @param string - string to transform\n * @returns - kebab case string created\n */\nexport const toKebabCase = (string: string): string => {\n const camelCase = toCamelCase(string)\n return camelCase.charAt(0).toUpperCase() + camelCase.slice(1)\n}\n\nlet warningThrown = 0\n\n/**\n * Throw a console warning with the passed arguments\n * @param warning - warning to be thrown\n */\nexport const throwWarning = (warning: string) => {\n if (warningThrown > 100) {\n return\n } else if (warningThrown === 100) {\n console.warn('GPUCurtains: too many warnings thrown, stop logging.')\n } else {\n console.warn(warning)\n }\n\n warningThrown++\n}\n\n/**\n * Throw a javascript error with the passed arguments\n * @param error - error to be thrown\n */\nexport const throwError = (error: string) => {\n throw new Error(error)\n}\n","import { throwError } from '../../utils/utils'\nimport { GPURenderer } from './GPURenderer'\nimport { GPUCameraRenderer } from './GPUCameraRenderer'\nimport { GPUCurtainsRenderer } from '../../curtains/renderers/GPUCurtainsRenderer'\nimport { WritableBufferBinding } from '../bindings/WritableBufferBinding'\n\n/**\n * A Renderer could be either a {@link GPURenderer}, a {@link GPUCameraRenderer} or a {@link GPUCurtainsRenderer}\n * @type {Renderer}\n */\nexport type Renderer = GPUCurtainsRenderer | GPUCameraRenderer | GPURenderer\n/**\n * A CameraRenderer could be either a {@link GPUCameraRenderer} or a {@link GPUCurtainsRenderer}\n * @type {CameraRenderer}\n */\nexport type CameraRenderer = GPUCurtainsRenderer | GPUCameraRenderer\n\n/**\n * Format a renderer error based on given renderer, renderer type and object type\n * @param renderer - renderer that failed the test\n * @param rendererType - expected renderer type\n * @param type - object type\n */\nconst formatRendererError = (renderer: Renderer, rendererType = 'GPURenderer', type: string | null): void => {\n const error = type\n ? `Unable to create ${type} because the ${rendererType} is not defined: ${renderer}`\n : `The ${rendererType} is not defined: ${renderer}`\n throwError(error)\n}\n\n/**\n * Check if the given renderer is a {@link Renderer}\n * @param renderer - renderer to test\n * @param type - object type used to format the error if needed\n * @returns - whether the given renderer is a {@link Renderer}\n */\nexport const isRenderer = (renderer: Renderer | undefined, type: string | null): boolean => {\n const isRenderer =\n renderer &&\n (renderer.type === 'GPURenderer' ||\n renderer.type === 'GPUCameraRenderer' ||\n renderer.type === 'GPUCurtainsRenderer')\n\n if (!isRenderer) {\n formatRendererError(renderer, 'GPURenderer', type)\n }\n\n return isRenderer\n}\n\n/**\n * Check if the given renderer is a {@link CameraRenderer}\n * @param renderer - renderer to test\n * @param type - object type used to format the error if needed\n * @returns - whether the given renderer is a {@link CameraRenderer}\n */\nexport const isCameraRenderer = (renderer: CameraRenderer | undefined, type: string | null): boolean => {\n const isCameraRenderer =\n renderer && (renderer.type === 'GPUCameraRenderer' || renderer.type === 'GPUCurtainsRenderer')\n\n if (!isCameraRenderer) {\n formatRendererError(renderer, 'GPUCameraRenderer', type)\n }\n\n return isCameraRenderer\n}\n\n/**\n * Check if the given renderer is a {@link GPUCurtainsRenderer}\n * @param renderer - renderer to test\n * @param type - object type used to format the error if needed\n * @returns - whether the given renderer is a {@link GPUCurtainsRenderer}\n */\nexport const isCurtainsRenderer = (renderer: GPUCurtainsRenderer | undefined, type: string | null): boolean => {\n const isCurtainsRenderer = renderer && renderer.type === 'GPUCurtainsRenderer'\n\n if (!isCurtainsRenderer) {\n formatRendererError(renderer, 'GPUCurtainsRenderer', type)\n }\n\n return isCurtainsRenderer\n}\n\n/**\n * Helper to generate mips on the GPU\n * Taken from https://webgpufundamentals.org/webgpu/lessons/webgpu-importing-textures.html\n */\nexport const generateMips = (() => {\n let sampler\n let module\n const pipelineByFormat = {}\n\n return function generateMips(device: GPUDevice, texture: GPUTexture) {\n if (!module) {\n module = device.createShaderModule({\n label: 'textured quad shaders for mip level generation',\n code: `\n struct VSOutput {\n @builtin(position) position: vec4f,\n @location(0) texcoord: vec2f,\n };\n\n @vertex fn vs(\n @builtin(vertex_index) vertexIndex : u32\n ) -> VSOutput {\n var pos = array(\n\n vec2f( 0.0, 0.0), // center\n vec2f( 1.0, 0.0), // right, center\n vec2f( 0.0, 1.0), // center, top\n\n // 2st triangle\n vec2f( 0.0, 1.0), // center, top\n vec2f( 1.0, 0.0), // right, center\n vec2f( 1.0, 1.0), // right, top\n );\n\n var vsOutput: VSOutput;\n let xy = pos[vertexIndex];\n vsOutput.position = vec4f(xy * 2.0 - 1.0, 0.0, 1.0);\n vsOutput.texcoord = vec2f(xy.x, 1.0 - xy.y);\n return vsOutput;\n }\n\n @group(0) @binding(0) var ourSampler: sampler;\n @group(0) @binding(1) var ourTexture: texture_2d;\n\n @fragment fn fs(fsInput: VSOutput) -> @location(0) vec4f {\n return textureSample(ourTexture, ourSampler, fsInput.texcoord);\n }\n `,\n })\n\n sampler = device.createSampler({\n minFilter: 'linear',\n })\n }\n\n if (!pipelineByFormat[texture.format]) {\n pipelineByFormat[texture.format] = device.createRenderPipeline({\n label: 'mip level generator pipeline',\n layout: 'auto',\n vertex: {\n module,\n entryPoint: 'vs',\n },\n fragment: {\n module,\n entryPoint: 'fs',\n targets: [{ format: texture.format }],\n },\n })\n }\n const pipeline = pipelineByFormat[texture.format]\n\n const encoder = device.createCommandEncoder({\n label: 'mip gen encoder',\n })\n\n let width = texture.width\n let height = texture.height\n let baseMipLevel = 0\n while (width > 1 || height > 1) {\n width = Math.max(1, (width / 2) | 0)\n height = Math.max(1, (height / 2) | 0)\n\n const bindGroup = device.createBindGroup({\n layout: pipeline.getBindGroupLayout(0),\n entries: [\n { binding: 0, resource: sampler },\n {\n binding: 1,\n resource: texture.createView({\n baseMipLevel,\n mipLevelCount: 1,\n }),\n },\n ],\n })\n\n ++baseMipLevel\n\n const renderPassDescriptor = {\n label: 'our basic canvas renderPass',\n colorAttachments: [\n {\n view: texture.createView({ baseMipLevel, mipLevelCount: 1 }),\n loadOp: 'clear',\n storeOp: 'store',\n },\n ],\n }\n\n const pass = encoder.beginRenderPass(renderPassDescriptor as GPURenderPassDescriptor)\n pass.setPipeline(pipeline)\n pass.setBindGroup(0, bindGroup)\n pass.draw(6) // call our vertex shader 6 times\n pass.end()\n }\n\n const commandBuffer = encoder.finish()\n device.queue.submit([commandBuffer])\n }\n})()\n","import { toCamelCase } from '../../utils/utils'\nimport { MaterialShadersType } from '../../types/Materials'\nimport { TextureBinding } from './TextureBinding'\nimport { SamplerBinding } from './SamplerBinding'\n\n/** Defines all kind of texture binding types */\nexport type TextureBindingType = 'texture' | 'externalTexture' | 'storage' | 'depth'\n/** Defines all kind of binding types */\nexport type BindingType = 'uniform' | 'storage' | TextureBindingType | 'sampler'\n\n// see https://www.w3.org/TR/WGSL/#memory-access-mode\n/** Defines buffer binding memory access types (read only or read/write) */\nexport type BufferBindingMemoryAccessType = 'read' | 'read_write'\n/** Defines texture binding memory access types (read only, write only or read/write) */\nexport type BindingMemoryAccessType = BufferBindingMemoryAccessType | 'write'\n\n/**\n * Defines all kind of {@link Binding} that are related to textures or samplers\n */\nexport type TextureSamplerBindings = TextureBinding | SamplerBinding\n\n/**\n * An object defining all possible {@link Binding} class instancing parameters\n */\nexport interface BindingParams {\n /** {@link Binding} label */\n label?: string\n /** {@link Binding} name/key */\n name?: string\n /** {@link BindingType | binding type} to use with this {@link Binding} */\n bindingType?: BindingType\n /** {@link Binding} variables shaders visibility */\n visibility?: MaterialShadersType | null\n}\n\n/**\n * Used as a shell to build actual bindings upon, like {@link core/bindings/BufferBinding.BufferBinding | BufferBinding}, {@link core/bindings/WritableBufferBinding.WritableBufferBinding | WritableBufferBinding}, {@link TextureBinding} and {@link SamplerBinding}.\n *\n * Ultimately the goal of a {@link Binding} element is to provide correct resources for {@link GPUBindGroupLayoutEntry} and {@link GPUBindGroupEntry}\n *\n * ## WGSL\n *\n * Each {@link Binding} creates its own WGSL code snippet variable declaration, using structured types or not.\n */\nexport class Binding {\n /** The label of the {@link Binding} */\n label: string\n /** The name/key of the {@link Binding} */\n name: string\n /** The binding type of the {@link Binding} */\n bindingType: BindingType\n /** The visibility of the {@link Binding} in the shaders */\n visibility: GPUShaderStageFlags\n /** Options used to create this {@link Binding} */\n options: BindingParams\n\n /** Flag indicating whether we should recreate the parentMesh {@link core/bindGroups/BindGroup.BindGroup#bindGroup | bind group}, usually when a resource has changed */\n shouldResetBindGroup: boolean\n /** Flag indicating whether we should recreate the parentMesh {@link core/bindGroups/BindGroup.BindGroup#bindGroupLayout | GPU bind group layout}, usually when a resource layout has changed */\n shouldResetBindGroupLayout: boolean\n\n /**\n * Binding constructor\n * @param parameters - {@link BindingParams | parameters} used to create our {@link Binding}\n */\n constructor({ label = 'Uniform', name = 'uniform', bindingType = 'uniform', visibility }: BindingParams) {\n this.label = label\n this.name = toCamelCase(name)\n this.bindingType = bindingType\n\n this.visibility = visibility\n ? (() => {\n switch (visibility) {\n case 'vertex':\n return GPUShaderStage.VERTEX\n case 'fragment':\n return GPUShaderStage.FRAGMENT\n case 'compute':\n return GPUShaderStage.COMPUTE\n default:\n return GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE\n }\n })()\n : GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE\n\n this.options = {\n label,\n name,\n bindingType,\n visibility,\n }\n\n this.shouldResetBindGroup = false\n this.shouldResetBindGroupLayout = false\n }\n}\n","import { BindingType } from './Binding'\nimport { BufferBinding } from './BufferBinding'\nimport { TextureBinding } from './TextureBinding'\n\n/** Defines a typed array */\nexport type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array\n\n/** Defines a typed array constructor */\nexport type TypedArrayConstructor =\n | Int8ArrayConstructor\n | Uint8ArrayConstructor\n | Int16ArrayConstructor\n | Uint16ArrayConstructor\n | Int32ArrayConstructor\n | Uint32ArrayConstructor\n | Float32ArrayConstructor\n | Float64ArrayConstructor\n\n/** Defines the possible WGSL variable types */\nexport type WGSLVariableType = string // TODO 'mat4x4f', 'mat3x3f', 'vec3f', 'vec2f', 'f32' etc\n\n/**\n * Defines a {@link BufferLayout} object used to pad our {@link GPUBuffer} arrays\n */\nexport type BufferLayout = {\n /** Number of elements hold by this variable type */\n numElements: number\n /** Required alignment by this variable type */\n align: number\n /** Size in bytes of this variable type */\n size: number\n /** Variable type */\n type: WGSLVariableType\n /** Typed array constructor required by this variable type */\n View: TypedArrayConstructor\n /** Pad values required by this variable type */\n pad?: number[]\n}\n\n// from https://github.com/greggman/webgpu-utils/blob/main/src/buffer-views.ts\n/**\n * Get the correct [buffer layout]{@link BufferLayout} for given [variable type]{@link WGSLVariableType}\n * @param bufferType - [variable type]{@link WGSLVariableType} to use\n * @returns - the [buffer layout]{@link BufferLayout}\n */\nexport const getBufferLayout = (bufferType: WGSLVariableType): BufferLayout => {\n const bufferLayouts = {\n i32: { numElements: 1, align: 4, size: 4, type: 'i32', View: Int32Array },\n u32: { numElements: 1, align: 4, size: 4, type: 'u32', View: Uint32Array },\n f32: { numElements: 1, align: 4, size: 4, type: 'f32', View: Float32Array },\n f16: { numElements: 1, align: 2, size: 2, type: 'u16', View: Uint16Array },\n\n vec2f: { numElements: 2, align: 8, size: 8, type: 'f32', View: Float32Array },\n vec2i: { numElements: 2, align: 8, size: 8, type: 'i32', View: Int32Array },\n vec2u: { numElements: 2, align: 8, size: 8, type: 'u32', View: Uint32Array },\n vec2h: { numElements: 2, align: 4, size: 4, type: 'u16', View: Uint16Array },\n vec3i: { numElements: 3, align: 16, size: 12, type: 'i32', View: Int32Array },\n vec3u: { numElements: 3, align: 16, size: 12, type: 'u32', View: Uint32Array },\n vec3f: { numElements: 3, align: 16, size: 12, type: 'f32', View: Float32Array },\n vec3h: { numElements: 3, align: 8, size: 6, type: 'u16', View: Uint16Array },\n vec4i: { numElements: 4, align: 16, size: 16, type: 'i32', View: Int32Array },\n vec4u: { numElements: 4, align: 16, size: 16, type: 'u32', View: Uint32Array },\n vec4f: { numElements: 4, align: 16, size: 16, type: 'f32', View: Float32Array },\n vec4h: { numElements: 4, align: 8, size: 8, type: 'u16', View: Uint16Array },\n\n // AlignOf(vecR)\tSizeOf(array)\n mat2x2f: { numElements: 4, align: 8, size: 16, type: 'f32', View: Float32Array },\n mat2x2h: { numElements: 4, align: 4, size: 8, type: 'u16', View: Uint16Array },\n mat3x2f: { numElements: 6, align: 8, size: 24, type: 'f32', View: Float32Array },\n mat3x2h: { numElements: 6, align: 4, size: 12, type: 'u16', View: Uint16Array },\n mat4x2f: { numElements: 8, align: 8, size: 32, type: 'f32', View: Float32Array },\n mat4x2h: { numElements: 8, align: 4, size: 16, type: 'u16', View: Uint16Array },\n mat2x3f: { numElements: 8, align: 16, size: 32, pad: [3, 1], type: 'f32', View: Float32Array },\n mat2x3h: { numElements: 8, align: 8, size: 16, pad: [3, 1], type: 'u16', View: Uint16Array },\n mat3x3f: { numElements: 12, align: 16, size: 48, pad: [3, 1], type: 'f32', View: Float32Array },\n mat3x3h: { numElements: 12, align: 8, size: 24, pad: [3, 1], type: 'u16', View: Uint16Array },\n mat4x3f: { numElements: 16, align: 16, size: 64, pad: [3, 1], type: 'f32', View: Float32Array },\n mat4x3h: { numElements: 16, align: 8, size: 32, pad: [3, 1], type: 'u16', View: Uint16Array },\n mat2x4f: { numElements: 8, align: 16, size: 32, type: 'f32', View: Float32Array },\n mat2x4h: { numElements: 8, align: 8, size: 16, type: 'u16', View: Uint16Array },\n mat3x4f: { numElements: 12, align: 16, size: 48, pad: [3, 1], type: 'f32', View: Float32Array },\n mat3x4h: { numElements: 12, align: 8, size: 24, pad: [3, 1], type: 'u16', View: Uint16Array },\n mat4x4f: { numElements: 16, align: 16, size: 64, type: 'f32', View: Float32Array },\n mat4x4h: { numElements: 16, align: 8, size: 32, type: 'u16', View: Uint16Array },\n }\n\n return bufferLayouts[bufferType]\n}\n\n/**\n * Get the correct WGSL variable declaration code fragment based on the given [buffer binding]{@link BufferBinding}\n * @param binding - [buffer binding]{@link BufferBinding} to use\n * @returns - WGSL variable declaration code fragment\n */\nexport const getBindingWGSLVarType = (binding: BufferBinding): string => {\n return (() => {\n switch (binding.bindingType) {\n case 'storage':\n return `var<${binding.bindingType}, ${binding.options.access}>`\n case 'uniform':\n default:\n return 'var'\n }\n })()\n}\n\n/**\n * Get the correct WGSL variable declaration code fragment based on the given [texture binding]{@link TextureBinding}\n * @param binding - [texture binding]{@link TextureBinding} to use\n * @returns - WGSL variable declaration code fragment\n */\nexport const getTextureBindingWGSLVarType = (binding: TextureBinding): string => {\n if (binding.bindingType === 'externalTexture') {\n return `var ${binding.name}: texture_external;`\n }\n\n return binding.bindingType === 'storage'\n ? `var ${binding.name}: texture_storage_${binding.options.viewDimension}<${binding.options.format}, ${binding.options.access}>;`\n : binding.bindingType === 'depth'\n ? `var ${binding.name}: texture_depth${binding.options.multisampled ? '_multisampled' : ''}_${\n binding.options.viewDimension\n };`\n : `var ${binding.name}: texture${binding.options.multisampled ? '_multisampled' : ''}_${\n binding.options.viewDimension\n };`\n}\n\n/**\n * Get the correct [bind group layout]{@link GPUBindGroupLayout} resource type based on the given [binding type]{@link BindingType}\n * @param binding - [buffer binding]{@link BufferBinding} to use\n * @returns - {@link GPUBindGroupLayout | bind group layout} resource type\n */\nexport const getBindGroupLayoutBindingType = (binding: BufferBinding): GPUBufferBindingType => {\n if (binding.bindingType === 'storage' && binding.options.access === 'read_write') {\n return 'storage'\n } else if (binding.bindingType === 'storage') {\n return 'read-only-storage'\n } else {\n return 'uniform'\n }\n}\n\n/**\n * Get the correct [bind group layout]{@link GPUBindGroupLayout} resource type based on the given [texture binding type]{@link BindingType}\n * @param binding - [texture binding]{@link TextureBinding} to use\n * @returns - [bind group layout]{@link GPUBindGroupLayout} resource type\n */\nexport const getBindGroupLayoutTextureBindingType = (\n binding: TextureBinding\n): GPUTextureBindingLayout | GPUExternalTextureBindingLayout | GPUStorageTextureBindingLayout | null => {\n return (() => {\n switch (binding.bindingType) {\n case 'externalTexture':\n return { externalTexture: {} }\n case 'storage':\n return {\n storageTexture: {\n format: binding.options.format,\n viewDimension: binding.options.viewDimension,\n } as GPUStorageTextureBindingLayout,\n }\n case 'texture':\n return {\n texture: {\n multisampled: binding.options.multisampled,\n viewDimension: binding.options.viewDimension,\n sampleType: binding.options.multisampled ? 'unfilterable-float' : 'float',\n } as GPUTextureBindingLayout,\n }\n case 'depth':\n return {\n texture: {\n multisampled: binding.options.multisampled,\n format: binding.options.format,\n viewDimension: binding.options.viewDimension,\n sampleType: 'depth',\n } as GPUTextureBindingLayout,\n }\n default:\n return null\n }\n })()\n}\n","/**\n * Really basic 2D vector class used for vector calculations\n * @see https://github.com/mrdoob/three.js/blob/dev/src/math/Vector2.js\n * @see http://glmatrix.net/docs/vec2.js.html\n */\nexport class Vec2 {\n /** The type of the {@link Vec2} */\n type: string\n /** X component of our {@link Vec2} */\n private _x: number\n /** Y component of our {@link Vec2} */\n private _y: number\n\n /** function assigned to the {@link onChange} callback */\n _onChangeCallback?(): void\n\n /**\n * Vec2 constructor\n * @param x - X component of our {@link Vec2}\n * @param y - Y component of our {@link Vec2}\n */\n constructor(x = 0, y = x) {\n this.type = 'Vec2'\n\n this._x = x\n this._y = y\n }\n\n /**\n * Get the X component of the {@link Vec2}\n */\n get x(): number {\n return this._x\n }\n\n /**\n * Set the X component of the {@link Vec2}\n * Can trigger {@link onChange} callback\n * @param value - X component to set\n */\n set x(value: number) {\n const changed = value !== this._x\n this._x = value\n changed && this._onChangeCallback && this._onChangeCallback()\n }\n\n /**\n * Get the Y component of the {@link Vec2}\n */\n get y(): number {\n return this._y\n }\n\n /**\n * Set the Y component of the {@link Vec2}\n * Can trigger {@link onChange} callback\n * @param value - Y component to set\n */\n set y(value: number) {\n const changed = value !== this._y\n this._y = value\n changed && this._onChangeCallback && this._onChangeCallback()\n }\n\n /**\n * Called when at least one component of the {@link Vec2} has changed\n * @param callback - callback to run when at least one component of the {@link Vec2} has changed\n * @returns - our {@link Vec2}\n */\n onChange(callback: () => void): Vec2 {\n if (callback) {\n this._onChangeCallback = callback\n }\n\n return this\n }\n\n /**\n * Set the {@link Vec2} from values\n * @param x - new X component to set\n * @param y - new Y component to set\n * @returns - this {@link Vec2} after being set\n */\n set(x = 0, y = x): Vec2 {\n this.x = x\n this.y = y\n\n return this\n }\n\n /**\n * Add a {@link Vec2} to this {@link Vec2}\n * @param vector - {@link Vec2} to add\n * @returns - this {@link Vec2} after addition\n */\n add(vector: Vec2 = new Vec2()): Vec2 {\n this.x += vector.x\n this.y += vector.y\n\n return this\n }\n\n /**\n * Add a scalar to all the components of this {@link Vec2}\n * @param value - number to add\n * @returns - this {@link Vec2} after addition\n */\n addScalar(value = 0): Vec2 {\n this.x += value\n this.y += value\n\n return this\n }\n\n /**\n * Subtract a {@link Vec2} from this {@link Vec2}\n * @param vector - {@link Vec2} to subtract\n * @returns - this {@link Vec2} after subtraction\n */\n sub(vector: Vec2 = new Vec2()): Vec2 {\n this.x -= vector.x\n this.y -= vector.y\n\n return this\n }\n\n /**\n * Subtract a scalar to all the components of this {@link Vec2}\n * @param value - number to subtract\n * @returns - this {@link Vec2} after subtraction\n */\n subScalar(value = 0): Vec2 {\n this.x -= value\n this.y -= value\n\n return this\n }\n\n /**\n * Multiply a {@link Vec2} with this {@link Vec2}\n * @param vector - {@link Vec2} to multiply with\n * @returns - this {@link Vec2} after multiplication\n */\n multiply(vector: Vec2 = new Vec2(1)): Vec2 {\n this.x *= vector.x\n this.y *= vector.y\n\n return this\n }\n\n /**\n * Multiply all components of this {@link Vec2} with a scalar\n * @param value - number to multiply with\n * @returns - this {@link Vec2} after multiplication\n */\n multiplyScalar(value = 1): Vec2 {\n this.x *= value\n this.y *= value\n\n return this\n }\n\n /**\n * Divide a {@link Vec2} with this {@link Vec2}\n * @param vector - {@link Vec2} to divide with\n * @returns - this {@link Vec2} after division\n */\n divide(vector: Vec2 = new Vec2(1)): Vec2 {\n this.x /= vector.x\n this.y /= vector.y\n\n return this\n }\n\n /**\n * Divide all components of this {@link Vec2} with a scalar\n * @param value - number to divide with\n * @returns - this {@link Vec2} after division\n */\n divideScalar(value = 1): Vec2 {\n this.x /= value\n this.y /= value\n\n return this\n }\n\n /**\n * Copy a {@link Vec2} into this {@link Vec2}\n * @param vector - {@link Vec2} to copy\n * @returns - this {@link Vec2} after copy\n */\n copy(vector: Vec2 = new Vec2()): Vec2 {\n this.x = vector.x\n this.y = vector.y\n\n return this\n }\n\n /**\n * Clone this {@link Vec2}\n * @returns - cloned {@link Vec2}\n */\n clone(): Vec2 {\n return new Vec2(this.x, this.y)\n }\n\n /**\n * Apply max values to this {@link Vec2} components\n * @param vector - {@link Vec2} representing max values\n * @returns - {@link Vec2} with max values applied\n */\n max(vector: Vec2 = new Vec2()): Vec2 {\n this.x = Math.max(this.x, vector.x)\n this.y = Math.max(this.y, vector.y)\n\n return this\n }\n\n /**\n * Apply min values to this {@link Vec2} components\n * @param vector - {@link Vec2} representing min values\n * @returns - {@link Vec2} with min values applied\n */\n min(vector: Vec2 = new Vec2()): Vec2 {\n this.x = Math.min(this.x, vector.x)\n this.y = Math.min(this.y, vector.y)\n\n return this\n }\n\n /**\n * Clamp this {@link Vec2} components by min and max {@link Vec2} vectors\n * @param min - minimum {@link Vec2} components to compare with\n * @param max - maximum {@link Vec2} components to compare with\n * @returns - clamped {@link Vec2}\n */\n clamp(min: Vec2 = new Vec2(), max: Vec2 = new Vec2()): Vec2 {\n this.x = Math.max(min.x, Math.min(max.x, this.x))\n this.y = Math.max(min.y, Math.min(max.y, this.y))\n\n return this\n }\n\n /**\n * Check if 2 {@link Vec2} are equal\n * @param vector - {@link Vec2} to compare\n * @returns - whether the {@link Vec2} are equals or not\n */\n equals(vector: Vec2 = new Vec2()): boolean {\n return this.x === vector.x && this.y === vector.y\n }\n\n /**\n * Get the square length of this {@link Vec2}\n * @returns - square length of this {@link Vec2}\n */\n lengthSq(): number {\n return this.x * this.x + this.y * this.y\n }\n\n /**\n * Get the length of this {@link Vec2}\n * @returns - length of this {@link Vec2}\n */\n length(): number {\n return Math.sqrt(this.lengthSq())\n }\n\n /**\n * Normalize this {@link Vec2}\n * @returns - normalized {@link Vec2}\n */\n normalize(): Vec2 {\n // normalize\n let len = this.x * this.x + this.y * this.y\n if (len > 0) {\n len = 1 / Math.sqrt(len)\n }\n this.x *= len\n this.y *= len\n\n return this\n }\n\n /**\n * Calculate the dot product of 2 {@link Vec2}\n * @param vector - {@link Vec2} to use for dot product\n * @returns - dot product of the 2 {@link Vec2}\n */\n dot(vector: Vec2 = new Vec2()): number {\n return this.x * vector.x + this.y * vector.y\n }\n\n /**\n * Calculate the linear interpolation of this {@link Vec2} by given {@link Vec2} and alpha, where alpha is the percent distance along the line\n * @param vector - {@link Vec2} to interpolate towards\n * @param [alpha=1] - interpolation factor in the [0, 1] interval\n * @returns - this {@link Vec2} after linear interpolation\n */\n lerp(vector: Vec2 = new Vec2(), alpha = 1): Vec2 {\n this.x += (vector.x - this.x) * alpha\n this.y += (vector.y - this.y) * alpha\n\n return this\n }\n}\n","import { Vec3 } from './Vec3'\nimport { Mat4 } from './Mat4'\n\n/** Defines all possible rotations axis orders */\nexport type AxisOrder = 'XYZ' | 'XZY' | 'YXZ' | 'YZX' | 'ZXY' | 'ZYX'\n\n/**\n * Really basic quaternion class used for 3D rotation calculations\n * @see https://github.com/mrdoosb/three.js/blob/dev/src/math/Quaternion.js\n */\nexport class Quat {\n /** The type of the {@link Quat} */\n type: string\n /** Our quaternion array */\n elements: Float32Array\n /** Rotation axis order */\n axisOrder: AxisOrder\n\n /**\n * Quat constructor\n * @param [elements] - initial array to use\n * @param [axisOrder='XYZ'] - axis order to use\n */\n constructor(elements: Float32Array = new Float32Array([0, 0, 0, 1]), axisOrder: AxisOrder = 'XYZ') {\n this.type = 'Quat'\n this.elements = elements\n // rotation axis order\n this.axisOrder = axisOrder\n }\n\n /**\n * Sets the {@link Quat} values from an array\n * @param array - an array of at least 4 elements\n * @returns - this {@link Quat} after being set\n */\n setFromArray(array: Float32Array | number[] = new Float32Array([0, 0, 0, 1])): Quat {\n this.elements[0] = array[0]\n this.elements[1] = array[1]\n this.elements[2] = array[2]\n this.elements[3] = array[3]\n\n return this\n }\n\n /**\n * Sets the {@link Quat} axis order\n * @param axisOrder - axis order to use\n * @returns - this {@link Quat} after axis order has been set\n */\n setAxisOrder(axisOrder: AxisOrder | string = 'XYZ'): Quat {\n // force uppercase for strict equality tests\n axisOrder = axisOrder.toUpperCase()\n\n switch (axisOrder) {\n case 'XYZ':\n case 'YXZ':\n case 'ZXY':\n case 'ZYX':\n case 'YZX':\n case 'XZY':\n this.axisOrder = axisOrder\n break\n default:\n // apply a default axis order\n this.axisOrder = 'XYZ'\n }\n\n return this\n }\n\n /**\n * Copy a {@link Quat} into this {@link Quat}\n * @param quaternion - {@link Quat} to copy\n * @returns - this {@link Quat} after copy\n */\n copy(quaternion: Quat = new Quat()): Quat {\n this.elements = quaternion.elements\n this.axisOrder = quaternion.axisOrder\n\n return this\n }\n\n /**\n * Clone a {@link Quat}\n * @returns - cloned {@link Quat}\n */\n clone(): Quat {\n return new Quat().copy(this)\n }\n\n /**\n * Check if 2 {@link Quat} are equal\n * @param quaternion - {@link Quat} to check against\n * @returns - whether the {@link Quat} are equal or not\n */\n equals(quaternion: Quat = new Quat()): boolean {\n return (\n this.elements[0] === quaternion.elements[0] &&\n this.elements[1] === quaternion.elements[1] &&\n this.elements[2] === quaternion.elements[2] &&\n this.elements[3] === quaternion.elements[3] &&\n this.axisOrder === quaternion.axisOrder\n )\n }\n\n /**\n * Sets a rotation {@link Quat} using Euler angles {@link Vec3 | vector} and its axis order\n * @param vector - rotation {@link Vec3 | vector} to set our {@link Quat} from\n * @returns - {@link Quat} after having applied the rotation\n */\n setFromVec3(vector: Vec3): Quat {\n const ax = vector.x * 0.5\n const ay = vector.y * 0.5\n const az = vector.z * 0.5\n\n const cosx = Math.cos(ax)\n const cosy = Math.cos(ay)\n const cosz = Math.cos(az)\n const sinx = Math.sin(ax)\n const siny = Math.sin(ay)\n const sinz = Math.sin(az)\n\n // XYZ order\n if (this.axisOrder === 'XYZ') {\n this.elements[0] = sinx * cosy * cosz + cosx * siny * sinz\n this.elements[1] = cosx * siny * cosz - sinx * cosy * sinz\n this.elements[2] = cosx * cosy * sinz + sinx * siny * cosz\n this.elements[3] = cosx * cosy * cosz - sinx * siny * sinz\n } else if (this.axisOrder === 'YXZ') {\n this.elements[0] = sinx * cosy * cosz + cosx * siny * sinz\n this.elements[1] = cosx * siny * cosz - sinx * cosy * sinz\n this.elements[2] = cosx * cosy * sinz - sinx * siny * cosz\n this.elements[3] = cosx * cosy * cosz + sinx * siny * sinz\n } else if (this.axisOrder === 'ZXY') {\n this.elements[0] = sinx * cosy * cosz - cosx * siny * sinz\n this.elements[1] = cosx * siny * cosz + sinx * cosy * sinz\n this.elements[2] = cosx * cosy * sinz + sinx * siny * cosz\n this.elements[3] = cosx * cosy * cosz - sinx * siny * sinz\n } else if (this.axisOrder === 'ZYX') {\n this.elements[0] = sinx * cosy * cosz - cosx * siny * sinz\n this.elements[1] = cosx * siny * cosz + sinx * cosy * sinz\n this.elements[2] = cosx * cosy * sinz - sinx * siny * cosz\n this.elements[3] = cosx * cosy * cosz + sinx * siny * sinz\n } else if (this.axisOrder === 'YZX') {\n this.elements[0] = sinx * cosy * cosz + cosx * siny * sinz\n this.elements[1] = cosx * siny * cosz + sinx * cosy * sinz\n this.elements[2] = cosx * cosy * sinz - sinx * siny * cosz\n this.elements[3] = cosx * cosy * cosz - sinx * siny * sinz\n } else if (this.axisOrder === 'XZY') {\n this.elements[0] = sinx * cosy * cosz - cosx * siny * sinz\n this.elements[1] = cosx * siny * cosz - sinx * cosy * sinz\n this.elements[2] = cosx * cosy * sinz + sinx * siny * cosz\n this.elements[3] = cosx * cosy * cosz + sinx * siny * sinz\n }\n\n return this\n }\n\n /**\n * Set a {@link Quat} from a rotation axis {@link Vec3 | vector} and an angle\n * @param axis - normalized {@link Vec3 | vector} around which to rotate\n * @param angle - angle (in radians) to rotate\n * @returns - {@link Quat} after having applied the rotation\n */\n setFromAxisAngle(axis: Vec3, angle = 0): Quat {\n // https://github.com/mrdoob/three.js/blob/dev/src/math/Quaternion.js#L275\n // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm\n\n // assumes axis is normalized\n\n const halfAngle = angle / 2,\n s = Math.sin(halfAngle)\n\n this.elements[0] = axis.x * s\n this.elements[1] = axis.y * s\n this.elements[2] = axis.z * s\n this.elements[3] = Math.cos(halfAngle)\n\n return this\n }\n\n /**\n * Set a {@link Quat} from a rotation {@link Mat4 | matrix}\n * @param matrix - rotation {@link Mat4 | matrix} to use\n * @returns - {@link Quat} after having applied the rotation\n */\n setFromRotationMatrix(matrix: Mat4): Quat {\n // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm\n // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)\n const te = matrix.elements,\n m11 = te[0],\n m12 = te[4],\n m13 = te[8],\n m21 = te[1],\n m22 = te[5],\n m23 = te[9],\n m31 = te[2],\n m32 = te[6],\n m33 = te[10],\n trace = m11 + m22 + m33\n\n if (trace > 0) {\n const s = 0.5 / Math.sqrt(trace + 1.0)\n\n this.elements[3] = 0.25 / s\n this.elements[0] = (m32 - m23) * s\n this.elements[1] = (m13 - m31) * s\n this.elements[2] = (m21 - m12) * s\n } else if (m11 > m22 && m11 > m33) {\n const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33)\n\n this.elements[3] = (m32 - m23) / s\n this.elements[0] = 0.25 * s\n this.elements[1] = (m12 + m21) / s\n this.elements[2] = (m13 + m31) / s\n } else if (m22 > m33) {\n const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33)\n\n this.elements[3] = (m13 - m31) / s\n this.elements[0] = (m12 + m21) / s\n this.elements[1] = 0.25 * s\n this.elements[2] = (m23 + m32) / s\n } else {\n const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22)\n\n this.elements[3] = (m21 - m12) / s\n this.elements[0] = (m13 + m31) / s\n this.elements[1] = (m23 + m32) / s\n this.elements[2] = 0.25 * s\n }\n\n return this\n }\n}\n","import { Mat4 } from './Mat4'\nimport { Quat } from './Quat'\nimport { Camera } from '../core/camera/Camera'\n\n/**\n * Really basic 3D vector class used for vector calculations\n * @see https://github.com/mrdoob/three.js/blob/dev/src/math/Vector3.js\n * @see http://glmatrix.net/docs/vec3.js.html\n */\nexport class Vec3 {\n /** The type of the {@link Vec3} */\n type: string\n /** X component of our {@link Vec3} */\n private _x: number\n /** Y component of our {@link Vec3} */\n private _y: number\n /** Z component of our {@link Vec3} */\n private _z: number\n\n /** function assigned to the {@link onChange} callback */\n _onChangeCallback?(): void\n\n /**\n * Vec3 constructor\n * @param x - X component of our {@link Vec3}\n * @param y - Y component of our {@link Vec3}\n * @param z - Z component of our {@link Vec3}\n */\n constructor(x = 0, y = x, z = x) {\n this.type = 'Vec3'\n\n this._x = x\n this._y = y\n this._z = z\n }\n\n /**\n * Get the X component of the {@link Vec3}\n */\n get x(): number {\n return this._x\n }\n\n /**\n * Set the X component of the {@link Vec3}\n * Can trigger {@link onChange} callback\n * @param value - X component to set\n */\n set x(value: number) {\n const changed = value !== this._x\n this._x = value\n changed && this._onChangeCallback && this._onChangeCallback()\n }\n\n /**\n * Get the Y component of the {@link Vec3}\n */\n get y(): number {\n return this._y\n }\n\n /**\n * Set the Y component of the {@link Vec3}\n * Can trigger {@link onChange} callback\n * @param value - Y component to set\n */\n set y(value: number) {\n const changed = value !== this._y\n this._y = value\n changed && this._onChangeCallback && this._onChangeCallback()\n }\n\n /**\n * Get the Z component of the {@link Vec3}\n */\n get z(): number {\n return this._z\n }\n\n /**\n * Set the Z component of the {@link Vec3}\n * Can trigger {@link onChange} callback\n * @param value - Z component to set\n */\n set z(value: number) {\n const changed = value !== this._z\n this._z = value\n changed && this._onChangeCallback && this._onChangeCallback()\n }\n\n /**\n * Called when at least one component of the {@link Vec3} has changed\n * @param callback - callback to run when at least one component of the {@link Vec3} has changed\n * @returns - our {@link Vec3}\n */\n onChange(callback: () => void): Vec3 {\n if (callback) {\n this._onChangeCallback = callback\n }\n\n return this\n }\n\n /**\n * Set the {@link Vec3} from values\n * @param x - new X component to set\n * @param y - new Y component to set\n * @param z - new Z component to set\n * @returns - this {@link Vec3} after being set\n */\n set(x = 0, y = x, z = x): Vec3 {\n this.x = x\n this.y = y\n this.z = z\n\n return this\n }\n\n /**\n * Add a {@link Vec3} to this {@link Vec3}\n * @param vector - {@link Vec3} to add\n * @returns - this {@link Vec3} after addition\n */\n add(vector: Vec3 = new Vec3()): Vec3 {\n this.x += vector.x\n this.y += vector.y\n this.z += vector.z\n\n return this\n }\n\n /**\n * Add a scalar to all the components of this {@link Vec3}\n * @param value - number to add\n * @returns - this {@link Vec3} after addition\n */\n addScalar(value = 0): Vec3 {\n this.x += value\n this.y += value\n this.z += value\n\n return this\n }\n\n /**\n * Subtract a {@link Vec3} from this {@link Vec3}\n * @param vector - {@link Vec3} to subtract\n * @returns - this {@link Vec3} after subtraction\n */\n sub(vector: Vec3 = new Vec3()): Vec3 {\n this.x -= vector.x\n this.y -= vector.y\n this.z -= vector.z\n\n return this\n }\n\n /**\n * Subtract a scalar to all the components of this {@link Vec3}\n * @param value - number to subtract\n * @returns - this {@link Vec3} after subtraction\n */\n subScalar(value = 0): Vec3 {\n this.x -= value\n this.y -= value\n this.z -= value\n\n return this\n }\n\n /**\n * Multiply a {@link Vec3} with this {@link Vec3}\n * @param vector - {@link Vec3} to multiply with\n * @returns - this {@link Vec3} after multiplication\n */\n multiply(vector: Vec3 = new Vec3(1)): Vec3 {\n this.x *= vector.x\n this.y *= vector.y\n this.z *= vector.z\n\n return this\n }\n\n /**\n * Multiply all components of this {@link Vec3} with a scalar\n * @param value - number to multiply with\n * @returns - this {@link Vec3} after multiplication\n */\n multiplyScalar(value = 1): Vec3 {\n this.x *= value\n this.y *= value\n this.z *= value\n\n return this\n }\n\n /**\n * Divide a {@link Vec3} with this {@link Vec3}\n * @param vector - {@link Vec3} to divide with\n * @returns - this {@link Vec3} after division\n */\n divide(vector: Vec3 = new Vec3(1)): Vec3 {\n this.x /= vector.x\n this.y /= vector.y\n this.z /= vector.z\n\n return this\n }\n\n /**\n * Divide all components of this {@link Vec3} with a scalar\n * @param value - number to divide with\n * @returns - this {@link Vec3} after division\n */\n divideScalar(value = 1): Vec3 {\n this.x /= value\n this.y /= value\n this.z /= value\n\n return this\n }\n\n /**\n * Copy a {@link Vec3} into this {@link Vec3}\n * @param vector - {@link Vec3} to copy\n * @returns - this {@link Vec3} after copy\n */\n copy(vector: Vec3 = new Vec3()): Vec3 {\n this.x = vector.x\n this.y = vector.y\n this.z = vector.z\n\n return this\n }\n\n /**\n * Clone this {@link Vec3}\n * @returns - cloned {@link Vec3}\n */\n clone(): Vec3 {\n return new Vec3(this.x, this.y, this.z)\n }\n\n /**\n * Apply max values to this {@link Vec3} components\n * @param vector - {@link Vec3} representing max values\n * @returns - {@link Vec3} with max values applied\n */\n max(vector: Vec3 = new Vec3()): Vec3 {\n this.x = Math.max(this.x, vector.x)\n this.y = Math.max(this.y, vector.y)\n this.z = Math.max(this.z, vector.z)\n\n return this\n }\n\n /**\n * Apply min values to this {@link Vec3} components\n * @param vector - {@link Vec3} representing min values\n * @returns - {@link Vec3} with min values applied\n */\n min(vector: Vec3 = new Vec3()): Vec3 {\n this.x = Math.min(this.x, vector.x)\n this.y = Math.min(this.y, vector.y)\n this.z = Math.min(this.z, vector.z)\n\n return this\n }\n\n /**\n * Clamp this {@link Vec3} components by min and max {@link Vec3} vectors\n * @param min - minimum {@link Vec3} components to compare with\n * @param max - maximum {@link Vec3} components to compare with\n * @returns - clamped {@link Vec3}\n */\n clamp(min: Vec3 = new Vec3(), max: Vec3 = new Vec3()): Vec3 {\n this.x = Math.max(min.x, Math.min(max.x, this.x))\n this.y = Math.max(min.y, Math.min(max.y, this.y))\n this.z = Math.max(min.z, Math.min(max.z, this.z))\n\n return this\n }\n\n /**\n * Check if 2 {@link Vec3} are equal\n * @param vector - {@link Vec3} to compare\n * @returns - whether the {@link Vec3} are equals or not\n */\n equals(vector: Vec3 = new Vec3()): boolean {\n return this.x === vector.x && this.y === vector.y && this.z === vector.z\n }\n\n /**\n * Get the square length of this {@link Vec3}\n * @returns - square length of this {@link Vec3}\n */\n lengthSq(): number {\n return this.x * this.x + this.y * this.y + this.z * this.z\n }\n\n /**\n * Get the length of this {@link Vec3}\n * @returns - length of this {@link Vec3}\n */\n length(): number {\n return Math.sqrt(this.lengthSq())\n }\n\n /**\n * Normalize this {@link Vec3}\n * @returns - normalized {@link Vec3}\n */\n normalize(): Vec3 {\n // normalize\n let len = this.lengthSq()\n if (len > 0) {\n len = 1 / Math.sqrt(len)\n }\n this.x *= len\n this.y *= len\n this.z *= len\n\n return this\n }\n\n /**\n * Calculate the dot product of 2 {@link Vec3}\n * @param vector - {@link Vec3} to use for dot product\n * @returns - dot product of the 2 {@link Vec3}\n */\n dot(vector: Vec3 = new Vec3()): number {\n return this.x * vector.x + this.y * vector.y + this.z * vector.z\n }\n\n /**\n * Get the cross product of this {@link Vec3} with another {@link Vec3}\n * @param vector - {@link Vec3} to use for cross product\n * @returns - this {@link Vec3} after cross product\n */\n cross(vector: Vec3 = new Vec3()): Vec3 {\n return this.crossVectors(this, vector)\n }\n\n /**\n * Set this {@link Vec3} as the result of the cross product of two {@link Vec3}\n * @param a - first {@link Vec3} to use for cross product\n * @param b - second {@link Vec3} to use for cross product\n * @returns - this {@link Vec3} after cross product\n */\n crossVectors(a: Vec3 = new Vec3(), b: Vec3 = new Vec3()): Vec3 {\n const ax = a.x,\n ay = a.y,\n az = a.z\n const bx = b.x,\n by = b.y,\n bz = b.z\n\n this.x = ay * bz - az * by\n this.y = az * bx - ax * bz\n this.z = ax * by - ay * bx\n\n return this\n }\n\n /**\n * Calculate the linear interpolation of this {@link Vec3} by given {@link Vec3} and alpha, where alpha is the percent distance along the line\n * @param vector - {@link Vec3} to interpolate towards\n * @param alpha - interpolation factor in the [0, 1] interval\n * @returns - this {@link Vec3} after linear interpolation\n */\n lerp(vector: Vec3 = new Vec3(), alpha = 1): Vec3 {\n this.x += (vector.x - this.x) * alpha\n this.y += (vector.y - this.y) * alpha\n this.z += (vector.z - this.z) * alpha\n\n return this\n }\n\n /**\n * Apply a {@link Mat4 | matrix} to a {@link Vec3}\n * Useful to convert a position {@link Vec3} from plane local world to webgl space using projection view matrix for example\n * Source code from: http://glmatrix.net/docs/vec3.js.html\n * @param matrix - {@link Mat4 | matrix} to use\n * @returns - this {@link Vec3} after {@link Mat4 | matrix} application\n */\n applyMat4(matrix: Mat4): Vec3 {\n const x = this._x,\n y = this._y,\n z = this._z\n const mArray = matrix.elements\n\n let w = mArray[3] * x + mArray[7] * y + mArray[11] * z + mArray[15]\n w = w || 1\n\n this.x = (mArray[0] * x + mArray[4] * y + mArray[8] * z + mArray[12]) / w\n this.y = (mArray[1] * x + mArray[5] * y + mArray[9] * z + mArray[13]) / w\n this.z = (mArray[2] * x + mArray[6] * y + mArray[10] * z + mArray[14]) / w\n\n return this\n }\n\n /**\n * Apply a {@link Quat | quaternion} (rotation in 3D space) to this {@link Vec3}\n * @param quaternion - {@link Quat | quaternion} to use\n * @returns - this {@link Vec3} with the transformation applied\n */\n applyQuat(quaternion: Quat = new Quat()): Vec3 {\n const x = this.x,\n y = this.y,\n z = this.z\n const qx = quaternion.elements[0],\n qy = quaternion.elements[1],\n qz = quaternion.elements[2],\n qw = quaternion.elements[3]\n\n // calculate quat * vector\n\n const ix = qw * x + qy * z - qz * y\n const iy = qw * y + qz * x - qx * z\n const iz = qw * z + qx * y - qy * x\n const iw = -qx * x - qy * y - qz * z\n\n // calculate result * inverse quat\n\n this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy\n this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz\n this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx\n\n return this\n }\n\n /**\n * Rotate a {@link Vec3} around and axis by a given angle\n * @param axis - normalized {@link Vec3} around which to rotate\n * @param angle - angle (in radians) to rotate\n * @param quaternion - optional {@link Quat | quaternion} to use for rotation computations\n * @returns - this {@link Vec3} with the rotation applied\n */\n applyAxisAngle(axis = new Vec3(), angle = 0, quaternion = new Quat()) {\n // https://github.com/mrdoob/three.js/blob/master/src/math/Vector3.js#L212\n return this.applyQuat(quaternion.setFromAxisAngle(axis, angle))\n }\n\n /**\n * Project a 3D coordinate {@link Vec3} to a 2D coordinate {@link Vec3}\n * @param camera - {@link Camera} to use for projection\n * @returns - projected {@link Vec3}\n */\n project(camera: Camera): Vec3 {\n this.applyMat4(camera.viewMatrix).applyMat4(camera.projectionMatrix)\n return this\n }\n\n /**\n * Unproject a 2D coordinate {@link Vec3} to 3D coordinate {@link Vec3}\n * @param camera - {@link Camera} to use for projection\n * @returns - unprojected {@link Vec3}\n */\n unproject(camera: Camera): Vec3 {\n this.applyMat4(camera.projectionMatrix.getInverse()).applyMat4(camera.modelMatrix)\n return this\n }\n}\n","import { BufferLayout, getBufferLayout, TypedArray, WGSLVariableType } from '../utils'\r\nimport { Vec2 } from '../../../math/Vec2'\r\nimport { Vec3 } from '../../../math/Vec3'\r\nimport { Quat } from '../../../math/Quat'\r\nimport { Mat4 } from '../../../math/Mat4'\r\n\r\n/** Number of slots per row */\r\nexport const slotsPerRow = 4\r\n/** Number of bytes per slot */\r\nexport const bytesPerSlot = 4\r\n/** Number of bytes per row */\r\nexport const bytesPerRow = slotsPerRow * bytesPerSlot\r\n\r\n/**\r\n * Defines a position in our array buffer with a row index and a byte index\r\n */\r\nexport interface BufferElementAlignmentPosition {\r\n /** row index of that position */\r\n row: number\r\n /** byte index of that position */\r\n byte: number\r\n}\r\n\r\n/**\r\n * Defines our {@link BufferElement} alignment:\r\n * Keep track of an entry start and end row and bytes indexes (16 bytes per row)\r\n */\r\nexport interface BufferElementAlignment {\r\n /** The row and byte indexes at which this {@link BufferElement} starts */\r\n start: BufferElementAlignmentPosition\r\n /** The row and byte indexes at which this {@link BufferElement} ends */\r\n end: BufferElementAlignmentPosition\r\n}\r\n\r\n/**\r\n * Parameters used to create a {@link BufferElement}\r\n */\r\nexport interface BufferElementParams {\r\n /** The name of the {@link BufferElement} */\r\n name: string\r\n /** The key of the {@link BufferElement} */\r\n key: string\r\n /** The WGSL variable type of the {@link BufferElement} */\r\n type: WGSLVariableType\r\n}\r\n\r\n/**\r\n * Used to handle each {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array} view and data layout alignment.\r\n * Compute the exact alignment offsets needed to fill an {@link ArrayBuffer} that will be sent to a {@link GPUBuffer}, based on an input type and value.\r\n * Also update the view array at the correct offset.\r\n *\r\n * So all our struct need to be packed into our arrayBuffer using a precise layout.\r\n * They will be stored in rows, each row made of 4 slots and each slots made of 4 bytes. Depending on the binding element type, its row and slot may vary and we may have to insert empty padded values.\r\n * All in all it looks like that:
\r\n *
\r\n *          slot 0    slot 1    slot 2    slot 3\r\n * row 0 | _ _ _ _ | _ _ _ _ | _ _ _ _ | _ _ _ _ |\r\n * row 1 | _ _ _ _ | _ _ _ _ | _ _ _ _ | _ _ _ _ |\r\n * row 2 | _ _ _ _ | _ _ _ _ | _ _ _ _ | _ _ _ _ |\r\n * 
\r\n * see https://webgpufundamentals.org/webgpu/lessons/resources/wgsl-offset-computer.html\r\n */\r\nexport class BufferElement {\r\n /** The name of the {@link BufferElement} */\r\n name: string\r\n /** The WGSL variable type of the {@link BufferElement} */\r\n type: WGSLVariableType\r\n /** The key of the {@link BufferElement} */\r\n key: string\r\n\r\n /** {@link BufferLayout} used to fill the {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array} at the right offsets */\r\n bufferLayout: BufferLayout\r\n\r\n /**\r\n * Object defining exactly at which place a binding should be inserted into the {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array}\r\n */\r\n alignment: BufferElementAlignment\r\n\r\n /** Array containing the {@link BufferElement} values */\r\n view?: TypedArray\r\n\r\n /**\r\n * BufferElement constructor\r\n * @param parameters - {@link BufferElementParams | parameters} used to create our {@link BufferElement}\r\n */\r\n constructor({ name, key, type = 'f32' }: BufferElementParams) {\r\n this.name = name\r\n this.key = key\r\n this.type = type\r\n\r\n this.bufferLayout = getBufferLayout(this.type.replace('array', '').replace('<', '').replace('>', ''))\r\n\r\n // set init alignment\r\n this.alignment = {\r\n start: {\r\n row: 0,\r\n byte: 0,\r\n },\r\n end: {\r\n row: 0,\r\n byte: 0,\r\n },\r\n }\r\n }\r\n\r\n /**\r\n * Get the total number of rows used by this {@link BufferElement}\r\n * @readonly\r\n */\r\n get rowCount(): number {\r\n return this.alignment.end.row - this.alignment.start.row + 1\r\n }\r\n\r\n /**\r\n * Get the total number of bytes used by this {@link BufferElement} based on {@link BufferElementAlignment | alignment} start and end offsets\r\n * @readonly\r\n */\r\n get byteCount(): number {\r\n return Math.abs(this.endOffset - this.startOffset) + 1\r\n }\r\n\r\n /**\r\n * Get the total number of bytes used by this {@link BufferElement}, including final padding\r\n * @readonly\r\n */\r\n get paddedByteCount(): number {\r\n return (this.alignment.end.row + 1) * bytesPerRow\r\n }\r\n\r\n /**\r\n * Get the offset (i.e. byte index) at which our {@link BufferElement} starts\r\n * @readonly\r\n */\r\n get startOffset(): number {\r\n return this.getByteCountAtPosition(this.alignment.start)\r\n }\r\n\r\n /**\r\n * Get the array offset (i.e. array index) at which our {@link BufferElement} starts\r\n * @readonly\r\n */\r\n get startOffsetToIndex(): number {\r\n return this.startOffset / bytesPerSlot\r\n }\r\n\r\n /**\r\n * Get the offset (i.e. byte index) at which our {@link BufferElement} ends\r\n * @readonly\r\n */\r\n get endOffset(): number {\r\n return this.getByteCountAtPosition(this.alignment.end)\r\n }\r\n\r\n /**\r\n * Get the array offset (i.e. array index) at which our {@link BufferElement} ends\r\n * @readonly\r\n */\r\n get endOffsetToIndex(): number {\r\n return Math.floor(this.endOffset / bytesPerSlot)\r\n }\r\n\r\n /**\r\n * Get the position at given offset (i.e. byte index)\r\n * @param offset - byte index to use\r\n */\r\n getPositionAtOffset(offset = 0): BufferElementAlignmentPosition {\r\n return {\r\n row: Math.floor(offset / bytesPerRow),\r\n byte: offset % bytesPerRow,\r\n }\r\n }\r\n\r\n /**\r\n * Get the number of bytes at a given {@link BufferElementAlignmentPosition | position}\r\n * @param position - {@link BufferElementAlignmentPosition | position} from which to count\r\n * @returns - byte count at the given {@link BufferElementAlignmentPosition | position}\r\n */\r\n getByteCountAtPosition(position: BufferElementAlignmentPosition = { row: 0, byte: 0 }): number {\r\n return position.row * bytesPerRow + position.byte\r\n }\r\n\r\n /**\r\n * Check that a {@link BufferElementAlignmentPosition#byte | byte position} does not overflow its max value (16)\r\n * @param position - {@link BufferElementAlignmentPosition | position}\r\n * @returns - updated {@link BufferElementAlignmentPosition | position}\r\n */\r\n applyOverflowToPosition(\r\n position: BufferElementAlignmentPosition = { row: 0, byte: 0 }\r\n ): BufferElementAlignmentPosition {\r\n if (position.byte > bytesPerRow - 1) {\r\n const overflow = position.byte % bytesPerRow\r\n position.row += Math.floor(position.byte / bytesPerRow)\r\n position.byte = overflow\r\n }\r\n\r\n return position\r\n }\r\n\r\n /**\r\n * Get the number of bytes between two {@link BufferElementAlignmentPosition | positions}\r\n * @param p1 - first {@link BufferElementAlignmentPosition | position}\r\n * @param p2 - second {@link BufferElementAlignmentPosition | position}\r\n * @returns - number of bytes\r\n */\r\n getByteCountBetweenPositions(\r\n p1: BufferElementAlignmentPosition = { row: 0, byte: 0 },\r\n p2: BufferElementAlignmentPosition = { row: 0, byte: 0 }\r\n ): number {\r\n return Math.abs(this.getByteCountAtPosition(p2) - this.getByteCountAtPosition(p1))\r\n }\r\n\r\n /**\r\n * Compute the right alignment (i.e. start and end rows and bytes) given the size and align properties and the next available {@link BufferElementAlignmentPosition | position}\r\n * @param nextPositionAvailable - next {@link BufferElementAlignmentPosition | position} at which we should insert this element\r\n * @returns - computed {@link BufferElementAlignment | alignment}\r\n */\r\n getElementAlignment(\r\n nextPositionAvailable: BufferElementAlignmentPosition = { row: 0, byte: 0 }\r\n ): BufferElementAlignment {\r\n const alignment = {\r\n start: nextPositionAvailable,\r\n end: nextPositionAvailable,\r\n }\r\n\r\n const { size, align } = this.bufferLayout\r\n\r\n // check the alignment, i.e. even if there's enough space for our binding\r\n // we might have to pad the slot because some types need a specific alignment\r\n if (nextPositionAvailable.byte % align !== 0) {\r\n nextPositionAvailable.byte += nextPositionAvailable.byte % align\r\n }\r\n\r\n // in the case of a binding that could fit on one row\r\n // but we don't have space on the current row for this binding element\r\n // go to next row\r\n if (size <= bytesPerRow && nextPositionAvailable.byte + size > bytesPerRow) {\r\n nextPositionAvailable.row += 1\r\n nextPositionAvailable.byte = 0\r\n }\r\n\r\n alignment.end = {\r\n row: nextPositionAvailable.row + Math.ceil(size / bytesPerRow) - 1,\r\n byte: nextPositionAvailable.byte + (size % bytesPerRow === 0 ? bytesPerRow - 1 : (size % bytesPerRow) - 1), // end of row ? then it ends on slot (bytesPerRow - 1)\r\n }\r\n\r\n // now final check, if end slot has overflown\r\n alignment.end = this.applyOverflowToPosition(alignment.end)\r\n\r\n return alignment\r\n }\r\n\r\n /**\r\n * Set the {@link BufferElementAlignment | alignment} from a {@link BufferElementAlignmentPosition | position}\r\n * @param position - {@link BufferElementAlignmentPosition | position} at which to start inserting the values in the {@link !core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array}\r\n */\r\n setAlignmentFromPosition(position: BufferElementAlignmentPosition = { row: 0, byte: 0 }) {\r\n this.alignment = this.getElementAlignment(position)\r\n }\r\n\r\n /**\r\n * Set the {@link BufferElementAlignment | alignment} from an offset (byte count)\r\n * @param startOffset - offset at which to start inserting the values in the {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array}\r\n */\r\n setAlignment(startOffset = 0) {\r\n this.setAlignmentFromPosition(this.getPositionAtOffset(startOffset))\r\n }\r\n\r\n /**\r\n * Set the {@link view}\r\n * @param arrayBuffer - the {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array}\r\n * @param arrayView - the {@link core/bindings/BufferBinding.BufferBinding#arrayView | buffer binding array view}\r\n */\r\n setView(arrayBuffer: ArrayBuffer, arrayView: DataView) {\r\n this.view = new this.bufferLayout.View(\r\n arrayBuffer,\r\n this.startOffset,\r\n this.byteCount / this.bufferLayout.View.BYTES_PER_ELEMENT\r\n )\r\n }\r\n\r\n /**\r\n * Update the {@link view} based on the new value\r\n * @param value - new value to use\r\n */\r\n update(value) {\r\n if (this.type === 'f32' || this.type === 'u32' || this.type === 'i32') {\r\n this.view[0] = value as number\r\n } else if (this.type === 'vec2f') {\r\n this.view[0] = (value as Vec2).x ?? value[0] ?? 0\r\n this.view[1] = (value as Vec2).y ?? value[1] ?? 0\r\n } else if (this.type === 'vec3f') {\r\n this.view[0] = (value as Vec3).x ?? value[0] ?? 0\r\n this.view[1] = (value as Vec3).y ?? value[1] ?? 0\r\n this.view[2] = (value as Vec3).z ?? value[2] ?? 0\r\n } else if ((value as Quat | Mat4).elements) {\r\n this.view.set((value as Quat | Mat4).elements)\r\n } else if (ArrayBuffer.isView(value) || Array.isArray(value)) {\r\n this.view.set(value as number[])\r\n }\r\n }\r\n\r\n /**\r\n * Extract the data corresponding to this specific {@link BufferElement} from a {@link Float32Array} holding the {@link GPUBuffer} data of the parentMesh {@link core/bindings/BufferBinding.BufferBinding | BufferBinding}\r\n * @param result - {@link Float32Array} holding {@link GPUBuffer} data\r\n * @returns - extracted data from the {@link Float32Array}\r\n */\r\n extractDataFromBufferResult(result: Float32Array) {\r\n return result.slice(this.startOffsetToIndex, this.endOffsetToIndex)\r\n }\r\n}\r\n","import { BufferElement, BufferElementParams, bytesPerSlot } from './BufferElement'\nimport { throwWarning } from '../../../utils/utils'\n\n/**\n * Parameters used to create a {@link BufferArrayElement}\n */\nexport interface BufferArrayElementParams extends BufferElementParams {\n /** Initial length of the input {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array} */\n arrayLength: number\n}\n\n/**\n * Used to handle specific array {@link core/bindings/BufferBinding.BufferBinding | BufferBinding} types\n */\nexport class BufferArrayElement extends BufferElement {\n /** Initial length of the input {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array} */\n arrayLength: number\n /** Total number of elements (i.e. {@link arrayLength} divided by {@link core/bindings/utils.BufferLayout | buffer layout} number of elements */\n numElements: number\n /** Number of bytes in the {@link ArrayBuffer} between two elements {@link startOffset} */\n arrayStride: number\n\n /**\n * BufferArrayElement constructor\n * @param parameters - {@link BufferArrayElementParams | parameters} used to create our {@link BufferArrayElement}\n */\n constructor({ name, key, type = 'f32', arrayLength = 1 }: BufferArrayElementParams) {\n super({ name, key, type })\n\n this.arrayLength = arrayLength\n this.numElements = this.arrayLength / this.bufferLayout.numElements\n }\n\n /**\n * Get the array stride between two elements of the array, in indices\n * @readonly\n */\n get arrayStrideToIndex(): number {\n return this.arrayStride / bytesPerSlot\n }\n\n /**\n * Set the {@link core/bindings/bufferElements/BufferElement.BufferElementAlignment | alignment}\n * To compute how arrays are packed, we get the second item alignment as well and use it to calculate the arrayStride between two array elements. Using the arrayStride and the total number of elements, we can easily get the end alignment position.\n * @param startOffset - offset at which to start inserting the values in the {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array buffer}\n */\n setAlignment(startOffset = 0) {\n super.setAlignment(startOffset)\n\n // repeat for a second element to know how things are laid out\n const nextAlignment = this.getElementAlignment(this.getPositionAtOffset(this.endOffset + 1))\n this.arrayStride = this.getByteCountBetweenPositions(this.alignment.end, nextAlignment.end)\n\n this.alignment.end = this.getPositionAtOffset(this.endOffset + this.arrayStride * (this.numElements - 1))\n }\n\n /**\n * Update the {@link view} based on the new value\n * @param value - new value to use\n */\n update(value) {\n if (ArrayBuffer.isView(value) || Array.isArray(value)) {\n let valueIndex = 0\n\n const viewLength = this.byteCount / this.bufferLayout.View.BYTES_PER_ELEMENT\n // arrayStride is our view length divided by the number of elements in our array\n const stride = Math.ceil(viewLength / this.numElements)\n\n for (let i = 0; i < this.numElements; i++) {\n for (let j = 0; j < this.bufferLayout.numElements; j++) {\n this.view[j + i * stride] = value[valueIndex]\n\n valueIndex++\n }\n }\n } else {\n throwWarning(`BufferArrayElement: value passed to ${this.name} is not an array: ${value}`)\n }\n }\n}\n","import { BufferArrayElement, BufferArrayElementParams } from './BufferArrayElement'\r\n\r\n/**\r\n * Used to compute alignment when dealing with arrays of Struct\r\n */\r\nexport class BufferInterleavedArrayElement extends BufferArrayElement {\r\n /** Corresponding {@link DataView} set function based on {@link view} type */\r\n viewSetFunction: DataView['setInt32'] | DataView['setUint16'] | DataView['setUint32'] | DataView['setFloat32']\r\n\r\n /**\r\n * BufferInterleavedArrayElement constructor\r\n * @param parameters - {@link BufferArrayElementParams | parameters} used to create our {@link BufferInterleavedArrayElement}\r\n */\r\n constructor({ name, key, type = 'f32', arrayLength = 1 }: BufferArrayElementParams) {\r\n super({ name, key, type, arrayLength })\r\n\r\n this.arrayStride = 1\r\n\r\n this.arrayLength = arrayLength\r\n this.numElements = this.arrayLength / this.bufferLayout.numElements\r\n }\r\n\r\n /**\r\n * Get the total number of slots used by this {@link BufferInterleavedArrayElement} based on buffer layout size and total number of elements\r\n * @readonly\r\n */\r\n get byteCount(): number {\r\n return this.bufferLayout.size * this.numElements\r\n }\r\n\r\n /**\r\n * Set the {@link core/bindings/bufferElements/BufferElement.BufferElementAlignment | alignment}\r\n * To compute how arrays are packed, we need to compute the arrayStride between two elements beforehand and pass it here. Using the arrayStride and the total number of elements, we can easily get the end alignment position.\r\n * @param startOffset - offset at which to start inserting the values in the {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array}\r\n * @param stride - Stride in the {@link ArrayBuffer} between two elements of the array\r\n */\r\n setAlignment(startOffset = 0, stride = 0) {\r\n this.alignment = this.getElementAlignment(this.getPositionAtOffset(startOffset))\r\n\r\n this.arrayStride = stride\r\n\r\n this.alignment.end = this.getPositionAtOffset(this.endOffset + stride * (this.numElements - 1))\r\n }\r\n\r\n /**\r\n * Set the {@link view} and {@link viewSetFunction}\r\n * @param arrayBuffer - the {@link core/bindings/BufferBinding.BufferBinding#arrayBuffer | buffer binding array}\r\n * @param arrayView - the {@link core/bindings/BufferBinding.BufferBinding#arrayView | buffer binding array view}\r\n */\r\n setView(arrayBuffer: ArrayBuffer, arrayView: DataView) {\r\n // our view will be a simple typed array, not linked to the array buffer\r\n this.view = new this.bufferLayout.View(this.bufferLayout.numElements * this.numElements)\r\n\r\n // but our viewSetFunction is linked to the array view\r\n this.viewSetFunction = ((arrayView) => {\r\n switch (this.bufferLayout.View) {\r\n case Int32Array:\r\n return arrayView.setInt32.bind(arrayView) as DataView['setInt32']\r\n case Uint16Array:\r\n return arrayView.setUint16.bind(arrayView) as DataView['setUint16']\r\n case Uint32Array:\r\n return arrayView.setUint32.bind(arrayView) as DataView['setUint32']\r\n case Float32Array:\r\n default:\r\n return arrayView.setFloat32.bind(arrayView) as DataView['setFloat32']\r\n }\r\n })(arrayView)\r\n }\r\n\r\n /**\r\n * Update the {@link view} based on the new value, and then update the {@link core/bindings/BufferBinding.BufferBinding#arrayView | buffer binding array view} using sub arrays\r\n * @param value - new value to use\r\n */\r\n update(value) {\r\n super.update(value)\r\n\r\n // now use our viewSetFunction to fill the array view with interleaved alignment\r\n for (let i = 0; i < this.numElements; i++) {\r\n const subarray = this.view.subarray(\r\n i * this.bufferLayout.numElements,\r\n i * this.bufferLayout.numElements + this.bufferLayout.numElements\r\n )\r\n\r\n const startByteOffset = this.startOffset + i * this.arrayStride\r\n\r\n // view set function need to be called for each subarray entry, so loop over subarray entries\r\n subarray.forEach((value, index) => {\r\n this.viewSetFunction(startByteOffset + index * this.bufferLayout.View.BYTES_PER_ELEMENT, value, true)\r\n })\r\n }\r\n }\r\n\r\n /**\r\n * Extract the data corresponding to this specific {@link BufferInterleavedArrayElement} from a {@link Float32Array} holding the {@link GPUBuffer} data of the parentMesh {@link core/bindings/BufferBinding.BufferBinding | BufferBinding}\r\n * @param result - {@link Float32Array} holding {@link GPUBuffer} data\r\n */\r\n extractDataFromBufferResult(result: Float32Array) {\r\n const interleavedResult = new Float32Array(this.arrayLength)\r\n for (let i = 0; i < this.numElements; i++) {\r\n const resultOffset = this.startOffsetToIndex + i * this.arrayStrideToIndex\r\n\r\n for (let j = 0; j < this.bufferLayout.numElements; j++) {\r\n interleavedResult[i * this.bufferLayout.numElements + j] = result[resultOffset + j]\r\n }\r\n }\r\n return interleavedResult\r\n }\r\n}\r\n","import { Binding, BindingParams, BufferBindingMemoryAccessType } from './Binding'\nimport { getBindGroupLayoutBindingType, getBindingWGSLVarType, getBufferLayout, TypedArray } from './utils'\nimport { throwWarning, toCamelCase, toKebabCase } from '../../utils/utils'\nimport { Vec2 } from '../../math/Vec2'\nimport { Vec3 } from '../../math/Vec3'\nimport { Input, InputBase, InputValue } from '../../types/BindGroups'\nimport { BufferElement } from './bufferElements/BufferElement'\nimport { BufferArrayElement } from './bufferElements/BufferArrayElement'\nimport { BufferInterleavedArrayElement } from './bufferElements/BufferInterleavedArrayElement'\n\n/**\n * Defines a {@link BufferBinding} input object that can set a value and run a callback function when this happens\n */\nexport interface BufferBindingInput extends InputBase {\n /** Original {@link InputValue | input value} */\n _value: InputValue\n\n /** Get the {@link InputValue | input value} */\n get value(): InputValue\n\n /** Set the {@link InputValue | input value} */\n set value(value: InputValue)\n\n /** Whether the {@link InputValue | input value} has changed and we should update the {@link BufferBinding#arrayBuffer | buffer binding array} */\n shouldUpdate: boolean\n}\n\n/**\n * Base parameters used to create a {@link BufferBinding}\n */\nexport interface BufferBindingBaseParams {\n /** Whether this {@link BufferBinding} should use structured WGSL variables */\n useStruct?: boolean\n /** {@link BufferBinding} memory access types (read only or read/write) */\n access?: BufferBindingMemoryAccessType\n /** Object containing one or multiple {@link Input | inputs} describing the structure of the {@link BufferBinding} */\n struct?: Record\n}\n\n/**\n * Parameters used to create a {@link BufferBinding}\n */\nexport interface BufferBindingParams extends BindingParams, BufferBindingBaseParams {}\n\n/** All allowed {@link BufferElement | buffer elements} */\nexport type AllowedBufferElement = BufferElement | BufferArrayElement | BufferInterleavedArrayElement\n\n/**\n * Used to format {@link BufferBindingParams#struct | uniforms or storages struct inputs} and create a single typed array that will hold all those inputs values. The array needs to be correctly padded depending on every value type, so it can be safely used as a GPUBuffer input.
\n * It will also create WGSL Structs and variables according to the BufferBindings inputs parameters.
\n * The WGSL structs and variables declaration may vary based on the input types, especially if there's one or more arrays involved (i.e. `array`, `array` etc.).\n *\n * @example\n * ```javascript\n * // create a GPU buffer binding\n * const bufferBinding = new BufferBinding({\n * name: 'params', // name of the WGSL object\n * bindingType: 'uniform', // should be 'storage' for large arrays\n * struct: {\n * opacity: {\n * type: 'f32',\n * value: 1,\n * },\n * mousePosition: {\n * type: 'vec2f',\n * value: new Vec2(),\n * },\n * },\n * })\n * ```\n */\nexport class BufferBinding extends Binding {\n /** Flag to indicate whether this {@link BufferBinding} {@link bufferElements | buffer elements} should be packed in a single structured object or if each one of them should be a separate binding. */\n useStruct: boolean\n /** All the {@link BufferBinding} data inputs */\n inputs: Record\n\n /** Flag to indicate whether one of the {@link inputs} value has changed and we need to update the GPUBuffer linked to the {@link arrayBuffer} array */\n shouldUpdate: boolean\n\n /** An array describing how each corresponding {@link inputs} should be inserted into our {@link arrayView} array */\n bufferElements: AllowedBufferElement[]\n\n /** Total size of our {@link arrayBuffer} array in bytes */\n arrayBufferSize: number\n /** Array buffer that will be sent to the {@link GPUBuffer} */\n arrayBuffer: ArrayBuffer\n /** Data view of our {@link arrayBuffer | array buffer} */\n arrayView: DataView\n\n /** The GPUBuffer */\n buffer: GPUBuffer | null\n\n /** A string to append to our shaders code describing the WGSL structure representing this {@link BufferBinding} */\n wgslStructFragment: string\n /** An array of strings to append to our shaders code declaring all the WGSL variables representing this {@link BufferBinding} */\n wgslGroupFragment: string[]\n /** Options used to create this {@link BufferBinding} */\n options: BufferBindingParams\n\n /**\n * BufferBinding constructor\n * @param parameters - {@link BufferBindingParams | parameters} used to create our BufferBindings\n */\n constructor({\n label = 'Uniform',\n name = 'uniform',\n bindingType,\n visibility,\n useStruct = true,\n access = 'read',\n struct = {},\n }: BufferBindingParams) {\n bindingType = bindingType ?? 'uniform'\n\n super({ label, name, bindingType, visibility })\n\n this.options = {\n ...this.options,\n useStruct,\n access,\n struct: struct,\n }\n\n this.arrayBufferSize = 0\n\n this.shouldUpdate = false\n this.useStruct = useStruct\n\n this.bufferElements = []\n this.inputs = {}\n this.buffer = null\n\n this.setBindings(struct)\n this.setBufferAttributes()\n this.setWGSLFragment()\n }\n\n /**\n * Get {@link GPUBindGroupLayoutEntry#buffer | bind group layout entry resource}\n * @readonly\n */\n get resourceLayout(): {\n /** {@link GPUBindGroupLayout | bind group layout} resource */\n buffer: GPUBufferBindingLayout\n } {\n return {\n buffer: {\n type: getBindGroupLayoutBindingType(this),\n },\n }\n }\n\n /**\n * Get {@link GPUBindGroupEntry#resource | bind group resource}\n * @readonly\n */\n get resource(): {\n /** {@link GPUBindGroup | bind group} resource */\n buffer: GPUBuffer | null\n } {\n return { buffer: this.buffer }\n }\n\n /**\n * Format bindings struct and set our {@link inputs}\n * @param bindings - bindings inputs\n */\n setBindings(bindings: Record) {\n Object.keys(bindings).forEach((bindingKey) => {\n const binding = {} as BufferBindingInput\n\n for (const key in bindings[bindingKey]) {\n if (key !== 'value') {\n binding[key] = bindings[bindingKey][key]\n }\n }\n\n // force the binding to have a name\n binding.name = bindings[bindingKey].name ?? bindingKey\n\n // define a \"value\" getter/setter so we can now when to update the buffer binding\n Object.defineProperty(binding, 'value', {\n get() {\n return binding._value\n },\n set(v) {\n binding._value = v\n binding.shouldUpdate = true\n },\n })\n\n binding.value = bindings[bindingKey].value\n\n if (binding.value instanceof Vec2 || binding.value instanceof Vec3) {\n binding.value.onChange(() => (binding.shouldUpdate = true))\n }\n\n this.inputs[bindingKey] = binding\n })\n }\n\n /**\n * Set our buffer attributes:\n * Takes all the {@link inputs} and adds them to the {@link bufferElements} array with the correct start and end offsets (padded), then fill our {@link arrayBuffer} typed array accordingly.\n */\n setBufferAttributes() {\n // early on, check if there's at least one array binding\n // If there's one and only one, put it at the end of the binding elements array, treat it as a single entry of the type, but loop on it by array.length / size to fill the alignment\n // If there's more than one, create buffer interleaved elements.\n\n // if length === 0, OK\n // if length === 1, put it at the end of our struct\n // if length > 1, create a buffer interleaved elements\n const arrayBindings = Object.keys(this.inputs).filter(\n (bindingKey) => this.inputs[bindingKey].type.indexOf('array') !== -1\n )\n\n // put the array struct at the end\n let orderedBindings = Object.keys(this.inputs).sort((bindingKeyA, bindingKeyB) => {\n // 0 if it's an array, -1 else\n const isBindingAArray = Math.min(0, this.inputs[bindingKeyA].type.indexOf('array'))\n const isBindingBArray = Math.min(0, this.inputs[bindingKeyB].type.indexOf('array'))\n\n return isBindingAArray - isBindingBArray\n })\n\n if (arrayBindings.length > 1) {\n // remove interleaved arrays from the ordered struct key array\n orderedBindings = orderedBindings.filter((bindingKey) => !arrayBindings.includes(bindingKey))\n }\n\n // handle buffer (non interleaved) elements\n orderedBindings.forEach((bindingKey) => {\n const binding = this.inputs[bindingKey]\n\n const bufferElementOptions = {\n name: toCamelCase(binding.name ?? bindingKey),\n key: bindingKey,\n type: binding.type,\n }\n\n const isArray =\n binding.type.indexOf('array') !== -1 && (Array.isArray(binding.value) || ArrayBuffer.isView(binding.value))\n\n this.bufferElements.push(\n isArray\n ? new BufferArrayElement({\n ...bufferElementOptions,\n arrayLength: (binding.value as number[]).length,\n })\n : new BufferElement(bufferElementOptions)\n )\n })\n\n // set their alignments\n this.bufferElements.forEach((bufferElement, index) => {\n const startOffset = index === 0 ? 0 : this.bufferElements[index - 1].endOffset + 1\n\n bufferElement.setAlignment(startOffset)\n })\n\n // now create our interleaved buffer elements\n if (arrayBindings.length > 1) {\n // first get the sizes of the arrays\n const arraySizes = arrayBindings.map((bindingKey) => {\n const binding = this.inputs[bindingKey]\n const bufferLayout = getBufferLayout(binding.type.replace('array', '').replace('<', '').replace('>', ''))\n\n return (binding.value as number[] | TypedArray).length / bufferLayout.numElements\n })\n\n // are they all of the same size?\n const equalSize = arraySizes.every((size, i, array) => size === array[0])\n\n if (equalSize) {\n // this will hold our interleaved buffer elements\n const interleavedBufferElements = arrayBindings.map((bindingKey) => {\n const binding = this.inputs[bindingKey]\n return new BufferInterleavedArrayElement({\n name: toCamelCase(binding.name ?? bindingKey),\n key: bindingKey,\n type: binding.type,\n arrayLength: (binding.value as number[]).length,\n })\n })\n\n // now create temp buffer elements that we'll use to fill the interleaved buffer elements alignments\n const tempBufferElements = arrayBindings.map((bindingKey) => {\n const binding = this.inputs[bindingKey]\n return new BufferElement({\n name: toCamelCase(binding.name ?? bindingKey),\n key: bindingKey,\n type: binding.type.replace('array', '').replace('<', '').replace('>', ''),\n })\n })\n\n // set temp buffer alignments as if it was regular buffer elements\n tempBufferElements.forEach((bufferElement, index) => {\n if (index === 0) {\n if (this.bufferElements.length) {\n // if there are already buffer elements\n // get last one end row, and start at the next row\n bufferElement.setAlignmentFromPosition({\n row: this.bufferElements[this.bufferElements.length - 1].alignment.end.row + 1,\n byte: 0,\n })\n } else {\n bufferElement.setAlignment(0)\n }\n } else {\n bufferElement.setAlignment(tempBufferElements[index - 1].endOffset + 1)\n }\n })\n\n // now use last temp buffer end offset as our interleaved arrayStride\n const totalStride =\n tempBufferElements[tempBufferElements.length - 1].endOffset + 1 - tempBufferElements[0].startOffset\n\n // finally, set interleaved buffer elements alignment\n interleavedBufferElements.forEach((bufferElement, index) => {\n bufferElement.setAlignment(tempBufferElements[index].startOffset, totalStride)\n })\n\n // add to our buffer elements array\n this.bufferElements = [...this.bufferElements, ...interleavedBufferElements]\n } else {\n throwWarning(\n `BufferBinding: \"${\n this.label\n }\" contains multiple array inputs that should use an interleaved array, but their sizes do not match. These inputs cannot be added to the BufferBinding: \"${arrayBindings.join(\n ', '\n )}\"`\n )\n }\n }\n\n this.arrayBufferSize = this.bufferElements.length\n ? this.bufferElements[this.bufferElements.length - 1].paddedByteCount\n : 0\n\n this.arrayBuffer = new ArrayBuffer(this.arrayBufferSize)\n this.arrayView = new DataView(this.arrayBuffer, 0, this.arrayBuffer.byteLength)\n\n this.bufferElements.forEach((bufferElement) => {\n bufferElement.setView(this.arrayBuffer, this.arrayView)\n })\n\n this.shouldUpdate = this.arrayBufferSize > 0\n }\n\n /**\n * Set the WGSL code snippet to append to the shaders code. It consists of variable (and Struct structures if needed) declarations.\n */\n setWGSLFragment() {\n const kebabCaseLabel = toKebabCase(this.label)\n\n if (this.useStruct) {\n const bufferElements = this.bufferElements.filter(\n (bufferElement) => !(bufferElement instanceof BufferInterleavedArrayElement)\n )\n const interleavedBufferElements = this.bufferElements.filter(\n (bufferElement) => bufferElement instanceof BufferInterleavedArrayElement\n ) as BufferInterleavedArrayElement[]\n\n if (interleavedBufferElements.length) {\n const arrayLength = this.bindingType === 'uniform' ? `, ${interleavedBufferElements[0].numElements}` : ''\n\n if (bufferElements.length) {\n this.wgslStructFragment = `struct ${kebabCaseLabel}Element {\\n\\t${interleavedBufferElements\n .map((binding) => binding.name + ': ' + binding.type.replace('array', '').replace('<', '').replace('>', ''))\n .join(',\\n\\t')}\n};\\n\\n`\n\n const interleavedBufferStructDeclaration = `${this.name}Element: array<${kebabCaseLabel}Element${arrayLength}>,`\n\n this.wgslStructFragment += `struct ${kebabCaseLabel} {\\n\\t${bufferElements\n .map((bufferElement) => bufferElement.name + ': ' + bufferElement.type)\n .join(',\\n\\t')}\n\\t${interleavedBufferStructDeclaration}\n};`\n\n const varType = getBindingWGSLVarType(this)\n this.wgslGroupFragment = [`${varType} ${this.name}: ${kebabCaseLabel};`]\n } else {\n this.wgslStructFragment = `struct ${kebabCaseLabel} {\\n\\t${this.bufferElements\n .map((binding) => binding.name + ': ' + binding.type.replace('array', '').replace('<', '').replace('>', ''))\n .join(',\\n\\t')}\n};`\n\n const varType = getBindingWGSLVarType(this)\n this.wgslGroupFragment = [`${varType} ${this.name}: array<${kebabCaseLabel}${arrayLength}>;`]\n }\n } else {\n this.wgslStructFragment = `struct ${kebabCaseLabel} {\\n\\t${this.bufferElements\n .map((binding) => {\n // now add array length if needed\n const bindingType =\n this.bindingType === 'uniform' && 'numElements' in binding\n ? `array<${binding.type.replace('array', '').replace('<', '').replace('>', '')}, ${\n binding.numElements\n }>`\n : binding.type\n return binding.name + ': ' + bindingType\n })\n .join(',\\n\\t')}\n};`\n\n const varType = getBindingWGSLVarType(this)\n this.wgslGroupFragment = [`${varType} ${this.name}: ${kebabCaseLabel};`]\n }\n } else {\n this.wgslStructFragment = ''\n this.wgslGroupFragment = this.bufferElements.map((binding) => {\n const varType = getBindingWGSLVarType(this)\n return `${varType} ${binding.name}: ${binding.type};`\n })\n }\n }\n\n /**\n * Set a binding shouldUpdate flag to true to update our {@link arrayBuffer} array during next render.\n * @param bindingName - the binding name/key to update\n */\n shouldUpdateBinding(bindingName = '') {\n const bindingKey = Object.keys(this.inputs).find((bindingKey) => this.inputs[bindingKey].name === bindingName)\n\n if (bindingKey) this.inputs[bindingKey].shouldUpdate = true\n }\n\n /**\n * Executed at the beginning of a Material render call.\n * If any of the {@link inputs} has changed, run its onBeforeUpdate callback then updates our {@link arrayBuffer} array.\n * Also sets the {@link shouldUpdate} property to true so the {@link core/bindGroups/BindGroup.BindGroup | BindGroup} knows it will need to update the {@link GPUBuffer}.\n */\n update() {\n Object.keys(this.inputs).forEach((bindingKey) => {\n const binding = this.inputs[bindingKey]\n const bufferElement = this.bufferElements.find((bufferEl) => bufferEl.key === bindingKey)\n\n if (binding.shouldUpdate && bufferElement) {\n binding.onBeforeUpdate && binding.onBeforeUpdate()\n // we're going to directly update the arrayBuffer from the buffer element update method\n bufferElement.update(binding.value)\n\n this.shouldUpdate = true\n binding.shouldUpdate = false\n }\n })\n }\n\n /**\n * Extract the data corresponding to a specific {@link BufferElement} from a {@link Float32Array} holding the {@link BufferBinding#buffer | GPU buffer} data of this {@link BufferBinding}\n * @param parameters - parameters used to extract the data\n * @param parameters.result - {@link Float32Array} holding {@link GPUBuffer} data\n * @param parameters.bufferElementName - name of the {@link BufferElement} to use to extract the data\n * @returns - extracted data from the {@link Float32Array}\n */\n extractBufferElementDataFromBufferResult({\n result,\n bufferElementName,\n }: {\n result: Float32Array\n bufferElementName: BufferElement['name']\n }): Float32Array {\n const bufferElement = this.bufferElements.find((bufferElement) => bufferElement.name === bufferElementName)\n if (bufferElement) {\n return bufferElement.extractDataFromBufferResult(result)\n } else {\n return result\n }\n }\n}\n","import { BufferBinding, BufferBindingParams } from './BufferBinding'\n\n/**\n * Parameters used to create a {@link WritableBufferBinding}\n */\nexport interface WritableBufferBindingParams extends BufferBindingParams {\n /** Whether whe should automatically copy the {@link WritableBufferBinding#buffer | GPU buffer} content into our {@link WritableBufferBinding#resultBuffer | result GPU buffer} */\n shouldCopyResult?: boolean\n}\n\n/**\n * Used to create a {@link BufferBinding} that can hold read/write storage bindings along with a {@link WritableBufferBinding#resultBuffer | result GPU buffer} that can be used to get data back from the GPU.\n *\n * Note that it is automatically created by the {@link core/bindGroups/BindGroup.BindGroup | BindGroup} when a {@link types/BindGroups.BindGroupInputs#storages | storages input} has its {@link BufferBindingParams#access | access} property set to `\"read_write\"`.\n */\nexport class WritableBufferBinding extends BufferBinding {\n /** Flag indicating whether whe should automatically copy the {@link buffer | GPU buffer} content into our {@link resultBuffer | result GPU buffer} */\n shouldCopyResult: boolean\n /** The result GPUBuffer */\n resultBuffer: GPUBuffer | null\n /** Options used to create this {@link WritableBufferBinding} */\n options: WritableBufferBindingParams\n\n /**\n * WritableBufferBinding constructor\n * @param parameters - {@link WritableBufferBindingParams | parameters} used to create our {@link WritableBufferBinding}\n */\n constructor({\n label = 'Work',\n name = 'work',\n bindingType,\n useStruct = true,\n struct = {},\n visibility,\n access = 'read_write',\n shouldCopyResult = false,\n }: WritableBufferBindingParams) {\n bindingType = 'storage'\n visibility = 'compute'\n\n super({ label, name, bindingType, useStruct, struct: struct, visibility, access })\n\n this.options = {\n ...this.options,\n shouldCopyResult,\n }\n\n this.shouldCopyResult = shouldCopyResult\n\n // can be used as our buffer copy destination\n this.resultBuffer = null\n }\n}\n","import { isRenderer, Renderer } from '../renderers/utils'\r\nimport { generateUUID, toKebabCase } from '../../utils/utils'\r\nimport { WritableBufferBinding, WritableBufferBindingParams } from '../bindings/WritableBufferBinding'\r\nimport { BufferBinding } from '../bindings/BufferBinding'\r\nimport {\r\n AllowedBindGroups,\r\n BindGroupBindingElement,\r\n BindGroupBufferBindingElement,\r\n BindGroupEntries,\r\n BindGroupParams,\r\n ReadOnlyInputBindings,\r\n} from '../../types/BindGroups'\r\nimport { GPUCurtains } from '../../curtains/GPUCurtains'\r\nimport { TextureBindGroupParams } from './TextureBindGroup'\r\nimport { BindingType } from '../bindings/Binding'\r\n\r\n/**\r\n * Used to handle all inputs data sent to the GPU.
\r\n * In WebGPU, data (buffers, textures or samplers, called bindings) are organised by bind groups, containing those bindings.\r\n *\r\n * ## Bindings\r\n *\r\n * A {@link BindGroup} is responsible for creating each {@link BufferBinding} {@link GPUBuffer} and then the {@link GPUBindGroup} and {@link GPUBindGroupLayout} that are used to create {@link GPUComputePipeline} or {@link GPURenderPipeline}.
\r\n * Those are generally automatically created by the {@link core/materials/Material.Material | Material} using this {@link BindGroup}. If you need to manually create them, you will have to call its {@link BindGroup#createBindGroup | `createBindGroup()` method}\r\n *\r\n * ### Samplers and textures\r\n *\r\n * A {@link BindGroup} is best suited to handle {@link GPUBuffer} only bindings. If you need to handle {@link GPUSampler}, a {@link GPUTexture} or a {@link GPUExternalTexture}, you should use a {@link core/bindGroups/TextureBindGroup.TextureBindGroup | TextureBindGroup} instead.\r\n *\r\n * ### Updating a GPUBindGroup or GPUBindGroupLayout\r\n *\r\n * Each time one of the {@link https://developer.mozilla.org/en-US/docs/Web/API/GPUDevice/createBindGroup#resource | binding resource} changes, its {@link BindGroup#bindGroup | bindGroup} will be recreated (usually, when a {@link GPUTexture} is uploaded).
\r\n * Each time one of the {@link https://developer.mozilla.org/en-US/docs/Web/API/GPUDevice/createBindGroupLayout#resource_layout_objects | binding resource layout} changes, its {@link BindGroup#bindGroupLayout | bindGroupLayout} and {@link BindGroup#bindGroup | bindGroup} will be recreated, and the {@link GPUComputePipeline} or {@link GPURenderPipeline} will be recreated as well.\r\n *\r\n * @example\r\n * ```javascript\r\n * // set our main GPUCurtains instance\r\n * const gpuCurtains = new GPUCurtains({\r\n * container: '#canvas' // selector of our WebGPU canvas container\r\n * })\r\n *\r\n * // set the GPU device\r\n * // note this is asynchronous\r\n * await gpuCurtains.setDevice()\r\n *\r\n * const bindGroup = new BindGroup(gpuCurtains, {\r\n * label: 'My bind group',\r\n * uniforms: {\r\n * params: {\r\n * struct: {\r\n * opacity: {\r\n * type: 'f32',\r\n * value: 1,\r\n * },\r\n * mousePosition: {\r\n * type: 'vec2f',\r\n * value: new Vec2(),\r\n * },\r\n * },\r\n * },\r\n * },\r\n * })\r\n *\r\n * // create the GPU buffer, bindGroupLayout and bindGroup\r\n * bindGroup.createBindGroup()\r\n * ```\r\n */\r\nexport class BindGroup {\r\n /** The type of the {@link BindGroup} */\r\n type: string\r\n /** The universal unique id of the {@link BindGroup} */\r\n uuid: string\r\n /** The {@link Renderer} used */\r\n renderer: Renderer\r\n /** Options used to create this {@link BindGroup} */\r\n options: TextureBindGroupParams\r\n /** Index of this {@link BindGroup}, used to link struct in the shaders */\r\n index: number\r\n\r\n /** List of {@link BindGroupBindingElement | bindings} (buffers, texture, etc.) handled by this {@link BindGroup} */\r\n bindings: BindGroupBindingElement[]\r\n\r\n /** Our {@link BindGroup} {@link BindGroupEntries | entries} objects */\r\n entries: BindGroupEntries\r\n\r\n /** Our {@link BindGroup}{@link GPUBindGroupLayout} */\r\n bindGroupLayout: null | GPUBindGroupLayout\r\n /** Our {@link BindGroup} {@link GPUBindGroup} */\r\n bindGroup: null | GPUBindGroup\r\n\r\n /** Flag indicating whether we need to flush and recreate the pipeline using this {@link BindGroup} s*/\r\n needsPipelineFlush: boolean\r\n\r\n /**\r\n * BindGroup constructor\r\n * @param renderer - a {@link Renderer} class object or a {@link GPUCurtains} class object\r\n * @param parameters - {@link BindGroupParams | parameters} used to create our {@link BindGroup}\r\n */\r\n constructor(\r\n renderer: Renderer | GPUCurtains,\r\n { label = 'BindGroup', index = 0, bindings = [], uniforms, storages }: BindGroupParams = {}\r\n ) {\r\n this.type = 'BindGroup'\r\n\r\n // we could pass our curtains object OR our curtains renderer object\r\n renderer = (renderer && (renderer as GPUCurtains).renderer) || (renderer as Renderer)\r\n\r\n isRenderer(renderer, this.type)\r\n\r\n this.renderer = renderer\r\n this.options = {\r\n label,\r\n index,\r\n bindings,\r\n ...(uniforms && { uniforms }),\r\n ...(storages && { storages }),\r\n }\r\n\r\n this.index = index\r\n this.uuid = generateUUID()\r\n\r\n this.bindings = []\r\n bindings.length && this.addBindings(bindings)\r\n if (this.options.uniforms || this.options.storages) this.setInputBindings()\r\n\r\n this.resetEntries()\r\n\r\n this.bindGroupLayout = null\r\n this.bindGroup = null\r\n\r\n // if we ever update our bind group layout\r\n // we will have to recreate the whole pipeline again\r\n this.needsPipelineFlush = false\r\n\r\n this.renderer.addBindGroup(this)\r\n }\r\n\r\n /**\r\n * Sets our {@link BindGroup#index | bind group index}\r\n * @param index - {@link BindGroup#index | bind group index} to set\r\n */\r\n setIndex(index: number) {\r\n this.index = index\r\n }\r\n\r\n /**\r\n * Adds an array of already created {@link bindings} (buffers, texture, etc.) to the {@link bindings} array\r\n * @param bindings - {@link bindings} to add\r\n */\r\n addBindings(bindings: BindGroupBindingElement[] = []) {\r\n this.bindings = [...this.bindings, ...bindings]\r\n }\r\n\r\n /**\r\n * Adds an already created {@link bindings} (buffers, texture, etc.) to the {@link bindings} array\r\n * @param binding - binding to add\r\n */\r\n addBinding(binding: BindGroupBindingElement) {\r\n this.bindings.push(binding)\r\n }\r\n\r\n /**\r\n * Creates Bindings based on a list of inputs\r\n * @param bindingType - {@link core/bindings/Binding.Binding#bindingType | binding type}\r\n * @param inputs - {@link ReadOnlyInputBindings | inputs (uniform or storage)} that will be used to create the binding\r\n * @returns - a {@link bindings} array\r\n */\r\n createInputBindings(\r\n bindingType: BindingType = 'uniform',\r\n inputs: ReadOnlyInputBindings = {}\r\n ): BindGroupBindingElement[] {\r\n return [\r\n ...Object.keys(inputs).map((inputKey) => {\r\n const binding = inputs[inputKey] as WritableBufferBindingParams\r\n\r\n const bindingParams: WritableBufferBindingParams = {\r\n label: toKebabCase(binding.label || inputKey),\r\n name: inputKey,\r\n bindingType,\r\n useStruct: true, // by default\r\n visibility: binding.access === 'read_write' ? 'compute' : binding.visibility,\r\n access: binding.access ?? 'read', // read by default\r\n struct: binding.struct,\r\n ...(binding.shouldCopyResult !== undefined && { shouldCopyResult: binding.shouldCopyResult }),\r\n }\r\n\r\n const BufferBindingConstructor = bindingParams.access === 'read_write' ? WritableBufferBinding : BufferBinding\r\n\r\n return binding.useStruct !== false\r\n ? new BufferBindingConstructor(bindingParams)\r\n : Object.keys(binding.struct).map((bindingKey) => {\r\n bindingParams.label = toKebabCase(binding.label ? binding.label + bindingKey : inputKey + bindingKey)\r\n bindingParams.name = inputKey + bindingKey\r\n bindingParams.useStruct = false\r\n bindingParams.struct = { [bindingKey]: binding.struct[bindingKey] }\r\n\r\n return new BufferBindingConstructor(bindingParams)\r\n })\r\n }),\r\n ].flat()\r\n }\r\n\r\n /**\r\n * Create and adds {@link bindings} based on inputs provided upon creation\r\n */\r\n setInputBindings() {\r\n this.addBindings([\r\n ...this.createInputBindings('uniform', this.options.uniforms),\r\n ...this.createInputBindings('storage', this.options.storages),\r\n ])\r\n }\r\n\r\n /**\r\n * Get whether the GPU bind group is ready to be created\r\n * It can be created if it has {@link bindings} and has not been created yet\r\n * @readonly\r\n */\r\n get shouldCreateBindGroup(): boolean {\r\n return !this.bindGroup && !!this.bindings.length\r\n }\r\n\r\n /**\r\n * Reset our {@link BindGroup} {@link entries}\r\n */\r\n resetEntries() {\r\n this.entries = {\r\n bindGroupLayout: [],\r\n bindGroup: [],\r\n }\r\n }\r\n\r\n /**\r\n * Create the GPU buffers, {@link bindings}, {@link entries}, {@link bindGroupLayout} and {@link bindGroup}\r\n */\r\n createBindGroup() {\r\n this.fillEntries()\r\n this.setBindGroupLayout()\r\n this.setBindGroup()\r\n }\r\n\r\n /**\r\n * Reset the {@link BindGroup#entries.bindGroup | bindGroup entries}, recreates them and then recreate the {@link BindGroup#bindGroup | GPU bind group}\r\n */\r\n resetBindGroup() {\r\n this.entries.bindGroup = []\r\n this.bindings.forEach((binding) => {\r\n this.entries.bindGroup.push({\r\n binding: this.entries.bindGroup.length,\r\n resource: binding.resource,\r\n })\r\n })\r\n\r\n this.setBindGroup()\r\n }\r\n\r\n /**\r\n * Reset the {@link BindGroup#entries.bindGroupLayout | bindGroupLayout entries}, recreates them and then recreate the {@link BindGroup#bindGroupLayout | GPU bind group layout}\r\n */\r\n resetBindGroupLayout() {\r\n this.entries.bindGroupLayout = []\r\n this.bindings.forEach((binding) => {\r\n this.entries.bindGroupLayout.push({\r\n binding: this.entries.bindGroupLayout.length,\r\n ...binding.resourceLayout,\r\n visibility: binding.visibility,\r\n })\r\n })\r\n\r\n this.setBindGroupLayout()\r\n }\r\n\r\n /**\r\n * Called when the {@link core/renderers/GPUDeviceManager.GPUDeviceManager#device | device} has been lost to prepare everything for restoration\r\n */\r\n loseContext() {\r\n this.resetEntries()\r\n\r\n this.bufferBindings.forEach((binding) => {\r\n binding.buffer = null\r\n\r\n if ('resultBuffer' in binding) {\r\n binding.resultBuffer = null\r\n }\r\n })\r\n\r\n this.bindGroup = null\r\n this.bindGroupLayout = null\r\n this.needsPipelineFlush = true\r\n }\r\n\r\n /**\r\n * Get all {@link BindGroup#bindings | bind group bindings} that handle a {@link GPUBuffer}\r\n */\r\n get bufferBindings(): BindGroupBufferBindingElement[] {\r\n return this.bindings.filter(\r\n (binding) => binding instanceof BufferBinding || binding instanceof WritableBufferBinding\r\n ) as BindGroupBufferBindingElement[]\r\n }\r\n\r\n /**\r\n * Creates binding GPUBuffer with correct params\r\n * @param binding - the binding element\r\n */\r\n createBindingBuffer(binding: BindGroupBufferBindingElement) {\r\n // TODO user defined usage?\r\n // [Kangz](https://github.com/Kangz) said:\r\n // \"In general though COPY_SRC/DST is free (at least in Dawn / Chrome because we add it all the time for our own purpose).\"\r\n binding.buffer = this.renderer.createBuffer({\r\n label: this.options.label + ': ' + binding.bindingType + ' buffer from: ' + binding.label,\r\n size: binding.arrayBuffer.byteLength,\r\n usage:\r\n binding.bindingType === 'uniform'\r\n ? GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC | GPUBufferUsage.VERTEX\r\n : GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC | GPUBufferUsage.VERTEX,\r\n })\r\n\r\n if ('resultBuffer' in binding) {\r\n binding.resultBuffer = this.renderer.createBuffer({\r\n label: this.options.label + ': Result buffer from: ' + binding.label,\r\n size: binding.arrayBuffer.byteLength,\r\n usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,\r\n })\r\n }\r\n }\r\n\r\n /**\r\n * Fill in our entries bindGroupLayout and bindGroup arrays with the correct binding resources.\r\n * For buffer struct, create a GPUBuffer first if needed\r\n */\r\n fillEntries() {\r\n this.bindings.forEach((binding) => {\r\n // if no visibility specified, just set it to the maximum default capabilities\r\n if (!binding.visibility) {\r\n binding.visibility = GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE\r\n }\r\n\r\n // if it's a buffer binding, create the GPUBuffer\r\n if ('buffer' in binding && !binding.buffer) {\r\n this.createBindingBuffer(binding)\r\n }\r\n\r\n // now that everything is ready, fill our entries\r\n this.entries.bindGroupLayout.push({\r\n binding: this.entries.bindGroupLayout.length,\r\n ...binding.resourceLayout,\r\n visibility: binding.visibility,\r\n })\r\n\r\n this.entries.bindGroup.push({\r\n binding: this.entries.bindGroup.length,\r\n resource: binding.resource,\r\n })\r\n })\r\n }\r\n\r\n /**\r\n * Get a bind group binding by name/key\r\n * @param bindingName - the binding name or key\r\n * @returns - the found binding, or null if not found\r\n */\r\n getBindingByName(bindingName = ''): BindGroupBindingElement | null {\r\n return this.bindings.find((binding) => binding.name === bindingName)\r\n }\r\n\r\n /**\r\n * Create a GPUBindGroupLayout and set our {@link bindGroupLayout}\r\n */\r\n setBindGroupLayout() {\r\n this.bindGroupLayout = this.renderer.createBindGroupLayout({\r\n label: this.options.label + ' layout',\r\n entries: this.entries.bindGroupLayout,\r\n })\r\n }\r\n\r\n /**\r\n * Create a GPUBindGroup and set our {@link bindGroup}\r\n */\r\n setBindGroup() {\r\n this.bindGroup = this.renderer.createBindGroup({\r\n label: this.options.label,\r\n layout: this.bindGroupLayout,\r\n entries: this.entries.bindGroup,\r\n })\r\n }\r\n\r\n /**\r\n * Check whether we should update (write) our {@link GPUBuffer} or not.\r\n */\r\n updateBufferBindings() {\r\n this.bufferBindings.forEach((binding, index) => {\r\n // update binding elements\r\n binding.update()\r\n\r\n // now write to the GPUBuffer if needed\r\n if (binding.shouldUpdate) {\r\n // bufferOffset is always equals to 0 in our case\r\n if (!binding.useStruct && binding.bufferElements.length > 1) {\r\n // we're in a non struct buffer binding with multiple entries\r\n // that should not happen but that way we're covered\r\n this.renderer.queueWriteBuffer(binding.buffer, 0, binding.bufferElements[index].view)\r\n } else {\r\n this.renderer.queueWriteBuffer(binding.buffer, 0, binding.arrayBuffer)\r\n }\r\n }\r\n\r\n // reset update flag\r\n binding.shouldUpdate = false\r\n })\r\n }\r\n\r\n /**\r\n * Update the {@link BindGroup}, which means update its {@link BindGroup#bufferBindings | buffer bindings} and {@link BindGroup#resetBindGroup | reset it} if needed.\r\n * Called at each render from the parentMesh {@link core/materials/Material.Material | material}\r\n */\r\n update() {\r\n this.updateBufferBindings()\r\n\r\n const needBindGroupReset = this.bindings.some((binding) => binding.shouldResetBindGroup)\r\n const needBindGroupLayoutReset = this.bindings.some((binding) => binding.shouldResetBindGroupLayout)\r\n\r\n // since other bind groups might be using that binding\r\n // wait for the end of the render loop to reset the bindings flags\r\n if (needBindGroupReset || needBindGroupLayoutReset) {\r\n this.renderer.onAfterCommandEncoderSubmission.add(\r\n () => {\r\n this.bindings.forEach((binding) => {\r\n binding.shouldResetBindGroup = false\r\n binding.shouldResetBindGroupLayout = false\r\n })\r\n },\r\n { once: true }\r\n )\r\n }\r\n\r\n if (needBindGroupLayoutReset) {\r\n this.resetBindGroupLayout()\r\n // bind group layout has changed, we have to recreate the pipeline\r\n this.needsPipelineFlush = true\r\n }\r\n\r\n if (needBindGroupReset) {\r\n this.resetBindGroup()\r\n }\r\n }\r\n\r\n /**\r\n * Clones a {@link BindGroup} from a list of {@link bindings}\r\n * Useful to create a new bind group with already created buffers, but swapped\r\n * @param parameters - parameters to use for cloning\r\n * @param parameters.bindings - our input {@link bindings}\r\n * @param [parameters.keepLayout=false] - whether we should keep original {@link bindGroupLayout} or not\r\n * @returns - the cloned {@link BindGroup}\r\n */\r\n clone({\r\n bindings = [],\r\n keepLayout = false,\r\n }: {\r\n bindings?: BindGroupBindingElement[]\r\n keepLayout?: boolean\r\n } = {}): AllowedBindGroups {\r\n const params = { ...this.options }\r\n params.label += ' (copy)'\r\n\r\n const bindGroupCopy = new (this.constructor as typeof BindGroup)(this.renderer, {\r\n label: params.label,\r\n })\r\n\r\n bindGroupCopy.setIndex(this.index)\r\n bindGroupCopy.options = params\r\n\r\n const bindingsRef = bindings.length ? bindings : this.bindings\r\n\r\n bindingsRef.forEach((binding, index) => {\r\n bindGroupCopy.addBinding(binding)\r\n\r\n // if it's a buffer binding without a GPUBuffer, create it now\r\n if ('buffer' in binding && !binding.buffer) {\r\n bindGroupCopy.createBindingBuffer(binding)\r\n }\r\n\r\n // if we should create a new bind group layout, fill it\r\n if (!keepLayout) {\r\n bindGroupCopy.entries.bindGroupLayout.push({\r\n binding: bindGroupCopy.entries.bindGroupLayout.length,\r\n ...binding.resourceLayout,\r\n visibility: binding.visibility,\r\n })\r\n }\r\n\r\n bindGroupCopy.entries.bindGroup.push({\r\n binding: bindGroupCopy.entries.bindGroup.length,\r\n resource: binding.resource,\r\n } as GPUBindGroupEntry)\r\n })\r\n\r\n // if we should copy the given bind group layout\r\n if (keepLayout) {\r\n bindGroupCopy.entries.bindGroupLayout = [...this.entries.bindGroupLayout]\r\n }\r\n\r\n bindGroupCopy.setBindGroupLayout()\r\n bindGroupCopy.setBindGroup()\r\n\r\n return bindGroupCopy\r\n }\r\n\r\n /**\r\n * Destroy our {@link BindGroup}\r\n * Most important is to destroy the GPUBuffers to free the memory\r\n */\r\n destroy() {\r\n this.renderer.removeBindGroup(this)\r\n\r\n this.bufferBindings.forEach((binding) => {\r\n if ('buffer' in binding) {\r\n this.renderer.removeBuffer(binding.buffer)\r\n binding.buffer?.destroy()\r\n binding.buffer = null\r\n }\r\n\r\n if ('resultBuffer' in binding) {\r\n this.renderer.removeBuffer(binding.resultBuffer)\r\n binding.resultBuffer?.destroy()\r\n binding.resultBuffer = null\r\n }\r\n })\r\n\r\n this.bindings = []\r\n this.bindGroupLayout = null\r\n this.bindGroup = null\r\n this.resetEntries()\r\n }\r\n}\r\n","import { Binding, BindingMemoryAccessType, BindingParams, BindingType } from './Binding'\nimport { getBindGroupLayoutTextureBindingType, getTextureBindingWGSLVarType } from './utils'\n\n/** Defines a {@link TextureBinding} {@link TextureBinding#resource | resource} */\nexport type TextureBindingResource = GPUTexture | GPUExternalTexture | null\n\n/**\n * An object defining all possible {@link TextureBinding} class instancing parameters\n */\nexport interface TextureBindingParams extends BindingParams {\n /** {@link TextureBinding} {@link TextureBinding#resource | resource} */\n texture: TextureBindingResource\n /** The {@link GPUTexture | texture} format to use */\n format?: GPUTextureFormat\n /** The storage {@link GPUTexture | texture} binding memory access types (read only, write only or read/write) */\n access?: BindingMemoryAccessType\n /** The {@link GPUTexture | texture} view dimension to use */\n viewDimension?: GPUTextureViewDimension\n /** Whethe the {@link GPUTexture | texture} is a multisampled texture. Mainly used internally by depth textures if needed. */\n multisampled?: boolean\n}\n\n/**\n * Used to handle {@link GPUTexture} and {@link GPUExternalTexture} bindings.\n *\n * Provide both {@link TextureBinding#resourceLayout | resourceLayout} and {@link TextureBinding#resource | resource} to the {@link GPUBindGroupLayout} and {@link GPUBindGroup}.
\n * Also create the appropriate WGSL code snippet to add to the shaders.\n */\nexport class TextureBinding extends Binding {\n /** Our {@link TextureBinding} resource, i.e. a {@link GPUTexture} or {@link GPUExternalTexture} */\n texture: TextureBindingResource\n /** An array of strings to append to our shaders code declaring all the WGSL variables representing this {@link TextureBinding} */\n wgslGroupFragment: string[]\n /** Options used to create this {@link TextureBinding} */\n options: TextureBindingParams\n\n /**\n * TextureBinding constructor\n * @param parameters - {@link TextureBindingParams | parameters} used to create our {@link TextureBinding}\n */\n constructor({\n label = 'Texture',\n name = 'texture',\n bindingType,\n visibility,\n texture,\n format = 'rgba8unorm',\n access = 'write',\n viewDimension = '2d',\n multisampled = false,\n }: TextureBindingParams) {\n bindingType = bindingType ?? 'texture'\n\n if (bindingType === 'storage') {\n visibility = 'compute'\n }\n\n super({ label, name, bindingType, visibility })\n\n this.options = {\n ...this.options,\n texture,\n format,\n access,\n viewDimension,\n multisampled,\n }\n\n this.resource = texture // should be a texture or an external texture\n\n this.setWGSLFragment()\n }\n\n /**\n * Get bind group layout entry resource, either for {@link GPUBindGroupLayoutEntry#texture | texture} or {@link GPUBindGroupLayoutEntry#externalTexture | external texture}\n * @readonly\n */\n get resourceLayout():\n | GPUTextureBindingLayout\n | GPUExternalTextureBindingLayout\n | GPUStorageTextureBindingLayout\n | null {\n return getBindGroupLayoutTextureBindingType(this)\n }\n\n /**\n * Get the {@link GPUBindGroupEntry#resource | bind group resource}\n */\n get resource(): GPUExternalTexture | GPUTextureView | null {\n return this.texture instanceof GPUTexture\n ? this.texture.createView({ label: this.options.label + ' view', dimension: this.options.viewDimension })\n : this.texture instanceof GPUExternalTexture\n ? this.texture\n : null\n }\n\n /**\n * Set the {@link GPUBindGroupEntry#resource | bind group resource}\n * @param value - new bind group resource\n */\n set resource(value: TextureBindingResource) {\n // resource changed, update bind group!\n if (value || this.texture) this.shouldResetBindGroup = true\n this.texture = value\n }\n\n /**\n * Set or update our {@link Binding#bindingType | bindingType} and our WGSL code snippet\n * @param bindingType - the new {@link Binding#bindingType | binding type}\n */\n setBindingType(bindingType: BindingType) {\n if (bindingType !== this.bindingType) {\n // binding type has changed!\n if (bindingType) this.shouldResetBindGroupLayout = true\n\n this.bindingType = bindingType\n this.setWGSLFragment()\n }\n }\n\n /**\n * Set the correct WGSL code snippet.\n */\n setWGSLFragment() {\n this.wgslGroupFragment = [`${getTextureBindingWGSLVarType(this)}`]\n }\n}\n","import { Vec3 } from './Vec3'\nimport { Quat } from './Quat'\n\nconst xAxis = new Vec3()\nconst yAxis = new Vec3()\nconst zAxis = new Vec3()\n\n/**\n * Basic 4x4 matrix class used for matrix calculations.\n *\n * Note that like three.js, the constructor and {@link set} method take arguments in row-major order, while internally they are stored in the {@link elements} array in column-major order.\n *\n * @see https://github.com/mrdoob/three.js/blob/dev/src/math/Matrix4.js\n * @see http://glmatrix.net/docs/mat4.js.html\n */\nexport class Mat4 {\n /** The type of the {@link Mat4} */\n type: string\n /** Our matrix array */\n elements: Float32Array\n\n // prettier-ignore\n /**\n * Mat4 constructor\n * @param elements - initial array to use, default to identity matrix\n */\n constructor(elements: Float32Array = new Float32Array([\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1\n ])) {\n this.type = 'Mat4'\n this.elements = elements\n }\n\n /***\n * Sets the matrix from 16 numbers\n *\n * @param n11 number\n * @param n12 number\n * @param n13 number\n * @param n14 number\n * @param n21 number\n * @param n22 number\n * @param n23 number\n * @param n24 number\n * @param n31 number\n * @param n32 number\n * @param n33 number\n * @param n34 number\n * @param n41 number\n * @param n42 number\n * @param n43 number\n * @param n44 number\n *\n * @returns - this {@link Mat4} after being set\n */\n set(\n n11: number,\n n12: number,\n n13: number,\n n14: number,\n n21: number,\n n22: number,\n n23: number,\n n24: number,\n n31: number,\n n32: number,\n n33: number,\n n34: number,\n n41: number,\n n42: number,\n n43: number,\n n44: number\n ): Mat4 {\n const te = this.elements\n\n te[0] = n11\n te[1] = n12\n te[2] = n13\n te[3] = n14\n te[4] = n21\n te[5] = n22\n te[6] = n23\n te[7] = n24\n te[8] = n31\n te[9] = n32\n te[10] = n33\n te[11] = n34\n te[12] = n41\n te[13] = n42\n te[14] = n43\n te[15] = n44\n\n return this\n }\n\n /**\n * Sets the {@link Mat4} to an identity matrix\n * @returns - this {@link Mat4} after being set\n */\n identity(): Mat4 {\n // prettier-ignore\n this.set(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1\n )\n\n return this\n }\n\n /**\n * Sets the {@link Mat4} values from an array\n * @param array - array to use\n * @returns - this {@link Mat4} after being set\n */\n // prettier-ignore\n setFromArray(array: Float32Array | number[] = new Float32Array([\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1\n ])): Mat4 {\n for (let i = 0; i < this.elements.length; i++) {\n this.elements[i] = array[i]\n }\n\n return this\n }\n\n /**\n * Copy another {@link Mat4}\n * @param matrix\n * @returns - this {@link Mat4} after being set\n */\n copy(matrix: Mat4 = new Mat4()): Mat4 {\n const array = matrix.elements\n this.elements[0] = array[0]\n this.elements[1] = array[1]\n this.elements[2] = array[2]\n this.elements[3] = array[3]\n this.elements[4] = array[4]\n this.elements[5] = array[5]\n this.elements[6] = array[6]\n this.elements[7] = array[7]\n this.elements[8] = array[8]\n this.elements[9] = array[9]\n this.elements[10] = array[10]\n this.elements[11] = array[11]\n this.elements[12] = array[12]\n this.elements[13] = array[13]\n this.elements[14] = array[14]\n this.elements[15] = array[15]\n\n return this\n }\n\n /**\n * Clone a {@link Mat4}\n * @returns - cloned {@link Mat4}\n */\n clone(): Mat4 {\n return new Mat4().copy(this)\n }\n\n /**\n * Multiply this {@link Mat4} with another {@link Mat4}\n * @param matrix - {@link Mat4} to multiply with\n * @returns - this {@link Mat4} after multiplication\n */\n multiply(matrix: Mat4 = new Mat4()): Mat4 {\n return this.multiplyMatrices(this, matrix)\n }\n\n /**\n * Multiply another {@link Mat4} with this {@link Mat4}\n * @param matrix - {@link Mat4} to multiply with\n * @returns - this {@link Mat4} after multiplication\n */\n premultiply(matrix: Mat4 = new Mat4()): Mat4 {\n return this.multiplyMatrices(matrix, this)\n }\n\n /**\n * Multiply two {@link Mat4}\n * @param a - first {@link Mat4}\n * @param b - second {@link Mat4}\n * @returns - {@link Mat4} resulting from the multiplication\n */\n multiplyMatrices(a: Mat4 = new Mat4(), b: Mat4 = new Mat4()): Mat4 {\n const ae = a.elements\n const be = b.elements\n const te = this.elements\n\n const a11 = ae[0],\n a12 = ae[4],\n a13 = ae[8],\n a14 = ae[12]\n const a21 = ae[1],\n a22 = ae[5],\n a23 = ae[9],\n a24 = ae[13]\n const a31 = ae[2],\n a32 = ae[6],\n a33 = ae[10],\n a34 = ae[14]\n const a41 = ae[3],\n a42 = ae[7],\n a43 = ae[11],\n a44 = ae[15]\n\n const b11 = be[0],\n b12 = be[4],\n b13 = be[8],\n b14 = be[12]\n const b21 = be[1],\n b22 = be[5],\n b23 = be[9],\n b24 = be[13]\n const b31 = be[2],\n b32 = be[6],\n b33 = be[10],\n b34 = be[14]\n const b41 = be[3],\n b42 = be[7],\n b43 = be[11],\n b44 = be[15]\n\n te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41\n te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42\n te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43\n te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44\n\n te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41\n te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42\n te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43\n te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44\n\n te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41\n te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42\n te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43\n te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44\n\n te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41\n te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42\n te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43\n te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44\n\n return this\n }\n\n /**\n * {@link premultiply} this {@link Mat4} by a translate matrix (i.e. translateMatrix = new Mat4().translate(vector))\n * @param vector - translation {@link Vec3 | vector} to use\n * @returns - this {@link Mat4} after the premultiply translate operation\n */\n premultiplyTranslate(vector: Vec3 = new Vec3()): Mat4 {\n // premultiply by a translateMatrix, ie translateMatrix = new Mat4().translate(vector)\n // where translateMatrix[0] = 1, translateMatrix[5] = 1, scaleMatrix[10] = 1, translateMatrix[15] = 1 from identity\n // and translateMatrix[12] = vector.x, translateMatrix[13] = vector.y, translateMatrix[14] = vector.z from translation\n // equivalent (but faster) to this.multiply(translateMatrix, this)\n\n // from identity matrix\n const a11 = 1\n const a22 = 1\n const a33 = 1\n const a44 = 1\n\n // from translation\n const a14 = vector.x\n const a24 = vector.y\n const a34 = vector.z\n\n const be = this.elements\n const te = this.elements\n\n const b11 = be[0],\n b12 = be[4],\n b13 = be[8],\n b14 = be[12]\n const b21 = be[1],\n b22 = be[5],\n b23 = be[9],\n b24 = be[13]\n const b31 = be[2],\n b32 = be[6],\n b33 = be[10],\n b34 = be[14]\n const b41 = be[3],\n b42 = be[7],\n b43 = be[11],\n b44 = be[15]\n\n te[0] = a11 * b11 + a14 * b41\n te[4] = a11 * b12 + a14 * b42\n te[8] = a11 * b13 + a14 * b43\n te[12] = a11 * b14 + a14 * b44\n\n te[1] = a22 * b21 + a24 * b41\n te[5] = a22 * b22 + a24 * b42\n te[9] = a22 * b23 + a24 * b43\n te[13] = a22 * b24 + a24 * b44\n\n te[2] = a33 * b31 + a34 * b41\n te[6] = a33 * b32 + a34 * b42\n te[10] = a33 * b33 + a34 * b43\n te[14] = a33 * b34 + a34 * b44\n\n te[3] = a44 * b41\n te[7] = a44 * b42\n te[11] = a44 * b43\n te[15] = a44 * b44\n\n return this\n }\n\n /**\n * {@link premultiply} this {@link Mat4} by a scale matrix (i.e. translateMatrix = new Mat4().scale(vector))\n * @param vector - scale {@link Vec3 | vector} to use\n * @returns - this {@link Mat4} after the premultiply scale operation\n */\n premultiplyScale(vector: Vec3 = new Vec3()): Mat4 {\n // premultiply by a scaleMatrix, ie scaleMatrix = new Mat4().scale(vector)\n // where scaleMatrix[0] = vector.x, scaleMatrix[5] = vector.y, scaleMatrix[10] = vector.z, scaleMatrix[15] = 1\n // equivalent (but faster) to this.multiply(scaleMatrix, this)\n\n const be = this.elements\n const te = this.elements\n\n const a11 = vector.x\n const a22 = vector.y\n const a33 = vector.z\n const a44 = 1\n\n const b11 = be[0],\n b12 = be[4],\n b13 = be[8],\n b14 = be[12]\n const b21 = be[1],\n b22 = be[5],\n b23 = be[9],\n b24 = be[13]\n const b31 = be[2],\n b32 = be[6],\n b33 = be[10],\n b34 = be[14]\n const b41 = be[3],\n b42 = be[7],\n b43 = be[11],\n b44 = be[15]\n\n te[0] = a11 * b11\n te[4] = a11 * b12\n te[8] = a11 * b13\n te[12] = a11 * b14\n\n te[1] = a22 * b21\n te[5] = a22 * b22\n te[9] = a22 * b23\n te[13] = a22 * b24\n\n te[2] = a33 * b31\n te[6] = a33 * b32\n te[10] = a33 * b33\n te[14] = a33 * b34\n\n te[3] = a44 * b41\n te[7] = a44 * b42\n te[11] = a44 * b43\n te[15] = a44 * b44\n\n return this\n }\n\n /**\n * Get the {@link Mat4} inverse\n * @returns - the inverted {@link Mat4}\n */\n invert() {\n // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm\n const te = this.elements,\n n11 = te[0],\n n21 = te[1],\n n31 = te[2],\n n41 = te[3],\n n12 = te[4],\n n22 = te[5],\n n32 = te[6],\n n42 = te[7],\n n13 = te[8],\n n23 = te[9],\n n33 = te[10],\n n43 = te[11],\n n14 = te[12],\n n24 = te[13],\n n34 = te[14],\n n44 = te[15],\n t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,\n t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,\n t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,\n t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34\n\n const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14\n\n if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n\n const detInv = 1 / det\n\n te[0] = t11 * detInv\n te[1] =\n (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) *\n detInv\n te[2] =\n (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) *\n detInv\n te[3] =\n (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) *\n detInv\n\n te[4] = t12 * detInv\n te[5] =\n (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) *\n detInv\n te[6] =\n (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) *\n detInv\n te[7] =\n (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) *\n detInv\n\n te[8] = t13 * detInv\n te[9] =\n (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) *\n detInv\n te[10] =\n (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) *\n detInv\n te[11] =\n (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) *\n detInv\n\n te[12] = t14 * detInv\n te[13] =\n (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) *\n detInv\n te[14] =\n (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) *\n detInv\n te[15] =\n (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) *\n detInv\n\n return this\n }\n\n /**\n * Clone and invert the {@link Mat4}\n * @returns - inverted cloned {@link Mat4}\n */\n getInverse(): Mat4 {\n return this.clone().invert()\n }\n\n /**\n * Transpose this {@link Mat4}\n * @returns - the transposed {@link Mat4}\n */\n transpose(): Mat4 {\n let t\n const te = this.elements\n\n t = te[1]\n te[1] = te[4]\n te[4] = t\n\n t = te[2]\n te[2] = te[8]\n te[8] = t\n\n t = te[3]\n te[3] = te[12]\n te[12] = t\n\n t = te[6]\n te[6] = te[9]\n te[9] = t\n\n t = te[7]\n te[7] = te[13]\n te[13] = t\n\n t = te[11]\n te[11] = te[14]\n te[14] = t\n\n return this\n }\n\n /**\n * Translate a {@link Mat4}\n * @param vector - translation {@link Vec3 | vector} to use\n * @returns - translated {@link Mat4}\n */\n translate(vector: Vec3 = new Vec3()): Mat4 {\n const a = this.elements\n\n a[12] = a[0] * vector.x + a[4] * vector.y + a[8] * vector.z + a[12]\n a[13] = a[1] * vector.x + a[5] * vector.y + a[9] * vector.z + a[13]\n a[14] = a[2] * vector.x + a[6] * vector.y + a[10] * vector.z + a[14]\n a[15] = a[3] * vector.x + a[7] * vector.y + a[11] * vector.z + a[15]\n\n return this\n }\n\n /**\n * Get the translation {@link Vec3} component of a {@link Mat4}\n * @param position - {@link Vec3} to set\n * @returns - translation {@link Vec3} component of this {@link Mat4}\n */\n getTranslation(position = new Vec3()): Vec3 {\n return position.set(this.elements[12], this.elements[13], this.elements[14])\n }\n\n /**\n * Scale a {@link Mat4}\n * @param vector - scale {@link Vec3 | vector} to use\n * @returns - scaled {@link Mat4}\n */\n scale(vector: Vec3 = new Vec3()): Mat4 {\n const a = this.elements\n\n a[0] *= vector.x\n a[1] *= vector.x\n a[2] *= vector.x\n a[3] *= vector.x\n a[4] *= vector.y\n a[5] *= vector.y\n a[6] *= vector.y\n a[7] *= vector.y\n a[8] *= vector.z\n a[9] *= vector.z\n a[10] *= vector.z\n a[11] *= vector.z\n\n return this\n }\n\n /**\n * Rotate a {@link Mat4} from a {@link Quat | quaternion}\n * @param quaternion - {@link Quat | quaternion} to use\n * @returns - rotated {@link Mat4}\n */\n rotateFromQuaternion(quaternion: Quat = new Quat()): Mat4 {\n const te = this.elements\n\n const x = quaternion.elements[0],\n y = quaternion.elements[1],\n z = quaternion.elements[2],\n w = quaternion.elements[3]\n\n const x2 = x + x,\n y2 = y + y,\n z2 = z + z\n const xx = x * x2,\n xy = x * y2,\n xz = x * z2\n const yy = y * y2,\n yz = y * z2,\n zz = z * z2\n const wx = w * x2,\n wy = w * y2,\n wz = w * z2\n\n te[0] = 1 - (yy + zz)\n te[4] = xy - wz\n te[8] = xz + wy\n\n te[1] = xy + wz\n te[5] = 1 - (xx + zz)\n te[9] = yz - wx\n\n te[2] = xz - wy\n te[6] = yz + wx\n te[10] = 1 - (xx + yy)\n\n return this\n }\n\n /**\n * Creates a {@link Mat4} from a {@link Quat | quaternion} rotation, {@link Vec3 | vector} translation and {@link Vec3 | vector} scale\n * Equivalent for applying translation, rotation and scale matrices but much faster\n * Source code from: http://glmatrix.net/docs/mat4.js.html\n *\n * @param translation - translation {@link Vec3 | vector} to use\n * @param quaternion - {@link Quat | quaternion} to use\n * @param scale - translation {@link Vec3 | vector} to use\n * @returns - transformed {@link Mat4}\n */\n compose(translation: Vec3 = new Vec3(), quaternion: Quat = new Quat(), scale: Vec3 = new Vec3(1)): Mat4 {\n const matrix = this.elements\n\n // Quaternion math\n const x = quaternion.elements[0],\n y = quaternion.elements[1],\n z = quaternion.elements[2],\n w = quaternion.elements[3]\n\n const x2 = x + x\n const y2 = y + y\n const z2 = z + z\n const xx = x * x2\n const xy = x * y2\n const xz = x * z2\n const yy = y * y2\n const yz = y * z2\n const zz = z * z2\n const wx = w * x2\n const wy = w * y2\n const wz = w * z2\n const sx = scale.x\n const sy = scale.y\n const sz = scale.z\n\n matrix[0] = (1 - (yy + zz)) * sx\n matrix[1] = (xy + wz) * sx\n matrix[2] = (xz - wy) * sx\n matrix[3] = 0\n matrix[4] = (xy - wz) * sy\n matrix[5] = (1 - (xx + zz)) * sy\n matrix[6] = (yz + wx) * sy\n matrix[7] = 0\n matrix[8] = (xz + wy) * sz\n matrix[9] = (yz - wx) * sz\n matrix[10] = (1 - (xx + yy)) * sz\n matrix[11] = 0\n matrix[12] = translation.x\n matrix[13] = translation.y\n matrix[14] = translation.z\n matrix[15] = 1\n\n return this\n }\n\n /**\n * Creates a {@link Mat4} from a {@link Quat | quaternion} rotation, {@link Vec3 | vector} translation and {@link Vec3 | vector} scale, rotating and scaling around the given {@link Vec3 | origin vector}\n * Equivalent for applying translation, rotation and scale matrices but much faster\n * Source code from: http://glmatrix.net/docs/mat4.js.html\n *\n * @param translation - translation {@link Vec3 | vector} to use\n * @param quaternion - {@link Quat | quaternion} to use\n * @param scale - translation {@link Vec3 | vector} to use\n * @param origin - origin {@link Vec3 | vector} around which to scale and rotate\n * @returns - transformed {@link Mat4}\n */\n composeFromOrigin(\n translation: Vec3 = new Vec3(),\n quaternion: Quat = new Quat(),\n scale: Vec3 = new Vec3(1),\n origin: Vec3 = new Vec3()\n ): Mat4 {\n const matrix = this.elements\n\n // Quaternion math\n const x = quaternion.elements[0],\n y = quaternion.elements[1],\n z = quaternion.elements[2],\n w = quaternion.elements[3]\n\n const x2 = x + x\n const y2 = y + y\n const z2 = z + z\n\n const xx = x * x2\n const xy = x * y2\n const xz = x * z2\n const yy = y * y2\n const yz = y * z2\n const zz = z * z2\n\n const wx = w * x2\n const wy = w * y2\n const wz = w * z2\n\n const sx = scale.x\n const sy = scale.y\n const sz = scale.z\n\n const ox = origin.x\n const oy = origin.y\n const oz = origin.z\n\n const out0 = (1 - (yy + zz)) * sx\n const out1 = (xy + wz) * sx\n const out2 = (xz - wy) * sx\n const out4 = (xy - wz) * sy\n const out5 = (1 - (xx + zz)) * sy\n const out6 = (yz + wx) * sy\n const out8 = (xz + wy) * sz\n const out9 = (yz - wx) * sz\n const out10 = (1 - (xx + yy)) * sz\n\n matrix[0] = out0\n matrix[1] = out1\n matrix[2] = out2\n matrix[3] = 0\n matrix[4] = out4\n matrix[5] = out5\n matrix[6] = out6\n matrix[7] = 0\n matrix[8] = out8\n matrix[9] = out9\n matrix[10] = out10\n matrix[11] = 0\n matrix[12] = translation.x + ox - (out0 * ox + out4 * oy + out8 * oz)\n matrix[13] = translation.y + oy - (out1 * ox + out5 * oy + out9 * oz)\n matrix[14] = translation.z + oz - (out2 * ox + out6 * oy + out10 * oz)\n matrix[15] = 1\n\n return this\n }\n\n /**\n * Set this {@link Mat4} as a rotation matrix based on an eye, target and up {@link Vec3 | vectors}\n * @param eye - {@link Vec3 | position vector} of the object that should be rotated\n * @param target - {@link Vec3 | target vector} to look at\n * @param up - up {@link Vec3 | vector}\n * @returns - rotated {@link Mat4}\n */\n lookAt(eye: Vec3 = new Vec3(), target: Vec3 = new Vec3(), up: Vec3 = new Vec3(0, 1, 0)): Mat4 {\n const te = this.elements\n\n zAxis.copy(eye).sub(target)\n\n if (zAxis.lengthSq() === 0) {\n // eye and target are in the same position\n zAxis.z = 1\n }\n\n zAxis.normalize()\n xAxis.crossVectors(up, zAxis)\n\n if (xAxis.lengthSq() === 0) {\n // up and z are parallel\n if (Math.abs(up.z) === 1) {\n zAxis.x += 0.0001\n } else {\n zAxis.z += 0.0001\n }\n\n zAxis.normalize()\n xAxis.crossVectors(up, zAxis)\n }\n\n xAxis.normalize()\n yAxis.crossVectors(zAxis, xAxis)\n\n te[0] = xAxis.x\n te[1] = xAxis.y\n te[2] = xAxis.z\n te[3] = 0\n te[4] = yAxis.x\n te[5] = yAxis.y\n te[6] = yAxis.z\n te[7] = 0\n te[8] = zAxis.x\n te[9] = zAxis.y\n te[10] = zAxis.z\n te[11] = 0\n te[12] = eye.x\n te[13] = eye.y\n te[14] = eye.z\n te[15] = 1\n\n return this\n }\n\n /**\n * Compute a view {@link Mat4} matrix.\n *\n * This is a view matrix which transforms all other objects\n * to be in the space of the view defined by the parameters.\n *\n * @param eye - the position of the object.\n * @param target - the position meant to be aimed at.\n * @param up - a vector pointing up.\n * @returns - the view {@link Mat4} matrix.\n */\n makeView(eye: Vec3 = new Vec3(), target: Vec3 = new Vec3(), up: Vec3 = new Vec3(0, 1, 0)): Mat4 {\n // TODO can easily be confused with lookAt\n\n zAxis.copy(eye).sub(target).normalize()\n xAxis.crossVectors(up, zAxis).normalize()\n yAxis.crossVectors(zAxis, xAxis).normalize()\n\n const te = this.elements\n\n te[0] = xAxis.x\n te[1] = yAxis.x\n te[2] = zAxis.x\n te[3] = 0\n te[4] = xAxis.y\n te[5] = yAxis.y\n te[6] = zAxis.y\n te[7] = 0\n te[8] = xAxis.z\n te[9] = yAxis.z\n te[10] = zAxis.z\n te[11] = 0\n\n te[12] = -(xAxis.x * eye.x + xAxis.y * eye.y + xAxis.z * eye.z)\n te[13] = -(yAxis.x * eye.x + yAxis.y * eye.y + yAxis.z * eye.z)\n te[14] = -(zAxis.x * eye.x + zAxis.y * eye.y + zAxis.z * eye.z)\n te[15] = 1\n\n return this\n }\n\n /**\n * Create an orthographic {@link Mat4} matrix based on the parameters. Transforms from\n * * the given the left, right, bottom, and top dimensions to -1 +1 in x, and y\n * * and 0 to +1 in z.\n *\n * @param parameters - parameters used to create the camera orthographic matrix.\n * @param parameters.left - the left side of the camera near clipping plane viewport.\n * @param parameters.right - the right side of the camera near clipping plane viewport.\n * @param parameters.bottom - the bottom of the camera near clipping plane viewport.\n * @param parameters.top - the top of the camera near clipping plane viewport.\n * @param parameters.near - the camera near plane.\n * @param parameters.far - the camera far plane.\n * @returns - the camera orthographic {@link Mat4} matrix.\n */\n makeOrthographic({\n left,\n right,\n bottom,\n top,\n near,\n far,\n }: {\n left: number\n right: number\n bottom: number\n top: number\n near: number\n far: number\n }): Mat4 {\n const te = this.elements\n\n te[0] = 2 / (right - left)\n te[1] = 0\n te[2] = 0\n te[3] = 0\n\n te[4] = 0\n te[5] = 2 / (top - bottom)\n te[6] = 0\n te[7] = 0\n\n te[8] = 0\n te[9] = 0\n te[10] = 1 / (near - far)\n te[11] = 0\n\n te[12] = (right + left) / (left - right)\n te[13] = (top + bottom) / (bottom - top)\n te[14] = near / (near - far)\n te[15] = 1\n\n return this\n }\n\n /**\n * Create a perspective {@link Mat4} matrix based on the parameters.\n *\n * Note, The matrix generated sends the viewing frustum to the unit box.\n * We assume a unit box extending from -1 to 1 in the x and y dimensions and\n * from -1 to 1 in the z dimension, as three.js and more generally WebGL handles it.\n *\n * @param parameters - parameters used to create the camera perspective matrix.\n * @param parameters.fov - the camera field of view (in radians).\n * @param parameters.aspect - the camera aspect ratio (width / height).\n * @param parameters.near - the camera near plane.\n * @param parameters.far - the camera far plane.\n * @returns - the camera perspective {@link Mat4} matrix.\n */\n makePerspective({ fov, aspect, near, far }: { fov: number; aspect: number; near: number; far: number }): Mat4 {\n // TODO handle z from 0 to 1 like https://github.com/greggman/wgpu-matrix/blob/main/src/mat4-impl.ts#L756 does it?\n // It would be aligned with the WebGPU specs but it breaks the Camera screenRatio and DOMObject3D position calcs\n\n const top = near * Math.tan((Math.PI / 180) * 0.5 * fov)\n const height = 2 * top\n const width = aspect * height\n const left = -0.5 * width\n\n const right = left + width\n const bottom = top - height\n\n const x = (2 * near) / (right - left)\n const y = (2 * near) / (top - bottom)\n\n const a = (right + left) / (right - left)\n const b = (top + bottom) / (top - bottom)\n const c = -(far + near) / (far - near)\n const d = (-2 * far * near) / (far - near)\n\n // prettier-ignore\n this.set(\n x, 0, 0, 0,\n 0, y, 0, 0,\n a, b, c, -1,\n 0, 0, d, 0\n )\n\n return this\n }\n}\n","import { Vec3 } from '../../math/Vec3'\nimport { Quat } from '../../math/Quat'\nimport { Mat4 } from '../../math/Mat4'\n\nlet objectIndex = 0\n\n/** Defines all kind of possible {@link Object3D} matrix types */\nexport type Object3DMatricesType = 'model' | 'world'\n\n/**\n * Defines an {@link Object3D} matrix object\n */\nexport interface Object3DTransformMatrix {\n /** The {@link Mat4 | matrix} used */\n matrix: Mat4\n /** Whether we should update the {@link Mat4 | matrix} */\n shouldUpdate: boolean\n /** Function to update our {@link Mat4 | matrix} */\n onUpdate: () => void\n}\n\n/** Defines all possible {@link Object3DTransformMatrix | matrix object} used by our {@link Object3D} */\nexport type Object3DMatrices = Record\n\n/**\n * Defines all necessary {@link Vec3 | vectors}/{@link Quat | quaternions} to compute a 3D {@link Mat4 | model matrix}\n */\nexport interface Object3DTransforms {\n /** Transformation origin object */\n origin: {\n /** Transformation origin {@link Vec3 | vector} relative to the {@link Object3D} */\n model: Vec3\n }\n /** Model {@link Quat | quaternion} defining its rotation in 3D space */\n quaternion: Quat\n /** Model rotation {@link Vec3 | vector} used to compute its {@link Quat | quaternion} */\n rotation: Vec3\n /** Position object */\n position: {\n /** Position {@link Vec3 | vector} relative to the 3D world */\n world: Vec3\n }\n /** Model 3D scale {@link Vec3 | vector} */\n scale: Vec3\n}\n\n/**\n * Used to create an object with transformation properties such as position, scale, rotation and transform origin {@link Vec3 | vectors} and a {@link Quat | quaternion} in order to compute the {@link Object3D#modelMatrix | model matrix} and {@link Object3D#worldMatrix | world matrix}.\n *\n * If an {@link Object3D} does not have any {@link Object3D#parent | parent}, then its {@link Object3D#modelMatrix | model matrix} and {@link Object3D#worldMatrix | world matrix} are the same.\n *\n * The transformations {@link Vec3 | vectors} are reactive to changes, which mean that updating one of their components will automatically update the {@link Object3D#modelMatrix | model matrix} and {@link Object3D#worldMatrix | world matrix}.\n */\nexport class Object3D {\n /** {@link Object3DTransforms | Transformation object} of the {@link Object3D} */\n transforms: Object3DTransforms\n /** {@link Object3DMatrices | Matrices object} of the {@link Object3D} */\n matrices: Object3DMatrices\n\n /** Parent {@link Object3D} in the scene graph, used to compute the {@link worldMatrix | world matrix} */\n private _parent: null | Object3D\n /** Children {@link Object3D} in the scene graph, used to compute their own {@link worldMatrix | world matrix} */\n children: Object3D[]\n\n /** Index (order of creation) of this {@link Object3D}. Used in the {@link parent} / {@link children} relation. */\n object3DIndex: number\n\n /**\n * Object3D constructor\n */\n constructor() {\n this.parent = null\n this.children = []\n\n Object.defineProperty(this as Object3D, 'object3DIndex', { value: objectIndex++ })\n\n this.setMatrices()\n this.setTransforms()\n }\n\n /* PARENT */\n\n /**\n * Get the parent of this {@link Object3D} if any\n */\n get parent(): Object3D | null {\n return this._parent\n }\n\n /**\n * Set the parent of this {@link Object3D}\n * @param value - new parent to set, could be an {@link Object3D} or null\n */\n set parent(value: Object3D | null) {\n if (this.parent) {\n this.parent.children = this.parent.children.filter((child) => child.object3DIndex !== this.object3DIndex)\n }\n this._parent = value\n this._parent?.children.push(this)\n }\n\n /* TRANSFORMS */\n\n /**\n * Set our transforms properties and {@link Vec3#onChange | vectors onChange} callbacks\n */\n setTransforms() {\n this.transforms = {\n origin: {\n model: new Vec3(),\n },\n quaternion: new Quat(),\n rotation: new Vec3(),\n position: {\n world: new Vec3(),\n },\n scale: new Vec3(1),\n }\n\n this.rotation.onChange(() => this.applyRotation())\n this.position.onChange(() => this.applyPosition())\n this.scale.onChange(() => this.applyScale())\n this.transformOrigin.onChange(() => this.applyTransformOrigin())\n }\n\n /**\n * Get our rotation {@link Vec3 | vector}\n */\n get rotation(): Vec3 {\n return this.transforms.rotation\n }\n\n /**\n * Set our rotation {@link Vec3 | vector}\n * @param value - new rotation {@link Vec3 | vector}\n */\n set rotation(value: Vec3) {\n this.transforms.rotation = value\n this.applyRotation()\n }\n\n /**\n * Get our {@link Quat | quaternion}\n */\n get quaternion(): Quat {\n return this.transforms.quaternion\n }\n\n /**\n * Set our {@link Quat | quaternion}\n * @param value - new {@link Quat | quaternion}\n */\n set quaternion(value: Quat) {\n this.transforms.quaternion = value\n }\n\n /**\n * Get our position {@link Vec3 | vector}\n */\n get position(): Vec3 {\n return this.transforms.position.world\n }\n\n /**\n * Set our position {@link Vec3 | vector}\n * @param value - new position {@link Vec3 | vector}\n */\n set position(value: Vec3) {\n this.transforms.position.world = value\n }\n\n /**\n * Get our scale {@link Vec3 | vector}\n */\n get scale(): Vec3 {\n return this.transforms.scale\n }\n\n /**\n * Set our scale {@link Vec3 | vector}\n * @param value - new scale {@link Vec3 | vector}\n */\n set scale(value: Vec3) {\n // force scale to 1 on Z axis\n this.transforms.scale = value\n this.applyScale()\n }\n\n /**\n * Get our transform origin {@link Vec3 | vector}\n */\n get transformOrigin(): Vec3 {\n return this.transforms.origin.model\n }\n\n /**\n * Set our transform origin {@link Vec3 | vector}\n * @param value - new transform origin {@link Vec3 | vector}\n */\n set transformOrigin(value: Vec3) {\n this.transforms.origin.model = value\n }\n\n /**\n * Apply our rotation and tell our {@link modelMatrix | model matrix} to update\n */\n applyRotation() {\n this.quaternion.setFromVec3(this.rotation)\n\n this.shouldUpdateModelMatrix()\n }\n\n /**\n * Tell our {@link modelMatrix | model matrix} to update\n */\n applyPosition() {\n this.shouldUpdateModelMatrix()\n }\n\n /**\n * Tell our {@link modelMatrix | model matrix} to update\n */\n applyScale() {\n this.shouldUpdateModelMatrix()\n }\n\n /**\n * Tell our {@link modelMatrix | model matrix} to update\n */\n applyTransformOrigin() {\n this.shouldUpdateModelMatrix()\n }\n\n /* MATRICES */\n\n /**\n * Set our {@link modelMatrix | model matrix} and {@link worldMatrix | world matrix}\n */\n setMatrices() {\n this.matrices = {\n model: {\n matrix: new Mat4(),\n shouldUpdate: false,\n onUpdate: () => this.updateModelMatrix(),\n },\n world: {\n matrix: new Mat4(),\n shouldUpdate: false,\n onUpdate: () => this.updateWorldMatrix(),\n },\n }\n }\n\n /**\n * Get our {@link Mat4 | model matrix}\n */\n get modelMatrix(): Mat4 {\n return this.matrices.model.matrix\n }\n\n /**\n * Set our {@link Mat4 | model matrix}\n * @param value - new {@link Mat4 | model matrix}\n */\n set modelMatrix(value: Mat4) {\n this.matrices.model.matrix = value\n this.shouldUpdateModelMatrix()\n }\n\n /**\n * Set our {@link modelMatrix | model matrix} shouldUpdate flag to true (tell it to update)\n */\n shouldUpdateModelMatrix() {\n this.matrices.model.shouldUpdate = true\n this.shouldUpdateWorldMatrix()\n }\n\n /**\n * Get our {@link Mat4 | world matrix}\n */\n get worldMatrix(): Mat4 {\n return this.matrices.world.matrix\n }\n\n /**\n * Set our {@link Mat4 | world matrix}\n * @param value - new {@link Mat4 | world matrix}\n */\n set worldMatrix(value: Mat4) {\n this.matrices.world.matrix = value\n this.shouldUpdateWorldMatrix()\n }\n\n /**\n * Set our {@link worldMatrix | world matrix} shouldUpdate flag to true (tell it to update)\n */\n shouldUpdateWorldMatrix() {\n this.matrices.world.shouldUpdate = true\n }\n\n /**\n * Rotate this {@link Object3D} so it looks at the {@link Vec3 | target}\n * @param target - {@link Vec3 | target} to look at\n */\n lookAt(target: Vec3 = new Vec3()) {\n const rotationMatrix = new Mat4().lookAt(target, this.position)\n this.quaternion.setFromRotationMatrix(rotationMatrix)\n this.shouldUpdateModelMatrix()\n }\n\n /**\n * Update our {@link modelMatrix | model matrix}\n */\n updateModelMatrix() {\n // compose our model transformation matrix from custom origin\n this.modelMatrix = this.modelMatrix.composeFromOrigin(\n this.position,\n this.quaternion,\n this.scale,\n this.transformOrigin\n )\n\n // tell our world matrix to update\n this.shouldUpdateWorldMatrix()\n }\n\n /**\n * Update our {@link worldMatrix | model matrix}\n */\n updateWorldMatrix() {\n if (!this.parent) {\n this.worldMatrix.copy(this.modelMatrix)\n } else {\n this.worldMatrix.multiplyMatrices(this.parent.worldMatrix, this.modelMatrix)\n }\n\n // update the children world matrix as well\n this.children.forEach((child) => {\n child.shouldUpdateWorldMatrix()\n })\n }\n\n /**\n * Callback to run if at least one matrix of the stack has been updated\n */\n onAfterMatrixStackUpdate() {\n /* will be used by the classes extending Object3D */\n }\n\n /**\n * Check at each render whether we should update our matrices, and update them if needed\n */\n updateMatrixStack() {\n // if it has a parent and it is an Object3D\n // it means nothing updates it in the render loop, so do it from here\n if (this.parent && this.parent.constructor.name === 'Object3D') {\n this.parent.updateMatrixStack()\n }\n\n // check if at least one matrix should update\n const matrixShouldUpdate = !!Object.keys(this.matrices).find((matrixName) => this.matrices[matrixName].shouldUpdate)\n\n if (matrixShouldUpdate) {\n for (const matrixName in this.matrices) {\n if (this.matrices[matrixName].shouldUpdate) {\n this.matrices[matrixName].onUpdate()\n this.matrices[matrixName].shouldUpdate = false\n }\n }\n\n // callback to run if at least one matrix of the stack has been updated\n this.onAfterMatrixStackUpdate()\n }\n }\n}\n","import { Vec3 } from '../../math/Vec3'\r\nimport { isRenderer, Renderer } from '../renderers/utils'\r\nimport { TextureBinding, TextureBindingParams } from '../bindings/TextureBinding'\r\nimport { BufferBinding } from '../bindings/BufferBinding'\r\nimport { Object3D } from '../objects3D/Object3D'\r\nimport { Mat4 } from '../../math/Mat4'\r\nimport { generateUUID, throwWarning } from '../../utils/utils'\r\nimport { BindGroupBindingElement } from '../../types/BindGroups'\r\nimport { TextureOptions, TextureParams, TextureParent, TextureSize, TextureSource } from '../../types/Textures'\r\nimport { GPUCurtains } from '../../curtains/GPUCurtains'\r\nimport { DOMProjectedMesh } from '../renderers/GPURenderer'\r\nimport { RectSize } from '../DOM/DOMElement'\r\n\r\n/** @const - default {@link Texture} parameters */\r\nconst defaultTextureParams: TextureParams = {\r\n name: 'texture',\r\n generateMips: false,\r\n flipY: false,\r\n format: 'rgba8unorm',\r\n premultipliedAlpha: true,\r\n placeholderColor: [0, 0, 0, 255], // default to black\r\n useExternalTextures: true,\r\n fromTexture: null,\r\n viewDimension: '2d',\r\n cache: true,\r\n}\r\n\r\n/**\r\n * Used to create {@link GPUTexture} or {@link GPUExternalTexture} from different kinds of {@link TextureSource | sources}, like {@link HTMLImageElement}, {@link HTMLVideoElement} or {@link HTMLCanvasElement}.\r\n *\r\n * Handles the various sources loading and uploading, GPU textures creation,{@link BufferBinding | texture model matrix binding} and {@link TextureBinding | GPU texture binding}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // set our main GPUCurtains instance\r\n * const gpuCurtains = new GPUCurtains({\r\n * container: '#canvas' // selector of our WebGPU canvas container\r\n * })\r\n *\r\n * // set the GPU device\r\n * // note this is asynchronous\r\n * await gpuCurtains.setDevice()\r\n *\r\n * // create a render texture\r\n * const imageTexture = new Texture(gpuCurtains, {\r\n * label: 'My image texture',\r\n * name: 'imageTexture',\r\n * })\r\n *\r\n * // load an image\r\n * await imageTexture.loadImage(document.querySelector('img'))\r\n * ```\r\n */\r\nexport class Texture extends Object3D {\r\n /** The type of the {@link Texture} */\r\n type: string\r\n /** The universal unique id of this {@link Texture} */\r\n readonly uuid: string\r\n /** {@link Renderer} used by this {@link Texture} */\r\n renderer: Renderer\r\n\r\n /** The {@link GPUTexture} used if any */\r\n texture: null | GPUTexture\r\n /** The {@link GPUExternalTexture} used if any */\r\n externalTexture: null | GPUExternalTexture\r\n\r\n /** The {@link Texture} {@link TextureSource | source} to use */\r\n source: TextureSource\r\n /** The {@link GPUTexture}, matching the {@link TextureSource | source} {@link RectSize | size} (with 1 for depth) */\r\n size: TextureSize\r\n\r\n /** Options used to create this {@link Texture} */\r\n options: TextureOptions\r\n\r\n /** A {@link BufferBinding | buffer binding} that will hold the texture model matrix */\r\n textureMatrix: BufferBinding\r\n /** The bindings used by this {@link Texture}, i.e. its {@link textureMatrix} and its {@link TextureBinding | GPU texture binding} */\r\n bindings: BindGroupBindingElement[]\r\n\r\n /** {@link Texture} parentMesh if any */\r\n private _parentMesh: TextureParent\r\n\r\n /** Whether the source has been loaded */\r\n private _sourceLoaded: boolean\r\n /** Whether the source has been uploaded to the GPU, handled by the {@link core/renderers/GPUDeviceManager.GPUDeviceManager#texturesQueue | GPUDeviceManager texturesQueue array} */\r\n private _sourceUploaded: boolean\r\n /** Whether the texture should be uploaded to the GPU */\r\n shouldUpdate: boolean\r\n\r\n /** {@link HTMLVideoElement.requestVideoFrameCallback | requestVideoFrameCallback} returned id if used */\r\n videoFrameCallbackId: null | number\r\n\r\n /** Private {@link Vec3 | vector} used for {@link#modelMatrix} calculations, based on {@link parentMesh} {@link RectSize | size} */\r\n #parentRatio: Vec3 = new Vec3(1)\r\n /** Private {@link Vec3 | vector} used for {@link modelMatrix} calculations, based on {@link size | source size} */\r\n #sourceRatio: Vec3 = new Vec3(1)\r\n /** Private {@link Vec3 | vector} used for {@link modelMatrix} calculations, based on #parentRatio and #sourceRatio */\r\n #coverScale: Vec3 = new Vec3(1)\r\n /** Private rotation {@link Mat4 | matrix} based on texture {@link quaternion} */\r\n #rotationMatrix: Mat4 = new Mat4()\r\n\r\n // callbacks / events\r\n /** function assigned to the {@link onSourceLoaded} callback */\r\n _onSourceLoadedCallback = () => {\r\n /* allow empty callback */\r\n }\r\n /** function assigned to the {@link onSourceUploaded} callback */\r\n _onSourceUploadedCallback = () => {\r\n /* allow empty callback */\r\n }\r\n\r\n /**\r\n * Texture constructor\r\n * @param renderer - {@link Renderer} object or {@link GPUCurtains} class object used to create this {@link Texture}\r\n * @param parameters - {@link TextureParams | parameters} used to create this {@link Texture}\r\n */\r\n constructor(renderer: Renderer | GPUCurtains, parameters = defaultTextureParams) {\r\n super()\r\n\r\n this.type = 'Texture'\r\n\r\n // we could pass our curtains object OR our curtains renderer object\r\n renderer = (renderer && (renderer as GPUCurtains).renderer) || (renderer as Renderer)\r\n\r\n isRenderer(renderer, parameters.label ? parameters.label + ' ' + this.type : this.type)\r\n\r\n this.renderer = renderer\r\n\r\n this.uuid = generateUUID()\r\n\r\n const defaultOptions = {\r\n ...defaultTextureParams,\r\n source: parameters.fromTexture ? parameters.fromTexture.options.source : null,\r\n sourceType: parameters.fromTexture ? parameters.fromTexture.options.sourceType : null,\r\n }\r\n\r\n this.options = { ...defaultOptions, ...parameters }\r\n // force merge of texture object\r\n //this.options.texture = { ...defaultOptions.texture, ...parameters.texture }\r\n\r\n this.options.label = this.options.label ?? this.options.name\r\n\r\n this.texture = null\r\n this.externalTexture = null\r\n this.source = null\r\n\r\n // sizes\r\n this.size = {\r\n width: 1,\r\n height: 1,\r\n depth: 1,\r\n }\r\n\r\n // we will always declare a texture matrix\r\n this.textureMatrix = new BufferBinding({\r\n label: this.options.label + ': model matrix',\r\n name: this.options.name + 'Matrix',\r\n useStruct: false,\r\n struct: {\r\n matrix: {\r\n name: this.options.name + 'Matrix',\r\n type: 'mat4x4f',\r\n value: this.modelMatrix,\r\n },\r\n },\r\n })\r\n\r\n this.setBindings()\r\n\r\n this._parentMesh = null\r\n\r\n this.sourceLoaded = false\r\n this.sourceUploaded = false\r\n this.shouldUpdate = false\r\n\r\n this.renderer.addTexture(this)\r\n this.createTexture()\r\n }\r\n\r\n /**\r\n * Set our {@link bindings}\r\n */\r\n setBindings() {\r\n this.bindings = [\r\n new TextureBinding({\r\n label: this.options.label + ': texture',\r\n name: this.options.name,\r\n texture: this.options.sourceType === 'externalVideo' ? this.externalTexture : this.texture,\r\n bindingType: this.options.sourceType === 'externalVideo' ? 'externalTexture' : 'texture',\r\n viewDimension: this.options.viewDimension,\r\n } as TextureBindingParams),\r\n this.textureMatrix,\r\n ]\r\n }\r\n\r\n /**\r\n * Get our {@link TextureBinding | GPU texture binding}\r\n * @readonly\r\n */\r\n get textureBinding(): TextureBinding {\r\n return this.bindings[0] as TextureBinding\r\n }\r\n\r\n /**\r\n * Get our texture {@link parentMesh}\r\n */\r\n get parentMesh(): TextureParent {\r\n return this._parentMesh\r\n }\r\n\r\n /**\r\n * Set our texture {@link parentMesh}\r\n * @param value - texture {@link parentMesh} to set (i.e. any kind of {@link core/renderers/GPURenderer.RenderedMesh | Mesh}\r\n */\r\n set parentMesh(value: TextureParent) {\r\n this._parentMesh = value\r\n this.resize()\r\n }\r\n\r\n /**\r\n * Get whether our {@link source} has been loaded\r\n */\r\n get sourceLoaded(): boolean {\r\n return this._sourceLoaded\r\n }\r\n\r\n /**\r\n * Set whether our {@link source} has been loaded\r\n * @param value - boolean flag indicating if the {@link source} has been loaded\r\n */\r\n set sourceLoaded(value: boolean) {\r\n if (value && !this.sourceLoaded) {\r\n this._onSourceLoadedCallback && this._onSourceLoadedCallback()\r\n }\r\n this._sourceLoaded = value\r\n }\r\n\r\n /**\r\n * Get whether our {@link source} has been uploaded\r\n */\r\n get sourceUploaded(): boolean {\r\n return this._sourceUploaded\r\n }\r\n\r\n /**\r\n * Set whether our {@link source} has been uploaded\r\n * @param value - boolean flag indicating if the {@link source} has been uploaded\r\n */\r\n set sourceUploaded(value: boolean) {\r\n if (value && !this.sourceUploaded) {\r\n this._onSourceUploadedCallback && this._onSourceUploadedCallback()\r\n }\r\n this._sourceUploaded = value\r\n }\r\n\r\n /**\r\n * Set our texture {@link transforms} object\r\n */\r\n setTransforms() {\r\n super.setTransforms()\r\n\r\n this.transforms.quaternion.setAxisOrder('ZXY')\r\n\r\n // reset our model transform origin to reflect CSS transform origins\r\n this.transforms.origin.model.set(0.5, 0.5, 0)\r\n }\r\n\r\n /* TEXTURE MATRIX */\r\n\r\n /**\r\n * Update the {@link modelMatrix}\r\n */\r\n updateModelMatrix() {\r\n if (!this.parentMesh) return\r\n\r\n const parentScale = (this.parentMesh as DOMProjectedMesh).scale\r\n ? (this.parentMesh as DOMProjectedMesh).scale\r\n : new Vec3(1, 1, 1)\r\n\r\n const parentWidth = (this.parentMesh as DOMProjectedMesh).boundingRect\r\n ? (this.parentMesh as DOMProjectedMesh).boundingRect.width * parentScale.x\r\n : this.size.width\r\n const parentHeight = (this.parentMesh as DOMProjectedMesh).boundingRect\r\n ? (this.parentMesh as DOMProjectedMesh).boundingRect.height * parentScale.y\r\n : this.size.height\r\n\r\n const parentRatio = parentWidth / parentHeight\r\n const sourceRatio = this.size.width / this.size.height\r\n\r\n // handle the texture rotation\r\n // huge props to [@grgrdvrt](https://github.com/grgrdvrt) for this solution!\r\n if (parentWidth > parentHeight) {\r\n this.#parentRatio.set(parentRatio, 1, 1)\r\n this.#sourceRatio.set(1 / sourceRatio, 1, 1)\r\n } else {\r\n this.#parentRatio.set(1, 1 / parentRatio, 1)\r\n this.#sourceRatio.set(1, sourceRatio, 1)\r\n }\r\n\r\n // cover ratio is a bit tricky!\r\n const coverRatio =\r\n parentRatio > sourceRatio !== parentWidth > parentHeight\r\n ? 1\r\n : parentWidth > parentHeight\r\n ? this.#parentRatio.x * this.#sourceRatio.x\r\n : this.#sourceRatio.y * this.#parentRatio.y\r\n\r\n this.#coverScale.set(1 / (coverRatio * this.scale.x), 1 / (coverRatio * this.scale.y), 1)\r\n\r\n this.#rotationMatrix.rotateFromQuaternion(this.quaternion)\r\n\r\n // here we could create a matrix for each translations / scales and do:\r\n // this.modelMatrix\r\n // .identity()\r\n // .premultiply(negativeOriginMatrix)\r\n // .premultiply(coverScaleMatrix)\r\n // .premultiply(parentRatioMatrix)\r\n // .premultiply(rotationMatrix)\r\n // .premultiply(textureRatioMatrix)\r\n // .premultiply(originMatrix)\r\n // .translate(this.position)\r\n\r\n // but this is faster!\r\n this.modelMatrix\r\n .identity()\r\n .premultiplyTranslate(this.transformOrigin.clone().multiplyScalar(-1))\r\n .premultiplyScale(this.#coverScale)\r\n .premultiplyScale(this.#parentRatio)\r\n .premultiply(this.#rotationMatrix)\r\n .premultiplyScale(this.#sourceRatio)\r\n .premultiplyTranslate(this.transformOrigin)\r\n .translate(this.position)\r\n }\r\n\r\n /**\r\n * If our {@link modelMatrix} has been updated, tell the {@link textureMatrix | texture matrix binding} to update as well\r\n */\r\n onAfterMatrixStackUpdate() {\r\n this.textureMatrix.shouldUpdateBinding(this.options.name + 'Matrix')\r\n }\r\n\r\n /**\r\n * Resize our {@link Texture}\r\n */\r\n resize() {\r\n // this should only happen with canvas textures\r\n if (\r\n this.source &&\r\n this.source instanceof HTMLCanvasElement &&\r\n (this.source.width !== this.size.width || this.source.height !== this.size.height)\r\n ) {\r\n // since the source size has changed, we have to recreate a new texture\r\n this.setSourceSize()\r\n this.createTexture()\r\n }\r\n\r\n // tell our model matrix to update\r\n this.shouldUpdateModelMatrix()\r\n }\r\n\r\n /**\r\n * Get the number of mip levels create based on {@link size}\r\n * @param sizes - Array containing our texture width, height and depth\r\n * @returns - number of mip levels\r\n */\r\n getNumMipLevels(...sizes: number[]): number {\r\n const maxSize = Math.max(...sizes)\r\n return (1 + Math.log2(maxSize)) | 0\r\n }\r\n\r\n /**\r\n * Tell the {@link Renderer} to upload or texture\r\n */\r\n uploadTexture() {\r\n this.renderer.uploadTexture(this)\r\n this.shouldUpdate = false\r\n }\r\n\r\n /**\r\n * Import a {@link GPUExternalTexture} from the {@link Renderer}, update the {@link textureBinding} and its {@link core/bindGroups/TextureBindGroup.TextureBindGroup | bind group}\r\n */\r\n uploadVideoTexture() {\r\n this.externalTexture = this.renderer.importExternalTexture(this.source as HTMLVideoElement)\r\n this.textureBinding.resource = this.externalTexture\r\n this.textureBinding.setBindingType('externalTexture')\r\n this.shouldUpdate = false\r\n this.sourceUploaded = true\r\n }\r\n\r\n /**\r\n * Copy a {@link Texture}\r\n * @param texture - {@link Texture} to copy\r\n */\r\n copy(texture: Texture) {\r\n if (this.options.sourceType === 'externalVideo' && texture.options.sourceType !== 'externalVideo') {\r\n throwWarning(`${this.options.label}: cannot copy a GPUTexture to a GPUExternalTexture`)\r\n return\r\n } else if (this.options.sourceType !== 'externalVideo' && texture.options.sourceType === 'externalVideo') {\r\n throwWarning(`${this.options.label}: cannot copy a GPUExternalTexture to a GPUTexture`)\r\n return\r\n }\r\n\r\n this.options.fromTexture = texture\r\n\r\n // now copy all desired texture options except source\r\n // const { source, ...optionsToCopy } = texture.options\r\n // this.options = { ...this.options, ...optionsToCopy }\r\n\r\n this.options.sourceType = texture.options.sourceType\r\n\r\n // TODO better way to do that?\r\n this.options.generateMips = texture.options.generateMips\r\n this.options.flipY = texture.options.flipY\r\n this.options.format = texture.options.format\r\n this.options.premultipliedAlpha = texture.options.premultipliedAlpha\r\n this.options.placeholderColor = texture.options.placeholderColor\r\n this.options.useExternalTextures = texture.options.useExternalTextures\r\n\r\n this.sourceLoaded = texture.sourceLoaded\r\n this.sourceUploaded = texture.sourceUploaded\r\n\r\n // TODO external texture?\r\n if (texture.texture) {\r\n if (texture.sourceLoaded) {\r\n this.size = texture.size\r\n this.source = texture.source\r\n\r\n this.resize()\r\n }\r\n\r\n if (texture.sourceUploaded) {\r\n // texture to copy is ready, update our texture and binding\r\n this.texture = texture.texture\r\n this.textureBinding.resource = this.texture\r\n } else {\r\n this.createTexture()\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Set the {@link texture | GPU texture}\r\n */\r\n createTexture() {\r\n const options = {\r\n label: this.options.label,\r\n format: this.options.format,\r\n size: [this.size.width, this.size.height, this.size.depth], // [1, 1] if no source\r\n dimensions: this.options.viewDimension === '1d' ? '1d' : this.options.viewDimension === '3d' ? '3d' : '2d',\r\n //sampleCount: this.source ? this.renderer.sampleCount : 1,\r\n usage: !!this.source\r\n ? GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT\r\n : GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,\r\n } as GPUTextureDescriptor\r\n\r\n if (this.options.sourceType !== 'externalVideo') {\r\n options.mipLevelCount = this.options.generateMips ? this.getNumMipLevels(this.size.width, this.size.height) : 1\r\n\r\n this.texture?.destroy()\r\n\r\n this.texture = this.renderer.createTexture(options)\r\n\r\n // update texture binding\r\n this.textureBinding.resource = this.texture\r\n }\r\n\r\n this.shouldUpdate = true\r\n }\r\n\r\n /* SOURCES */\r\n\r\n /**\r\n * Set the {@link size} based on the {@link source}\r\n */\r\n setSourceSize() {\r\n this.size = {\r\n width:\r\n (this.source as HTMLImageElement).naturalWidth ||\r\n (this.source as HTMLCanvasElement).width ||\r\n (this.source as HTMLVideoElement).videoWidth,\r\n height:\r\n (this.source as HTMLImageElement).naturalHeight ||\r\n (this.source as HTMLCanvasElement).height ||\r\n (this.source as HTMLVideoElement).videoHeight,\r\n depth: 1,\r\n }\r\n }\r\n\r\n /**\r\n * Load an {@link HTMLImageElement} from a URL and create an {@link ImageBitmap} to use as a {@link source}\r\n * @async\r\n * @param url - URL of the image to load\r\n * @returns - the newly created {@link ImageBitmap}\r\n */\r\n async loadImageBitmap(url: string): Promise {\r\n const res = await fetch(url)\r\n const blob = await res.blob()\r\n return await createImageBitmap(blob, { colorSpaceConversion: 'none' })\r\n }\r\n\r\n /**\r\n * Load and create an {@link ImageBitmap} from a URL or {@link HTMLImageElement}, use it as a {@link source} and create the {@link GPUTexture}\r\n * @async\r\n * @param source - the image URL or {@link HTMLImageElement} to load\r\n * @returns - the newly created {@link ImageBitmap}\r\n */\r\n async loadImage(source: string | HTMLImageElement): Promise {\r\n const url = typeof source === 'string' ? source : source.getAttribute('src')\r\n\r\n this.options.source = url\r\n this.options.sourceType = 'image'\r\n\r\n const cachedTexture = this.renderer.textures.find((t) => t.options.source === url)\r\n if (cachedTexture && cachedTexture.texture && cachedTexture.sourceUploaded) {\r\n this.copy(cachedTexture)\r\n return\r\n }\r\n\r\n this.sourceLoaded = false\r\n this.sourceUploaded = false\r\n\r\n this.source = await this.loadImageBitmap(this.options.source)\r\n\r\n this.setSourceSize()\r\n this.resize()\r\n\r\n this.sourceLoaded = true\r\n this.createTexture()\r\n }\r\n\r\n // weirldy enough, we don't have to do anything in that callback\r\n // because the