super-three 0.181.0 → 0.185.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (693) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +3 -4
  3. package/build/three.cjs +21332 -19201
  4. package/build/three.core.js +20908 -19853
  5. package/build/three.core.min.js +2 -2
  6. package/build/three.module.js +1947 -862
  7. package/build/three.module.min.js +2 -2
  8. package/build/three.tsl.js +37 -16
  9. package/build/three.tsl.min.js +2 -2
  10. package/build/three.webgpu.js +33628 -25197
  11. package/build/three.webgpu.min.js +2 -2
  12. package/build/three.webgpu.nodes.js +33394 -25000
  13. package/build/three.webgpu.nodes.min.js +2 -2
  14. package/examples/jsm/Addons.js +14 -3
  15. package/examples/jsm/animation/CCDIKSolver.js +7 -3
  16. package/examples/jsm/controls/ArcballControls.js +13 -6
  17. package/examples/jsm/controls/DragControls.js +2 -2
  18. package/examples/jsm/controls/FirstPersonControls.js +127 -86
  19. package/examples/jsm/controls/FlyControls.js +4 -0
  20. package/examples/jsm/controls/MapControls.js +55 -1
  21. package/examples/jsm/controls/OrbitControls.js +111 -8
  22. package/examples/jsm/controls/TrackballControls.js +8 -8
  23. package/examples/jsm/controls/TransformControls.js +102 -17
  24. package/examples/jsm/csm/CSM.js +2 -1
  25. package/examples/jsm/csm/CSMFrustum.js +31 -6
  26. package/examples/jsm/csm/CSMShadowNode.js +10 -3
  27. package/examples/jsm/effects/AnaglyphEffect.js +102 -7
  28. package/examples/jsm/effects/AsciiEffect.js +14 -1
  29. package/examples/jsm/environments/ColorEnvironment.js +59 -0
  30. package/examples/jsm/environments/RoomEnvironment.js +3 -0
  31. package/examples/jsm/exporters/DRACOExporter.js +27 -6
  32. package/examples/jsm/exporters/EXRExporter.js +1 -1
  33. package/examples/jsm/exporters/GLTFExporter.js +266 -21
  34. package/examples/jsm/exporters/PLYExporter.js +286 -73
  35. package/examples/jsm/exporters/USDZExporter.js +353 -99
  36. package/examples/jsm/generators/CityGenerator.js +346 -0
  37. package/examples/jsm/generators/ForestGenerator.js +347 -0
  38. package/examples/jsm/generators/TerrainGenerator.js +504 -0
  39. package/examples/jsm/generators/TreeGenerator.js +377 -0
  40. package/examples/jsm/generators/city/SidewalkGenerator.js +253 -0
  41. package/examples/jsm/generators/city/SkyscraperGenerator.js +1357 -0
  42. package/examples/jsm/geometries/DecalGeometry.js +1 -1
  43. package/examples/jsm/geometries/LoftGeometry.js +355 -0
  44. package/examples/jsm/geometries/TextGeometry.js +18 -0
  45. package/examples/jsm/helpers/AnimationPathHelper.js +302 -0
  46. package/examples/jsm/helpers/LightProbeGridHelper.js +221 -0
  47. package/examples/jsm/helpers/LightProbeHelper.js +5 -4
  48. package/examples/jsm/helpers/LightProbeHelperGPU.js +1 -1
  49. package/examples/jsm/helpers/TextureHelperGPU.js +1 -1
  50. package/examples/jsm/helpers/ViewHelper.js +83 -14
  51. package/examples/jsm/inspector/Extension.js +13 -0
  52. package/examples/jsm/inspector/Inspector.js +244 -91
  53. package/examples/jsm/inspector/RendererInspector.js +165 -39
  54. package/examples/jsm/inspector/extensions/tsl-graph/TSLGraphEditor.js +916 -0
  55. package/examples/jsm/inspector/extensions/tsl-graph/TSLGraphLoader.js +281 -0
  56. package/examples/jsm/inspector/tabs/Console.js +241 -25
  57. package/examples/jsm/inspector/tabs/Memory.js +136 -0
  58. package/examples/jsm/inspector/tabs/Parameters.js +115 -7
  59. package/examples/jsm/inspector/tabs/Performance.js +24 -9
  60. package/examples/jsm/inspector/tabs/Settings.js +306 -0
  61. package/examples/jsm/inspector/tabs/Timeline.js +1696 -0
  62. package/examples/jsm/inspector/tabs/Viewer.js +723 -9
  63. package/examples/jsm/inspector/ui/Graph.js +162 -25
  64. package/examples/jsm/inspector/ui/Item.js +92 -13
  65. package/examples/jsm/inspector/ui/List.js +2 -2
  66. package/examples/jsm/inspector/ui/Profiler.js +1991 -44
  67. package/examples/jsm/inspector/ui/Style.js +1943 -543
  68. package/examples/jsm/inspector/ui/Tab.js +226 -5
  69. package/examples/jsm/inspector/ui/Values.js +126 -8
  70. package/examples/jsm/inspector/ui/utils.js +143 -10
  71. package/examples/jsm/interaction/InteractionManager.js +226 -0
  72. package/examples/jsm/libs/basis/README.md +0 -1
  73. package/examples/jsm/libs/demuxer_mp4.js +3 -3
  74. package/examples/jsm/libs/draco/README.md +0 -1
  75. package/examples/jsm/libs/meshopt_clusterizer.module.js +421 -0
  76. package/examples/jsm/libs/meshopt_decoder.module.js +9 -8
  77. package/examples/jsm/libs/meshopt_simplifier.module.js +627 -0
  78. package/examples/jsm/libs/mikktspace.module.js +34 -9
  79. package/examples/jsm/lighting/ClusteredLighting.js +55 -0
  80. package/examples/jsm/lighting/DynamicLighting.js +82 -0
  81. package/examples/jsm/lighting/LightProbeGrid.js +681 -0
  82. package/examples/jsm/lines/LineMaterial.js +45 -16
  83. package/examples/jsm/lines/LineSegments2.js +8 -0
  84. package/examples/jsm/lines/webgpu/LineSegments2.js +8 -0
  85. package/examples/jsm/loaders/3DMLoader.js +6 -5
  86. package/examples/jsm/loaders/3MFLoader.js +2 -2
  87. package/examples/jsm/loaders/AMFLoader.js +2 -2
  88. package/examples/jsm/loaders/ColladaLoader.js +24 -4026
  89. package/examples/jsm/loaders/DRACOLoader.js +51 -18
  90. package/examples/jsm/loaders/EXRLoader.js +701 -90
  91. package/examples/jsm/loaders/FBXLoader.js +235 -37
  92. package/examples/jsm/loaders/GCodeLoader.js +34 -8
  93. package/examples/jsm/loaders/GLTFLoader.js +146 -178
  94. package/examples/jsm/loaders/HDRLoader.js +7 -30
  95. package/examples/jsm/loaders/KMZLoader.js +5 -5
  96. package/examples/jsm/loaders/KTX2Loader.js +58 -17
  97. package/examples/jsm/loaders/LDrawLoader.js +49 -58
  98. package/examples/jsm/loaders/LUT3dlLoader.js +2 -2
  99. package/examples/jsm/loaders/LUTCubeLoader.js +2 -2
  100. package/examples/jsm/loaders/LWOLoader.js +11 -39
  101. package/examples/jsm/loaders/LottieLoader.js +1 -1
  102. package/examples/jsm/loaders/MaterialXLoader.js +31 -9
  103. package/examples/jsm/loaders/NRRDLoader.js +5 -5
  104. package/examples/jsm/loaders/PCDLoader.js +11 -9
  105. package/examples/jsm/loaders/PLYLoader.js +218 -55
  106. package/examples/jsm/loaders/SVGLoader.js +549 -497
  107. package/examples/jsm/loaders/TDSLoader.js +0 -2
  108. package/examples/jsm/loaders/TGALoader.js +0 -2
  109. package/examples/jsm/loaders/TTFLoader.js +1 -1
  110. package/examples/jsm/loaders/USDLoader.js +127 -43
  111. package/examples/jsm/loaders/UltraHDRLoader.js +285 -160
  112. package/examples/jsm/loaders/VOXLoader.js +660 -117
  113. package/examples/jsm/loaders/VRMLLoader.js +80 -3
  114. package/examples/jsm/loaders/VTKLoader.js +42 -25
  115. package/examples/jsm/loaders/collada/ColladaComposer.js +3044 -0
  116. package/examples/jsm/loaders/collada/ColladaParser.js +1977 -0
  117. package/examples/jsm/loaders/usd/USDAParser.js +504 -344
  118. package/examples/jsm/loaders/usd/USDCParser.js +1867 -6
  119. package/examples/jsm/loaders/usd/USDComposer.js +4627 -0
  120. package/examples/jsm/materials/LDrawConditionalLineNodeMaterial.js +2 -2
  121. package/examples/jsm/materials/WoodNodeMaterial.js +11 -11
  122. package/examples/jsm/math/Octree.js +131 -1
  123. package/examples/jsm/misc/GPUComputationRenderer.js +2 -0
  124. package/examples/jsm/misc/RollerCoaster.js +42 -4
  125. package/examples/jsm/misc/TileCreasedNormalsPlugin.js +270 -0
  126. package/examples/jsm/misc/Volume.js +2 -3
  127. package/examples/jsm/misc/VolumeSlice.js +0 -1
  128. package/examples/jsm/modifiers/TessellateModifier.js +1 -1
  129. package/examples/jsm/objects/GroundedSkybox.js +1 -1
  130. package/examples/jsm/objects/LensflareMesh.js +1 -1
  131. package/examples/jsm/objects/Reflector.js +72 -25
  132. package/examples/jsm/objects/Sky.js +90 -6
  133. package/examples/jsm/objects/SkyMesh.js +150 -16
  134. package/examples/jsm/objects/Water.js +4 -3
  135. package/examples/jsm/objects/Water2.js +5 -3
  136. package/examples/jsm/objects/Water2Mesh.js +1 -1
  137. package/examples/jsm/objects/WaterMesh.js +5 -7
  138. package/examples/jsm/physics/AmmoPhysics.js +27 -15
  139. package/examples/jsm/physics/JoltPhysics.js +10 -6
  140. package/examples/jsm/physics/RapierPhysics.js +36 -7
  141. package/examples/jsm/postprocessing/EffectComposer.js +7 -5
  142. package/examples/jsm/postprocessing/OutputPass.js +9 -0
  143. package/examples/jsm/postprocessing/RenderPass.js +10 -0
  144. package/examples/jsm/postprocessing/RenderTransitionPass.js +1 -1
  145. package/examples/jsm/postprocessing/UnrealBloomPass.js +48 -18
  146. package/examples/jsm/renderers/CSS3DRenderer.js +1 -1
  147. package/examples/jsm/renderers/Projector.js +246 -28
  148. package/examples/jsm/renderers/SVGRenderer.js +174 -60
  149. package/examples/jsm/shaders/GTAOShader.js +19 -6
  150. package/examples/jsm/shaders/HalftoneShader.js +12 -1
  151. package/examples/jsm/shaders/PoissonDenoiseShader.js +6 -2
  152. package/examples/jsm/shaders/SAOShader.js +17 -4
  153. package/examples/jsm/shaders/SSAOShader.js +11 -1
  154. package/examples/jsm/shaders/SSRShader.js +6 -5
  155. package/examples/jsm/shaders/UnpackDepthRGBAShader.js +2 -4
  156. package/examples/jsm/shaders/VignetteShader.js +1 -1
  157. package/examples/jsm/shaders/VolumeShader.js +31 -44
  158. package/examples/jsm/transpiler/AST.js +44 -0
  159. package/examples/jsm/transpiler/GLSLDecoder.js +65 -8
  160. package/examples/jsm/transpiler/Linker.js +1 -1
  161. package/examples/jsm/transpiler/ShaderToyDecoder.js +2 -0
  162. package/examples/jsm/transpiler/TSLEncoder.js +46 -3
  163. package/examples/jsm/transpiler/TranspilerUtils.js +3 -3
  164. package/examples/jsm/transpiler/WGSLEncoder.js +27 -0
  165. package/examples/jsm/tsl/WebGLNodesHandler.js +605 -0
  166. package/examples/jsm/tsl/display/AfterImageNode.js +11 -1
  167. package/examples/jsm/tsl/display/AnaglyphPassNode.js +458 -16
  168. package/examples/jsm/tsl/display/BilateralBlurNode.js +374 -0
  169. package/examples/jsm/tsl/display/BloomNode.js +75 -25
  170. package/examples/jsm/tsl/display/CRT.js +150 -0
  171. package/examples/jsm/tsl/display/ChromaticAberrationNode.js +3 -36
  172. package/examples/jsm/tsl/display/DenoiseNode.js +1 -1
  173. package/examples/jsm/tsl/display/DepthOfFieldNode.js +3 -3
  174. package/examples/jsm/tsl/display/DotScreenNode.js +1 -1
  175. package/examples/jsm/tsl/display/FSR1Node.js +477 -0
  176. package/examples/jsm/tsl/display/FXAANode.js +13 -14
  177. package/examples/jsm/tsl/display/GTAONode.js +40 -17
  178. package/examples/jsm/tsl/display/GaussianBlurNode.js +21 -2
  179. package/examples/jsm/tsl/display/GodraysNode.js +615 -0
  180. package/examples/jsm/tsl/display/ImportanceSampledEnvironment.js +560 -0
  181. package/examples/jsm/tsl/display/LensflareNode.js +1 -1
  182. package/examples/jsm/tsl/display/Lut3DNode.js +1 -1
  183. package/examples/jsm/tsl/display/OutlineNode.js +69 -19
  184. package/examples/jsm/tsl/display/ParallaxBarrierPassNode.js +2 -2
  185. package/examples/jsm/tsl/display/PixelationPassNode.js +9 -8
  186. package/examples/jsm/tsl/display/RGBShiftNode.js +2 -2
  187. package/examples/jsm/tsl/display/RecurrentDenoiseNode.js +912 -0
  188. package/examples/jsm/tsl/display/RetroPassNode.js +263 -0
  189. package/examples/jsm/tsl/display/SMAANode.js +2 -2
  190. package/examples/jsm/tsl/display/SSAAPassNode.js +15 -27
  191. package/examples/jsm/tsl/display/SSGINode.js +96 -62
  192. package/examples/jsm/tsl/display/SSRNode.js +831 -134
  193. package/examples/jsm/tsl/display/SSSNode.js +8 -6
  194. package/examples/jsm/tsl/display/Shape.js +29 -0
  195. package/examples/jsm/tsl/display/SharpenNode.js +283 -0
  196. package/examples/jsm/tsl/display/SobelOperatorNode.js +2 -2
  197. package/examples/jsm/tsl/display/StereoCompositePassNode.js +8 -1
  198. package/examples/jsm/tsl/display/StereoPassNode.js +1 -2
  199. package/examples/jsm/tsl/display/TAAUNode.js +835 -0
  200. package/examples/jsm/tsl/display/TRAANode.js +315 -126
  201. package/examples/jsm/tsl/display/TemporalReprojectNode.js +1023 -0
  202. package/examples/jsm/tsl/display/TransitionNode.js +1 -1
  203. package/examples/jsm/tsl/display/depthAwareBlend.js +80 -0
  204. package/examples/jsm/tsl/display/radialBlur.js +68 -0
  205. package/examples/jsm/tsl/lighting/ClusteredLightsNode.js +622 -0
  206. package/examples/jsm/tsl/lighting/DynamicLightsNode.js +300 -0
  207. package/examples/jsm/tsl/lighting/data/AmbientLightDataNode.js +61 -0
  208. package/examples/jsm/tsl/lighting/data/DirectionalLightDataNode.js +111 -0
  209. package/examples/jsm/tsl/lighting/data/HemisphereLightDataNode.js +99 -0
  210. package/examples/jsm/tsl/lighting/data/PointLightDataNode.js +134 -0
  211. package/examples/jsm/tsl/lighting/data/SpotLightDataNode.js +161 -0
  212. package/examples/jsm/tsl/math/Bayer.js +53 -3
  213. package/examples/jsm/tsl/math/curlNoise.js +107 -0
  214. package/examples/jsm/tsl/shadows/TileShadowNode.js +1 -1
  215. package/examples/jsm/tsl/shadows/TileShadowNodeHelper.js +3 -3
  216. package/examples/jsm/tsl/utils/GroundedSkybox.js +62 -0
  217. package/examples/jsm/tsl/utils/RNoise.js +51 -0
  218. package/examples/jsm/tsl/utils/SpecularHelpers.js +325 -0
  219. package/examples/jsm/utils/BufferGeometryUtils.js +128 -62
  220. package/examples/jsm/utils/ColorUtils.js +76 -0
  221. package/examples/jsm/utils/GeometryCompressionUtils.js +1 -1
  222. package/examples/jsm/utils/LDrawUtils.js +1 -1
  223. package/examples/jsm/utils/SceneOptimizer.js +1 -1
  224. package/examples/jsm/utils/ShadowMapViewer.js +24 -10
  225. package/examples/jsm/utils/ShadowMapViewerGPU.js +1 -1
  226. package/examples/jsm/utils/SkeletonUtils.js +14 -8
  227. package/examples/jsm/utils/WebGPUTextureUtils.js +1 -1
  228. package/examples/jsm/webxr/ARButton.js +1 -1
  229. package/examples/jsm/webxr/WebGLXRFallback.js +89 -0
  230. package/examples/jsm/webxr/XRControllerModelFactory.js +2 -2
  231. package/examples/jsm/webxr/XRHandMeshModel.js +36 -10
  232. package/examples/jsm/webxr/XRHandModelFactory.js +2 -1
  233. package/package.json +28 -34
  234. package/src/Three.Core.js +3 -1
  235. package/src/Three.TSL.js +35 -14
  236. package/src/Three.WebGPU.Nodes.js +5 -0
  237. package/src/Three.WebGPU.js +13 -0
  238. package/src/Three.js +1 -0
  239. package/src/animation/AnimationAction.js +18 -4
  240. package/src/animation/AnimationClip.js +0 -139
  241. package/src/animation/AnimationMixer.js +6 -0
  242. package/src/animation/AnimationUtils.js +1 -12
  243. package/src/animation/KeyframeTrack.js +47 -8
  244. package/src/animation/PropertyBinding.js +2 -2
  245. package/src/animation/PropertyMixer.js +4 -4
  246. package/src/animation/tracks/BooleanKeyframeTrack.js +1 -1
  247. package/src/animation/tracks/ColorKeyframeTrack.js +1 -1
  248. package/src/animation/tracks/NumberKeyframeTrack.js +1 -1
  249. package/src/animation/tracks/QuaternionKeyframeTrack.js +1 -1
  250. package/src/animation/tracks/StringKeyframeTrack.js +1 -1
  251. package/src/animation/tracks/VectorKeyframeTrack.js +1 -1
  252. package/src/audio/Audio.js +1 -1
  253. package/src/audio/AudioContext.js +2 -2
  254. package/src/audio/AudioListener.js +5 -3
  255. package/src/cameras/Camera.js +34 -4
  256. package/src/cameras/CubeCamera.js +20 -0
  257. package/src/cameras/StereoCamera.js +5 -2
  258. package/src/constants.js +90 -5
  259. package/src/core/BufferAttribute.js +13 -1
  260. package/src/core/BufferGeometry.js +43 -9
  261. package/src/core/Clock.js +7 -0
  262. package/src/core/Object3D.js +69 -11
  263. package/src/core/Raycaster.js +3 -3
  264. package/src/core/RenderTarget.js +19 -6
  265. package/src/extras/PMREMGenerator.js +13 -22
  266. package/src/extras/TextureUtils.js +6 -2
  267. package/src/extras/core/ShapePath.js +149 -160
  268. package/src/extras/curves/CatmullRomCurve3.js +3 -2
  269. package/src/geometries/ExtrudeGeometry.js +2 -2
  270. package/src/geometries/PolyhedronGeometry.js +1 -1
  271. package/src/geometries/SphereGeometry.js +8 -3
  272. package/src/geometries/TorusGeometry.js +8 -3
  273. package/src/helpers/CameraHelper.js +3 -0
  274. package/src/helpers/DirectionalLightHelper.js +6 -1
  275. package/src/helpers/HemisphereLightHelper.js +5 -0
  276. package/src/helpers/PointLightHelper.js +3 -25
  277. package/src/helpers/SpotLightHelper.js +4 -1
  278. package/src/lights/DirectionalLight.js +13 -0
  279. package/src/lights/HemisphereLight.js +10 -0
  280. package/src/lights/Light.js +1 -11
  281. package/src/lights/LightProbe.js +0 -15
  282. package/src/lights/LightShadow.js +15 -6
  283. package/src/lights/PointLight.js +15 -0
  284. package/src/lights/PointLightShadow.js +0 -86
  285. package/src/lights/SpotLight.js +22 -1
  286. package/src/lights/webgpu/IESSpotLight.js +2 -1
  287. package/src/loaders/AudioLoader.js +11 -1
  288. package/src/loaders/Cache.js +28 -0
  289. package/src/loaders/DataTextureLoader.js +75 -42
  290. package/src/loaders/FileLoader.js +2 -3
  291. package/src/loaders/ImageBitmapLoader.js +12 -9
  292. package/src/loaders/Loader.js +6 -0
  293. package/src/loaders/LoadingManager.js +5 -0
  294. package/src/loaders/MaterialLoader.js +37 -266
  295. package/src/loaders/ObjectLoader.js +48 -6
  296. package/src/loaders/nodes/NodeLoader.js +2 -2
  297. package/src/loaders/nodes/NodeObjectLoader.js +18 -0
  298. package/src/materials/LineBasicMaterial.js +4 -0
  299. package/src/materials/Material.js +198 -1
  300. package/src/materials/MeshBasicMaterial.js +24 -0
  301. package/src/materials/MeshDepthMaterial.js +10 -0
  302. package/src/materials/MeshDistanceMaterial.js +10 -0
  303. package/src/materials/MeshLambertMaterial.js +49 -1
  304. package/src/materials/MeshMatcapMaterial.js +25 -1
  305. package/src/materials/MeshNormalMaterial.js +9 -1
  306. package/src/materials/MeshPhongMaterial.js +49 -1
  307. package/src/materials/MeshPhysicalMaterial.js +38 -0
  308. package/src/materials/MeshStandardMaterial.js +42 -1
  309. package/src/materials/MeshToonMaterial.js +35 -2
  310. package/src/materials/PointsMaterial.js +7 -0
  311. package/src/materials/ShaderMaterial.js +106 -1
  312. package/src/materials/SpriteMaterial.js +7 -0
  313. package/src/materials/nodes/Line2NodeMaterial.js +380 -297
  314. package/src/materials/nodes/MeshBasicNodeMaterial.js +2 -2
  315. package/src/materials/nodes/MeshNormalNodeMaterial.js +2 -2
  316. package/src/materials/nodes/MeshPhongNodeMaterial.js +0 -9
  317. package/src/materials/nodes/MeshPhysicalNodeMaterial.js +3 -30
  318. package/src/materials/nodes/MeshSSSNodeMaterial.js +0 -13
  319. package/src/materials/nodes/MeshStandardNodeMaterial.js +5 -15
  320. package/src/materials/nodes/NodeMaterial.js +153 -89
  321. package/src/materials/nodes/SpriteNodeMaterial.js +0 -10
  322. package/src/materials/nodes/manager/NodeMaterialObserver.js +234 -100
  323. package/src/math/Box3.js +5 -0
  324. package/src/math/FrustumArray.js +103 -133
  325. package/src/math/Interpolant.js +1 -1
  326. package/src/math/Line3.js +6 -5
  327. package/src/math/MathUtils.js +12 -12
  328. package/src/math/Matrix2.js +13 -9
  329. package/src/math/Matrix3.js +24 -9
  330. package/src/math/Matrix4.js +112 -74
  331. package/src/math/Plane.js +4 -3
  332. package/src/math/Quaternion.js +3 -29
  333. package/src/math/Sphere.js +1 -1
  334. package/src/math/Triangle.js +1 -1
  335. package/src/math/Vector2.js +13 -9
  336. package/src/math/Vector3.js +17 -15
  337. package/src/math/Vector4.js +15 -11
  338. package/src/math/interpolants/BezierInterpolant.js +106 -0
  339. package/src/nodes/Nodes.js +86 -71
  340. package/src/nodes/TSL.js +15 -13
  341. package/src/nodes/accessors/Arrays.js +5 -5
  342. package/src/nodes/accessors/Batch.js +108 -0
  343. package/src/nodes/accessors/Bitangent.js +7 -7
  344. package/src/nodes/accessors/BufferAttributeNode.js +120 -17
  345. package/src/nodes/accessors/BufferNode.js +29 -2
  346. package/src/nodes/accessors/Camera.js +149 -28
  347. package/src/nodes/accessors/ClippingNode.js +5 -5
  348. package/src/nodes/accessors/CubeTextureNode.js +27 -2
  349. package/src/nodes/accessors/Instance.js +264 -0
  350. package/src/nodes/accessors/MaterialNode.js +27 -3
  351. package/src/nodes/accessors/MaterialProperties.js +6 -8
  352. package/src/nodes/accessors/MaterialReferenceNode.js +1 -2
  353. package/src/nodes/accessors/ModelNode.js +1 -1
  354. package/src/nodes/accessors/{MorphNode.js → Morph.js} +99 -112
  355. package/src/nodes/accessors/Normal.js +24 -24
  356. package/src/nodes/accessors/Object3DNode.js +1 -1
  357. package/src/nodes/accessors/Position.js +39 -3
  358. package/src/nodes/accessors/ReferenceBaseNode.js +6 -6
  359. package/src/nodes/accessors/ReferenceNode.js +9 -8
  360. package/src/nodes/accessors/ReflectVector.js +3 -3
  361. package/src/nodes/accessors/RendererReferenceNode.js +1 -2
  362. package/src/nodes/accessors/SceneProperties.js +47 -0
  363. package/src/nodes/accessors/Skinning.js +263 -0
  364. package/src/nodes/accessors/StorageBufferNode.js +16 -27
  365. package/src/nodes/accessors/StorageTexture3DNode.js +100 -0
  366. package/src/nodes/accessors/StorageTextureNode.js +74 -11
  367. package/src/nodes/accessors/Tangent.js +8 -18
  368. package/src/nodes/accessors/Texture3DNode.js +32 -35
  369. package/src/nodes/accessors/TextureNode.js +124 -25
  370. package/src/nodes/accessors/UniformArrayNode.js +6 -4
  371. package/src/nodes/accessors/UserDataNode.js +1 -2
  372. package/src/nodes/accessors/VertexColorNode.js +1 -2
  373. package/src/nodes/code/FunctionCallNode.js +1 -1
  374. package/src/nodes/code/FunctionNode.js +4 -19
  375. package/src/nodes/core/ArrayNode.js +21 -2
  376. package/src/nodes/core/AssignNode.js +3 -3
  377. package/src/nodes/core/AttributeNode.js +3 -3
  378. package/src/nodes/core/BypassNode.js +1 -1
  379. package/src/nodes/core/ContextNode.js +104 -5
  380. package/src/nodes/core/IndexNode.js +2 -1
  381. package/src/nodes/core/InputNode.js +1 -1
  382. package/src/nodes/core/InspectorNode.js +1 -1
  383. package/src/nodes/core/IsolateNode.js +1 -1
  384. package/src/nodes/core/MRTNode.js +55 -4
  385. package/src/nodes/core/Node.js +151 -17
  386. package/src/nodes/core/NodeBuilder.js +479 -101
  387. package/src/nodes/core/NodeError.js +28 -0
  388. package/src/nodes/core/NodeFrame.js +12 -4
  389. package/src/nodes/core/NodeUtils.js +20 -18
  390. package/src/nodes/core/OutputStructNode.js +13 -11
  391. package/src/nodes/core/OverrideContextNode.js +153 -0
  392. package/src/nodes/core/ParameterNode.js +4 -4
  393. package/src/nodes/core/PropertyNode.js +66 -4
  394. package/src/nodes/core/StackNode.js +91 -20
  395. package/src/nodes/core/StackTrace.js +139 -0
  396. package/src/nodes/core/StructNode.js +20 -8
  397. package/src/nodes/core/StructTypeNode.js +17 -23
  398. package/src/nodes/core/SubBuildNode.js +2 -2
  399. package/src/nodes/core/UniformGroupNode.js +36 -6
  400. package/src/nodes/core/UniformNode.js +21 -5
  401. package/src/nodes/core/VarNode.js +56 -23
  402. package/src/nodes/core/VaryingNode.js +14 -21
  403. package/src/nodes/display/BlendModes.js +1 -105
  404. package/src/nodes/display/BumpMapNode.js +6 -1
  405. package/src/nodes/display/ColorAdjustment.js +27 -9
  406. package/src/nodes/display/ColorSpaceNode.js +3 -3
  407. package/src/nodes/display/FrontFacingNode.js +38 -9
  408. package/src/nodes/display/NormalMapNode.js +41 -6
  409. package/src/nodes/display/PassNode.js +157 -56
  410. package/src/nodes/display/PremultiplyAlphaFunctions.js +39 -0
  411. package/src/nodes/display/RenderOutputNode.js +19 -10
  412. package/src/nodes/display/ScreenNode.js +4 -2
  413. package/src/nodes/display/ToneMappingNode.js +1 -1
  414. package/src/nodes/display/ToonOutlinePassNode.js +2 -2
  415. package/src/nodes/display/ViewportDepthNode.js +52 -4
  416. package/src/nodes/display/ViewportDepthTextureNode.js +11 -15
  417. package/src/nodes/display/ViewportTextureNode.js +39 -11
  418. package/src/nodes/fog/Fog.js +18 -35
  419. package/src/nodes/functions/BSDF/BRDF_GGX_Multiscatter.js +3 -3
  420. package/src/nodes/functions/BSDF/DFGLUT.js +56 -0
  421. package/src/nodes/functions/BSDF/EnvironmentBRDF.js +2 -2
  422. package/src/nodes/functions/BSDF/V_GGX_SmithCorrelated_Anisotropic.js +2 -2
  423. package/src/nodes/functions/PhysicalLightingModel.js +126 -45
  424. package/src/nodes/functions/VolumetricLightingModel.js +40 -7
  425. package/src/nodes/geometry/RangeNode.js +5 -3
  426. package/src/nodes/gpgpu/AtomicFunctionNode.js +1 -1
  427. package/src/nodes/gpgpu/BarrierNode.js +9 -0
  428. package/src/nodes/gpgpu/ComputeBuiltinNode.js +2 -3
  429. package/src/nodes/gpgpu/ComputeNode.js +74 -48
  430. package/src/nodes/gpgpu/SubgroupFunctionNode.js +2 -2
  431. package/src/nodes/gpgpu/WorkgroupInfoNode.js +5 -5
  432. package/src/nodes/lighting/AnalyticLightNode.js +53 -0
  433. package/src/nodes/lighting/EnvironmentNode.js +30 -5
  434. package/src/nodes/lighting/IESSpotLightNode.js +40 -2
  435. package/src/nodes/lighting/LightingContextNode.js +10 -2
  436. package/src/nodes/lighting/LightsNode.js +97 -65
  437. package/src/nodes/lighting/PointShadowNode.js +166 -148
  438. package/src/nodes/lighting/ShadowFilterNode.js +74 -117
  439. package/src/nodes/lighting/ShadowNode.js +149 -51
  440. package/src/nodes/materialx/lib/mx_noise.js +2 -2
  441. package/src/nodes/math/BitcastNode.js +1 -1
  442. package/src/nodes/math/BitcountNode.js +433 -0
  443. package/src/nodes/math/ConditionalNode.js +6 -6
  444. package/src/nodes/math/MathNode.js +115 -52
  445. package/src/nodes/math/OperatorNode.js +24 -23
  446. package/src/nodes/math/PackFloatNode.js +98 -0
  447. package/src/nodes/math/UnpackFloatNode.js +96 -0
  448. package/src/nodes/parsers/GLSLNodeFunction.js +1 -1
  449. package/src/nodes/pmrem/PMREMNode.js +34 -3
  450. package/src/nodes/pmrem/PMREMUtils.js +9 -15
  451. package/src/nodes/tsl/TSLBase.js +1 -1
  452. package/src/nodes/tsl/TSLCore.js +99 -33
  453. package/src/nodes/utils/ArrayElementNode.js +14 -1
  454. package/src/nodes/utils/ConvertNode.js +1 -1
  455. package/src/nodes/utils/DebugNode.js +12 -12
  456. package/src/nodes/utils/EquirectUV.js +30 -5
  457. package/src/nodes/utils/EventNode.js +31 -2
  458. package/src/nodes/utils/FlipNode.js +1 -1
  459. package/src/nodes/utils/FunctionOverloadingNode.js +2 -2
  460. package/src/nodes/utils/JoinNode.js +3 -3
  461. package/src/nodes/utils/LoopNode.js +1 -1
  462. package/src/nodes/utils/MemberNode.js +2 -2
  463. package/src/nodes/utils/Packing.js +48 -5
  464. package/src/nodes/utils/PostProcessingUtils.js +33 -1
  465. package/src/nodes/utils/RTTNode.js +41 -25
  466. package/src/nodes/utils/ReflectorNode.js +4 -4
  467. package/src/nodes/utils/Remap.js +48 -0
  468. package/src/nodes/utils/RotateNode.js +1 -1
  469. package/src/nodes/utils/SampleNode.js +1 -1
  470. package/src/nodes/utils/SetNode.js +1 -1
  471. package/src/nodes/utils/SplitNode.js +1 -1
  472. package/src/nodes/utils/SpriteSheetUV.js +35 -0
  473. package/src/nodes/utils/StorageArrayElementNode.js +1 -1
  474. package/src/nodes/utils/UVUtils.js +28 -0
  475. package/src/objects/BatchedMesh.js +66 -30
  476. package/src/objects/InstancedMesh.js +19 -3
  477. package/src/objects/Line.js +1 -1
  478. package/src/objects/Mesh.js +1 -1
  479. package/src/objects/Points.js +1 -1
  480. package/src/objects/SkinnedMesh.js +26 -9
  481. package/src/renderers/WebGLRenderer.js +344 -156
  482. package/src/renderers/common/Animation.js +3 -3
  483. package/src/renderers/common/Attributes.js +15 -1
  484. package/src/renderers/common/Backend.js +78 -13
  485. package/src/renderers/common/Background.js +26 -13
  486. package/src/renderers/common/BindGroup.js +1 -16
  487. package/src/renderers/common/Binding.js +11 -0
  488. package/src/renderers/common/Bindings.js +141 -57
  489. package/src/renderers/common/BlendMode.js +143 -0
  490. package/src/renderers/common/Buffer.js +49 -0
  491. package/src/renderers/common/BundleGroup.js +1 -1
  492. package/src/renderers/common/ChainMap.js +30 -6
  493. package/src/renderers/common/ClippingContext.js +10 -2
  494. package/src/renderers/common/ComputePipeline.js +1 -1
  495. package/src/renderers/common/CubeRenderTarget.js +51 -7
  496. package/src/renderers/common/Geometries.js +29 -3
  497. package/src/renderers/common/Info.js +374 -4
  498. package/src/renderers/common/InspectorBase.js +6 -1
  499. package/src/renderers/common/Lighting.js +51 -19
  500. package/src/renderers/common/Pipelines.js +40 -7
  501. package/src/renderers/common/PostProcessing.js +8 -206
  502. package/src/renderers/common/ReadbackBuffer.js +78 -0
  503. package/src/renderers/common/RenderBundle.js +3 -1
  504. package/src/renderers/common/RenderBundles.js +7 -3
  505. package/src/renderers/common/RenderContext.js +16 -0
  506. package/src/renderers/common/RenderContexts.js +33 -49
  507. package/src/renderers/common/RenderList.js +41 -4
  508. package/src/renderers/common/RenderLists.js +2 -1
  509. package/src/renderers/common/RenderObject.js +88 -16
  510. package/src/renderers/common/RenderObjectPipeline.js +40 -0
  511. package/src/renderers/common/RenderObjects.js +21 -5
  512. package/src/renderers/common/RenderPipeline.js +232 -17
  513. package/src/renderers/common/Renderer.js +700 -163
  514. package/src/renderers/common/Sampler.js +16 -48
  515. package/src/renderers/common/StorageBuffer.js +13 -1
  516. package/src/renderers/common/Textures.js +121 -9
  517. package/src/renderers/common/TimestampQueryPool.js +6 -4
  518. package/src/renderers/common/Uniform.js +8 -0
  519. package/src/renderers/common/UniformsGroup.js +84 -1
  520. package/src/renderers/common/XRManager.js +377 -51
  521. package/src/renderers/common/extras/PMREMGenerator.js +40 -61
  522. package/src/renderers/common/nodes/NodeBuilderState.js +10 -2
  523. package/src/renderers/common/nodes/NodeLibrary.js +4 -4
  524. package/src/renderers/common/nodes/{Nodes.js → NodeManager.js} +298 -106
  525. package/src/renderers/common/nodes/NodeStorageBuffer.js +13 -2
  526. package/src/renderers/common/nodes/NodeUniformBuffer.js +65 -0
  527. package/src/renderers/shaders/DFGLUTData.js +19 -34
  528. package/src/renderers/shaders/ShaderChunk/batching_pars_vertex.glsl.js +2 -2
  529. package/src/renderers/shaders/ShaderChunk/color_fragment.glsl.js +1 -5
  530. package/src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl.js +1 -5
  531. package/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl.js +1 -5
  532. package/src/renderers/shaders/ShaderChunk/color_vertex.glsl.js +8 -10
  533. package/src/renderers/shaders/ShaderChunk/common.glsl.js +13 -4
  534. package/src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl.js +0 -6
  535. package/src/renderers/shaders/ShaderChunk/envmap_common_pars_fragment.glsl.js +0 -1
  536. package/src/renderers/shaders/ShaderChunk/envmap_fragment.glsl.js +9 -13
  537. package/src/renderers/shaders/ShaderChunk/envmap_physical_pars_fragment.glsl.js +2 -2
  538. package/src/renderers/shaders/ShaderChunk/envmap_vertex.glsl.js +1 -1
  539. package/src/renderers/shaders/ShaderChunk/lightprobes_pars_fragment.glsl.js +80 -0
  540. package/src/renderers/shaders/ShaderChunk/lights_fragment_begin.glsl.js +13 -2
  541. package/src/renderers/shaders/ShaderChunk/lights_fragment_end.glsl.js +6 -0
  542. package/src/renderers/shaders/ShaderChunk/lights_fragment_maps.glsl.js +6 -2
  543. package/src/renderers/shaders/ShaderChunk/lights_pars_begin.glsl.js +3 -1
  544. package/src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl.js +8 -4
  545. package/src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl.js +112 -53
  546. package/src/renderers/shaders/ShaderChunk/normal_fragment_begin.glsl.js +2 -2
  547. package/src/renderers/shaders/ShaderChunk/normal_fragment_maps.glsl.js +7 -0
  548. package/src/renderers/shaders/ShaderChunk/normal_vertex.glsl.js +6 -0
  549. package/src/renderers/shaders/ShaderChunk/packing.glsl.js +20 -4
  550. package/src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl.js +0 -1
  551. package/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl.js +225 -186
  552. package/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl.js +12 -2
  553. package/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl.js +1 -1
  554. package/src/renderers/shaders/ShaderChunk/transmission_fragment.glsl.js +2 -2
  555. package/src/renderers/shaders/ShaderChunk.js +5 -3
  556. package/src/renderers/shaders/ShaderLib/backgroundCube.glsl.js +1 -2
  557. package/src/renderers/shaders/ShaderLib/depth.glsl.js +3 -0
  558. package/src/renderers/shaders/ShaderLib/{distanceRGBA.glsl.js → distance.glsl.js} +2 -3
  559. package/src/renderers/shaders/ShaderLib/meshlambert.glsl.js +2 -1
  560. package/src/renderers/shaders/ShaderLib/meshnormal.glsl.js +1 -2
  561. package/src/renderers/shaders/ShaderLib/meshphong.glsl.js +2 -1
  562. package/src/renderers/shaders/ShaderLib/meshphysical.glsl.js +4 -9
  563. package/src/renderers/shaders/ShaderLib/meshtoon.glsl.js +0 -1
  564. package/src/renderers/shaders/ShaderLib/shadow.glsl.js +1 -1
  565. package/src/renderers/shaders/ShaderLib/vsm.glsl.js +4 -6
  566. package/src/renderers/shaders/ShaderLib.js +7 -6
  567. package/src/renderers/shaders/UniformsLib.js +7 -5
  568. package/src/renderers/shaders/UniformsUtils.js +27 -5
  569. package/src/renderers/webgl/WebGLAnimation.js +2 -1
  570. package/src/renderers/webgl/WebGLBackground.js +15 -15
  571. package/src/renderers/webgl/WebGLBindingStates.js +99 -27
  572. package/src/renderers/webgl/WebGLBufferRenderer.js +0 -32
  573. package/src/renderers/webgl/WebGLCapabilities.js +9 -4
  574. package/src/renderers/webgl/WebGLEnvironments.js +228 -0
  575. package/src/renderers/webgl/WebGLGeometries.js +10 -7
  576. package/src/renderers/webgl/WebGLIndexedBufferRenderer.js +0 -32
  577. package/src/renderers/webgl/WebGLLights.js +18 -1
  578. package/src/renderers/webgl/WebGLMaterials.js +24 -13
  579. package/src/renderers/webgl/WebGLObjects.js +3 -1
  580. package/src/renderers/webgl/WebGLOutput.js +271 -0
  581. package/src/renderers/webgl/WebGLProgram.js +54 -113
  582. package/src/renderers/webgl/WebGLPrograms.js +74 -55
  583. package/src/renderers/webgl/WebGLRenderLists.js +24 -1
  584. package/src/renderers/webgl/WebGLRenderStates.js +13 -2
  585. package/src/renderers/webgl/WebGLShaderCache.js +5 -11
  586. package/src/renderers/webgl/WebGLShadowMap.js +188 -24
  587. package/src/renderers/webgl/WebGLState.js +75 -37
  588. package/src/renderers/webgl/WebGLTextures.js +230 -56
  589. package/src/renderers/webgl/WebGLUniforms.js +40 -3
  590. package/src/renderers/webgl/WebGLUniformsGroups.js +82 -35
  591. package/src/renderers/webgl/WebGLUtils.js +6 -2
  592. package/src/renderers/webgl-fallback/WebGLBackend.js +322 -92
  593. package/src/renderers/webgl-fallback/WebGLBufferRenderer.js +0 -41
  594. package/src/renderers/webgl-fallback/nodes/GLSLNodeBuilder.js +295 -66
  595. package/src/renderers/webgl-fallback/utils/WebGLAttributeUtils.js +53 -19
  596. package/src/renderers/webgl-fallback/utils/WebGLCapabilities.js +25 -0
  597. package/src/renderers/webgl-fallback/utils/WebGLState.js +223 -6
  598. package/src/renderers/webgl-fallback/utils/WebGLTextureUtils.js +118 -73
  599. package/src/renderers/webgl-fallback/utils/WebGLTimestampQueryPool.js +10 -10
  600. package/src/renderers/webgl-fallback/utils/WebGLUtils.js +9 -3
  601. package/src/renderers/webgpu/WebGPUBackend.js +733 -302
  602. package/src/renderers/webgpu/WebGPURenderer.js +2 -1
  603. package/src/renderers/webgpu/descriptors/GPUBindGroupDescriptor.js +48 -0
  604. package/src/renderers/webgpu/descriptors/GPUBufferDescriptor.js +57 -0
  605. package/src/renderers/webgpu/descriptors/GPUCommandEncoderDescriptor.js +30 -0
  606. package/src/renderers/webgpu/descriptors/GPUComputePassDescriptor.js +38 -0
  607. package/src/renderers/webgpu/descriptors/GPUComputePipelineDescriptor.js +48 -0
  608. package/src/renderers/webgpu/descriptors/GPUCopyExternalImageDestInfo.js +47 -0
  609. package/src/renderers/webgpu/descriptors/GPUCopyExternalImageSourceInfo.js +50 -0
  610. package/src/renderers/webgpu/descriptors/GPUExtent3D.js +51 -0
  611. package/src/renderers/webgpu/descriptors/GPUPipelineLayoutDescriptor.js +39 -0
  612. package/src/renderers/webgpu/descriptors/GPUQuerySetDescriptor.js +47 -0
  613. package/src/renderers/webgpu/descriptors/GPURenderBundleEncoderDescriptor.js +74 -0
  614. package/src/renderers/webgpu/descriptors/GPURenderPassColorAttachment.js +72 -0
  615. package/src/renderers/webgpu/descriptors/GPURenderPassDepthStencilAttachment.js +99 -0
  616. package/src/renderers/webgpu/descriptors/GPURenderPassDescriptor.js +72 -0
  617. package/src/renderers/webgpu/descriptors/GPURenderPassTimestampWrites.js +49 -0
  618. package/src/renderers/webgpu/descriptors/GPURenderPipelineDescriptor.js +130 -0
  619. package/src/renderers/webgpu/descriptors/GPUSamplerDescriptor.js +119 -0
  620. package/src/renderers/webgpu/descriptors/GPUShaderModuleDescriptor.js +46 -0
  621. package/src/renderers/webgpu/descriptors/GPUTexelCopyBufferInfo.js +57 -0
  622. package/src/renderers/webgpu/descriptors/GPUTexelCopyBufferLayout.js +48 -0
  623. package/src/renderers/webgpu/descriptors/GPUTexelCopyTextureInfo.js +61 -0
  624. package/src/renderers/webgpu/descriptors/GPUTextureDescriptor.js +99 -0
  625. package/src/renderers/webgpu/descriptors/GPUTextureViewDescriptor.js +108 -0
  626. package/src/renderers/webgpu/nodes/StandardNodeLibrary.js +0 -1
  627. package/src/renderers/webgpu/nodes/WGSLNodeBuilder.js +526 -93
  628. package/src/renderers/webgpu/nodes/WGSLNodeFunction.js +1 -1
  629. package/src/renderers/webgpu/utils/WebGPUAttributeUtils.js +194 -61
  630. package/src/renderers/webgpu/utils/WebGPUBindingUtils.js +395 -234
  631. package/src/renderers/webgpu/utils/WebGPUCapabilities.js +48 -0
  632. package/src/renderers/webgpu/utils/WebGPUConstants.js +10 -0
  633. package/src/renderers/webgpu/utils/WebGPUPipelineUtils.js +224 -91
  634. package/src/renderers/webgpu/utils/WebGPUTexturePassUtils.js +228 -213
  635. package/src/renderers/webgpu/utils/WebGPUTextureUtils.js +428 -175
  636. package/src/renderers/webgpu/utils/WebGPUTimestampQueryPool.js +40 -25
  637. package/src/renderers/webgpu/utils/WebGPUUtils.js +70 -13
  638. package/src/renderers/webxr/WebXRController.js +12 -0
  639. package/src/renderers/webxr/WebXRManager.js +4 -2
  640. package/src/textures/CubeDepthTexture.js +76 -0
  641. package/src/textures/DepthTexture.js +1 -1
  642. package/src/textures/ExternalTexture.js +0 -3
  643. package/src/textures/HTMLTexture.js +74 -0
  644. package/src/textures/Source.js +2 -2
  645. package/src/textures/Texture.js +16 -5
  646. package/src/utils.js +280 -3
  647. package/examples/fonts/LICENSE +0 -13
  648. package/examples/fonts/MPLUSRounded1c/MPLUSRounded1c-Regular.typeface.json.zip +0 -0
  649. package/examples/fonts/MPLUSRounded1c/OFL.txt +0 -91
  650. package/examples/fonts/README.md +0 -11
  651. package/examples/fonts/droid/NOTICE +0 -190
  652. package/examples/fonts/droid/README.txt +0 -18
  653. package/examples/fonts/droid/droid_sans_bold.typeface.json +0 -1
  654. package/examples/fonts/droid/droid_sans_mono_regular.typeface.json +0 -1
  655. package/examples/fonts/droid/droid_sans_regular.typeface.json +0 -1
  656. package/examples/fonts/droid/droid_serif_bold.typeface.json +0 -1
  657. package/examples/fonts/droid/droid_serif_regular.typeface.json +0 -1
  658. package/examples/fonts/gentilis_bold.typeface.json +0 -1
  659. package/examples/fonts/gentilis_regular.typeface.json +0 -1
  660. package/examples/fonts/helvetiker_bold.typeface.json +0 -1
  661. package/examples/fonts/helvetiker_regular.typeface.json +0 -1
  662. package/examples/fonts/optimer_bold.typeface.json +0 -1
  663. package/examples/fonts/optimer_regular.typeface.json +0 -1
  664. package/examples/fonts/ttf/README.md +0 -9
  665. package/examples/fonts/ttf/kenpixel.ttf +0 -0
  666. package/examples/jsm/libs/ammo.wasm.js +0 -822
  667. package/examples/jsm/libs/ammo.wasm.wasm +0 -0
  668. package/examples/jsm/libs/draco/draco_encoder.js +0 -33
  669. package/examples/jsm/libs/draco/gltf/draco_encoder.js +0 -33
  670. package/examples/jsm/libs/lottie_canvas.module.js +0 -14849
  671. package/examples/jsm/libs/opentype.module.js +0 -14506
  672. package/examples/jsm/libs/rhino3dm/rhino3dm.js +0 -21
  673. package/examples/jsm/libs/rhino3dm/rhino3dm.module.js +0 -16
  674. package/examples/jsm/libs/rhino3dm/rhino3dm.wasm +0 -0
  675. package/examples/jsm/lighting/TiledLighting.js +0 -42
  676. package/examples/jsm/materials/MeshGouraudMaterial.js +0 -434
  677. package/examples/jsm/materials/MeshPostProcessingMaterial.js +0 -167
  678. package/examples/jsm/shaders/GodRaysShader.js +0 -333
  679. package/examples/jsm/tsl/display/AnamorphicNode.js +0 -282
  680. package/examples/jsm/tsl/lighting/TiledLightsNode.js +0 -442
  681. package/src/nodes/accessors/BatchNode.js +0 -163
  682. package/src/nodes/accessors/InstanceNode.js +0 -244
  683. package/src/nodes/accessors/InstancedMeshNode.js +0 -50
  684. package/src/nodes/accessors/SceneNode.js +0 -145
  685. package/src/nodes/accessors/SkinningNode.js +0 -327
  686. package/src/nodes/code/ScriptableNode.js +0 -726
  687. package/src/nodes/code/ScriptableValueNode.js +0 -253
  688. package/src/nodes/display/PosterizeNode.js +0 -65
  689. package/src/nodes/functions/BSDF/DFGApprox.js +0 -71
  690. package/src/nodes/utils/RemapNode.js +0 -125
  691. package/src/nodes/utils/SpriteSheetUVNode.js +0 -90
  692. package/src/renderers/webgl/WebGLCubeMaps.js +0 -99
  693. package/src/renderers/webgl/WebGLCubeUVMaps.js +0 -134
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2010-2025 Three.js Authors
3
+ * Copyright 2010-2026 Three.js Authors
4
4
  * SPDX-License-Identifier: MIT
5
5
  */
6
- import{error as e,Color as t,Vector2 as r,Vector3 as s,Vector4 as i,Matrix2 as n,Matrix3 as a,Matrix4 as o,EventDispatcher as u,MathUtils as l,warn as d,WebGLCoordinateSystem as c,WebGPUCoordinateSystem as h,ColorManagement as p,SRGBTransfer as g,NoToneMapping as m,StaticDrawUsage as f,InterleavedBuffer as y,DynamicDrawUsage as b,InterleavedBufferAttribute as x,NoColorSpace as T,log as _,warnOnce as v,UnsignedIntType as N,IntType as S,NearestFilter as A,Texture as R,Sphere as E,BackSide as w,DoubleSide as C,Euler as M,CubeReflectionMapping as B,CubeRefractionMapping as P,CubeTexture as L,TangentSpaceNormalMap as F,ObjectSpaceNormalMap as I,InstancedInterleavedBuffer as D,InstancedBufferAttribute as U,DataArrayTexture as V,FloatType as O,FramebufferTexture as G,LinearMipmapLinearFilter as k,DepthTexture as z,Material as $,LineBasicMaterial as W,LineDashedMaterial as H,NoBlending as j,SRGBColorSpace as q,MeshNormalMaterial as X,WebGLCubeRenderTarget as K,BoxGeometry as Y,Mesh as Q,Scene as Z,LinearFilter as J,CubeCamera as ee,EquirectangularReflectionMapping as te,EquirectangularRefractionMapping as re,AddOperation as se,MixOperation as ie,MultiplyOperation as ne,MeshBasicMaterial as ae,MeshLambertMaterial as oe,MeshPhongMaterial as ue,DataTexture as le,RGFormat as de,HalfFloatType as ce,ClampToEdgeWrapping as he,BufferGeometry as pe,BufferAttribute as ge,RenderTarget as me,CubeUVReflectionMapping as fe,OrthographicCamera as ye,RGBAFormat as be,LinearSRGBColorSpace as xe,PerspectiveCamera as Te,MeshStandardMaterial as _e,MeshPhysicalMaterial as ve,MeshToonMaterial as Ne,MeshMatcapMaterial as Se,SpriteMaterial as Ae,PointsMaterial as Re,ShadowMaterial as Ee,arrayNeedsUint32 as we,Uint32BufferAttribute as Ce,Uint16BufferAttribute as Me,Camera as Be,DepthStencilFormat as Pe,DepthFormat as Le,UnsignedInt248Type as Fe,UnsignedByteType as Ie,Plane as De,Object3D as Ue,LinearMipMapLinearFilter as Ve,Float32BufferAttribute as Oe,UVMapping as Ge,VSMShadowMap as ke,LessCompare as ze,BasicShadowMap as $e,SphereGeometry as We,NormalBlending as He,LinearMipmapNearestFilter as je,NearestMipmapLinearFilter as qe,Float16BufferAttribute as Xe,REVISION as Ke,ArrayCamera as Ye,PlaneGeometry as Qe,FrontSide as Ze,CustomBlending as Je,AddEquation as et,ZeroFactor as tt,CylinderGeometry as rt,WebXRController as st,RAD2DEG as it,Quaternion as nt,PCFShadowMap as at,Frustum as ot,FrustumArray as ut,RedIntegerFormat as lt,RedFormat as dt,RGIntegerFormat as ct,RGBIntegerFormat as ht,RGBFormat as pt,RGBAIntegerFormat as gt,UnsignedShortType as mt,ByteType as ft,ShortType as yt,TimestampQuery as bt,createCanvasElement as xt,SubtractEquation as Tt,ReverseSubtractEquation as _t,OneFactor as vt,SrcColorFactor as Nt,SrcAlphaFactor as St,SrcAlphaSaturateFactor as At,DstColorFactor as Rt,DstAlphaFactor as Et,OneMinusSrcColorFactor as wt,OneMinusSrcAlphaFactor as Ct,OneMinusDstColorFactor as Mt,OneMinusDstAlphaFactor as Bt,CullFaceNone as Pt,CullFaceBack as Lt,CullFaceFront as Ft,MultiplyBlending as It,SubtractiveBlending as Dt,AdditiveBlending as Ut,NotEqualDepth as Vt,GreaterDepth as Ot,GreaterEqualDepth as Gt,EqualDepth as kt,LessEqualDepth as zt,LessDepth as $t,AlwaysDepth as Wt,NeverDepth as Ht,UnsignedShort4444Type as jt,UnsignedShort5551Type as qt,UnsignedInt5999Type as Xt,UnsignedInt101111Type as Kt,AlphaFormat as Yt,RGB_S3TC_DXT1_Format as Qt,RGBA_S3TC_DXT1_Format as Zt,RGBA_S3TC_DXT3_Format as Jt,RGBA_S3TC_DXT5_Format as er,RGB_PVRTC_4BPPV1_Format as tr,RGB_PVRTC_2BPPV1_Format as rr,RGBA_PVRTC_4BPPV1_Format as sr,RGBA_PVRTC_2BPPV1_Format as ir,RGB_ETC1_Format as nr,RGB_ETC2_Format as ar,RGBA_ETC2_EAC_Format as or,RGBA_ASTC_4x4_Format as ur,RGBA_ASTC_5x4_Format as lr,RGBA_ASTC_5x5_Format as dr,RGBA_ASTC_6x5_Format as cr,RGBA_ASTC_6x6_Format as hr,RGBA_ASTC_8x5_Format as pr,RGBA_ASTC_8x6_Format as gr,RGBA_ASTC_8x8_Format as mr,RGBA_ASTC_10x5_Format as fr,RGBA_ASTC_10x6_Format as yr,RGBA_ASTC_10x8_Format as br,RGBA_ASTC_10x10_Format as xr,RGBA_ASTC_12x10_Format as Tr,RGBA_ASTC_12x12_Format as _r,RGBA_BPTC_Format as vr,RED_RGTC1_Format as Nr,SIGNED_RED_RGTC1_Format as Sr,RED_GREEN_RGTC2_Format as Ar,SIGNED_RED_GREEN_RGTC2_Format as Rr,RepeatWrapping as Er,MirroredRepeatWrapping as wr,NearestMipmapNearestFilter as Cr,NeverCompare as Mr,AlwaysCompare as Br,LessEqualCompare as Pr,EqualCompare as Lr,GreaterEqualCompare as Fr,GreaterCompare as Ir,NotEqualCompare as Dr,LinearTransfer as Ur,getByteLength as Vr,NotEqualStencilFunc as Or,GreaterStencilFunc as Gr,GreaterEqualStencilFunc as kr,EqualStencilFunc as zr,LessEqualStencilFunc as $r,LessStencilFunc as Wr,AlwaysStencilFunc as Hr,NeverStencilFunc as jr,DecrementWrapStencilOp as qr,IncrementWrapStencilOp as Xr,DecrementStencilOp as Kr,IncrementStencilOp as Yr,InvertStencilOp as Qr,ReplaceStencilOp as Zr,ZeroStencilOp as Jr,KeepStencilOp as es,MaxEquation as ts,MinEquation as rs,SpotLight as ss,PointLight as is,DirectionalLight as ns,RectAreaLight as as,AmbientLight as os,HemisphereLight as us,LightProbe as ls,LinearToneMapping as ds,ReinhardToneMapping as cs,CineonToneMapping as hs,ACESFilmicToneMapping as ps,AgXToneMapping as gs,NeutralToneMapping as ms,Group as fs,Loader as ys,FileLoader as bs,MaterialLoader as xs,ObjectLoader as Ts}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BatchedMesh,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,ConstantAlphaFactor,ConstantColorFactor,Controls,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CustomToneMapping,Cylindrical,Data3DTexture,DataTextureLoader,DataUtils,DefaultLoadingManager,DetachedBindMode,DirectionalLightHelper,DiscreteInterpolant,DodecahedronGeometry,DynamicCopyUsage,DynamicReadUsage,EdgesGeometry,EllipseCurve,ExternalTexture,ExtrudeGeometry,Fog,FogExp2,GLBufferAttribute,GLSL1,GLSL3,GridHelper,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,InstancedBufferGeometry,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,Interpolant,InterpolateDiscrete,InterpolateLinear,InterpolateSmooth,InterpolationSamplingMode,InterpolationSamplingType,KeyframeTrack,LOD,LatheGeometry,Layers,Light,Line,Line3,LineCurve,LineCurve3,LineLoop,LineSegments,LinearInterpolant,LinearMipMapNearestFilter,LoaderUtils,LoadingManager,LoopOnce,LoopPingPong,LoopRepeat,MOUSE,MeshDepthMaterial,MeshDistanceMaterial,NearestMipMapLinearFilter,NearestMipMapNearestFilter,NormalAnimationBlendMode,NumberKeyframeTrack,OctahedronGeometry,OneMinusConstantAlphaFactor,OneMinusConstantColorFactor,PCFSoftShadowMap,Path,PlaneHelper,PointLightHelper,Points,PolarGridHelper,PolyhedronGeometry,PositionalAudio,PropertyBinding,PropertyMixer,QuadraticBezierCurve,QuadraticBezierCurve3,QuaternionKeyframeTrack,QuaternionLinearInterpolant,RGBADepthPacking,RGBDepthPacking,RGB_BPTC_SIGNED_Format,RGB_BPTC_UNSIGNED_Format,RGDepthPacking,RawShaderMaterial,Ray,Raycaster,RenderTarget3D,RingGeometry,ShaderMaterial,Shape,ShapeGeometry,ShapePath,ShapeUtils,Skeleton,SkeletonHelper,SkinnedMesh,Source,Spherical,SphericalHarmonics3,SplineCurve,SpotLightHelper,Sprite,StaticCopyUsage,StaticReadUsage,StereoCamera,StreamCopyUsage,StreamDrawUsage,StreamReadUsage,StringKeyframeTrack,TOUCH,TetrahedronGeometry,TextureLoader,TextureUtils,Timer,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGLRenderTarget,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding,getConsoleFunction,setConsoleFunction}from"./three.core.min.js";const _s=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],vs=new WeakMap;class Ns{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=_s,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:r,material:s,object:i}=e;if(t={material:this.getMaterialData(s),geometry:{id:r.id,attributes:this.getAttributesData(r.attributes),indexVersion:r.index?r.index.version:null,drawRange:{start:r.drawRange.start,count:r.drawRange.count}},worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={version:s.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}getMaterialData(e){const t={};for(const r of this.refreshUniforms){const s=e[r];null!=s&&("object"==typeof s&&void 0!==s.clone?!0===s.isTexture?t[r]={id:s.id,version:s.version}:t[r]=s.clone():t[r]=s)}return t}equals(e,t){const{object:r,material:s,geometry:i}=e,n=this.getRenderObjectData(e);if(!0!==n.worldMatrix.equals(r.matrixWorld))return n.worldMatrix.copy(r.matrixWorld),!1;const a=n.material;for(const e in a){const t=a[e],r=s[e];if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,!1}else if(t!==r)return a[e]=r,!1}if(a.transmission>0){const{width:t,height:r}=e.context;if(n.bufferWidth!==t||n.bufferHeight!==r)return n.bufferWidth=t,n.bufferHeight=r,!1}const o=n.geometry,u=i.attributes,l=o.attributes,d=Object.keys(l),c=Object.keys(u);if(o.id!==i.id)return o.id=i.id,!1;if(d.length!==c.length)return n.geometry.attributes=this.getAttributesData(u),!1;for(const e of d){const t=l[e],r=u[e];if(void 0===r)return delete l[e],!1;if(t.version!==r.version)return t.version=r.version,!1}const h=i.index,p=o.indexVersion,g=h?h.version:null;if(p!==g)return o.indexVersion=g,!1;if(o.drawRange.start!==i.drawRange.start||o.drawRange.count!==i.drawRange.count)return o.drawRange.start=i.drawRange.start,o.drawRange.count=i.drawRange.count,!1;if(n.morphTargetInfluences){let e=!1;for(let t=0;t<n.morphTargetInfluences.length;t++)n.morphTargetInfluences[t]!==r.morphTargetInfluences[t]&&(n.morphTargetInfluences[t]=r.morphTargetInfluences[t],e=!0);if(e)return!1}if(n.lights)for(let e=0;e<t.length;e++)if(n.lights[e].map!==t[e].map)return!1;return n.center&&!1===n.center.equals(r.center)?(n.center.copy(r.center),!0):(null!==e.bundle&&(n.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const r of e)!0===r.isSpotLight&&null!==r.map&&t.push({map:r.map.version});return t}getLights(e,t){if(vs.has(e)){const r=vs.get(e);if(r.renderId===t)return r.lightsData}const r=this.getLightsData(e.getLights());return vs.set(e,{renderId:t,lightsData:r}),r}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:r}=t;if(this.renderId!==r)return this.renderId=r,!0;const s=!0===e.object.static,i=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(s||i)return!1;const n=this.getLights(e.lightsNode,r);return!0!==this.equals(e,n)}}function Ss(e,t=0){let r=3735928559^t,s=1103547991^t;if(e instanceof Array)for(let t,i=0;i<e.length;i++)t=e[i],r=Math.imul(r^t,2654435761),s=Math.imul(s^t,1597334677);else for(let t,i=0;i<e.length;i++)t=e.charCodeAt(i),r=Math.imul(r^t,2654435761),s=Math.imul(s^t,1597334677);return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&s)+(r>>>0)}const As=e=>Ss(e),Rs=e=>Ss(e),Es=(...e)=>Ss(e),ws=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Cs=new WeakMap;function Ms(e){return ws.get(e)}function Bs(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e))return Float32Array;if(/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function Ps(t){return/float|int|uint/.test(t)?1:/vec2/.test(t)?2:/vec3/.test(t)?3:/vec4/.test(t)||/mat2/.test(t)?4:/mat3/.test(t)?9:/mat4/.test(t)?16:void e("TSL: Unsupported type:",t)}function Ls(t){return/float|int|uint/.test(t)?1:/vec2/.test(t)?2:/vec3/.test(t)?3:/vec4/.test(t)||/mat2/.test(t)?4:/mat3/.test(t)?12:/mat4/.test(t)?16:void e("TSL: Unsupported type:",t)}function Fs(t){return/float|int|uint/.test(t)?4:/vec2/.test(t)?8:/vec3/.test(t)||/vec4/.test(t)?16:/mat2/.test(t)?8:/mat3/.test(t)?48:/mat4/.test(t)?64:void e("TSL: Unsupported type:",t)}function Is(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function Ds(e,...u){const l=e?e.slice(-4):void 0;return 1===u.length&&("vec2"===l?u=[u[0],u[0]]:"vec3"===l?u=[u[0],u[0],u[0]]:"vec4"===l&&(u=[u[0],u[0],u[0],u[0]])),"color"===e?new t(...u):"vec2"===l?new r(...u):"vec3"===l?new s(...u):"vec4"===l?new i(...u):"mat2"===l?new n(...u):"mat3"===l?new a(...u):"mat4"===l?new o(...u):"bool"===e?u[0]||!1:"float"===e||"int"===e||"uint"===e?u[0]||0:"string"===e?u[0]||"":"ArrayBuffer"===e?Os(u[0]):null}function Us(e){let t=Cs.get(e);return void 0===t&&(t={},Cs.set(e,t)),t}function Vs(e){let t="";const r=new Uint8Array(e);for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return btoa(t)}function Os(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0))).buffer}var Gs=Object.freeze({__proto__:null,arrayBufferToBase64:Vs,base64ToArrayBuffer:Os,getByteBoundaryFromType:Fs,getDataFromObject:Us,getLengthFromType:Ps,getMemoryLengthFromType:Ls,getTypeFromLength:Ms,getTypedArrayFromType:Bs,getValueFromType:Ds,getValueType:Is,hash:Es,hashArray:Rs,hashString:As});const ks={VERTEX:"vertex",FRAGMENT:"fragment"},zs={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},$s={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},Ws={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},Hs=["fragment","vertex"],js=["setup","analyze","generate"],qs=[...Hs,"compute"],Xs=["x","y","z","w"],Ks={analyze:"setup",generate:"analyze"};let Ys=0;class Qs extends u{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=zs.NONE,this.updateBeforeType=zs.NONE,this.updateAfterType=zs.NONE,this.uuid=l.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Ys++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,zs.FRAME)}onRenderUpdate(e){return this.onUpdate(e,zs.RENDER)}onObjectUpdate(e){return this.onUpdate(e,zs.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const r of Object.getOwnPropertyNames(this)){const s=this[r];if(!0!==r.startsWith("_")&&!e.has(s))if(!0===Array.isArray(s))for(let e=0;e<s.length;e++){const i=s[e];i&&!0===i.isNode&&t.push({property:r,index:e,childNode:i})}else if(s&&!0===s.isNode)t.push({property:r,childNode:s});else if(s&&Object.getPrototypeOf(s)===Object.prototype)for(const e in s){if(!0===e.startsWith("_"))continue;const i=s[e];i&&!0===i.isNode&&t.push({property:r,index:e,childNode:i})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const r=[];for(const{property:s,childNode:i}of this._getChildren(t))r.push(As(s.slice(0,-4)),i.getCacheKey(e,t));this._cacheKey=Es(Rs(r),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let r=0;for(const e of this.getChildren())t["node"+r++]=e;return t.outputNode||null}analyze(e,t=null){const r=e.increaseUsage(this);if(!0===this.parents){const r=e.getDataFromNode(this,"any");r.stages=r.stages||{},r.stages[e.shaderStage]=r.stages[e.shaderStage]||[],r.stages[e.shaderStage].push(t)}if(1===r){const t=e.getNodeProperties(this);for(const r of Object.values(t))r&&!0===r.isNode&&r.build(e,this)}}generate(e,t){const{outputNode:r}=e.getNodeProperties(this);if(r&&!0===r.isNode)return r.build(e,t)}updateBefore(){d("Abstract function.")}updateAfter(){d("Abstract function.")}update(){d("Abstract function.")}before(e){return null===this._beforeNodes&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(t,r=null){const s=this.getShared(t);if(this!==s)return s.build(t,r);if(null!==this._beforeNodes){const e=this._beforeNodes;this._beforeNodes=null;for(const s of e)s.build(t,r);this._beforeNodes=e}const i=t.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[t.buildStage]=!0;const n=Ks[t.buildStage];if(n&&!0!==i.buildStages[n]){const e=t.getBuildStage();t.setBuildStage(n),this.build(t),t.setBuildStage(e)}t.addNode(this),t.addChain(this);let a=null;const o=t.getBuildStage();if("setup"===o){this.updateReference(t);const e=t.getNodeProperties(this);if(!0!==e.initialized){e.initialized=!0,e.outputNode=this.setup(t)||e.outputNode||null;for(const r of Object.values(e))if(r&&!0===r.isNode){if(!0===r.parents){const e=t.getNodeProperties(r);e.parents=e.parents||[],e.parents.push(this)}r.build(t)}}a=e.outputNode}else if("analyze"===o)this.analyze(t,r);else if("generate"===o){if(this.generate.length<2){const e=this.getNodeType(t),s=t.getDataFromNode(this);a=s.snippet,void 0===a?void 0===s.generated?(s.generated=!0,a=this.generate(t)||"",s.snippet=a):(d("Node: Recursion detected.",this),a="/* Recursion detected. */"):void 0!==s.flowCodes&&void 0!==t.context.nodeBlock&&t.addFlowCodeHierarchy(this,t.context.nodeBlock),a=t.format(a,e,r)}else a=this.generate(t,r)||"";""===a&&null!==r&&"void"!==r&&"OutputType"!==r&&(e(`TSL: Invalid generated code, expected a "${r}".`),a=t.generateConst(r))}return t.removeChain(this),t.addSequentialNode(this),a}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),r={};for(const{property:s,index:i,childNode:n}of t)void 0!==i?(void 0===r[s]&&(r[s]=Number.isInteger(i)?[]:{}),r[s][i]=n.toJSON(e.meta).uuid):r[s]=n.toJSON(e.meta).uuid;Object.keys(r).length>0&&(e.inputNodes=r)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const r in e.inputNodes)if(Array.isArray(e.inputNodes[r])){const s=[];for(const i of e.inputNodes[r])s.push(t[i]);this[r]=s}else if("object"==typeof e.inputNodes[r]){const s={};for(const i in e.inputNodes[r]){const n=e.inputNodes[r][i];s[i]=t[n]}this[r]=s}else{const s=e.inputNodes[r];this[r]=t[s]}}}toJSON(e){const{uuid:t,type:r}=this,s=void 0===e||"string"==typeof e;s&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(void 0===i&&(i={uuid:t,type:r,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==s&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),s){const t=n(e.textures),r=n(e.images),s=n(e.nodes);t.length>0&&(i.textures=t),r.length>0&&(i.images=r),s.length>0&&(i.nodes=s)}return i}}class Zs extends Qs{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Js extends Qs{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let r=null;for(const s of this.convertTo.split("|"))null!==r&&e.getTypeLength(t)!==e.getTypeLength(s)||(r=s);return r}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const r=this.node,s=this.getNodeType(e),i=r.build(e,s);return e.format(i,s,t)}}class ei extends Qs{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const r=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(void 0!==s.propertyName)return e.format(s.propertyName,r,t);if("void"!==r&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,r),n=e.getVarFromNode(this,null,r),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${i}`,this),s.snippet=i,s.propertyName=a,e.format(s.propertyName,r,t)}}return super.build(e,t)}}class ti extends ei{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,r)=>t+e.getTypeLength(r.getNodeType(e))),0))}generate(t,r){const s=this.getNodeType(t),i=t.getTypeLength(s),n=this.nodes,a=t.getComponentType(s),o=[];let u=0;for(const r of n){if(u>=i){e(`TSL: Length of parameters exceeds maximum length of function '${s}()' type.`);break}let n,l=r.getNodeType(t),d=t.getTypeLength(l);u+d>i&&(e(`TSL: Length of '${s}()' data exceeds maximum length of output type.`),d=i-u,l=t.getTypeFromLength(d)),u+=d,n=r.build(t,l);if(t.getComponentType(l)!==a){const e=t.getTypeFromLength(d,a);n=t.format(n,l,e)}o.push(n)}const l=`${t.getType(s)}( ${o.join(", ")} )`;return t.format(l,s,r)}}const ri=Xs.join("");class si extends Qs{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(Xs.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const r=this.node,s=e.getTypeLength(r.getNodeType(e));let i=null;if(s>1){let n=null;this.getVectorLength()>=s&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=r.build(e,n);i=this.components.length===s&&this.components===ri.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=r.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class ii extends ei{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:r,targetNode:s}=this,i=this.getNodeType(e),n=e.getComponentType(s.getNodeType(e)),a=e.getTypeFromLength(r.length,n),o=s.build(e,a),u=t.build(e,i),l=e.getTypeLength(i),d=[];for(let e=0;e<l;e++){const t=Xs[e];t===r[0]?(d.push(o),e+=r.length-1):d.push(u+"."+t)}return`${e.getType(i)}( ${d.join(", ")} )`}}class ni extends ei{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:r}=this,s=this.getNodeType(e),i=r.build(e),n=e.getVarFromNode(this),a=e.getPropertyName(n);e.addLineFlowCode(a+" = "+i,this);const o=e.getTypeLength(s),u=[];let l=0;for(let e=0;e<o;e++){const r=Xs[e];r===t[l]?(u.push("1.0 - "+a+"."+r),l++):u.push(a+"."+r)}return`${e.getType(s)}( ${u.join(", ")} )`}}class ai extends Qs{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?Is(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=Is(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=Vs(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Ds(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){d("Abstract function.")}}const oi=/float|u?int/;class ui extends ai{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const r=this.getNodeType(e);return oi.test(r)&&oi.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),r,t)}}class li extends Qs{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}getNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){d(`TSL: Member "${this.property}" does not exist in struct.`);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let di=null;const ci=new Map;function hi(e,t){if(ci.has(e))d(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);ci.set(e,t),"assign"!==e&&(Qs.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},Qs.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const pi=e=>(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Qs.prototype.assign=function(...t){if(!0!==this.isStackNode)return null!==di?di.assign(this,...t):e("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn()."),this;{const e=ci.get("assign");return this.addToStack(e(...t))}},Qs.prototype.toVarIntent=function(){return this},Qs.prototype.get=function(e){return new li(this,e)};const gi={};function mi(e,t,r){gi[e]=gi[t]=gi[r]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new si(this,e),this._cache[e]=t),t},set(t){this[e].assign(ki(t))}};const s=e.toUpperCase(),i=t.toUpperCase(),n=r.toUpperCase();Qs.prototype["set"+s]=Qs.prototype["set"+i]=Qs.prototype["set"+n]=function(t){const r=pi(e);return new ii(this,r,ki(t))},Qs.prototype["flip"+s]=Qs.prototype["flip"+i]=Qs.prototype["flip"+n]=function(){const t=pi(e);return new ni(this,t)}}const fi=["x","y","z","w"],yi=["r","g","b","a"],bi=["s","t","p","q"];for(let e=0;e<4;e++){let t=fi[e],r=yi[e],s=bi[e];mi(t,r,s);for(let i=0;i<4;i++){t=fi[e]+fi[i],r=yi[e]+yi[i],s=bi[e]+bi[i],mi(t,r,s);for(let n=0;n<4;n++){t=fi[e]+fi[i]+fi[n],r=yi[e]+yi[i]+yi[n],s=bi[e]+bi[i]+bi[n],mi(t,r,s);for(let a=0;a<4;a++)t=fi[e]+fi[i]+fi[n]+fi[a],r=yi[e]+yi[i]+yi[n]+yi[a],s=bi[e]+bi[i]+bi[n]+bi[a],mi(t,r,s)}}}for(let e=0;e<32;e++)gi[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Zs(this,new ui(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(ki(t))}};Object.defineProperties(Qs.prototype,gi);const xi=new WeakMap,Ti=function(e,t=null){for(const r in e)e[r]=ki(e[r],t);return e},_i=function(e,t=null){const r=e.length;for(let s=0;s<r;s++)e[s]=ki(e[s],t);return e},vi=function(t,r=null,s=null,i=null){function n(e){return null!==i?(e=ki(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=ki(e),e}let a,o,u,l=r;function d(r){let s;return s=l?/[a-z]/i.test(l)?l+"()":l:t.type,void 0!==o&&r.length<o?(e(`TSL: "${s}" parameter length is less than minimum required.`),r.concat(new Array(o-r.length).fill(0))):void 0!==u&&r.length>u?(e(`TSL: "${s}" parameter length exceeds limit.`),r.slice(0,u)):r}return null===r?a=(...e)=>n(new t(...Wi(d(e)))):null!==s?(s=ki(s),a=(...e)=>n(new t(r,...Wi(d(e)),s))):a=(...e)=>n(new t(r,...Wi(d(e)))),a.setParameterLength=(...e)=>(1===e.length?o=u=e[0]:2===e.length&&([o,u]=e),a),a.setName=e=>(l=e,a),a},Ni=function(e,...t){return ki(new e(...Wi(t)))};class Si extends Qs{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=i,e.fnCall=this;let u=null;if(t.layout){let s=xi.get(e.constructor);void 0===s&&(s=new WeakMap,xi.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=ki(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i);const n=r?function(e){let t;$i(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(r):null;u=ki(i.call(n))}else{const s=new Proxy(e,{get:(e,t,r)=>{let s;return s=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,r),s}}),i=r?function(e){let t=0;return $i(e),new Proxy(e,{get:(r,s,i)=>{let n;if("length"===s)return n=e.length,n;if(Symbol.iterator===s)n=function*(){for(const t of e)yield ki(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const r=e[0];n=void 0===r[s]?r[t++]:Reflect.get(r,s,i)}else e[0]instanceof Qs&&(n=void 0===e[s]?e[t++]:Reflect.get(e,s,i));else n=Reflect.get(r,s,i);n=ki(n)}return n}})}(r):null,n=Array.isArray(r)?r.length>0:null!==r,a=t.jsFunc,o=n||a.length>1?a(i,s):a(s);u=ki(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(s[n]=u),u}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),r=e.getSubBuildOutput(this);return t[r]=t[r]||this.setupOutput(e),t[r].subBuild=e.getClosestSubBuild(this),t[r]}build(e,t=null){let r=null;const s=e.getBuildStage(),i=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===s){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[n]=this.getOutputNode(e),i[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const r=e.getDataFromNode(t,"any");r.subBuilds=r.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)r.subBuilds.add(e)}r=i[n]}else"analyze"===s?a.build(e,t):"generate"===s&&(r=a.build(e,t)||"");return e.fnCall=o,r}}class Ai extends Qs{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Si(this,e)}setup(){return this.call()}}const Ri=[!1,!0],Ei=[0,1,2,3],wi=[-1,-2],Ci=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],Mi=new Map;for(const e of Ri)Mi.set(e,new ui(e));const Bi=new Map;for(const e of Ei)Bi.set(e,new ui(e,"uint"));const Pi=new Map([...Bi].map((e=>new ui(e.value,"int"))));for(const e of wi)Pi.set(e,new ui(e,"int"));const Li=new Map([...Pi].map((e=>new ui(e.value))));for(const e of Ci)Li.set(e,new ui(e));for(const e of Ci)Li.set(-e,new ui(-e));const Fi={bool:Mi,uint:Bi,ints:Pi,float:Li},Ii=new Map([...Mi,...Li]),Di=(e,t)=>Ii.has(e)?Ii.get(e):!0===e.isNode?e:new ui(e,t),Ui=function(t,r=null){return(...s)=>{for(const r of s)if(void 0===r)return e(`TSL: Invalid parameter for the type "${t}".`),ki(new ui(0,t));if((0===s.length||!["bool","float","int","uint"].includes(t)&&s.every((e=>{const t=typeof e;return"object"!==t&&"function"!==t})))&&(s=[Ds(t,...s)]),1===s.length&&null!==r&&r.has(s[0]))return zi(r.get(s[0]));if(1===s.length){const e=Di(s[0],t);return e.nodeType===t?zi(e):zi(new Js(e,t))}const i=s.map((e=>Di(e)));return zi(new ti(i,t))}},Vi=e=>"object"==typeof e&&null!==e?e.value:e,Oi=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function Gi(e,t){return new Ai(e,t)}const ki=(e,t=null)=>function(e,t=null){const r=Is(e);return"node"===r?e:null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?ki(Di(e,t)):"shader"===r?e.isFn?e:Yi(e):e}(e,t),zi=(e,t=null)=>ki(e,t).toVarIntent(),$i=(e,t=null)=>new Ti(e,t),Wi=(e,t=null)=>new _i(e,t),Hi=(e,t=null,r=null,s=null)=>new vi(e,t,r,s),ji=(e,...t)=>new Ni(e,...t),qi=(e,t=null,r=null,s={})=>new vi(e,t,r,{...s,intent:!0});let Xi=0;class Ki extends Qs{constructor(t,r=null){super();let s=null;null!==r&&("object"==typeof r?s=r.return:("string"==typeof r?s=r:e("TSL: Invalid layout type."),r=null)),this.shaderNode=new Gi(t,s),null!==r&&this.setLayout(r),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const r={name:"fn"+Xi++,type:t,inputs:[]};for(const t in e)"return"!==t&&r.inputs.push({name:t,type:e[t]});e=r}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(t){const r=this.getNodeType(t);return e('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".'),t.generateConst(r)}}function Yi(e,t=null){const r=new Ki(e,t);return new Proxy((()=>{}),{apply:(e,t,s)=>r.call(...s),get:(e,t,s)=>Reflect.get(r,t,s),set:(e,t,s,i)=>Reflect.set(r,t,s,i)})}const Qi=e=>{di=e},Zi=()=>di,Ji=(...e)=>di.If(...e);function en(e){return di&&di.addToStack(e),e}hi("toStack",en);const tn=new Ui("color"),rn=new Ui("float",Fi.float),sn=new Ui("int",Fi.ints),nn=new Ui("uint",Fi.uint),an=new Ui("bool",Fi.bool),on=new Ui("vec2"),un=new Ui("ivec2"),ln=new Ui("uvec2"),dn=new Ui("bvec2"),cn=new Ui("vec3"),hn=new Ui("ivec3"),pn=new Ui("uvec3"),gn=new Ui("bvec3"),mn=new Ui("vec4"),fn=new Ui("ivec4"),yn=new Ui("uvec4"),bn=new Ui("bvec4"),xn=new Ui("mat2"),Tn=new Ui("mat3"),_n=new Ui("mat4");hi("toColor",tn),hi("toFloat",rn),hi("toInt",sn),hi("toUint",nn),hi("toBool",an),hi("toVec2",on),hi("toIVec2",un),hi("toUVec2",ln),hi("toBVec2",dn),hi("toVec3",cn),hi("toIVec3",hn),hi("toUVec3",pn),hi("toBVec3",gn),hi("toVec4",mn),hi("toIVec4",fn),hi("toUVec4",yn),hi("toBVec4",bn),hi("toMat2",xn),hi("toMat3",Tn),hi("toMat4",_n);const vn=Hi(Zs).setParameterLength(2),Nn=(e,t)=>ki(new Js(ki(e),t));hi("element",vn),hi("convert",Nn);hi("append",(e=>(d("TSL: .append() has been renamed to .toStack()."),en(e))));class Sn extends Qs{static get type(){return"PropertyNode"}constructor(e,t=null,r=!1){super(e),this.name=t,this.varying=r,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return As(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const An=(e,t)=>ki(new Sn(e,t)),Rn=(e,t)=>ki(new Sn(e,t,!0)),En=ji(Sn,"vec4","DiffuseColor"),wn=ji(Sn,"vec3","EmissiveColor"),Cn=ji(Sn,"float","Roughness"),Mn=ji(Sn,"float","Metalness"),Bn=ji(Sn,"float","Clearcoat"),Pn=ji(Sn,"float","ClearcoatRoughness"),Ln=ji(Sn,"vec3","Sheen"),Fn=ji(Sn,"float","SheenRoughness"),In=ji(Sn,"float","Iridescence"),Dn=ji(Sn,"float","IridescenceIOR"),Un=ji(Sn,"float","IridescenceThickness"),Vn=ji(Sn,"float","AlphaT"),On=ji(Sn,"float","Anisotropy"),Gn=ji(Sn,"vec3","AnisotropyT"),kn=ji(Sn,"vec3","AnisotropyB"),zn=ji(Sn,"color","SpecularColor"),$n=ji(Sn,"float","SpecularF90"),Wn=ji(Sn,"float","Shininess"),Hn=ji(Sn,"vec4","Output"),jn=ji(Sn,"float","dashSize"),qn=ji(Sn,"float","gapSize"),Xn=ji(Sn,"float","pointWidth"),Kn=ji(Sn,"float","IOR"),Yn=ji(Sn,"float","Transmission"),Qn=ji(Sn,"float","Thickness"),Zn=ji(Sn,"float","AttenuationDistance"),Jn=ji(Sn,"color","AttenuationColor"),ea=ji(Sn,"float","Dispersion");class ta extends Qs{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1){super("string"),this.name=e,this.shared=t,this.order=r,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const ra=e=>new ta(e),sa=(e,t=0)=>new ta(e,!0,t),ia=sa("frame"),na=sa("render"),aa=ra("object");class oa extends ai{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=aa}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate((t=>{const r=e(t,this);void 0!==r&&(this.value=r)}),t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const r=this.getNodeType(e),s=this.getUniformHash(e);let i=e.getNodeFromHash(s);void 0===i&&(e.setHashNode(this,s),i=this);const n=i.getInputType(e),a=e.getUniformFromNode(i,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let u=o;if("bool"===r){const t=e.getDataFromNode(this);let s=t.propertyName;if(void 0===s){const i=e.getVarFromNode(this,null,"bool");s=e.getPropertyName(i),t.propertyName=s,u=e.format(o,n,r),e.addLineFlowCode(`${s} = ${u}`,this)}u=s}return e.format(u,r,t)}}const ua=(e,t)=>{const r=Oi(t||e);return r===e&&(e=Ds(r)),e=e&&!0===e.isNode?e.node&&e.node.value||e.value:e,ki(new oa(e,r))};class la extends ei{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const da=(...e)=>{let t;if(1===e.length){const r=e[0];t=new la(null,r.length,r)}else{const r=e[0],s=e[1];t=new la(r,s)}return ki(t)};hi("toArray",((e,t)=>da(Array(t).fill(e))));class ca extends ei{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const r=e.getTypeLength(t.node.getNodeType(e));return Xs.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=t.getScope();e.getNodeProperties(s).assign=!0;const i=e.getNodeProperties(this);i.sourceNode=r,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.build(e),a=r.getNodeType(e),o=s.build(e,a),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=n);else if(i){const s=e.getVarFromNode(this,null,a),i=e.getPropertyName(s);e.addLineFlowCode(`${i} = ${o}`,this);const u=r.node,l=u.node.context({assign:!0}).build(e);for(let t=0;t<u.components.length;t++){const r=u.components[t];e.addLineFlowCode(`${l}.${r} = ${i}[ ${t} ]`,this)}"void"!==t&&(d=n)}else d=`${n} = ${o}`,"void"!==t&&"void"!==u||(e.addLineFlowCode(d,this),"void"!==t&&(d=n));return l.initialized=!0,e.format(d,a,t)}}const ha=Hi(ca).setParameterLength(2);hi("assign",ha);class pa extends ei{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(t){const r=[],s=this.functionNode,i=s.getInputs(t),n=this.parameters,a=(e,r)=>{const s=r.type;let i;return i="pointer"===s?"&"+e.build(t):e.build(t,s),i};if(Array.isArray(n)){if(n.length>i.length)e("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),n.length=i.length;else if(n.length<i.length)for(e("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");n.length<i.length;)n.push(rn(0));for(let e=0;e<n.length;e++)r.push(a(n[e],i[e]))}else for(const t of i){const s=n[t.name];void 0!==s?r.push(a(s,t)):(e(`TSL: Input '${t.name}' not found in 'Fn()'.`),r.push(a(rn(0),t)))}return`${s.build(t,"property")}( ${r.join(", ")} )`}}const ga=(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?Wi(t):$i(t[0]),new pa(ki(e),t));hi("call",ga);const ma={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class fa extends ei{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new fa(e,t,r);for(let t=0;t<s.length-1;t++)i=new fa(e,i,s[t]);t=i,r=s[s.length-1]}this.op=e,this.aNode=t,this.bNode=r,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(ma[this.op],t)}getNodeType(e,t=null){const r=this.op,s=this.aNode,i=this.bNode,n=s.getNodeType(e),a=i?i.getNodeType(e):null;if("void"===n||"void"===a)return t||"void";if("%"===r)return n;if("~"===r||"&"===r||"|"===r||"^"===r||">>"===r||"<<"===r)return e.getIntegerType(n);if("!"===r||"&&"===r||"||"===r||"^^"===r)return"bool";if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=s.getNodeType(e),o=i?i.getNodeType(e):null,"<"===r||">"===r||"<="===r||">="===r||"=="===r||"!="===r?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===r||"<<"===r?(a=n,o=e.changeComponentType(o,"uint")):"%"===r?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const u=s.build(e,a),l=i?i.build(e,o):null,d=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===c;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${l} )`,n,t):e.format(`( ${u} ${r} ${l} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${l} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${l} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(d)return e.format(`${d}( ${u}, ${l} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${l} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${l}`,n,t);{let i=`( ${u} ${r} ${l} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return d?e.format(`${d}( ${u}, ${l} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${l} ${r} ${u}`,n,t):e.format(`${u} ${r} ${l}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const ya=qi(fa,"+").setParameterLength(2,1/0).setName("add"),ba=qi(fa,"-").setParameterLength(2,1/0).setName("sub"),xa=qi(fa,"*").setParameterLength(2,1/0).setName("mul"),Ta=qi(fa,"/").setParameterLength(2,1/0).setName("div"),_a=qi(fa,"%").setParameterLength(2).setName("mod"),va=qi(fa,"==").setParameterLength(2).setName("equal"),Na=qi(fa,"!=").setParameterLength(2).setName("notEqual"),Sa=qi(fa,"<").setParameterLength(2).setName("lessThan"),Aa=qi(fa,">").setParameterLength(2).setName("greaterThan"),Ra=qi(fa,"<=").setParameterLength(2).setName("lessThanEqual"),Ea=qi(fa,">=").setParameterLength(2).setName("greaterThanEqual"),wa=qi(fa,"&&").setParameterLength(2,1/0).setName("and"),Ca=qi(fa,"||").setParameterLength(2,1/0).setName("or"),Ma=qi(fa,"!").setParameterLength(1).setName("not"),Ba=qi(fa,"^^").setParameterLength(2).setName("xor"),Pa=qi(fa,"&").setParameterLength(2).setName("bitAnd"),La=qi(fa,"~").setParameterLength(1).setName("bitNot"),Fa=qi(fa,"|").setParameterLength(2).setName("bitOr"),Ia=qi(fa,"^").setParameterLength(2).setName("bitXor"),Da=qi(fa,"<<").setParameterLength(2).setName("shiftLeft"),Ua=qi(fa,">>").setParameterLength(2).setName("shiftRight"),Va=Yi((([e])=>(e.addAssign(1),e))),Oa=Yi((([e])=>(e.subAssign(1),e))),Ga=Yi((([e])=>{const t=sn(e).toConst();return e.addAssign(1),t})),ka=Yi((([e])=>{const t=sn(e).toConst();return e.subAssign(1),t}));hi("add",ya),hi("sub",ba),hi("mul",xa),hi("div",Ta),hi("mod",_a),hi("equal",va),hi("notEqual",Na),hi("lessThan",Sa),hi("greaterThan",Aa),hi("lessThanEqual",Ra),hi("greaterThanEqual",Ea),hi("and",wa),hi("or",Ca),hi("not",Ma),hi("xor",Ba),hi("bitAnd",Pa),hi("bitNot",La),hi("bitOr",Fa),hi("bitXor",Ia),hi("shiftLeft",Da),hi("shiftRight",Ua),hi("incrementBefore",Va),hi("decrementBefore",Oa),hi("increment",Ga),hi("decrement",ka);const za=(e,t)=>(d('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),_a(sn(e),sn(t)));hi("modInt",za);class $a extends ei{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===$a.MAX||e===$a.MIN)&&arguments.length>3){let i=new $a(e,t,r);for(let t=2;t<arguments.length-1;t++)i=new $a(e,i,arguments[t]);t=i,r=arguments[arguments.length-1],s=null}this.method=e,this.aNode=t,this.bNode=r,this.cNode=s,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),r=this.bNode?this.bNode.getNodeType(e):null,s=this.cNode?this.cNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(r)?0:e.getTypeLength(r),a=e.isMatrix(s)?0:e.getTypeLength(s);return i>n&&i>a?t:n>a?r:a>i?s:t}getNodeType(e){const t=this.method;return t===$a.LENGTH||t===$a.DISTANCE||t===$a.DOT?"float":t===$a.CROSS?"vec3":t===$a.ALL||t===$a.ANY?"bool":t===$a.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:r,method:s}=this;let i=null;if(s===$a.ONE_MINUS)i=ba(1,t);else if(s===$a.RECIPROCAL)i=Ta(1,t);else if(s===$a.DIFFERENCE)i=yo(ba(t,r));else if(s===$a.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=mn(cn(n),0):s=mn(cn(s),0);const a=xa(s,n).xyz;i=uo(a)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let r=this.method;const s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,u=e.renderer.coordinateSystem;if(r===$a.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const l=[];return r===$a.CROSS?l.push(n.build(e,s),a.build(e,s)):u===c&&r===$a.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==c||r!==$a.MIN&&r!==$a.MAX?r===$a.REFRACT?l.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===$a.MIX?l.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===h&&r===$a.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==$a.DFDX&&r!==$a.DFDY||(d(`TSL: '${r}' is not supported in the ${e.shaderStage} stage.`),r="/*"+r+"*/"),l.push(n.build(e,i)),null!==a&&l.push(a.build(e,i)),null!==o&&l.push(o.build(e,i))):l.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${l.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}$a.ALL="all",$a.ANY="any",$a.RADIANS="radians",$a.DEGREES="degrees",$a.EXP="exp",$a.EXP2="exp2",$a.LOG="log",$a.LOG2="log2",$a.SQRT="sqrt",$a.INVERSE_SQRT="inversesqrt",$a.FLOOR="floor",$a.CEIL="ceil",$a.NORMALIZE="normalize",$a.FRACT="fract",$a.SIN="sin",$a.COS="cos",$a.TAN="tan",$a.ASIN="asin",$a.ACOS="acos",$a.ATAN="atan",$a.ABS="abs",$a.SIGN="sign",$a.LENGTH="length",$a.NEGATE="negate",$a.ONE_MINUS="oneMinus",$a.DFDX="dFdx",$a.DFDY="dFdy",$a.ROUND="round",$a.RECIPROCAL="reciprocal",$a.TRUNC="trunc",$a.FWIDTH="fwidth",$a.TRANSPOSE="transpose",$a.DETERMINANT="determinant",$a.INVERSE="inverse",$a.EQUALS="equals",$a.MIN="min",$a.MAX="max",$a.STEP="step",$a.REFLECT="reflect",$a.DISTANCE="distance",$a.DIFFERENCE="difference",$a.DOT="dot",$a.CROSS="cross",$a.POW="pow",$a.TRANSFORM_DIRECTION="transformDirection",$a.MIX="mix",$a.CLAMP="clamp",$a.REFRACT="refract",$a.SMOOTHSTEP="smoothstep",$a.FACEFORWARD="faceforward";const Wa=rn(1e-6),Ha=rn(1e6),ja=rn(Math.PI),qa=rn(2*Math.PI),Xa=rn(2*Math.PI),Ka=rn(.5*Math.PI),Ya=qi($a,$a.ALL).setParameterLength(1),Qa=qi($a,$a.ANY).setParameterLength(1),Za=qi($a,$a.RADIANS).setParameterLength(1),Ja=qi($a,$a.DEGREES).setParameterLength(1),eo=qi($a,$a.EXP).setParameterLength(1),to=qi($a,$a.EXP2).setParameterLength(1),ro=qi($a,$a.LOG).setParameterLength(1),so=qi($a,$a.LOG2).setParameterLength(1),io=qi($a,$a.SQRT).setParameterLength(1),no=qi($a,$a.INVERSE_SQRT).setParameterLength(1),ao=qi($a,$a.FLOOR).setParameterLength(1),oo=qi($a,$a.CEIL).setParameterLength(1),uo=qi($a,$a.NORMALIZE).setParameterLength(1),lo=qi($a,$a.FRACT).setParameterLength(1),co=qi($a,$a.SIN).setParameterLength(1),ho=qi($a,$a.COS).setParameterLength(1),po=qi($a,$a.TAN).setParameterLength(1),go=qi($a,$a.ASIN).setParameterLength(1),mo=qi($a,$a.ACOS).setParameterLength(1),fo=qi($a,$a.ATAN).setParameterLength(1,2),yo=qi($a,$a.ABS).setParameterLength(1),bo=qi($a,$a.SIGN).setParameterLength(1),xo=qi($a,$a.LENGTH).setParameterLength(1),To=qi($a,$a.NEGATE).setParameterLength(1),_o=qi($a,$a.ONE_MINUS).setParameterLength(1),vo=qi($a,$a.DFDX).setParameterLength(1),No=qi($a,$a.DFDY).setParameterLength(1),So=qi($a,$a.ROUND).setParameterLength(1),Ao=qi($a,$a.RECIPROCAL).setParameterLength(1),Ro=qi($a,$a.TRUNC).setParameterLength(1),Eo=qi($a,$a.FWIDTH).setParameterLength(1),wo=qi($a,$a.TRANSPOSE).setParameterLength(1),Co=qi($a,$a.DETERMINANT).setParameterLength(1),Mo=qi($a,$a.INVERSE).setParameterLength(1),Bo=(e,t)=>(d('TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),va(e,t)),Po=qi($a,$a.MIN).setParameterLength(2,1/0),Lo=qi($a,$a.MAX).setParameterLength(2,1/0),Fo=qi($a,$a.STEP).setParameterLength(2),Io=qi($a,$a.REFLECT).setParameterLength(2),Do=qi($a,$a.DISTANCE).setParameterLength(2),Uo=qi($a,$a.DIFFERENCE).setParameterLength(2),Vo=qi($a,$a.DOT).setParameterLength(2),Oo=qi($a,$a.CROSS).setParameterLength(2),Go=qi($a,$a.POW).setParameterLength(2),ko=e=>xa(e,e),zo=e=>xa(e,e,e),$o=e=>xa(e,e,e,e),Wo=qi($a,$a.TRANSFORM_DIRECTION).setParameterLength(2),Ho=e=>xa(bo(e),Go(yo(e),1/3)),jo=e=>Vo(e,e),qo=qi($a,$a.MIX).setParameterLength(3),Xo=(e,t=0,r=1)=>ki(new $a($a.CLAMP,ki(e),ki(t),ki(r))),Ko=e=>Xo(e),Yo=qi($a,$a.REFRACT).setParameterLength(3),Qo=qi($a,$a.SMOOTHSTEP).setParameterLength(3),Zo=qi($a,$a.FACEFORWARD).setParameterLength(3),Jo=Yi((([e])=>{const t=Vo(e.xy,on(12.9898,78.233)),r=_a(t,ja);return lo(co(r).mul(43758.5453))})),eu=(e,t,r)=>qo(t,r,e),tu=(e,t,r)=>Qo(t,r,e),ru=(e,t)=>Fo(t,e),su=(e,t)=>(d('TSL: "atan2" is overloaded. Use "atan" instead.'),fo(e,t)),iu=Zo,nu=no;hi("all",Ya),hi("any",Qa),hi("equals",Bo),hi("radians",Za),hi("degrees",Ja),hi("exp",eo),hi("exp2",to),hi("log",ro),hi("log2",so),hi("sqrt",io),hi("inverseSqrt",no),hi("floor",ao),hi("ceil",oo),hi("normalize",uo),hi("fract",lo),hi("sin",co),hi("cos",ho),hi("tan",po),hi("asin",go),hi("acos",mo),hi("atan",fo),hi("abs",yo),hi("sign",bo),hi("length",xo),hi("lengthSq",jo),hi("negate",To),hi("oneMinus",_o),hi("dFdx",vo),hi("dFdy",No),hi("round",So),hi("reciprocal",Ao),hi("trunc",Ro),hi("fwidth",Eo),hi("atan2",su),hi("min",Po),hi("max",Lo),hi("step",ru),hi("reflect",Io),hi("distance",Do),hi("dot",Vo),hi("cross",Oo),hi("pow",Go),hi("pow2",ko),hi("pow3",zo),hi("pow4",$o),hi("transformDirection",Wo),hi("mix",eu),hi("clamp",Xo),hi("refract",Yo),hi("smoothstep",tu),hi("faceForward",Zo),hi("difference",Uo),hi("saturate",Ko),hi("cbrt",Ho),hi("transpose",wo),hi("determinant",Co),hi("inverse",Mo),hi("rand",Jo);class au extends Qs{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}getNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const s=t.getNodeType(e);if(null!==r){const t=r.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(s))return t}return s}setup(e){const t=this.condNode,r=this.ifNode.isolate(),s=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?r:r.context({nodeBlock:r}),a.elseNode=s?n?s:s.context({nodeBlock:s}):null}generate(e,t){const r=this.getNodeType(e),s=e.getDataFromNode(this);if(void 0!==s.nodeProperty)return s.nodeProperty;const{condNode:i,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,u="void"!==t,l=u?An(r).build(e):"";s.nodeProperty=l;const c=i.build(e,"bool");if(e.context.uniformFlow&&null!==a){const s=n.build(e,r),i=a.build(e,r),o=e.getTernary(c,s,i);return e.format(o,r,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=n.build(e,r);if(h&&(u?h=l+" = "+h+";":(h="return "+h+";",null===o&&(d("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),h="// "+h))),e.removeFlowTab().addFlowCode(e.tab+"\t"+h+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(d("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const ou=Hi(au).setParameterLength(2,3);hi("select",ou);class uu extends Qs{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const r=e.addContext(this.value),s=this.node.build(e,t);return e.setContext(r),s}}const lu=Hi(uu).setParameterLength(1,2),du=e=>lu(e,{uniformFlow:!0}),cu=(e,t)=>lu(e,{nodeName:t});function hu(e,t){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),cu(e,t)}hi("context",lu),hi("label",hu),hi("uniformFlow",du),hi("setName",cu);class pu extends Qs{static get type(){return"VarNode"}constructor(e,t=null,r=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=r,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){let t=e.getNodeProperties(this).assign;if(!0!==t&&this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&e.fnCall&&e.fnCall.shaderNode){e.getDataFromNode(this.node.shaderNode).hasLoop&&(t=!0)}return t}build(...e){const t=e[0];return!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)&&t.getBaseStack().addToStack(this),!0===this.intent&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(t){const{node:r,name:s,readOnly:i}=this,{renderer:n}=t,a=!0===n.backend.isWebGPUBackend;let o=!1,u=!1;i&&(o=t.isDeterministic(r),u=a?i:o);const l=this.getNodeType(t);if("void"==l){!0!==this.intent&&e('TSL: ".toVar()" can not be used with void type.');return r.build(t)}const d=t.getVectorType(l),c=r.build(t,d),h=t.getVarFromNode(this,s,d,void 0,u),p=t.getPropertyName(h);let g=p;if(u)if(a)g=o?`const ${p}`:`let ${p}`;else{const e=r.getArrayCount(t);g=`const ${t.getVar(h.type,p,e)}`}return t.addLineFlowCode(`${g} = ${c}`,this),p}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const gu=Hi(pu),mu=(e,t=null)=>gu(e,t).toStack(),fu=(e,t=null)=>gu(e,t,!0).toStack(),yu=e=>gu(e).setIntent(!0).toStack();hi("toVar",mu),hi("toConst",fu),hi("toVarIntent",yu);class bu extends Qs{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const r=this.node.build(e,...t);return e.removeSubBuild(),r}}const xu=(e,t,r=null)=>ki(new bu(ki(e),t,r));class Tu extends Qs{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let r=t.varying;if(void 0===r){const s=this.name,i=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=r=e.getVaryingFromNode(this,s,i,n,a),t.node=xu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(ks.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(ks.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),r=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===r[t]){const i=this.getNodeType(e),n=e.getPropertyName(s,ks.VERTEX);e.flowNodeFromShaderStage(ks.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const _u=Hi(Tu).setParameterLength(1,2),vu=e=>_u(e);hi("toVarying",_u),hi("toVertexStage",vu),hi("varying",((...e)=>(d("TSL: .varying() has been renamed to .toVarying()."),_u(...e)))),hi("vertexStage",((...e)=>(d("TSL: .vertexStage() has been renamed to .toVertexStage()."),_u(...e))));const Nu=Yi((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return qo(t,r,s)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Su=Yi((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return qo(t,r,s)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Au="WorkingColorSpace";class Ru extends ei{static get type(){return"ColorSpaceNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.source=t,this.target=r}resolveColorSpace(e,t){return t===Au?p.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,r=this.resolveColorSpace(e,this.source),s=this.resolveColorSpace(e,this.target);let i=t;return!1!==p.enabled&&r!==s&&r&&s?(p.getTransfer(r)===g&&(i=mn(Nu(i.rgb),i.a)),p.getPrimaries(r)!==p.getPrimaries(s)&&(i=mn(Tn(p._getMatrix(new a,r,s)).mul(i.rgb),i.a)),p.getTransfer(s)===g&&(i=mn(Su(i.rgb),i.a)),i):i}}const Eu=(e,t)=>ki(new Ru(ki(e),Au,t)),wu=(e,t)=>ki(new Ru(ki(e),t,Au));hi("workingToColorSpace",Eu),hi("colorSpaceToWorking",wu);let Cu=class extends Zs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class Mu extends Qs{static get type(){return"ReferenceBaseNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.updateType=zs.OBJECT}setGroup(e){return this.group=e,this}element(e){return ki(new Cu(this,ki(e)))}setNodeType(e){const t=ua(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;e<t.length;e++)r=r[t[e]];return r}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}class Bu extends Mu{static get type(){return"RendererReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.renderer=r,this.setGroup(na)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const Pu=(e,t,r=null)=>ki(new Bu(e,t,r));class Lu extends ei{static get type(){return"ToneMappingNode"}constructor(e,t=Iu,r=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Es(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(t){const r=this.colorNode||t.context.color,s=this._toneMapping;if(s===m)return r;let i=null;const n=t.renderer.library.getToneMappingFunction(s);return null!==n?i=mn(n(r.rgb,this.exposureNode),r.a):(e("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=r),i}}const Fu=(e,t,r)=>ki(new Lu(e,ki(t),ki(r))),Iu=Pu("toneMappingExposure","float");hi("toneMapping",((e,t,r)=>Fu(t,r,e)));class Du extends ai{static get type(){return"BufferAttributeNode"}constructor(e,t=null,r=0,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=r,this.bufferOffset=s,this.usage=f,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),r=this.value,s=e.getTypeLength(t),i=this.bufferStride||s,n=this.bufferOffset,a=!0===r.isInterleavedBuffer?r:new y(r,i),o=new x(a,s,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),r=e.getBufferAttributeFromNode(this,t),s=e.getPropertyName(r);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=s,i=s;else{i=_u(this).build(e,t)}return i}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}const Uu=(e,t=null,r=0,s=0)=>ki(new Du(e,t,r,s)),Vu=(e,t=null,r=0,s=0)=>Uu(e,t,r,s).setUsage(b),Ou=(e,t=null,r=0,s=0)=>Uu(e,t,r,s).setInstanced(!0),Gu=(e,t=null,r=0,s=0)=>Vu(e,t,r,s).setInstanced(!0);hi("toAttribute",(e=>Uu(e.value)));class ku extends Qs{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=zs.OBJECT,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:r}=e;if("compute"===r){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const r=e.getNodeProperties(this).outputComputeNode;if(r)return r.build(e,t)}}}const zu=(t,r=[64])=>{(0===r.length||r.length>3)&&e("TSL: compute() workgroupSize must have 1, 2, or 3 elements");for(let t=0;t<r.length;t++){const s=r[t];("number"!=typeof s||s<=0||!Number.isInteger(s))&&e(`TSL: compute() workgroupSize element at index [ ${t} ] must be a positive integer`)}for(;r.length<3;)r.push(1);return ki(new ku(ki(t),r))},$u=(e,t,r)=>zu(e,r).setCount(t);hi("compute",$u),hi("computeKernel",zu);class Wu extends Qs{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const s=this.node.getNodeType(e);return e.setCache(t),s}build(e,...t){const r=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.build(e,...t);return e.setCache(r),i}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const Hu=e=>new Wu(ki(e));function ju(e,t=!0){return d('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),Hu(e).setParent(t)}hi("cache",ju),hi("isolate",Hu);class qu extends Qs{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Xu=Hi(qu).setParameterLength(2);hi("bypass",Xu);class Ku extends Qs{static get type(){return"RemapNode"}constructor(e,t,r,s=rn(0),i=rn(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=r,this.outLowNode=s,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:r,outLowNode:s,outHighNode:i,doClamp:n}=this;let a=e.sub(t).div(r.sub(t));return!0===n&&(a=a.clamp()),a.mul(i.sub(s)).add(s)}}const Yu=Hi(Ku,null,null,{doClamp:!1}).setParameterLength(3,5),Qu=Hi(Ku).setParameterLength(3,5);hi("remap",Yu),hi("remapClamp",Qu);class Zu extends Qs{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const r=this.getNodeType(e),s=this.snippet;if("void"!==r)return e.format(s,r,t);e.addLineFlowCode(s,this)}}const Ju=Hi(Zu).setParameterLength(1,2),el=e=>(e?ou(e,Ju("discard")):Ju("discard")).toStack();hi("discard",el);class tl extends ei{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||m,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||T;return r!==m&&(t=t.toneMapping(r)),s!==T&&s!==p.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const rl=(e,t=null,r=null)=>ki(new tl(ki(e),t,r));hi("renderOutput",rl);class sl extends ei{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,r=this.node.build(e),s="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(s.length);let n="";return n+="// #"+s+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+r+" /* ... */\n",n+="// #"+i+"#\n",null!==t?t(e,n):_(n),r}}const il=(e,t=null)=>ki(new sl(ki(e),t)).toStack();hi("debug",il);class nl{constructor(){this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class al extends Qs{static get type(){return"InspectorNode"}constructor(e,t="",r=null){super(),this.node=e,this.name=t,this.callback=r,this.updateType=zs.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==nl&&v('TSL: ".toInspector()" is only available with WebGPU.'),t}}function ol(e,t="",r=null){return(e=ki(e)).before(new al(e,t,r))}hi("toInspector",ol);class ul extends Qs{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const r=this.getAttributeName(e);if(e.hasGeometryAttribute(r)){const s=e.geometry.getAttribute(r);t=e.getTypeFromAttribute(s)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),r=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const s=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(s),n=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(n.name,i,r);return _u(this).build(e,r)}return d(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(r)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const ll=(e,t=null)=>ki(new ul(e,t)),dl=(e=0)=>ll("uv"+(e>0?e:""),"vec2");class cl extends Qs{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const r=this.textureNode.build(e,"property"),s=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${r}, ${s} )`,this.getNodeType(e),t)}}const hl=Hi(cl).setParameterLength(1,2);class pl extends oa{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=zs.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,r=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(r&&void 0!==r.width){const{width:e,height:t}=r;this.value=Math.log2(Math.max(e,t))}}}const gl=Hi(pl).setParameterLength(1),ml=new R;class fl extends oa{static get type(){return"TextureNode"}constructor(e=ml,t=null,r=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=r,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=zs.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===N?"uvec4":this.value.type===S?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return dl(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=ua(this.value.matrix)),this._matrixUniform.mul(cn(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=ua(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(sn(hl(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");const s=Yi((()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?zs.OBJECT:zs.NONE,t}))();let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;let d;return d=i?e.generateTextureBias(l,t,r,i,n,u):o?e.generateTextureGrad(l,t,r,o,n,u):a?e.generateTextureCompare(l,t,r,a,n,u):!1===this.sampler?e.generateTextureLoad(l,t,r,s,n,u):s?e.generateTextureLevel(l,t,r,s,n,u):e.generateTexture(l,t,r,n,u),d}generate(e,t){const r=this.value,s=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this);let a=n.propertyName;if(void 0===a){const{uvNode:t,levelNode:r,biasNode:o,compareNode:u,depthNode:l,gradNode:d,offsetNode:c}=s,h=this.generateUV(e,t),p=r?r.build(e,"float"):null,g=o?o.build(e,"float"):null,m=l?l.build(e,"int"):null,f=u?u.build(e,"float"):null,y=d?[d[0].build(e,"vec2"),d[1].build(e,"vec2")]:null,b=c?this.generateOffset(e,c):null,x=e.getVarFromNode(this);a=e.getPropertyName(x);const T=this.generateSnippet(e,i,h,p,g,m,f,y,b);e.addLineFlowCode(`${a} = ${T}`,this),n.snippet=T,n.propertyName=a}let o=a;const u=this.getNodeType(e);return e.needsToWorkingColorSpace(r)&&(o=wu(Ju(o,u),r.colorSpace).setup(e).build(e,u)),e.format(o,u,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return d("TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=ki(e),t.referenceNode=this.getBase(),ki(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=ki(e).mul(gl(t)),t.referenceNode=this.getBase();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===A||r.magFilter===A)&&(d("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),ki(t)}level(e){const t=this.clone();return t.levelNode=ki(e),t.referenceNode=this.getBase(),ki(t)}size(e){return hl(this,e)}bias(e){const t=this.clone();return t.biasNode=ki(e),t.referenceNode=this.getBase(),ki(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=ki(e),t.referenceNode=this.getBase(),ki(t)}grad(e,t){const r=this.clone();return r.gradNode=[ki(e),ki(t)],r.referenceNode=this.getBase(),ki(r)}depth(e){const t=this.clone();return t.depthNode=ki(e),t.referenceNode=this.getBase(),ki(t)}offset(e){const t=this.clone();return t.offsetNode=ki(e),t.referenceNode=this.getBase(),ki(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const r=this._flipYUniform;null!==r&&(r.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const yl=Hi(fl).setParameterLength(1,4).setName("texture"),bl=(e=ml,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=ki(e.clone()),i.referenceNode=e.getBase(),null!==t&&(i.uvNode=ki(t)),null!==r&&(i.levelNode=ki(r)),null!==s&&(i.biasNode=ki(s))):i=yl(e,t,r,s),i},xl=(...e)=>bl(...e).setSampler(!1);class Tl extends oa{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const _l=(e,t,r)=>ki(new Tl(e,t,r));class vl extends Zs{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(),s=this.node.getPaddedType();return e.format(t,s,r)}}class Nl extends Tl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Is(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=zs.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;r<e.length;r++){t[4*r]=e[r]}else if("color"===r)for(let r=0;r<e.length;r++){const s=4*r,i=e[r];t[s]=i.r,t[s+1]=i.g,t[s+2]=i.b||0}else if("mat2"===r)for(let r=0;r<e.length;r++){const s=4*r,i=e[r];t[s]=i.elements[0],t[s+1]=i.elements[1],t[s+2]=i.elements[2],t[s+3]=i.elements[3]}else if("mat3"===r)for(let r=0;r<e.length;r++){const s=16*r,i=e[r];t[s]=i.elements[0],t[s+1]=i.elements[1],t[s+2]=i.elements[2],t[s+4]=i.elements[3],t[s+5]=i.elements[4],t[s+6]=i.elements[5],t[s+8]=i.elements[6],t[s+9]=i.elements[7],t[s+10]=i.elements[8],t[s+15]=1}else if("mat4"===r)for(let r=0;r<e.length;r++){const s=16*r,i=e[r];for(let e=0;e<i.elements.length;e++)t[s+e]=i.elements[e]}else for(let r=0;r<e.length;r++){const s=4*r,i=e[r];t[s]=i.x,t[s+1]=i.y,t[s+2]=i.z||0,t[s+3]=i.w||0}}setup(e){const t=this.array.length,r=this.elementType;let s=Float32Array;const i=this.paddedType,n=e.getTypeLength(i);return"i"===r.charAt(0)&&(s=Int32Array),"u"===r.charAt(0)&&(s=Uint32Array),this.value=new s(t*n),this.bufferCount=t,this.bufferType=i,super.setup(e)}element(e){return ki(new vl(this,ki(e)))}}const Sl=(e,t)=>ki(new Nl(e,t));const Al=Hi(class extends Qs{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let Rl,El;class wl extends Qs{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===wl.DPR?"float":this.scope===wl.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=zs.NONE;return this.scope!==wl.SIZE&&this.scope!==wl.VIEWPORT&&this.scope!==wl.DPR||(e=zs.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===wl.VIEWPORT?null!==t?El.copy(t.viewport):(e.getViewport(El),El.multiplyScalar(e.getPixelRatio())):this.scope===wl.DPR?this._output.value=e.getPixelRatio():null!==t?(Rl.width=t.width,Rl.height=t.height):e.getDrawingBufferSize(Rl)}setup(){const e=this.scope;let t=null;return t=e===wl.SIZE?ua(Rl||(Rl=new r)):e===wl.VIEWPORT?ua(El||(El=new i)):e===wl.DPR?ua(1):on(Pl.div(Bl)),this._output=t,t}generate(e){if(this.scope===wl.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(Bl).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}wl.COORDINATE="coordinate",wl.VIEWPORT="viewport",wl.SIZE="size",wl.UV="uv",wl.DPR="dpr";const Cl=ji(wl,wl.DPR),Ml=ji(wl,wl.UV),Bl=ji(wl,wl.SIZE),Pl=ji(wl,wl.COORDINATE),Ll=ji(wl,wl.VIEWPORT),Fl=Ll.zw,Il=Pl.sub(Ll.xy),Dl=Il.div(Fl),Ul=Yi((()=>(d('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),Bl)),"vec2").once()(),Vl=ua(0,"uint").setName("u_cameraIndex").setGroup(sa("cameraIndex")).toVarying("v_cameraIndex"),Ol=ua("float").setName("cameraNear").setGroup(na).onRenderUpdate((({camera:e})=>e.near)),Gl=ua("float").setName("cameraFar").setGroup(na).onRenderUpdate((({camera:e})=>e.far)),kl=Yi((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);t=Sl(r).setGroup(na).setName("cameraProjectionMatrices").element(e.isMultiViewCamera?Al("gl_ViewID_OVR"):Vl).toConst("cameraProjectionMatrix")}else t=ua("mat4").setName("cameraProjectionMatrix").setGroup(na).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),zl=Yi((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);t=Sl(r).setGroup(na).setName("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?Al("gl_ViewID_OVR"):Vl).toConst("cameraProjectionMatrixInverse")}else t=ua("mat4").setName("cameraProjectionMatrixInverse").setGroup(na).onRenderUpdate((({camera:e})=>e.projectionMatrixInverse));return t})).once()(),$l=Yi((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);t=Sl(r).setGroup(na).setName("cameraViewMatrices").element(e.isMultiViewCamera?Al("gl_ViewID_OVR"):Vl).toConst("cameraViewMatrix")}else t=ua("mat4").setName("cameraViewMatrix").setGroup(na).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),Wl=Yi((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorld);t=Sl(r).setGroup(na).setName("cameraWorldMatrices").element(e.isMultiViewCamera?Al("gl_ViewID_OVR"):Vl).toConst("cameraWorldMatrix")}else t=ua("mat4").setName("cameraWorldMatrix").setGroup(na).onRenderUpdate((({camera:e})=>e.matrixWorld));return t})).once()(),Hl=Yi((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.normalMatrix);t=Sl(r).setGroup(na).setName("cameraNormalMatrices").element(e.isMultiViewCamera?Al("gl_ViewID_OVR"):Vl).toConst("cameraNormalMatrix")}else t=ua("mat3").setName("cameraNormalMatrix").setGroup(na).onRenderUpdate((({camera:e})=>e.normalMatrix));return t})).once()(),jl=Yi((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(let t=0,i=e.cameras.length;t<i;t++)r.push(new s);const i=Sl(r).setGroup(na).setName("cameraPositions").onRenderUpdate((({camera:e},t)=>{const r=e.cameras,s=t.array;for(let e=0,t=r.length;e<t;e++)s[e].setFromMatrixPosition(r[e].matrixWorld)}));t=i.element(e.isMultiViewCamera?Al("gl_ViewID_OVR"):Vl).toConst("cameraPosition")}else t=ua(new s).setName("cameraPosition").setGroup(na).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)));return t})).once()(),ql=Yi((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.viewport);t=Sl(r,"vec4").setGroup(na).setName("cameraViewports").element(Vl).toConst("cameraViewport")}else t=mn(0,0,Bl.x,Bl.y).toConst("cameraViewport");return t})).once()(),Xl=new E;class Kl extends Qs{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=zs.OBJECT,this.uniformNode=new oa(null)}getNodeType(){const e=this.scope;return e===Kl.WORLD_MATRIX?"mat4":e===Kl.POSITION||e===Kl.VIEW_POSITION||e===Kl.DIRECTION||e===Kl.SCALE?"vec3":e===Kl.RADIUS?"float":void 0}update(e){const t=this.object3d,r=this.uniformNode,i=this.scope;if(i===Kl.WORLD_MATRIX)r.value=t.matrixWorld;else if(i===Kl.POSITION)r.value=r.value||new s,r.value.setFromMatrixPosition(t.matrixWorld);else if(i===Kl.SCALE)r.value=r.value||new s,r.value.setFromMatrixScale(t.matrixWorld);else if(i===Kl.DIRECTION)r.value=r.value||new s,t.getWorldDirection(r.value);else if(i===Kl.VIEW_POSITION){const i=e.camera;r.value=r.value||new s,r.value.setFromMatrixPosition(t.matrixWorld),r.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Kl.RADIUS){const s=e.object.geometry;null===s.boundingSphere&&s.computeBoundingSphere(),Xl.copy(s.boundingSphere).applyMatrix4(t.matrixWorld),r.value=Xl.radius}}generate(e){const t=this.scope;return t===Kl.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Kl.POSITION||t===Kl.VIEW_POSITION||t===Kl.DIRECTION||t===Kl.SCALE?this.uniformNode.nodeType="vec3":t===Kl.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Kl.WORLD_MATRIX="worldMatrix",Kl.POSITION="position",Kl.SCALE="scale",Kl.VIEW_POSITION="viewPosition",Kl.DIRECTION="direction",Kl.RADIUS="radius";const Yl=Hi(Kl,Kl.DIRECTION).setParameterLength(1),Ql=Hi(Kl,Kl.WORLD_MATRIX).setParameterLength(1),Zl=Hi(Kl,Kl.POSITION).setParameterLength(1),Jl=Hi(Kl,Kl.SCALE).setParameterLength(1),ed=Hi(Kl,Kl.VIEW_POSITION).setParameterLength(1),td=Hi(Kl,Kl.RADIUS).setParameterLength(1);class rd extends Kl{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const sd=ji(rd,rd.DIRECTION),id=ji(rd,rd.WORLD_MATRIX),nd=ji(rd,rd.POSITION),ad=ji(rd,rd.SCALE),od=ji(rd,rd.VIEW_POSITION),ud=ji(rd,rd.RADIUS),ld=ua(new a).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),dd=ua(new o).onObjectUpdate((({object:e},t)=>t.value.copy(e.matrixWorld).invert())),cd=Yi((e=>e.renderer.overrideNodes.modelViewMatrix||hd)).once()().toVar("modelViewMatrix"),hd=$l.mul(id),pd=Yi((e=>(e.context.isHighPrecisionModelViewMatrix=!0,ua("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highpModelViewMatrix"),gd=Yi((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return ua("mat3").onObjectUpdate((({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highpModelNormalViewMatrix"),md=ll("position","vec3"),fd=md.toVarying("positionLocal"),yd=md.toVarying("positionPrevious"),bd=Yi((e=>id.mul(fd).xyz.toVarying(e.getSubBuildProperty("v_positionWorld"))),"vec3").once(["POSITION"])(),xd=Yi((()=>fd.transformDirection(id).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection")),"vec3").once(["POSITION"])(),Td=Yi((e=>e.context.setupPositionView().toVarying("v_positionView")),"vec3").once(["POSITION"])(),_d=Yi((e=>{let t;return t=e.camera.isOrthographicCamera?cn(0,0,1):Td.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")}),"vec3").once(["POSITION"])();class vd extends Qs{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return t.side===w?"false":e.getFrontFacing()}}const Nd=ji(vd),Sd=rn(Nd).mul(2).sub(1),Ad=Yi((([e],{material:t})=>{const r=t.side;return r===w?e=e.mul(-1):r===C&&(e=e.mul(Sd)),e})),Rd=ll("normal","vec3"),Ed=Yi((e=>!1===e.geometry.hasAttribute("normal")?(d('TSL: Vertex attribute "normal" not found on geometry.'),cn(0,1,0)):Rd),"vec3").once()().toVar("normalLocal"),wd=Td.dFdx().cross(Td.dFdy()).normalize().toVar("normalFlat"),Cd=Yi((e=>{let t;return t=!0===e.material.flatShading?wd:Id(Ed).toVarying("v_normalViewGeometry").normalize(),t}),"vec3").once()().toVar("normalViewGeometry"),Md=Yi((e=>{let t=Cd.transformDirection($l);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")}),"vec3").once()(),Bd=Yi((({subBuildFn:e,material:t,context:r})=>{let s;return"NORMAL"===e||"VERTEX"===e?(s=Cd,!0!==t.flatShading&&(s=Ad(s))):s=r.setupNormal().context({getUV:null}),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Pd=Bd.transformDirection($l).toVar("normalWorld"),Ld=Yi((({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Bd:t.setupClearcoatNormal().context({getUV:null}),r}),"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Fd=Yi((([e,t=id])=>{const r=Tn(t),s=e.div(cn(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz})),Id=Yi((([e],t)=>{const r=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==r)return r.transformDirection(e);const s=ld.mul(e);return $l.transformDirection(s)})),Dd=Yi((()=>(d('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Bd))).once(["NORMAL","VERTEX"])(),Ud=Yi((()=>(d('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Pd))).once(["NORMAL","VERTEX"])(),Vd=Yi((()=>(d('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Ld))).once(["NORMAL","VERTEX"])(),Od=new M,Gd=new o,kd=ua(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),zd=ua(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),$d=ua(new o).onReference((function(e){return e.material})).onObjectUpdate((function({material:e,scene:t}){const r=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return r?(Od.copy(r),Gd.makeRotationFromEuler(Od)):Gd.identity(),Gd})),Wd=_d.negate().reflect(Bd),Hd=_d.negate().refract(Bd,kd),jd=Wd.transformDirection($l).toVar("reflectVector"),qd=Hd.transformDirection($l).toVar("reflectVector"),Xd=new L;class Kd extends fl{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const t=this.value;return t.mapping===B?jd:t.mapping===P?qd:(e('CubeTextureNode: Mapping "%s" not supported.',t.mapping),cn(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return e.renderer.coordinateSystem!==h&&r.isRenderTargetTexture||(t=cn(t.x.negate(),t.yz)),$d.mul(t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const Yd=Hi(Kd).setParameterLength(1,4).setName("cubeTexture"),Qd=(e=Xd,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=ki(e.clone()),i.referenceNode=e,null!==t&&(i.uvNode=ki(t)),null!==r&&(i.levelNode=ki(r)),null!==s&&(i.biasNode=ki(s))):i=Yd(e,t,r,s),i};class Zd extends Zs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}}class Jd extends Qs{static get type(){return"ReferenceNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.name=null,this.updateType=zs.OBJECT}element(e){return ki(new Zd(this,ki(e)))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?_l(null,e,this.count):Array.isArray(this.getValueFromReference())?Sl(null,e):"texture"===e?bl(null):"cubeTexture"===e?Qd(null):ua(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;e<t.length;e++)r=r[t[e]];return r}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const ec=(e,t,r)=>ki(new Jd(e,t,r)),tc=(e,t,r,s)=>ki(new Jd(e,t,s,r));class rc extends Jd{static get type(){return"MaterialReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.material=r,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const sc=(e,t,r=null)=>ki(new rc(e,t,r)),ic=dl(),nc=Td.dFdx(),ac=Td.dFdy(),oc=ic.dFdx(),uc=ic.dFdy(),lc=Bd,dc=ac.cross(lc),cc=lc.cross(nc),hc=dc.mul(oc.x).add(cc.mul(uc.x)),pc=dc.mul(oc.y).add(cc.mul(uc.y)),gc=hc.dot(hc).max(pc.dot(pc)),mc=gc.equal(0).select(0,gc.inverseSqrt()),fc=hc.mul(mc).toVar("tangentViewFrame"),yc=pc.mul(mc).toVar("bitangentViewFrame"),bc=Yi((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),ll("tangent","vec4"))))(),xc=bc.xyz.toVar("tangentLocal"),Tc=Yi((({subBuildFn:e,geometry:t,material:r})=>{let s;return s="VERTEX"===e||t.hasAttribute("tangent")?cd.mul(mn(xc,0)).xyz.toVarying("v_tangentView").normalize():fc,!0!==r.flatShading&&(s=Ad(s)),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),_c=Tc.transformDirection($l).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),vc=Yi((([e,t],{subBuildFn:r,material:s})=>{let i=e.mul(bc.w).xyz;return"NORMAL"===r&&!0!==s.flatShading&&(i=i.toVarying(t)),i})).once(["NORMAL"]),Nc=vc(Rd.cross(bc),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Sc=vc(Ed.cross(xc),"v_bitangentLocal").normalize().toVar("bitangentLocal"),Ac=Yi((({subBuildFn:e,geometry:t,material:r})=>{let s;return s="VERTEX"===e||t.hasAttribute("tangent")?vc(Bd.cross(Tc),"v_bitangentView").normalize():yc,!0!==r.flatShading&&(s=Ad(s)),s}),"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Rc=vc(Pd.cross(_c),"v_bitangentWorld").normalize().toVar("bitangentWorld"),Ec=Tn(Tc,Ac,Bd).toVar("TBNViewMatrix"),wc=_d.mul(Ec),Cc=Yi((()=>{let e=kn.cross(_d);return e=e.cross(kn).normalize(),e=qo(e,Bd,On.mul(Cn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})).once()();class Mc extends ei{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=F}setup({material:t}){const{normalMapType:r,scaleNode:s}=this;let i=this.node.mul(2).sub(1);if(null!==s){let e=s;!0===t.flatShading&&(e=Ad(e)),i=cn(i.xy.mul(e),i.z)}let n=null;return r===I?n=Id(i):r===F?n=Ec.mul(i).normalize():(e(`NodeMaterial: Unsupported normal map type: ${r}`),n=Bd),n}}const Bc=Hi(Mc).setParameterLength(1,2),Pc=Yi((({textureNode:e,bumpScale:t})=>{const r=t=>e.isolate().context({getUV:e=>t(e.uvNode||dl()),forceUVContext:!0}),s=rn(r((e=>e)));return on(rn(r((e=>e.add(e.dFdx())))).sub(s),rn(r((e=>e.add(e.dFdy())))).sub(s)).mul(t)})),Lc=Yi((e=>{const{surf_pos:t,surf_norm:r,dHdxy:s}=e,i=t.dFdx().normalize(),n=r,a=t.dFdy().normalize().cross(n),o=n.cross(i),u=i.dot(a).mul(Sd),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()}));class Fc extends ei{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Pc({textureNode:this.textureNode,bumpScale:e});return Lc({surf_pos:Td,surf_norm:Bd,dHdxy:t})}}const Ic=Hi(Fc).setParameterLength(1,2),Dc=new Map;class Uc extends Qs{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=Dc.get(e);return void 0===r&&(r=sc(e,t),Dc.set(e,r)),r}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,r=this.scope;let s=null;if(r===Uc.COLOR){const e=void 0!==t.color?this.getColor(r):cn();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Uc.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Uc.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:rn(1);else if(r===Uc.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Uc.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Uc.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Uc.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Uc.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(r).mul(e);s=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(r)):i}else if(r===Uc.NORMAL)t.normalMap?(s=Bc(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType):s=t.bumpMap?Ic(this.getTexture("bump").r,this.getFloat("bumpScale")):Bd;else if(r===Uc.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Uc.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Uc.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Bc(this.getTexture(r),this.getCache(r+"Scale","vec2")):Bd;else if(r===Uc.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));s=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(r===Uc.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(.07,1)}else if(r===Uc.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=xn(_h.x,_h.y,_h.y.negate(),_h.x).mul(e.rg.mul(2).sub(on(1)).normalize().mul(e.b))}else s=_h;else if(r===Uc.IRIDESCENCE_THICKNESS){const e=ec("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=ec("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Uc.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Uc.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Uc.IOR)s=this.getFloat(r);else if(r===Uc.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===Uc.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===Uc.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):rn(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Uc.ALPHA_TEST="alphaTest",Uc.COLOR="color",Uc.OPACITY="opacity",Uc.SHININESS="shininess",Uc.SPECULAR="specular",Uc.SPECULAR_STRENGTH="specularStrength",Uc.SPECULAR_INTENSITY="specularIntensity",Uc.SPECULAR_COLOR="specularColor",Uc.REFLECTIVITY="reflectivity",Uc.ROUGHNESS="roughness",Uc.METALNESS="metalness",Uc.NORMAL="normal",Uc.CLEARCOAT="clearcoat",Uc.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Uc.CLEARCOAT_NORMAL="clearcoatNormal",Uc.EMISSIVE="emissive",Uc.ROTATION="rotation",Uc.SHEEN="sheen",Uc.SHEEN_ROUGHNESS="sheenRoughness",Uc.ANISOTROPY="anisotropy",Uc.IRIDESCENCE="iridescence",Uc.IRIDESCENCE_IOR="iridescenceIOR",Uc.IRIDESCENCE_THICKNESS="iridescenceThickness",Uc.IOR="ior",Uc.TRANSMISSION="transmission",Uc.THICKNESS="thickness",Uc.ATTENUATION_DISTANCE="attenuationDistance",Uc.ATTENUATION_COLOR="attenuationColor",Uc.LINE_SCALE="scale",Uc.LINE_DASH_SIZE="dashSize",Uc.LINE_GAP_SIZE="gapSize",Uc.LINE_WIDTH="linewidth",Uc.LINE_DASH_OFFSET="dashOffset",Uc.POINT_SIZE="size",Uc.DISPERSION="dispersion",Uc.LIGHT_MAP="light",Uc.AO="ao";const Vc=ji(Uc,Uc.ALPHA_TEST),Oc=ji(Uc,Uc.COLOR),Gc=ji(Uc,Uc.SHININESS),kc=ji(Uc,Uc.EMISSIVE),zc=ji(Uc,Uc.OPACITY),$c=ji(Uc,Uc.SPECULAR),Wc=ji(Uc,Uc.SPECULAR_INTENSITY),Hc=ji(Uc,Uc.SPECULAR_COLOR),jc=ji(Uc,Uc.SPECULAR_STRENGTH),qc=ji(Uc,Uc.REFLECTIVITY),Xc=ji(Uc,Uc.ROUGHNESS),Kc=ji(Uc,Uc.METALNESS),Yc=ji(Uc,Uc.NORMAL),Qc=ji(Uc,Uc.CLEARCOAT),Zc=ji(Uc,Uc.CLEARCOAT_ROUGHNESS),Jc=ji(Uc,Uc.CLEARCOAT_NORMAL),eh=ji(Uc,Uc.ROTATION),th=ji(Uc,Uc.SHEEN),rh=ji(Uc,Uc.SHEEN_ROUGHNESS),sh=ji(Uc,Uc.ANISOTROPY),ih=ji(Uc,Uc.IRIDESCENCE),nh=ji(Uc,Uc.IRIDESCENCE_IOR),ah=ji(Uc,Uc.IRIDESCENCE_THICKNESS),oh=ji(Uc,Uc.TRANSMISSION),uh=ji(Uc,Uc.THICKNESS),lh=ji(Uc,Uc.IOR),dh=ji(Uc,Uc.ATTENUATION_DISTANCE),ch=ji(Uc,Uc.ATTENUATION_COLOR),hh=ji(Uc,Uc.LINE_SCALE),ph=ji(Uc,Uc.LINE_DASH_SIZE),gh=ji(Uc,Uc.LINE_GAP_SIZE),mh=ji(Uc,Uc.LINE_WIDTH),fh=ji(Uc,Uc.LINE_DASH_OFFSET),yh=ji(Uc,Uc.POINT_SIZE),bh=ji(Uc,Uc.DISPERSION),xh=ji(Uc,Uc.LIGHT_MAP),Th=ji(Uc,Uc.AO),_h=ua(new r).onReference((function(e){return e.material})).onRenderUpdate((function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))})),vh=Yi((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class Nh extends Qs{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),r=this.scope;let s,i;if(r===Nh.VERTEX)s=e.getVertexIndex();else if(r===Nh.INSTANCE)s=e.getInstanceIndex();else if(r===Nh.DRAW)s=e.getDrawIndex();else if(r===Nh.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===Nh.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==Nh.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=_u(this).build(e,t)}return i}}Nh.VERTEX="vertex",Nh.INSTANCE="instance",Nh.SUBGROUP="subgroup",Nh.INVOCATION_LOCAL="invocationLocal",Nh.INVOCATION_SUBGROUP="invocationSubgroup",Nh.DRAW="draw";const Sh=ji(Nh,Nh.VERTEX),Ah=ji(Nh,Nh.INSTANCE),Rh=ji(Nh,Nh.SUBGROUP),Eh=ji(Nh,Nh.INVOCATION_SUBGROUP),wh=ji(Nh,Nh.INVOCATION_LOCAL),Ch=ji(Nh,Nh.DRAW);class Mh extends Qs{static get type(){return"InstanceNode"}constructor(e,t,r=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=r,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=zs.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{instanceMatrix:t,instanceColor:r}=this,{count:s}=t;let{instanceMatrixNode:i,instanceColorNode:n}=this;if(null===i){if(s<=1e3)i=_l(t.array,"mat4",Math.max(s,1)).element(Ah);else{const e=new D(t.array,16,1);this.buffer=e;const r=t.usage===b?Gu:Ou,s=[r(e,"vec4",16,0),r(e,"vec4",16,4),r(e,"vec4",16,8),r(e,"vec4",16,12)];i=_n(...s)}this.instanceMatrixNode=i}if(r&&null===n){const e=new U(r.array,3),t=r.usage===b?Gu:Ou;this.bufferColor=e,n=cn(t(e,"vec3",3,0)),this.instanceColorNode=n}const a=i.mul(fd).xyz;if(fd.assign(a),e.hasGeometryAttribute("normal")){const e=Fd(Ed,i);Ed.assign(e)}null!==this.instanceColorNode&&Rn("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){null!==this.buffer&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.usage!==b&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.usage!==b&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version))}}const Bh=Hi(Mh).setParameterLength(2,3);class Ph extends Mh{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const Lh=Hi(Ph).setParameterLength(1);class Fh extends Qs{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=Ah:this.batchingIdNode=Ch);const t=Yi((([e])=>{const t=sn(hl(xl(this.batchMesh._indirectTexture),0).x),r=sn(e).mod(t),s=sn(e).div(t);return xl(this.batchMesh._indirectTexture,un(r,s)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(sn(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=sn(hl(xl(s),0).x),n=rn(r).mul(4).toInt().toVar(),a=n.mod(i),o=n.div(i),u=_n(xl(s,un(a,o)),xl(s,un(a.add(1),o)),xl(s,un(a.add(2),o)),xl(s,un(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=Yi((([e])=>{const t=sn(hl(xl(l),0).x),r=e,s=r.mod(t),i=r.div(t);return xl(l,un(s,i)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);Rn("vec3","vBatchColor").assign(t)}const d=Tn(u);fd.assign(u.mul(fd));const c=Ed.div(cn(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Ed.assign(h),e.hasGeometryAttribute("tangent")&&xc.mulAssign(d)}}const Ih=Hi(Fh).setParameterLength(1);class Dh extends Zs{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const r=this.storageBufferNode.structTypeNode;return r?r.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let r;const s=e.context.assign;if(r=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===s||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}const Uh=Hi(Dh).setParameterLength(2);class Vh extends Tl{static get type(){return"StorageBufferNode"}constructor(e,t=null,r=0){let s,i=null;t&&t.isStruct?(s="struct",i=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(r=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(s=Ms(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=Ws.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return Uh(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Ws.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=Uu(this.value),this._varying=_u(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:r}=this.getAttributeData(),s=r.build(e);return e.registerTransform(s,t),s}}const Oh=(e,t=null,r=0)=>ki(new Vh(e,t,r)),Gh=new WeakMap;class kh extends Qs{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=zs.OBJECT,this.skinIndexNode=ll("skinIndex","uvec4"),this.skinWeightNode=ll("skinWeight","vec4"),this.bindMatrixNode=ec("bindMatrix","mat4"),this.bindMatrixInverseNode=ec("bindMatrixInverse","mat4"),this.boneMatricesNode=tc("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=fd,this.toPositionNode=fd,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:r,skinWeightNode:s,bindMatrixNode:i,bindMatrixInverseNode:n}=this,a=e.element(r.x),o=e.element(r.y),u=e.element(r.z),l=e.element(r.w),d=i.mul(t),c=ya(a.mul(s.x).mul(d),o.mul(s.y).mul(d),u.mul(s.z).mul(d),l.mul(s.w).mul(d));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=Ed){const{skinIndexNode:r,skinWeightNode:s,bindMatrixNode:i,bindMatrixInverseNode:n}=this,a=e.element(r.x),o=e.element(r.y),u=e.element(r.z),l=e.element(r.w);let d=ya(s.x.mul(a),s.y.mul(o),s.z.mul(u),s.w.mul(l));return d=n.mul(d).mul(i),d.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=tc("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,yd)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Us(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&yd.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Ed.assign(t),e.hasGeometryAttribute("tangent")&&xc.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Gh.get(t)!==e.frameId&&(Gh.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const zh=e=>ki(new kh(e));class $h extends Qs{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const r={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],s=!0!==t.isNode&&t.name||this.getVarName(e),i=!0!==t.isNode&&t.type||"int";r[s]=Ju(s,i)}const s=e.addStack(),i=this.params[this.params.length-1](r);t.returnsNode=i.context({nodeLoop:i}),t.stackNode=s;const n=this.params[0];if(!0!==n.isNode&&"function"==typeof n.update){const e=Yi(this.params[0].update)(r);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(t){const r=this.getProperties(t),s=this.params,i=r.stackNode;for(let i=0,n=s.length-1;i<n;i++){const n=s[i];let a,o=!1,u=null,l=null,d=null,c=null,h=null,p=null;if(n.isNode?"bool"===n.getNodeType(t)?(o=!0,c="bool",l=n.build(t,c)):(c="int",d=this.getVarName(i),u="0",l=n.build(t,c),h="<"):(c=n.type||"int",d=n.name||this.getVarName(i),u=n.start,l=n.end,h=n.condition,p=n.update,"number"==typeof u?u=t.generateConst(c,u):u&&u.isNode&&(u=u.build(t,c)),"number"==typeof l?l=t.generateConst(c,l):l&&l.isNode&&(l=l.build(t,c)),void 0!==u&&void 0===l?(u+=" - 1",l="0",h=">="):void 0!==l&&void 0===u&&(u="0",h="<"),void 0===h&&(h=Number(u)>Number(l)?">=":"<")),o)a=`while ( ${l} )`;else{const s={start:u,end:l,condition:h},i=s.start,n=s.end;let o;const g=()=>h.includes("<")?"+=":"-=";if(null!=p)switch(typeof p){case"function":o=t.flowStagesNode(r.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":o=d+" "+g()+" "+t.generateConst(c,p);break;case"string":o=d+" "+p;break;default:p.isNode?o=d+" "+g()+" "+p.build(t):(e("TSL: 'Loop( { update: ... } )' is not a function, string or number."),o="break /* invalid update */")}else p="int"===c||"uint"===c?h.includes("<")?"++":"--":g()+" 1.",o=d+" "+p;a=`for ( ${t.getVar(c,d)+" = "+i}; ${d+" "+h+" "+n}; ${o} )`}t.addFlowCode((0===i?"\n":"")+t.tab+a+" {\n\n").addFlowTab()}const n=i.build(t,"void");r.returnsNode.build(t,"void"),t.removeFlowTab().addFlowCode("\n"+t.tab+n);for(let e=0,r=this.params.length-1;e<r;e++)t.addFlowCode((0===e?"":t.tab)+"}\n\n").removeFlowTab();t.addFlowTab()}}const Wh=(...e)=>new $h(Wi(e,"int")).toStack(),Hh=()=>Ju("break").toStack(),jh=new WeakMap,qh=new i,Xh=Yi((({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=sn(Sh).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return xl(e,un(u,o)).depth(i).xyz.mul(t)}));class Kh extends Qs{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=ua(1),this.updateType=zs.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,n=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,a=void 0!==n?n.length:0,{texture:o,stride:u,size:l}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=void 0!==n?n.length:0;let o=jh.get(e);if(void 0===o||o.count!==a){void 0!==o&&o.texture.dispose();const u=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],d=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===s&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,p=1;const g=4096;h>g&&(p=Math.ceil(h/g),h=g);const m=new Float32Array(h*p*4*a),f=new V(m,h,p,a);f.type=O,f.needsUpdate=!0;const y=4*c;for(let x=0;x<a;x++){const T=u[x],_=l[x],v=d[x],N=h*p*4*x;for(let S=0;S<T.count;S++){const A=S*y;!0===t&&(qh.fromBufferAttribute(T,S),m[N+A+0]=qh.x,m[N+A+1]=qh.y,m[N+A+2]=qh.z,m[N+A+3]=0),!0===s&&(qh.fromBufferAttribute(_,S),m[N+A+4]=qh.x,m[N+A+5]=qh.y,m[N+A+6]=qh.z,m[N+A+7]=0),!0===i&&(qh.fromBufferAttribute(v,S),m[N+A+8]=qh.x,m[N+A+9]=qh.y,m[N+A+10]=qh.z,m[N+A+11]=4===v.itemSize?qh.w:1)}}function b(){f.dispose(),jh.delete(e),e.removeEventListener("dispose",b)}o={count:a,texture:f,stride:c,size:new r(h,p)},jh.set(e,o),e.addEventListener("dispose",b)}return o}(t);!0===s&&fd.mulAssign(this.morphBaseInfluence),!0===i&&Ed.mulAssign(this.morphBaseInfluence);const d=sn(l.width);Wh(a,(({i:e})=>{const t=rn(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(xl(this.mesh.morphTexture,un(sn(e).add(1),sn(Ah))).r):t.assign(ec("morphTargetInfluences","float").element(e).toVar()),Ji(t.notEqual(0),(()=>{!0===s&&fd.addAssign(Xh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:sn(0)})),!0===i&&Ed.addAssign(Xh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:sn(1)}))}))}))}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce(((e,t)=>e+t),0)}}const Yh=Hi(Kh).setParameterLength(1);class Qh extends Qs{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Zh extends Qh{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Jh extends uu{static get type(){return"LightingContextNode"}constructor(e,t=null,r=null,s=null){super(e),this.lightingModel=t,this.backdropNode=r,this.backdropAlphaNode=s,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,r={directDiffuse:cn().toVar("directDiffuse"),directSpecular:cn().toVar("directSpecular"),indirectDiffuse:cn().toVar("indirectDiffuse"),indirectSpecular:cn().toVar("indirectSpecular")};return{radiance:cn().toVar("radiance"),irradiance:cn().toVar("irradiance"),iblIrradiance:cn().toVar("iblIrradiance"),ambientOcclusion:rn(1).toVar("ambientOcclusion"),reflectedLight:r,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const ep=Hi(Jh);class tp extends Qh{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const rp=new r;class sp extends fl{static get type(){return"ViewportTextureNode"}constructor(e=Ml,t=null,r=null){let s=null;null===r?(s=new G,s.minFilter=k,r=s):s=r,super(r,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=s,this.isOutputTextureNode=!0,this.updateBeforeType=zs.FRAME,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,r;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,r=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,r=this._cacheTextures),null===e)return t;if(!1===r.has(e)){const s=t.clone();r.set(e,s)}return r.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,r=t.getRenderTarget();null===r?t.getDrawingBufferSize(rp):rp.set(r.width,r.height);const s=this.getTextureForReference(r);s.image.width===rp.width&&s.image.height===rp.height||(s.image.width=rp.width,s.image.height=rp.height,s.needsUpdate=!0);const i=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const ip=Hi(sp).setParameterLength(0,3),np=Hi(sp,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let ap=null;class op extends sp{static get type(){return"ViewportDepthTextureNode"}constructor(e=Ml,t=null){null===ap&&(ap=new z),super(e,t,ap)}getTextureForReference(){return ap}}const up=Hi(op).setParameterLength(0,2);class lp extends Qs{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===lp.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===lp.DEPTH_BASE)null!==r&&(s=gp().assign(r));else if(t===lp.DEPTH)s=e.isPerspectiveCamera?cp(Td.z,Ol,Gl):dp(Td.z,Ol,Gl);else if(t===lp.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=hp(r,Ol,Gl);s=dp(e,Ol,Gl)}else s=r;else s=dp(Td.z,Ol,Gl);return s}}lp.DEPTH_BASE="depthBase",lp.DEPTH="depth",lp.LINEAR_DEPTH="linearDepth";const dp=(e,t,r)=>e.add(t).div(t.sub(r)),cp=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),hp=(e,t,r)=>t.mul(r).div(r.sub(t).mul(e).sub(r)),pp=(e,t,r)=>{t=t.max(1e-6).toVar();const s=so(e.negate().div(t)),i=so(r.div(t));return s.div(i)},gp=Hi(lp,lp.DEPTH_BASE),mp=ji(lp,lp.DEPTH),fp=Hi(lp,lp.LINEAR_DEPTH).setParameterLength(0,1),yp=fp(up());mp.assign=e=>gp(e);class bp extends Qs{static get type(){return"ClippingNode"}constructor(e=bp.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:r,unionPlanes:s}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===bp.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===bp.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return Yi((()=>{const r=rn().toVar("distanceToPlane"),s=rn().toVar("distanceToGradient"),i=rn(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Sl(t).setGroup(na);Wh(n,(({i:t})=>{const n=e.element(t);r.assign(Td.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(Qo(s.negate(),s,r))}))}const a=e.length;if(a>0){const t=Sl(e).setGroup(na),n=rn(1).toVar("intersectionClipOpacity");Wh(a,(({i:e})=>{const i=t.element(e);r.assign(Td.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(Qo(s.negate(),s,r).oneMinus())})),i.mulAssign(n.oneMinus())}En.a.mulAssign(i),En.a.equal(0).discard()}))()}setupDefault(e,t){return Yi((()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=Sl(t).setGroup(na);Wh(r,(({i:t})=>{const r=e.element(t);Td.dot(r.xyz).greaterThan(r.w).discard()}))}const s=e.length;if(s>0){const t=Sl(e).setGroup(na),r=an(!0).toVar("clipped");Wh(s,(({i:e})=>{const s=t.element(e);r.assign(Td.dot(s.xyz).greaterThan(s.w).and(r))})),r.discard()}}))()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),Yi((()=>{const s=Sl(e).setGroup(na),i=Al(t.getClipDistance());Wh(r,(({i:e})=>{const t=s.element(e),r=Td.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)}))}))()}}bp.ALPHA_TO_COVERAGE="alphaToCoverage",bp.DEFAULT="default",bp.HARDWARE="hardware";const xp=Yi((([e])=>lo(xa(1e4,co(xa(17,e.x).add(xa(.1,e.y)))).mul(ya(.1,yo(co(xa(13,e.y).add(e.x)))))))),Tp=Yi((([e])=>xp(on(xp(e.xy),e.z)))),_p=Yi((([e])=>{const t=Lo(xo(vo(e.xyz)),xo(No(e.xyz))),r=rn(1).div(rn(.05).mul(t)).toVar("pixScale"),s=on(to(ao(so(r))),to(oo(so(r)))),i=on(Tp(ao(s.x.mul(e.xyz))),Tp(ao(s.y.mul(e.xyz)))),n=lo(so(r)),a=ya(xa(n.oneMinus(),i.x),xa(n,i.y)),o=Po(n,n.oneMinus()),u=cn(a.mul(a).div(xa(2,o).mul(ba(1,o))),a.sub(xa(.5,o)).div(ba(1,o)),ba(1,ba(1,a).mul(ba(1,a)).div(xa(2,o).mul(ba(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return Xo(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class vp extends ul{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let r;return r=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new i(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Np=(e=0)=>ki(new vp(e)),Sp=Yi((([e,t])=>Po(1,e.oneMinus().div(t)).oneMinus())).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Ap=Yi((([e,t])=>Po(e.div(t.oneMinus()),1))).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Rp=Yi((([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus())).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Ep=Yi((([e,t])=>qo(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),Fo(.5,e)))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),wp=Yi((([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return mn(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(r),r)})).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),Cp=Yi((([e])=>mn(e.rgb.mul(e.a),e.a)),{color:"vec4",return:"vec4"}),Mp=Yi((([e])=>(Ji(e.a.equal(0),(()=>mn(0))),mn(e.rgb.div(e.a),e.a))),{color:"vec4",return:"vec4"});class Bp extends ${static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{d('NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const r=this[t];r&&!0===r.isNode&&e.push({property:t,childNode:r})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:r}of this._getNodeChildren())e.push(As(t.slice(0,-4)),r.getCacheKey());return this.type+Rs(e)}build(e){this.setup(e)}setupObserver(e){return new Ns(e)}setup(e){e.context.setupNormal=()=>xu(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,r=t.getRenderTarget();e.addStack();const s=xu(this.setupVertex(e),"VERTEX"),i=this.vertexNode||s;let n;e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==r?!0===r.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const s=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const i=mn(s,En.a).max(0);n=this.setupOutput(e,i),Hn.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&Hn.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=mn(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:r}=e.clippingContext;let s=null;if(t.length>0||r.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?s=ki(new bp(bp.ALPHA_TO_COVERAGE)):e.stack.addToStack(ki(new bp))}return s}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(ki(new bp(bp.HARDWARE))),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:r}=e;let s=this.depthNode;if(null===s){const e=t.getMRT();e&&e.has("depth")?s=e.get("depth"):!0===t.logarithmicDepthBuffer&&(s=r.isPerspectiveCamera?pp(Td.z,Ol,Gl):dp(Td.z,Ol,Gl))}null!==s&&mp.assign(s).toStack()}setupPositionView(){return cd.mul(fd).xyz}setupModelViewProjection(){return kl.mul(Td)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),vh}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&Yh(t).toStack(),!0===t.isSkinnedMesh&&zh(t).toStack(),this.displacementMap){const e=sc("displacementMap","texture"),t=sc("displacementScale","float"),r=sc("displacementBias","float");fd.addAssign(Ed.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&Ih(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Lh(t).toStack(),null!==this.positionNode&&fd.assign(xu(this.positionNode,"POSITION","vec3")),fd}setupDiffuseColor(e){const{object:t,geometry:r}=e;null!==this.maskNode&&an(this.maskNode).not().discard();let s=this.colorNode?mn(this.colorNode):Oc;if(!0===this.vertexColors&&r.hasAttribute("color")&&(s=s.mul(Np())),t.instanceColor){s=Rn("vec3","vInstanceColor").mul(s)}if(t.isBatchedMesh&&t._colorsTexture){s=Rn("vec3","vBatchColor").mul(s)}En.assign(s);const i=this.opacityNode?rn(this.opacityNode):zc;En.a.assign(En.a.mul(i));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?rn(this.alphaTestNode):Vc,!0===this.alphaToCoverage?(En.a=Qo(n,n.add(Eo(En.a)),En.a),En.a.lessThanEqual(0).discard()):En.a.lessThanEqual(n).discard()),!0===this.alphaHash&&En.a.lessThan(_p(fd)).discard(),e.isOpaque()&&En.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?cn(0):En.rgb}setupNormal(){return this.normalNode?cn(this.normalNode):Yc}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?sc("envMap","cubeTexture"):sc("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new tp(xh)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);if(s&&s.isLightingNode&&t.push(s),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Th;t.push(new Zh(e))}let i=this.lightsNode||e.lightsNode;return t.length>0&&(i=e.renderer.lighting.createNode([...i.getLights(),...t])),i}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:r,backdropAlphaNode:s,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=ep(n,t,r,s)}else null!==r&&(a=cn(null!==s?qo(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(wn.assign(cn(i||kc)),a=a.add(wn)),a}setupFog(e,t){const r=e.fogNode;return r&&(Hn.assign(t),t=mn(r.toVar())),t}setupPremultipliedAlpha(e,t){return Cp(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const r=e[t];void 0===this[t]&&(this[t]=r,r&&r.clone&&(this[t]=r.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const r=$.prototype.toJSON.call(this,e);r.inputNodes={};for(const{property:t,childNode:s}of this._getNodeChildren())r.inputNodes[t]=s.toJSON(e).uuid;function s(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=s(e.textures),i=s(e.images),n=s(e.nodes);t.length>0&&(r.textures=t),i.length>0&&(r.images=i),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const Pp=new W;class Lp extends Bp{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Pp),this.setValues(e)}}const Fp=new H;class Ip extends Bp{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Fp),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?rn(this.offsetNode):fh,t=this.dashScaleNode?rn(this.dashScaleNode):hh,r=this.dashSizeNode?rn(this.dashSizeNode):ph,s=this.gapSizeNode?rn(this.gapSizeNode):gh;jn.assign(r),qn.assign(s);const i=_u(ll("lineDistance").mul(t));(e?i.add(e):i).mod(jn.add(qn)).greaterThan(jn).discard()}}let Dp=null;class Up extends sp{static get type(){return"ViewportSharedTextureNode"}constructor(e=Ml,t=null){null===Dp&&(Dp=new G),super(e,t,Dp)}getTextureForReference(){return Dp}updateReference(){return this}}const Vp=Hi(Up).setParameterLength(0,2),Op=new H;class Gp extends Bp{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(Op),this.useColor=e.vertexColors,this.dashOffset=0,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=j,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.useColor,i=this._useDash,n=this._useWorldUnits,a=Yi((({start:e,end:t})=>{const r=kl.element(2).element(2),s=kl.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return mn(qo(e.xyz,t.xyz,s),t.w)})).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=Yi((()=>{const e=ll("instanceStart"),t=ll("instanceEnd"),r=mn(cd.mul(mn(e,1))).toVar("start"),s=mn(cd.mul(mn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?rn(this.dashScaleNode):hh,t=this.offsetNode?rn(this.offsetNode):fh,r=ll("instanceDistanceStart"),s=ll("instanceDistanceEnd");let i=md.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),Rn("float","lineDistance").assign(i)}n&&(Rn("vec3","worldStart").assign(r.xyz),Rn("vec3","worldEnd").assign(s.xyz));const o=Ll.z.div(Ll.w),u=kl.element(2).element(3).equal(-1);Ji(u,(()=>{Ji(r.z.lessThan(0).and(s.z.greaterThan(0)),(()=>{s.assign(a({start:r,end:s}))})).ElseIf(s.z.lessThan(0).and(r.z.greaterThanEqual(0)),(()=>{r.assign(a({start:s,end:r}))}))}));const l=kl.mul(r),d=kl.mul(s),c=l.xyz.div(l.w),h=d.xyz.div(d.w),p=h.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(o)),p.assign(p.normalize());const g=mn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=qo(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=Rn("vec4","worldPos");o.assign(md.y.lessThan(.5).select(r,s));const u=mh.mul(.5);o.addAssign(mn(md.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(mn(md.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(mn(a.mul(u),0)),Ji(md.y.greaterThan(1).or(md.y.lessThan(0)),(()=>{o.subAssign(mn(a.mul(2).mul(u),0))}))),g.assign(kl.mul(o));const l=cn().toVar();l.assign(md.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=on(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(md.x.lessThan(0).select(e.negate(),e)),Ji(md.y.lessThan(0),(()=>{e.assign(e.sub(p))})).ElseIf(md.y.greaterThan(1),(()=>{e.assign(e.add(p))})),e.assign(e.mul(mh)),e.assign(e.div(Ll.w)),g.assign(md.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(mn(e,0,0)))}return g}))();const o=Yi((({p1:e,p2:t,p3:r,p4:s})=>{const i=e.sub(r),n=s.sub(r),a=t.sub(e),o=i.dot(n),u=n.dot(a),l=i.dot(a),d=n.dot(n),c=a.dot(a).mul(d).sub(u.mul(u)),h=o.mul(u).sub(l.mul(d)).div(c).clamp(),p=o.add(u.mul(h)).div(d).clamp();return on(h,p)}));if(this.colorNode=Yi((()=>{const e=dl();if(i){const t=this.dashSizeNode?rn(this.dashSizeNode):ph,r=this.gapSizeNode?rn(this.gapSizeNode):gh;jn.assign(t),qn.assign(r);const s=Rn("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(jn.add(qn)).greaterThan(jn).discard()}const a=rn(1).toVar("alpha");if(n){const e=Rn("vec3","worldStart"),s=Rn("vec3","worldEnd"),n=Rn("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:cn(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(mh);if(!i)if(r&&t.currentSamples>0){const e=h.fwidth();a.assign(Qo(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.currentSamples>0){const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1)),s=t.mul(t).add(r.mul(r)),i=rn(s.fwidth()).toVar("dlen");Ji(e.y.abs().greaterThan(1),(()=>{a.assign(Qo(i.oneMinus(),i.add(1),s).oneMinus())}))}else Ji(e.y.abs().greaterThan(1),(()=>{const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1));t.mul(t).add(r.mul(r)).greaterThan(1).discard()}));let u;if(this.lineColorNode)u=this.lineColorNode;else if(s){const e=ll("instanceColorStart"),t=ll("instanceColorEnd");u=md.y.lessThan(.5).select(e,t).mul(Oc)}else u=Oc;return mn(u,a)}))(),this.transparent){const e=this.opacityNode?rn(this.opacityNode):zc;this.outputNode=mn(this.colorNode.rgb.mul(e).add(Vp().rgb.mul(e.oneMinus())),this.colorNode.a)}super.setup(e)}get worldUnits(){return this._useWorldUnits}set worldUnits(e){this._useWorldUnits!==e&&(this._useWorldUnits=e,this.needsUpdate=!0)}get dashed(){return this._useDash}set dashed(e){this._useDash!==e&&(this._useDash=e,this.needsUpdate=!0)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const kp=e=>ki(e).mul(.5).add(.5),zp=new X;class $p extends Bp{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(zp),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?rn(this.opacityNode):zc;En.assign(wu(mn(kp(Bd),e),q))}}const Wp=Yi((([e=xd])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),r=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return on(t,r)}));class Hp extends K{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const r=t.minFilter,s=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i=new Y(5,5,5),n=Wp(xd),a=new Bp;a.colorNode=bl(t,n,0),a.side=w,a.blending=j;const o=new Q(i,a),u=new Z;u.add(o),t.minFilter===k&&(t.minFilter=J);const l=new ee(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.currentGenerateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}}const jp=new WeakMap;class qp extends ei{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Qd(null);const t=new L;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=zs.RENDER}updateBefore(e){const{renderer:t,material:r}=e,s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:r[s.property];if(e&&e.isTexture){const r=e.mapping;if(r===te||r===re){if(jp.has(e)){const t=jp.get(e);Kp(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new Hp(r.height);s.fromEquirectangularTexture(t,e),Kp(s.texture,e.mapping),this._cubeTexture=s.texture,jp.set(e,s.texture),e.addEventListener("dispose",Xp)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Xp(e){const t=e.target;t.removeEventListener("dispose",Xp);const r=jp.get(t);void 0!==r&&(jp.delete(t),r.dispose())}function Kp(e,t){t===te?e.mapping=B:t===re&&(e.mapping=P)}const Yp=Hi(qp).setParameterLength(1);class Qp extends Qh{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Yp(this.envNode)}}class Zp extends Qh{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=rn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Jp{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class eg extends Jp{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(mn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(mn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(En.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case ne:s.rgb.assign(qo(s.rgb,s.rgb.mul(i.rgb),jc.mul(qc)));break;case ie:s.rgb.assign(qo(s.rgb,i.rgb,jc.mul(qc)));break;case se:s.rgb.addAssign(i.rgb.mul(jc.mul(qc)));break;default:d("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const tg=new ae;class rg extends Bp{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(tg),this.setValues(e)}setupNormal(){return Ad(Cd)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Qp(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Zp(xh)),t}setupOutgoingLight(){return En.rgb}setupLightingModel(){return new eg}}const sg=Yi((({f0:e,f90:t,dotVH:r})=>{const s=r.mul(-5.55473).sub(6.98316).mul(r).exp2();return e.mul(s.oneMinus()).add(t.mul(s))})),ig=Yi((e=>e.diffuseColor.mul(1/Math.PI))),ng=Yi((({dotNH:e})=>Wn.mul(rn(.5)).add(1).mul(rn(1/Math.PI)).mul(e.pow(Wn)))),ag=Yi((({lightDirection:e})=>{const t=e.add(_d).normalize(),r=Bd.dot(t).clamp(),s=_d.dot(t).clamp(),i=sg({f0:zn,f90:1,dotVH:s}),n=rn(.25),a=ng({dotNH:r});return i.mul(n).mul(a)}));class og extends eg{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Bd.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(ig({diffuseColor:En.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(ag({lightDirection:e})).mul(jc))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(ig({diffuseColor:En}))),s.indirectDiffuse.mulAssign(t)}}const ug=new oe;class lg extends Bp{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ug),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Qp(t):null}setupLightingModel(){return new og(!1)}}const dg=new ue;class cg extends Bp{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(dg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Qp(t):null}setupLightingModel(){return new og}setupVariants(){const e=(this.shininessNode?rn(this.shininessNode):Gc).max(1e-4);Wn.assign(e);const t=this.specularNode||$c;zn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const hg=Yi((e=>{if(!1===e.geometry.hasAttribute("normal"))return rn(0);const t=Cd.dFdx().abs().max(Cd.dFdy().abs());return t.x.max(t.y).max(t.z)})),pg=Yi((e=>{const{roughness:t}=e,r=hg();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s})),gg=Yi((({alpha:e,dotNL:t,dotNV:r})=>{const s=e.pow2(),i=t.mul(s.add(s.oneMinus().mul(r.pow2())).sqrt()),n=r.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt());return Ta(.5,i.add(n).max(Wa))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),mg=Yi((({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(cn(e.mul(r),t.mul(s),a).length()),l=a.mul(cn(e.mul(i),t.mul(n),o).length());return Ta(.5,u.add(l)).saturate()})).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),fg=Yi((({alpha:e,dotNH:t})=>{const r=e.pow2(),s=t.pow2().mul(r.oneMinus()).oneMinus();return r.div(s.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),yg=rn(1/Math.PI),bg=Yi((({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=cn(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return yg.mul(n.mul(u.pow2()))})).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),xg=Yi((({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Bd,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(_d).normalize(),d=n.dot(e).clamp(),c=n.dot(_d).clamp(),h=n.dot(l).clamp(),p=_d.dot(l).clamp();let g,m,f=sg({f0:t,f90:r,dotVH:p});if(Vi(a)&&(f=In.mix(f,i)),Vi(o)){const t=Gn.dot(e),r=Gn.dot(_d),s=Gn.dot(l),i=kn.dot(e),n=kn.dot(_d),a=kn.dot(l);g=mg({alphaT:Vn,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=bg({alphaT:Vn,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=gg({alpha:u,dotNL:d,dotNV:c}),m=fg({alpha:u,dotNH:h});return f.mul(g).mul(m)})),Tg=new Uint16Array([11481,15204,11534,15171,11808,15015,12385,14843,12894,14716,13396,14600,13693,14483,13976,14366,14237,14171,14405,13961,14511,13770,14605,13598,14687,13444,14760,13305,14822,13066,14876,12857,14923,12675,14963,12517,14997,12379,15025,12230,15049,12023,15070,11843,15086,11687,15100,11551,15111,11433,15120,11330,15127,11217,15132,11060,15135,10922,15138,10801,15139,10695,15139,10600,13012,14923,13020,14917,13064,14886,13176,14800,13349,14666,13513,14526,13724,14398,13960,14230,14200,14020,14383,13827,14488,13651,14583,13491,14667,13348,14740,13132,14803,12908,14856,12713,14901,12542,14938,12394,14968,12241,14992,12017,15010,11822,15024,11654,15034,11507,15041,11380,15044,11269,15044,11081,15042,10913,15037,10764,15031,10635,15023,10520,15014,10419,15003,10330,13657,14676,13658,14673,13670,14660,13698,14622,13750,14547,13834,14442,13956,14317,14112,14093,14291,13889,14407,13704,14499,13538,14586,13389,14664,13201,14733,12966,14792,12758,14842,12577,14882,12418,14915,12272,14940,12033,14959,11826,14972,11646,14980,11490,14983,11355,14983,11212,14979,11008,14971,10830,14961,10675,14950,10540,14936,10420,14923,10315,14909,10204,14894,10041,14089,14460,14090,14459,14096,14452,14112,14431,14141,14388,14186,14305,14252,14130,14341,13941,14399,13756,14467,13585,14539,13430,14610,13272,14677,13026,14737,12808,14790,12617,14833,12449,14869,12303,14896,12065,14916,11845,14929,11655,14937,11490,14939,11347,14936,11184,14930,10970,14921,10783,14912,10621,14900,10480,14885,10356,14867,10247,14848,10062,14827,9894,14805,9745,14400,14208,14400,14206,14402,14198,14406,14174,14415,14122,14427,14035,14444,13913,14469,13767,14504,13613,14548,13463,14598,13324,14651,13082,14704,12858,14752,12658,14795,12483,14831,12330,14860,12106,14881,11875,14895,11675,14903,11501,14905,11351,14903,11178,14900,10953,14892,10757,14880,10589,14865,10442,14847,10313,14827,10162,14805,9965,14782,9792,14757,9642,14731,9507,14562,13883,14562,13883,14563,13877,14566,13862,14570,13830,14576,13773,14584,13689,14595,13582,14613,13461,14637,13336,14668,13120,14704,12897,14741,12695,14776,12516,14808,12358,14835,12150,14856,11910,14870,11701,14878,11519,14882,11361,14884,11187,14880,10951,14871,10748,14858,10572,14842,10418,14823,10286,14801,10099,14777,9897,14751,9722,14725,9567,14696,9430,14666,9309,14702,13604,14702,13604,14702,13600,14703,13591,14705,13570,14707,13533,14709,13477,14712,13400,14718,13305,14727,13106,14743,12907,14762,12716,14784,12539,14807,12380,14827,12190,14844,11943,14855,11727,14863,11539,14870,11376,14871,11204,14868,10960,14858,10748,14845,10565,14829,10406,14809,10269,14786,10058,14761,9852,14734,9671,14705,9512,14674,9374,14641,9253,14608,9076,14821,13366,14821,13365,14821,13364,14821,13358,14821,13344,14821,13320,14819,13252,14817,13145,14815,13011,14814,12858,14817,12698,14823,12539,14832,12389,14841,12214,14850,11968,14856,11750,14861,11558,14866,11390,14867,11226,14862,10972,14853,10754,14840,10565,14823,10401,14803,10259,14780,10032,14754,9820,14725,9635,14694,9473,14661,9333,14627,9203,14593,8988,14557,8798,14923,13014,14922,13014,14922,13012,14922,13004,14920,12987,14919,12957,14915,12907,14909,12834,14902,12738,14894,12623,14888,12498,14883,12370,14880,12203,14878,11970,14875,11759,14873,11569,14874,11401,14872,11243,14865,10986,14855,10762,14842,10568,14825,10401,14804,10255,14781,10017,14754,9799,14725,9611,14692,9445,14658,9301,14623,9139,14587,8920,14548,8729,14509,8562,15008,12672,15008,12672,15008,12671,15007,12667,15005,12656,15001,12637,14997,12605,14989,12556,14978,12490,14966,12407,14953,12313,14940,12136,14927,11934,14914,11742,14903,11563,14896,11401,14889,11247,14879,10992,14866,10767,14851,10570,14833,10400,14812,10252,14789,10007,14761,9784,14731,9592,14698,9424,14663,9279,14627,9088,14588,8868,14548,8676,14508,8508,14467,8360,15080,12386,15080,12386,15079,12385,15078,12383,15076,12378,15072,12367,15066,12347,15057,12315,15045,12253,15030,12138,15012,11998,14993,11845,14972,11685,14951,11530,14935,11383,14920,11228,14904,10981,14887,10762,14870,10567,14850,10397,14827,10248,14803,9997,14774,9771,14743,9578,14710,9407,14674,9259,14637,9048,14596,8826,14555,8632,14514,8464,14471,8317,14427,8182,15139,12008,15139,12008,15138,12008,15137,12007,15135,12003,15130,11990,15124,11969,15115,11929,15102,11872,15086,11794,15064,11693,15041,11581,15013,11459,14987,11336,14966,11170,14944,10944,14921,10738,14898,10552,14875,10387,14850,10239,14824,9983,14794,9758,14762,9563,14728,9392,14692,9244,14653,9014,14611,8791,14569,8597,14526,8427,14481,8281,14436,8110,14391,7885,15188,11617,15188,11617,15187,11617,15186,11618,15183,11617,15179,11612,15173,11601,15163,11581,15150,11546,15133,11495,15110,11427,15083,11346,15051,11246,15024,11057,14996,10868,14967,10687,14938,10517,14911,10362,14882,10206,14853,9956,14821,9737,14787,9543,14752,9375,14715,9228,14675,8980,14632,8760,14589,8565,14544,8395,14498,8248,14451,8049,14404,7824,14357,7630,15228,11298,15228,11298,15227,11299,15226,11301,15223,11303,15219,11302,15213,11299,15204,11290,15191,11271,15174,11217,15150,11129,15119,11015,15087,10886,15057,10744,15024,10599,14990,10455,14957,10318,14924,10143,14891,9911,14856,9701,14820,9516,14782,9352,14744,9200,14703,8946,14659,8725,14615,8533,14568,8366,14521,8220,14472,7992,14423,7770,14374,7578,14315,7408,15260,10819,15260,10819,15259,10822,15258,10826,15256,10832,15251,10836,15246,10841,15237,10838,15225,10821,15207,10788,15183,10734,15151,10660,15120,10571,15087,10469,15049,10359,15012,10249,14974,10041,14937,9837,14900,9647,14860,9475,14820,9320,14779,9147,14736,8902,14691,8688,14646,8499,14598,8335,14549,8189,14499,7940,14448,7720,14397,7529,14347,7363,14256,7218,15285,10410,15285,10411,15285,10413,15284,10418,15282,10425,15278,10434,15272,10442,15264,10449,15252,10445,15235,10433,15210,10403,15179,10358,15149,10301,15113,10218,15073,10059,15033,9894,14991,9726,14951,9565,14909,9413,14865,9273,14822,9073,14777,8845,14730,8641,14682,8459,14633,8300,14583,8129,14531,7883,14479,7670,14426,7482,14373,7321,14305,7176,14201,6939,15305,9939,15305,9940,15305,9945,15304,9955,15302,9967,15298,9989,15293,10010,15286,10033,15274,10044,15258,10045,15233,10022,15205,9975,15174,9903,15136,9808,15095,9697,15053,9578,15009,9451,14965,9327,14918,9198,14871,8973,14825,8766,14775,8579,14725,8408,14675,8259,14622,8058,14569,7821,14515,7615,14460,7435,14405,7276,14350,7108,14256,6866,14149,6653,15321,9444,15321,9445,15321,9448,15320,9458,15317,9470,15314,9490,15310,9515,15302,9540,15292,9562,15276,9579,15251,9577,15226,9559,15195,9519,15156,9463,15116,9389,15071,9304,15025,9208,14978,9023,14927,8838,14878,8661,14827,8496,14774,8344,14722,8206,14667,7973,14612,7749,14556,7555,14499,7382,14443,7229,14385,7025,14322,6791,14210,6588,14100,6409,15333,8920,15333,8921,15332,8927,15332,8943,15329,8965,15326,9002,15322,9048,15316,9106,15307,9162,15291,9204,15267,9221,15244,9221,15212,9196,15175,9134,15133,9043,15088,8930,15040,8801,14990,8665,14938,8526,14886,8391,14830,8261,14775,8087,14719,7866,14661,7664,14603,7482,14544,7322,14485,7178,14426,6936,14367,6713,14281,6517,14166,6348,14054,6198,15341,8360,15341,8361,15341,8366,15341,8379,15339,8399,15336,8431,15332,8473,15326,8527,15318,8585,15302,8632,15281,8670,15258,8690,15227,8690,15191,8664,15149,8612,15104,8543,15055,8456,15001,8360,14948,8259,14892,8122,14834,7923,14776,7734,14716,7558,14656,7397,14595,7250,14534,7070,14472,6835,14410,6628,14350,6443,14243,6283,14125,6135,14010,5889,15348,7715,15348,7717,15348,7725,15347,7745,15345,7780,15343,7836,15339,7905,15334,8e3,15326,8103,15310,8193,15293,8239,15270,8270,15240,8287,15204,8283,15163,8260,15118,8223,15067,8143,15014,8014,14958,7873,14899,7723,14839,7573,14778,7430,14715,7293,14652,7164,14588,6931,14524,6720,14460,6531,14396,6362,14330,6210,14207,6015,14086,5781,13969,5576,15352,7114,15352,7116,15352,7128,15352,7159,15350,7195,15348,7237,15345,7299,15340,7374,15332,7457,15317,7544,15301,7633,15280,7703,15251,7754,15216,7775,15176,7767,15131,7733,15079,7670,15026,7588,14967,7492,14906,7387,14844,7278,14779,7171,14714,6965,14648,6770,14581,6587,14515,6420,14448,6269,14382,6123,14299,5881,14172,5665,14049,5477,13929,5310,15355,6329,15355,6330,15355,6339,15355,6362,15353,6410,15351,6472,15349,6572,15344,6688,15337,6835,15323,6985,15309,7142,15287,7220,15260,7277,15226,7310,15188,7326,15142,7318,15090,7285,15036,7239,14976,7177,14914,7045,14849,6892,14782,6736,14714,6581,14645,6433,14576,6293,14506,6164,14438,5946,14369,5733,14270,5540,14140,5369,14014,5216,13892,5043,15357,5483,15357,5484,15357,5496,15357,5528,15356,5597,15354,5692,15351,5835,15347,6011,15339,6195,15328,6317,15314,6446,15293,6566,15268,6668,15235,6746,15197,6796,15152,6811,15101,6790,15046,6748,14985,6673,14921,6583,14854,6479,14785,6371,14714,6259,14643,6149,14571,5946,14499,5750,14428,5567,14358,5401,14242,5250,14109,5111,13980,4870,13856,4657,15359,4555,15359,4557,15358,4573,15358,4633,15357,4715,15355,4841,15353,5061,15349,5216,15342,5391,15331,5577,15318,5770,15299,5967,15274,6150,15243,6223,15206,6280,15161,6310,15111,6317,15055,6300,14994,6262,14928,6208,14860,6141,14788,5994,14715,5838,14641,5684,14566,5529,14492,5384,14418,5247,14346,5121,14216,4892,14079,4682,13948,4496,13822,4330,15359,3498,15359,3501,15359,3520,15359,3598,15358,3719,15356,3860,15355,4137,15351,4305,15344,4563,15334,4809,15321,5116,15303,5273,15280,5418,15250,5547,15214,5653,15170,5722,15120,5761,15064,5763,15002,5733,14935,5673,14865,5597,14792,5504,14716,5400,14640,5294,14563,5185,14486,5041,14410,4841,14335,4655,14191,4482,14051,4325,13918,4183,13790,4012,15360,2282,15360,2285,15360,2306,15360,2401,15359,2547,15357,2748,15355,3103,15352,3349,15345,3675,15336,4020,15324,4272,15307,4496,15285,4716,15255,4908,15220,5086,15178,5170,15128,5214,15072,5234,15010,5231,14943,5206,14871,5166,14796,5102,14718,4971,14639,4833,14559,4687,14480,4541,14402,4401,14315,4268,14167,4142,14025,3958,13888,3747,13759,3556,15360,923,15360,925,15360,946,15360,1052,15359,1214,15357,1494,15356,1892,15352,2274,15346,2663,15338,3099,15326,3393,15309,3679,15288,3980,15260,4183,15226,4325,15185,4437,15136,4517,15080,4570,15018,4591,14950,4581,14877,4545,14800,4485,14720,4411,14638,4325,14556,4231,14475,4136,14395,3988,14297,3803,14145,3628,13999,3465,13861,3314,13729,3177,15360,263,15360,264,15360,272,15360,325,15359,407,15358,548,15356,780,15352,1144,15347,1580,15339,2099,15328,2425,15312,2795,15292,3133,15264,3329,15232,3517,15191,3689,15143,3819,15088,3923,15025,3978,14956,3999,14882,3979,14804,3931,14722,3855,14639,3756,14554,3645,14470,3529,14388,3409,14279,3289,14124,3173,13975,3055,13834,2848,13701,2658,15360,49,15360,49,15360,52,15360,75,15359,111,15358,201,15356,283,15353,519,15348,726,15340,1045,15329,1415,15314,1795,15295,2173,15269,2410,15237,2649,15197,2866,15150,3054,15095,3140,15032,3196,14963,3228,14888,3236,14808,3224,14725,3191,14639,3146,14553,3088,14466,2976,14382,2836,14262,2692,14103,2549,13952,2409,13808,2278,13674,2154,15360,4,15360,4,15360,4,15360,13,15359,33,15358,59,15357,112,15353,199,15348,302,15341,456,15331,628,15316,827,15297,1082,15272,1332,15241,1601,15202,1851,15156,2069,15101,2172,15039,2256,14970,2314,14894,2348,14813,2358,14728,2344,14640,2311,14551,2263,14463,2203,14376,2133,14247,2059,14084,1915,13930,1761,13784,1609,13648,1464,15360,0,15360,0,15360,0,15360,3,15359,18,15358,26,15357,53,15354,80,15348,97,15341,165,15332,238,15318,326,15299,427,15275,529,15245,654,15207,771,15161,885,15108,994,15046,1089,14976,1170,14900,1229,14817,1266,14731,1284,14641,1282,14550,1260,14460,1223,14370,1174,14232,1116,14066,1050,13909,981,13761,910,13623,839]);let _g=null;const vg=Yi((({roughness:e,dotNV:t})=>{null===_g&&(_g=new le(Tg,32,32,de,ce),_g.minFilter=J,_g.magFilter=J,_g.wrapS=he,_g.wrapT=he,_g.generateMipmaps=!1,_g.needsUpdate=!0);const r=on(e,t);return bl(_g,r).rg})),Ng=Yi((({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=xg({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),u=Bd.dot(e).clamp(),l=Bd.dot(_d).clamp(),d=vg({roughness:s,dotNV:l}),c=vg({roughness:s,dotNV:u}),h=t.mul(d.x).add(r.mul(d.y)),p=t.mul(c.x).add(r.mul(c.y)),g=d.x.add(d.y),m=c.x.add(c.y),f=rn(1).sub(g),y=rn(1).sub(m),b=t.add(t.oneMinus().mul(.047619)),x=h.mul(p).mul(b).div(rn(1).sub(f.mul(y).mul(b).mul(b)).add(Wa)),T=f.mul(y),_=x.mul(T);return o.add(_)})),Sg=Yi((e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=vg({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))})),Ag=Yi((({f:e,f90:t,dotVH:r})=>{const s=r.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return e.sub(cn(t).mul(n)).div(n.oneMinus())})).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),Rg=Yi((({roughness:e,dotNH:t})=>{const r=e.pow2(),s=rn(1).div(r),i=t.pow2().oneMinus().max(.0078125);return rn(2).add(s).mul(i.pow(s.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),Eg=Yi((({dotNV:e,dotNL:t})=>rn(1).div(rn(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),wg=Yi((({lightDirection:e})=>{const t=e.add(_d).normalize(),r=Bd.dot(e).clamp(),s=Bd.dot(_d).clamp(),i=Bd.dot(t).clamp(),n=Rg({roughness:Fn,dotNH:i}),a=Eg({dotNV:s,dotNL:r});return Ln.mul(n).mul(a)})),Cg=Yi((({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=on(r,s.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i})).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),Mg=Yi((({f:e})=>{const t=e.length();return Lo(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Bg=Yi((({v1:e,v2:t})=>{const r=e.dot(t),s=r.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),a=i.div(n),o=r.greaterThan(0).select(a,Lo(r.mul(r).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)})).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),Pg=Yi((({N:e,V:t,P:r,mInv:s,p0:i,p1:n,p2:a,p3:o})=>{const u=n.sub(i).toVar(),l=o.sub(i).toVar(),d=u.cross(l),c=cn().toVar();return Ji(d.dot(r.sub(i)).greaterThanEqual(0),(()=>{const u=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(u).negate(),d=s.mul(Tn(u,l,e).transpose()).toVar(),h=d.mul(i.sub(r)).normalize().toVar(),p=d.mul(n.sub(r)).normalize().toVar(),g=d.mul(a.sub(r)).normalize().toVar(),m=d.mul(o.sub(r)).normalize().toVar(),f=cn(0).toVar();f.addAssign(Bg({v1:h,v2:p})),f.addAssign(Bg({v1:p,v2:g})),f.addAssign(Bg({v1:g,v2:m})),f.addAssign(Bg({v1:m,v2:h})),c.assign(cn(Mg({f:f})))})),c})).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Lg=Yi((({P:e,p0:t,p1:r,p2:s,p3:i})=>{const n=r.sub(t).toVar(),a=i.sub(t).toVar(),o=n.cross(a),u=cn().toVar();return Ji(o.dot(e.sub(t)).greaterThanEqual(0),(()=>{const n=t.sub(e).normalize().toVar(),a=r.sub(e).normalize().toVar(),o=s.sub(e).normalize().toVar(),l=i.sub(e).normalize().toVar(),d=cn(0).toVar();d.addAssign(Bg({v1:n,v2:a})),d.addAssign(Bg({v1:a,v2:o})),d.addAssign(Bg({v1:o,v2:l})),d.addAssign(Bg({v1:l,v2:n})),u.assign(cn(Mg({f:d.abs()})))})),u})).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"P",type:"vec3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Fg=1/6,Ig=e=>xa(Fg,xa(e,xa(e,e.negate().add(3)).sub(3)).add(1)),Dg=e=>xa(Fg,xa(e,xa(e,xa(3,e).sub(6))).add(4)),Ug=e=>xa(Fg,xa(e,xa(e,xa(-3,e).add(3)).add(3)).add(1)),Vg=e=>xa(Fg,Go(e,3)),Og=e=>Ig(e).add(Dg(e)),Gg=e=>Ug(e).add(Vg(e)),kg=e=>ya(-1,Dg(e).div(Ig(e).add(Dg(e)))),zg=e=>ya(1,Vg(e).div(Ug(e).add(Vg(e)))),$g=(e,t,r)=>{const s=e.uvNode,i=xa(s,t.zw).add(.5),n=ao(i),a=lo(i),o=Og(a.x),u=Gg(a.x),l=kg(a.x),d=zg(a.x),c=kg(a.y),h=zg(a.y),p=on(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=on(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=on(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=on(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=Og(a.y).mul(ya(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=Gg(a.y).mul(ya(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},Wg=Yi((([e,t])=>{const r=on(e.size(sn(t))),s=on(e.size(sn(t.add(1)))),i=Ta(1,r),n=Ta(1,s),a=$g(e,mn(i,r),ao(t)),o=$g(e,mn(n,s),oo(t));return lo(t).mix(a,o)})),Hg=Yi((([e,t])=>{const r=t.mul(gl(e));return Wg(e,r)})),jg=Yi((([e,t,r,s,i])=>{const n=cn(Yo(t.negate(),uo(e),Ta(1,s))),a=cn(xo(i[0].xyz),xo(i[1].xyz),xo(i[2].xyz));return uo(n).mul(r.mul(a))})).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),qg=Yi((([e,t])=>e.mul(Xo(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Xg=np(),Kg=np(),Yg=Yi((([e,t,r],{material:s})=>{const i=(s.side===w?Xg:Kg).sample(e),n=so(Bl.x).mul(qg(t,r));return Wg(i,n)})),Qg=Yi((([e,t,r])=>(Ji(r.notEqual(0),(()=>{const s=ro(t).negate().div(r);return eo(s.negate().mul(e))})),cn(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Zg=Yi((([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=mn().toVar(),f=cn().toVar();const i=d.sub(1).mul(g.mul(.025)),n=cn(d.sub(i),d,d.add(i));Wh({start:0,end:3},(({i:i})=>{const d=n.element(i),g=jg(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(mn(y,1))),x=on(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(on(x.x,x.y.oneMinus()));const T=Yg(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(Qg(xo(g),h,p).element(i)))})),m.a.divAssign(3)}else{const i=jg(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(mn(n,1))),y=on(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(on(y.x,y.y.oneMinus())),m=Yg(y,r,d),f=s.mul(Qg(xo(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=cn(Sg({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return mn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())})),Jg=Tn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),em=(e,t)=>e.sub(t).div(e.add(t)).pow2(),tm=Yi((({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=qo(e,t,Qo(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();Ji(a.lessThan(0),(()=>cn(1)));const o=a.sqrt(),u=em(n,e),l=sg({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=rn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return cn(1).add(t).div(cn(1).sub(t))})(i.clamp(0,.9999)),g=em(p,n.toVec3()),m=sg({f0:g,f90:1,dotVH:o}),f=cn(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(s,o,2),b=cn(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(cn(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Wh({start:1,end:2,condition:"<=",name:"m"},(({m:e})=>{N.mulAssign(T);const t=((e,t)=>{const r=e.mul(2*Math.PI*1e-9),s=cn(54856e-17,44201e-17,52481e-17),i=cn(1681e3,1795300,2208400),n=cn(43278e5,93046e5,66121e5),a=rn(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(r.mul(2239900).add(t.x).cos()).mul(r.pow2().mul(-45282e5).exp());let o=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(r).add(t).cos()).mul(r.pow2().negate().mul(n).exp());return o=cn(o.x.add(a),o.y,o.z).div(1.0685e-7),Jg.mul(o)})(rn(e).mul(y),rn(e).mul(b)).mul(2);v.addAssign(N.mul(t))})),v.max(cn(0))})).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),rm=Yi((({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.pow2(),n=ou(r.lessThan(.25),rn(-339.2).mul(i).add(rn(161.4).mul(r)).sub(25.9),rn(-8.48).mul(i).add(rn(14.3).mul(r)).sub(9.95)),a=ou(r.lessThan(.25),rn(44).mul(i).sub(rn(23.7).mul(r)).add(3.26),rn(1.97).mul(i).sub(rn(3.27).mul(r)).add(.72));return ou(r.lessThan(.25),0,rn(.1).mul(r).sub(.025)).add(n.mul(s).add(a).exp()).mul(1/Math.PI).saturate()})),sm=cn(.04),im=rn(1);class nm extends Jp{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=r,this.anisotropy=s,this.transmission=i,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=cn().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=cn().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=cn().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=cn().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=cn().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Bd.dot(_d).clamp();this.iridescenceFresnel=tm({outsideIOR:rn(1),eta2:Dn,cosTheta1:e,thinFilmThickness:Un,baseF0:zn}),this.iridescenceF0=Ag({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=bd,r=jl.sub(bd).normalize(),s=Pd,i=e.context;i.backdrop=Zg(s,r,Cn,En,zn,$n,t,id,$l,kl,Kn,Qn,Jn,Zn,this.dispersion?ea:null),i.backdropAlpha=Yn,En.a.mulAssign(qo(1,i.backdrop.a,Yn))}super.start(e)}computeMultiscattering(e,t,r){const s=Bd.dot(_d).clamp(),i=vg({roughness:Cn,dotNV:s}),n=this.iridescenceF0?In.mix(zn,this.iridescenceF0):zn,a=n.mul(i.x).add(r.mul(i.y)),o=i.x.add(i.y).oneMinus(),u=n.add(n.oneMinus().mul(.047619)),l=a.mul(u).div(o.mul(u).oneMinus());e.addAssign(a),t.addAssign(l.mul(o))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Bd.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(s.mul(wg({lightDirection:e}))),!0===this.clearcoat){const r=Ld.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(xg({lightDirection:e,f0:sm,f90:im,roughness:Pn,normalView:Ld})))}r.directDiffuse.addAssign(s.mul(ig({diffuseColor:En.rgb}))),r.directSpecular.addAssign(s.mul(Ng({lightDirection:e,f0:zn,f90:1,roughness:Cn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s,reflectedLight:i,ltc_1:n,ltc_2:a}){const o=t.add(r).sub(s),u=t.sub(r).sub(s),l=t.sub(r).add(s),d=t.add(r).add(s),c=Bd,h=_d,p=Td.toVar(),g=Cg({N:c,V:h,roughness:Cn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=Tn(cn(m.x,0,m.y),cn(0,1,0),cn(m.z,0,m.w)).toVar(),b=zn.mul(f.x).add(zn.oneMinus().mul(f.y)).toVar();i.directSpecular.addAssign(e.mul(b).mul(Pg({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(En).mul(Pg({N:c,V:h,P:p,mInv:Tn(1,0,0,0,1,0,0,0,1),p0:o,p1:u,p2:l,p3:d})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(t.mul(ig({diffuseColor:En})))}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Ln,rm({normal:Bd,viewDir:_d,roughness:Fn}))),!0===this.clearcoat){const e=Ld.dot(_d).clamp(),t=Sg({dotNV:e,specularColor:sm,specularF90:im,roughness:Pn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=cn().toVar("singleScattering"),n=cn().toVar("multiScattering"),a=r.mul(1/Math.PI);this.computeMultiscattering(i,n,$n);const o=i.add(n),u=En.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(t.mul(i)),s.indirectSpecular.addAssign(n.mul(a)),s.indirectDiffuse.addAssign(u.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Bd.dot(_d).clamp().add(t),i=Cn.mul(-16).oneMinus().negate().exp2(),n=t.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),r.indirectDiffuse.mulAssign(t),r.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Ld.dot(_d).clamp(),r=sg({dotVH:e,f0:sm,f90:im}),s=t.mul(Bn.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Bn));t.assign(s)}if(!0===this.sheen){const e=Ln.r.max(Ln.g).max(Ln.b).mul(.157).oneMinus(),r=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(r)}}}const am=rn(1),om=rn(-2),um=rn(.8),lm=rn(-1),dm=rn(.4),cm=rn(2),hm=rn(.305),pm=rn(3),gm=rn(.21),mm=rn(4),fm=rn(4),ym=rn(16),bm=Yi((([e])=>{const t=cn(yo(e)).toVar(),r=rn(-1).toVar();return Ji(t.x.greaterThan(t.z),(()=>{Ji(t.x.greaterThan(t.y),(()=>{r.assign(ou(e.x.greaterThan(0),0,3))})).Else((()=>{r.assign(ou(e.y.greaterThan(0),1,4))}))})).Else((()=>{Ji(t.z.greaterThan(t.y),(()=>{r.assign(ou(e.z.greaterThan(0),2,5))})).Else((()=>{r.assign(ou(e.y.greaterThan(0),1,4))}))})),r})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),xm=Yi((([e,t])=>{const r=on().toVar();return Ji(t.equal(0),(()=>{r.assign(on(e.z,e.y).div(yo(e.x)))})).ElseIf(t.equal(1),(()=>{r.assign(on(e.x.negate(),e.z.negate()).div(yo(e.y)))})).ElseIf(t.equal(2),(()=>{r.assign(on(e.x.negate(),e.y).div(yo(e.z)))})).ElseIf(t.equal(3),(()=>{r.assign(on(e.z.negate(),e.y).div(yo(e.x)))})).ElseIf(t.equal(4),(()=>{r.assign(on(e.x.negate(),e.z).div(yo(e.y)))})).Else((()=>{r.assign(on(e.x,e.y).div(yo(e.z)))})),xa(.5,r.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Tm=Yi((([e])=>{const t=rn(0).toVar();return Ji(e.greaterThanEqual(um),(()=>{t.assign(am.sub(e).mul(lm.sub(om)).div(am.sub(um)).add(om))})).ElseIf(e.greaterThanEqual(dm),(()=>{t.assign(um.sub(e).mul(cm.sub(lm)).div(um.sub(dm)).add(lm))})).ElseIf(e.greaterThanEqual(hm),(()=>{t.assign(dm.sub(e).mul(pm.sub(cm)).div(dm.sub(hm)).add(cm))})).ElseIf(e.greaterThanEqual(gm),(()=>{t.assign(hm.sub(e).mul(mm.sub(pm)).div(hm.sub(gm)).add(pm))})).Else((()=>{t.assign(rn(-2).mul(so(xa(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),_m=Yi((([e,t])=>{const r=e.toVar();r.assign(xa(2,r).sub(1));const s=cn(r,1).toVar();return Ji(t.equal(0),(()=>{s.assign(s.zyx)})).ElseIf(t.equal(1),(()=>{s.assign(s.xzy),s.xz.mulAssign(-1)})).ElseIf(t.equal(2),(()=>{s.x.mulAssign(-1)})).ElseIf(t.equal(3),(()=>{s.assign(s.zyx),s.xz.mulAssign(-1)})).ElseIf(t.equal(4),(()=>{s.assign(s.xzy),s.xy.mulAssign(-1)})).ElseIf(t.equal(5),(()=>{s.z.mulAssign(-1)})),s})).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),vm=Yi((([e,t,r,s,i,n])=>{const a=rn(r),o=cn(t),u=Xo(Tm(a),om,n),l=lo(u),d=ao(u),c=cn(Nm(e,o,d,s,i,n)).toVar();return Ji(l.notEqual(0),(()=>{const t=cn(Nm(e,o,d.add(1),s,i,n)).toVar();c.assign(qo(c,t,l))})),c})),Nm=Yi((([e,t,r,s,i,n])=>{const a=rn(r).toVar(),o=cn(t),u=rn(bm(o)).toVar(),l=rn(Lo(fm.sub(a),0)).toVar();a.assign(Lo(a,fm));const d=rn(to(a)).toVar(),c=on(xm(o,u).mul(d.sub(2)).add(1)).toVar();return Ji(u.greaterThan(2),(()=>{c.y.addAssign(d),u.subAssign(3)})),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(xa(3,ym))),c.y.addAssign(xa(4,to(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(on(),on())})),Sm=Yi((({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=ho(s),l=r.mul(u).add(i.cross(r).mul(co(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return Nm(e,l,t,n,a,o)})),Am=Yi((({n:e,latitudinal:t,poleAxis:r,outputDirection:s,weights:i,samples:n,dTheta:a,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})=>{const h=cn(ou(t,r,Oo(r,s))).toVar();Ji(h.equal(cn(0)),(()=>{h.assign(cn(s.z,0,s.x.negate()))})),h.assign(uo(h));const p=cn().toVar();return p.addAssign(i.element(0).mul(Sm({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Wh({start:sn(1),end:e},(({i:e})=>{Ji(e.greaterThanEqual(n),(()=>{Hh()}));const t=rn(a.mul(rn(e))).toVar();p.addAssign(i.element(e).mul(Sm({theta:t.mul(-1),axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),p.addAssign(i.element(e).mul(Sm({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))})),mn(p,1)})),Rm=Yi((([e])=>{const t=nn(e).toVar();return t.assign(t.shiftLeft(nn(16)).bitOr(t.shiftRight(nn(16)))),t.assign(t.bitAnd(nn(1431655765)).shiftLeft(nn(1)).bitOr(t.bitAnd(nn(2863311530)).shiftRight(nn(1)))),t.assign(t.bitAnd(nn(858993459)).shiftLeft(nn(2)).bitOr(t.bitAnd(nn(3435973836)).shiftRight(nn(2)))),t.assign(t.bitAnd(nn(252645135)).shiftLeft(nn(4)).bitOr(t.bitAnd(nn(4042322160)).shiftRight(nn(4)))),t.assign(t.bitAnd(nn(16711935)).shiftLeft(nn(8)).bitOr(t.bitAnd(nn(4278255360)).shiftRight(nn(8)))),rn(t).mul(2.3283064365386963e-10)})),Em=Yi((([e,t])=>on(rn(e).div(rn(t)),Rm(e)))),wm=Yi((([e,t,r])=>{const s=cn(t).toVar(),i=rn(r),n=i.mul(i).toVar(),a=uo(cn(n.mul(s.x),n.mul(s.y),s.z)).toVar(),o=a.x.mul(a.x).add(a.y.mul(a.y)),u=ou(o.greaterThan(0),cn(a.y.negate(),a.x,0).div(io(o)),cn(1,0,0)).toVar(),l=Oo(a,u).toVar(),d=io(e.x),c=xa(2,3.14159265359).mul(e.y),h=d.mul(ho(c)).toVar(),p=d.mul(co(c)).toVar(),g=xa(.5,a.z.add(1));p.assign(g.oneMinus().mul(io(h.mul(h).oneMinus())).add(g.mul(p)));const m=u.mul(h).add(l.mul(p)).add(a.mul(io(Lo(0,h.mul(h).add(p.mul(p)).oneMinus()))));return uo(cn(n.mul(m.x),n.mul(m.y),Lo(0,m.z)))})),Cm=Yi((({roughness:e,mipInt:t,envMap:r,N_immutable:s,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=cn(s).toVar(),l=cn(0).toVar(),d=rn(0).toVar();return Ji(e.lessThan(.001),(()=>{l.assign(Nm(r,u,t,n,a,o))})).Else((()=>{const s=ou(yo(u.z).lessThan(.999),cn(0,0,1),cn(1,0,0)),c=uo(Oo(s,u)).toVar(),h=Oo(u,c).toVar();Wh({start:nn(0),end:i},(({i:s})=>{const p=Em(s,i),g=wm(p,cn(0,0,1),e),m=uo(c.mul(g.x).add(h.mul(g.y)).add(u.mul(g.z))),f=uo(m.mul(Vo(u,m).mul(2)).sub(u)),y=Lo(Vo(u,f),0);Ji(y.greaterThan(0),(()=>{const e=Nm(r,f,t,n,a,o);l.addAssign(e.mul(y)),d.addAssign(y)}))})),Ji(d.greaterThan(0),(()=>{l.assign(l.div(d))}))})),mn(l,1)})),Mm=[.125,.215,.35,.446,.526,.582],Bm=20,Pm=new ye(-1,1,1,-1,0,1),Lm=new Te(90,1),Fm=new t;let Im=null,Dm=0,Um=0;const Vm=new s,Om=new WeakMap,Gm=[3,1,5,0,4,2],km=_m(dl(),ll("faceIndex")).normalize(),zm=cn(km.x,km.y,km.z);class $m{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Vm,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){d('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}Im=this._renderer.getRenderTarget(),Dm=this._renderer.getActiveCubeFace(),Um=this._renderer.getActiveMipmapLevel();const u=o||this._allocateTarget();return u.depthBuffer=!0,this._init(u),this._sceneToCubeUV(e,r,s,u,a),t>0&&this._blur(u,0,0,t),this._applyPMREM(u),this._cleanup(u),u}async fromSceneAsync(e,t=0,r=.1,s=100,i={}){return v('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){d('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return v('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){d("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return v('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=qm(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Xm(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===B||e.mapping===P?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Im,Dm,Um),e.scissorTest=!1,Hm(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Im=this._renderer.getRenderTarget(),Dm=this._renderer.getActiveCubeFace(),Um=this._renderer.getActiveMipmapLevel();const r=t||this._allocateTarget();return this._init(r),this._textureToCubeUV(e,r),this._applyPMREM(r),this._cleanup(r),r}_allocateTarget(){return Wm(3*Math.max(this._cubeSize,112),4*this._cubeSize)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=Wm(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],r=[],s=[];let i=e;const n=e-4+1+Mm.length;for(let a=0;a<n;a++){const n=Math.pow(2,i);t.push(n);let o=1/n;a>e-4?o=Mm[a-e+4-1]:0===a&&(o=0),r.push(o);const u=1/(n-2),l=-u,d=1+u,c=[l,l,d,l,d,d,l,l,d,d,l,d],h=6,p=6,g=3,m=2,f=1,y=new Float32Array(g*p*h),b=new Float32Array(m*p*h),x=new Float32Array(f*p*h);for(let e=0;e<h;e++){const t=e%3*2/3-1,r=e>2?0:-1,s=[t,r,0,t+2/3,r,0,t+2/3,r+1,0,t,r,0,t+2/3,r+1,0,t,r+1,0],i=Gm[e];y.set(s,g*p*i),b.set(c,m*p*i);const n=[i,i,i,i,i,i];x.set(n,f*p*i)}const T=new pe;T.setAttribute("position",new ge(y,g)),T.setAttribute("uv",new ge(b,m)),T.setAttribute("faceIndex",new ge(x,f)),s.push(new Q(T,null)),i>4&&i--}return{lodMeshes:s,sizeLods:t,sigmas:r}}(t)),this._blurMaterial=function(e,t,r){const i=Sl(new Array(Bm).fill(0)),n=ua(new s(0,1,0)),a=ua(0),o=rn(Bm),u=ua(0),l=ua(1),d=bl(),c=ua(0),h=rn(1/t),p=rn(1/r),g=rn(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:zm,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=jm("blur");return f.fragmentNode=Am({...m,latitudinal:u.equal(1)}),Om.set(f,m),f}(t,e.width,e.height)}}async _compileMaterial(e){const t=new Q(new pe,e);await this._renderer.compile(t,Pm)}_sceneToCubeUV(e,t,r,s,i){const n=Lm;n.near=t,n.far=r;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],u=this._renderer,l=u.autoClear;u.getClearColor(Fm),u.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new Q(new Y,new ae({name:"PMREM.Background",side:w,depthWrite:!1,depthTest:!1})));const d=this._backgroundBox,c=d.material;let h=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,h=!0):(c.color.copy(Fm),h=!0),u.setRenderTarget(s),u.clear(),h&&u.render(d,n);for(let t=0;t<6;t++){const r=t%3;0===r?(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x+o[t],i.y,i.z)):1===r?(n.up.set(0,0,a[t]),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y+o[t],i.z)):(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y,i.z+o[t]));const l=this._cubeSize;Hm(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=p}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===B||e.mapping===P;s?null===this._cubemapMaterial&&(this._cubemapMaterial=qm(e)):null===this._equirectMaterial&&(this._equirectMaterial=Xm(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;Hm(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,Pm)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let t=1;t<s;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=r}_applyGGXFilter(e,t,r){const s=this._renderer,i=this._pingPongRenderTarget;null===this._ggxMaterial&&(this._ggxMaterial=function(e,t,r){const s=bl(),i=ua(0),n=ua(0),a=rn(1/t),o=rn(1/r),u=rn(e),l={envMap:s,roughness:i,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:u},d=jm("ggx");return d.fragmentNode=Cm({...l,N_immutable:zm,GGX_SAMPLES:nn(512)}),Om.set(d,l),d}(this._lodMax,this._pingPongRenderTarget.width,this._pingPongRenderTarget.height));const n=this._ggxMaterial,a=this._lodMeshes[r];a.material=n;const o=Om.get(n),u=r/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),d=Math.sqrt(u*u-l*l)*(.05+.95*u),{_lodMax:c}=this,h=this._sizeLods[r],p=3*h*(r>c-4?r-c+4:0),g=4*(this._cubeSize-h);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=d,o.mipInt.value=c-t,Hm(i,p,g,3*h,2*h),s.setRenderTarget(i),s.render(a,Pm),i.texture.frame=(i.texture.frame||0)+1,o.envMap.value=i.texture,o.roughness.value=0,o.mipInt.value=c-r,Hm(e,p,g,3*h,2*h),s.setRenderTarget(e),s.render(a,Pm)}_blur(e,t,r,s,i){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,r,s,"latitudinal",i),this._halfBlur(n,e,r,r,s,"longitudinal",i)}_halfBlur(t,r,s,i,n,a,o){const u=this._renderer,l=this._blurMaterial;"latitudinal"!==a&&"longitudinal"!==a&&e("blur direction must be either latitudinal or longitudinal!");const c=this._lodMeshes[i];c.material=l;const h=Om.get(l),p=this._sizeLods[s]-1,g=isFinite(n)?Math.PI/(2*p):2*Math.PI/39,m=n/g,f=isFinite(n)?1+Math.floor(3*m):Bm;f>Bm&&d(`sigmaRadians, ${n}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const y=[];let b=0;for(let e=0;e<Bm;++e){const t=e/m,r=Math.exp(-t*t/2);y.push(r),0===e?b+=r:e<f&&(b+=2*r)}for(let e=0;e<y.length;e++)y[e]=y[e]/b;t.texture.frame=(t.texture.frame||0)+1,h.envMap.value=t.texture,h.samples.value=f,h.weights.array=y,h.latitudinal.value="latitudinal"===a?1:0,o&&(h.poleAxis.value=o);const{_lodMax:x}=this;h.dTheta.value=g,h.mipInt.value=x-s;const T=this._sizeLods[i];Hm(r,3*T*(i>x-4?i-x+4:0),4*(this._cubeSize-T),3*T,2*T),u.setRenderTarget(r),u.render(c,Pm)}}function Wm(e,t){const r=new me(e,t,{magFilter:J,minFilter:J,generateMipmaps:!1,type:ce,format:be,colorSpace:xe});return r.texture.mapping=fe,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function Hm(e,t,r,s,i){e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i)}function jm(e){const t=new Bp;return t.depthTest=!1,t.depthWrite=!1,t.blending=j,t.name=`PMREM_${e}`,t}function qm(e){const t=jm("cubemap");return t.fragmentNode=Qd(e,zm),t}function Xm(e){const t=jm("equirect");return t.fragmentNode=bl(e,Wp(zm),0),t}const Km=new WeakMap;function Ym(e,t,r){const s=function(e){let t=Km.get(e);void 0===t&&(t=new WeakMap,Km.set(e,t));return t}(t);let i=s.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const r=6;for(let s=0;s<r;s++)void 0!==e[s]&&t++;return t===r}(t))return null;i=r.fromCubemap(e,i)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;i=r.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,s.set(e,i)}return i.texture}class Qm extends ei{static get type(){return"PMREMNode"}constructor(e,t=null,r=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=r,this._generator=null;const s=new R;s.isRenderTargetTexture=!0,this._texture=bl(s),this._width=ua(0),this._height=ua(0),this._maxMip=ua(0),this.updateBeforeType=zs.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:r,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const r=t?t.pmremVersion:-1,s=this._value;r!==s.pmremVersion&&(t=!0===s.isPMREMTexture?s:Ym(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new $m(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=$d.mul(cn(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),vm(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Zm=Hi(Qm).setParameterLength(1,3),Jm=new WeakMap;class ef extends Qh{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const e=r.isTextureNode?r.value:t[r.property];let s=Jm.get(e);void 0===s&&(s=Zm(e),Jm.set(e,s)),r=s}const s=!0===t.useAnisotropy||t.anisotropy>0?Cc:Bd,i=r.context(tf(Cn,s)).mul(zd),n=r.context(rf(Pd)).mul(Math.PI).mul(zd),a=Hu(i),o=Hu(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(tf(Pn,Ld)).mul(zd),t=Hu(e);u.addAssign(t)}}}const tf=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=_d.negate().reflect(t),r=$o(e).mix(r,t).normalize(),r=r.transformDirection($l)),r),getTextureLevel:()=>e}},rf=e=>({getUV:()=>e,getTextureLevel:()=>rn(1)}),sf=new _e;class nf extends Bp{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(sf),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new ef(t):null}setupLightingModel(){return new nm}setupSpecular(){const e=qo(cn(.04),En.rgb,Mn);zn.assign(e),$n.assign(1)}setupVariants(){const e=this.metalnessNode?rn(this.metalnessNode):Kc;Mn.assign(e);let t=this.roughnessNode?rn(this.roughnessNode):Xc;t=pg({roughness:t}),Cn.assign(t),this.setupSpecular(),En.assign(mn(En.rgb.mul(e.oneMinus()),En.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const af=new ve;class of extends nf{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(af),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?rn(this.iorNode):lh;Kn.assign(e),zn.assign(qo(Po(ko(Kn.sub(1).div(Kn.add(1))).mul(Hc),cn(1)).mul(Wc),En.rgb,Mn)),$n.assign(qo(Wc,1,Mn))}setupLightingModel(){return new nm(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?rn(this.clearcoatNode):Qc,t=this.clearcoatRoughnessNode?rn(this.clearcoatRoughnessNode):Zc;Bn.assign(e),Pn.assign(pg({roughness:t}))}if(this.useSheen){const e=this.sheenNode?cn(this.sheenNode):th,t=this.sheenRoughnessNode?rn(this.sheenRoughnessNode):rh;Ln.assign(e),Fn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?rn(this.iridescenceNode):ih,t=this.iridescenceIORNode?rn(this.iridescenceIORNode):nh,r=this.iridescenceThicknessNode?rn(this.iridescenceThicknessNode):ah;In.assign(e),Dn.assign(t),Un.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?on(this.anisotropyNode):sh).toVar();On.assign(e.length()),Ji(On.equal(0),(()=>{e.assign(on(1,0))})).Else((()=>{e.divAssign(on(On)),On.assign(On.saturate())})),Vn.assign(On.pow2().mix(Cn.pow2(),1)),Gn.assign(Ec[0].mul(e.x).add(Ec[1].mul(e.y))),kn.assign(Ec[1].mul(e.x).sub(Ec[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?rn(this.transmissionNode):oh,t=this.thicknessNode?rn(this.thicknessNode):uh,r=this.attenuationDistanceNode?rn(this.attenuationDistanceNode):dh,s=this.attenuationColorNode?cn(this.attenuationColorNode):ch;if(Yn.assign(e),Qn.assign(t),Zn.assign(r),Jn.assign(s),this.useDispersion){const e=this.dispersionNode?rn(this.dispersionNode):bh;ea.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?cn(this.clearcoatNormalNode):Jc}setup(e){e.context.setupClearcoatNormal=()=>xu(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}class uf extends nm{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1,a=!1){super(e,t,r,s,i,n),this.useSSS=a}direct({lightDirection:e,lightColor:t,reflectedLight:r},s){if(!0===this.useSSS){const i=s.material,{thicknessColorNode:n,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:d}=i,c=e.add(Bd.mul(a)).normalize(),h=rn(_d.dot(c.negate()).saturate().pow(l).mul(d)),p=cn(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class lf extends of{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=rn(.1),this.thicknessAmbientNode=rn(0),this.thicknessAttenuationNode=rn(.1),this.thicknessPowerNode=rn(2),this.thicknessScaleNode=rn(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new uf(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useSSS)}copy(e){return this.thicknessColorNode=e.thicknessColorNode,this.thicknessDistortionNode=e.thicknessDistortionNode,this.thicknessAmbientNode=e.thicknessAmbientNode,this.thicknessAttenuationNode=e.thicknessAttenuationNode,this.thicknessPowerNode=e.thicknessPowerNode,this.thicknessScaleNode=e.thicknessScaleNode,super.copy(e)}}const df=Yi((({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=on(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=sc("gradientMap","texture").context({getUV:()=>i});return cn(e.r)}{const e=i.fwidth().mul(.5);return qo(cn(.7),cn(1),Qo(rn(.7).sub(e.x),rn(.7).add(e.x),i.x))}}));class cf extends Jp{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=df({normal:Rd,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(ig({diffuseColor:En.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(ig({diffuseColor:En}))),s.indirectDiffuse.mulAssign(t)}}const hf=new Ne;class pf extends Bp{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(hf),this.setValues(e)}setupLightingModel(){return new cf}}const gf=Yi((()=>{const e=cn(_d.z,0,_d.x.negate()).normalize(),t=_d.cross(e);return on(e.dot(Bd),t.dot(Bd)).mul(.495).add(.5)})).once(["NORMAL","VERTEX"])().toVar("matcapUV"),mf=new Se;class ff extends Bp{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(mf),this.setValues(e)}setupVariants(e){const t=gf;let r;r=e.material.matcap?sc("matcap","texture").context({getUV:()=>t}):cn(qo(.2,.8,t.y)),En.rgb.mulAssign(r.rgb)}}class yf extends ei{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:r}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),s=t.sin();return xn(e,s,s.negate(),e).mul(r)}{const e=t,s=_n(mn(1,0,0,0),mn(0,ho(e.x),co(e.x).negate(),0),mn(0,co(e.x),ho(e.x),0),mn(0,0,0,1)),i=_n(mn(ho(e.y),0,co(e.y),0),mn(0,1,0,0),mn(co(e.y).negate(),0,ho(e.y),0),mn(0,0,0,1)),n=_n(mn(ho(e.z),co(e.z).negate(),0,0),mn(co(e.z),ho(e.z),0,0),mn(0,0,1,0),mn(0,0,0,1));return s.mul(i).mul(n).mul(mn(r,1)).xyz}}}const bf=Hi(yf).setParameterLength(2),xf=new Ae;class Tf extends Bp{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(xf),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,{positionNode:s,rotationNode:i,scaleNode:n,sizeAttenuation:a}=this,o=cd.mul(cn(s||0));let u=on(id[0].xyz.length(),id[1].xyz.length());null!==n&&(u=u.mul(on(n))),r.isPerspectiveCamera&&!1===a&&(u=u.mul(o.z.negate()));let l=md.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>ki(new Mu(e,t,r)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=rn(i||eh),c=bf(l,d);return mn(o.xy.add(c),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const _f=new Re,vf=new r;class Nf extends Tf{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(_f),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return cd.mul(cn(e||fd)).xyz}setupVertexSprite(e){const{material:t,camera:r}=e,{rotationNode:s,scaleNode:i,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let u=null!==n?on(n):yh;u=u.mul(Cl),r.isPerspectiveCamera&&!0===a&&(u=u.mul(Sf.div(Td.z.negate()))),i&&i.isNode&&(u=u.mul(on(i)));let l=md.xy;if(s&&s.isNode){const e=rn(s);l=bf(l,e)}return l=l.mul(u),l=l.div(Fl.div(2)),l=l.mul(o.w),o=o.add(mn(l,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const Sf=ua(1).onFrameUpdate((function({renderer:e}){const t=e.getSize(vf);this.value=.5*t.y}));class Af extends Jp{constructor(){super(),this.shadowNode=rn(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){En.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(En.rgb)}}const Rf=new Ee;class Ef extends Bp{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(Rf),this.setValues(e)}setupLightingModel(){return new Af}}const wf=An("vec3"),Cf=An("vec3"),Mf=An("vec3");class Bf extends Jp{constructor(){super()}start(e){const{material:t}=e,r=An("vec3"),s=An("vec3");Ji(jl.sub(bd).length().greaterThan(ud.mul(2)),(()=>{r.assign(jl),s.assign(bd)})).Else((()=>{r.assign(bd),s.assign(jl)}));const i=s.sub(r),n=ua("int").onRenderUpdate((({material:e})=>e.steps)),a=i.length().div(n).toVar(),o=i.normalize().toVar(),u=rn(0).toVar(),l=cn(1).toVar();t.offsetNode&&u.addAssign(t.offsetNode.mul(a)),Wh(n,(()=>{const s=r.add(o.mul(u)),i=$l.mul(mn(s,1)).xyz;let n;null!==t.depthNode&&(Cf.assign(fp(cp(i.z,Ol,Gl))),e.context.sceneDepthNode=fp(t.depthNode).toVar()),e.context.positionWorld=s,e.context.shadowPositionWorld=s,e.context.positionView=i,wf.assign(0),t.scatteringNode&&(n=t.scatteringNode({positionRay:s})),super.start(e),n&&wf.mulAssign(n);const d=wf.mul(.01).negate().mul(a).exp();l.mulAssign(d),u.addAssign(a)})),Mf.addAssign(l.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?Ji(r.greaterThanEqual(Cf),(()=>{wf.addAssign(e)})):wf.addAssign(e)}direct({lightNode:e,lightColor:t},r){if(void 0===e.light.distance)return;const s=t.xyz.toVar();s.mulAssign(e.shadowNode),this.scatteringLight(s,r)}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s},i){const n=t.add(r).sub(s),a=t.sub(r).sub(s),o=t.sub(r).add(s),u=t.add(r).add(s),l=i.context.positionView,d=e.xyz.mul(Lg({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(Mf)}}class Pf extends Bp{static get type(){return"VolumeNodeMaterial"}constructor(e){super(),this.isVolumeNodeMaterial=!0,this.steps=25,this.offsetNode=null,this.scatteringNode=null,this.lights=!0,this.transparent=!0,this.side=w,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new Bf}}class Lf{constructor(e,t,r){this.renderer=e,this.nodes=t,this.info=r,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,r)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,r),this.renderer._inspector.finish()};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class Ff{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let r=0;r<e.length-1;r++)if(t=t.get(e[r]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let r=this.weakMap;for(let t=0;t<e.length-1;t++){const s=e[t];!1===r.has(s)&&r.set(s,new WeakMap),r=r.get(s)}return r.set(e[e.length-1],t),this}delete(e){let t=this.weakMap;for(let r=0;r<e.length-1;r++)if(t=t.get(e[r]),void 0===t)return!1;return t.delete(e[e.length-1])}}let If=0;class Df{constructor(e,t,r,s,i,n,a,o,u,l){this.id=If++,this._nodes=e,this._geometries=t,this.renderer=r,this.object=s,this.material=i,this.scene=n,this.camera=a,this.lightsNode=o,this.context=u,this.geometry=s.geometry,this.version=i.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=l,this.clippingContextCacheKey=null!==l?l.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,r=[],s=new Set,i={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),i[n.name]=e.version),void 0===e)continue;r.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;s.add(a)}return this.attributes=r,this.attributesId=i,this.vertexBuffers=Array.from(s.values()),r}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:r,group:s,drawRange:i}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let u=1;if(!0===r.isInstancedBufferGeometry?u=r.instanceCount:void 0!==e.count&&(u=Math.max(0,e.count)),0===u)return null;if(n.instanceCount=u,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let d=i.start*l,c=(i.start+i.count)*l;null!==s&&(d=Math.max(d,s.start*l),c=Math.min(c,(s.start+s.count)*l));const h=r.attributes.position;let p=1/0;o?p=a.count:null!=h&&(p=h.count),d=Math.max(d,0),c=Math.min(c,p);const g=c-d;return g<0||g===1/0?null:(n.vertexCount=g,n.firstVertex=d,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const r of Object.keys(e.attributes).sort()){const s=e.attributes[r];t+=r+",",s.data&&(t+=s.data.stride+","),s.offset&&(t+=s.offset+","),s.itemSize&&(t+=s.itemSize+","),s.normalized&&(t+="n,")}for(const r of Object.keys(e.morphAttributes).sort()){const s=e.morphAttributes[r];t+="morph-"+r+",";for(let e=0,r=s.length;e<r;e++){t+=s[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:r}=this;let s=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let r=Object.getPrototypeOf(e);for(;r;){const e=Object.getOwnPropertyDescriptors(r);for(const r in e)if(void 0!==e[r]){const s=e[r];s&&"function"==typeof s.get&&t.push(r)}r=Object.getPrototypeOf(r)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const i=t[e];let n;if(null!==i){const e=typeof i;"number"===e?n=0!==i?"1":"0":"object"===e?(n="{",i.isTexture&&(n+=i.mapping,!0===r.backend.isWebGPUBackend&&(n+=i.magFilter,n+=i.minFilter,n+=i.wrapS,n+=i.wrapT,n+=i.wrapR)),n+="}"):n=String(i)}else n=String(i);s+=n+","}return s+=this.clippingContextCacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(s+=e.uuid+","),s+=e.receiveShadow+",",As(s)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const r=this.geometry.getAttribute(t);if(void 0===r||e[t]!==r.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Es(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Es(e,1)),e=Es(e,this.camera.id),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Uf=[];class Vf{constructor(e,t,r,s,i,n){this.renderer=e,this.nodes=t,this.geometries=r,this.pipelines=s,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,r,s,i,n,a,o){const u=this.getChainMap(o);Uf[0]=e,Uf[1]=t,Uf[2]=n,Uf[3]=i;let l=u.get(Uf);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(Uf,l)):(l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),Uf.length=0,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Ff)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new Df(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.deleteForRender(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class Of{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const Gf=1,kf=2,zf=3,$f=4,Wf=16;class Hf extends Of{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const r=this.get(e);if(void 0===r.version)t===Gf?this.backend.createAttribute(e):t===kf?this.backend.createIndexAttribute(e):t===zf?this.backend.createStorageAttribute(e):t===$f&&this.backend.createIndirectStorageAttribute(e),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version<t.version||t.usage===b)&&(this.backend.updateAttribute(e),r.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function jf(e){return null!==e.index?e.index.version:e.attributes.position.version}function qf(e){const t=[],r=e.index,s=e.attributes.position;if(null!==r){const e=r.array;for(let r=0,s=e.length;r<s;r+=3){const s=e[r+0],i=e[r+1],n=e[r+2];t.push(s,i,i,n,n,s)}}else{for(let e=0,r=s.array.length/3-1;e<r;e+=3){const r=e+0,s=e+1,i=e+2;t.push(r,s,s,i,i,r)}}const i=new(we(t)?Ce:Me)(t,1);return i.version=jf(e),i}class Xf extends Of{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const r=()=>{this.info.memory.geometries--;const s=t.index,i=e.getAttributes();null!==s&&this.attributes.delete(s);for(const e of i)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",r),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,zf):this.updateAttribute(e,Gf);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,kf);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,$f)}updateAttribute(e,t){const r=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,r)):this.attributeCall.get(e.data)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e.data,r),this.attributeCall.set(e,r)):this.attributeCall.get(e)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e,r))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:r}=e;let s=t.index;if(!0===r.wireframe){const e=this.wireframes;let r=e.get(t);void 0===r?(r=qf(t),e.set(t,r)):r.version!==jf(t)&&(this.attributes.delete(r),r=qf(t),e.set(t,r)),s=r}return s}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class Kf{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(t,r,s){this.render.drawCalls++,t.isMesh||t.isSprite?this.render.triangles+=s*(r/3):t.isPoints?this.render.points+=s*r:t.isLineSegments?this.render.lines+=s*(r/2):t.isLine?this.render.lines+=s*(r-1):e("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class Yf{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Qf extends Yf{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class Zf extends Yf{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Jf=0;class ey{constructor(e,t,r,s=null,i=null){this.id=Jf++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class ty extends Of{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:r}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new ey(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.createProgram(a));const o=this._getComputeCacheKey(e,a);let u=this.caches.get(o);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(i),u=this._getComputePipeline(e,a,o,t)),u.usedTimes++,a.usedTimes++,s.version=e.version,s.pipeline=u}return s.pipeline}getForRender(e,t=null){const{backend:r}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new ey(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new ey(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.createProgram(u));const l=this._getRenderCacheKey(e,o,u);let d=this.caches.get(l);void 0===d?(i&&0===i.usedTimes&&this._releasePipeline(i),d=this._getRenderPipeline(e,o,u,l,t)):e.pipeline=d,d.usedTimes++,o.usedTimes++,u.usedTimes++,s.pipeline=d}return s.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,r,s){r=r||this._getComputeCacheKey(e,t);let i=this.caches.get(r);return void 0===i&&(i=new Zf(r,t),this.caches.set(r,i),this.backend.createComputePipeline(i,s)),i}_getRenderPipeline(e,t,r,s,i){s=s||this._getRenderCacheKey(e,t,r);let n=this.caches.get(s);return void 0===n&&(n=new Qf(s,t,r),this.caches.set(s,n),e.pipeline=n,this.backend.createRenderPipeline(e,i)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,r){return t.id+","+r.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,r=e.stage;this.programs[r].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class ry extends Of{constructor(e,t,r,s,i,n){super(),this.backend=e,this.textures=r,this.pipelines=i,this.attributes=s,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?$f:zf;this.attributes.update(e,r)}}_update(e,t){const{backend:r}=this;let s=!1,i=!0,n=0,a=0;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?$f:zf;this.attributes.update(e,r)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampledTexture){const e=t.update(),o=t.texture,u=this.textures.get(o);e&&(this.textures.updateTexture(o),t.generation!==u.generation&&(t.generation=u.generation,s=!0,i=!1));if(void 0!==r.get(o).externalTexture||u.isDefaultTexture?i=!1:(n=10*n+o.id,a+=o.version),!0===o.isStorageTexture&&!0===o.mipmapsAutoUpdate){const e=this.get(o);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(o)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(o),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,s=!0,i=!1)}}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function sy(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function iy(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function ny(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&e.side===C&&!1===e.forceSinglePass}class ay{constructor(e,t,r){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,r),this.lightsArray=[],this.scene=t,this.camera=r,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,r,s,i,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:r,groupOrder:s,renderOrder:e.renderOrder,z:i,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=r,o.groupOrder=s,o.renderOrder=e.renderOrder,o.z=i,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(ny(r)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(ny(r)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||sy),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||iy),this.transparent.length>1&&this.transparent.sort(t||iy)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.groupOrder=null,t.renderOrder=null,t.z=null,t.group=null,t.clippingContext=null}}}const oy=[];class uy{constructor(e){this.lighting=e,this.lists=new Ff}get(e,t){const r=this.lists;oy[0]=e,oy[1]=t;let s=r.get(oy);return void 0===s&&(s=new ay(this.lighting,e,t),r.set(oy,s)),oy.length=0,s}dispose(){this.lists=new Ff}}let ly=0;class dy{constructor(){this.id=ly++,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new i,this.scissor=!1,this.scissorValue=new i,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.isRenderContext=!0}getCacheKey(){return cy(this)}}function cy(e){const{textures:t,activeCubeFace:r,activeMipmapLevel:s}=e,i=[r,s];for(const e of t)i.push(e.id);return Rs(i)}const hy=[],py=new Z,gy=new Be;class my{constructor(){this.chainMaps={}}get(e,t,r=null){let s;if(hy[0]=e,hy[1]=t,null===r)s="default";else{const e=r.texture.format;s=`${r.textures.length}:${e}:${r.samples}:${r.depthBuffer}:${r.stencilBuffer}`}const i=this._getChainMap(s);let n=i.get(hy);return void 0===n&&(n=new dy,i.set(hy,n)),hy.length=0,null!==r&&(n.sampleCount=0===r.samples?1:r.samples),n}getForClear(e=null){return this.get(py,gy,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new Ff)}dispose(){this.chainMaps={}}}const fy=new s;class yy extends Of{constructor(e,t,r){super(),this.renderer=e,this.backend=t,this.info=r}updateRenderTarget(e,t=0){const r=this.get(e),s=0===e.samples?1:e.samples,i=r.depthTextureMips||(r.depthTextureMips={}),n=e.textures,a=this.getSize(n[0]),o=a.width>>t,u=a.height>>t;let l=e.depthTexture||i[t];const d=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&d&&(l=new z,l.format=e.stencilBuffer?Pe:Le,l.type=e.stencilBuffer?Fe:N,l.image.width=o,l.image.height=u,l.image.depth=a.depth,l.renderTarget=e,l.isArrayTexture=!0===e.multiview&&a.depth>1,i[t]=l),r.width===a.width&&a.height===r.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=u,l.image.depth=l.isArrayTexture?l.image.depth:1)),r.width=a.width,r.height=a.height,r.textures=n,r.depthTexture=l||null,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,r.renderTarget=e,r.sampleCount!==s&&(c=!0,l&&(l.needsUpdate=!0),r.sampleCount=s);const h={sampleCount:s};if(!0!==e.isXRRenderTarget){for(let e=0;e<n.length;e++){const t=n[e];c&&(t.needsUpdate=!0),this.updateTexture(t,h)}l&&this.updateTexture(l,h)}!0!==r.initialized&&(r.initialized=!0,r.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",r.onDispose))}updateTexture(e,t={}){const r=this.get(e);if(!0===r.initialized&&r.version===e.version)return;const s=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(s&&!0===r.initialized&&i.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:Ie}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,s||!0===e.isStorageTexture||!0===e.isExternalTexture)i.createTexture(e,t),r.generation=e.version;else if(e.version>0){const s=e.image;if(void 0===s)d("Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)d("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const r=[];for(const t of e.images)r.push(t);t.images=r}else t.image=s;void 0!==r.isDefaultTexture&&!0!==r.isDefaultTexture||(i.createTexture(e,t),r.isDefaultTexture=!1,r.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version;!0!==r.initialized&&(r.initialized=!0,r.generation=e.version,this.info.memory.textures++,e.isVideoTexture&&p.getTransfer(e.colorSpace)!==g&&d("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),r.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",r.onDispose)),r.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=fy){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),"undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement?(t.width=r.videoWidth||1,t.height=r.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&r instanceof VideoFrame?(t.width=r.displayWidth||1,t.height=r.displayHeight||1,t.depth=1):(t.width=r.width||1,t.height=r.height||1,t.depth=e.isCubeTexture?6:r.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,r){let s;return s=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),r=t.textures,s=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e<r.length;e++)this._destroyTexture(r[e]);s&&this._destroyTexture(s),this.delete(e),this.backend.delete(e)}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const r=t.isDefaultTexture;this.backend.destroyTexture(e,r),this.delete(e),this.info.memory.textures--}}}class by extends t{constructor(e,t,r,s=1){super(e,t,r),this.a=s}set(e,t,r,s=1){return this.a=s,super.set(e,t,r)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class xy extends Sn{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(t,r){const s=this.getNodeType(t),i=t.getStructTypeNode(s);let n;return null!==i?n=i.getMemberType(t,r):(e(`TSL: Member "${r}" not found in struct "${s}".`),n="float"),n}getHash(){return this.uuid}generate(){return this.name}}class Ty extends Qs{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput?this.outputNode.getElementType(e):"void"}getNodeType(e){return this.hasOutput?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput?this.outputNode.getMemberType(e,t):"void"}addToStack(t){return!0!==t.isNode?(e("TSL: Invalid node added to stack."),this):(this.nodes.push(t),this)}If(e,t){const r=new Gi(t);return this._currentCond=ou(e,r),this.addToStack(this._currentCond)}ElseIf(e,t){const r=new Gi(t),s=ou(e,r);return this._currentCond.elseNode=s,this._currentCond=s,this}Else(e){return this._currentCond.elseNode=new Gi(e),this}Switch(e){return this._expressionNode=ki(e),this}Case(...t){const r=[];if(t.length>=2)for(let e=0;e<t.length-1;e++)r.push(this._expressionNode.equal(ki(t[e])));else e("TSL: Invalid parameter length. Case() requires at least two parameters.");const s=new Gi(t[t.length-1]);let i=r[0];for(let e=1;e<r.length;e++)i=i.or(r[e]);const n=ou(i,s);return null===this._currentCond?(this._currentCond=n,this.addToStack(this._currentCond)):(this._currentCond.elseNode=n,this._currentCond=n,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let r=0;for(const s of this.getChildren())s.isVarNode&&!0===s.intent&&!0!==s.isAssign(e)||(t["node"+r++]=s);return t.outputNode||null}get hasOutput(){return this.outputNode&&this.outputNode.isNode}build(e,...t){const r=Zi();Qi(this),e.setActiveStack(this);const s=e.buildStage;for(const t of this.nodes)if(!t.isVarNode||!0!==t.intent||!0===t.isAssign(e))if("setup"===s)t.build(e);else if("analyze"===s)t.build(e,this);else if("generate"===s){const r=e.getDataFromNode(t,"any").stages,s=r&&r[e.shaderStage];if(t.isVarNode&&s&&1===s.length&&s[0]&&s[0].isStackNode)continue;t.build(e,"void")}let i;return i=this.hasOutput?this.outputNode.build(e,...t):super.build(e,...t),Qi(r),e.removeActiveStack(this),i}}const _y=Hi(Ty).setParameterLength(0,1);class vy extends Qs{static get type(){return"StructTypeNode"}constructor(e,t=null){var r;super("struct"),this.membersLayout=(r=e,Object.entries(r).map((([e,t])=>"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1}))),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=0;for(const r of this.membersLayout){const s=r.type,i=Ls(s)*e,n=t%8,a=n%Fs(s),o=n+a;t+=a,0!==o&&8-o<i&&(t+=8-o),t+=i}return 8*Math.ceil(t/8)/e}getMemberType(e,t){const r=this.membersLayout.find((e=>e.name===t));return r?r.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class Ny extends Qs{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class Sy extends Qs{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(e){const t=e.getNodeProperties(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;t<r.length;t++){const i="m"+t,n=r[t].getNodeType(e);s.push({name:i,type:n,index:t})}t.membersLayout=s,t.structType=e.getOutputStructTypeFromNode(this,t.membersLayout)}return t.structType.name}generate(e){const t=e.getOutputStructName(),r=this.members,s=""!==t?t+".":"";for(let t=0;t<r.length;t++){const i=r[t].build(e);e.addLineFlowCode(`${s}m${t} = ${i}`,this)}return t}}const Ay=Hi(Sy);function Ry(e,t){for(let r=0;r<e.length;r++)if(e[r].name===t)return r;return-1}class Ey extends Sy{static get type(){return"MRTNode"}constructor(e){super(),this.outputNodes=e,this.isMRTNode=!0}has(e){return void 0!==this.outputNodes[e]}get(e){return this.outputNodes[e]}merge(e){const t={...this.outputNodes,...e.outputNodes};return wy(t)}setup(e){const t=this.outputNodes,r=[],s=e.renderer.getRenderTarget().textures;for(const e in t){r[Ry(s,e)]=mn(t[e])}return this.members=r,super.setup(e)}}const wy=Hi(Ey);class Cy extends ei{static get type(){return"BitcastNode"}constructor(e,t,r=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=r,this.isBitcastNode=!0}getNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),r=e.getTypeLength(t);return e.getTypeFromLength(r,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let r="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);r=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else r=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,r)}( ${this.valueNode.build(e,r)} )`}}const My=qi(Cy).setParameterLength(2),By=Yi((([e])=>{const t=e.toUint().mul(747796405).add(2891336453),r=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return r.shiftRight(22).bitXor(r).toFloat().mul(1/2**32)})),Py=(e,t)=>Go(xa(4,e.mul(ba(1,e))),t),Ly=Yi((([e])=>e.fract().sub(.5).abs())).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),Fy=Yi((([e])=>cn(Ly(e.z.add(Ly(e.y.mul(1)))),Ly(e.z.add(Ly(e.x.mul(1)))),Ly(e.y.add(Ly(e.x.mul(1))))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Iy=Yi((([e,t,r])=>{const s=cn(e).toVar(),i=rn(1.4).toVar(),n=rn(0).toVar(),a=cn(s).toVar();return Wh({start:rn(0),end:rn(3),type:"float",condition:"<="},(()=>{const e=cn(Fy(a.mul(2))).toVar();s.addAssign(e.add(r.mul(rn(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=rn(Ly(s.z.add(Ly(s.x.add(Ly(s.y)))))).toVar();n.addAssign(o.div(i)),a.addAssign(.14)})),n})).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class Dy extends Qs{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}getNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let r=this._candidateFn;if(null===r){let s=null,i=-1;for(const r of this.functionNodes){const n=r.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const a=n.inputs;if(t.length===a.length){let n=0;for(let r=0;r<t.length;r++){const s=t[r],i=a[r];s.getNodeType(e)===i.type&&n++}n>i&&(s=r,i=n)}}this._candidateFn=r=s}return r}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const Uy=Hi(Dy),Vy=e=>(...t)=>Uy(e,...t),Oy=ua(0).setGroup(na).onRenderUpdate((e=>e.time)),Gy=ua(0).setGroup(na).onRenderUpdate((e=>e.deltaTime)),ky=ua(0,"uint").setGroup(na).onRenderUpdate((e=>e.frameId)),zy=Yi((([e,t,r=on(.5)])=>bf(e.sub(r),t).add(r))),$y=Yi((([e,t,r=on(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))})),Wy=Yi((({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=id.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=id;const i=$l.mul(s);return Vi(t)&&(i[0][0]=id[0].length(),i[0][1]=0,i[0][2]=0),Vi(r)&&(i[1][0]=0,i[1][1]=id[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,kl.mul(i).mul(fd)})),Hy=Yi((([e=null])=>{const t=fp();return fp(up(e)).sub(t).lessThan(0).select(Ml,e)}));class jy extends Qs{static get type(){return"SpriteSheetUVNode"}constructor(e,t=dl(),r=rn(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=r}setup(){const{frameNode:e,uvNode:t,countNode:r}=this,{width:s,height:i}=r,n=e.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=r.reciprocal(),l=on(a,o);return t.add(l).mul(u)}}const qy=Hi(jy).setParameterLength(3),Xy=Yi((([e,t=null,r=null,s=rn(1),i=fd,n=Ed])=>{let a=n.abs().normalize();a=a.div(a.dot(cn(1)));const o=i.yz.mul(s),u=i.zx.mul(s),l=i.xy.mul(s),d=e.value,c=null!==t?t.value:d,h=null!==r?r.value:d,p=bl(d,o).mul(a.x),g=bl(c,u).mul(a.y),m=bl(h,l).mul(a.z);return ya(p,g,m)})),Ky=new De,Yy=new s,Qy=new s,Zy=new s,Jy=new o,eb=new s(0,0,-1),tb=new i,rb=new s,sb=new s,ib=new i,nb=new r,ab=new me,ob=Ml.flipX();ab.depthTexture=new z(1,1);let ub=!1;class lb extends fl{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||ab.texture,ob),this._reflectorBaseNode=e.reflector||new db(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=ki(new lb({defaultTexture:ab.depthTexture,reflector:this._reflectorBaseNode}))}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class db extends Qs{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new Ue,resolutionScale:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1,samples:o=0}=t;this.textureNode=e,this.target=r,this.resolutionScale=s,void 0!==t.resolution&&(v('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=i,this.bounces=n,this.depth=a,this.samples=o,this.updateBeforeType=n?zs.RENDER:zs.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolutionScale;t.getDrawingBufferSize(nb),e.setSize(Math.round(nb.width*r),Math.round(nb.height*r))}setup(e){return this._updateResolution(ab,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new me(0,0,{type:ce,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=Ve,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new z),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&ub)return!1;ub=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(nb),this._updateResolution(o,s),Qy.setFromMatrixPosition(n.matrixWorld),Zy.setFromMatrixPosition(r.matrixWorld),Jy.extractRotation(n.matrixWorld),Yy.set(0,0,1),Yy.applyMatrix4(Jy),rb.subVectors(Qy,Zy);let u=!1;if(!0===rb.dot(Yy)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(ub=!1);u=!0}rb.reflect(Yy).negate(),rb.add(Qy),Jy.extractRotation(r.matrixWorld),eb.set(0,0,-1),eb.applyMatrix4(Jy),eb.add(Zy),sb.subVectors(Qy,eb),sb.reflect(Yy).negate(),sb.add(Qy),a.coordinateSystem=r.coordinateSystem,a.position.copy(rb),a.up.set(0,1,0),a.up.applyMatrix4(Jy),a.up.reflect(Yy),a.lookAt(sb),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),Ky.setFromNormalAndCoplanarPoint(Yy,Qy),Ky.applyMatrix4(a.matrixWorldInverse),tb.set(Ky.normal.x,Ky.normal.y,Ky.normal.z,Ky.constant);const l=a.projectionMatrix;ib.x=(Math.sign(tb.x)+l.elements[8])/l.elements[0],ib.y=(Math.sign(tb.y)+l.elements[9])/l.elements[5],ib.z=-1,ib.w=(1+l.elements[10])/l.elements[14],tb.multiplyScalar(1/tb.dot(ib));l.elements[2]=tb.x,l.elements[6]=tb.y,l.elements[10]=s.coordinateSystem===h?tb.z-0:tb.z+1-0,l.elements[14]=tb.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const d=s.getRenderTarget(),c=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0;const g=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),t.name=g,s.setMRT(c),s.setRenderTarget(d),s.autoClear=p,i.visible=!0,ub=!1,this.forceUpdate=!1}get resolution(){return v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const cb=new ye(-1,1,1,-1,0,1);class hb extends pe{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Oe([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Oe(t,2))}}const pb=new hb;class gb extends Q{constructor(e=null){super(pb,e),this.camera=cb,this.isQuadMesh=!0}async renderAsync(e){v('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,cb)}render(e){e.render(this,cb)}}const mb=new r;class fb extends fl{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:ce}){const i=new me(t,r,s);super(i.texture,dl()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=r,this.pixelRatio=1,this.renderTarget=i,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new gb(new Bp),this.updateBeforeType=zs.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const r=e*this.pixelRatio,s=t*this.pixelRatio;this.renderTarget.setSize(r,s),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;if(this.textureNeedsUpdate=!1,!0===this.autoResize){const t=e.getPixelRatio(),r=e.getSize(mb),s=Math.floor(r.width*t),i=Math.floor(r.height*t);s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}let t="RTT";this.node.name&&(t=this.node.name+" [ "+t+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=t;const r=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(r)}clone(){const e=new fl(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const yb=(e,...t)=>ki(new fb(ki(e),...t)),bb=Yi((([e,t,r],s)=>{let i;s.renderer.coordinateSystem===h?(e=on(e.x,e.y.oneMinus()).mul(2).sub(1),i=mn(cn(e,t),1)):i=mn(cn(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=mn(r.mul(i));return n.xyz.div(n.w)})),xb=Yi((([e,t])=>{const r=t.mul(mn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return on(s.x,s.y.oneMinus())})),Tb=Yi((([e,t,r])=>{const s=hl(xl(t)),i=un(e.mul(s)).toVar(),n=xl(t,i).toVar(),a=xl(t,i.sub(un(2,0))).toVar(),o=xl(t,i.sub(un(1,0))).toVar(),u=xl(t,i.add(un(1,0))).toVar(),l=xl(t,i.add(un(2,0))).toVar(),d=xl(t,i.add(un(0,2))).toVar(),c=xl(t,i.add(un(0,1))).toVar(),h=xl(t,i.sub(un(0,1))).toVar(),p=xl(t,i.sub(un(0,2))).toVar(),g=yo(ba(rn(2).mul(o).sub(a),n)).toVar(),m=yo(ba(rn(2).mul(u).sub(l),n)).toVar(),f=yo(ba(rn(2).mul(c).sub(d),n)).toVar(),y=yo(ba(rn(2).mul(h).sub(p),n)).toVar(),b=bb(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(bb(e.sub(on(rn(1).div(s.x),0)),o,r)),b.negate().add(bb(e.add(on(rn(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(bb(e.add(on(0,rn(1).div(s.y))),c,r)),b.negate().add(bb(e.sub(on(0,rn(1).div(s.y))),h,r)));return uo(Oo(x,T))})),_b=Yi((([e])=>lo(rn(52.9829189).mul(lo(Vo(e,on(.06711056,.00583715))))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]});class vb extends Qs{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(dl())}sample(e){return this.callback(e)}}class Nb extends Qs{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===Nb.OBJECT?this.updateType=zs.OBJECT:e===Nb.MATERIAL?this.updateType=zs.RENDER:e===Nb.BEFORE_OBJECT?this.updateBeforeType=zs.OBJECT:e===Nb.BEFORE_MATERIAL&&(this.updateBeforeType=zs.RENDER)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}Nb.OBJECT="object",Nb.MATERIAL="material",Nb.BEFORE_OBJECT="beforeObject",Nb.BEFORE_MATERIAL="beforeMaterial";const Sb=(e,t)=>ki(new Nb(e,t)).toStack();class Ab extends U{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class Rb extends ge{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class Eb extends Qs{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const wb=ji(Eb),Cb=new M,Mb=new o;class Bb extends Qs{static get type(){return"SceneNode"}constructor(e=Bb.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(t){const r=this.scope,s=null!==this.scene?this.scene:t.scene;let i;return r===Bb.BACKGROUND_BLURRINESS?i=ec("backgroundBlurriness","float",s):r===Bb.BACKGROUND_INTENSITY?i=ec("backgroundIntensity","float",s):r===Bb.BACKGROUND_ROTATION?i=ua("mat4").setName("backgroundRotation").setGroup(na).onRenderUpdate((()=>{const e=s.background;return null!==e&&e.isTexture&&e.mapping!==Ge?(Cb.copy(s.backgroundRotation),Cb.x*=-1,Cb.y*=-1,Cb.z*=-1,Mb.makeRotationFromEuler(Cb)):Mb.identity(),Mb})):e("SceneNode: Unknown scope:",r),i}}Bb.BACKGROUND_BLURRINESS="backgroundBlurriness",Bb.BACKGROUND_INTENSITY="backgroundIntensity",Bb.BACKGROUND_ROTATION="backgroundRotation";const Pb=ji(Bb,Bb.BACKGROUND_BLURRINESS),Lb=ji(Bb,Bb.BACKGROUND_INTENSITY),Fb=ji(Bb,Bb.BACKGROUND_ROTATION);class Ib extends fl{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=Ws.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){let r;return r=null!==this.storeNode?this.generateStore(e):super.generate(e,t),r}toReadWrite(){return this.setAccess(Ws.READ_WRITE)}toReadOnly(){return this.setAccess(Ws.READ_ONLY)}toWriteOnly(){return this.setAccess(Ws.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:r,storeNode:s,depthNode:i}=t,n=super.generate(e,"property"),a=r.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(e,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e}}const Db=Hi(Ib).setParameterLength(1,3),Ub=Yi((({texture:e,uv:t})=>{const r=1e-4,s=cn().toVar();return Ji(t.x.lessThan(r),(()=>{s.assign(cn(1,0,0))})).ElseIf(t.y.lessThan(r),(()=>{s.assign(cn(0,1,0))})).ElseIf(t.z.lessThan(r),(()=>{s.assign(cn(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{s.assign(cn(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{s.assign(cn(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{s.assign(cn(0,0,-1))})).Else((()=>{const r=.01,i=e.sample(t.add(cn(-.01,0,0))).r.sub(e.sample(t.add(cn(r,0,0))).r),n=e.sample(t.add(cn(0,-.01,0))).r.sub(e.sample(t.add(cn(0,r,0))).r),a=e.sample(t.add(cn(0,0,-.01))).r.sub(e.sample(t.add(cn(0,0,r))).r);s.assign(cn(i,n,a))})),s.normalize()}));class Vb extends fl{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return cn(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!e.isFlipY()||!0!==r.isRenderTargetTexture&&!0!==r.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(sn(hl(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return Ub({texture:this,uv:e})}}const Ob=Hi(Vb).setParameterLength(1,3);class Gb extends Jd{static get type(){return"UserDataNode"}constructor(e,t,r=null){super(e,t,r),this.userData=r}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const kb=new WeakMap;class zb extends ei{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=zs.OBJECT,this.updateAfterType=zs.OBJECT,this.previousModelWorldMatrix=ua(new o),this.previousProjectionMatrix=ua(new o).setGroup(na),this.previousCameraViewMatrix=ua(new o)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=Wb(r);this.previousModelWorldMatrix.value.copy(s);const i=$b(t);i.frameId!==e&&(i.frameId=e,void 0===i.previousProjectionMatrix?(i.previousProjectionMatrix=new o,i.previousCameraViewMatrix=new o,i.currentProjectionMatrix=new o,i.currentCameraViewMatrix=new o,i.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(i.previousProjectionMatrix.copy(i.currentProjectionMatrix),i.previousCameraViewMatrix.copy(i.currentCameraViewMatrix)),i.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(i.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(i.previousCameraViewMatrix))}updateAfter({object:e}){Wb(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?kl:ua(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(cd).mul(fd),s=this.previousProjectionMatrix.mul(t).mul(yd),i=r.xy.div(r.w),n=s.xy.div(s.w);return ba(i,n)}}function $b(e){let t=kb.get(e);return void 0===t&&(t={},kb.set(e,t)),t}function Wb(e,t=0){const r=$b(e);let s=r[t];return void 0===s&&(r[t]=s=new o,r[t].copy(e.matrixWorld)),s}const Hb=ji(zb),jb=Yi((([e])=>Yb(e.rgb))),qb=Yi((([e,t=rn(1)])=>t.mix(Yb(e.rgb),e.rgb))),Xb=Yi((([e,t=rn(1)])=>{const r=ya(e.r,e.g,e.b).div(3),s=e.r.max(e.g.max(e.b)),i=s.sub(r).mul(t).mul(-3);return qo(e.rgb,s,i)})),Kb=Yi((([e,t=rn(1)])=>{const r=cn(.57735,.57735,.57735),s=t.cos();return cn(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(Vo(r,e.rgb).mul(s.oneMinus())))))})),Yb=(e,t=cn(p.getLuminanceCoefficients(new s)))=>Vo(e,t),Qb=Yi((([e,t=cn(1),r=cn(0),i=cn(1),n=rn(1),a=cn(p.getLuminanceCoefficients(new s,xe))])=>{const o=e.rgb.dot(cn(a)),u=Lo(e.rgb.mul(t).add(r),0).toVar(),l=u.pow(i).toVar();return Ji(u.r.greaterThan(0),(()=>{u.r.assign(l.r)})),Ji(u.g.greaterThan(0),(()=>{u.g.assign(l.g)})),Ji(u.b.greaterThan(0),(()=>{u.b.assign(l.b)})),u.assign(o.add(u.sub(o).mul(n))),mn(u.rgb,e.a)}));class Zb extends ei{static get type(){return"PosterizeNode"}constructor(e,t){super(),this.sourceNode=e,this.stepsNode=t}setup(){const{sourceNode:e,stepsNode:t}=this;return e.mul(t).floor().div(t)}}const Jb=Hi(Zb).setParameterLength(2),ex=new r;class tx extends fl{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class rx extends tx{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class sx extends ei{static get type(){return"PassNode"}constructor(e,t,r,s={}){super("vec4"),this.scope=e,this.scene=t,this.camera=r,this.options=s,this._pixelRatio=1,this._width=1,this._height=1;const i=new z;i.isRenderTargetTexture=!0,i.name="depth";const n=new me(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ce,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=ua(0),this._cameraFar=ua(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=zs.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return d("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return d("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const r=this._textures[e],s=this.renderTarget.textures.indexOf(r);this.renderTarget.textures[s]=t,this._textures[e]=t,this._previousTextures[e]=r,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=ki(new rx(this,e)),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=ki(new rx(this,e,!0)),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar;this._viewZNodes[e]=t=hp(this.getTextureNode(e),r,s)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=dp(i,r,s)}return t}async compileAsync(e){const t=e.getRenderTarget(),r=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(r)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getColorBufferType(),this.scope===sx.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:r}=this;let s,i;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(i=1,s=t.xr.getCamera(),t.xr.updateCamera(s),ex.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(ex)),this._pixelRatio=i,this.setSize(ex.width,ex.height);const a=t.getRenderTarget(),o=t.getMRT(),u=t.autoClear,l=s.layers.mask;this._cameraNear.value=s.near,this._cameraFar.value=s.far,null!==this._layers&&(s.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0;const d=r.name;r.name=this.name?this.name:r.name,t.render(r,s),r.name=d,t.setRenderTarget(a),t.setMRT(o),t.autoClear=u,s.layers.mask=l}setSize(e,t){this._width=e,this._height=t;const r=Math.floor(this._width*this._pixelRatio*this._resolutionScale),s=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(r,s),null!==this._scissor&&this.renderTarget.scissor.copy(this._scissor),null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,r,s){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new i),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,r,s),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,r,s){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new i),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,r,s),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}sx.COLOR="color",sx.DEPTH="depth";class ix extends sx{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(sx.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,r=t.getRenderObjectFunction();t.setRenderObjectFunction(((e,r,s,i,n,a,o,u)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const l=this._getOutlineMaterial(n);t.renderObject(e,r,s,i,l,a,o,u)}t.renderObject(e,r,s,i,n,a,o,u)})),super.updateBefore(e),t.setRenderObjectFunction(r)}_createMaterial(){const e=new Bp;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=w;const t=Ed.negate(),r=kl.mul(cd),s=rn(1),i=r.mul(mn(fd,1)),n=r.mul(mn(fd.add(t),1)),a=uo(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=mn(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const nx=Yi((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),ax=Yi((([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),ox=Yi((([e,t])=>{const r=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),s=e.mul(e.mul(6.2).add(1.7)).add(.06);return r.div(s).pow(2.2)})).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),ux=Yi((([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),r=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(r)})),lx=Yi((([e,t])=>{const r=Tn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=Tn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=ux(e),(e=s.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),dx=Tn(cn(1.6605,-.1246,-.0182),cn(-.5876,1.1329,-.1006),cn(-.0728,-.0083,1.1187)),cx=Tn(cn(.6274,.0691,.0164),cn(.3293,.9195,.088),cn(.0433,.0113,.8956)),hx=Yi((([e])=>{const t=cn(e).toVar(),r=cn(t.mul(t)).toVar(),s=cn(r.mul(r)).toVar();return rn(15.5).mul(s.mul(r)).sub(xa(40.14,s.mul(t))).add(xa(31.96,s).sub(xa(6.868,r.mul(t))).add(xa(.4298,r).add(xa(.1191,t).sub(.00232))))})),px=Yi((([e,t])=>{const r=cn(e).toVar(),s=Tn(cn(.856627153315983,.137318972929847,.11189821299995),cn(.0951212405381588,.761241990602591,.0767994186031903),cn(.0482516061458583,.101439036467562,.811302368396859)),i=Tn(cn(1.1271005818144368,-.1413297634984383,-.14132976349843826),cn(-.11060664309660323,1.157823702216272,-.11060664309660294),cn(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=rn(-12.47393),a=rn(4.026069);return r.mulAssign(t),r.assign(cx.mul(r)),r.assign(s.mul(r)),r.assign(Lo(r,1e-10)),r.assign(so(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(Xo(r,0,1)),r.assign(hx(r)),r.assign(i.mul(r)),r.assign(Go(Lo(cn(0),r),cn(2.2))),r.assign(dx.mul(r)),r.assign(Xo(r,0,1)),r})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),gx=Yi((([e,t])=>{const r=rn(.76),s=rn(.15);e=e.mul(t);const i=Po(e.r,Po(e.g,e.b)),n=ou(i.lessThan(.08),i.sub(xa(6.25,i.mul(i))),.04);e.subAssign(n);const a=Lo(e.r,Lo(e.g,e.b));Ji(a.lessThan(r),(()=>e));const o=ba(1,r),u=ba(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=ba(1,Ta(1,s.mul(a.sub(u)).add(1)));return qo(e,cn(u),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class mx extends Qs{static get type(){return"CodeNode"}constructor(e="",t=[],r=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=r}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const r of t)r.build(e);const r=e.getCodeFromNode(this,this.getNodeType(e));return r.code=this.code,r.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const fx=Hi(mx).setParameterLength(1,3);class yx extends mx{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let r=t.nodeFunction;return void 0===r&&(r=e.parser.parseFunction(this.code),t.nodeFunction=r),r}generate(e,t){super.generate(e);const r=this.getNodeFunction(e),s=r.name,i=r.type,n=e.getCodeFromNode(this,i);""!==s&&(n.name=s);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}const bx=(e,t=[],r="")=>{for(let e=0;e<t.length;e++){const r=t[e];"function"==typeof r&&(t[e]=r.functionNode)}const s=ki(new yx(e,t,r)),i=(...e)=>s.call(...e);return i.functionNode=s,i};class xx extends Qs{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new u,this.isScriptableValueNode=!0}get isScriptableOutputNode(){return null!==this.outputType}set value(e){this._value!==e&&(this._cache&&"URL"===this.inputType&&this.value.value instanceof ArrayBuffer&&(URL.revokeObjectURL(this._cache),this._cache=null),this._value=e,this.events.dispatchEvent({type:"change"}),this.refresh())}get value(){return this._value}refresh(){this.events.dispatchEvent({type:"refresh"})}getValue(){const e=this.value;if(e&&null===this._cache&&"URL"===this.inputType&&e.value instanceof ArrayBuffer)this._cache=URL.createObjectURL(new Blob([e.value]));else if(e&&null!==e.value&&void 0!==e.value&&(("URL"===this.inputType||"String"===this.inputType)&&"string"==typeof e.value||"Number"===this.inputType&&"number"==typeof e.value||"Vector2"===this.inputType&&e.value.isVector2||"Vector3"===this.inputType&&e.value.isVector3||"Vector4"===this.inputType&&e.value.isVector4||"Color"===this.inputType&&e.value.isColor||"Matrix3"===this.inputType&&e.value.isMatrix3||"Matrix4"===this.inputType&&e.value.isMatrix4))return e.value;return this._cache||e}getNodeType(e){return this.value&&this.value.isNode?this.value.getNodeType(e):"float"}setup(){return this.value&&this.value.isNode?this.value:rn()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Vs(this.value):e.value=this.value?this.value.toJSON(e.meta).uuid:null:e.value=null,e.inputType=this.inputType,e.outputType=this.outputType}deserialize(e){super.deserialize(e);let t=null;null!==e.value&&(t="ArrayBuffer"===e.inputType?Os(e.value):"Texture"===e.inputType?e.meta.textures[e.value]:e.meta.nodes[e.value]||null),this.value=t,this.inputType=e.inputType,this.outputType=e.outputType}}const Tx=Hi(xx).setParameterLength(1);class _x extends Map{get(e,t=null,...r){if(this.has(e))return super.get(e);if(null!==t){const s=t(...r);return this.set(e,s),s}}}class vx{constructor(e){this.scriptableNode=e}get parameters(){return this.scriptableNode.parameters}get layout(){return this.scriptableNode.getLayout()}getInputLayout(e){return this.scriptableNode.getInputLayout(e)}get(e){const t=this.parameters[e];return t?t.getValue():null}}const Nx=new _x;class Sx extends Qs{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new _x,this._output=Tx(null),this._outputs={},this._source=this.source,this._method=null,this._object=null,this._value=null,this._needsOutputUpdate=!0,this.onRefresh=this.onRefresh.bind(this),this.isScriptableNode=!0}get source(){return this.codeNode?this.codeNode.code:""}setLocal(e,t){return this._local.set(e,t)}getLocal(e){return this._local.get(e)}onRefresh(){this._refresh()}getInputLayout(e){for(const t of this.getLayout())if(t.inputType&&(t.id===e||t.name===e))return t}getOutputLayout(e){for(const t of this.getLayout())if(t.outputType&&(t.id===e||t.name===e))return t}setOutput(e,t){const r=this._outputs;return void 0===r[e]?r[e]=Tx(t):r[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const r=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),r[e]=t,r[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),r[e]=t,r[e].events.addEventListener("refresh",this.onRefresh)):void 0===r[e]?(r[e]=Tx(t),r[e].events.addEventListener("refresh",this.onRefresh)):r[e].value=t,this}getValue(){return this.getDefaultOutput().getValue()}deleteParameter(e){let t=this.parameters[e];return t&&(t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.removeEventListener("refresh",this.onRefresh)),this}clearParameters(){for(const e of Object.keys(this.parameters))this.deleteParameter(e);return this.needsUpdate=!0,this}call(e,...t){const r=this.getObject()[e];if("function"==typeof r)return r(...t)}async callAsync(e,...t){const r=this.getObject()[e];if("function"==typeof r)return"AsyncFunction"===r.constructor.name?await r(...t):r(...t)}getNodeType(e){return this.getDefaultOutputNode().getNodeType(e)}refresh(e=null){null!==e?this.getOutput(e).refresh():this._refresh()}getObject(){if(this.needsUpdate&&this.dispose(),null!==this._object)return this._object;const e=new vx(this),t=Nx.get("THREE"),r=Nx.get("TSL"),s=this.getMethod(),i=[e,this._local,Nx,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,r];this._object=s(...i);const n=this._object.layout;if(n&&(!1===n.cache&&this._local.clear(),this._output.outputType=n.outputType||null,Array.isArray(n.elements)))for(const e of n.elements){const t=e.id||e.name;e.inputType&&(void 0===this.getParameter(t)&&this.setParameter(t,null),this.getParameter(t).inputType=e.inputType),e.outputType&&(void 0===this.getOutput(t)&&this.setOutput(t,null),this.getOutput(t).outputType=e.outputType)}return this._object}deserialize(e){super.deserialize(e);for(const e in this.parameters){let t=this.parameters[e];t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.addEventListener("refresh",this.onRefresh)}}getLayout(){return this.getObject().layout}getDefaultOutputNode(){const e=this.getDefaultOutput().value;return e&&e.isNode?e:rn()}getDefaultOutput(){return this._exec()._output}getMethod(){if(this.needsUpdate&&this.dispose(),null!==this._method)return this._method;const e=["layout","init","main","dispose"].join(", "),t="\nreturn { ...output, "+e+" };",r="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],r),this._method}dispose(){null!==this._method&&(this._object&&"function"==typeof this._object.dispose&&this._object.dispose(),this._method=null,this._object=null,this._source=null,this._value=null,this._needsOutputUpdate=!0,this._output.value=null,this._outputs={})}setup(){return this.getDefaultOutputNode()}getCacheKey(e){const t=[As(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const r in this.parameters)t.push(this.parameters[r].getCacheKey(e));return Rs(t)}set needsUpdate(e){!0===e&&this.dispose()}get needsUpdate(){return this.source!==this._source}_exec(){return null===this.codeNode||(!0===this._needsOutputUpdate&&(this._value=this.call("main"),this._needsOutputUpdate=!1),this._output.value=this._value),this}_refresh(){this.needsUpdate=!0,this._exec(),this._output.refresh()}}const Ax=Hi(Sx).setParameterLength(1,2);function Rx(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||Td.z).negate()}const Ex=Yi((([e,t],r)=>{const s=Rx(r);return Qo(e,t,s)})),wx=Yi((([e],t)=>{const r=Rx(t);return e.mul(e,r,r).negate().exp().oneMinus()})),Cx=Yi((([e,t])=>mn(t.toFloat().mix(Hn.rgb,e.toVec3()),Hn.a)));let Mx=null,Bx=null;class Px extends Qs{static get type(){return"RangeNode"}constructor(e=rn(),t=rn()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),r=this.getConstNode(this.maxNode),s=e.getTypeLength(Is(t.value)),i=e.getTypeLength(Is(r.value));return s>i?s:i}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse((e=>{!0===e.isConstNode&&(t=e)})),null===t)throw new Error('THREE.TSL: No "ConstNode" found in node graph.');return t}setup(e){const t=e.object;let r=null;if(t.count>1){const s=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),a=s.value,o=n.value,u=e.getTypeLength(Is(a)),d=e.getTypeLength(Is(o));Mx=Mx||new i,Bx=Bx||new i,Mx.setScalar(0),Bx.setScalar(0),1===u?Mx.setScalar(a):a.isColor?Mx.set(a.r,a.g,a.b,1):Mx.set(a.x,a.y,a.z||0,a.w||0),1===d?Bx.setScalar(o):o.isColor?Bx.set(o.r,o.g,o.b,1):Bx.set(o.x,o.y,o.z||0,o.w||0);const c=4,h=c*t.count,p=new Float32Array(h);for(let e=0;e<h;e++){const t=e%c,r=Mx.getComponent(t),s=Bx.getComponent(t);p[e]=l.lerp(r,s,Math.random())}const g=this.getNodeType(e);if(t.count<=4096)r=_l(p,"vec4",t.count).element(Ah).convert(g);else{const t=new U(p,4);e.geometry.setAttribute("__range"+this.id,t),r=Ou(t).convert(g)}}else r=rn(0);return r}}const Lx=Hi(Px).setParameterLength(2);class Fx extends Qs{static get type(){return"ComputeBuiltinNode"}constructor(e,t){super(t),this._builtinName=e}getHash(e){return this.getBuiltinName(e)}getNodeType(){return this.nodeType}setBuiltinName(e){return this._builtinName=e,this}getBuiltinName(){return this._builtinName}hasBuiltin(e){return e.hasBuiltin(this._builtinName)}generate(e,t){const r=this.getBuiltinName(e),s=this.getNodeType(e);return"compute"===e.shaderStage?e.format(r,s,t):(d(`ComputeBuiltinNode: Compute built-in value ${r} can not be accessed in the ${e.shaderStage} stage`),e.generateConst(s))}serialize(e){super.serialize(e),e.global=this.global,e._builtinName=this._builtinName}deserialize(e){super.deserialize(e),this.global=e.global,this._builtinName=e._builtinName}}const Ix=(e,t)=>ki(new Fx(e,t)),Dx=Ix("numWorkgroups","uvec3"),Ux=Ix("workgroupId","uvec3"),Vx=Ix("globalId","uvec3"),Ox=Ix("localId","uvec3"),Gx=Ix("subgroupSize","uint");const kx=Hi(class extends Qs{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class zx extends Zs{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let r;const s=e.context.assign;if(r=super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}class $x extends Qs{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return ki(new zx(this,e))}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class Wx extends Qs{static get type(){return"AtomicFunctionNode"}constructor(e,t,r){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=r,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),r=t.parents,s=this.method,i=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,u=[];u.push(`&${a.build(e,n)}`),null!==o&&u.push(o.build(e,n));const l=`${e.getMethod(s,i)}( ${u.join(", ")} )`;if(!(!!r&&(1===r.length&&!0===r[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Ju(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}Wx.ATOMIC_LOAD="atomicLoad",Wx.ATOMIC_STORE="atomicStore",Wx.ATOMIC_ADD="atomicAdd",Wx.ATOMIC_SUB="atomicSub",Wx.ATOMIC_MAX="atomicMax",Wx.ATOMIC_MIN="atomicMin",Wx.ATOMIC_AND="atomicAnd",Wx.ATOMIC_OR="atomicOr",Wx.ATOMIC_XOR="atomicXor";const Hx=Hi(Wx),jx=(e,t,r)=>Hx(e,t,r).toStack();class qx extends ei{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=r}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,r=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(r)?0:e.getTypeLength(r))?t:r}getNodeType(e){const t=this.method;return t===qx.SUBGROUP_ELECT?"bool":t===qx.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const r=this.method,s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(r===qx.SUBGROUP_BROADCAST||r===qx.SUBGROUP_SHUFFLE||r===qx.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,s),a.build(e,"float"===t?"int":s))}else r===qx.SUBGROUP_SHUFFLE_XOR||r===qx.SUBGROUP_SHUFFLE_DOWN||r===qx.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,s),a.build(e,"uint")):(null!==n&&o.push(n.build(e,i)),null!==a&&o.push(a.build(e,i)));const u=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(r,s)}${u}`,s,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}qx.SUBGROUP_ELECT="subgroupElect",qx.SUBGROUP_BALLOT="subgroupBallot",qx.SUBGROUP_ADD="subgroupAdd",qx.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",qx.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",qx.SUBGROUP_MUL="subgroupMul",qx.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",qx.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",qx.SUBGROUP_AND="subgroupAnd",qx.SUBGROUP_OR="subgroupOr",qx.SUBGROUP_XOR="subgroupXor",qx.SUBGROUP_MIN="subgroupMin",qx.SUBGROUP_MAX="subgroupMax",qx.SUBGROUP_ALL="subgroupAll",qx.SUBGROUP_ANY="subgroupAny",qx.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",qx.QUAD_SWAP_X="quadSwapX",qx.QUAD_SWAP_Y="quadSwapY",qx.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",qx.SUBGROUP_BROADCAST="subgroupBroadcast",qx.SUBGROUP_SHUFFLE="subgroupShuffle",qx.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",qx.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",qx.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",qx.QUAD_BROADCAST="quadBroadcast";const Xx=qi(qx,qx.SUBGROUP_ELECT).setParameterLength(0),Kx=qi(qx,qx.SUBGROUP_BALLOT).setParameterLength(1),Yx=qi(qx,qx.SUBGROUP_ADD).setParameterLength(1),Qx=qi(qx,qx.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),Zx=qi(qx,qx.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),Jx=qi(qx,qx.SUBGROUP_MUL).setParameterLength(1),eT=qi(qx,qx.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),tT=qi(qx,qx.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),rT=qi(qx,qx.SUBGROUP_AND).setParameterLength(1),sT=qi(qx,qx.SUBGROUP_OR).setParameterLength(1),iT=qi(qx,qx.SUBGROUP_XOR).setParameterLength(1),nT=qi(qx,qx.SUBGROUP_MIN).setParameterLength(1),aT=qi(qx,qx.SUBGROUP_MAX).setParameterLength(1),oT=qi(qx,qx.SUBGROUP_ALL).setParameterLength(0),uT=qi(qx,qx.SUBGROUP_ANY).setParameterLength(0),lT=qi(qx,qx.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),dT=qi(qx,qx.QUAD_SWAP_X).setParameterLength(1),cT=qi(qx,qx.QUAD_SWAP_Y).setParameterLength(1),hT=qi(qx,qx.QUAD_SWAP_DIAGONAL).setParameterLength(1),pT=qi(qx,qx.SUBGROUP_BROADCAST).setParameterLength(2),gT=qi(qx,qx.SUBGROUP_SHUFFLE).setParameterLength(2),mT=qi(qx,qx.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),fT=qi(qx,qx.SUBGROUP_SHUFFLE_UP).setParameterLength(2),yT=qi(qx,qx.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),bT=qi(qx,qx.QUAD_BROADCAST).setParameterLength(1);let xT;function TT(e){xT=xT||new WeakMap;let t=xT.get(e);return void 0===t&&xT.set(e,t={}),t}function _T(e){const t=TT(e);return t.shadowMatrix||(t.shadowMatrix=ua("mat4").setGroup(na).onRenderUpdate((t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix))))}function vT(e,t=bd){const r=_T(e).mul(t);return r.xyz.div(r.w)}function NT(e){const t=TT(e);return t.position||(t.position=ua(new s).setGroup(na).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld))))}function ST(e){const t=TT(e);return t.targetPosition||(t.targetPosition=ua(new s).setGroup(na).onRenderUpdate(((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld))))}function AT(e){const t=TT(e);return t.viewPosition||(t.viewPosition=ua(new s).setGroup(na).onRenderUpdate((({camera:t},r)=>{r.value=r.value||new s,r.value.setFromMatrixPosition(e.matrixWorld),r.value.applyMatrix4(t.matrixWorldInverse)})))}const RT=e=>$l.transformDirection(NT(e).sub(ST(e))),ET=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},wT=new WeakMap,CT=[];class MT extends Qs{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=An("vec3","totalDiffuse"),this.totalSpecularNode=An("vec3","totalSpecular"),this.outgoingLightNode=An("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;t<e.length;t++){const r=e[t];if(CT.push(r.id),CT.push(r.castShadow?1:0),!0===r.isSpotLight){const e=null!==r.map?r.map.id:-1,t=r.colorNode?r.colorNode.getCacheKey():-1;CT.push(e,t)}}const t=Rs(CT);return CT.length=0,t}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const r of t.nodes)r.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],r=this._lightNodes,s=(e=>e.sort(((e,t)=>e.id-t.id)))(this._lights),i=e.renderer.library;for(const e of s)if(e.isNode)t.push(ki(e));else{let s=null;if(null!==r&&(s=ET(e.id,r)),null===s){const r=i.getLightNodeClass(e.constructor);if(null===r){d(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let s=null;wT.has(e)?s=wT.get(e):(s=ki(new r(e)),wT.set(e,s)),t.push(s)}}this._lightNodes=t}setupDirectLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.direct({...r,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.directRectArea({...r,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const r of t)r.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let r=this.outgoingLightNode;const s=e.context,i=s.lightingModel,n=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;s.outgoingLight=r;const o=e.addStack();n.nodes=o.nodes,i.start(e);const{backdrop:u,backdropAlpha:l}=s,{directDiffuse:d,directSpecular:c,indirectDiffuse:h,indirectSpecular:p}=s.reflectedLight;let g=d.add(h);null!==u&&(g=cn(null!==l?l.mix(g,u):u)),t.assign(g),a.assign(c.add(p)),r.assign(t.add(a)),i.finish(e),r=r.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,r}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class BT extends Qs{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=zs.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){PT.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||bd)}}const PT=An("vec3","shadowPositionWorld");function LT(e,r={}){return r.toneMapping=e.toneMapping,r.toneMappingExposure=e.toneMappingExposure,r.outputColorSpace=e.outputColorSpace,r.renderTarget=e.getRenderTarget(),r.activeCubeFace=e.getActiveCubeFace(),r.activeMipmapLevel=e.getActiveMipmapLevel(),r.renderObjectFunction=e.getRenderObjectFunction(),r.pixelRatio=e.getPixelRatio(),r.mrt=e.getMRT(),r.clearColor=e.getClearColor(r.clearColor||new t),r.clearAlpha=e.getClearAlpha(),r.autoClear=e.autoClear,r.scissorTest=e.getScissorTest(),r}function FT(e,t){return t=LT(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function IT(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}function DT(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function UT(e,t){return t=DT(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function VT(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function OT(e,t,r){return r=UT(t,r=FT(e,r))}function GT(e,t,r){IT(e,r),VT(t,r)}var kT=Object.freeze({__proto__:null,resetRendererAndSceneState:OT,resetRendererState:FT,resetSceneState:UT,restoreRendererAndSceneState:GT,restoreRendererState:IT,restoreSceneState:VT,saveRendererAndSceneState:function(e,t,r={}){return r=DT(t,r=LT(e,r))},saveRendererState:LT,saveSceneState:DT});const zT=new WeakMap,$T=Yi((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=bl(e,t.xy).setName("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)})),WT=Yi((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=bl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=ec("mapSize","vec2",r).setGroup(na),a=ec("radius","float",r).setGroup(na),o=on(1).div(n),u=o.x.negate().mul(a),l=o.y.negate().mul(a),d=o.x.mul(a),c=o.y.mul(a),h=u.div(2),p=l.div(2),g=d.div(2),m=c.div(2);return ya(i(t.xy.add(on(u,l)),t.z),i(t.xy.add(on(0,l)),t.z),i(t.xy.add(on(d,l)),t.z),i(t.xy.add(on(h,p)),t.z),i(t.xy.add(on(0,p)),t.z),i(t.xy.add(on(g,p)),t.z),i(t.xy.add(on(u,0)),t.z),i(t.xy.add(on(h,0)),t.z),i(t.xy,t.z),i(t.xy.add(on(g,0)),t.z),i(t.xy.add(on(d,0)),t.z),i(t.xy.add(on(h,m)),t.z),i(t.xy.add(on(0,m)),t.z),i(t.xy.add(on(g,m)),t.z),i(t.xy.add(on(u,c)),t.z),i(t.xy.add(on(0,c)),t.z),i(t.xy.add(on(d,c)),t.z)).mul(1/17)})),HT=Yi((({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=bl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=ec("mapSize","vec2",r).setGroup(na),a=on(1).div(n),o=a.x,u=a.y,l=t.xy,d=lo(l.mul(n).add(.5));return l.subAssign(d.mul(a)),ya(i(l,t.z),i(l.add(on(o,0)),t.z),i(l.add(on(0,u)),t.z),i(l.add(a),t.z),qo(i(l.add(on(o.negate(),0)),t.z),i(l.add(on(o.mul(2),0)),t.z),d.x),qo(i(l.add(on(o.negate(),u)),t.z),i(l.add(on(o.mul(2),u)),t.z),d.x),qo(i(l.add(on(0,u.negate())),t.z),i(l.add(on(0,u.mul(2))),t.z),d.y),qo(i(l.add(on(o,u.negate())),t.z),i(l.add(on(o,u.mul(2))),t.z),d.y),qo(qo(i(l.add(on(o.negate(),u.negate())),t.z),i(l.add(on(o.mul(2),u.negate())),t.z),d.x),qo(i(l.add(on(o.negate(),u.mul(2))),t.z),i(l.add(on(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)})),jT=Yi((({depthTexture:e,shadowCoord:t,depthLayer:r})=>{const s=rn(1).toVar();let i=bl(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=Fo(t.z,i.x);return Ji(n.notEqual(rn(1)),(()=>{const e=t.z.sub(i.x),r=Lo(0,i.y.mul(i.y));let a=r.div(r.add(e.mul(e)));a=Xo(ba(a,.3).div(.95-.3)),s.assign(Xo(Lo(n,a)))})),s})),qT=Yi((([e,t,r])=>{let s=bd.sub(e).length();return s=s.sub(t).div(r.sub(t)),s=s.saturate(),s})),XT=e=>{let t=zT.get(e);if(void 0===t){const r=e.isPointLight?(e=>{const t=e.shadow.camera,r=ec("near","float",t).setGroup(na),s=ec("far","float",t).setGroup(na),i=Zl(e);return qT(i,r,s)})(e):null;t=new Bp,t.colorNode=mn(0,0,0,1),t.depthNode=r,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,zT.set(e,t)}return t},KT=new Ff,YT=[],QT=(e,t,r,s)=>{YT[0]=e,YT[1]=t;let i=KT.get(YT);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===ke)&&(s&&(Us(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,n.overrideMaterial,l),e.renderObject(i,n,a,o,u,l,...d),i.onAfterShadow(e,i,a,t.camera,o,n.overrideMaterial,l))},i.shadowType=r,i.useVelocity=s,KT.set(YT,i)),YT[0]=null,YT[1]=null,i},ZT=Yi((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=rn(0).toVar("meanVertical"),a=rn(0).toVar("squareMeanVertical"),o=e.lessThanEqual(rn(1)).select(rn(0),rn(2).div(e.sub(1))),u=e.lessThanEqual(rn(1)).select(rn(0),rn(-1));Wh({start:sn(0),end:sn(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(rn(e).mul(o));let d=s.sample(ya(Pl.xy,on(0,l).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),a.addAssign(d.mul(d))})),n.divAssign(e),a.divAssign(e);const l=io(a.sub(n.mul(n)));return on(n,l)})),JT=Yi((({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=rn(0).toVar("meanHorizontal"),a=rn(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(rn(1)).select(rn(0),rn(2).div(e.sub(1))),u=e.lessThanEqual(rn(1)).select(rn(0),rn(-1));Wh({start:sn(0),end:sn(e),type:"int",condition:"<"},(({i:e})=>{const l=u.add(rn(e).mul(o));let d=s.sample(ya(Pl.xy,on(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(ya(d.y.mul(d.y),d.x.mul(d.x)))})),n.divAssign(e),a.divAssign(e);const l=io(a.sub(n.mul(n)));return on(n,l)})),e_=[$T,WT,HT,jT];let t_;const r_=new gb;class s_ extends BT{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n}){const a=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1)).and(s.z.lessThanEqual(1)),o=t({depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n});return a.select(o,rn(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=ec("bias","float",r).setGroup(na);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z,s.coordinateSystem===h&&(n=n.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=ec("near","float",r.camera).setGroup(na),s=ec("far","float",r.camera).setGroup(na);n=pp(e.negate(),t,s)}return a=cn(a.x,a.y.oneMinus(),n.add(i)),a}getShadowFilterFn(e){return e_[e]}setupRenderTarget(e,t){const r=new z(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=ze;const s=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return s.texture.name="ShadowMap",s.texture.type=e.mapType,s.depthTexture=r,{shadowMap:s,depthTexture:r}}setupShadow(e){const{renderer:t,camera:r}=e,{light:s,shadow:i}=this,n=t.shadowMap.type,{depthTexture:a,shadowMap:o}=this.setupRenderTarget(i,e);if(i.camera.coordinateSystem=r.coordinateSystem,i.camera.updateProjectionMatrix(),n===ke&&!0!==i.isPointLightShadow){a.compareFunction=null,o.depth>1?(o._vsmShadowMapVertical||(o._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:de,type:ce,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=o._vsmShadowMapVertical,o._vsmShadowMapHorizontal||(o._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:de,type:ce,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=o._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:de,type:ce,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:de,type:ce,depthBuffer:!1}));let t=bl(a);a.isArrayTexture&&(t=t.depth(this.depthLayer));let r=bl(this.vsmShadowMapVertical.texture);a.isArrayTexture&&(r=r.depth(this.depthLayer));const s=ec("blurSamples","float",i).setGroup(na),n=ec("radius","float",i).setGroup(na),u=ec("mapSize","vec2",i).setGroup(na);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Bp);l.fragmentNode=ZT({samples:s,radius:n,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Bp),l.fragmentNode=JT({samples:s,radius:n,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const u=ec("intensity","float",i).setGroup(na),l=ec("normalBias","float",i).setGroup(na),d=_T(s).mul(PT.add(Pd.mul(l))),c=this.setupShadowCoord(e,d),h=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===h)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const p=n===ke&&!0!==i.isPointLightShadow?this.vsmShadowMapHorizontal.texture:a,g=this.setupShadowFilter(e,{filterFn:h,shadowTexture:o.texture,depthTexture:p,shadowCoord:c,shadow:i,depthLayer:this.depthLayer});let m=bl(o.texture,c);a.isArrayTexture&&(m=m.depth(this.depthLayer));const f=qo(1,g.rgb.mix(m,1),u.mul(m.a)).toVar();this.shadowMap=o,this.shadow.map=o;const y=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return f.toInspector(`${y} / Color`,(()=>bl(this.shadowMap.texture))).toInspector(`${y} / Depth`,(()=>xl(this.shadowMap.depthTexture,dl().mul(hl(bl(this.shadowMap.depthTexture)))).x.oneMinus()))}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Yi((()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let r=this._node;return this.setupShadowPosition(e),null===r&&(this._node=r=this.setupShadow(e),this._currentShadowType=t),e.material.shadowNode&&d('NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(r=e.material.receivedShadowNode(r)),r}))()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth);const a=n.name;n.name=`Shadow Map [ ${s.name||"ID: "+s.id} ]`,i.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:r,shadow:s}=this,{renderer:i,scene:n,camera:a}=e,o=i.shadowMap.type,u=t.depthTexture.version;this._depthVersionCached=u;const l=s.camera.layers.mask;4294967294&s.camera.layers.mask||(s.camera.layers.mask=a.layers.mask);const d=i.getRenderObjectFunction(),c=i.getMRT(),h=!!c&&c.has("velocity");t_=OT(i,n,t_),n.overrideMaterial=XT(r),i.setRenderObjectFunction(QT(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===ke&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,GT(i,n,t_)}vsmPass(e){const{shadow:t}=this,r=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,r),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,r),e.setRenderTarget(this.vsmShadowMapVertical),r_.material=this.vsmMaterialVertical,r_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),r_.material=this.vsmMaterialHorizontal,r_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let r=t.needsUpdate||t.autoUpdate;r&&(this._cameraFrameId[e.camera]===e.frameId&&(r=!1),this._cameraFrameId[e.camera]=e.frameId),r&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const i_=(e,t)=>ki(new s_(e,t)),n_=new t,a_=Yi((([e,t])=>{const r=e.toVar(),s=yo(r),i=Ta(1,Lo(s.x,Lo(s.y,s.z)));s.mulAssign(i),r.mulAssign(i.mul(t.mul(2).oneMinus()));const n=on(r.xy).toVar(),a=t.mul(1.5).oneMinus();return Ji(s.z.greaterThanEqual(a),(()=>{Ji(r.z.greaterThan(0),(()=>{n.x.assign(ba(4,r.x))}))})).ElseIf(s.x.greaterThanEqual(a),(()=>{const e=bo(r.x);n.x.assign(r.z.mul(e).add(e.mul(2)))})).ElseIf(s.y.greaterThanEqual(a),(()=>{const e=bo(r.y);n.x.assign(r.x.add(e.mul(2)).add(2)),n.y.assign(r.z.mul(e).sub(2))})),on(.125,.25).mul(n).add(on(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),o_=Yi((({depthTexture:e,bd3D:t,dp:r,texelSize:s})=>bl(e,a_(t,s.y)).compare(r))),u_=Yi((({depthTexture:e,bd3D:t,dp:r,texelSize:s,shadow:i})=>{const n=ec("radius","float",i).setGroup(na),a=on(-1,1).mul(n).mul(s.y);return bl(e,a_(t.add(a.xyy),s.y)).compare(r).add(bl(e,a_(t.add(a.yyy),s.y)).compare(r)).add(bl(e,a_(t.add(a.xyx),s.y)).compare(r)).add(bl(e,a_(t.add(a.yyx),s.y)).compare(r)).add(bl(e,a_(t,s.y)).compare(r)).add(bl(e,a_(t.add(a.xxy),s.y)).compare(r)).add(bl(e,a_(t.add(a.yxy),s.y)).compare(r)).add(bl(e,a_(t.add(a.xxx),s.y)).compare(r)).add(bl(e,a_(t.add(a.yxx),s.y)).compare(r)).mul(1/9)})),l_=Yi((({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s})=>{const i=r.xyz.toVar(),n=i.length(),a=ua("float").setGroup(na).onRenderUpdate((()=>s.camera.near)),o=ua("float").setGroup(na).onRenderUpdate((()=>s.camera.far)),u=ec("bias","float",s).setGroup(na),l=ua(s.mapSize).setGroup(na),d=rn(1).toVar();return Ji(n.sub(o).lessThanEqual(0).and(n.sub(a).greaterThanEqual(0)),(()=>{const r=n.sub(a).div(o.sub(a)).toVar();r.addAssign(u);const c=i.normalize(),h=on(1).div(l.mul(on(4,2)));d.assign(e({depthTexture:t,bd3D:c,dp:r,texelSize:h,shadow:s}))})),d})),d_=new i,c_=new r,h_=new r;class p_ extends s_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===$e?o_:u_}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n}){return l_({filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n})}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.getFrameExtents();h_.copy(t.mapSize),h_.multiply(a),r.setSize(h_.width,h_.height),c_.copy(t.mapSize);const o=i.autoClear,u=i.getClearColor(n_),l=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha),i.clear();const d=t.getViewportCount();for(let e=0;e<d;e++){const a=t.getViewport(e),o=c_.x*a.x,u=h_.y-c_.y-c_.y*a.y;d_.set(o,u,c_.x*a.z,c_.y*a.w),r.viewport.copy(d_),t.updateMatrices(s,e);const l=n.name;n.name=`Point Light Shadow [ ${s.name||"ID: "+s.id} ] - Face ${e+1}`,i.render(n,t.camera),n.name=l}i.autoClear=o,i.setClearColor(u,l)}}const g_=(e,t)=>ki(new p_(e,t));class m_ extends Qh{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new t,this.colorNode=e&&e.colorNode||ua(this.color).setGroup(na),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=zs.FRAME}getHash(){return this.light.uuid}getLightVector(e){return AT(this.light).sub(e.context.positionView||Td)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return i_(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let r=this.shadowColorNode;if(null===r){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?ki(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}this.colorNode=r}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),r=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),r&&e.lightsNode.setupDirectRectAreaLight(e,this,r)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const f_=Yi((({lightDistance:e,cutoffDistance:t,decayExponent:r})=>{const s=e.pow(r).max(.01).reciprocal();return t.greaterThan(0).select(s.mul(e.div(t).pow4().oneMinus().clamp().pow2()),s)})),y_=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=f_({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class b_ extends m_{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=ua(0).setGroup(na),this.decayExponentNode=ua(2).setGroup(na)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return g_(this.light)}setupDirect(e){return y_({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const x_=Yi((([e=dl()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()})),T_=Yi((([e=dl()],{renderer:t,material:r})=>{const s=jo(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.currentSamples>0){const e=rn(s.fwidth()).toVar();i=Qo(e.oneMinus(),e.add(1),s).oneMinus()}else i=ou(s.greaterThan(1),0,1);return i})),__=Yi((([e,t,r])=>{const s=rn(r).toVar(),i=rn(t).toVar(),n=an(e).toVar();return ou(n,i,s)})).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),v_=Yi((([e,t])=>{const r=an(t).toVar(),s=rn(e).toVar();return ou(r,s.negate(),s)})).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),N_=Yi((([e])=>{const t=rn(e).toVar();return sn(ao(t))})).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),S_=Yi((([e,t])=>{const r=rn(e).toVar();return t.assign(N_(r)),r.sub(rn(t))})),A_=Vy([Yi((([e,t,r,s,i,n])=>{const a=rn(n).toVar(),o=rn(i).toVar(),u=rn(s).toVar(),l=rn(r).toVar(),d=rn(t).toVar(),c=rn(e).toVar(),h=rn(ba(1,o)).toVar();return ba(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))})).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),Yi((([e,t,r,s,i,n])=>{const a=rn(n).toVar(),o=rn(i).toVar(),u=cn(s).toVar(),l=cn(r).toVar(),d=cn(t).toVar(),c=cn(e).toVar(),h=rn(ba(1,o)).toVar();return ba(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))})).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),R_=Vy([Yi((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=rn(d).toVar(),h=rn(l).toVar(),p=rn(u).toVar(),g=rn(o).toVar(),m=rn(a).toVar(),f=rn(n).toVar(),y=rn(i).toVar(),b=rn(s).toVar(),x=rn(r).toVar(),T=rn(t).toVar(),_=rn(e).toVar(),v=rn(ba(1,p)).toVar(),N=rn(ba(1,h)).toVar();return rn(ba(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))})).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),Yi((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=rn(d).toVar(),h=rn(l).toVar(),p=rn(u).toVar(),g=cn(o).toVar(),m=cn(a).toVar(),f=cn(n).toVar(),y=cn(i).toVar(),b=cn(s).toVar(),x=cn(r).toVar(),T=cn(t).toVar(),_=cn(e).toVar(),v=rn(ba(1,p)).toVar(),N=rn(ba(1,h)).toVar();return rn(ba(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))})).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),E_=Yi((([e,t,r])=>{const s=rn(r).toVar(),i=rn(t).toVar(),n=nn(e).toVar(),a=nn(n.bitAnd(nn(7))).toVar(),o=rn(__(a.lessThan(nn(4)),i,s)).toVar(),u=rn(xa(2,__(a.lessThan(nn(4)),s,i))).toVar();return v_(o,an(a.bitAnd(nn(1)))).add(v_(u,an(a.bitAnd(nn(2)))))})).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),w_=Yi((([e,t,r,s])=>{const i=rn(s).toVar(),n=rn(r).toVar(),a=rn(t).toVar(),o=nn(e).toVar(),u=nn(o.bitAnd(nn(15))).toVar(),l=rn(__(u.lessThan(nn(8)),a,n)).toVar(),d=rn(__(u.lessThan(nn(4)),n,__(u.equal(nn(12)).or(u.equal(nn(14))),a,i))).toVar();return v_(l,an(u.bitAnd(nn(1)))).add(v_(d,an(u.bitAnd(nn(2)))))})).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),C_=Vy([E_,w_]),M_=Yi((([e,t,r])=>{const s=rn(r).toVar(),i=rn(t).toVar(),n=pn(e).toVar();return cn(C_(n.x,i,s),C_(n.y,i,s),C_(n.z,i,s))})).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),B_=Yi((([e,t,r,s])=>{const i=rn(s).toVar(),n=rn(r).toVar(),a=rn(t).toVar(),o=pn(e).toVar();return cn(C_(o.x,a,n,i),C_(o.y,a,n,i),C_(o.z,a,n,i))})).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),P_=Vy([M_,B_]),L_=Yi((([e])=>{const t=rn(e).toVar();return xa(.6616,t)})).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),F_=Yi((([e])=>{const t=rn(e).toVar();return xa(.982,t)})).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),I_=Vy([L_,Yi((([e])=>{const t=cn(e).toVar();return xa(.6616,t)})).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),D_=Vy([F_,Yi((([e])=>{const t=cn(e).toVar();return xa(.982,t)})).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),U_=Yi((([e,t])=>{const r=sn(t).toVar(),s=nn(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(sn(32).sub(r)))})).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),V_=Yi((([e,t,r])=>{e.subAssign(r),e.bitXorAssign(U_(r,sn(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(U_(e,sn(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(U_(t,sn(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(U_(r,sn(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(U_(e,sn(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(U_(t,sn(4))),t.addAssign(e)})),O_=Yi((([e,t,r])=>{const s=nn(r).toVar(),i=nn(t).toVar(),n=nn(e).toVar();return s.bitXorAssign(i),s.subAssign(U_(i,sn(14))),n.bitXorAssign(s),n.subAssign(U_(s,sn(11))),i.bitXorAssign(n),i.subAssign(U_(n,sn(25))),s.bitXorAssign(i),s.subAssign(U_(i,sn(16))),n.bitXorAssign(s),n.subAssign(U_(s,sn(4))),i.bitXorAssign(n),i.subAssign(U_(n,sn(14))),s.bitXorAssign(i),s.subAssign(U_(i,sn(24))),s})).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),G_=Yi((([e])=>{const t=nn(e).toVar();return rn(t).div(rn(nn(sn(4294967295))))})).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),k_=Yi((([e])=>{const t=rn(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))})).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),z_=Vy([Yi((([e])=>{const t=sn(e).toVar(),r=nn(nn(1)).toVar(),s=nn(nn(sn(3735928559)).add(r.shiftLeft(nn(2))).add(nn(13))).toVar();return O_(s.add(nn(t)),s,s)})).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Yi((([e,t])=>{const r=sn(t).toVar(),s=sn(e).toVar(),i=nn(nn(2)).toVar(),n=nn().toVar(),a=nn().toVar(),o=nn().toVar();return n.assign(a.assign(o.assign(nn(sn(3735928559)).add(i.shiftLeft(nn(2))).add(nn(13))))),n.addAssign(nn(s)),a.addAssign(nn(r)),O_(n,a,o)})).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Yi((([e,t,r])=>{const s=sn(r).toVar(),i=sn(t).toVar(),n=sn(e).toVar(),a=nn(nn(3)).toVar(),o=nn().toVar(),u=nn().toVar(),l=nn().toVar();return o.assign(u.assign(l.assign(nn(sn(3735928559)).add(a.shiftLeft(nn(2))).add(nn(13))))),o.addAssign(nn(n)),u.addAssign(nn(i)),l.addAssign(nn(s)),O_(o,u,l)})).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Yi((([e,t,r,s])=>{const i=sn(s).toVar(),n=sn(r).toVar(),a=sn(t).toVar(),o=sn(e).toVar(),u=nn(nn(4)).toVar(),l=nn().toVar(),d=nn().toVar(),c=nn().toVar();return l.assign(d.assign(c.assign(nn(sn(3735928559)).add(u.shiftLeft(nn(2))).add(nn(13))))),l.addAssign(nn(o)),d.addAssign(nn(a)),c.addAssign(nn(n)),V_(l,d,c),l.addAssign(nn(i)),O_(l,d,c)})).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),Yi((([e,t,r,s,i])=>{const n=sn(i).toVar(),a=sn(s).toVar(),o=sn(r).toVar(),u=sn(t).toVar(),l=sn(e).toVar(),d=nn(nn(5)).toVar(),c=nn().toVar(),h=nn().toVar(),p=nn().toVar();return c.assign(h.assign(p.assign(nn(sn(3735928559)).add(d.shiftLeft(nn(2))).add(nn(13))))),c.addAssign(nn(l)),h.addAssign(nn(u)),p.addAssign(nn(o)),V_(c,h,p),c.addAssign(nn(a)),h.addAssign(nn(n)),O_(c,h,p)})).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),$_=Vy([Yi((([e,t])=>{const r=sn(t).toVar(),s=sn(e).toVar(),i=nn(z_(s,r)).toVar(),n=pn().toVar();return n.x.assign(i.bitAnd(sn(255))),n.y.assign(i.shiftRight(sn(8)).bitAnd(sn(255))),n.z.assign(i.shiftRight(sn(16)).bitAnd(sn(255))),n})).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Yi((([e,t,r])=>{const s=sn(r).toVar(),i=sn(t).toVar(),n=sn(e).toVar(),a=nn(z_(n,i,s)).toVar(),o=pn().toVar();return o.x.assign(a.bitAnd(sn(255))),o.y.assign(a.shiftRight(sn(8)).bitAnd(sn(255))),o.z.assign(a.shiftRight(sn(16)).bitAnd(sn(255))),o})).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),W_=Vy([Yi((([e])=>{const t=on(e).toVar(),r=sn().toVar(),s=sn().toVar(),i=rn(S_(t.x,r)).toVar(),n=rn(S_(t.y,s)).toVar(),a=rn(k_(i)).toVar(),o=rn(k_(n)).toVar(),u=rn(A_(C_(z_(r,s),i,n),C_(z_(r.add(sn(1)),s),i.sub(1),n),C_(z_(r,s.add(sn(1))),i,n.sub(1)),C_(z_(r.add(sn(1)),s.add(sn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return I_(u)})).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Yi((([e])=>{const t=cn(e).toVar(),r=sn().toVar(),s=sn().toVar(),i=sn().toVar(),n=rn(S_(t.x,r)).toVar(),a=rn(S_(t.y,s)).toVar(),o=rn(S_(t.z,i)).toVar(),u=rn(k_(n)).toVar(),l=rn(k_(a)).toVar(),d=rn(k_(o)).toVar(),c=rn(R_(C_(z_(r,s,i),n,a,o),C_(z_(r.add(sn(1)),s,i),n.sub(1),a,o),C_(z_(r,s.add(sn(1)),i),n,a.sub(1),o),C_(z_(r.add(sn(1)),s.add(sn(1)),i),n.sub(1),a.sub(1),o),C_(z_(r,s,i.add(sn(1))),n,a,o.sub(1)),C_(z_(r.add(sn(1)),s,i.add(sn(1))),n.sub(1),a,o.sub(1)),C_(z_(r,s.add(sn(1)),i.add(sn(1))),n,a.sub(1),o.sub(1)),C_(z_(r.add(sn(1)),s.add(sn(1)),i.add(sn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return D_(c)})).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),H_=Vy([Yi((([e])=>{const t=on(e).toVar(),r=sn().toVar(),s=sn().toVar(),i=rn(S_(t.x,r)).toVar(),n=rn(S_(t.y,s)).toVar(),a=rn(k_(i)).toVar(),o=rn(k_(n)).toVar(),u=cn(A_(P_($_(r,s),i,n),P_($_(r.add(sn(1)),s),i.sub(1),n),P_($_(r,s.add(sn(1))),i,n.sub(1)),P_($_(r.add(sn(1)),s.add(sn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return I_(u)})).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Yi((([e])=>{const t=cn(e).toVar(),r=sn().toVar(),s=sn().toVar(),i=sn().toVar(),n=rn(S_(t.x,r)).toVar(),a=rn(S_(t.y,s)).toVar(),o=rn(S_(t.z,i)).toVar(),u=rn(k_(n)).toVar(),l=rn(k_(a)).toVar(),d=rn(k_(o)).toVar(),c=cn(R_(P_($_(r,s,i),n,a,o),P_($_(r.add(sn(1)),s,i),n.sub(1),a,o),P_($_(r,s.add(sn(1)),i),n,a.sub(1),o),P_($_(r.add(sn(1)),s.add(sn(1)),i),n.sub(1),a.sub(1),o),P_($_(r,s,i.add(sn(1))),n,a,o.sub(1)),P_($_(r.add(sn(1)),s,i.add(sn(1))),n.sub(1),a,o.sub(1)),P_($_(r,s.add(sn(1)),i.add(sn(1))),n,a.sub(1),o.sub(1)),P_($_(r.add(sn(1)),s.add(sn(1)),i.add(sn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return D_(c)})).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),j_=Vy([Yi((([e])=>{const t=rn(e).toVar(),r=sn(N_(t)).toVar();return G_(z_(r))})).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),Yi((([e])=>{const t=on(e).toVar(),r=sn(N_(t.x)).toVar(),s=sn(N_(t.y)).toVar();return G_(z_(r,s))})).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),Yi((([e])=>{const t=cn(e).toVar(),r=sn(N_(t.x)).toVar(),s=sn(N_(t.y)).toVar(),i=sn(N_(t.z)).toVar();return G_(z_(r,s,i))})).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),Yi((([e])=>{const t=mn(e).toVar(),r=sn(N_(t.x)).toVar(),s=sn(N_(t.y)).toVar(),i=sn(N_(t.z)).toVar(),n=sn(N_(t.w)).toVar();return G_(z_(r,s,i,n))})).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),q_=Vy([Yi((([e])=>{const t=rn(e).toVar(),r=sn(N_(t)).toVar();return cn(G_(z_(r,sn(0))),G_(z_(r,sn(1))),G_(z_(r,sn(2))))})).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),Yi((([e])=>{const t=on(e).toVar(),r=sn(N_(t.x)).toVar(),s=sn(N_(t.y)).toVar();return cn(G_(z_(r,s,sn(0))),G_(z_(r,s,sn(1))),G_(z_(r,s,sn(2))))})).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Yi((([e])=>{const t=cn(e).toVar(),r=sn(N_(t.x)).toVar(),s=sn(N_(t.y)).toVar(),i=sn(N_(t.z)).toVar();return cn(G_(z_(r,s,i,sn(0))),G_(z_(r,s,i,sn(1))),G_(z_(r,s,i,sn(2))))})).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Yi((([e])=>{const t=mn(e).toVar(),r=sn(N_(t.x)).toVar(),s=sn(N_(t.y)).toVar(),i=sn(N_(t.z)).toVar(),n=sn(N_(t.w)).toVar();return cn(G_(z_(r,s,i,n,sn(0))),G_(z_(r,s,i,n,sn(1))),G_(z_(r,s,i,n,sn(2))))})).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),X_=Yi((([e,t,r,s])=>{const i=rn(s).toVar(),n=rn(r).toVar(),a=sn(t).toVar(),o=cn(e).toVar(),u=rn(0).toVar(),l=rn(1).toVar();return Wh(a,(()=>{u.addAssign(l.mul(W_(o))),l.mulAssign(i),o.mulAssign(n)})),u})).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),K_=Yi((([e,t,r,s])=>{const i=rn(s).toVar(),n=rn(r).toVar(),a=sn(t).toVar(),o=cn(e).toVar(),u=cn(0).toVar(),l=rn(1).toVar();return Wh(a,(()=>{u.addAssign(l.mul(H_(o))),l.mulAssign(i),o.mulAssign(n)})),u})).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Y_=Yi((([e,t,r,s])=>{const i=rn(s).toVar(),n=rn(r).toVar(),a=sn(t).toVar(),o=cn(e).toVar();return on(X_(o,a,n,i),X_(o.add(cn(sn(19),sn(193),sn(17))),a,n,i))})).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Q_=Yi((([e,t,r,s])=>{const i=rn(s).toVar(),n=rn(r).toVar(),a=sn(t).toVar(),o=cn(e).toVar(),u=cn(K_(o,a,n,i)).toVar(),l=rn(X_(o.add(cn(sn(19),sn(193),sn(17))),a,n,i)).toVar();return mn(u,l)})).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),Z_=Vy([Yi((([e,t,r,s,i,n,a])=>{const o=sn(a).toVar(),u=rn(n).toVar(),l=sn(i).toVar(),d=sn(s).toVar(),c=sn(r).toVar(),h=sn(t).toVar(),p=on(e).toVar(),g=cn(q_(on(h.add(d),c.add(l)))).toVar(),m=on(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=on(on(rn(h),rn(c)).add(m)).toVar(),y=on(f.sub(p)).toVar();return Ji(o.equal(sn(2)),(()=>yo(y.x).add(yo(y.y)))),Ji(o.equal(sn(3)),(()=>Lo(yo(y.x),yo(y.y)))),Vo(y,y)})).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Yi((([e,t,r,s,i,n,a,o,u])=>{const l=sn(u).toVar(),d=rn(o).toVar(),c=sn(a).toVar(),h=sn(n).toVar(),p=sn(i).toVar(),g=sn(s).toVar(),m=sn(r).toVar(),f=sn(t).toVar(),y=cn(e).toVar(),b=cn(q_(cn(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=cn(cn(rn(f),rn(m),rn(g)).add(b)).toVar(),T=cn(x.sub(y)).toVar();return Ji(l.equal(sn(2)),(()=>yo(T.x).add(yo(T.y)).add(yo(T.z)))),Ji(l.equal(sn(3)),(()=>Lo(yo(T.x),yo(T.y),yo(T.z)))),Vo(T,T)})).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),J_=Yi((([e,t,r])=>{const s=sn(r).toVar(),i=rn(t).toVar(),n=on(e).toVar(),a=sn().toVar(),o=sn().toVar(),u=on(S_(n.x,a),S_(n.y,o)).toVar(),l=rn(1e6).toVar();return Wh({start:-1,end:sn(1),name:"x",condition:"<="},(({x:e})=>{Wh({start:-1,end:sn(1),name:"y",condition:"<="},(({y:t})=>{const r=rn(Z_(u,e,t,a,o,i,s)).toVar();l.assign(Po(l,r))}))})),Ji(s.equal(sn(0)),(()=>{l.assign(io(l))})),l})).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),ev=Yi((([e,t,r])=>{const s=sn(r).toVar(),i=rn(t).toVar(),n=on(e).toVar(),a=sn().toVar(),o=sn().toVar(),u=on(S_(n.x,a),S_(n.y,o)).toVar(),l=on(1e6,1e6).toVar();return Wh({start:-1,end:sn(1),name:"x",condition:"<="},(({x:e})=>{Wh({start:-1,end:sn(1),name:"y",condition:"<="},(({y:t})=>{const r=rn(Z_(u,e,t,a,o,i,s)).toVar();Ji(r.lessThan(l.x),(()=>{l.y.assign(l.x),l.x.assign(r)})).ElseIf(r.lessThan(l.y),(()=>{l.y.assign(r)}))}))})),Ji(s.equal(sn(0)),(()=>{l.assign(io(l))})),l})).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),tv=Yi((([e,t,r])=>{const s=sn(r).toVar(),i=rn(t).toVar(),n=on(e).toVar(),a=sn().toVar(),o=sn().toVar(),u=on(S_(n.x,a),S_(n.y,o)).toVar(),l=cn(1e6,1e6,1e6).toVar();return Wh({start:-1,end:sn(1),name:"x",condition:"<="},(({x:e})=>{Wh({start:-1,end:sn(1),name:"y",condition:"<="},(({y:t})=>{const r=rn(Z_(u,e,t,a,o,i,s)).toVar();Ji(r.lessThan(l.x),(()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(r)})).ElseIf(r.lessThan(l.y),(()=>{l.z.assign(l.y),l.y.assign(r)})).ElseIf(r.lessThan(l.z),(()=>{l.z.assign(r)}))}))})),Ji(s.equal(sn(0)),(()=>{l.assign(io(l))})),l})).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),rv=Vy([J_,Yi((([e,t,r])=>{const s=sn(r).toVar(),i=rn(t).toVar(),n=cn(e).toVar(),a=sn().toVar(),o=sn().toVar(),u=sn().toVar(),l=cn(S_(n.x,a),S_(n.y,o),S_(n.z,u)).toVar(),d=rn(1e6).toVar();return Wh({start:-1,end:sn(1),name:"x",condition:"<="},(({x:e})=>{Wh({start:-1,end:sn(1),name:"y",condition:"<="},(({y:t})=>{Wh({start:-1,end:sn(1),name:"z",condition:"<="},(({z:r})=>{const n=rn(Z_(l,e,t,r,a,o,u,i,s)).toVar();d.assign(Po(d,n))}))}))})),Ji(s.equal(sn(0)),(()=>{d.assign(io(d))})),d})).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),sv=Vy([ev,Yi((([e,t,r])=>{const s=sn(r).toVar(),i=rn(t).toVar(),n=cn(e).toVar(),a=sn().toVar(),o=sn().toVar(),u=sn().toVar(),l=cn(S_(n.x,a),S_(n.y,o),S_(n.z,u)).toVar(),d=on(1e6,1e6).toVar();return Wh({start:-1,end:sn(1),name:"x",condition:"<="},(({x:e})=>{Wh({start:-1,end:sn(1),name:"y",condition:"<="},(({y:t})=>{Wh({start:-1,end:sn(1),name:"z",condition:"<="},(({z:r})=>{const n=rn(Z_(l,e,t,r,a,o,u,i,s)).toVar();Ji(n.lessThan(d.x),(()=>{d.y.assign(d.x),d.x.assign(n)})).ElseIf(n.lessThan(d.y),(()=>{d.y.assign(n)}))}))}))})),Ji(s.equal(sn(0)),(()=>{d.assign(io(d))})),d})).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),iv=Vy([tv,Yi((([e,t,r])=>{const s=sn(r).toVar(),i=rn(t).toVar(),n=cn(e).toVar(),a=sn().toVar(),o=sn().toVar(),u=sn().toVar(),l=cn(S_(n.x,a),S_(n.y,o),S_(n.z,u)).toVar(),d=cn(1e6,1e6,1e6).toVar();return Wh({start:-1,end:sn(1),name:"x",condition:"<="},(({x:e})=>{Wh({start:-1,end:sn(1),name:"y",condition:"<="},(({y:t})=>{Wh({start:-1,end:sn(1),name:"z",condition:"<="},(({z:r})=>{const n=rn(Z_(l,e,t,r,a,o,u,i,s)).toVar();Ji(n.lessThan(d.x),(()=>{d.z.assign(d.y),d.y.assign(d.x),d.x.assign(n)})).ElseIf(n.lessThan(d.y),(()=>{d.z.assign(d.y),d.y.assign(n)})).ElseIf(n.lessThan(d.z),(()=>{d.z.assign(n)}))}))}))})),Ji(s.equal(sn(0)),(()=>{d.assign(io(d))})),d})).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),nv=Yi((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=sn(e).toVar(),h=on(t).toVar(),p=on(r).toVar(),g=on(s).toVar(),m=rn(i).toVar(),f=rn(n).toVar(),y=rn(a).toVar(),b=an(o).toVar(),x=sn(u).toVar(),T=rn(l).toVar(),_=rn(d).toVar(),v=h.mul(p).add(g),N=rn(0).toVar();return Ji(c.equal(sn(0)),(()=>{N.assign(H_(v))})),Ji(c.equal(sn(1)),(()=>{N.assign(q_(v))})),Ji(c.equal(sn(2)),(()=>{N.assign(iv(v,m,sn(0)))})),Ji(c.equal(sn(3)),(()=>{N.assign(K_(cn(v,0),x,T,_))})),N.assign(N.mul(y.sub(f)).add(f)),Ji(b,(()=>{N.assign(Xo(N,f,y))})),N})).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),av=Yi((([e,t,r,s,i,n,a,o,u,l,d])=>{const c=sn(e).toVar(),h=cn(t).toVar(),p=cn(r).toVar(),g=cn(s).toVar(),m=rn(i).toVar(),f=rn(n).toVar(),y=rn(a).toVar(),b=an(o).toVar(),x=sn(u).toVar(),T=rn(l).toVar(),_=rn(d).toVar(),v=h.mul(p).add(g),N=rn(0).toVar();return Ji(c.equal(sn(0)),(()=>{N.assign(H_(v))})),Ji(c.equal(sn(1)),(()=>{N.assign(q_(v))})),Ji(c.equal(sn(2)),(()=>{N.assign(iv(v,m,sn(0)))})),Ji(c.equal(sn(3)),(()=>{N.assign(K_(v,x,T,_))})),N.assign(N.mul(y.sub(f)).add(f)),Ji(b,(()=>{N.assign(Xo(N,f,y))})),N})).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),ov=Yi((([e])=>{const t=e.y,r=e.z,s=cn().toVar();return Ji(t.lessThan(1e-4),(()=>{s.assign(cn(r,r,r))})).Else((()=>{let i=e.x;i=i.sub(ao(i)).mul(6).toVar();const n=sn(Ro(i)),a=i.sub(rn(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());Ji(n.equal(sn(0)),(()=>{s.assign(cn(r,l,o))})).ElseIf(n.equal(sn(1)),(()=>{s.assign(cn(u,r,o))})).ElseIf(n.equal(sn(2)),(()=>{s.assign(cn(o,r,l))})).ElseIf(n.equal(sn(3)),(()=>{s.assign(cn(o,u,r))})).ElseIf(n.equal(sn(4)),(()=>{s.assign(cn(l,o,r))})).Else((()=>{s.assign(cn(r,o,u))}))})),s})).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),uv=Yi((([e])=>{const t=cn(e).toVar(),r=rn(t.x).toVar(),s=rn(t.y).toVar(),i=rn(t.z).toVar(),n=rn(Po(r,Po(s,i))).toVar(),a=rn(Lo(r,Lo(s,i))).toVar(),o=rn(a.sub(n)).toVar(),u=rn().toVar(),l=rn().toVar(),d=rn().toVar();return d.assign(a),Ji(a.greaterThan(0),(()=>{l.assign(o.div(a))})).Else((()=>{l.assign(0)})),Ji(l.lessThanEqual(0),(()=>{u.assign(0)})).Else((()=>{Ji(r.greaterThanEqual(a),(()=>{u.assign(s.sub(i).div(o))})).ElseIf(s.greaterThanEqual(a),(()=>{u.assign(ya(2,i.sub(r).div(o)))})).Else((()=>{u.assign(ya(4,r.sub(s).div(o)))})),u.mulAssign(1/6),Ji(u.lessThan(0),(()=>{u.addAssign(1)}))})),cn(u,l,d)})).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),lv=Yi((([e])=>{const t=cn(e).toVar(),r=gn(Aa(t,cn(.04045))).toVar(),s=cn(t.div(12.92)).toVar(),i=cn(Go(Lo(t.add(cn(.055)),cn(0)).div(1.055),cn(2.4))).toVar();return qo(s,i,r)})).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),dv=(e,t)=>{e=rn(e),t=rn(t);const r=on(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Qo(e.sub(r),e.add(r),t)},cv=(e,t,r,s)=>qo(e,t,r[s].clamp()),hv=(e,t,r,s,i)=>qo(e,t,dv(r,s[i])),pv=Yi((([e,t,r])=>{const s=uo(e).toVar(),i=ba(rn(.5).mul(t.sub(r)),bd).div(s).toVar(),n=ba(rn(-.5).mul(t.sub(r)),bd).div(s).toVar(),a=cn().toVar();a.x=s.x.greaterThan(rn(0)).select(i.x,n.x),a.y=s.y.greaterThan(rn(0)).select(i.y,n.y),a.z=s.z.greaterThan(rn(0)).select(i.z,n.z);const o=Po(a.x,a.y,a.z).toVar();return bd.add(s.mul(o)).toVar().sub(r)})),gv=Yi((([e,t])=>{const r=e.x,s=e.y,i=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(s)),n=n.add(t.element(2).mul(1.023328).mul(i)),n=n.add(t.element(3).mul(1.023328).mul(r)),n=n.add(t.element(4).mul(.858086).mul(r).mul(s)),n=n.add(t.element(5).mul(.858086).mul(s).mul(i)),n=n.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(r).mul(i)),n=n.add(t.element(8).mul(.429043).mul(xa(r,r).sub(xa(s,s)))),n}));var mv=Object.freeze({__proto__:null,BRDF_GGX:xg,BRDF_Lambert:ig,BasicPointShadowFilter:o_,BasicShadowFilter:$T,Break:Hh,Const:fu,Continue:()=>Ju("continue").toStack(),DFGApprox:vg,D_GGX:fg,Discard:el,EPSILON:Wa,F_Schlick:sg,Fn:Yi,HALF_PI:Ka,INFINITY:Ha,If:Ji,Loop:Wh,NodeAccess:Ws,NodeShaderStage:ks,NodeType:$s,NodeUpdateType:zs,OnBeforeMaterialUpdate:e=>Sb(Nb.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>Sb(Nb.BEFORE_OBJECT,e),OnMaterialUpdate:e=>Sb(Nb.MATERIAL,e),OnObjectUpdate:e=>Sb(Nb.OBJECT,e),PCFShadowFilter:WT,PCFSoftShadowFilter:HT,PI:ja,PI2:qa,PointShadowFilter:u_,Return:()=>Ju("return").toStack(),Schlick_to_F0:Ag,ScriptableNodeResources:Nx,ShaderNode:Gi,Stack:en,Switch:(...e)=>di.Switch(...e),TBNViewMatrix:Ec,TWO_PI:Xa,VSMShadowFilter:jT,V_GGX_SmithCorrelated:gg,Var:mu,VarIntent:yu,abs:yo,acesFilmicToneMapping:lx,acos:mo,add:ya,addMethodChaining:hi,addNodeElement:function(e){d("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:px,all:Ya,alphaT:Vn,and:wa,anisotropy:On,anisotropyB:kn,anisotropyT:Gn,any:Qa,append:e=>(d("TSL: append() has been renamed to Stack()."),en(e)),array:da,arrayBuffer:e=>ki(new ui(e,"ArrayBuffer")),asin:go,assign:ha,atan:fo,atan2:su,atomicAdd:(e,t)=>jx(Wx.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>jx(Wx.ATOMIC_AND,e,t),atomicFunc:jx,atomicLoad:e=>jx(Wx.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>jx(Wx.ATOMIC_MAX,e,t),atomicMin:(e,t)=>jx(Wx.ATOMIC_MIN,e,t),atomicOr:(e,t)=>jx(Wx.ATOMIC_OR,e,t),atomicStore:(e,t)=>jx(Wx.ATOMIC_STORE,e,t),atomicSub:(e,t)=>jx(Wx.ATOMIC_SUB,e,t),atomicXor:(e,t)=>jx(Wx.ATOMIC_XOR,e,t),attenuationColor:Jn,attenuationDistance:Zn,attribute:ll,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Bs("float")):(r=Ps(t),s=Bs(t));const i=new Rb(e,r,s);return Oh(i,t,e)},backgroundBlurriness:Pb,backgroundIntensity:Lb,backgroundRotation:Fb,batch:Ih,bentNormalView:Cc,billboarding:Wy,bitAnd:Pa,bitNot:La,bitOr:Fa,bitXor:Ia,bitangentGeometry:Nc,bitangentLocal:Sc,bitangentView:Ac,bitangentWorld:Rc,bitcast:My,blendBurn:Sp,blendColor:wp,blendDodge:Ap,blendOverlay:Ep,blendScreen:Rp,blur:Am,bool:an,buffer:_l,bufferAttribute:Uu,builtin:Al,bumpMap:Ic,burn:(...e)=>(d('TSL: "burn" has been renamed. Use "blendBurn" instead.'),Sp(e)),bvec2:dn,bvec3:gn,bvec4:bn,bypass:Xu,cache:ju,call:ga,cameraFar:Gl,cameraIndex:Vl,cameraNear:Ol,cameraNormalMatrix:Hl,cameraPosition:jl,cameraProjectionMatrix:kl,cameraProjectionMatrixInverse:zl,cameraViewMatrix:$l,cameraViewport:ql,cameraWorldMatrix:Wl,cbrt:Ho,cdl:Qb,ceil:oo,checker:x_,cineonToneMapping:ox,clamp:Xo,clearcoat:Bn,clearcoatNormalView:Ld,clearcoatRoughness:Pn,code:fx,color:tn,colorSpaceToWorking:wu,colorToDirection:e=>ki(e).mul(2).sub(1),compute:$u,computeKernel:zu,computeSkinning:(e,t=null)=>{const r=new kh(e);return r.positionNode=Oh(new U(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(Ah).toVar(),r.skinIndexNode=Oh(new U(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(Ah).toVar(),r.skinWeightNode=Oh(new U(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(Ah).toVar(),r.bindMatrixNode=ua(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=ua(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=_l(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,ki(r)},context:lu,convert:Nn,convertColorSpace:(e,t,r)=>ki(new Ru(ki(e),t,r)),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():yb(e,...t),cos:ho,cross:Oo,cubeTexture:Qd,cubeTextureBase:Yd,cubeToUV:a_,dFdx:vo,dFdy:No,dashSize:jn,debug:il,decrement:ka,decrementBefore:Oa,defaultBuildStages:js,defaultShaderStages:Hs,defined:Vi,degrees:Ja,deltaTime:Gy,densityFog:function(e,t){return d('TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),Cx(e,wx(t))},densityFogFactor:wx,depth:mp,depthPass:(e,t,r)=>ki(new sx(sx.DEPTH,e,t,r)),determinant:Co,difference:Uo,diffuseColor:En,directPointLight:y_,directionToColor:kp,directionToFaceDirection:Ad,dispersion:ea,distance:Do,div:Ta,dodge:(...e)=>(d('TSL: "dodge" has been renamed. Use "blendDodge" instead.'),Ap(e)),dot:Vo,drawIndex:Ch,dynamicBufferAttribute:Vu,element:vn,emissive:wn,equal:va,equals:Bo,equirectUV:Wp,exp:eo,exp2:to,expression:Ju,faceDirection:Sd,faceForward:Zo,faceforward:iu,float:rn,floatBitsToInt:e=>new Cy(e,"int","float"),floatBitsToUint:e=>new Cy(e,"uint","float"),floor:ao,fog:Cx,fract:lo,frameGroup:ia,frameId:ky,frontFacing:Nd,fwidth:Eo,gain:(e,t)=>e.lessThan(.5)?Py(e.mul(2),t).div(2):ba(1,Py(xa(ba(1,e),2),t).div(2)),gapSize:qn,getConstNodeType:Oi,getCurrentStack:Zi,getDirection:_m,getDistanceAttenuation:f_,getGeometryRoughness:hg,getNormalFromDepth:Tb,getParallaxCorrectNormal:pv,getRoughness:pg,getScreenPosition:xb,getShIrradianceAt:gv,getShadowMaterial:XT,getShadowRenderObjectFunction:QT,getTextureIndex:Ry,getViewPosition:bb,ggxConvolution:Cm,globalId:Vx,glsl:(e,t)=>fx(e,t,"glsl"),glslFn:(e,t)=>bx(e,t,"glsl"),grayscale:jb,greaterThan:Aa,greaterThanEqual:Ea,hash:By,highpModelNormalViewMatrix:gd,highpModelViewMatrix:pd,hue:Kb,increment:Ga,incrementBefore:Va,inspector:ol,instance:Bh,instanceIndex:Ah,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Bs("float")):(r=Ps(t),s=Bs(t));const i=new Ab(e,r,s);return Oh(i,t,e)},instancedBufferAttribute:Ou,instancedDynamicBufferAttribute:Gu,instancedMesh:Lh,int:sn,intBitsToFloat:e=>new Cy(e,"float","int"),interleavedGradientNoise:_b,inverse:Mo,inverseSqrt:no,inversesqrt:nu,invocationLocalIndex:wh,invocationSubgroupIndex:Eh,ior:Kn,iridescence:In,iridescenceIOR:Dn,iridescenceThickness:Un,isolate:Hu,ivec2:un,ivec3:hn,ivec4:fn,js:(e,t)=>fx(e,t,"js"),label:hu,length:xo,lengthSq:jo,lessThan:Sa,lessThanEqual:Ra,lightPosition:NT,lightProjectionUV:vT,lightShadowMatrix:_T,lightTargetDirection:RT,lightTargetPosition:ST,lightViewPosition:AT,lightingContext:ep,lights:(e=[])=>ki(new MT).setLights(e),linearDepth:fp,linearToneMapping:nx,localId:Ox,log:ro,log2:so,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul(ro(r.div(t)));return rn(Math.E).pow(s).mul(t).negate()},luminance:Yb,mat2:xn,mat3:Tn,mat4:_n,matcapUV:gf,materialAO:Th,materialAlphaTest:Vc,materialAnisotropy:sh,materialAnisotropyVector:_h,materialAttenuationColor:ch,materialAttenuationDistance:dh,materialClearcoat:Qc,materialClearcoatNormal:Jc,materialClearcoatRoughness:Zc,materialColor:Oc,materialDispersion:bh,materialEmissive:kc,materialEnvIntensity:zd,materialEnvRotation:$d,materialIOR:lh,materialIridescence:ih,materialIridescenceIOR:nh,materialIridescenceThickness:ah,materialLightMap:xh,materialLineDashOffset:fh,materialLineDashSize:ph,materialLineGapSize:gh,materialLineScale:hh,materialLineWidth:mh,materialMetalness:Kc,materialNormal:Yc,materialOpacity:zc,materialPointSize:yh,materialReference:sc,materialReflectivity:qc,materialRefractionRatio:kd,materialRotation:eh,materialRoughness:Xc,materialSheen:th,materialSheenRoughness:rh,materialShininess:Gc,materialSpecular:$c,materialSpecularColor:Hc,materialSpecularIntensity:Wc,materialSpecularStrength:jc,materialThickness:uh,materialTransmission:oh,max:Lo,maxMipLevel:gl,mediumpModelViewMatrix:hd,metalness:Mn,min:Po,mix:qo,mixElement:eu,mod:_a,modInt:za,modelDirection:sd,modelNormalMatrix:ld,modelPosition:nd,modelRadius:ud,modelScale:ad,modelViewMatrix:cd,modelViewPosition:od,modelViewProjection:vh,modelWorldMatrix:id,modelWorldMatrixInverse:dd,morphReference:Yh,mrt:wy,mul:xa,mx_aastep:dv,mx_add:(e,t=rn(0))=>ya(e,t),mx_atan2:(e=rn(0),t=rn(1))=>fo(e,t),mx_cell_noise_float:(e=dl())=>j_(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>rn(e).sub(r).mul(t).add(r),mx_divide:(e,t=rn(1))=>Ta(e,t),mx_fractal_noise_float:(e=dl(),t=3,r=2,s=.5,i=1)=>X_(e,sn(t),r,s).mul(i),mx_fractal_noise_vec2:(e=dl(),t=3,r=2,s=.5,i=1)=>Y_(e,sn(t),r,s).mul(i),mx_fractal_noise_vec3:(e=dl(),t=3,r=2,s=.5,i=1)=>K_(e,sn(t),r,s).mul(i),mx_fractal_noise_vec4:(e=dl(),t=3,r=2,s=.5,i=1)=>Q_(e,sn(t),r,s).mul(i),mx_frame:()=>ky,mx_heighttonormal:(e,t)=>(e=cn(e),t=rn(t),Ic(e,t)),mx_hsvtorgb:ov,mx_ifequal:(e,t,r,s)=>e.equal(t).mix(r,s),mx_ifgreater:(e,t,r,s)=>e.greaterThan(t).mix(r,s),mx_ifgreatereq:(e,t,r,s)=>e.greaterThanEqual(t).mix(r,s),mx_invert:(e,t=rn(1))=>ba(t,e),mx_modulo:(e,t=rn(1))=>_a(e,t),mx_multiply:(e,t=rn(1))=>xa(e,t),mx_noise_float:(e=dl(),t=1,r=0)=>W_(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=dl(),t=1,r=0)=>H_(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=dl(),t=1,r=0)=>{e=e.convert("vec2|vec3");return mn(H_(e),W_(e.add(on(19,73)))).mul(t).add(r)},mx_place2d:(e,t=on(.5,.5),r=on(1,1),s=rn(0),i=on(0,0))=>{let n=e;if(t&&(n=n.sub(t)),r&&(n=n.mul(r)),s){const e=s.mul(Math.PI/180),t=e.cos(),r=e.sin();n=on(n.x.mul(t).sub(n.y.mul(r)),n.x.mul(r).add(n.y.mul(t)))}return t&&(n=n.add(t)),i&&(n=n.add(i)),n},mx_power:(e,t=rn(1))=>Go(e,t),mx_ramp4:(e,t,r,s,i=dl())=>{const n=i.x.clamp(),a=i.y.clamp(),o=qo(e,t,n),u=qo(r,s,n);return qo(o,u,a)},mx_ramplr:(e,t,r=dl())=>cv(e,t,r,"x"),mx_ramptb:(e,t,r=dl())=>cv(e,t,r,"y"),mx_rgbtohsv:uv,mx_rotate2d:(e,t)=>{e=on(e);const r=(t=rn(t)).mul(Math.PI/180);return bf(e,r)},mx_rotate3d:(e,t,r)=>{e=cn(e),t=rn(t),r=cn(r);const s=t.mul(Math.PI/180),i=r.normalize(),n=s.cos(),a=s.sin(),o=rn(1).sub(n);return e.mul(n).add(i.cross(e).mul(a)).add(i.mul(i.dot(e)).mul(o))},mx_safepower:(e,t=1)=>(e=rn(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},s=t.replace(/^out/,"").toLowerCase();if(void 0!==r[s])return e.element(r[s])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==r[t])return e.element(r[t])}return e},mx_splitlr:(e,t,r,s=dl())=>hv(e,t,r,s,"x"),mx_splittb:(e,t,r,s=dl())=>hv(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:lv,mx_subtract:(e,t=rn(0))=>ba(e,t),mx_timer:()=>Oy,mx_transform_uv:(e=1,t=0,r=dl())=>r.mul(e).add(t),mx_unifiednoise2d:(e,t=dl(),r=on(1,1),s=on(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>nv(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_unifiednoise3d:(e,t=dl(),r=on(1,1),s=on(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>av(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_worley_noise_float:(e=dl(),t=1)=>rv(e.convert("vec2|vec3"),t,sn(1)),mx_worley_noise_vec2:(e=dl(),t=1)=>sv(e.convert("vec2|vec3"),t,sn(1)),mx_worley_noise_vec3:(e=dl(),t=1)=>iv(e.convert("vec2|vec3"),t,sn(1)),negate:To,neutralToneMapping:gx,nodeArray:Wi,nodeImmutable:ji,nodeObject:ki,nodeObjectIntent:zi,nodeObjects:$i,nodeProxy:Hi,nodeProxyIntent:qi,normalFlat:wd,normalGeometry:Rd,normalLocal:Ed,normalMap:Bc,normalView:Bd,normalViewGeometry:Cd,normalWorld:Pd,normalWorldGeometry:Md,normalize:uo,not:Ma,notEqual:Na,numWorkgroups:Dx,objectDirection:Yl,objectGroup:aa,objectPosition:Zl,objectRadius:td,objectScale:Jl,objectViewPosition:ed,objectWorldMatrix:Ql,oneMinus:_o,or:Ca,orthographicDepthToViewZ:(e,t,r)=>t.sub(r).mul(e).sub(t),oscSawtooth:(e=Oy)=>e.fract(),oscSine:(e=Oy)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=Oy)=>e.fract().round(),oscTriangle:(e=Oy)=>e.add(.5).fract().mul(2).sub(1).abs(),output:Hn,outputStruct:Ay,overlay:(...e)=>(d('TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),Ep(e)),overloadingFn:Vy,parabola:Py,parallaxDirection:wc,parallaxUV:(e,t)=>e.sub(wc.mul(t)),parameter:(e,t)=>ki(new xy(e,t)),pass:(e,t,r)=>ki(new sx(sx.COLOR,e,t,r)),passTexture:(e,t)=>ki(new tx(e,t)),pcurve:(e,t,r)=>Go(Ta(Go(e,t),ya(Go(e,t),Go(ba(1,e),r))),1/t),perspectiveDepthToViewZ:hp,pmremTexture:Zm,pointShadow:g_,pointUV:wb,pointWidth:Xn,positionGeometry:md,positionLocal:fd,positionPrevious:yd,positionView:Td,positionViewDirection:_d,positionWorld:bd,positionWorldDirection:xd,posterize:Jb,pow:Go,pow2:ko,pow3:zo,pow4:$o,premultiplyAlpha:Cp,property:An,quadBroadcast:bT,quadSwapDiagonal:hT,quadSwapX:dT,quadSwapY:cT,radians:Za,rand:Jo,range:Lx,rangeFog:function(e,t,r){return d('TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),Cx(e,Ex(t,r))},rangeFogFactor:Ex,reciprocal:Ao,reference:ec,referenceBuffer:tc,reflect:Io,reflectVector:jd,reflectView:Wd,reflector:e=>ki(new lb(e)),refract:Yo,refractVector:qd,refractView:Hd,reinhardToneMapping:ax,remap:Yu,remapClamp:Qu,renderGroup:na,renderOutput:rl,rendererReference:Pu,rotate:bf,rotateUV:zy,roughness:Cn,round:So,rtt:yb,sRGBTransferEOTF:Nu,sRGBTransferOETF:Su,sample:(e,t=null)=>ki(new vb(e,ki(t))),sampler:e=>(!0===e.isNode?e:bl(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:bl(e)).convert("samplerComparison"),saturate:Ko,saturation:qb,screen:(...e)=>(d('TSL: "screen" has been renamed. Use "blendScreen" instead.'),Rp(e)),screenCoordinate:Pl,screenDPR:Cl,screenSize:Bl,screenUV:Ml,scriptable:Ax,scriptableValue:Tx,select:ou,setCurrentStack:Qi,setName:cu,shaderStages:qs,shadow:i_,shadowPositionWorld:PT,shapeCircle:T_,sharedUniformGroup:sa,sheen:Ln,sheenRoughness:Fn,shiftLeft:Da,shiftRight:Ua,shininess:Wn,sign:bo,sin:co,sinc:(e,t)=>co(ja.mul(t.mul(e).sub(1))).div(ja.mul(t.mul(e).sub(1))),skinning:zh,smoothstep:Qo,smoothstepElement:tu,specularColor:zn,specularF90:$n,spherizeUV:$y,split:(e,t)=>ki(new si(ki(e),t)),spritesheetUV:qy,sqrt:io,stack:_y,step:Fo,stepElement:ru,storage:Oh,storageBarrier:()=>kx("storage").toStack(),storageObject:(e,t,r)=>(d('TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),Oh(e,t,r).setPBO(!0)),storageTexture:Db,string:(e="")=>ki(new ui(e,"string")),struct:(e,t=null)=>{const r=new vy(e,t),s=(...t)=>{let s=null;if(t.length>0)if(t[0].isNode){s={};const r=Object.keys(e);for(let e=0;e<t.length;e++)s[r[e]]=t[e]}else s=t[0];return ki(new Ny(r,s))};return s.layout=r,s.isStruct=!0,s},sub:ba,subBuild:xu,subgroupAdd:Yx,subgroupAll:oT,subgroupAnd:rT,subgroupAny:uT,subgroupBallot:Kx,subgroupBroadcast:pT,subgroupBroadcastFirst:lT,subgroupElect:Xx,subgroupExclusiveAdd:Zx,subgroupExclusiveMul:tT,subgroupInclusiveAdd:Qx,subgroupInclusiveMul:eT,subgroupIndex:Rh,subgroupMax:aT,subgroupMin:nT,subgroupMul:Jx,subgroupOr:sT,subgroupShuffle:gT,subgroupShuffleDown:yT,subgroupShuffleUp:fT,subgroupShuffleXor:mT,subgroupSize:Gx,subgroupXor:iT,tan:po,tangentGeometry:bc,tangentLocal:xc,tangentView:Tc,tangentWorld:_c,texture:bl,texture3D:Ob,textureBarrier:()=>kx("texture").toStack(),textureBicubic:Hg,textureBicubicLevel:Wg,textureCubeUV:vm,textureLevel:(e,t,r)=>bl(e,t).level(r),textureLoad:xl,textureSize:hl,textureStore:(e,t,r)=>{const s=Db(e,t,r);return null!==r&&s.toStack(),s},thickness:Qn,time:Oy,toneMapping:Fu,toneMappingExposure:Iu,toonOutlinePass:(e,r,s=new t(0,0,0),i=.003,n=1)=>ki(new ix(e,r,ki(s),ki(i),ki(n))),transformDirection:Wo,transformNormal:Fd,transformNormalToView:Id,transformedClearcoatNormalView:Vd,transformedNormalView:Dd,transformedNormalWorld:Ud,transmission:Yn,transpose:wo,triNoise3D:Iy,triplanarTexture:(...e)=>Xy(...e),triplanarTextures:Xy,trunc:Ro,uint:nn,uintBitsToFloat:e=>new Cy(e,"float","uint"),uniform:ua,uniformArray:Sl,uniformCubeTexture:(e=Xd)=>Yd(e),uniformFlow:du,uniformGroup:ra,uniformTexture:(e=ml)=>bl(e),unpremultiplyAlpha:Mp,userData:(e,t,r)=>ki(new Gb(e,t,r)),uv:dl,uvec2:ln,uvec3:pn,uvec4:yn,varying:_u,varyingProperty:Rn,vec2:on,vec3:cn,vec4:mn,vectorComponents:Xs,velocity:Hb,vertexColor:Np,vertexIndex:Sh,vertexStage:vu,vibrance:Xb,viewZToLogarithmicDepth:pp,viewZToOrthographicDepth:dp,viewZToPerspectiveDepth:cp,viewport:Ll,viewportCoordinate:Il,viewportDepthTexture:up,viewportLinearDepth:yp,viewportMipTexture:np,viewportResolution:Ul,viewportSafeUV:Hy,viewportSharedTexture:Vp,viewportSize:Fl,viewportTexture:ip,viewportUV:Dl,wgsl:(e,t)=>fx(e,t,"wgsl"),wgslFn:(e,t)=>bx(e,t,"wgsl"),workgroupArray:(e,t)=>ki(new $x("Workgroup",e,t)),workgroupBarrier:()=>kx("workgroup").toStack(),workgroupId:Ux,workingToColorSpace:Eu,xor:Ba});const fv=new by;class yv extends Of{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(t,r,s){const i=this.renderer,n=this.nodes.getBackgroundNode(t)||t.background;let a=!1;if(null===n)i._clearColor.getRGB(fv),fv.a=i._clearColor.a;else if(!0===n.isColor)n.getRGB(fv),fv.a=1,a=!0;else if(!0===n.isNode){const u=this.get(t),l=n;fv.copy(i._clearColor);let d=u.backgroundMesh;if(void 0===d){const h=lu(mn(l).mul(Lb),{getUV:()=>Fb.mul(Md),getTextureLevel:()=>Pb});let p=vh;p=p.setZ(p.w);const g=new Bp;function m(){n.removeEventListener("dispose",m),d.material.dispose(),d.geometry.dispose()}g.name="Background.material",g.side=w,g.depthTest=!1,g.depthWrite=!1,g.allowOverride=!1,g.fog=!1,g.lights=!1,g.vertexNode=p,g.colorNode=h,u.backgroundMeshNode=h,u.backgroundMesh=d=new Q(new We(1,32,32),g),d.frustumCulled=!1,d.name="Background.mesh",d.onBeforeRender=function(e,t,r){this.matrixWorld.copyPosition(r.matrixWorld)},n.addEventListener("dispose",m)}const c=l.getCacheKey();u.backgroundCacheKey!==c&&(u.backgroundMeshNode.node=mn(l).mul(Lb),u.backgroundMeshNode.needsUpdate=!0,d.material.needsUpdate=!0,u.backgroundCacheKey=c),r.unshift(d,d.geometry,d.material,0,0,null,null)}else e("Renderer: Unsupported background configuration.",n);const o=i.xr.getEnvironmentBlendMode();if("additive"===o?fv.set(0,0,0,1):"alpha-blend"===o&&fv.set(0,0,0,0),!0===i.autoClear||!0===a){const f=s.clearColorValue;f.r=fv.r,f.g=fv.g,f.b=fv.b,f.a=fv.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(f.r*=f.a,f.g*=f.a,f.b*=f.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let bv=0;class xv{constructor(e="",t=[],r=0,s=[]){this.name=e,this.bindings=t,this.index=r,this.bindingsReference=s,this.id=bv++}}class Tv{constructor(e,t,r,s,i,n,a,o,u,l=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=r,this.transforms=l,this.nodeAttributes=s,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=u,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const r=new xv(t.name,[],t.index,t.bindingsReference);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class _v{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class vv{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class Nv{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class Sv extends Nv{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class Av{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let Rv=0;class Ev{constructor(e=null){this.id=Rv++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class wv{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class Cv{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class Mv extends Cv{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class Bv extends Cv{constructor(e,t=new r){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class Pv extends Cv{constructor(e,t=new s){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class Lv extends Cv{constructor(e,t=new i){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class Fv extends Cv{constructor(e,r=new t){super(e,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class Iv extends Cv{constructor(e,t=new n){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class Dv extends Cv{constructor(e,t=new a){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class Uv extends Cv{constructor(e,t=new o){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Vv extends Mv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Ov extends Bv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Gv extends Pv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kv extends Lv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zv extends Fv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $v extends Iv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Wv extends Dv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Hv extends Uv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let jv=0;const qv=new WeakMap,Xv=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Kv=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class Yv{constructor(e,t,r){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=r,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=_y(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Ev,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:jv++})}isOpaque(){const e=this.material;return!1===e.transparent&&e.blending===He&&!1===e.alphaToCoverage}getBindGroupsCache(){let e=qv.get(this.renderer);return void 0===e&&(e=new Ff,qv.set(this.renderer,e)),e}createRenderTarget(e,t,r){return new me(e,t,r)}createCubeRenderTarget(e,t){return new Hp(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=this.getBindGroupsCache(),s=[];let i,n=!0;for(const e of t)s.push(e),n=n&&!0!==e.groupNode.shared;return n?(i=r.get(s),void 0===i&&(i=new xv(e,s,this.bindingsIndexes[e].group,s),r.set(s,i))):i=new xv(e,s,this.bindingsIndexes[e].group,s),i}getBindGroupArray(e,t){const r=this.bindings[t];let s=r[e];return void 0===s&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),r[e]=s=[]),s}getBindings(){let e=this.bindGroups;if(null===e){const t={},r=this.bindings;for(const e of qs)for(const s in r[e]){const i=r[e][s];(t[s]||(t[s]=[])).push(...i)}e=[];for(const r in t){const s=t[r],i=this._getBindGroup(r,s);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort(((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order));for(let t=0;t<e.length;t++){const r=e[t];this.bindingsIndexes[r.name].group=t,r.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==zs.NONE&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),r=e.getUpdateAfterType();t!==zs.NONE&&this.updateBeforeNodes.push(e),r!==zs.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===J||e.magFilter===je||e.magFilter===qe||e.magFilter===k||e.minFilter===J||e.minFilter===je||e.minFilter===qe||e.minFilter===k}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){return this.context,this.context}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const r=this.getDataFromNode(e);return void 0===r.cache&&(r.cache=new Ev(t?this.getCache():null)),r.cache}isAvailable(){return!1}getVertexIndex(){d("Abstract function.")}getInstanceIndex(){d("Abstract function.")}getDrawIndex(){d("Abstract function.")}getFrontFacing(){d("Abstract function.")}getFragCoord(){d("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,t.usageCount}generateTexture(){d("Abstract function.")}generateTextureLod(){d("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,r=null){let s=this.generateArrayDeclaration(e,t)+"( ";for(let i=0;i<t;i++){const n=r?r[i]:null;s+=null!==n?n.build(this,e):this.generateConst(e),i<t-1&&(s+=", ")}return s+=" )",s}generateStruct(e,t,r=null){const s=[];for(const e of t){const{name:t,type:i}=e;r&&r[t]&&r[t].isNode?s.push(r[t].build(this,i)):s.push(this.generateConst(i))}return e+"( "+s.join(", ")+" )"}generateConst(e,n=null){if(null===n&&("float"===e||"int"===e||"uint"===e?n=0:"bool"===e?n=!1:"color"===e?n=new t:"vec2"===e?n=new r:"vec3"===e?n=new s:"vec4"===e&&(n=new i)),"float"===e)return Kv(n);if("int"===e)return`${Math.round(n)}`;if("uint"===e)return n>=0?`${Math.round(n)}u`:"0u";if("bool"===e)return n?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${Kv(n.r)}, ${Kv(n.g)}, ${Kv(n.b)} )`;const a=this.getTypeLength(e),o=this.getComponentType(e),u=e=>this.generateConst(o,e);if(2===a)return`${this.getType(e)}( ${u(n.x)}, ${u(n.y)} )`;if(3===a)return`${this.getType(e)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)} )`;if(4===a&&"mat2"!==e)return`${this.getType(e)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)}, ${u(n.w)} )`;if(a>=4&&n&&(n.isMatrix2||n.isMatrix3||n.isMatrix4))return`${this.getType(e)}( ${n.elements.map(u).join(", ")} )`;if(a>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const r=this.attributes;for(const t of r)if(t.name===e)return t;const s=new _v(e,t);return this.registerDeclaration(s),r.push(s),s}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===S)return"int";if(t===N)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let r=Ms(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return Xv.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const r=t.array,s=e.itemSize,i=e.normalized;let n;return e instanceof Xe||!0===i||(n=this.getTypeFromArray(r)),this.getTypeFromLength(s,n)}getTypeLength(e){const t=this.getVectorType(e),r=/vec([2-4])/.exec(t);return null!==r?Number(r[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=_y(this.stack);const e=Zi();return this.stacks.push(e),Qi(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,Qi(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,r=null){let s=(r=null===r?e.isGlobal(this)?this.globalCache:this.cache:r).getData(e);void 0===s&&(s={},r.setData(e,s)),void 0===s[t]&&(s[t]={});let i=s[t];const n=s.any?s.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=n),i}getNodeProperties(e,t="any"){const r=this.getDataFromNode(e,t);return r.properties||(r.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const r=this.getDataFromNode(e);let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new _v("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,r=null,s=this.shaderStage){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.structType;if(void 0===n){const a=this.structs.index++;null===r&&(r="StructType"+a),n=new wv(r,t),this.structs[s].push(n),this.types[s][r]=e,i.structType=n}return n}getOutputStructTypeFromNode(e,t){const r=this.getStructTypeFromNode(e,t,"OutputType","fragment");return r.output=!0,r}getUniformFromNode(e,t,r=this.shaderStage,s=null){const i=this.getDataFromNode(e,r,this.globalCache);let n=i.uniform;if(void 0===n){const a=this.uniforms.index++;n=new vv(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getVarFromNode(e,t=null,r=e.getNodeType(this),s=this.shaderStage,i=!1){const n=this.getDataFromNode(e,s),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const u=i?"_const":"_var",l=this.vars[s]||(this.vars[s]=[]),d=this.vars[u]||(this.vars[u]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+d,this.vars[u]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new Nv(t,r,i,c),i||l.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,r=e.getNodeType(this),s=null,i=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,u=e.length;null===t&&(t="nodeVarying"+u),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new Sv(t,r,s,i),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,r=this.declarations[t]||(this.declarations[t]={}),s=this.getPropertyName(e);let i=1,n=s;for(;void 0!==r[n];)n=s+"_"+i++;i>1&&(e.name=n,d(`TSL: Declaration name '${s}' of '${e.type}' already in use. Renamed to '${n}'.`)),r[n]=e}getCodeFromNode(e,t,r=this.shaderStage){const s=this.getDataFromNode(e);let i=s.code;if(void 0===i){const e=this.codes[r]||(this.codes[r]=[]),n=e.length;i=new Av("nodeCode"+n,t),e.push(i),s.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:r,flowCodeBlock:s}=this.getDataFromNode(e);let i=!0,n=t;for(;n;){if(!0===s.get(n)){i=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(i)for(const e of r)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,r){const s=this.getDataFromNode(e),i=s.flowCodes||(s.flowCodes=[]),n=s.flowCodeBlock||(s.flowCodeBlock=new WeakMap);i.push(t),n.set(r,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),r=this.flowChildNode(e,t);return this.flowsData.set(e,r),r}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new yx,r=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=r,t}flowShaderNode(e){const t=e.layout,r={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)r[e.name]=new xy(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,i}flowBuildStage(e,t,r=null){const s=this.getBuildStage();this.setBuildStage(t);const i=e.build(this,r);return this.setBuildStage(s),i}flowStagesNode(e,t=null){const r=this.flow,s=this.vars,i=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new Ev,this.stack=_y();for(const r of js)this.setBuildStage(r),u.result=e.build(this,t);return u.vars=this.getVars(this.shaderStage),this.flow=r,this.vars=s,this.declarations=i,this.cache=n,this.stack=o,this.setBuildStage(a),u}getFunctionOperator(){return null}buildFunctionCode(){d("Abstract function.")}flowChildNode(e,t=null){const r=this.flow,s={code:""};return this.flow=s,s.result=e.build(this,t),this.flow=r,s}flowNodeFromShaderStage(e,t,r=null,s=null){const i=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const u={...this.context};delete u.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=u;let l=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,r);null!==s&&(i.code+=`${this.tab+s} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=i,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){d("Abstract function.")}getVaryings(){d("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e){let t="";const r=this.vars[e];if(void 0!==r)for(const e of r)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){d("Abstract function.")}getCodes(e){const t=this.codes[e];let r="";if(void 0!==t)for(const e of t)r+=e.code+"\n";return r}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){d("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const r=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const s=t[e];if(r.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let r,s;return r=null!==t?this.getClosestSubBuild(t):this.subBuildFn,s=r?e?r+"_"+e:r:e,s}build(){const{object:t,material:r,renderer:s}=this;if(null!==r){let t=s.library.fromMaterial(r);null===t&&(e(`NodeMaterial: Material "${r.type}" is not compatible.`),t=new Bp),t.build(this)}else this.addFlow("compute",t);for(const e of js){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of qs){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new Vv(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new Ov(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new Gv(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new kv(e);if("color"===t)return new zv(e);if("mat2"===t)return new $v(e);if("mat3"===t)return new Wv(e);if("mat4"===t)return new Hv(e);throw new Error(`Uniform "${t}" not declared.`)}format(e,t,r){if((t=this.getVectorType(t))===(r=this.getVectorType(r))||null===r||this.isReference(r))return e;const s=this.getTypeLength(t),i=this.getTypeLength(r);return 16===s&&9===i?`${this.getType(r)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===s&&4===i?`${this.getType(r)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:s>4||i>4||0===i?e:s===i?`${this.getType(r)}( ${e} )`:s>i?(e="bool"===r?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),r)):4===i&&s>1?`${this.getType(r)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===s?`${this.getType(r)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===s&&i>1&&t!==this.getComponentType(r)&&(e=`${this.getType(this.getComponentType(r))}( ${e} )`),`${this.getType(r)}( ${e} )`)}getSignature(){return`// Three.js r${Ke} - Node System\n`}}class Qv{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let r=e.get(t);return void 0===r&&(r={renderId:0,frameId:0},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===zs.FRAME){const t=this._getMaps(this.updateBeforeMap,r);t.frameId!==this.frameId&&!1!==e.updateBefore(this)&&(t.frameId=this.frameId)}else if(t===zs.RENDER){const t=this._getMaps(this.updateBeforeMap,r);t.renderId!==this.renderId&&!1!==e.updateBefore(this)&&(t.renderId=this.renderId)}else t===zs.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===zs.FRAME){const t=this._getMaps(this.updateAfterMap,r);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===zs.RENDER){const t=this._getMaps(this.updateAfterMap,r);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===zs.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===zs.FRAME){const t=this._getMaps(this.updateMap,r);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===zs.RENDER){const t=this._getMaps(this.updateMap,r);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===zs.OBJECT&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class Zv{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}Zv.isNodeFunctionInput=!0;class Jv extends m_{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:RT(this.light),lightColor:e}}}const eN=new o,tN=new o;let rN=null;class sN extends m_{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=ua(new s).setGroup(na),this.halfWidth=ua(new s).setGroup(na),this.updateType=zs.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;tN.identity(),eN.copy(t.matrixWorld),eN.premultiply(r),tN.extractRotation(eN),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(tN),this.halfHeight.value.applyMatrix4(tN)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=bl(rN.LTC_FLOAT_1),r=bl(rN.LTC_FLOAT_2)):(t=bl(rN.LTC_HALF_1),r=bl(rN.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:AT(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){rN=e}}class iN extends m_{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=ua(0).setGroup(na),this.penumbraCosNode=ua(0).setGroup(na),this.cutoffDistanceNode=ua(0).setGroup(na),this.decayExponentNode=ua(0).setGroup(na),this.colorNode=ua(this.color).setGroup(na)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:r,penumbraCosNode:s}=this;return Qo(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=vT(this.light,e.context.positionWorld),t.projectionUV=r),r}setupDirect(e){const{colorNode:t,cutoffDistanceNode:r,decayExponentNode:s,light:i}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(RT(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=f_({lightDistance:l,cutoffDistance:r,decayExponent:s});let c,h,p=t.mul(u).mul(d);if(i.colorNode?(h=this.getLightCoord(e),c=i.colorNode(h)):i.map&&(h=this.getLightCoord(e),c=bl(i.map,h.xy).onRenderUpdate((()=>i.map))),c){p=h.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class nN extends iN{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const r=this.light.iesMap;let s=null;if(r&&!0===r.isTexture){const e=t.acos().mul(1/Math.PI);s=bl(r,on(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}const aN=Yi((([e,t])=>{const r=e.abs().sub(t);return xo(Lo(r,0)).add(Po(Lo(r.x,r.y),0))}));class oN extends iN{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=rn(0),r=this.penumbraCosNode,s=_T(this.light).mul(e.context.positionWorld||bd);return Ji(s.w.greaterThan(0),(()=>{const e=s.xyz.div(s.w),i=aN(e.xy.sub(on(.5)),on(.5)),n=Ta(-1,ba(1,mo(r)).sub(1));t.assign(Ko(i.mul(-2).mul(n)))})),t}}class uN extends m_{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class lN extends m_{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=NT(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=ua(new t).setGroup(na)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:r,lightDirectionNode:s}=this,i=Pd.dot(s).mul(.5).add(.5),n=qo(r,t,i);e.context.irradiance.addAssign(n)}}class dN extends m_{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new s);this.lightProbe=Sl(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=gv(Pd,this.lightProbe);e.context.irradiance.addAssign(t)}}class cN{parseFunction(){d("Abstract function.")}}class hN{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){d("Abstract function.")}}hN.isNodeFunction=!0;const pN=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,gN=/[a-z_0-9]+/gi,mN="#pragma main";class fN extends hN{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(mN),r=-1!==t?e.slice(t+12):e,s=r.match(pN);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=gN.exec(i));)n.push(a);const o=[];let u=0;for(;u<n.length;){const e="const"===n[u][0];!0===e&&u++;let t=n[u][0];"in"===t||"out"===t||"inout"===t?u++:t="";const r=n[u++][0];let s=Number.parseInt(n[u][0]);!1===Number.isNaN(s)?u++:s=null;const i=n[u++][0];o.push(new Zv(r,i,s,t,e))}const l=r.substring(s[0].length),d=void 0!==s[3]?s[3]:"";return{type:s[2],inputs:o,name:d,precision:void 0!==s[1]?s[1]:"",inputsCode:i,blockCode:l,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("FunctionNode: Function is not a GLSL code.")})(e);super(t,r,s,i),this.inputsCode=n,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const r=this.blockCode;if(""!==r){const{type:s,inputsCode:i,headerCode:n,precision:a}=this;let o=`${s} ${e} ( ${i.trim()} )`;""!==a&&(o=`${a} ${o}`),t=n+o+r}else t="";return t}}class yN extends cN{parseFunction(e){return new fN(e)}}const bN=new WeakMap,xN=[],TN=[];class _N extends Of{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new Qv,this.nodeBuilderCache=new Map,this.callHashCache=new Ff,this.groupsData=new Ff,this.cacheLib={}}updateGroup(e){const t=e.groupNode,r=t.name;if(r===aa.name)return!0;if(r===na.name){const t=this.get(e),r=this.nodeFrame.renderId;return t.renderId!==r&&(t.renderId=r,!0)}if(r===ia.name){const t=this.get(e),r=this.nodeFrame.frameId;return t.frameId!==r&&(t.frameId=r,!0)}xN[0]=t,xN[1]=e;let s=this.groupsData.get(xN);return void 0===s&&this.groupsData.set(xN,s={}),xN.length=0,s.version!==t.version&&(s.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(t){const r=this.get(t);let s=r.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:i}=this,n=this.getForRenderCacheKey(t);if(s=i.get(n),void 0===s){const r=e=>{const r=this.backend.createNodeBuilder(t.object,this.renderer);return r.scene=t.scene,r.material=e,r.camera=t.camera,r.context.material=e,r.lightsNode=t.lightsNode,r.environmentNode=this.getEnvironmentNode(t.scene),r.fogNode=this.getFogNode(t.scene),r.clippingContext=t.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&r.enableMultiview(),r};let a=r(t.material);try{a.build()}catch(t){a=r(new Bp),a.build(),e("TSL: "+t)}s=this._createNodeBuilderState(a),i.set(n,s)}s.usedTimes++,r.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let r=t.nodeBuilderState;if(void 0===r){const s=this.backend.createNodeBuilder(e,this.renderer);s.build(),r=this._createNodeBuilderState(s),t.nodeBuilderState=r}return r}_createNodeBuilderState(e){return new Tv(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const r=this.get(e);r.environmentNode&&(t=r.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const r=this.get(e);r.backgroundNode&&(t=r.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){xN[0]=e,xN[1]=t;const r=this.renderer.info.calls,s=this.callHashCache.get(xN)||{};if(s.callId!==r){const i=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&TN.push(t.getCacheKey(!0)),i&&TN.push(i.getCacheKey()),n&&TN.push(n.getCacheKey()),TN.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),TN.push(this.renderer.shadowMap.enabled?1:0),TN.push(this.renderer.shadowMap.type),s.callId=r,s.cacheKey=Rs(TN),this.callHashCache.set(xN,s),TN.length=0}return xN.length=0,s.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(t){const r=this.get(t),s=t.background;if(s){const i=0===t.backgroundBlurriness&&r.backgroundBlurriness>0||t.backgroundBlurriness>0&&0===r.backgroundBlurriness;if(r.background!==s||i){const n=this.getCacheNode("background",s,(()=>{if(!0===s.isCubeTexture||s.mapping===te||s.mapping===re||s.mapping===fe){if(t.backgroundBlurriness>0||s.mapping===fe)return Zm(s);{let e;return e=!0===s.isCubeTexture?Qd(s):bl(s),Yp(e)}}if(!0===s.isTexture)return bl(s,Ml.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&e("WebGPUNodes: Unsupported background configuration.",s)}),i);r.backgroundNode=n,r.background=s,r.backgroundBlurriness=t.backgroundBlurriness}}else r.backgroundNode&&(delete r.backgroundNode,delete r.background)}getCacheNode(e,t,r,s=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=i.get(t);return(void 0===n||s)&&(n=r(),i.set(t,n)),n}updateFog(t){const r=this.get(t),s=t.fog;if(s){if(r.fog!==s){const t=this.getCacheNode("fog",s,(()=>{if(s.isFogExp2){const e=ec("color","color",s).setGroup(na),t=ec("density","float",s).setGroup(na);return Cx(e,wx(t))}if(s.isFog){const e=ec("color","color",s).setGroup(na),t=ec("near","float",s).setGroup(na),r=ec("far","float",s).setGroup(na);return Cx(e,Ex(t,r))}e("Renderer: Unsupported fog configuration.",s)}));r.fogNode=t,r.fog=s}}else delete r.fogNode,delete r.fog}updateEnvironment(t){const r=this.get(t),s=t.environment;if(s){if(r.environment!==s){const t=this.getCacheNode("environment",s,(()=>!0===s.isCubeTexture?Qd(s):!0===s.isTexture?bl(s):void e("Nodes: Unsupported environment configuration.",s)));r.environmentNode=t,r.environment=s}}else r.environmentNode&&(delete r.environmentNode,delete r.environment)}getNodeFrame(e=this.renderer,t=null,r=null,s=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=r,n.camera=s,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return bN.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,r=this.getOutputCacheKey(),s=e.isArrayTexture?Ob(e,cn(Ml,Al("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):bl(e,Ml).renderOutput(t.toneMapping,t.currentColorSpace);return bN.set(e,r),s}updateBefore(e){const t=e.getNodeBuilderState();for(const r of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(r)}updateAfter(e){const t=e.getNodeBuilderState();for(const r of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(r)}updateForCompute(e){const t=this.getNodeFrame(),r=this.getForCompute(e);for(const e of r.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),r=e.getNodeBuilderState();for(const e of r.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new Qv,this.nodeBuilderCache=new Map,this.cacheLib={}}}const vN=new De;class NN{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new a,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,r){const s=e.length;for(let i=0;i<s;i++){vN.copy(e[i]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const s=t[r+i],n=vN.normal;s.x=-n.x,s.y=-n.y,s.z=-n.z,s.w=vN.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let r=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const s=t.clippingPlanes,n=s.length;let a,o;if(this.clipIntersection?(a=this.intersectionPlanes,o=e.intersectionPlanes.length):(a=this.unionPlanes,o=e.unionPlanes.length),a.length!==o+n){a.length=o+n;for(let e=0;e<n;e++)a[o+e]=new i;r=!0}this.projectPlanes(s,a,o),r&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return void 0===t&&(t=new NN(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class SN{constructor(e,t){this.bundleGroup=e,this.camera=t}}const AN=[];class RN{constructor(){this.bundles=new Ff}get(e,t){const r=this.bundles;AN[0]=e,AN[1]=t;let s=r.get(AN);return void 0===s&&(s=new SN(e,t),r.set(AN,s)),AN.length=0,s}dispose(){this.bundles=new Ff}}class EN{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const r=this.getMaterialNodeClass(e.type);if(null!==r){t=new r;for(const r in e)t[r]=e[r]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,r){if(r.has(t))d(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);r.set(t,e)}}addClass(e,t,r){if(r.has(t))d(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);r.set(t,e)}}}const wN=new MT,CN=[];class MN extends Ff{constructor(){super()}createNode(e=[]){return(new MT).setLights(e)}getNode(e,t){if(e.isQuadMesh)return wN;CN[0]=e,CN[1]=t;let r=this.get(CN);return void 0===r&&(r=this.createNode(),this.set(CN,r)),CN.length=0,r}}class BN extends me{constructor(e=1,t=1,r={}){super(e,t,r),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const PN=new s,LN=new s;class FN extends u{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Te,this._cameraL.viewport=new i,this._cameraR=new Te,this._cameraR.viewport=new i,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Ye,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._frameBufferTargets=null,this._createXRLayer=ON.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new r,this._onSessionEvent=DN.bind(this),this._onSessionEnd=UN.bind(this),this._onInputSourcesChange=VN.bind(this),this._onAnimationFrame=GN.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(null!==this._glProjLayer||null!==this._glBaseLayer)return this._foveation}setFoveation(e){this._foveation=e,null!==this._glProjLayer&&(this._glProjLayer.fixedFoveation=e),null!==this._glBaseLayer&&void 0!==this._glBaseLayer.fixedFoveation&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,!0===this.isPresenting&&d("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&d("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(null!==this._session)return this._session.environmentBlendMode}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,r,s,i,n,a,o={}){const u=new Qe(e,t),l=new BN(i,n,{format:be,type:Ie,depthTexture:new z(i,n,o.stencil?Fe:N,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?Pe:Le),stencilBuffer:o.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});l._autoAllocateDepthBuffer=!0;const d=new ae({color:16777215,side:Ze});d.map=l.texture,d.map.offset.y=1,d.map.repeat.y=-1;const c=new Q(u,d);c.position.copy(r),c.quaternion.copy(s);const h={type:"quad",width:e,height:t,translation:r,quaternion:s,pixelwidth:i,pixelheight:n,plane:c,material:d,rendercall:a,renderTarget:l};if(this._layers.push(h),null!==this._session){h.plane.material=new ae({color:16777215,side:Ze}),h.plane.material.blending=Je,h.plane.material.blendEquation=et,h.plane.material.blendSrc=tt,h.plane.material.blendDst=tt,h.xrlayer=this._createXRLayer(h);const e=this._session.renderState.layers;e.unshift(h.xrlayer),this._session.updateRenderState({layers:e})}else l.isXRRenderTarget=!1;return c}createCylinderLayer(e,t,r,s,i,n,a,o,u={}){const l=new rt(e,e,e*t/r,64,64,!0,Math.PI-t/2,t),d=new BN(n,a,{format:be,type:Ie,depthTexture:new z(n,a,u.stencil?Fe:N,void 0,void 0,void 0,void 0,void 0,void 0,u.stencil?Pe:Le),stencilBuffer:u.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});d._autoAllocateDepthBuffer=!0;const c=new ae({color:16777215,side:w});c.map=d.texture,c.map.offset.y=1,c.map.repeat.y=-1;const h=new Q(l,c);h.position.copy(s),h.quaternion.copy(i);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:r,translation:s,quaternion:i,pixelwidth:n,pixelheight:a,plane:h,material:c,rendercall:o,renderTarget:d};if(this._layers.push(p),null!==this._session){p.plane.material=new ae({color:16777215,side:w}),p.plane.material.blending=Je,p.plane.material.blendEquation=et,p.plane.material.blendSrc=tt,p.plane.material.blendDst=tt,p.xrlayer=this._createXRLayer(p);const e=this._session.renderState.layers;e.unshift(p.xrlayer),this._session.updateRenderState({layers:e})}else d.isXRRenderTarget=!1;return h}renderLayers(){const e=new s,t=new nt,i=this._renderer,n=this.isPresenting,a=i.getOutputRenderTarget(),o=i._frameBufferTarget;this.isPresenting=!1;const u=new r;i.getSize(u);const l=i._quad;for(const r of this._layers)if(r.renderTarget.isXRRenderTarget=null!==this._session,r.renderTarget._hasExternalTextures=r.renderTarget.isXRRenderTarget,r.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){r.xrlayer.transform=new XRRigidTransform(r.plane.getWorldPosition(e),r.plane.getWorldQuaternion(t));const s=this._glBinding.getSubImage(r.xrlayer,this._xrFrame);i.backend.setXRRenderTargetTextures(r.renderTarget,s.colorTexture,void 0),i._setXRLayerSize(r.renderTarget.width,r.renderTarget.height),i.setOutputRenderTarget(r.renderTarget),i.setRenderTarget(null),i._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:n,quad:a}=this._frameBufferTargets.get(r.renderTarget)||{frameBufferTarget:null,quad:null};n?(i._frameBufferTarget=n,i._quad=a):(i._quad=new gb(new Bp),this._frameBufferTargets.set(r.renderTarget,{frameBufferTarget:i._getFrameBufferTarget(),quad:i._quad})),r.rendercall(),i._frameBufferTarget=null}else i.setRenderTarget(r.renderTarget),r.rendercall();i.setRenderTarget(null),i.setOutputRenderTarget(a),i._frameBufferTarget=o,i._setXRLayerSize(u.x,u.y),i._quad=l,this.isPresenting=n}getSession(){return this._session}async setSession(e){const t=this._renderer,r=t.backend;this._gl=t.getContext();const s=this._gl,i=s.getContextAttributes();if(this._session=e,null!==e){if(!0===r.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await r.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let r=null,n=null,a=null;t.depth&&(a=t.stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24,r=t.stencil?Pe:Le,n=t.stencil?Fe:N);const o={colorFormat:s.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const u=this._glBinding.createProjectionLayer(o),l=[u];this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const d=this._useMultiview?2:1,c=new z(u.textureWidth,u.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,r,d);if(this._xrRenderTarget=new BN(u.textureWidth,u.textureHeight,{format:be,type:Ie,colorSpace:t.outputColorSpace,depthTexture:c,stencilBuffer:t.stencil,samples:i.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const e of this._layers)e.plane.material=new ae({color:16777215,side:"cylinder"===e.type?w:Ze}),e.plane.material.blending=Je,e.plane.material.blendEquation=et,e.plane.material.blendSrc=tt,e.plane.material.blendDst=tt,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{const r={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,s,r);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new BN(i.framebufferWidth,i.framebufferHeight,{format:be,type:Ie,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const r=e.near,s=e.far,i=this._cameraXR,n=this._cameraL,a=this._cameraR;i.near=a.near=n.near=r,i.far=a.far=n.far=s,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=6|e.layers.mask,n.layers.mask=3&i.layers.mask,a.layers.mask=5&i.layers.mask;const o=e.parent,u=i.cameras;IN(i,o);for(let e=0;e<u.length;e++)IN(u[e],o);2===u.length?function(e,t,r){PN.setFromMatrixPosition(t.matrixWorld),LN.setFromMatrixPosition(r.matrixWorld);const s=PN.distanceTo(LN),i=t.projectionMatrix.elements,n=r.projectionMatrix.elements,a=i[14]/(i[10]-1),o=i[14]/(i[10]+1),u=(i[9]+1)/i[5],l=(i[9]-1)/i[5],d=(i[8]-1)/i[0],c=(n[8]+1)/n[0],h=a*d,p=a*c,g=s/(-d+c),m=g*-d;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(g),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===i[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+g,r=o+g,i=h-m,n=p+(s-m),d=u*o/r*t,c=l*o/r*t;e.projectionMatrix.makePerspective(i,n,d,c,t,r),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(i,n,a):i.projectionMatrix.copy(n.projectionMatrix),function(e,t,r){null===r?e.matrix.copy(t.matrixWorld):(e.matrix.copy(r.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*it*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,i,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new st,this._controllers[e]=t),t}}function IN(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function DN(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const r=this._controllers[t];if(void 0!==r){const t=this.getReferenceSpace();r.update(e.inputSource,e.frame,t),r.dispatchEvent({type:e.type,data:e.inputSource})}}function UN(){const e=this._session,t=this._renderer;e.removeEventListener("select",this._onSessionEvent),e.removeEventListener("selectstart",this._onSessionEvent),e.removeEventListener("selectend",this._onSessionEvent),e.removeEventListener("squeeze",this._onSessionEvent),e.removeEventListener("squeezestart",this._onSessionEvent),e.removeEventListener("squeezeend",this._onSessionEvent),e.removeEventListener("end",this._onSessionEnd),e.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){const t=this._controllerInputSources[e];null!==t&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,t._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new BN(e.pixelwidth,e.pixelheight,{format:be,type:Ie,depthTexture:new z(e.pixelwidth,e.pixelheight,e.stencilBuffer?Fe:N,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?Pe:Le),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function VN(e){const t=this._controllers,r=this._controllerInputSources;for(let s=0;s<e.removed.length;s++){const i=e.removed[s],n=r.indexOf(i);n>=0&&(r[n]=null,t[n].disconnect(i))}for(let s=0;s<e.added.length;s++){const i=e.added[s];let n=r.indexOf(i);if(-1===n){for(let e=0;e<t.length;e++){if(e>=r.length){r.push(i),n=e;break}if(null===r[e]){r[e]=i,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(i)}}function ON(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function GN(e,t){if(void 0===t)return;const r=this._cameraXR,s=this._renderer,n=s.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),u=t.getViewerPose(o);if(this._xrFrame=t,null!==u){const e=u.views;null!==this._glBaseLayer&&n.setXRTarget(a.framebuffer);let t=!1;e.length!==r.cameras.length&&(r.cameras.length=0,t=!0);for(let s=0;s<e.length;s++){const o=e[s];let u;if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,o);u=e.viewport,0===s&&n.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else u=a.getViewport(o);let l=this._cameras[s];void 0===l&&(l=new Te,l.layers.enable(s),l.viewport=new i,this._cameras[s]=l),l.matrix.fromArray(o.transform.matrix),l.matrix.decompose(l.position,l.quaternion,l.scale),l.projectionMatrix.fromArray(o.projectionMatrix),l.projectionMatrixInverse.copy(l.projectionMatrix).invert(),l.viewport.set(u.x,u.y,u.width,u.height),0===s&&(r.matrix.copy(l.matrix),r.matrix.decompose(r.position,r.quaternion,r.scale)),!0===t&&r.cameras.push(l)}s.setOutputRenderTarget(this._xrRenderTarget)}for(let e=0;e<this._controllers.length;e++){const r=this._controllerInputSources[e],s=this._controllers[e];null!==r&&void 0!==s&&s.update(r,t,o)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class kN extends u{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new i(0,0,this._width,this._height),this._scissor=new i(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new G,this.depthTexture=new z}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=r,this.domElement.width=Math.floor(e*r),this.domElement.height=Math.floor(t*r),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===r&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,r,s){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,r,s)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,r,s,i=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,r,s),a.minDepth=i,a.maxDepth=n}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const zN=new Z,$N=new r,WN=new i,HN=new ot,jN=new ut,qN=new o,XN=new i;class KN{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:r=!1,alpha:s=!0,depth:i=!0,stencil:n=!1,antialias:a=!1,samples:o=0,getFallback:u=null,colorBufferType:l=ce,multiview:d=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=s,this.logarithmicDepthBuffer=r,this.outputColorSpace=q,this.toneMapping=m,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=i,this.stencil=n,this.info=new Kf,this.overrideNodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new EN,this.lighting=new MN,this._samples=o||!0===a?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new kN(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new nl,this._inspector.setRenderer(this),this._getFallback=u,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new gb(new Bp),this._quad.name="Output Color Transform",this._quad.material.name="outputColorTransform",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const c=!0===this.alpha?0:1;this._clearColor=new by(0,0,0,c),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._colorBufferType=l,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:at},this.xr=new FN(this,d),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,r)=>{await this.compileAsync(e,t);const s=this._renderLists.get(e,t),i=this._renderContexts.get(e,t,this._renderTarget),n=e.overrideMaterial||r.material,a=this._objects.get(r,n,e,t,s.lightsNode,i,i.clippingContext),{fragmentShader:o,vertexShader:u}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:u}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise((async(e,t)=>{let r=this.backend;try{await r.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=r=this._getFallback(e),await r.init(this)}catch(e){return void t(e)}}this._nodes=new _N(this,r),this._animation=new Lf(this,this._nodes,this.info),this._attributes=new Hf(r),this._background=new yv(this,this._nodes),this._geometries=new Xf(this._attributes,this.info),this._textures=new yy(this,r,this.info),this._pipelines=new ty(r,this._nodes),this._bindings=new ry(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Vf(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new uy(this.lighting),this._bundles=new RN,this._renderContexts=new my,this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)}))),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,r=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const s=this._nodes.nodeFrame,i=s.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._compilationPromises,u=!0===e.isScene?e:zN;null===r&&(r=e);const l=this._renderTarget,d=this._renderContexts.get(r,t,l),c=this._activeMipmapLevel,h=[];this._currentRenderContext=d,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=h,s.renderId++,s.update(),d.depth=this.depth,d.stencil=this.stencil,d.clippingContext||(d.clippingContext=new NN),d.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,d.clippingContext),r!==e&&r.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==l){this._textures.updateRenderTarget(l,c);const e=this._textures.get(l);d.textures=e.textures,d.depthTexture=e.depthTexture}else d.textures=null,d.depthTexture=null;this._background.update(u,p,d);const g=p.opaque,m=p.transparent,f=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,u,y),!0===this.transparent&&m.length>0&&this._renderTransparents(m,f,t,u,y),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(h)}async renderAsync(e,t){v('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){e("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=pd,this.overrideNodes.modelNormalViewMatrix=gd):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===pd&&this.overrideNodes.modelNormalViewMatrix===gd}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(t){let r=`THREE.WebGPURenderer: ${t.api} Device Lost:\n\nMessage: ${t.message}`;t.reason&&(r+=`\nReason: ${t.reason}`),e(r),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i),u=this.backend.get(o);void 0===u.renderContexts&&(u.renderContexts=new Set);const l=s.version!==u.version,d=!1===u.renderContexts.has(a)||l;if(u.renderContexts.add(a),d){this.backend.beginBundle(a),(void 0===u.renderObjects||l)&&(u.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:d,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,i,t,r),!0===this.transparent&&d.length>0&&this._renderTransparents(d,e,i,t,r),this._currentRenderBundle=null,this.backend.finishBundle(a,o),u.version=s.version}else{const{renderObjects:e}=u;for(let t=0,r=e.length;t<r;t++){const r=e[t];this._nodes.needsRefresh(r)&&(this._nodes.updateBefore(r),this._nodes.updateForRender(r),this._bindings.updateForRender(r),this._nodes.updateAfter(r))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,r=e!==m,s=t!==p.workingColorSpace;if(!1===r&&!1===s)return null;const{width:i,height:n}=this.getDrawingBufferSize($N),{depth:a,stencil:o}=this;let u=this._frameBufferTarget;null===u&&(u=new me(i,n,{depthBuffer:a,stencilBuffer:o,type:this._colorBufferType,format:be,colorSpace:p.workingColorSpace,generateMipmaps:!1,minFilter:J,magFilter:J,samples:this.samples}),u.isPostProcessingRenderTarget=!0,this._frameBufferTarget=u);const l=this.getOutputRenderTarget();u.depthBuffer=a,u.stencilBuffer=o,null!==l?u.setSize(l.width,l.height,l.depth):u.setSize(i,n,1);const d=this._canvasTarget;return u.viewport.copy(d._viewport),u.scissor.copy(d._scissor),u.viewport.multiplyScalar(d._pixelRatio),u.scissor.multiplyScalar(d._pixelRatio),u.scissorTest=d._scissorTest,u.multiview=null!==l&&l.multiview,u.resolveDepthBuffer=null===l||l.resolveDepthBuffer,u._autoAllocateDepthBuffer=null!==l&&l._autoAllocateDepthBuffer,u}_renderScene(e,t,r=!0){if(!0===this._isDeviceLost)return;const s=r?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,n=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,u=!0===e.isScene?e:zN,l=this._renderTarget||this._outputRenderTarget,d=this._activeCubeFace,c=this._activeMipmapLevel;let h;null!==s?(h=s,this.setRenderTarget(h)):h=l;const p=this._renderContexts.get(e,t,h);this._currentRenderContext=p,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls,this.backend.updateTimeStampUID(p),this.inspector.beginRender(this.backend.getTimestampUID(p),e,t,h);const g=this.coordinateSystem,m=this.xr;if(t.coordinateSystem!==g&&!1===m.isPresenting&&(t.coordinateSystem=g,t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.coordinateSystem=g,e.updateProjectionMatrix();!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===m.enabled&&!0===m.isPresenting&&(!0===m.cameraAutoUpdate&&m.updateCamera(t),t=m.getCamera());const f=this._canvasTarget;let y=f._viewport,b=f._scissor,x=f._pixelRatio;null!==h&&(y=h.viewport,b=h.scissor,x=1),this.getDrawingBufferSize($N),WN.set(0,0,$N.width,$N.height);const T=void 0===y.minDepth?0:y.minDepth,_=void 0===y.maxDepth?1:y.maxDepth;p.viewportValue.copy(y).multiplyScalar(x).floor(),p.viewportValue.width>>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=T,p.viewportValue.maxDepth=_,p.viewport=!1===p.viewportValue.equals(WN),p.scissorValue.copy(b).multiplyScalar(x).floor(),p.scissor=f._scissorTest&&!1===p.scissorValue.equals(WN),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new NN),p.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,h);const v=t.isArrayCamera?jN:HN;t.isArrayCamera||(qN.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(qN,t.coordinateSystem,t.reversedDepth));const N=this._renderLists.get(e,t);if(N.begin(),this._projectObject(e,t,0,N,p.clippingContext),N.finish(),!0===this.sortObjects&&N.sort(this._opaqueSort,this._transparentSort),null!==h){this._textures.updateRenderTarget(h,c);const e=this._textures.get(h);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=h,p.depth=h.depthBuffer,p.stencil=h.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=$N.width,p.height=$N.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=d,p.activeMipmapLevel=c,p.occlusionQueryCount=N.occlusionQueryCount,p.scissorValue.max(XN.set(0,0,0,0)),p.scissorValue.x+p.scissorValue.width>p.width&&(p.scissorValue.width=Math.max(p.width-p.scissorValue.x,0)),p.scissorValue.y+p.scissorValue.height>p.height&&(p.scissorValue.height=Math.max(p.height-p.scissorValue.y,0)),this._background.update(u,N,p),p.camera=t,this.backend.beginRender(p);const{bundles:S,lightsNode:A,transparentDoublePass:R,transparent:E,opaque:w}=N;return S.length>0&&this._renderBundles(S,u,A),!0===this.opaque&&w.length>0&&this._renderObjects(w,t,u,A),!0===this.transparent&&E.length>0&&this._renderTransparents(E,R,t,u,A),this.backend.finishRender(p),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==s&&(this.setRenderTarget(l,d,c),this._renderOutput(h)),u.onAfterRender(this,e,t,h),this.inspector.finishRender(this.backend.getTimestampUID(p)),p}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const r=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=r,this.xr.enabled=s}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,r)}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,r)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,r,s){this._canvasTarget.setScissor(e,t,r,s)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,r,s,i=0,n=1){this._canvasTarget.setViewport(e,t,r,s,i,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const s=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==s){this._textures.updateRenderTarget(s);const e=this._textures.get(s);i=this._renderContexts.getForClear(s),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=s,i.depth=s.depthBuffer,i.stencil=s.stencilBuffer,i.clearColorValue=this.backend.getClearColor(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){v('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,r)}async clearColorAsync(){v('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){v('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){v('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==m,t=this.currentColorSpace!==p.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:m}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:p.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){!0===this._initialized&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach((e=>{null!==e&&e.dispose()}))),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return d("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const r=this._nodes.nodeFrame,s=r.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const i=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,u=Array.isArray(e)?e:[e];if(void 0===u[0]||!0!==u[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const r of u){if(!1===n.has(r)){const e=()=>{r.removeEventListener("dispose",e),n.delete(r),a.deleteForCompute(r),o.delete(r)};r.addEventListener("dispose",e);const t=r.onInitFunction;null!==t&&t.call(r,{renderer:this})}o.updateForCompute(r),a.updateForCompute(r);const s=a.getForCompute(r),u=n.getForCompute(r,s);i.compute(e,r,s,u,t)}i.finishCompute(e),r.renderId=s,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return v('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){v('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}copyFramebufferToTexture(t,r=null){if(null!==r)if(r.isVector2)r=XN.set(r.x,r.y,t.image.width,t.image.height).floor();else{if(!r.isVector4)return void e("Renderer.copyFramebufferToTexture: Invalid rectangle.");r=XN.copy(r).floor()}else r=XN.set(0,0,t.image.width,t.image.height);let s,i=this._currentRenderContext;null!==i?s=i.renderTarget:(s=this._renderTarget||this._getFrameBufferTarget(),null!==s&&(this._textures.updateRenderTarget(s),i=this._textures.get(s))),this._textures.updateTexture(t,{renderTarget:s}),this.backend.copyFramebufferToTexture(t,i,r),this._inspector.copyFramebufferToTexture(t)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,r,s,i,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,r,s,i,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,r,s,i,a)}_projectObject(t,r,s,i,n){if(!1===t.visible)return;if(t.layers.test(r.layers))if(t.isGroup)s=t.renderOrder,t.isClippingGroup&&t.enabled&&(n=n.getGroupContext(t));else if(t.isLOD)!0===t.autoUpdate&&t.update(r);else if(t.isLight)i.pushLight(t);else if(t.isSprite){const e=r.isArrayCamera?jN:HN;if(!t.frustumCulled||e.intersectsSprite(t,r)){!0===this.sortObjects&&XN.setFromMatrixPosition(t.matrixWorld).applyMatrix4(qN);const{geometry:e,material:r}=t;r.visible&&i.push(t,e,r,s,XN.z,null,n)}}else if(t.isLineLoop)e("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(t.isMesh||t.isLine||t.isPoints){const e=r.isArrayCamera?jN:HN;if(!t.frustumCulled||e.intersectsObject(t,r)){const{geometry:e,material:r}=t;if(!0===this.sortObjects&&(null===e.boundingSphere&&e.computeBoundingSphere(),XN.copy(e.boundingSphere.center).applyMatrix4(t.matrixWorld).applyMatrix4(qN)),Array.isArray(r)){const a=e.groups;for(let o=0,u=a.length;o<u;o++){const u=a[o],l=r[u.materialIndex];l&&l.visible&&i.push(t,e,l,s,XN.z,u,n)}}else r.visible&&i.push(t,e,r,s,XN.z,null,n)}}if(!0===t.isBundleGroup&&void 0!==this.backend.beginBundle){const e=i;(i=this._renderLists.get(t,r)).begin(),e.pushBundle({bundleGroup:t,camera:r,renderList:i}),i.finish()}const a=t.children;for(let e=0,t=a.length;e<t;e++)this._projectObject(a[e],r,s,i,n)}_renderBundles(e,t,r){for(const s of e)this._renderBundle(s,t,r)}_renderTransparents(e,t,r,s,i){if(t.length>0){for(const{material:e}of t)e.side=w;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=Ze;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=C}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n<a;n++){const{object:a,geometry:o,material:u,group:l,clippingContext:d}=e[n];this._currentRenderObjectFunction(a,r,t,o,u,l,s,d,i)}}_getShadowNodes(e){const t=e.version;let r=this._cacheShadowNodes.get(e);if(void 0===r||r.version!==t){const s=null!==e.map,i=e.colorNode&&e.colorNode.isNode,n=e.castShadowNode&&e.castShadowNode.isNode;let a=null,o=null,u=null;if(s||i||n){let t,r;n?(t=e.castShadowNode.rgb,r=e.castShadowNode.a):(t=cn(0),r=rn(1)),s&&(r=r.mul(ec("map","texture",e).a)),i&&(r=r.mul(e.colorNode.a)),o=mn(t,r)}e.depthNode&&e.depthNode.isNode&&(u=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?a=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(a=e.positionNode),r={version:t,colorNode:o,depthNode:u,positionNode:a},this._cacheShadowNodes.set(e,r)}return r}renderObject(e,t,r,s,i,n,a,o=null,u=null){let l,d,c,h,p=!1;if(e.onBeforeRender(this,t,r,s,i,n),!0===i.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,l=t.overrideMaterial.colorNode,d=t.overrideMaterial.depthNode,c=t.overrideMaterial.positionNode,h=t.overrideMaterial.side,i.positionNode&&i.positionNode.isNode&&(e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.transparent=i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:r,positionNode:s}=this._getShadowNodes(i);e.side=null===i.shadowSide?i.side:i.shadowSide,null!==t&&(e.colorNode=t),null!==r&&(e.depthNode=r),null!==s&&(e.positionNode=s)}i=e}!0===i.transparent&&i.side===C&&!1===i.forceSinglePass?(i.side=w,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=Ze,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=C):this._handleObjectFunction(e,i,t,r,a,n,o,u),p&&(t.overrideMaterial.colorNode=l,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=h),e.onAfterRender(this,t,r,s,i,n)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n;const l=this._nodes.needsRefresh(u);if(l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u)}_createObjectPipeline(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n,this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u),this._pipelines.getForRender(u,this._compilationPromises),this._nodes.updateAfter(u)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class YN{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class QN extends YN{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(Wf-e%Wf)%Wf;var e}get buffer(){return this._buffer}update(){return!0}}class ZN extends QN{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let JN=0;class eS extends ZN{constructor(e,t){super("UniformBuffer_"+JN++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class tS extends ZN{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r<s;r++){const s=this.uniforms[r],i=s.boundary,n=s.itemSize*e,a=t%Wf,o=a%i,u=a+o;t+=o,0!==u&&Wf-u<n&&(t+=Wf-u),s.offset=t/e,t+=n}return Math.ceil(t/Wf)*Wf}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}updateByType(t){return t.isNumberUniform?this.updateNumber(t):t.isVector2Uniform?this.updateVector2(t):t.isVector3Uniform?this.updateVector3(t):t.isVector4Uniform?this.updateVector4(t):t.isColorUniform?this.updateColor(t):t.isMatrix3Uniform?this.updateMatrix3(t):t.isMatrix4Uniform?this.updateMatrix4(t):void e("WebGPUUniformsGroup: Unsupported uniform type.",t)}updateNumber(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset,n=e.getType();if(r[i]!==s){this._getBufferForType(n)[i]=r[i]=s,t=!0}return t}updateVector2(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset,n=e.getType();if(r[i+0]!==s.x||r[i+1]!==s.y){const e=this._getBufferForType(n);e[i+0]=r[i+0]=s.x,e[i+1]=r[i+1]=s.y,t=!0}return t}updateVector3(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset,n=e.getType();if(r[i+0]!==s.x||r[i+1]!==s.y||r[i+2]!==s.z){const e=this._getBufferForType(n);e[i+0]=r[i+0]=s.x,e[i+1]=r[i+1]=s.y,e[i+2]=r[i+2]=s.z,t=!0}return t}updateVector4(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset,n=e.getType();if(r[i+0]!==s.x||r[i+1]!==s.y||r[i+2]!==s.z||r[i+4]!==s.w){const e=this._getBufferForType(n);e[i+0]=r[i+0]=s.x,e[i+1]=r[i+1]=s.y,e[i+2]=r[i+2]=s.z,e[i+3]=r[i+3]=s.w,t=!0}return t}updateColor(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset;if(r[i+0]!==s.r||r[i+1]!==s.g||r[i+2]!==s.b){const e=this.buffer;e[i+0]=r[i+0]=s.r,e[i+1]=r[i+1]=s.g,e[i+2]=r[i+2]=s.b,t=!0}return t}updateMatrix3(e){let t=!1;const r=this.values,s=e.getValue().elements,i=e.offset;if(r[i+0]!==s[0]||r[i+1]!==s[1]||r[i+2]!==s[2]||r[i+4]!==s[3]||r[i+5]!==s[4]||r[i+6]!==s[5]||r[i+8]!==s[6]||r[i+9]!==s[7]||r[i+10]!==s[8]){const e=this.buffer;e[i+0]=r[i+0]=s[0],e[i+1]=r[i+1]=s[1],e[i+2]=r[i+2]=s[2],e[i+4]=r[i+4]=s[3],e[i+5]=r[i+5]=s[4],e[i+6]=r[i+6]=s[5],e[i+8]=r[i+8]=s[6],e[i+9]=r[i+9]=s[7],e[i+10]=r[i+10]=s[8],t=!0}return t}updateMatrix4(e){let t=!1;const r=this.values,s=e.getValue().elements,i=e.offset;if(!1===function(e,t,r){for(let s=0,i=t.length;s<i;s++)if(e[r+s]!==t[s])return!1;return!0}(r,s,i)){this.buffer.set(s,i),function(e,t,r){for(let s=0,i=t.length;s<i;s++)e[r+s]=t[s]}(r,s,i),t=!0}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let rS=0;class sS extends tS{constructor(e,t){super(e),this.id=rS++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class iS extends YN{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=0},this.texture=t,this.version=t?t.version:0,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=0,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=0},e.texture=this.texture,e}}let nS=0;class aS extends iS{constructor(e,t){super(e,t),this.id=nS++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class oS extends aS{constructor(e,t,r,s=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r,this.access=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class uS extends oS{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledCubeTexture=!0}}class lS extends oS{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledTexture3D=!0}}const dS={bitcast_int_uint:new mx("uint tsl_bitcast_uint_to_int ( int x ) { return floatBitsToInt( uintBitsToFloat( x ) ); }"),bitcast_uint_int:new mx("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }")},cS={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint"},hS={low:"lowp",medium:"mediump",high:"highp"},pS={swizzleAssign:!0,storageBuffer:!1},gS={perspective:"smooth",linear:"noperspective"},mS={centroid:"centroid"},fS="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision lowp sampler2DShadow;\nprecision lowp sampler2DArrayShadow;\nprecision lowp samplerCubeShadow;\n";class yS extends Yv{constructor(e,t){super(e,t,new yN),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==T}_include(e){const t=dS[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==dS[e]&&this._include(e),cS[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getTernary(e,t,r){return`${e} ? ${t} : ${r}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${s.join(", ")} ) {\n\n\t${r.vars}\n\n${r.code}\n\treturn ${r.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,r=t.count*t.itemSize,{itemSize:s}=t,i=t.array.constructor.name.toLowerCase().includes("int");let n=i?lt:dt;2===s?n=i?ct:de:3===s?n=i?ht:pt:4===s&&(n=i?gt:be);const a={Float32Array:O,Uint8Array:Ie,Uint16Array:mt,Uint32Array:N,Int8Array:ft,Int16Array:yt,Int32Array:S,Uint8ClampedArray:Ie},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(r/s))));let u=Math.ceil(r/s/o);o*u*s<r&&u++;const l=o*u*s,d=new e.constructor(l);d.set(e,0),t.array=d;const c=new le(t.array,o,u,n,a[t.array.constructor.name]||O);c.needsUpdate=!0,c.isPBOTexture=!0;const h=new fl(c,null,null);h.setPrecision("high"),t.pboNode=h,t.pbo=h.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?t.charAt(0)+"_"+e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:r}=e,s=t.value;if(this.renderer.backend.has(s)){this.renderer.backend.get(s).pbo=s.pbo}const i=this.getUniformFromNode(s.pboNode,"texture",this.shaderStage,this.context.nodeName),n=this.getPropertyName(i);this.increaseUsage(r);const a=r.build(this,"uint"),o=this.getDataFromNode(e);let u=o.propertyName;if(void 0===u){const r=this.getVarFromNode(e);u=this.getPropertyName(r);const i=this.getDataFromNode(t);let l=i.propertySizeName;void 0===l&&(l=u+"Size",this.getVarFromNode(t,l,"uint"),this.addLineFlowCode(`${l} = uint( textureSize( ${n}, 0 ).x )`,e),i.propertySizeName=l);const{itemSize:d}=s,c="."+Xs.join("").slice(0,d),h=`ivec2(${a} % ${l}, ${a} / ${l})`,p=this.generateTextureLoad(null,n,h,"0",null,null);let g="vec4";s.pbo.type===N?g="uvec4":s.pbo.type===S&&(g="ivec4"),this.addLineFlowCode(`${u} = ${g}(${p})${c}`,e),o.propertyName=u}return u}generateTextureLoad(e,t,r,s,i,n){let a;return null===s&&(s="0"),a=i?n?`texelFetchOffset( ${t}, ivec3( ${r}, ${i} ), ${s}, ${n} )`:`texelFetch( ${t}, ivec3( ${r}, ${i} ), ${s} )`:n?`texelFetchOffset( ${t}, ${r}, ${s}, ${n} )`:`texelFetch( ${t}, ${r}, ${s} )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,r,s,i){return s&&(r=`vec3( ${r}, ${s} )`),e.isDepthTexture?i?`textureOffset( ${t}, ${r}, ${i} ).x`:`texture( ${t}, ${r} ).x`:i?`textureOffset( ${t}, ${r}, ${i} )`:`texture( ${t}, ${r} )`}generateTextureLevel(e,t,r,s,i){return i?`textureLodOffset( ${t}, ${r}, ${s}, ${i} )`:`textureLod( ${t}, ${r}, ${s} )`}generateTextureBias(e,t,r,s,i){return i?`textureOffset( ${t}, ${r}, ${i}, ${s} )`:`texture( ${t}, ${r}, ${s} )`}generateTextureGrad(e,t,r,s,i){return i?`textureGradOffset( ${t}, ${r}, ${s[0]}, ${s[1]}, ${i} )`:`textureGrad( ${t}, ${r}, ${s[0]}, ${s[1]} )`}generateTextureCompare(t,r,s,i,n,a,o=this.shaderStage){if("fragment"===o)return n?a?`textureOffset( ${r}, vec4( ${s}, ${n}, ${i} ), ${a} )`:`texture( ${r}, vec4( ${s}, ${n}, ${i} ) )`:a?`textureOffset( ${r}, vec3( ${s}, ${i} ), ${a} )`:`texture( ${r}, vec3( ${s}, ${i} ) )`;e(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}getVars(e){const t=[],r=this.vars[e];if(void 0!==r)for(const e of r)t.push(`${this.getVar(e.type,e.name,e.count)};`);return t.join("\n\t")}getUniforms(e){const t=this.uniforms[e],r=[],s={};for(const i of t){let t=null,n=!1;if("texture"===i.type||"texture3D"===i.type){const e=i.node.value;let r="";!0!==e.isDataTexture&&!0!==e.isData3DTexture||(e.type===N?r="u":e.type===S&&(r="i")),t="texture3D"===i.type&&!1===e.isArrayTexture?`${r}sampler3D ${i.name};`:e.compareFunction?!0===e.isArrayTexture?`sampler2DArrayShadow ${i.name};`:`sampler2DShadow ${i.name};`:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?`${r}sampler2DArray ${i.name};`:`${r}sampler2D ${i.name};`}else if("cubeTexture"===i.type)t=`samplerCube ${i.name};`;else if("buffer"===i.type){const e=i.node,r=this.getType(e.bufferType),s=e.bufferCount,n=s>0?s:"";t=`${e.name} {\n\t${r} ${i.name}[${n}];\n};\n`}else{t=`${this.getVectorType(i.type)} ${this.getPropertyName(i,e)};`,n=!0}const a=i.node.precision;if(null!==a&&(t=hS[a]+" "+t),n){t="\t"+t;const e=i.groupNode.name;(s[e]||(s[e]=[])).push(t)}else t="uniform "+t,r.push(t)}let i="";for(const t in s){const r=s[t];i+=this._getGLSLUniformStruct(e+"_"+t,r.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==S){let r=e;e.isInterleavedBufferAttribute&&(r=e.data);const s=r.array;!1==(s instanceof Uint32Array||s instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let r=0;for(const s of e)t+=`layout( location = ${r++} ) in ${s.type} ${s.name};\n`}return t}getStructMembers(e){const t=[];for(const r of e.members)t.push(`\t${r.type} ${r.name};`);return t.join("\n")}getStructs(e){const t=[],r=this.structs[e],s=[];for(const e of r)if(e.output)for(const t of e.members)s.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let r="struct "+e.name+" {\n";r+=this.getStructMembers(e),r+="\n};\n",t.push(r)}return 0===s.length&&s.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+s.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const r=this.varyings;if("vertex"===e||"compute"===e)for(const s of r){"compute"===e&&(s.needsInterpolation=!0);const r=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){t+=`${gS[s.interpolationType]||s.interpolationType} ${mS[s.interpolationSampling]||""} out ${r} ${s.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}out ${r} ${s.name};\n`}else t+=`${r} ${s.name};\n`}else if("fragment"===e)for(const e of r)if(e.needsInterpolation){const r=this.getType(e.type);if(e.interpolationType){t+=`${gS[e.interpolationType]||e.interpolationType} ${mS[e.interpolationSampling]||""} in ${r} ${e.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}in ${r} ${e.name};\n`}}for(const r of this.builtins[e])t+=`${r};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce(((e,t)=>e*t),1)}u`}getSubgroupSize(){e("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){e("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){e("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,r=this.shaderStage){const s=this.extensions[r]||(this.extensions[r]=new Map);!1===s.has(e)&&s.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const r=this.extensions[e];if(void 0!==r)for(const{name:e,behavior:s}of r.values())t.push(`#extension ${e} : ${s}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=pS[e];if(void 0===t){let r;switch(t=!1,e){case"float32Filterable":r="OES_texture_float_linear";break;case"clipDistance":r="WEBGL_clip_cull_distance"}if(void 0!==r){const e=this.renderer.backend.extensions;e.has(r)&&(e.get(r),t=!0)}pS[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let r=0;r<e.length;r++){const s=e[r],i=this.getPropertyName(s.attributeNode);i&&(t+=`${s.varyingName} = ${i};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${fS}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${fS}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let r="// code\n\n";r+=this.flowCode[t];const s=this.flowNodes[t],i=s[s.length-1];for(const e of s){const s=this.getFlowData(e),n=e.name;n&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${n}\n\t`),r+=`${s.code}\n\t`,e===i&&"compute"!==t&&(r+="// result\n\t","vertex"===t?(r+="gl_Position = ",r+=`${s.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(r+="fragColor = ",r+=`${s.result};`)))}const n=e[t];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);let a=n.uniformGPU;if(void 0===a){const s=e.groupNode,o=s.name,u=this.getBindGroupArray(o,r);if("texture"===t)a=new oS(i.name,i.node,s),u.push(a);else if("cubeTexture"===t)a=new uS(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new lS(i.name,i.node,s),u.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new eS(e,s);t.name=e.name,u.push(t),a=t}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let n=e[o];void 0===n&&(n=new sS(r+"_"+o,s),e[o]=n,u.push(n)),a=this.getNodeUniform(i,t),n.addUniform(a)}n.uniformGPU=a}return i}}let bS=null,xS=null;class TS{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[bt.RENDER]:null,[bt.COMPUTE]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),r=this.renderer.info.frame;let s;s=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=s+":"+e.id+":f"+r}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?bt.COMPUTE:bt.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void v("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return bS=bS||new r,this.renderer.getDrawingBufferSize(bS)}setScissorTest(){}getClearColor(){const e=this.renderer;return xS=xS||new by,e.getClearColor(xS),xS.getRGB(xS),xS}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:xt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Ke} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let _S,vS,NS=0;class SS{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class AS{constructor(e){this.backend=e}createAttribute(e,t){const r=this.backend,{gl:s}=r,i=e.array,n=e.usage||s.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a);let u,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(s,t,i,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),i instanceof Float32Array)u=s.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)u=s.HALF_FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?s.HALF_FLOAT:s.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=s.SHORT;else if(i instanceof Uint32Array)u=s.UNSIGNED_INT;else if(i instanceof Int32Array)u=s.INT;else if(i instanceof Int8Array)u=s.BYTE;else if(i instanceof Uint8Array)u=s.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=s.UNSIGNED_BYTE}let d={bufferGPU:l,bufferType:t,type:u,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===s.INT||u===s.UNSIGNED_INT||e.gpuType===S,id:NS++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new SS(d,e)}r.set(e,d)}updateAttribute(e){const t=this.backend,{gl:r}=t,s=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(r.bindBuffer(a,n.bufferGPU),0===o.length)r.bufferSubData(a,0,s);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];r.bufferSubData(a,t.start*s.BYTES_PER_ELEMENT,s,t.start,t.count)}i.clearUpdateRanges()}r.bindBuffer(a,null),n.version=i.version}destroyAttribute(e){const t=this.backend,{gl:r}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const s=t.get(e);r.deleteBuffer(s.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:r}=t,s=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:i}=t.get(s),n=e.array,a=n.byteLength;r.bindBuffer(r.COPY_READ_BUFFER,i);const o=r.createBuffer();r.bindBuffer(r.COPY_WRITE_BUFFER,o),r.bufferData(r.COPY_WRITE_BUFFER,a,r.STREAM_READ),r.copyBufferSubData(r.COPY_READ_BUFFER,r.COPY_WRITE_BUFFER,0,0,a),await t.utils._clientWaitAsync();const u=new e.array.constructor(n.length);return r.bindBuffer(r.COPY_WRITE_BUFFER,o),r.getBufferSubData(r.COPY_WRITE_BUFFER,0,u),r.deleteBuffer(o),r.bindBuffer(r.COPY_READ_BUFFER,null),r.bindBuffer(r.COPY_WRITE_BUFFER,null),u.buffer}_createBuffer(e,t,r,s){const i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,r,s),e.bindBuffer(t,null),i}}class RS{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;_S={[et]:e.FUNC_ADD,[Tt]:e.FUNC_SUBTRACT,[_t]:e.FUNC_REVERSE_SUBTRACT},vS={[tt]:e.ZERO,[vt]:e.ONE,[Nt]:e.SRC_COLOR,[St]:e.SRC_ALPHA,[At]:e.SRC_ALPHA_SATURATE,[Rt]:e.DST_COLOR,[Et]:e.DST_ALPHA,[wt]:e.ONE_MINUS_SRC_COLOR,[Ct]:e.ONE_MINUS_SRC_ALPHA,[Mt]:e.ONE_MINUS_DST_COLOR,[Bt]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),r=e.getParameter(e.VIEWPORT);this.currentScissor=(new i).fromArray(t),this.currentViewport=(new i).fromArray(r),this._tempVec4=new i}enable(e){const{enabled:t}=this;!0!==t[e]&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;!1!==t[e]&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;e!==Pt?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===Lt?t.cullFace(t.BACK):e===Ft?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:r}=this;e!==t&&(r.lineWidth(e),this.currentLineWidth=e)}setBlending(t,r,s,i,n,a,o,u){const{gl:l}=this;if(t!==j){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),t===Je)n=n||r,a=a||s,o=o||i,r===this.currentBlendEquation&&n===this.currentBlendEquationAlpha||(l.blendEquationSeparate(_S[r],_S[n]),this.currentBlendEquation=r,this.currentBlendEquationAlpha=n),s===this.currentBlendSrc&&i===this.currentBlendDst&&a===this.currentBlendSrcAlpha&&o===this.currentBlendDstAlpha||(l.blendFuncSeparate(vS[s],vS[i],vS[a],vS[o]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=a,this.currentBlendDstAlpha=o),this.currentBlending=t,this.currentPremultipledAlpha=!1;else if(t!==this.currentBlending||u!==this.currentPremultipledAlpha){if(this.currentBlendEquation===et&&this.currentBlendEquationAlpha===et||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=et,this.currentBlendEquationAlpha=et),u)switch(t){case He:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case Ut:l.blendFunc(l.ONE,l.ONE);break;case Dt:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case It:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:e("WebGLState: Invalid blending: ",t)}else switch(t){case He:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case Ut:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case Dt:e("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case It:e("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:e("WebGLState: Invalid blending: ",t)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=t,this.currentPremultipledAlpha=u}}else!0===this.currentBlendingEnabled&&(this.disable(l.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case Ht:t.depthFunc(t.NEVER);break;case Wt:t.depthFunc(t.ALWAYS);break;case $t:t.depthFunc(t.LESS);break;case zt:t.depthFunc(t.LEQUAL);break;case kt:t.depthFunc(t.EQUAL);break;case Gt:t.depthFunc(t.GEQUAL);break;case Ot:t.depthFunc(t.GREATER);break;case Vt:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,r,s){const i=this._tempVec4.set(e,t,r,s);if(!1===this.currentScissor.equals(i)){const{gl:e}=this;e.scissor(i.x,i.y,i.z,i.w),this.currentScissor.copy(i)}}viewport(e,t,r,s){const i=this._tempVec4.set(e,t,r,s);if(!1===this.currentViewport.equals(i)){const{gl:e}=this;e.viewport(i.x,i.y,i.z,i.w),this.currentViewport.copy(i)}}setScissorTest(e){const t=this.gl;e?t.enable(t.SCISSOR_TEST):t.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,r){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===r||(this.gl.stencilFunc(e,t,r),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=r)}setStencilOp(e,t,r){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===r||(this.gl.stencilOp(e,t,r),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=r)}setMaterial(e,t,r){const{gl:s}=this;e.side===C?this.disable(s.CULL_FACE):this.enable(s.CULL_FACE);let i=e.side===w;t&&(i=!i),this.setFlipSided(i),e.blending===He&&!1===e.transparent?this.setBlending(j):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const n=e.stencilWrite;if(this.setStencilTest(n),n&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage&&this.backend.renderer.currentSamples>0?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE),r>0&&this.currentClippingPlanes!==r){const e=12288;for(let t=0;t<8;t++)t<r?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,r){const{gl:s}=this;e?(this.enable(s.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===r||(s.polygonOffset(t,r),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=r)):this.disable(s.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const r=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(r.bindVertexArray(e),null!==t&&r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0)}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:r,currentBoundFramebuffers:s}=this;return s[e]!==t&&(r.bindFramebuffer(e,t),s[e]=t,e===r.DRAW_FRAMEBUFFER&&(s[r.FRAMEBUFFER]=t),e===r.FRAMEBUFFER&&(s[r.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:r}=this;let s=[],i=!1;if(null!==e.textures){s=this.currentDrawbuffers.get(t),void 0===s&&(s=[],this.currentDrawbuffers.set(t,s));const n=e.textures;if(s.length!==n.length||s[0]!==r.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e<t;e++)s[e]=r.COLOR_ATTACHMENT0+e;s.length=n.length,i=!0}}else s[0]!==r.BACK&&(s[0]=r.BACK,i=!0);i&&r.drawBuffers(s)}activeTexture(e){const{gl:t,currentTextureSlot:r,maxTextures:s}=this;void 0===e&&(e=t.TEXTURE0+s-1),r!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,r){const{gl:s,currentTextureSlot:i,currentBoundTextures:n,maxTextures:a}=this;void 0===r&&(r=null===i?s.TEXTURE0+a-1:i);let o=n[r];void 0===o&&(o={type:void 0,texture:void 0},n[r]=o),o.type===e&&o.texture===t||(i!==r&&(s.activeTexture(r),this.currentTextureSlot=r),s.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,r){const{gl:s}=this,i=`${e}-${t}`;return this.currentBoundBufferBases[i]!==r&&(s.bindBufferBase(e,t,r),this.currentBoundBufferBases[i]=r,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:r}=this,s=r[t];void 0!==s&&void 0!==s.type&&(e.bindTexture(s.type,null),s.type=void 0,s.texture=void 0)}}class ES{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=T){const{gl:r,extensions:s}=this;let i;const n=p.getTransfer(t);if(e===Ie)return r.UNSIGNED_BYTE;if(e===jt)return r.UNSIGNED_SHORT_4_4_4_4;if(e===qt)return r.UNSIGNED_SHORT_5_5_5_1;if(e===Xt)return r.UNSIGNED_INT_5_9_9_9_REV;if(e===Kt)return r.UNSIGNED_INT_10F_11F_11F_REV;if(e===ft)return r.BYTE;if(e===yt)return r.SHORT;if(e===mt)return r.UNSIGNED_SHORT;if(e===S)return r.INT;if(e===N)return r.UNSIGNED_INT;if(e===O)return r.FLOAT;if(e===ce)return r.HALF_FLOAT;if(e===Yt)return r.ALPHA;if(e===pt)return r.RGB;if(e===be)return r.RGBA;if(e===Le)return r.DEPTH_COMPONENT;if(e===Pe)return r.DEPTH_STENCIL;if(e===dt)return r.RED;if(e===lt)return r.RED_INTEGER;if(e===de)return r.RG;if(e===ct)return r.RG_INTEGER;if(e===gt)return r.RGBA_INTEGER;if(e===Qt||e===Zt||e===Jt||e===er)if(n===g){if(i=s.get("WEBGL_compressed_texture_s3tc_srgb"),null===i)return null;if(e===Qt)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Zt)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Jt)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===er)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(i=s.get("WEBGL_compressed_texture_s3tc"),null===i)return null;if(e===Qt)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Zt)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Jt)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===er)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===tr||e===rr||e===sr||e===ir){if(i=s.get("WEBGL_compressed_texture_pvrtc"),null===i)return null;if(e===tr)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===rr)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===sr)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===ir)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===nr||e===ar||e===or){if(i=s.get("WEBGL_compressed_texture_etc"),null===i)return null;if(e===nr||e===ar)return n===g?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(e===or)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC}if(e===ur||e===lr||e===dr||e===cr||e===hr||e===pr||e===gr||e===mr||e===fr||e===yr||e===br||e===xr||e===Tr||e===_r){if(i=s.get("WEBGL_compressed_texture_astc"),null===i)return null;if(e===ur)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===lr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===dr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===cr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===hr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===pr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===gr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===mr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===fr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===yr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===br)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===xr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Tr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===_r)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===vr){if(i=s.get("EXT_texture_compression_bptc"),null===i)return null;if(e===vr)return n===g?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===Nr||e===Sr||e===Ar||e===Rr){if(i=s.get("EXT_texture_compression_rgtc"),null===i)return null;if(e===Nr)return i.COMPRESSED_RED_RGTC1_EXT;if(e===Sr)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===Ar)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Rr)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===Fe?r.UNSIGNED_INT_24_8:void 0!==r[e]?r[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise(((r,s)=>{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void s();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),r()):requestAnimationFrame(i)}()}))}}let wS,CS,MS,BS=!1;class PS{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===BS&&(this._init(),BS=!0)}_init(){const e=this.gl;wS={[Er]:e.REPEAT,[he]:e.CLAMP_TO_EDGE,[wr]:e.MIRRORED_REPEAT},CS={[A]:e.NEAREST,[Cr]:e.NEAREST_MIPMAP_NEAREST,[qe]:e.NEAREST_MIPMAP_LINEAR,[J]:e.LINEAR,[je]:e.LINEAR_MIPMAP_NEAREST,[k]:e.LINEAR_MIPMAP_LINEAR},MS={[Mr]:e.NEVER,[Br]:e.ALWAYS,[ze]:e.LESS,[Pr]:e.LEQUAL,[Lr]:e.EQUAL,[Fr]:e.GEQUAL,[Ir]:e.GREATER,[Dr]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let r;return r=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,r}getInternalFormat(e,t,r,s,i=!1){const{gl:n,extensions:a}=this;if(null!==e){if(void 0!==n[e])return n[e];d("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===n.RED&&(r===n.FLOAT&&(o=n.R32F),r===n.HALF_FLOAT&&(o=n.R16F),r===n.UNSIGNED_BYTE&&(o=n.R8),r===n.UNSIGNED_SHORT&&(o=n.R16),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RED_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.R8UI),r===n.UNSIGNED_SHORT&&(o=n.R16UI),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RG&&(r===n.FLOAT&&(o=n.RG32F),r===n.HALF_FLOAT&&(o=n.RG16F),r===n.UNSIGNED_BYTE&&(o=n.RG8),r===n.UNSIGNED_SHORT&&(o=n.RG16),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RG_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RG8UI),r===n.UNSIGNED_SHORT&&(o=n.RG16UI),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RGB){const e=i?Ur:p.getTransfer(s);r===n.FLOAT&&(o=n.RGB32F),r===n.HALF_FLOAT&&(o=n.RGB16F),r===n.UNSIGNED_BYTE&&(o=n.RGB8),r===n.UNSIGNED_SHORT&&(o=n.RGB16),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I),r===n.UNSIGNED_BYTE&&(o=e===g?n.SRGB8:n.RGB8),r===n.UNSIGNED_SHORT_5_6_5&&(o=n.RGB565),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGB4),r===n.UNSIGNED_INT_5_9_9_9_REV&&(o=n.RGB9_E5),r===n.UNSIGNED_INT_10F_11F_11F_REV&&(o=n.R11F_G11F_B10F)}if(t===n.RGB_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGB8UI),r===n.UNSIGNED_SHORT&&(o=n.RGB16UI),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I)),t===n.RGBA){const e=i?Ur:p.getTransfer(s);r===n.FLOAT&&(o=n.RGBA32F),r===n.HALF_FLOAT&&(o=n.RGBA16F),r===n.UNSIGNED_BYTE&&(o=n.RGBA8),r===n.UNSIGNED_SHORT&&(o=n.RGBA16),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I),r===n.UNSIGNED_BYTE&&(o=e===g?n.SRGB8_ALPHA8:n.RGBA8),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGBA4),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGBA8UI),r===n.UNSIGNED_SHORT&&(o=n.RGBA16UI),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(r===n.UNSIGNED_SHORT&&(o=n.DEPTH_COMPONENT16),r===n.UNSIGNED_INT&&(o=n.DEPTH_COMPONENT24),r===n.FLOAT&&(o=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&r===n.UNSIGNED_INT_24_8&&(o=n.DEPTH24_STENCIL8),o!==n.R16F&&o!==n.R32F&&o!==n.RG16F&&o!==n.RG32F&&o!==n.RGBA16F&&o!==n.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,n=p.getPrimaries(p.workingColorSpace),a=t.colorSpace===T?null:p.getPrimaries(t.colorSpace),o=t.colorSpace===T||n===a?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),r.texParameteri(e,r.TEXTURE_WRAP_S,wS[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,wS[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,wS[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,CS[t.magFilter]);const u=void 0!==t.mipmaps&&t.mipmaps.length>0,l=t.minFilter===J&&u?k:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,CS[l]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,MS[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===A)return;if(t.minFilter!==qe&&t.minFilter!==k)return;if(t.type===O&&!1===s.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=s.get("EXT_texture_filter_anisotropic");r.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:r,defaultTextures:s}=this,i=this.getGLTextureType(e);let n=s[i];void 0===n&&(n=t.createTexture(),r.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),s[i]=n),r.set(e,{textureGPU:n,glTextureType:i})}createTexture(e,t){const{gl:r,backend:s}=this,{levels:i,width:n,height:a,depth:o}=t,u=s.utils.convert(e.format,e.colorSpace),l=s.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,u,l,e.colorSpace,e.isVideoTexture),c=r.createTexture(),h=this.getGLTextureType(e);s.state.bindTexture(h,c),this.setTextureParameters(h,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?r.texStorage3D(r.TEXTURE_2D_ARRAY,i,d,n,a,o):e.isData3DTexture?r.texStorage3D(r.TEXTURE_3D,i,d,n,a,o):e.isVideoTexture||r.texStorage2D(h,i,d,n,a),s.set(e,{textureGPU:c,glTextureType:h,glFormat:u,glType:l,glInternalFormat:d})}copyBufferToTexture(e,t){const{gl:r,backend:s}=this,{textureGPU:i,glTextureType:n,glFormat:a,glType:o}=s.get(t),{width:u,height:l}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(n,i),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(n,0,0,0,u,l,a,o,0),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),s.state.unbindTexture()}updateTexture(e,t){const{gl:r}=this,{width:s,height:i}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:u,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const s=e.mipmaps,i=t.image;for(let t=0;t<s.length;t++){const n=s[t];e.isCompressedArrayTexture?e.format!==r.RGBA?null!==o?r.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,i.depth,o,n.data):d("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):r.texSubImage3D(r.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,i.depth,o,u,n.data):null!==o?r.compressedTexSubImage2D(r.TEXTURE_2D,t,0,0,n.width,n.height,o,n.data):d("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const n=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=LS(n[e]);r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,s,i,o,u,t);for(let t=0;t<a.length;t++){const s=LS(a[t].images[e]);r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,s.width,s.height,o,u,s)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const s=t.image;if(e.layerUpdates.size>0){const t=Vr(s.width,s.height,e.format,e.type);for(const i of e.layerUpdates){const e=s.data.subarray(i*t/s.data.BYTES_PER_ELEMENT,(i+1)*t/s.data.BYTES_PER_ELEMENT);r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,i,s.width,s.height,1,o,u,e)}e.clearLayerUpdates()}else r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,s.width,s.height,s.depth,o,u,s.data)}else if(e.isData3DTexture){const e=t.image;r.texSubImage3D(r.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,u,e.data)}else if(e.isVideoTexture)e.update(),r.texImage2D(a,0,l,o,u,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e<t;e++){const t=n[e],s=LS(t);r.texSubImage2D(a,e,0,0,t.width,t.height,o,u,s)}else{const e=LS(t.image);r.texSubImage2D(a,0,0,0,s,i,o,u,e)}}}generateMipmaps(e){const{gl:t,backend:r}=this,{textureGPU:s,glTextureType:i}=r.get(e);r.state.bindTexture(i,s),t.generateMipmap(i)}deallocateRenderBuffers(e){const{gl:t,backend:r}=this;if(e){const s=r.get(e);if(s.renderBufferStorageSetup=void 0,s.framebuffers){for(const e in s.framebuffers)t.deleteFramebuffer(s.framebuffers[e]);delete s.framebuffers}if(s.depthRenderbuffer&&(t.deleteRenderbuffer(s.depthRenderbuffer),delete s.depthRenderbuffer),s.stencilRenderbuffer&&(t.deleteRenderbuffer(s.stencilRenderbuffer),delete s.stencilRenderbuffer),s.msaaFrameBuffer&&(t.deleteFramebuffer(s.msaaFrameBuffer),delete s.msaaFrameBuffer),s.msaaRenderbuffers){for(let e=0;e<s.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(s.msaaRenderbuffers[e]);delete s.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:r,backend:s}=this,{textureGPU:i,renderTarget:n}=s.get(e);this.deallocateRenderBuffers(n),!1===t&&r.deleteTexture(i),s.delete(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){const{gl:a,backend:o}=this,{state:u}=this.backend,{textureGPU:l,glTextureType:d,glType:c,glFormat:h}=o.get(t);let p,g,m,f,y,b,x,T,_;u.bindTexture(d,l);const v=e.isCompressedTexture?e.mipmaps[n]:e.image;if(null!==r)p=r.max.x-r.min.x,g=r.max.y-r.min.y,m=r.isBox3?r.max.z-r.min.z:1,f=r.min.x,y=r.min.y,b=r.isBox3?r.min.z:0;else{const t=Math.pow(2,-i);p=Math.floor(v.width*t),g=Math.floor(v.height*t),m=e.isDataArrayTexture||e.isArrayTexture?v.depth:e.isData3DTexture?Math.floor(v.depth*t):1,f=0,y=0,b=0}null!==s?(x=s.x,T=s.y,_=s.z):(x=0,T=0,_=0),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const N=a.getParameter(a.UNPACK_ROW_LENGTH),S=a.getParameter(a.UNPACK_IMAGE_HEIGHT),A=a.getParameter(a.UNPACK_SKIP_PIXELS),R=a.getParameter(a.UNPACK_SKIP_ROWS),E=a.getParameter(a.UNPACK_SKIP_IMAGES);a.pixelStorei(a.UNPACK_ROW_LENGTH,v.width),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,v.height),a.pixelStorei(a.UNPACK_SKIP_PIXELS,f),a.pixelStorei(a.UNPACK_SKIP_ROWS,y),a.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const w=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const r=o.get(e),s=o.get(t),d=o.get(r.renderTarget),c=o.get(s.renderTarget),h=d.framebuffers[r.cacheKey],v=c.framebuffers[s.cacheKey];u.bindFramebuffer(a.READ_FRAMEBUFFER,h),u.bindFramebuffer(a.DRAW_FRAMEBUFFER,v);for(let e=0;e<m;e++)w&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,r.textureGPU,i,b+e),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,l,n,_+e)),a.blitFramebuffer(f,y,p,g,x,T,p,g,a.DEPTH_BUFFER_BIT,a.NEAREST);u.bindFramebuffer(a.READ_FRAMEBUFFER,null),u.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else if(0!==i||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer()),u.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),u.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<m;e++)w?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,t.textureGPU,i,b+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,i),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,l,n,_+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,l,n),0!==i?a.blitFramebuffer(f,y,p,g,x,T,p,g,a.COLOR_BUFFER_BIT,a.NEAREST):C?a.copyTexSubImage3D(d,n,x,T,_+e,f,y,p,g):a.copyTexSubImage2D(d,n,x,T,f,y,p,g);u.bindFramebuffer(a.READ_FRAMEBUFFER,null),u.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else C?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(d,n,x,T,_,p,g,m,h,c,v.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(d,n,x,T,_,p,g,m,h,v.data):a.texSubImage3D(d,n,x,T,_,p,g,m,h,c,v):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,n,x,T,p,g,h,c,v.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,n,x,T,v.width,v.height,h,v.data):a.texSubImage2D(a.TEXTURE_2D,n,x,T,p,g,h,c,v);a.pixelStorei(a.UNPACK_ROW_LENGTH,N),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,S),a.pixelStorei(a.UNPACK_SKIP_PIXELS,A),a.pixelStorei(a.UNPACK_SKIP_ROWS,R),a.pixelStorei(a.UNPACK_SKIP_IMAGES,E),0===n&&t.generateMipmaps&&a.generateMipmap(d),u.unbindTexture()}copyFramebufferToTexture(e,t,r){const{gl:s}=this,{state:i}=this.backend,{textureGPU:n}=this.backend.get(e),{x:a,y:o,z:u,w:l}=r,d=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){const r=0!==a||0!==o;let d,h;if(!0===e.isDepthTexture?(d=s.DEPTH_BUFFER_BIT,h=s.DEPTH_ATTACHMENT,t.stencil&&(d|=s.STENCIL_BUFFER_BIT)):(d=s.COLOR_BUFFER_BIT,h=s.COLOR_ATTACHMENT0),r){const e=this.backend.get(t.renderTarget),r=e.framebuffers[t.getCacheKey()],h=e.msaaFrameBuffer;i.bindFramebuffer(s.DRAW_FRAMEBUFFER,r),i.bindFramebuffer(s.READ_FRAMEBUFFER,h);const p=c-o-l;s.blitFramebuffer(a,p,a+u,p+l,a,p,a+u,p+l,d,s.NEAREST),i.bindFramebuffer(s.READ_FRAMEBUFFER,r),i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,p,u,l),i.unbindTexture()}else{const e=s.createFramebuffer();i.bindFramebuffer(s.DRAW_FRAMEBUFFER,e),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,h,s.TEXTURE_2D,n,0),s.blitFramebuffer(0,0,u,l,0,0,u,l,d,s.NEAREST),s.deleteFramebuffer(e)}}else i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,c-l-o,u,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,r,s=!1){const{gl:i}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:u,width:l,height:d}=n;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!u){let t=i.DEPTH_COMPONENT24;if(!0===s){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,n.samples,t,l,d)}else r>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,r,t,l,d)):i.renderbufferStorage(i.RENDERBUFFER,t,l,d);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&u&&(r>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,r,i.DEPTH24_STENCIL8,l,d):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,d),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,r,s,i,n){const{backend:a,gl:o}=this,{textureGPU:u,glFormat:l,glType:d}=this.backend.get(e),c=o.createFramebuffer();o.bindFramebuffer(o.READ_FRAMEBUFFER,c);const h=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,u,0);const p=this._getTypedArrayType(d),g=s*i*this._getBytesPerTexel(d,l),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,g,o.STREAM_READ),o.readPixels(t,r,s,i,l,d,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(g/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:r}=this;let s=0;return e===r.UNSIGNED_BYTE&&(s=1),e!==r.UNSIGNED_SHORT_4_4_4_4&&e!==r.UNSIGNED_SHORT_5_5_5_1&&e!==r.UNSIGNED_SHORT_5_6_5&&e!==r.UNSIGNED_SHORT&&e!==r.HALF_FLOAT||(s=2),e!==r.UNSIGNED_INT&&e!==r.FLOAT||(s=4),t===r.RGBA?4*s:t===r.RGB?3*s:t===r.ALPHA?s:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function LS(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class FS{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class IS{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const DS={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class US{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:r,mode:s,object:i,type:n,info:a,index:o}=this;0!==o?r.drawElements(s,t,n,e):r.drawArrays(s,e,t),a.update(i,t,1)}renderInstances(e,t,r){const{gl:s,mode:i,type:n,index:a,object:o,info:u}=this;0!==r&&(0!==a?s.drawElementsInstanced(i,t,n,e,r):s.drawArraysInstanced(i,e,t,r),u.update(o,t,r))}renderMultiDraw(e,t,r){const{extensions:s,mode:i,object:n,info:a}=this;if(0===r)return;const o=s.get("WEBGL_multi_draw");if(null===o)for(let s=0;s<r;s++)this.render(e[s],t[s]);else{0!==this.index?o.multiDrawElementsWEBGL(i,t,0,this.type,e,0,r):o.multiDrawArraysWEBGL(i,e,0,t,0,r);let s=0;for(let e=0;e<r;e++)s+=t[e];a.update(n,s,1)}}renderMultiDrawInstances(e,t,r,s){const{extensions:i,mode:n,object:a,info:o}=this;if(0===r)return;const u=i.get("WEBGL_multi_draw");if(null===u)for(let i=0;i<r;i++)this.renderInstances(e[i],t[i],s[i]);else{0!==this.index?u.multiDrawElementsInstancedWEBGL(n,t,0,this.type,e,0,s,0,r):u.multiDrawArraysInstancedWEBGL(n,e,0,t,0,s,0,r);let i=0;for(let e=0;e<r;e++)i+=t[e]*s[e];o.update(a,i,1)}}}class VS{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return void 0===t&&(d(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class OS extends VS{constructor(e,t,r=2048){if(super(r),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return d("EXT_disjoint_timer_query not supported; timestamps will be disabled."),void(this.trackTimestamp=!1);this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return v(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const r=this.queries[t];if(r)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,r),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){e("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){e("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,r]of this.queryOffsets){if("ended"===this.queryStates.get(r)){const s=this.queries[r];e.set(t,this.resolveQuery(s))}}if(0===e.size)return this.lastValue;const t={},r=[];for(const[s,i]of e){const e=s.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===r.includes(n)&&r.push(n),void 0===t[n]&&(t[n]=0);const a=await i;this.timestamps.set(s,a),t[n]+=a}const s=t[r[r.length-1]];return this.lastValue=s,this.frames=r,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return e("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise((t=>{if(this.isDisposed)return void t(this.lastValue);let r,s=!1;const i=e=>{s||(s=!0,r&&(clearTimeout(r),r=null),t(e))},n=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(r=setTimeout(n,1));const s=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(s)/1e6)}catch(e){e("Error checking query:",e),t(this.lastValue)}};n()}))}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class GS extends TS{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,r={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},s=void 0!==t.context?t.context:e.domElement.getContext("webgl2",r);function i(t){t.preventDefault();const r={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(r)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new FS(this),this.capabilities=new IS(this),this.attributeUtils=new AS(this),this.textureUtils=new PS(this),this.bufferRenderer=new US(this),this.state=new RS(this),this.utils=new ES(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return c}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,r=null){const s=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:s.RGBA8}),null!==r){const t=e.stencilBuffer?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:r,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&d("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new OS(this.gl,e,2048));const r=this.timestampQueryPool[e];null!==r.allocateQueriesForContext(t)&&r.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.viewport(0,0,e,r)}if(e.scissor){const{x:r,y:s,width:i,height:n}=e.scissorValue;t.scissor(r,e.height-n-s,i,n)}this.initTimestampQuery(bt.RENDER,this.getTimestampUID(e)),r.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const s=e.occlusionQueryCount;s>0&&(r.currentOcclusionQueries=r.occlusionQueries,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,r.lastOcclusionObject=null,r.occlusionQueries=new Array(s),r.occlusionQueryObjects=new Array(s),r.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:r}=this,s=this.get(e),i=s.previousContext;r.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>s.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e<a.length;e++){const t=a[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=i,this._resolveRenderTarget(e),null!==i)if(this._setFramebuffer(i),i.viewport)this.updateViewport(i);else{const{width:e,height:t}=this.getDrawingBufferSize();r.viewport(0,0,e,t)}this.prepareTimestampBuffer(bt.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:r,currentOcclusionQueryObjects:s}=t;if(r&&s){const e=new WeakSet,{gl:i}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const n=()=>{let a=0;for(let t=0;t<r.length;t++){const n=r[t];null!==n&&(i.getQueryParameter(n,i.QUERY_RESULT_AVAILABLE)&&(0===i.getQueryParameter(n,i.QUERY_RESULT)&&e.add(s[t]),r[t]=null,i.deleteQuery(n),a++))}a<r.length?requestAnimationFrame(n):t.occluded=e};n()}}isOccluded(e,t){const r=this.get(e);return r.occluded&&r.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:r,y:s,width:i,height:n}=e.viewportValue;t.viewport(r,e.height-n-s,i,n)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,r,s=null,i=!0,n=!0){const{gl:a,renderer:o}=this;if(null===s){s={textures:null,clearColorValue:this.getClearColor()}}let u=0;if(e&&(u|=a.COLOR_BUFFER_BIT),t&&(u|=a.DEPTH_BUFFER_BIT),r&&(u|=a.STENCIL_BUFFER_BIT),0!==u){let l;l=s.clearColorValue?s.clearColorValue:this.getClearColor();const d=o.getClearDepth(),c=o.getClearStencil();if(t&&this.state.setDepthMask(!0),null===s.textures)a.clearColor(l.r,l.g,l.b,l.a),a.clear(u);else{if(i&&this._setFramebuffer(s),e)for(let e=0;e<s.textures.length;e++)0===e?a.clearBufferfv(a.COLOR,e,[l.r,l.g,l.b,l.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1]);t&&r?a.clearBufferfi(a.DEPTH_STENCIL,0,d,c):t?a.clearBufferfv(a.DEPTH,0,[d]):r&&a.clearBufferiv(a.STENCIL,0,[c]),i&&n&&this._resolveRenderTarget(s)}}}beginCompute(e){const{state:t,gl:r}=this;t.bindFramebuffer(r.FRAMEBUFFER,null),this.initTimestampQuery(bt.COMPUTE,this.getTimestampUID(e))}compute(e,t,r,s,i=null){const{state:n,gl:a}=this;!1===this.discard&&(a.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:u,attributes:l}=this.get(s),d=this._getVaoKey(l),c=this.vaoCache[d];void 0===c?this.vaoCache[d]=this._createVao(l):n.setVertexState(c),n.useProgram(o),this._bindUniforms(r);const h=this._getTransformFeedback(u);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,h),a.beginTransformFeedback(a.POINTS),i=null!==i?i:t.count,Array.isArray(i)?(v("WebGLBackend.compute(): The count parameter must be a single number, not an array."),i=i[0]):i&&"object"==typeof i&&i.isIndirectStorageBufferAttribute&&(v("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),i=t.count),l[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,i):a.drawArrays(a.POINTS,0,i),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let e=0;e<u.length;e++){const t=u[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const t=this.gl;this.discard=!1,t.disable(t.RASTERIZER_DISCARD),this.prepareTimestampBuffer(bt.COMPUTE,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:r,material:s,context:i,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(r),{gl:o,state:u}=this,l=this.get(i),d=e.getDrawParameters();if(null===d)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;u.setMaterial(s,c,n),u.useProgram(a);const h=e.getAttributes(),p=this.get(h);let g=p.vaoGPU;if(void 0===g){const e=this._getVaoKey(h);g=this.vaoCache[e],void 0===g&&(g=this._createVao(h),this.vaoCache[e]=g,p.vaoGPU=g)}const m=e.getIndex(),f=null!==m?this.get(m).bufferGPU:null;u.setVertexState(g,f);const y=l.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===s.wireframe?(u.setLineWidth(s.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:x,instanceCount:T}=d;let{firstVertex:_}=d;if(b.object=t,null!==m){_*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);b.index=m.count,b.type=e.type}else b.index=0;const N=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(v("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),b.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?b.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):v("WebGLBackend: WEBGL_multi_draw not supported."):T>1?b.renderInstances(_,x,T):b.render(_,x)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const r=this.get(e.camera),s=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===r.indexesGPU||r.indexesGPU.length!==s.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let r=0,i=s.length;r<i;r++){const s=o.createBuffer();e[0]=r,o.bindBuffer(o.UNIFORM_BUFFER,s),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(s)}r.indexesGPU=t}const n=this.get(i),a=this.renderer.getPixelRatio(),l=this._currentContext.renderTarget,d=this._isRenderCameraDepthArray(this._currentContext),c=this._currentContext.activeCubeFace;if(d){const e=this.get(l.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=l;for(let e=0,r=s.length;e<r;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=c,this._currentContext.activeCubeFace=c}}for(let i=0,l=s.length;i<l;i++){const l=s[i];if(t.layers.test(l.layers)){d&&(this.renderer._activeCubeFace=i,this._currentContext.activeCubeFace=i,this._setFramebuffer(this._currentContext));const t=l.viewport;if(void 0!==t){const r=t.x*a,s=t.y*a,i=t.width*a,n=t.height*a;u.viewport(Math.floor(r),Math.floor(e.context.height-n-s),Math.floor(i),Math.floor(n))}u.bindBufferBase(o.UNIFORM_BUFFER,n.index,r.indexesGPU[i]),N()}this._currentContext.activeCubeFace=c,this.renderer._activeCubeFace=c}}else N()}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,r,s,i,n){return this.textureUtils.copyTextureToBuffer(e,t,r,s,i,n)}updateSampler(){return""}createNodeBuilder(e,t){return new yS(e,t)}createProgram(e){const t=this.gl,{stage:r,code:s}=e,i="fragment"===r?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(i,s),t.compileShader(i),this.set(e,{shaderGPU:i})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const r=this.gl,s=e.pipeline,{fragmentProgram:i,vertexProgram:n}=s,a=r.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU;if(r.attachShader(a,o),r.attachShader(a,u),r.linkProgram(a),this.set(s,{programGPU:a,fragmentShader:o,vertexShader:u}),null!==t&&this.parallel){const i=new Promise((t=>{const i=this.parallel,n=()=>{r.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,s),t()):requestAnimationFrame(n)};n()}));t.push(i)}else this._completeCompile(e,s)}_handleSource(e,t){const r=e.split("\n"),s=[],i=Math.max(t-6,0),n=Math.min(t+6,r.length);for(let e=i;e<n;e++){const i=e+1;s.push(`${i===t?">":" "} ${i}: ${r[e]}`)}return s.join("\n")}_getShaderErrors(e,t,r){const s=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||"").trim();if(s&&""===i)return"";const n=/ERROR: 0:(\d+)/.exec(i);if(n){const s=parseInt(n[1]);return r.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),s)}return i}_logProgramError(t,r,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,n=(i.getProgramInfoLog(t)||"").trim();if(!1===i.getProgramParameter(t,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,t,s,r);else{const a=this._getShaderErrors(i,s,"vertex"),o=this._getShaderErrors(i,r,"fragment");e("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(t,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+n+"\n"+a+"\n"+o)}else""!==n&&d("WebGLProgram: Program Info Log:",n)}}_completeCompile(e,t){const{state:r,gl:s}=this,i=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=i;!1===s.getProgramParameter(n,s.LINK_STATUS)&&this._logProgramError(n,a,o),r.useProgram(n);const u=e.getBindings();this._setupBindings(u,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:r,gl:s}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:n}=e,a=s.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU,l=n.transforms,d=[],c=[];for(let e=0;e<l.length;e++){const t=l[e];d.push(t.varyingName),c.push(t.attributeNode)}s.attachShader(a,o),s.attachShader(a,u),s.transformFeedbackVaryings(a,d,s.SEPARATE_ATTRIBS),s.linkProgram(a),!1===s.getProgramParameter(a,s.LINK_STATUS)&&this._logProgramError(a,o,u),r.useProgram(a),this._setupBindings(t,a);const h=n.attributes,p=[],g=[];for(let e=0;e<h.length;e++){const t=h[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,s.ARRAY_BUFFER)}for(let e=0;e<c.length;e++){const t=c[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,s.ARRAY_BUFFER);const r=this.get(t);g.push(r)}this.set(e,{programGPU:a,transformBuffers:g,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,r=0;for(const s of t){this.set(s,{textures:r,uniformBuffers:e});for(const t of s.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&r++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,r=this.get(e);let s=r.uniformBuffers,i=r.textures;for(const r of e.bindings){const e=this.get(r);if(r.isUniformsGroup||r.isUniformBuffer){const i=r.buffer;let{bufferGPU:n}=this.get(i);void 0===n?(n=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,n),t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW),this.set(i,{bufferGPU:n})):(t.bindBuffer(t.UNIFORM_BUFFER,n),t.bufferSubData(t.UNIFORM_BUFFER,0,i)),e.index=s++,e.bufferGPU=n,this.set(r,e)}else if(r.isSampledTexture){const{textureGPU:t,glTextureType:s}=this.get(r.texture);e.index=i++,e.textureGPU=t,e.glTextureType=s,this.set(r,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const r=this.get(e).bufferGPU,s=e.buffer;t.bindBuffer(t.UNIFORM_BUFFER,r),t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW)}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(DS).filter((t=>DS[t]===e)),r=this.extensions;for(let e=0;e<t.length;e++)if(r.has(t[e]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this.textureUtils.copyTextureToTexture(e,t,r,s,i,n)}copyFramebufferToTexture(e,t,r){this.textureUtils.copyFramebufferToTexture(e,t,r)}_setFramebuffer(e){const{gl:t,state:r}=this;let s=null;if(null!==e.textures){const i=e.renderTarget,n=this.get(i),{samples:a,depthBuffer:o,stencilBuffer:u}=i,l=!0===i.isWebGLCubeRenderTarget,d=!0===i.isRenderTarget3D,c=i.depth>1,h=!0===i.isXRRenderTarget,p=!0===h&&!0===i._hasExternalTextures;let g=n.msaaFrameBuffer,m=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(i),x=cy(e);let T;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),T=n.cubeFramebuffers[x]):h&&!1===p?T=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),T=n.framebuffers[x]),void 0===T){T=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,T);const s=e.textures,o=[];if(l){n.cubeFramebuffers[x]=T;const{textureGPU:e}=this.get(s[0]),r=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,i)}else{n.framebuffers[x]=T;for(let r=0;r<s.length;r++){const n=s[r],o=this.get(n);o.renderTarget=e.renderTarget,o.cacheKey=x;const u=t.COLOR_ATTACHMENT0+r;if(i.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,u,o.textureGPU,0,a,0,2);else if(d||c){const e=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,u,o.textureGPU,r,e)}else if(b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,u,t.TEXTURE_2D,o.textureGPU,0,a);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,u,t.TEXTURE_2D,o.textureGPU,e)}}}const h=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===i._autoAllocateDepthBuffer){const r=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(r,e,0,b),n.xrDepthRenderbuffer=r,o.push(u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,h,t.RENDERBUFFER,r)}else if(null!==e.depthTexture){o.push(u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const r=this.get(e.depthTexture);if(r.renderTarget=e.renderTarget,r.cacheKey=x,i.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,h,r.textureGPU,0,a,0,2);else if(p&&b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,h,t.TEXTURE_2D,r.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,h,r.textureGPU,0,e)}else t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_2D,r.textureGPU,0)}n.depthInvalidationArray=o}else{if(this._isRenderCameraDepthArray(e)){r.bindFramebuffer(t.FRAMEBUFFER,T);const s=this.renderer._activeCubeFace,i=this.get(e.depthTexture),n=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,n,i.textureGPU,0,s)}if((h||b||i.multiview)&&!0!==i._isOpaqueFramebuffer){r.bindFramebuffer(t.FRAMEBUFFER,T);const s=this.get(e.textures[0]);i.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,s.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s.textureGPU,0);const o=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===i._autoAllocateDepthBuffer){const e=n.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{const r=this.get(e.depthTexture);i.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,r.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,r.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,r.textureGPU,0)}}}if(a>0&&!1===b&&!i.multiview){if(void 0===g){const s=[];g=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,g);const i=[],l=e.textures;for(let r=0;r<l.length;r++){i[r]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,i[r]),s.push(t.COLOR_ATTACHMENT0+r);const n=e.textures[r],o=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,o.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+r,t.RENDERBUFFER,i[r])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),n.msaaFrameBuffer=g,n.msaaRenderbuffers=i,o&&void 0===m){m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,a),n.depthRenderbuffer=m;const r=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;s.push(r)}n.invalidationArray=s}s=n.msaaFrameBuffer}else s=T;r.drawBuffers(e,T)}r.bindFramebuffer(t.FRAMEBUFFER,s)}_getVaoKey(e){let t="";for(let r=0;r<e.length;r++){t+=":"+this.get(e[r]).id}return t}_createVao(e){const{gl:t}=this,r=t.createVertexArray();t.bindVertexArray(r);for(let r=0;r<e.length;r++){const s=e[r],i=this.get(s);let n,a;t.bindBuffer(t.ARRAY_BUFFER,i.bufferGPU),t.enableVertexAttribArray(r),!0===s.isInterleavedBufferAttribute?(n=s.data.stride*i.bytesPerElement,a=s.offset*i.bytesPerElement):(n=0,a=0),i.isInteger?t.vertexAttribIPointer(r,s.itemSize,i.type,n,a):t.vertexAttribPointer(r,s.itemSize,i.type,s.normalized,n,a),s.isInstancedBufferAttribute&&!s.isInterleavedBufferAttribute?t.vertexAttribDivisor(r,s.meshPerAttribute):s.isInterleavedBufferAttribute&&s.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(r,s.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),r}_getTransformFeedback(e){let t="";for(let r=0;r<e.length;r++)t+=":"+e[r].id;let r=this.transformFeedbackCache[t];if(void 0!==r)return r;const{gl:s}=this;r=s.createTransformFeedback(),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,r);for(let t=0;t<e.length;t++){const r=e[t];s.bindBufferBase(s.TRANSFORM_FEEDBACK_BUFFER,t,r.transformBuffer)}return s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=r,r}_setupBindings(e,t){const r=this.gl;for(const s of e)for(const e of s.bindings){const s=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const i=r.getUniformBlockIndex(t,e.name);r.uniformBlockBinding(t,i,s)}else if(e.isSampledTexture){const i=r.getUniformLocation(t,e.name);r.uniform1i(i,s)}}}_bindUniforms(e){const{gl:t,state:r}=this;for(const s of e)for(const e of s.bindings){const s=this.get(e),i=s.index;e.isUniformsGroup||e.isUniformBuffer?r.bindBufferBase(t.UNIFORM_BUFFER,i,s.bufferGPU):e.isSampledTexture&&r.bindTexture(s.glTextureType,s.textureGPU,t.TEXTURE0+i)}}_resolveRenderTarget(e){const{gl:t,state:r}=this,s=e.renderTarget;if(null!==e.textures&&s){const i=this.get(s);if(s.samples>0&&!1===this._useMultisampledExtension(s)){const n=i.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;s.resolveDepthBuffer&&(s.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),s.stencilBuffer&&s.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=i.msaaFrameBuffer,u=i.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,o),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),d)for(let e=0;e<l.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let r=0;r<l.length;r++){if(d){const{textureGPU:e}=this.get(l[r]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,u[r]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:r,y:s,width:i,height:n}=e.scissorValue,o=e.height-n-s;t.blitFramebuffer(r,o,r+i,o+n,r,o,r+i,o+n,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(d)for(let e=0;e<l.length;e++){const{textureGPU:r}=this.get(l[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,u[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,r,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,i.invalidationArray)}else if(!1===s.resolveDepthBuffer&&i.framebuffers){const s=i.framebuffers[e.getCacheKey()];r.bindFramebuffer(t.DRAW_FRAMEBUFFER,s),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,i.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const kS="point-list",zS="line-list",$S="line-strip",WS="triangle-list",HS="triangle-strip",jS="never",qS="less",XS="equal",KS="less-equal",YS="greater",QS="not-equal",ZS="greater-equal",JS="always",eA="store",tA="load",rA="clear",sA="ccw",iA="cw",nA="none",aA="back",oA="uint16",uA="uint32",lA="r8unorm",dA="r8snorm",cA="r8uint",hA="r8sint",pA="r16uint",gA="r16sint",mA="r16float",fA="rg8unorm",yA="rg8snorm",bA="rg8uint",xA="rg8sint",TA="r32uint",_A="r32sint",vA="r32float",NA="rg16uint",SA="rg16sint",AA="rg16float",RA="rgba8unorm",EA="rgba8unorm-srgb",wA="rgba8snorm",CA="rgba8uint",MA="rgba8sint",BA="bgra8unorm",PA="bgra8unorm-srgb",LA="rgb9e5ufloat",FA="rgb10a2unorm",IA="rg11b10ufloat",DA="rg32uint",UA="rg32sint",VA="rg32float",OA="rgba16uint",GA="rgba16sint",kA="rgba16float",zA="rgba32uint",$A="rgba32sint",WA="rgba32float",HA="depth16unorm",jA="depth24plus",qA="depth24plus-stencil8",XA="depth32float",KA="depth32float-stencil8",YA="bc1-rgba-unorm",QA="bc1-rgba-unorm-srgb",ZA="bc2-rgba-unorm",JA="bc2-rgba-unorm-srgb",eR="bc3-rgba-unorm",tR="bc3-rgba-unorm-srgb",rR="bc4-r-unorm",sR="bc4-r-snorm",iR="bc5-rg-unorm",nR="bc5-rg-snorm",aR="bc6h-rgb-ufloat",oR="bc6h-rgb-float",uR="bc7-rgba-unorm",lR="bc7-rgba-unorm-srgb",dR="etc2-rgb8unorm",cR="etc2-rgb8unorm-srgb",hR="etc2-rgb8a1unorm",pR="etc2-rgb8a1unorm-srgb",gR="etc2-rgba8unorm",mR="etc2-rgba8unorm-srgb",fR="eac-r11unorm",yR="eac-r11snorm",bR="eac-rg11unorm",xR="eac-rg11snorm",TR="astc-4x4-unorm",_R="astc-4x4-unorm-srgb",vR="astc-5x4-unorm",NR="astc-5x4-unorm-srgb",SR="astc-5x5-unorm",AR="astc-5x5-unorm-srgb",RR="astc-6x5-unorm",ER="astc-6x5-unorm-srgb",wR="astc-6x6-unorm",CR="astc-6x6-unorm-srgb",MR="astc-8x5-unorm",BR="astc-8x5-unorm-srgb",PR="astc-8x6-unorm",LR="astc-8x6-unorm-srgb",FR="astc-8x8-unorm",IR="astc-8x8-unorm-srgb",DR="astc-10x5-unorm",UR="astc-10x5-unorm-srgb",VR="astc-10x6-unorm",OR="astc-10x6-unorm-srgb",GR="astc-10x8-unorm",kR="astc-10x8-unorm-srgb",zR="astc-10x10-unorm",$R="astc-10x10-unorm-srgb",WR="astc-12x10-unorm",HR="astc-12x10-unorm-srgb",jR="astc-12x12-unorm",qR="astc-12x12-unorm-srgb",XR="clamp-to-edge",KR="repeat",YR="mirror-repeat",QR="linear",ZR="nearest",JR="zero",eE="one",tE="src",rE="one-minus-src",sE="src-alpha",iE="one-minus-src-alpha",nE="dst",aE="one-minus-dst",oE="dst-alpha",uE="one-minus-dst-alpha",lE="src-alpha-saturated",dE="constant",cE="one-minus-constant",hE="add",pE="subtract",gE="reverse-subtract",mE="min",fE="max",yE=0,bE=15,xE="keep",TE="zero",_E="replace",vE="invert",NE="increment-clamp",SE="decrement-clamp",AE="increment-wrap",RE="decrement-wrap",EE="storage",wE="read-only-storage",CE="write-only",ME="read-only",BE="read-write",PE="non-filtering",LE="comparison",FE="float",IE="unfilterable-float",DE="depth",UE="sint",VE="uint",OE="2d",GE="3d",kE="2d",zE="2d-array",$E="cube",WE="3d",HE="all",jE="vertex",qE="instance",XE={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},KE={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class YE extends iS{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class QE extends QN{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let ZE=0;class JE extends QE{constructor(e,t){super("StorageBuffer_"+ZE++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Ws.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class ew extends Of{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:QR}),this.flipYSampler=e.createSampler({minFilter:ZR}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4<f32>,\n\t@location( 0 ) vTex : vec2<f32>\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( -1.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 ),\n\t\tvec2<f32>( -1.0, -1.0 ),\n\t\tvec2<f32>( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( 0.0, 0.0 ),\n\t\tvec2<f32>( 1.0, 0.0 ),\n\t\tvec2<f32>( 0.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:HS,stripIndexFormat:uA},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:HS,stripIndexFormat:uA},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.getTransferPipeline(s),o=this.getFlipYPipeline(s),u=this.device.createTexture({size:{width:i,height:n,depthOrArrayLayers:1},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:kE,baseArrayLayer:r}),d=u.createView({baseMipLevel:0,mipLevelCount:1,dimension:kE,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),h=(e,t,r)=>{const s=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:r,loadOp:rA,storeOp:eA,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,i),n.draw(4,1,0,0),n.end()};h(a,l,d),h(o,d,l),this.device.queue.submit([c.finish()]),u.destroy()}generateMipmaps(e,t,r=0,s=null){const i=this.get(e);void 0===i.layers&&(i.layers=[]);const n=i.layers[r]||this._mipmapCreateBundles(e,t,r),a=s||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(a,n),null===s&&this.device.queue.submit([a.finish()]),i.layers[r]=n}_mipmapCreateBundles(e,t,r){const s=this.getTransferPipeline(t.format),i=s.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:kE,baseArrayLayer:r});const a=[];for(let o=1;o<t.mipLevelCount;o++){const u=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:n}]}),l=e.createView({baseMipLevel:o,mipLevelCount:1,dimension:kE,baseArrayLayer:r}),d={colorAttachments:[{view:l,loadOp:rA,storeOp:eA,clearValue:[0,0,0,0]}]},c=this.device.createRenderBundleEncoder({colorFormats:[t.format]});c.setPipeline(s),c.setBindGroup(0,u),c.draw(4,1,0,0),a.push({renderBundles:[c.finish()],passDescriptor:d}),n=l}return a}_mipmapRunBundles(e,t){const r=t.length;for(let s=0;s<r;s++){const r=t[s],i=e.beginRenderPass(r.passDescriptor);i.executeBundles(r.renderBundles),i.end()}}}const tw={[Mr]:"never",[ze]:"less",[Lr]:"equal",[Pr]:"less-equal",[Ir]:"greater",[Fr]:"greater-equal",[Br]:"always",[Dr]:"not-equal"},rw=[0,1,3,2,4,5];class sw{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,r=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let s=this._samplerCache.get(r);if(void 0===s){const i={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};i.magFilter===QR&&i.minFilter===QR&&i.mipmapFilter===QR&&(i.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(i.compare=tw[e.compareFunction]);s={sampler:t.device.createSampler(i),usedTimes:0},this._samplerCache.set(r,s)}const i=t.get(e);if(i.sampler!==s.sampler){if(void 0!==i.sampler){const e=this._samplerCache.get(i.samplerKey);e.usedTimes--,0===e.usedTimes&&this._samplerCache.delete(i.samplerKey)}i.samplerKey=r,i.sampler=s.sampler,s.usedTimes++}return r}createDefaultTexture(e){let t;const r=iw(e);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(r):this._getDefaultTextureGPU(r),this.backend.get(e).texture=t}createTexture(e,t={}){const r=this.backend,s=r.get(e);if(s.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture)return s.texture=e.sourceTexture,void(s.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:i,height:n,depth:a,levels:o}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const u=this._getDimension(e),l=e.internalFormat||t.format||iw(e,r.device);s.format=l;const{samples:c,primarySamples:h,isMSAA:p}=r.utils.getTextureSampleData(e);let g=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(g|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&l!==LA&&(g|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:i,height:n,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:h,dimension:u,format:l,usage:g};if(void 0===l)return d("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);if(e.isCubeTexture&&(m.textureBindingViewDimension=$E),s.texture=r.device.createTexture(m),p){const e=Object.assign({},m);e.label=e.label+"-msaa",e.sampleCount=c,e.mipLevelCount=1,s.msaaTexture=r.device.createTexture(e)}s.initialized=!0,s.textureDescriptorGPU=m}destroyTexture(e,t=!1){const r=this.backend,s=r.get(e);void 0!==s.texture&&!1===t&&s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),r.delete(e)}generateMipmaps(e,t=null){const r=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(r.texture,r.textureDescriptorGPU,e,t);else{const s=e.image.depth||1;for(let e=0;e<s;e++)this._generateMipmaps(r.texture,r.textureDescriptorGPU,e,t)}}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:r,height:s}=e.getDrawingBufferSize(),i=e.renderer.currentSamples,n=t.colorTexture,a=e.get(n);if(n.width===r&&n.height===s&&n.samples===i)return a.texture;let o=a.texture;return o&&o.destroy(),o=e.device.createTexture({label:"colorBuffer",size:{width:r,height:s,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),n.source.width=r,n.source.height=s,n.samples=i,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const r=this.backend,s=r.renderer.getCanvasTarget(),{width:i,height:n}=r.getDrawingBufferSize(),a=r.renderer.currentSamples,o=s.depthTexture;if(o.width===i&&o.height===n&&o.samples===a&&o.depth===e&&o.stencil===t)return r.get(o).texture;const u=r.get(o).texture;let l,d;if(t?(l=Pe,d=Fe):e&&(l=Le,d=N),void 0!==u){if(o.image.width===i&&o.image.height===n&&o.format===l&&o.type===d&&o.samples===a)return u;this.destroyTexture(o)}return o.name="depthBuffer",o.format=l,o.type=d,o.image.width=i,o.image.height=n,o.samples=a,this.createTexture(o,{width:i,height:n}),r.get(o).texture}updateTexture(e,t){const r=this.backend.get(e),s=e.mipmaps,{textureDescriptorGPU:i}=r;if(!e.isRenderTargetTexture&&void 0!==i){if(e.isDataTexture)if(s.length>0)for(let t=0,n=s.length;t<n;t++){const n=s[t];this._copyBufferToTexture(n,r.texture,i,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,r.texture,i,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let s=0;s<t.image.depth;s++)this._copyBufferToTexture(t.image,r.texture,i,s,e.flipY,s);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,r.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,r.texture,i);else if(s.length>0)for(let t=0,n=s.length;t<n;t++){const n=s[t];this._copyImageToTexture(n,r.texture,i,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,r.texture,i,0,e.flipY,e.premultiplyAlpha);r.version=e.version}}async copyTextureToBuffer(e,t,r,s,i,n){const a=this.backend.device,o=this.backend.get(e),u=o.texture,l=o.textureDescriptorGPU.format,d=this._getBytesPerTexel(l);let c=s*d;c=256*Math.ceil(c/256);const h=a.createBuffer({size:(i-1)*c+s*d,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:u,origin:{x:t,y:r,z:n}},{buffer:h,bytesPerRow:c},{width:s,height:i});const g=this._getTypedArrayType(l);a.queue.submit([p.finish()]),await h.mapAsync(GPUMapMode.READ);return new g(h.getMappedRange())}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const r=new R;r.minFilter=A,r.magFilter=A,this.createTexture(r,{width:1,height:1,format:e}),this.defaultTexture[e]=t=r}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const r=new L;r.minFilter=A,r.magFilter=A,this.createTexture(r,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=r}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,r){const s=e.images,i=e.mipmaps;for(let n=0;n<6;n++){const a=s[n],o=!0===e.flipY?rw[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,r,o,e.flipY):this._copyImageToTexture(a,t,r,o,e.flipY,e.premultiplyAlpha);for(let s=0;s<i.length;s++){const a=i[s].images[n];a.isDataTexture?this._copyBufferToTexture(a.image,t,r,o,e.flipY,0,s+1):this._copyImageToTexture(a,t,r,o,e.flipY,e.premultiplyAlpha,s+1)}}}_copyImageToTexture(e,t,r,s,i,n,a=0){const o=this.backend.device,u=a>0?e.width:r.size.width,l=a>0?e.height:r.size.height;o.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:a,origin:{x:0,y:0,z:s},premultipliedAlpha:n},{width:u,height:l,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new ew(this.backend.device)),e}_generateMipmaps(e,t,r=0,s=null){this._getPassUtils().generateMipmaps(e,t,r,s)}_flipY(e,t,r=0){this._getPassUtils().flipY(e,t,r)}_copyBufferToTexture(e,t,r,s,i,n=0,a=0){const o=this.backend.device,u=e.data,l=this._getBytesPerTexel(r.format),d=e.width*l;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:s}},u,{offset:e.width*e.height*l*n,bytesPerRow:d},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===i&&this._flipY(t,r,s)}_copyCompressedBufferToTexture(e,t,r){const s=this.backend.device,i=this._getBlockData(r.format),n=r.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const o=e[a],u=o.width,l=o.height,d=n?r.size.depthOrArrayLayers:1,c=Math.ceil(u/i.width)*i.byteLength,h=c*Math.ceil(l/i.height);for(let e=0;e<d;e++)s.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:e}},o.data,{offset:e*h,bytesPerRow:c,rowsPerImage:Math.ceil(l/i.height)},{width:Math.ceil(u/i.width)*i.width,height:Math.ceil(l/i.height)*i.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===YA||e===QA?{byteLength:8,width:4,height:4}:e===ZA||e===JA||e===eR||e===tR?{byteLength:16,width:4,height:4}:e===rR||e===sR?{byteLength:8,width:4,height:4}:e===iR||e===nR||e===aR||e===oR||e===uR||e===lR?{byteLength:16,width:4,height:4}:e===dR||e===cR||e===hR||e===pR?{byteLength:8,width:4,height:4}:e===gR||e===mR?{byteLength:16,width:4,height:4}:e===fR||e===yR?{byteLength:8,width:4,height:4}:e===bR||e===xR||e===TR||e===_R?{byteLength:16,width:4,height:4}:e===vR||e===NR?{byteLength:16,width:5,height:4}:e===SR||e===AR?{byteLength:16,width:5,height:5}:e===RR||e===ER?{byteLength:16,width:6,height:5}:e===wR||e===CR?{byteLength:16,width:6,height:6}:e===MR||e===BR?{byteLength:16,width:8,height:5}:e===PR||e===LR?{byteLength:16,width:8,height:6}:e===FR||e===IR?{byteLength:16,width:8,height:8}:e===DR||e===UR?{byteLength:16,width:10,height:5}:e===VR||e===OR?{byteLength:16,width:10,height:6}:e===GR||e===kR?{byteLength:16,width:10,height:8}:e===zR||e===$R?{byteLength:16,width:10,height:10}:e===WR||e===HR?{byteLength:16,width:12,height:10}:e===jR||e===qR?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=XR;return e===Er?t=KR:e===wr&&(t=YR),t}_convertFilterMode(e){let t=QR;return e!==A&&e!==Cr&&e!==qe||(t=ZR),t}_getBytesPerTexel(e){return e===lA||e===dA||e===cA||e===hA?1:e===pA||e===gA||e===mA||e===fA||e===yA||e===bA||e===xA?2:e===TA||e===_A||e===vA||e===NA||e===SA||e===AA||e===RA||e===EA||e===wA||e===CA||e===MA||e===BA||e===PA||e===LA||e===FA||e===IA||e===XA||e===jA||e===qA||e===KA?4:e===DA||e===UA||e===VA||e===OA||e===GA||e===kA?8:e===zA||e===$A||e===WA?16:void 0}_getTypedArrayType(e){return e===cA?Uint8Array:e===hA?Int8Array:e===lA?Uint8Array:e===dA?Int8Array:e===bA?Uint8Array:e===xA?Int8Array:e===fA?Uint8Array:e===yA?Int8Array:e===CA?Uint8Array:e===MA?Int8Array:e===RA||e===EA?Uint8Array:e===wA?Int8Array:e===pA?Uint16Array:e===gA?Int16Array:e===NA?Uint16Array:e===SA?Int16Array:e===OA?Uint16Array:e===GA?Int16Array:e===mA||e===AA||e===kA?Uint16Array:e===TA?Uint32Array:e===_A?Int32Array:e===vA?Float32Array:e===DA?Uint32Array:e===UA?Int32Array:e===VA?Float32Array:e===zA?Uint32Array:e===$A?Int32Array:e===WA?Float32Array:e===BA||e===PA?Uint8Array:e===FA||e===LA||e===IA?Uint32Array:e===XA?Float32Array:e===jA||e===qA?Uint32Array:e===KA?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?GE:OE,t}}function iw(t,r=null){const s=t.format,i=t.type,n=t.colorSpace,a=p.getTransfer(n);let o;if(!0===t.isCompressedTexture||!0===t.isCompressedArrayTexture)switch(s){case Qt:case Zt:o=a===g?QA:YA;break;case Jt:o=a===g?JA:ZA;break;case er:o=a===g?tR:eR;break;case Nr:o=rR;break;case Sr:o=sR;break;case Ar:o=iR;break;case Rr:o=nR;break;case vr:o=a===g?lR:uR;break;case ar:case nr:o=a===g?cR:dR;break;case or:o=a===g?mR:gR;break;case ur:o=a===g?_R:TR;break;case lr:o=a===g?NR:vR;break;case dr:o=a===g?AR:SR;break;case cr:o=a===g?ER:RR;break;case hr:o=a===g?CR:wR;break;case pr:o=a===g?BR:MR;break;case gr:o=a===g?LR:PR;break;case mr:o=a===g?IR:FR;break;case fr:o=a===g?UR:DR;break;case yr:o=a===g?OR:VR;break;case br:o=a===g?kR:GR;break;case xr:o=a===g?$R:zR;break;case Tr:o=a===g?HR:WR;break;case _r:o=a===g?qR:jR;break;case be:o=a===g?EA:RA;break;default:e("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case be:switch(i){case ft:o=wA;break;case yt:o=GA;break;case mt:o=OA;break;case N:o=zA;break;case S:o=$A;break;case Ie:o=a===g?EA:RA;break;case ce:o=kA;break;case O:o=WA;break;default:e("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case pt:switch(i){case Xt:o=LA;break;case Kt:o=IA;break;default:e("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case dt:switch(i){case ft:o=dA;break;case yt:o=gA;break;case mt:o=pA;break;case N:o=TA;break;case S:o=_A;break;case Ie:o=lA;break;case ce:o=mA;break;case O:o=vA;break;default:e("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case de:switch(i){case ft:o=yA;break;case yt:o=SA;break;case mt:o=NA;break;case N:o=DA;break;case S:o=UA;break;case Ie:o=fA;break;case ce:o=AA;break;case O:o=VA;break;default:e("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case Le:switch(i){case mt:o=HA;break;case N:o=jA;break;case O:o=XA;break;default:e("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case Pe:switch(i){case Fe:o=qA;break;case O:r&&!1===r.features.has(XE.Depth32FloatStencil8)&&e('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=KA;break;default:e("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case lt:switch(i){case S:o=_A;break;case N:o=TA;break;default:e("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case ct:switch(i){case S:o=UA;break;case N:o=DA;break;default:e("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case gt:switch(i){case S:o=$A;break;case N:o=zA;break;default:e("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:e("WebGPURenderer: Unsupported texture format.",s)}return o}const nw=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,aw=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,ow={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class uw extends hN{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(nw);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=aw.exec(r));)s.push({name:i[1],type:i[2]});const n=[];for(let e=0;e<s.length;e++){const{name:t,type:r}=s[e];let i=r;i.startsWith("ptr")?i="pointer":(i.startsWith("texture")&&(i=r.split("<")[0]),i=ow[i]),n.push(new Zv(i,t))}const a=e.substring(t[0].length),o=t[3]||"void",u=void 0!==t[1]?t[1]:"";return{type:ow[o]||o,inputs:n,name:u,inputsCode:r,blockCode:a,outputType:o}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,r,s),this.inputsCode=i,this.blockCode=n,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class lw extends cN{parseFunction(e){return new uw(e)}}const dw="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},cw={[Ws.READ_ONLY]:"read",[Ws.WRITE_ONLY]:"write",[Ws.READ_WRITE]:"read_write"},hw={[Er]:"repeat",[he]:"clamp",[wr]:"mirror"},pw={vertex:dw?dw.VERTEX:1,fragment:dw?dw.FRAGMENT:2,compute:dw?dw.COMPUTE:4},gw={instance:!0,swizzleAssign:!1,storageBuffer:!0},mw={"^^":"tsl_xor"},fw={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},yw={},bw={tsl_xor:new mx("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new mx("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new mx("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new mx("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new mx("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new mx("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new mx("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new mx("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new mx("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new mx("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new mx("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new mx("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new mx("\nfn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},xw={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>"};let Tw="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(Tw+="diagnostic( off, derivative_uniformity );\n");class _w extends Yv{constructor(e,t){super(e,t,new lw),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,r,s,i,n=this.shaderStage){return"fragment"===n?s?i?`textureSample( ${t}, ${t}_sampler, ${r}, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:i?`textureSample( ${t}, ${t}_sampler, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this.generateTextureSampleLevel(e,t,r,"0",s)}generateTextureSampleLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s):this.generateTextureLod(e,t,r,i,n,s)}generateWrapFunction(e){const t=`tsl_coord_${hw[e.wrapS]}S_${hw[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let r=yw[t];if(void 0===r){const s=[],i=e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===Er?(s.push(bw.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===he?(s.push(bw.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===wr?(s.push(bw.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,d(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",yw[t]=r=new mx(n,s)}return r.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,r){const s=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===s.dimensionsSnippet&&(s.dimensionsSnippet={});let i=s.dimensionsSnippet[r];if(void 0===s.dimensionsSnippet[r]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),u=o>1;a=e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=u||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new pu(new Zu(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(s.arrayLayerCount=new pu(new Zu(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new pu(new Zu("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s,i="0u"){this._include("biquadraticTexture");const n=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i);return s&&(r=`${r} + vec2<f32>(${s}) / ${a}`),`tsl_biquadraticTexture( ${t}, ${n}( ${r} ), ${a}, u32( ${i} ) )`}generateTextureLod(e,t,r,s,i,n="0u"){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),u=e.isData3DTexture?"vec3":"vec2";i&&(r=`${r} + ${u}<f32>(${i}) / ${u}<f32>( ${o} )`);const l=`${u}<u32>( ${a}( ${r} ) * ${u}<f32>( ${o} ) )`;return this.generateTextureLoad(e,t,l,n,s,null)}generateTextureLoad(e,t,r,s,i,n){let a;return null===s&&(s="0u"),n&&(r=`${r} + ${n}`),i?a=`textureLoad( ${t}, ${r}, ${i}, u32( ${s} ) )`:(a=`textureLoad( ${t}, ${r}, u32( ${s} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,r,s,i){let n;return n=s?`textureStore( ${t}, ${r}, ${s}, ${i} )`:`textureStore( ${t}, ${r}, ${i} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===O||!1===this.isSampleCompare(e)&&e.minFilter===A&&e.magFilter===A||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,i,"0",n):this._generateTextureSample(e,t,r,s,i,n),a}generateTextureGrad(t,r,s,i,n,a,o=this.shaderStage){if("fragment"===o)return a?`textureSampleGrad( ${r}, ${r}_sampler, ${s}, ${i[0]}, ${i[1]}, ${a} )`:`textureSampleGrad( ${r}, ${r}_sampler, ${s}, ${i[0]}, ${i[1]} )`;e(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${o} shader.`)}generateTextureCompare(t,r,s,i,n,a,o=this.shaderStage){if("fragment"===o)return!0===t.isDepthTexture&&!0===t.isArrayTexture?a?`textureSampleCompare( ${r}, ${r}_sampler, ${s}, ${n}, ${i}, ${a} )`:`textureSampleCompare( ${r}, ${r}_sampler, ${s}, ${n}, ${i} )`:a?`textureSampleCompare( ${r}, ${r}_sampler, ${s}, ${i}, ${a} )`:`textureSampleCompare( ${r}, ${r}_sampler, ${s}, ${i} )`;e(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s):this.generateTextureLod(e,t,r,i,n,s)}generateTextureBias(t,r,s,i,n,a,o=this.shaderStage){if("fragment"===o)return a?`textureSampleBias( ${r}, ${r}_sampler, ${s}, ${i}, ${a} )`:`textureSampleBias( ${r}, ${r}_sampler, ${s}, ${i} )`;e(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${o} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,r=e.type;return"texture"===r||"cubeTexture"===r||"storageTexture"===r||"texture3D"===r?t:"buffer"===r||"storageBuffer"===r||"indirectStorageBuffer"===r?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=mw[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(d("WebGPURenderer: Atomic operations are only supported in compute shaders."),Ws.READ_WRITE):Ws.READ_ONLY:e.access}getStorageAccess(e,t){return cw[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,u=o.name,l=this.getBindGroupArray(u,r);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);if("texture"===t||"storageTexture"===t?s=!0===e.value.is3DTexture?new lS(i.name,i.node,o,n):new oS(i.name,i.node,o,n):"cubeTexture"===t?s=new uS(i.name,i.node,o,n):"texture3D"===t&&(s=new lS(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.mipLevel=s.store?e.mipLevel:0,s.setVisibility(pw[r]),!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new YE(`${i.name}_sampler`,i.node,o);e.setVisibility(pw[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?eS:JE)(e,o);n.setVisibility(pw[r]),l.push(n),a=n,i.name=s||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let s=e[u];void 0===s&&(s=new sS(u,o),s.setVisibility(pw[r]),e[u]=s,l.push(s)),a=this.getNodeUniform(i,t),s.addUniform(a)}n.uniformGPU=a}return i}getBuiltin(e,t,r,s=this.shaderStage){const i=this.builtins[s]||(this.builtins[s]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:r}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${s.join(", ")} ) -> ${this.getType(t.type)} {\n${r.vars}\n${r.code}\n`;return r.result&&(i+=`\treturn ${r.result};\n`),i+="\n}\n",i}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],r=this.directives[e];if(void 0!==r)for(const e of r)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],r=this.builtins[e];if(void 0!==r)for(const{name:e,property:s,type:i}of r.values())t.push(`@builtin( ${e} ) ${s} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,r,s){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:r,bufferCount:s}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:r,bufferType:s,bufferCount:i}of this.scopedArrays.values()){const n=this.getType(s);t.push(`var<${r}> ${e}: array< ${n}, ${i} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const r=this.getAttributesArray();for(let e=0,s=r.length;e<s;e++){const s=r[e],i=s.name,n=this.getType(s.type);t.push(`@location( ${e} ) ${i} : ${n}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const r of e.members){const s=e.output?"@location( "+r.index+" ) ":"";let i=this.getType(r.type);r.atomic&&(i="atomic< "+i+" >"),t.push(`\t${s+r.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const r=this.structs[e];if(r.length>0){const e=[];for(const t of r){let r=`struct ${t.name} {\n`;r+=this.getStructMembers(t),r+="\n};",e.push(r)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,r=null){let s=`var ${t} : `;return s+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),s}getVars(e){const t=[],r=this.vars[e];if(void 0!==r)for(const e of r)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];for(let i=0;i<r.length;i++){const n=r[i];if(n.needsInterpolation){let e=`@location( ${i} )`;if(n.interpolationType){const t=null!==n.interpolationSampling?`, ${n.interpolationSampling} )`:" )";e+=` @interpolate( ${n.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(n.type)&&(e+=` @interpolate( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);t.push(`${e} ${n.name} : ${this.getType(n.type)}`)}else"vertex"===e&&!1===s.includes(n)&&s.push(n)}}const r=this.getBuiltins(e);r&&t.push(r);const s=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+s):s}isCustomStruct(e){const t=e.value,r=e.node,s=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==r.structTypeNode,i=r.value&&r.value.array&&"number"==typeof r.value.itemSize&&r.value.array.length>r.value.itemSize;return s&&!i}getUniforms(e){const t=this.uniforms[e],r=[],s=[],i=[],n={};for(const i of t){const t=i.groupNode.name,a=this.bindingsIndexes[t];if("texture"===i.type||"cubeTexture"===i.type||"storageTexture"===i.type||"texture3D"===i.type){const t=i.node.value;let s;!1===this.isUnfilterable(t)&&!0!==i.node.isStorageTextureNode&&(this.isSampleCompare(t)?r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler_comparison;`):r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler;`));let n="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(n="_multisampled"),!0===t.isCubeTexture)s="texture_cube<f32>";else if(!0===t.isDepthTexture)s=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d<f32>`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===i.node.isStorageTextureNode){const r=iw(t),n=this.getStorageAccess(i.node,e),a=i.node.value.is3DTexture,o=i.node.value.isArrayTexture;s=`texture_storage_${a?"3d":"2d"+(o?"_array":"")}<${r}, ${n}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)s="texture_2d_array<f32>";else if(!0===t.is3DTexture||!0===t.isData3DTexture)s="texture_3d<f32>";else{s=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name} : ${s};`)}else if("buffer"===i.type||"storageBuffer"===i.type||"indirectStorageBuffer"===i.type){const t=i.node,r=this.getType(t.getNodeType(this)),n=t.bufferCount,o=n>0&&"buffer"===i.type?", "+n:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(i))s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${u}> ${i.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${o} >`;s.push(this._getWGSLStructBinding(i.name,e,u,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(n[t]||(n[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${i.name} : ${e}`)}}for(const e in n){const t=n[e];i.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=r.join("\n");return a+=s.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1],a=n.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),u=e.name;if(u&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${u}\n`),s+=`${i.code}\n\t`,e===n&&"compute"!==t)if(s+="// result\n\n\t","vertex"===t)s+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(o)r.returnType=a.getNodeType(this),r.structs+="var<private> output : "+r.returnType+";",s+=`return ${i.result};`;else{let e="\t@location(0) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),r.returnType="OutputStruct",r.structs+=this._getWGSLStruct("OutputStruct",e),r.structs+="\nvar<private> output : OutputStruct;",s+=`output.color = ${i.result};\n\n\treturn output;`}}r.flow=s}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getTernary(e,t,r){return`select( ${r}, ${t}, ${e} )`}getType(e){return fw[e]||e}isAvailable(e){let t=gw[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),gw[e]=t),t}_getWGSLMethod(e){return void 0!==bw[e]&&this._include(e),xw[e]}_include(e){const t=bw[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${Tw}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[r,s,i]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${r}, ${s}, ${i} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${r} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${r} * numWorkgroups.x ) * ( ${s} * numWorkgroups.y );\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class vw{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=qA:e.depth&&(t=jA),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,r=e.getRenderTarget();t=r?r.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const r=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:r?1:t,isMSAA:r}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map((e=>this.getTextureFormatGPU(e))):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?kS:e.isLineSegments||e.isMesh&&!0===t.wireframe?zS:e.isLine?$S:e.isMesh?WS:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ie)return BA;if(e===ce)return kA;throw new Error("Unsupported outputType")}}const Nw=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&Nw.set(Float16Array,["float16"]);const Sw=new Map([[Xe,["float16"]]]),Aw=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class Rw{constructor(e){this.backend=e}createAttribute(e,t){const r=this._getBufferAttribute(e),s=this.backend,i=s.get(r);let n=i.buffer;if(void 0===n){const a=s.device;let o=r.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e<o.length;e++)65535===o[e]&&(o[e]=4294967295);if(r.array=o,(r.isStorageBufferAttribute||r.isStorageInstancedBufferAttribute)&&3===r.itemSize){o=new o.constructor(4*r.count);for(let e=0;e<r.count;e++)o.set(r.array.subarray(3*e,3*e+3),4*e);r.itemSize=4,r.array=o,i._force3to4BytesAlignment=!0}const u=o.byteLength,l=u+(4-u%4)%4;n=a.createBuffer({label:r.name,size:l,usage:t,mappedAtCreation:!0}),new o.constructor(n.getMappedRange()).set(o),n.unmap(),i.buffer=n}}updateAttribute(e){const t=this._getBufferAttribute(e),r=this.backend,s=r.device,i=r.get(t),n=r.get(t).buffer;let a=t.array;if(!0===i._force3to4BytesAlignment){a=new a.constructor(4*t.count);for(let e=0;e<t.count;e++)a.set(t.array.subarray(3*e,3*e+3),4*e);t.array=a}const o=this._isTypedArray(a),u=t.updateRanges;if(0===u.length)s.queue.writeBuffer(n,0,a,0);else{const e=o?1:a.BYTES_PER_ELEMENT;for(let t=0,r=u.length;t<r;t++){const r=u[t];let l,d;if(!0===i._force3to4BytesAlignment){l=4*Math.floor(r.start/3)*e,d=4*Math.ceil(r.count/3)*e}else l=r.start*e,d=r.count*e;const c=l*(o?a.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(n,c,a,l,d)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),r=new Map;for(let e=0;e<t.length;e++){const s=t[e],i=s.array.BYTES_PER_ELEMENT,n=this._getBufferAttribute(s);let a=r.get(n);if(void 0===a){let e,t;!0===s.isInterleavedBufferAttribute?(e=s.data.stride*i,t=s.data.isInstancedInterleavedBuffer?qE:jE):(e=s.itemSize*i,t=s.isInstancedBufferAttribute?qE:jE),!1!==s.normalized||s.array.constructor!==Int16Array&&s.array.constructor!==Uint16Array||(e=4),a={arrayStride:e,attributes:[],stepMode:t},r.set(n,a)}const o=this._getVertexFormat(s),u=!0===s.isInterleavedBufferAttribute?s.offset*i:0;a.attributes.push({shaderLocation:e,offset:u,format:o})}return Array.from(r.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,r=t.device,s=t.get(this._getBufferAttribute(e)).buffer,i=s.size,n=r.createBuffer({label:`${e.name}_readback`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder({label:`readback_encoder_${e.name}`});a.copyBufferToBuffer(s,0,n,0,i);const o=a.finish();r.queue.submit([o]),await n.mapAsync(GPUMapMode.READ);const u=n.getMappedRange(),l=new e.array.constructor(u.slice(0));return n.unmap(),l.buffer}_getVertexFormat(t){const{itemSize:r,normalized:s}=t,i=t.array.constructor,n=t.constructor;let a;if(1===r)a=Aw.get(i);else{const e=(Sw.get(n)||Nw.get(i))[s?1:0];if(e){const t=i.BYTES_PER_ELEMENT*r,s=4*Math.floor((t+3)/4)/i.BYTES_PER_ELEMENT;if(s%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");a=`${e}x${s}`}}return a||e("WebGPUAttributeUtils: Vertex format not supported yet."),a}_isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class Ew{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(t){const r=this.backend,s=r.device,i=[];let n=0;for(const s of t.bindings){const t={binding:n++,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const e={};s.isStorageBuffer&&(4&s.visibility&&(s.access===Ws.READ_WRITE||s.access===Ws.WRITE_ONLY)?e.type=EE:e.type=wE),t.buffer=e}else if(s.isSampledTexture&&s.store){const e={};e.format=this.backend.get(s.texture).texture.format;const r=s.access;e.access=r===Ws.READ_WRITE?BE:r===Ws.WRITE_ONLY?CE:ME,s.texture.isArrayTexture?e.viewDimension=zE:s.texture.is3DTexture&&(e.viewDimension=WE),t.storageTexture=e}else if(s.isSampledTexture){const e={},{primarySamples:i}=r.utils.getTextureSampleData(s.texture);if(i>1&&(e.multisampled=!0,s.texture.isDepthTexture||(e.sampleType=IE)),s.texture.isDepthTexture)r.compatibilityMode&&null===s.texture.compareFunction?e.sampleType=IE:e.sampleType=DE;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture){const t=s.texture.type;t===S?e.sampleType=UE:t===N?e.sampleType=VE:t===O&&(this.backend.hasFeature("float32-filterable")?e.sampleType=FE:e.sampleType=IE)}s.isSampledCubeTexture?e.viewDimension=$E:s.texture.isArrayTexture||s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?e.viewDimension=zE:s.isSampledTexture3D&&(e.viewDimension=WE),t.texture=e}else if(s.isSampler){const e={};s.texture.isDepthTexture&&(null!==s.texture.compareFunction?e.type=LE:r.compatibilityMode&&(e.type=PE)),t.sampler=e}else e(`WebGPUBindingUtils: Unsupported binding "${s}".`);i.push(t)}return s.createBindGroupLayout({entries:i})}createBindings(e,t,r,s=0){const{backend:i,bindGroupLayoutCache:n}=this,a=i.get(e);let o,u=n.get(e.bindingsReference);void 0===u&&(u=this.createBindingsLayout(e),n.set(e.bindingsReference,u)),r>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[r]===s&&(o=a.groups[r])),void 0===o&&(o=this.createBindGroup(e,u),r>0&&(a.groups[r]=o,a.versions[r]=s)),a.group=o,a.layout=u}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer;r.queue.writeBuffer(i,0,s,0)}createBindGroupIndex(e,t){const r=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0],n=r.createBuffer({label:"bindingCameraIndex_"+i,size:16,usage:s});r.queue.writeBuffer(n,0,e,0);const a=[{binding:0,resource:{buffer:n}}];return r.createBindGroup({label:"bindGroupCameraIndex_"+i,layout:t,entries:a})}createBindGroup(e,t){const r=this.backend,s=r.device;let i=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=r.get(t);if(void 0===e.buffer){const r=t.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=s.createBuffer({label:"bindingBuffer_"+t.name,size:r,usage:i});e.buffer=n}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=r.get(t);if(void 0===e.buffer){const s=t.attribute;e.buffer=r.get(s).buffer}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isSampledTexture){const e=r.get(t.texture);let a;if(void 0!==e.externalTexture)a=s.importExternalTexture({source:e.externalTexture});else{const r=t.store?1:e.texture.mipLevelCount,s=t.store?t.mipLevel:0;let i=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${r}-${s}`,a=e[i],void 0===a){const n=HE;let o;o=t.isSampledCubeTexture?$E:t.isSampledTexture3D?WE:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?zE:kE,a=e[i]=e.texture.createView({aspect:n,dimension:o,mipLevelCount:r,baseMipLevel:s})}}n.push({binding:i,resource:a})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}}class ww{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(t,r){const{object:s,material:i,geometry:n,pipeline:a}=t,{vertexProgram:o,fragmentProgram:u}=a,l=this.backend,d=l.device,c=l.utils,h=l.get(a),p=[];for(const e of t.getBindings()){const t=l.get(e);p.push(t.layout)}const g=l.attributeUtils.createShaderVertexBuffers(t);let m;i.blending===j||i.blending===He&&!1===i.transparent||(m=this._getBlending(i));let f={};!0===i.stencilWrite&&(f={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const y=this._getColorWriteMask(i),b=[];if(null!==t.context.textures){const e=t.context.textures;for(let t=0;t<e.length;t++){const r=c.getTextureFormatGPU(e[t]);b.push({format:r,blend:m,writeMask:y})}}else{const e=c.getCurrentColorFormat(t.context);b.push({format:e,blend:m,writeMask:y})}const x=l.get(o).module,T=l.get(u).module,_=this._getPrimitiveState(s,n,i),v=this._getDepthCompare(i),N=c.getCurrentDepthStencilFormat(t.context),S=this._getSampleCount(t.context),A={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},x,{buffers:g}),fragment:Object.assign({},T,{targets:b}),primitive:_,multisample:{count:S,alphaToCoverageEnabled:i.alphaToCoverage&&S>1},layout:d.createPipelineLayout({bindGroupLayouts:p})},R={},E=t.context.depth,w=t.context.stencil;if(!0!==E&&!0!==w||(!0===E&&(R.format=N,R.depthWriteEnabled=i.depthWrite,R.depthCompare=v),!0===w&&(R.stencilFront=f,R.stencilBack={},R.stencilReadMask=i.stencilFuncMask,R.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(R.depthBias=i.polygonOffsetUnits,R.depthBiasSlopeScale=i.polygonOffsetFactor,R.depthBiasClamp=0),A.depthStencil=R),d.pushErrorScope("validation"),null===r)h.pipeline=d.createRenderPipeline(A),d.popErrorScope().then((t=>{null!==t&&(h.error=!0,e(t.message))}));else{const t=new Promise((async t=>{try{h.pipeline=await d.createRenderPipelineAsync(A)}catch(e){}const r=await d.popErrorScope();null!==r&&(h.error=!0,e(r.message)),t()}));r.push(t)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:s.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(a)}createComputePipeline(e,t){const r=this.backend,s=r.device,i=r.get(e.computeProgram).module,n=r.get(e),a=[];for(const e of t){const t=r.get(e);a.push(t.layout)}n.pipeline=s.createComputePipeline({compute:i,layout:s.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(t){let r,s;const i=t.blending,n=t.blendSrc,a=t.blendDst,o=t.blendEquation;if(i===Je){const e=null!==t.blendSrcAlpha?t.blendSrcAlpha:n,i=null!==t.blendDstAlpha?t.blendDstAlpha:a,u=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;r={srcFactor:this._getBlendFactor(n),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(e),dstFactor:this._getBlendFactor(i),operation:this._getBlendOperation(u)}}else{const n=(e,t,i,n)=>{r={srcFactor:e,dstFactor:t,operation:hE},s={srcFactor:i,dstFactor:n,operation:hE}};if(t.premultipliedAlpha)switch(i){case He:n(eE,iE,eE,iE);break;case Ut:n(eE,eE,eE,eE);break;case Dt:n(JR,rE,JR,eE);break;case It:n(nE,iE,JR,eE)}else switch(i){case He:n(sE,iE,eE,iE);break;case Ut:n(sE,eE,eE,eE);break;case Dt:e("WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case It:e("WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==r&&void 0!==s)return{color:r,alpha:s};e("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(t){let r;switch(t){case tt:r=JR;break;case vt:r=eE;break;case Nt:r=tE;break;case wt:r=rE;break;case St:r=sE;break;case Ct:r=iE;break;case Rt:r=nE;break;case Mt:r=aE;break;case Et:r=oE;break;case Bt:r=uE;break;case At:r=lE;break;case 211:r=dE;break;case 212:r=cE;break;default:e("WebGPURenderer: Blend factor not supported.",t)}return r}_getStencilCompare(t){let r;const s=t.stencilFunc;switch(s){case jr:r=jS;break;case Hr:r=JS;break;case Wr:r=qS;break;case $r:r=KS;break;case zr:r=XS;break;case kr:r=ZS;break;case Gr:r=YS;break;case Or:r=QS;break;default:e("WebGPURenderer: Invalid stencil function.",s)}return r}_getStencilOperation(t){let r;switch(t){case es:r=xE;break;case Jr:r=TE;break;case Zr:r=_E;break;case Qr:r=vE;break;case Yr:r=NE;break;case Kr:r=SE;break;case Xr:r=AE;break;case qr:r=RE;break;default:e("WebGPURenderer: Invalid stencil operation.",r)}return r}_getBlendOperation(t){let r;switch(t){case et:r=hE;break;case Tt:r=pE;break;case _t:r=gE;break;case rs:r=mE;break;case ts:r=fE;break;default:e("WebGPUPipelineUtils: Blend equation not supported.",t)}return r}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?oA:uA);let n=r.side===w;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),s.frontFace=!0===n?iA:sA,s.cullMode=r.side===C?nA:aA,s}_getColorWriteMask(e){return!0===e.colorWrite?bE:yE}_getDepthCompare(t){let r;if(!1===t.depthTest)r=JS;else{const s=t.depthFunc;switch(s){case Ht:r=jS;break;case Wt:r=JS;break;case $t:r=qS;break;case zt:r=KS;break;case kt:r=XS;break;case Gt:r=ZS;break;case Ot:r=YS;break;case Vt:r=QS;break;default:e("WebGPUPipelineUtils: Invalid depth function.",s)}}return r}}class Cw extends VS{constructor(e,t,r=2048){super(r),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const s=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return v(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,r=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const s=this.device.createCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),s.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,r);const i=s.finish();if(this.device.queue.submit([i]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,r),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,r)),a={},o=[];for(const[t,r]of e){const e=t.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===o.includes(s)&&o.push(s),void 0===a[s]&&(a[s]=0);const i=n[r],u=n[r+1],l=Number(u-i)/1e6;this.timestamps.set(t,l),a[s]+=l}const u=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=u,this.frames=o,u}catch(e){return e("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){e("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){e("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class Mw extends TS{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new vw(this),this.attributeUtils=new Rw(this),this.bindingUtils=new Ew(this),this.pipelineUtils=new ww(this),this.textureUtils=new sw(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},s="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===s)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(XE),n=[];for(const e of i)s.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};r=await s.requestDevice(a)}else r=t.device;r.lost.then((t=>{const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)})),this.device=r,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(XE.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let r=t.context;if(void 0===r){const s=this.parameters;r=!0===e.isDefaultCanvasTarget&&void 0!==s.context?s.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${Ke} webgpu`);const i=s.alpha?"premultiplied":"opaque",n=s.outputType===ce?"extended":"standard";r.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:n}}),t.context=r}return r}get coordinateSystem(){return h}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),r=this.get(t),s=e.currentSamples;let i=r.descriptor;if(void 0===i||r.samples!==s){i={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(i.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=i.colorAttachments[0];s>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,r.descriptor=i,r.samples=s}const n=i.colorAttachments[0];return s>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),i}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;void 0!==i&&s.width===r.width&&s.height===r.height&&s.samples===r.samples||(i={},s.descriptors=i);const n=e.getCacheKey();let a=i[n];if(void 0===a){const t=e.textures,o=[];let u;const l=this._isRenderCameraDepthArray(e);for(let s=0;s<t.length;s++){const i=this.get(t[s]),n={label:`colorAttachment_${s}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:kE};if(r.isRenderTarget3D)u=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=WE,n.depthOrArrayLayers=t[s].image.depth;else if(r.isRenderTarget&&t[s].image.depth>1)if(!0===l){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...n,baseArrayLayer:e,arrayLayerCount:1,dimension:kE},r=i.texture.createView(t);o.push({view:r,resolveTarget:void 0,depthSlice:void 0})}}else n.dimension=zE,n.depthOrArrayLayers=t[s].image.depth;if(!0!==l){const e=i.texture.createView(n);let t,r;void 0!==i.msaaTexture?(t=i.msaaTexture.createView(),r=e):(t=e,r=void 0),o.push({view:t,resolveTarget:r,depthSlice:u})}}if(a={textureViews:o},e.depth){const t=this.get(e.depthTexture),r={};e.depthTexture.isArrayTexture&&(r.dimension=kE,r.arrayLayerCount=1,r.baseArrayLayer=e.activeCubeFace),a.depthStencilView=t.texture.createView(r)}i[n]=a,s.width=r.width,s.height=r.height,s.samples=r.samples,s.activeMipmapLevel=e.activeMipmapLevel,s.activeCubeFace=e.activeCubeFace}const o={colorAttachments:[]};for(let e=0;e<a.textureViews.length;e++){const r=a.textureViews[e];let s={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(s=t.clearValue),o.colorAttachments.push({view:r.view,depthSlice:r.depthSlice,resolveTarget:r.resolveTarget,loadOp:t.loadOp||tA,storeOp:t.storeOp||eA,clearValue:s})}return a.depthStencilView&&(o.depthStencilAttachment={view:a.depthStencilView}),o}beginRender(e){const t=this.get(e),r=this.device,s=e.occlusionQueryCount;let i,n;s>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=r.createQuerySet({type:"occlusion",count:s,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(s),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:tA}),this.initTimestampQuery(bt.RENDER,this.getTimestampUID(e),n),n.occlusionQuerySet=i;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let r=0;r<t.length;r++){const s=t[r];e.clearColor?(s.clearValue=0===r?e.clearColorValue:{r:0,g:0,b:0,a:1},s.loadOp=rA):s.loadOp=tA,s.storeOp=eA}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=rA):t.loadOp=tA,t.storeOp=eA}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=rA):a.depthLoadOp=tA,a.depthStoreOp=eA),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=rA):a.stencilLoadOp=tA,a.stencilStoreOp=eA);const o=r.createCommandEncoder({label:"renderContext_"+e.id});if(!0===this._isRenderCameraDepthArray(e)){const r=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===r.length?this._updateDepthLayerDescriptors(e,t,r):this._createDepthLayerDescriptors(e,t,n,r),t.bundleEncoders=[],t.bundleSets=[];for(let s=0;s<r.length;s++){const r=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+s),i={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(r),t.bundleSets.push(i)}t.currentPass=null}else{const r=o.beginRenderPass(n);t.currentPass=r,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=n,t.encoder=o,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,r,s){const i=r.depthStencilAttachment;t.layerDescriptors=[];const n=this.get(e.depthTexture);n.viewCache||(n.viewCache=[]);for(let a=0;a<s.length;a++){const s={...r,colorAttachments:[{...r.colorAttachments[0],view:r.colorAttachments[a].view}]};if(r.depthStencilAttachment){const t=a;n.viewCache[t]||(n.viewCache[t]=n.texture.createView({dimension:kE,baseArrayLayer:a,arrayLayerCount:1})),s.depthStencilAttachment={view:n.viewCache[t],depthLoadOp:i.depthLoadOp||rA,depthStoreOp:i.depthStoreOp||eA,depthClearValue:i.depthClearValue||1},e.stencil&&(s.depthStencilAttachment.stencilLoadOp=i.stencilLoadOp,s.depthStencilAttachment.stencilStoreOp=i.stencilStoreOp,s.depthStencilAttachment.stencilClearValue=i.stencilClearValue)}else s.depthStencilAttachment={...i};t.layerDescriptors.push(s)}}_updateDepthLayerDescriptors(e,t,r){for(let s=0;s<r.length;s++){const r=t.layerDescriptors[s];if(r.depthStencilAttachment){const t=r.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=rA):t.depthLoadOp=tA),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=rA):t.stencilLoadOp=tA)}}}finishRender(e){const t=this.get(e),r=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),r>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const r=[];for(let e=0;e<t.bundleEncoders.length;e++){const s=t.bundleEncoders[e];r.push(s.finish())}for(let i=0;i<t.layerDescriptors.length;i++)if(i<r.length){const n=t.layerDescriptors[i],a=s.beginRenderPass(n);if(e.viewport){const{x:t,y:r,width:s,height:i,minDepth:n,maxDepth:o}=e.viewportValue;a.setViewport(t,r,s,i,n,o)}if(e.scissor){const{x:t,y:r,width:s,height:i}=e.scissorValue;a.setScissorRect(t,r,s,i)}a.executeBundles([r[i]]),a.end()}}else t.currentPass&&t.currentPass.end();if(r>0){const s=8*r;let i=this.occludedResolveCache.get(s);void 0===i&&(i=this.device.createBuffer({size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(s,i));const n=this.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,r,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,s),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;e<t.length;e++){const r=t[e];!0===r.generateMipmaps&&this.textureUtils.generateMipmaps(r)}}}isOccluded(e,t){const r=this.get(e);return r.occluded&&r.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:r,currentOcclusionQueryObjects:s}=t;if(r&&s){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await r.mapAsync(GPUMapMode.READ);const i=r.getMappedRange(),n=new BigUint64Array(i);for(let t=0;t<s.length;t++)n[t]===BigInt(0)&&e.add(s[t]);r.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:r,y:s,width:i,height:n,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(r,s,i,n,a,o)}updateScissor(e){const{currentPass:t}=this.get(e),{x:r,y:s,width:i,height:n}=e.scissorValue;t.setScissorRect(r,s,i,n)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,r,s=null){const i=this.device,n=this.renderer;let a,o,u,l,d=[];if(e){const e=this.getClearColor();o={r:e.r,g:e.g,b:e.b,a:e.a}}if(null===s){u=n.depth,l=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){d=t.colorAttachments;const e=d[0];e.clearValue=o,e.loadOp=rA,e.storeOp=eA}(u||l)&&(a=t.depthStencilAttachment)}else{u=s.depth,l=s.stencil;const i={loadOp:e?rA:tA,clearValue:e?o:void 0};u&&(i.depthLoadOp=t?rA:tA,i.depthClearValue=t?n.getClearDepth():void 0,i.depthStoreOp=eA),l&&(i.stencilLoadOp=r?rA:tA,i.stencilClearValue=r?n.getClearStencil():void 0,i.stencilStoreOp=eA);const c=this._getRenderPassDescriptor(s,i);d=c.colorAttachments,a=c.depthStencilAttachment}u&&a&&(t?(a.depthLoadOp=rA,a.depthClearValue=n.getClearDepth(),a.depthStoreOp=eA):(a.depthLoadOp=tA,a.depthStoreOp=eA)),l&&a&&(r?(a.stencilLoadOp=rA,a.stencilClearValue=n.getClearStencil(),a.stencilStoreOp=eA):(a.stencilLoadOp=tA,a.stencilStoreOp=eA));const c=i.createCommandEncoder({label:"clear"});c.beginRenderPass({colorAttachments:d,depthStencilAttachment:a}).end(),i.queue.submit([c.finish()])}beginCompute(e){const t=this.get(e),r={label:"computeGroup_"+e.id};this.initTimestampQuery(bt.COMPUTE,this.getTimestampUID(e),r),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(r)}compute(e,t,r,s,i=null){const n=this.get(t),{passEncoderGPU:a}=this.get(e),o=this.get(s).pipeline;this.pipelineUtils.setPipeline(a,o);for(let e=0,t=r.length;e<t;e++){const t=r[e],s=this.get(t);a.setBindGroup(e,s.group)}if(null===i&&(i=t.count),i&&"object"==typeof i&&i.isIndirectStorageBufferAttribute){const e=this.get(i).buffer;a.dispatchWorkgroupsIndirect(e,0)}else{if("number"==typeof i){const e=i;if(void 0===n.dispatchSize||n.count!==e){n.dispatchSize=[0,1,1],n.count=e;const r=t.workgroupSize;let s=r[0];for(let e=1;e<r.length;e++)s*=r[e];const a=Math.ceil(e/s),o=this.device.limits.maxComputeWorkgroupsPerDimension;i=[a,1,1],a>o&&(i[0]=Math.min(a,o),i[1]=Math.ceil(a/o)),n.dispatchSize=i}i=n.dispatchSize}a.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:r,material:s,context:i,pipeline:n}=e,a=e.getBindings(),o=this.get(i),u=this.get(n),l=u.pipeline;if(!0===u.error)return;const d=e.getIndex(),c=null!==d,h=e.getDrawParameters();if(null===h)return;const p=(t,r)=>{this.pipelineUtils.setPipeline(t,l),r.pipeline=l;const n=r.bindingGroups;for(let e=0,r=a.length;e<r;e++){const r=a[e],s=this.get(r);n[r.index]!==r.id&&(t.setBindGroup(r.index,s.group),n[r.index]=r.id)}if(!0===c&&r.index!==d){const e=this.get(d).buffer,s=d.array instanceof Uint16Array?oA:uA;t.setIndexBuffer(e,s),r.index=d}const u=e.getVertexBuffers();for(let e=0,s=u.length;e<s;e++){const s=u[e];if(r.attributes[e]!==s){const i=this.get(s).buffer;t.setVertexBuffer(e,i),r.attributes[e]=s}}!0===i.stencil&&!0===s.stencilWrite&&o.currentStencilRef!==s.stencilRef&&(t.setStencilReference(s.stencilRef),o.currentStencilRef=s.stencilRef)},g=(s,i)=>{if(p(s,i),!0===r.isBatchedMesh){const e=r._multiDrawStarts,i=r._multiDrawCounts,n=r._multiDrawCount,a=r._multiDrawInstances;null!==a&&v("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o<n;o++){const n=a?a[o]:1,u=n>1?0:o;!0===c?s.drawIndexed(i[o],n,e[o]/d.array.BYTES_PER_ELEMENT,0,u):s.draw(i[o],n,e[o],u),t.update(r,i[o],n)}}else if(!0===c){const{vertexCount:i,instanceCount:n,firstVertex:a}=h,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndexedIndirect(e,0)}else s.drawIndexed(i,n,a,0,0);t.update(r,i,n)}else{const{vertexCount:i,instanceCount:n,firstVertex:a}=h,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndirect(e,0)}else s.draw(i,n,a,0);t.update(r,i,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),s=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==s.length){const e=this.get(n),r=[],i=new Uint32Array([0,0,0,0]);for(let t=0,n=s.length;t<n;t++){i[0]=t;const s=this.bindingUtils.createBindGroupIndex(i,e.layout);r.push(s)}t.indexesGPU=r}const a=this.renderer.getPixelRatio();for(let e=0,u=s.length;e<u;e++){const u=s[e];if(r.layers.test(u.layers)){const r=u.viewport;let s=o.currentPass,l=o.currentSets;if(o.bundleEncoders){s=o.bundleEncoders[e],l=o.bundleSets[e]}r&&s.setViewport(Math.floor(r.x*a),Math.floor(r.y*a),Math.floor(r.width*a),Math.floor(r.height*a),i.viewportValue.minDepth,i.viewportValue.maxDepth),n&&t.indexesGPU&&(s.setBindGroup(n.index,t.indexesGPU[e]),l.bindingGroups[n.index]=n.id),g(s,l)}}}else if(o.currentPass){if(void 0!==o.occlusionQuerySet){const e=o.lastOcclusionObject;e!==r&&(null!==e&&!0===e.occlusionTest&&(o.currentPass.endOcclusionQuery(),o.occlusionQueryIndex++),!0===r.occlusionTest&&(o.currentPass.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=r),o.lastOcclusionObject=r)}g(o.currentPass,o.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:r,material:s}=e,i=this.utils,n=i.getSampleCountRenderContext(e.context),a=i.getCurrentColorSpace(e.context),o=i.getCurrentColorFormat(e.context),u=i.getCurrentDepthStencilFormat(e.context),l=i.getPrimitiveTopology(r,s);let d=!1;return t.material===s&&t.materialVersion===s.version&&t.transparent===s.transparent&&t.blending===s.blending&&t.premultipliedAlpha===s.premultipliedAlpha&&t.blendSrc===s.blendSrc&&t.blendDst===s.blendDst&&t.blendEquation===s.blendEquation&&t.blendSrcAlpha===s.blendSrcAlpha&&t.blendDstAlpha===s.blendDstAlpha&&t.blendEquationAlpha===s.blendEquationAlpha&&t.colorWrite===s.colorWrite&&t.depthWrite===s.depthWrite&&t.depthTest===s.depthTest&&t.depthFunc===s.depthFunc&&t.stencilWrite===s.stencilWrite&&t.stencilFunc===s.stencilFunc&&t.stencilFail===s.stencilFail&&t.stencilZFail===s.stencilZFail&&t.stencilZPass===s.stencilZPass&&t.stencilFuncMask===s.stencilFuncMask&&t.stencilWriteMask===s.stencilWriteMask&&t.side===s.side&&t.alphaToCoverage===s.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===u&&t.primitiveTopology===l&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=s,t.materialVersion=s.version,t.transparent=s.transparent,t.blending=s.blending,t.premultipliedAlpha=s.premultipliedAlpha,t.blendSrc=s.blendSrc,t.blendDst=s.blendDst,t.blendEquation=s.blendEquation,t.blendSrcAlpha=s.blendSrcAlpha,t.blendDstAlpha=s.blendDstAlpha,t.blendEquationAlpha=s.blendEquationAlpha,t.colorWrite=s.colorWrite,t.depthWrite=s.depthWrite,t.depthTest=s.depthTest,t.depthFunc=s.depthFunc,t.stencilWrite=s.stencilWrite,t.stencilFunc=s.stencilFunc,t.stencilFail=s.stencilFail,t.stencilZFail=s.stencilZFail,t.stencilZPass=s.stencilZPass,t.stencilFuncMask=s.stencilFuncMask,t.stencilWriteMask=s.stencilWriteMask,t.side=s.side,t.alphaToCoverage=s.alphaToCoverage,t.sampleCount=n,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=u,t.primitiveTopology=l,t.clippingContextCacheKey=e.clippingContextCacheKey,d=!0),d}getRenderCacheKey(e){const{object:t,material:r}=e,s=this.utils,i=e.context,n=t.isMesh&&t.matrixWorld.determinant()<0;return[r.transparent,r.blending,r.premultipliedAlpha,r.blendSrc,r.blendDst,r.blendEquation,r.blendSrcAlpha,r.blendDstAlpha,r.blendEquationAlpha,r.colorWrite,r.depthWrite,r.depthTest,r.depthFunc,r.stencilWrite,r.stencilFunc,r.stencilFail,r.stencilZFail,r.stencilZPass,r.stencilFuncMask,r.stencilWriteMask,r.side,n,s.getSampleCountRenderContext(i),s.getCurrentColorSpace(i),s.getCurrentColorFormat(i),s.getCurrentDepthStencilFormat(i),s.getPrimitiveTopology(t,r),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,r,s,i,n){return this.textureUtils.copyTextureToBuffer(e,t,r,s,i,n)}initTimestampQuery(e,t,r){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new Cw(this.device,e,2048));const s=this.timestampQueryPool[e],i=s.allocateQueriesForContext(t);r.timestampWrites={querySet:s.querySet,beginningOfPassWriteIndex:i,endOfPassWriteIndex:i+1}}createNodeBuilder(e,t){return new _w(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage+(""!==e.name?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const r=this.get(e),s=r.currentPass.finish();this.get(t).bundleGPU=s,r.currentSets=r._currentSets,r.currentPass=r._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,r,s){this.bindingUtils.createBindings(e,t,r,s)}updateBindings(e,t,r,s){this.bindingUtils.createBindings(e,t,r,s)}updateBinding(e){this.bindingUtils.updateBinding(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}getMaxAnisotropy(){return 16}hasFeature(e){return void 0!==KE[e]&&(e=KE[e]),this.device.features.has(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){let a=0,o=0,u=0,l=0,d=0,c=0,h=e.image.width,p=e.image.height,g=1;null!==r&&(!0===r.isBox3?(l=r.min.x,d=r.min.y,c=r.min.z,h=r.max.x-r.min.x,p=r.max.y-r.min.y,g=r.max.z-r.min.z):(l=r.min.x,d=r.min.y,h=r.max.x-r.min.x,p=r.max.y-r.min.y,g=1)),null!==s&&(a=s.x,o=s.y,u=s.z||0);const m=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),f=this.get(e).texture,y=this.get(t).texture;m.copyTextureToTexture({texture:f,mipLevel:i,origin:{x:l,y:d,z:c}},{texture:y,mipLevel:n,origin:{x:a,y:o,z:u}},[h,p,g]),this.device.queue.submit([m.finish()]),0===n&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(t,r,s){const i=this.get(r);let n=null;n=r.renderTarget?t.isDepthTexture?this.get(r.depthTexture).texture:this.get(r.textures[0]).texture:t.isDepthTexture?this.textureUtils.getDepthBuffer(r.depth,r.stencil):this.context.getCurrentTexture();const a=this.get(t).texture;if(n.format!==a.format)return void e("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",n.format,a.format);let o;if(i.currentPass?(i.currentPass.end(),o=i.encoder):o=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+t.id}),o.copyTextureToTexture({texture:n,origin:[s.x,s.y,0]},{texture:a},[s.z,s.w]),t.generateMipmaps&&this.textureUtils.generateMipmaps(t,o),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=tA;r.depth&&(e.depthStencilAttachment.depthLoadOp=tA),r.stencil&&(e.depthStencilAttachment.stencilLoadOp=tA),i.currentPass=o.beginRenderPass(e),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},r.viewport&&this.updateViewport(r),r.scissor&&this.updateScissor(r)}else this.device.queue.submit([o.finish()])}dispose(){this.textureUtils.dispose()}}class Bw extends ss{constructor(e,t,r,s,i,n){super(e,t,r,s,i,n),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class Pw extends ss{constructor(e,t,r,s,i,n){super(e,t,r,s,i,n),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class Lw extends EN{constructor(){super(),this.addMaterial(cg,"MeshPhongMaterial"),this.addMaterial(nf,"MeshStandardMaterial"),this.addMaterial(of,"MeshPhysicalMaterial"),this.addMaterial(pf,"MeshToonMaterial"),this.addMaterial(rg,"MeshBasicMaterial"),this.addMaterial(lg,"MeshLambertMaterial"),this.addMaterial($p,"MeshNormalMaterial"),this.addMaterial(ff,"MeshMatcapMaterial"),this.addMaterial(Lp,"LineBasicMaterial"),this.addMaterial(Ip,"LineDashedMaterial"),this.addMaterial(Nf,"PointsMaterial"),this.addMaterial(Tf,"SpriteMaterial"),this.addMaterial(Ef,"ShadowMaterial"),this.addLight(b_,is),this.addLight(Jv,ns),this.addLight(sN,as),this.addLight(iN,ss),this.addLight(uN,os),this.addLight(lN,us),this.addLight(dN,ls),this.addLight(nN,Bw),this.addLight(oN,Pw),this.addToneMapping(nx,ds),this.addToneMapping(ax,cs),this.addToneMapping(ox,hs),this.addToneMapping(lx,ps),this.addToneMapping(px,gs),this.addToneMapping(gx,ms)}}class Fw extends KN{constructor(e={}){let t;e.forceWebGL?t=GS:(t=Mw,e.getFallback=()=>(d("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new GS(e)));super(new t(e),e),this.library=new Lw,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class Iw extends fs{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class Dw{constructor(e,t=mn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new Bp;r.name="PostProcessing",this._quadMesh=new gb(r),this._quadMesh.name="Post-Processing",this._context=null}render(){const e=this.renderer;this._update(),null!==this._context.onBeforePostProcessing&&this._context.onBeforePostProcessing();const t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=m,e.outputColorSpace=p.workingColorSpace;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r,null!==this._context.onAfterPostProcessing&&this._context.onAfterPostProcessing()}get context(){return this._context}dispose(){this._quadMesh.material.dispose()}_update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace,s={postProcessing:this,onBeforePostProcessing:null,onAfterPostProcessing:null};let i=this.outputNode;!0===this.outputColorTransform?(i=i.context(s),i=rl(i,t,r)):(s.toneMapping=t,s.outputColorSpace=r,i=i.context(s)),this._context=s,this._quadMesh.material.fragmentNode=i,this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){v('PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.renderer.init(),this.render()}}class Uw extends R{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=J,this.minFilter=J,this.isStorageTexture=!0,this.mipmapsAutoUpdate=!0}setSize(e,t){this.image.width===e&&this.image.height===t||(this.image.width=e,this.image.height=t,this.dispose())}}class Vw extends R{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!1,this.image={width:e,height:t,depth:r},this.magFilter=J,this.minFilter=J,this.wrapR=he,this.isStorageTexture=!0,this.is3DTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class Ow extends R{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!0,this.image={width:e,height:t,depth:r},this.magFilter=J,this.minFilter=J,this.isStorageTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class Gw extends Rb{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class kw extends ys{constructor(e){super(e),this.textures={},this.nodes={}}load(t,r,s,i){const n=new bs(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(t,(s=>{try{r(this.parse(JSON.parse(s)))}catch(r){i?i(r):e(r),this.manager.itemError(t)}}),s,i)}parseNodes(e){const t={};if(void 0!==e){for(const r of e){const{uuid:e,type:s}=r;t[e]=this.createNodeFromType(s),t[e].uuid=e}const r={nodes:t,textures:this.textures};for(const s of e){s.meta=r;t[s.uuid].deserialize(s),delete s.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const r={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=r,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}setNodes(e){return this.nodes=e,this}createNodeFromType(t){return void 0===this.nodes[t]?(e("NodeLoader: Node type not found:",t),rn()):ki(new this.nodes[t])}}class zw extends xs{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),r=this.nodes,s=e.inputNodes;for(const e in s){const i=s[e];t[e]=r[i]}return t}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}createMaterialFromType(e){const t=this.nodeMaterials[e];return void 0!==t?new t:super.createMaterialFromType(e)}}class $w extends Ts{constructor(e){super(e),this.nodes={},this.nodeMaterials={},this._nodesJSON=null}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}parse(e,t){this._nodesJSON=e.nodes;const r=super.parse(e,t);return this._nodesJSON=null,r}parseNodes(e,t){if(void 0!==e){const r=new kw;return r.setNodes(this.nodes),r.setTextures(t),r.parseNodes(e)}return{}}parseMaterials(e,t){const r={};if(void 0!==e){const s=this.parseNodes(this._nodesJSON,t),i=new zw;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t<s;t++){const s=e[t];r[s.uuid]=i.parse(s)}}return r}}class Ww extends fs{constructor(){super(),this.isClippingGroup=!0,this.clippingPlanes=[],this.enabled=!0,this.clipIntersection=!1,this.clipShadows=!1}}export{ps as ACESFilmicToneMapping,Zh as AONode,et as AddEquation,se as AddOperation,Ut as AdditiveBlending,gs as AgXToneMapping,Yt as AlphaFormat,Br as AlwaysCompare,Wt as AlwaysDepth,Hr as AlwaysStencilFunc,os as AmbientLight,uN as AmbientLightNode,m_ as AnalyticLightNode,Ye as ArrayCamera,Zs as ArrayElementNode,la as ArrayNode,ca as AssignNode,ul as AttributeNode,w as BackSide,Qp as BasicEnvironmentNode,$e as BasicShadowMap,Fh as BatchNode,Cy as BitcastNode,Y as BoxGeometry,ge as BufferAttribute,Du as BufferAttributeNode,pe as BufferGeometry,Tl as BufferNode,Fc as BumpMapNode,Iw as BundleGroup,qu as BypassNode,ft as ByteType,Be as Camera,kN as CanvasTarget,hs as CineonToneMapping,he as ClampToEdgeWrapping,Ww as ClippingGroup,mx as CodeNode,t as Color,p as ColorManagement,Ru as ColorSpaceNode,ku as ComputeNode,ui as ConstNode,uu as ContextNode,Js as ConvertNode,ee as CubeCamera,B as CubeReflectionMapping,P as CubeRefractionMapping,L as CubeTexture,Kd as CubeTextureNode,fe as CubeUVReflectionMapping,Lt as CullFaceBack,Ft as CullFaceFront,Pt as CullFaceNone,Je as CustomBlending,rt as CylinderGeometry,V as DataArrayTexture,le as DataTexture,sl as DebugNode,Kr as DecrementStencilOp,qr as DecrementWrapStencilOp,Le as DepthFormat,Pe as DepthStencilFormat,z as DepthTexture,ns as DirectionalLight,Jv as DirectionalLightNode,C as DoubleSide,Et as DstAlphaFactor,Rt as DstColorFactor,b as DynamicDrawUsage,ef as EnvironmentNode,Lr as EqualCompare,kt as EqualDepth,zr as EqualStencilFunc,te as EquirectangularReflectionMapping,re as EquirectangularRefractionMapping,M as Euler,u as EventDispatcher,Nb as EventNode,Zu as ExpressionNode,bs as FileLoader,Xe as Float16BufferAttribute,Oe as Float32BufferAttribute,O as FloatType,G as FramebufferTexture,vd as FrontFacingNode,Ze as FrontSide,ot as Frustum,ut as FrustumArray,pa as FunctionCallNode,yx as FunctionNode,Dy as FunctionOverloadingNode,yN as GLSLNodeParser,Ir as GreaterCompare,Ot as GreaterDepth,Fr as GreaterEqualCompare,Gt as GreaterEqualDepth,kr as GreaterEqualStencilFunc,Gr as GreaterStencilFunc,fs as Group,ce as HalfFloatType,us as HemisphereLight,lN as HemisphereLightNode,Bw as IESSpotLight,nN as IESSpotLightNode,Yr as IncrementStencilOp,Xr as IncrementWrapStencilOp,Nh as IndexNode,Gw as IndirectStorageBufferAttribute,nl as InspectorBase,Mh as InstanceNode,U as InstancedBufferAttribute,D as InstancedInterleavedBuffer,Ph as InstancedMeshNode,S as IntType,y as InterleavedBuffer,x as InterleavedBufferAttribute,Qr as InvertStencilOp,tp as IrradianceNode,Wu as IsolateNode,ti as JoinNode,es as KeepStencilOp,ze as LessCompare,$t as LessDepth,Pr as LessEqualCompare,zt as LessEqualDepth,$r as LessEqualStencilFunc,Wr as LessStencilFunc,ls as LightProbe,dN as LightProbeNode,MN as Lighting,Jh as LightingContextNode,Jp as LightingModel,Qh as LightingNode,MT as LightsNode,Gp as Line2NodeMaterial,W as LineBasicMaterial,Lp as LineBasicNodeMaterial,H as LineDashedMaterial,Ip as LineDashedNodeMaterial,J as LinearFilter,Ve as LinearMipMapLinearFilter,k as LinearMipmapLinearFilter,je as LinearMipmapNearestFilter,xe as LinearSRGBColorSpace,ds as LinearToneMapping,Ur as LinearTransfer,ys as Loader,$h as LoopNode,Ey as MRTNode,$ as Material,xs as MaterialLoader,Uc as MaterialNode,rc as MaterialReferenceNode,l as MathUtils,n as Matrix2,a as Matrix3,o as Matrix4,ts as MaxEquation,pl as MaxMipLevelNode,li as MemberNode,Q as Mesh,ae as MeshBasicMaterial,rg as MeshBasicNodeMaterial,oe as MeshLambertMaterial,lg as MeshLambertNodeMaterial,Se as MeshMatcapMaterial,ff as MeshMatcapNodeMaterial,X as MeshNormalMaterial,$p as MeshNormalNodeMaterial,ue as MeshPhongMaterial,cg as MeshPhongNodeMaterial,ve as MeshPhysicalMaterial,of as MeshPhysicalNodeMaterial,lf as MeshSSSNodeMaterial,_e as MeshStandardMaterial,nf as MeshStandardNodeMaterial,Ne as MeshToonMaterial,pf as MeshToonNodeMaterial,rs as MinEquation,wr as MirroredRepeatWrapping,ie as MixOperation,rd as ModelNode,Kh as MorphNode,It as MultiplyBlending,ne as MultiplyOperation,A as NearestFilter,qe as NearestMipmapLinearFilter,Cr as NearestMipmapNearestFilter,ms as NeutralToneMapping,Mr as NeverCompare,Ht as NeverDepth,jr as NeverStencilFunc,j as NoBlending,T as NoColorSpace,m as NoToneMapping,Qs as Node,Ws as NodeAccess,_v as NodeAttribute,Yv as NodeBuilder,Ev as NodeCache,Av as NodeCode,Qv as NodeFrame,Zv as NodeFunctionInput,kw as NodeLoader,Bp as NodeMaterial,zw as NodeMaterialLoader,Ns as NodeMaterialObserver,$w as NodeObjectLoader,ks as NodeShaderStage,$s as NodeType,vv as NodeUniform,zs as NodeUpdateType,Gs as NodeUtils,Nv as NodeVar,Sv as NodeVarying,He as NormalBlending,Mc as NormalMapNode,Dr as NotEqualCompare,Vt as NotEqualDepth,Or as NotEqualStencilFunc,Ue as Object3D,Kl as Object3DNode,Ts as ObjectLoader,I as ObjectSpaceNormalMap,vt as OneFactor,Bt as OneMinusDstAlphaFactor,Mt as OneMinusDstColorFactor,Ct as OneMinusSrcAlphaFactor,wt as OneMinusSrcColorFactor,ye as OrthographicCamera,Sy as OutputStructNode,at as PCFShadowMap,$m as PMREMGenerator,Qm as PMREMNode,xy as ParameterNode,sx as PassNode,Te as PerspectiveCamera,og as PhongLightingModel,nm as PhysicalLightingModel,De as Plane,Qe as PlaneGeometry,is as PointLight,b_ as PointLightNode,Eb as PointUVNode,Re as PointsMaterial,Nf as PointsNodeMaterial,Dw as PostProcessing,Zb as PosterizeNode,Pw as ProjectorLight,oN as ProjectorLightNode,Sn as PropertyNode,gb as QuadMesh,nt as Quaternion,Ar as RED_GREEN_RGTC2_Format,Nr as RED_RGTC1_Format,Ke as REVISION,be as RGBAFormat,gt as RGBAIntegerFormat,xr as RGBA_ASTC_10x10_Format,fr as RGBA_ASTC_10x5_Format,yr as RGBA_ASTC_10x6_Format,br as RGBA_ASTC_10x8_Format,Tr as RGBA_ASTC_12x10_Format,_r as RGBA_ASTC_12x12_Format,ur as RGBA_ASTC_4x4_Format,lr as RGBA_ASTC_5x4_Format,dr as RGBA_ASTC_5x5_Format,cr as RGBA_ASTC_6x5_Format,hr as RGBA_ASTC_6x6_Format,pr as RGBA_ASTC_8x5_Format,gr as RGBA_ASTC_8x6_Format,mr as RGBA_ASTC_8x8_Format,vr as RGBA_BPTC_Format,or as RGBA_ETC2_EAC_Format,ir as RGBA_PVRTC_2BPPV1_Format,sr as RGBA_PVRTC_4BPPV1_Format,Zt as RGBA_S3TC_DXT1_Format,Jt as RGBA_S3TC_DXT3_Format,er as RGBA_S3TC_DXT5_Format,pt as RGBFormat,ht as RGBIntegerFormat,nr as RGB_ETC1_Format,ar as RGB_ETC2_Format,rr as RGB_PVRTC_2BPPV1_Format,tr as RGB_PVRTC_4BPPV1_Format,Qt as RGB_S3TC_DXT1_Format,de as RGFormat,ct as RGIntegerFormat,fb as RTTNode,Px as RangeNode,as as RectAreaLight,sN as RectAreaLightNode,dt as RedFormat,lt as RedIntegerFormat,Jd as ReferenceNode,lb as ReflectorNode,cs as ReinhardToneMapping,Ku as RemapNode,tl as RenderOutputNode,me as RenderTarget,Bu as RendererReferenceNode,kT as RendererUtils,Er as RepeatWrapping,Zr as ReplaceStencilOp,_t as ReverseSubtractEquation,yf as RotateNode,Rr as SIGNED_RED_GREEN_RGTC2_Format,Sr as SIGNED_RED_RGTC1_Format,q as SRGBColorSpace,g as SRGBTransfer,Z as Scene,Bb as SceneNode,wl as ScreenNode,Sx as ScriptableNode,xx as ScriptableValueNode,ii as SetNode,BT as ShadowBaseNode,Ee as ShadowMaterial,s_ as ShadowNode,Ef as ShadowNodeMaterial,yt as ShortType,kh as SkinningNode,E as Sphere,We as SphereGeometry,si as SplitNode,ss as SpotLight,iN as SpotLightNode,Ae as SpriteMaterial,Tf as SpriteNodeMaterial,jy as SpriteSheetUVNode,St as SrcAlphaFactor,At as SrcAlphaSaturateFactor,Nt as SrcColorFactor,Ty as StackNode,f as StaticDrawUsage,Vw as Storage3DTexture,Dh as StorageArrayElementNode,Ow as StorageArrayTexture,Rb as StorageBufferAttribute,Vh as StorageBufferNode,Ab as StorageInstancedBufferAttribute,Uw as StorageTexture,Ib as StorageTextureNode,Ny as StructNode,vy as StructTypeNode,bu as SubBuildNode,Tt as SubtractEquation,Dt as SubtractiveBlending,mv as TSL,F as TangentSpaceNormalMap,ei as TempNode,R as Texture,Vb as Texture3DNode,fl as TextureNode,cl as TextureSizeNode,bt as TimestampQuery,Lu as ToneMappingNode,ix as ToonOutlinePassNode,Ge as UVMapping,Me as Uint16BufferAttribute,Ce as Uint32BufferAttribute,Nl as UniformArrayNode,ta as UniformGroupNode,oa as UniformNode,Ie as UnsignedByteType,Kt as UnsignedInt101111Type,Fe as UnsignedInt248Type,Xt as UnsignedInt5999Type,N as UnsignedIntType,jt as UnsignedShort4444Type,qt as UnsignedShort5551Type,mt as UnsignedShortType,Gb as UserDataNode,ke as VSMShadowMap,pu as VarNode,Tu as VaryingNode,r as Vector2,s as Vector3,i as Vector4,vp as VertexColorNode,lp as ViewportDepthNode,op as ViewportDepthTextureNode,Up as ViewportSharedTextureNode,sp as ViewportTextureNode,Pf as VolumeNodeMaterial,c as WebGLCoordinateSystem,K as WebGLCubeRenderTarget,h as WebGPUCoordinateSystem,Fw as WebGPURenderer,st as WebXRController,tt as ZeroFactor,Jr as ZeroStencilOp,xt as createCanvasElement,js as defaultBuildStages,Hs as defaultShaderStages,e as error,_ as log,qs as shaderStages,Xs as vectorComponents,d as warn,v as warnOnce};
6
+ import{Color as e,Vector2 as t,Vector3 as r,Vector4 as s,Matrix2 as i,Matrix3 as n,Matrix4 as a,error as o,EventDispatcher as u,MathUtils as l,warn as d,WebGLCoordinateSystem as c,WebGPUCoordinateSystem as h,ColorManagement as p,SRGBTransfer as g,NoToneMapping as m,StaticDrawUsage as f,InterleavedBufferAttribute as y,InterleavedBuffer as b,DynamicDrawUsage as x,NoColorSpace as T,log as _,warnOnce as v,Texture as N,UnsignedIntType as S,IntType as E,Compatibility as R,LessCompare as w,LessEqualCompare as A,GreaterCompare as C,GreaterEqualCompare as M,NearestFilter as B,Sphere as L,BackSide as F,DoubleSide as P,CubeTexture as U,CubeReflectionMapping as D,CubeRefractionMapping as O,TangentSpaceNormalMap as I,NoNormalPacking as V,NormalRGPacking as k,NormalGAPacking as G,ObjectSpaceNormalMap as z,RGFormat as $,RED_GREEN_RGTC2_Format as W,RG11_EAC_Format as H,InstancedBufferAttribute as j,InstancedInterleavedBuffer as q,DataArrayTexture as X,FloatType as Y,FramebufferTexture as Q,LinearMipmapLinearFilter as K,DepthTexture as Z,Material as J,LineBasicMaterial as ee,LineDashedMaterial as te,NoBlending as re,MeshNormalMaterial as se,SRGBColorSpace as ie,RenderTarget as ne,BoxGeometry as ae,Mesh as oe,Scene as ue,LinearFilter as le,CubeCamera as de,EquirectangularReflectionMapping as ce,EquirectangularRefractionMapping as he,AddOperation as pe,MixOperation as ge,MultiplyOperation as me,MeshBasicMaterial as fe,MeshLambertMaterial as ye,MeshPhongMaterial as be,DataTexture as xe,HalfFloatType as Te,ClampToEdgeWrapping as _e,BufferGeometry as ve,OrthographicCamera as Ne,PerspectiveCamera as Se,LinearSRGBColorSpace as Ee,RGBAFormat as Re,CubeUVReflectionMapping as we,BufferAttribute as Ae,MeshStandardMaterial as Ce,MeshPhysicalMaterial as Me,MeshToonMaterial as Be,MeshMatcapMaterial as Le,SpriteMaterial as Fe,PointsMaterial as Pe,ShadowMaterial as Ue,Uint32BufferAttribute as De,Uint16BufferAttribute as Oe,ByteType as Ie,UnsignedByteType as Ve,ShortType as ke,UnsignedShortType as Ge,AlphaFormat as ze,RedFormat as $e,RedIntegerFormat as We,DepthFormat as He,DepthStencilFormat as je,RGIntegerFormat as qe,RGBFormat as Xe,RGBIntegerFormat as Ye,UnsignedShort4444Type as Qe,UnsignedShort5551Type as Ke,UnsignedInt248Type as Ze,UnsignedInt5999Type as Je,UnsignedInt101111Type as et,NormalBlending as tt,SrcAlphaFactor as rt,OneMinusSrcAlphaFactor as st,AddEquation as it,MaterialBlending as nt,Object3D as at,LinearMipMapLinearFilter as ot,Plane as ut,Float32BufferAttribute as lt,UVMapping as dt,PCFShadowMap as ct,PCFSoftShadowMap as ht,VSMShadowMap as pt,BasicShadowMap as gt,CubeDepthTexture as mt,SphereGeometry as ft,LinearMipmapNearestFilter as yt,NearestMipmapLinearFilter as bt,Float16BufferAttribute as xt,yieldToMain as Tt,REVISION as _t,ArrayCamera as vt,PlaneGeometry as Nt,FrontSide as St,CustomBlending as Et,ZeroFactor as Rt,CylinderGeometry as wt,Quaternion as At,WebXRController as Ct,RAD2DEG as Mt,FrustumArray as Bt,Frustum as Lt,RGBAIntegerFormat as Ft,TimestampQuery as Pt,createCanvasElement as Ut,ReverseSubtractEquation as Dt,SubtractEquation as Ot,OneMinusDstAlphaFactor as It,OneMinusDstColorFactor as Vt,OneMinusSrcColorFactor as kt,DstAlphaFactor as Gt,DstColorFactor as zt,SrcAlphaSaturateFactor as $t,SrcColorFactor as Wt,OneFactor as Ht,CullFaceNone as jt,CullFaceBack as qt,CullFaceFront as Xt,MultiplyBlending as Yt,SubtractiveBlending as Qt,AdditiveBlending as Kt,NotEqualDepth as Zt,GreaterDepth as Jt,GreaterEqualDepth as er,EqualDepth as tr,LessEqualDepth as rr,LessDepth as sr,AlwaysDepth as ir,NeverDepth as nr,ReversedDepthFuncs as ar,RGB_S3TC_DXT1_Format as or,RGBA_S3TC_DXT1_Format as ur,RGBA_S3TC_DXT3_Format as lr,RGBA_S3TC_DXT5_Format as dr,RGB_PVRTC_4BPPV1_Format as cr,RGB_PVRTC_2BPPV1_Format as hr,RGBA_PVRTC_4BPPV1_Format as pr,RGBA_PVRTC_2BPPV1_Format as gr,RGB_ETC1_Format as mr,RGB_ETC2_Format as fr,RGBA_ETC2_EAC_Format as yr,R11_EAC_Format as br,SIGNED_R11_EAC_Format as xr,SIGNED_RG11_EAC_Format as Tr,RGBA_ASTC_4x4_Format as _r,RGBA_ASTC_5x4_Format as vr,RGBA_ASTC_5x5_Format as Nr,RGBA_ASTC_6x5_Format as Sr,RGBA_ASTC_6x6_Format as Er,RGBA_ASTC_8x5_Format as Rr,RGBA_ASTC_8x6_Format as wr,RGBA_ASTC_8x8_Format as Ar,RGBA_ASTC_10x5_Format as Cr,RGBA_ASTC_10x6_Format as Mr,RGBA_ASTC_10x8_Format as Br,RGBA_ASTC_10x10_Format as Lr,RGBA_ASTC_12x10_Format as Fr,RGBA_ASTC_12x12_Format as Pr,RGBA_BPTC_Format as Ur,RGB_BPTC_SIGNED_Format as Dr,RGB_BPTC_UNSIGNED_Format as Or,RED_RGTC1_Format as Ir,SIGNED_RED_RGTC1_Format as Vr,SIGNED_RED_GREEN_RGTC2_Format as kr,MirroredRepeatWrapping as Gr,RepeatWrapping as zr,NearestMipmapNearestFilter as $r,NotEqualCompare as Wr,EqualCompare as Hr,AlwaysCompare as jr,NeverCompare as qr,LinearTransfer as Xr,getByteLength as Yr,isTypedArray as Qr,NotEqualStencilFunc as Kr,GreaterStencilFunc as Zr,GreaterEqualStencilFunc as Jr,EqualStencilFunc as es,LessEqualStencilFunc as ts,LessStencilFunc as rs,AlwaysStencilFunc as ss,NeverStencilFunc as is,DecrementWrapStencilOp as ns,IncrementWrapStencilOp as as,DecrementStencilOp as os,IncrementStencilOp as us,InvertStencilOp as ls,ReplaceStencilOp as ds,ZeroStencilOp as cs,KeepStencilOp as hs,MaxEquation as ps,MinEquation as gs,SpotLight as ms,PointLight as fs,DirectionalLight as ys,RectAreaLight as bs,AmbientLight as xs,HemisphereLight as Ts,LightProbe as _s,LinearToneMapping as vs,ReinhardToneMapping as Ns,CineonToneMapping as Ss,ACESFilmicToneMapping as Es,AgXToneMapping as Rs,NeutralToneMapping as ws,Group as As,Loader as Cs,FileLoader as Ms,MaterialLoader as Bs,ObjectLoader as Ls}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BatchedMesh,BezierInterpolant,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,Camera,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,ConstantAlphaFactor,ConstantColorFactor,Controls,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CustomToneMapping,Cylindrical,Data3DTexture,DataTextureLoader,DataUtils,DefaultLoadingManager,DetachedBindMode,DirectionalLightHelper,DiscreteInterpolant,DodecahedronGeometry,DynamicCopyUsage,DynamicReadUsage,EdgesGeometry,EllipseCurve,Euler,ExternalTexture,ExtrudeGeometry,Fog,FogExp2,GLBufferAttribute,GLSL1,GLSL3,GridHelper,HTMLTexture,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,InstancedBufferGeometry,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,Interpolant,InterpolateBezier,InterpolateDiscrete,InterpolateLinear,InterpolateSmooth,InterpolationSamplingMode,InterpolationSamplingType,KeyframeTrack,LOD,LatheGeometry,Layers,Light,Line,Line3,LineCurve,LineCurve3,LineLoop,LineSegments,LinearInterpolant,LinearMipMapNearestFilter,LoaderUtils,LoadingManager,LoopOnce,LoopPingPong,LoopRepeat,MOUSE,MeshDepthMaterial,MeshDistanceMaterial,NearestMipMapLinearFilter,NearestMipMapNearestFilter,NormalAnimationBlendMode,NumberKeyframeTrack,OctahedronGeometry,OneMinusConstantAlphaFactor,OneMinusConstantColorFactor,Path,PlaneHelper,PointLightHelper,Points,PolarGridHelper,PolyhedronGeometry,PositionalAudio,PropertyBinding,PropertyMixer,QuadraticBezierCurve,QuadraticBezierCurve3,QuaternionKeyframeTrack,QuaternionLinearInterpolant,RGBADepthPacking,RGBDepthPacking,RGDepthPacking,RawShaderMaterial,Ray,Raycaster,RenderTarget3D,RingGeometry,ShaderMaterial,Shape,ShapeGeometry,ShapePath,ShapeUtils,Skeleton,SkeletonHelper,SkinnedMesh,Source,Spherical,SphericalHarmonics3,SplineCurve,SpotLightHelper,Sprite,StaticCopyUsage,StaticReadUsage,StereoCamera,StreamCopyUsage,StreamDrawUsage,StreamReadUsage,StringKeyframeTrack,TOUCH,TetrahedronGeometry,TextureLoader,TextureUtils,Timer,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGLRenderTarget,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding,getConsoleFunction,setConsoleFunction}from"./three.core.min.js";const Fs=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","envMapRotation","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],Ps=new WeakMap,Us=new WeakMap,Ds=new WeakMap;class Os{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Fs,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:r,object:s}=e;if(t={geometryId:r.id,worldMatrix:s.matrixWorld.clone()},s.center&&(t.center=s.center.clone()),s.morphTargetInfluences&&(t.morphTargetInfluences=s.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),e.material.transmission>0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}const{environmentIntensity:i,environmentRotation:n}=e.scene;t.environmentIntensity=i,t.environmentRotation=n.clone(),t.lights=this.getLightsData(e.lightsNode.getLights(),[]),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={id:s.isInterleavedBufferAttribute?s.data.uuid:s.id,version:s.isInterleavedBufferAttribute?s.data.version:s.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=Ds.get(e);return void 0===t&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},Ds.set(e,t)),t}getMaterialData(e){let t=Us.get(e);if(void 0===t){t={_renderId:-1,_equal:!1};for(const r of this.refreshUniforms){const s=e[r];null!=s&&("object"==typeof s&&void 0!==s.clone?!0===s.isTexture?t[r]={id:s.id,version:0}:t[r]=s.clone():t[r]=s)}Us.set(e,t)}return t}equals(e,t,r){const{object:s,material:i,geometry:n}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(s.matrixWorld))return a.worldMatrix.copy(s.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==r){o._renderId=r;for(const e in o){const t=o[e],r=i[e];if("_renderId"!==e&&"_equal"!==e)if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),o._equal=!1,!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,o._equal=!1,!1}else if(t!==r)return o[e]=r,o._equal=!1,!1}if(o.transmission>0){const{width:t,height:r}=e.context;if(a.bufferWidth!==t||a.bufferHeight!==r)return a.bufferWidth=t,a.bufferHeight=r,o._equal=!1,!1}o._equal=!0}else if(!1===o._equal)return!1;if(a.geometryId!==n.id)return a.geometryId=n.id,!1;const u=this.getGeometryData(e.geometry);if(u._renderId!==r){u._renderId=r;const e=n.attributes,t=u.attributes;let s=0,i=0;for(const t in e)s++;for(const r in t){i++;const s=t[r],n=e[r];if(void 0===n)return delete t[r],u._equal=!1,!1;const a=n.isInterleavedBufferAttribute?n.data.uuid:n.id,o=n.isInterleavedBufferAttribute?n.data.version:n.version;if(s.id!==a||s.version!==o)return s.id=a,s.version=o,u._equal=!1,!1}if(i!==s)return u.attributes=this.getAttributesData(e),u._equal=!1,!1;const a=n.index,o=u.indexId,l=u.indexVersion,d=a?a.id:null,c=a?a.version:null;if(o!==d||l!==c)return u.indexId=d,u.indexVersion=c,u._equal=!1,!1;if(u.drawRange.start!==n.drawRange.start||u.drawRange.count!==n.drawRange.count)return u.drawRange.start=n.drawRange.start,u.drawRange.count=n.drawRange.count,u._equal=!1,!1;u._equal=!0}else if(!1===u._equal)return!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t<a.morphTargetInfluences.length;t++)a.morphTargetInfluences[t]!==s.morphTargetInfluences[t]&&(a.morphTargetInfluences[t]=s.morphTargetInfluences[t],e=!0);if(e)return!1}if(a.lights)for(let e=0;e<t.length;e++)if(a.lights[e].map!==t[e].map)return!1;const l=e.scene;return null===l.environment||null!==i.envMap||a.environmentIntensity===l.environmentIntensity&&!1!==a.environmentRotation.equals(l.environmentRotation)?a.center&&!1===a.center.equals(s.center)?(a.center.copy(s.center),!1):(null!==e.bundle&&(a.version=e.bundle.version),!0):(a.environmentIntensity=l.environmentIntensity,a.environmentRotation.copy(l.environmentRotation),!1)}getLightsData(e,t){t.length=0;for(const r of e)!0===r.isSpotLight&&null!==r.map&&t.push({map:r.map.version});return t}getLights(e,t){let r=Ps.get(e);return void 0===r&&(r={renderId:-1,lightsData:[]},Ps.set(e,r)),r.renderId===t||(r.renderId=t,this.getLightsData(e.getLights(),r.lightsData)),r.lightsData}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:r}=t;if(this.renderId!==r)return this.renderId=r,!0;const s=!0===e.object.static,i=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(s||i)return!1;const n=this.getLights(e.lightsNode,r);return!0!==this.equals(e,n,r)}}const Is=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class Vs{constructor(e=null){this.isStackTrace=!0,this.stack=function(e){const t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split("\n").map(e=>{const r=e.match(t);if(!r)return null;const s=r[1]||r[2]||"",i=r[3].split("?")[0],n=parseInt(r[4],10),a=parseInt(r[5],10);return{fn:s,file:i.split("/").pop(),line:n,column:a}}).filter(e=>e&&!Is.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function ks(e,t=0){let r=3735928559^t,s=1103547991^t;if(Array.isArray(e))for(let t,i=0;i<e.length;i++)t=e[i],r=Math.imul(r^t,2654435761),s=Math.imul(s^t,1597334677);else for(let t,i=0;i<e.length;i++)t=e.charCodeAt(i),r=Math.imul(r^t,2654435761),s=Math.imul(s^t,1597334677);return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&s)+(r>>>0)}const Gs=e=>ks(e),zs=e=>ks(e),$s=(...e)=>ks(e),Ws=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Hs=new WeakMap;function js(e){return Ws.get(e)}function qs(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e))return Float32Array;if(/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function Xs(e){return/float|int|uint|bool/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?9:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Vs)}function Ys(e){return/float|int|uint|bool/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?12:/mat4/.test(e)?16:void o(`TSL: Unsupported type: ${e}`,new Vs)}function Qs(e){return/float|int|uint|bool/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)||/vec4/.test(e)?4:/mat2/.test(e)?2:/mat3/.test(e)||/mat4/.test(e)?4:void o(`TSL: Unsupported type: ${e}`,new Vs)}function Ks(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function Zs(o,...u){const l=o?o.slice(-4):void 0;return 1===u.length&&("vec2"===l?u=[u[0],u[0]]:"vec3"===l?u=[u[0],u[0],u[0]]:"vec4"===l&&(u=[u[0],u[0],u[0],u[0]])),"color"===o?new e(...u):"vec2"===l?new t(...u):"vec3"===l?new r(...u):"vec4"===l?new s(...u):"mat2"===l?new i(...u):"mat3"===l?new n(...u):"mat4"===l?new a(...u):"bool"===o?u[0]||!1:"float"===o||"int"===o||"uint"===o?u[0]||0:"string"===o?u[0]||"":"ArrayBuffer"===o?ti(u[0]):null}function Js(e){let t=Hs.get(e);return void 0===t&&(t={},Hs.set(e,t)),t}function ei(e){let t="";const r=new Uint8Array(e);for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return btoa(t)}function ti(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0)).buffer}var ri=Object.freeze({__proto__:null,arrayBufferToBase64:ei,base64ToArrayBuffer:ti,getAlignmentFromType:Qs,getDataFromObject:Js,getLengthFromType:Xs,getMemoryLengthFromType:Ys,getTypeFromLength:js,getTypedArrayFromType:qs,getValueFromType:Zs,getValueType:Ks,hash:$s,hashArray:zs,hashString:Gs});const si={VERTEX:"vertex",FRAGMENT:"fragment"},ii={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},ni={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},ai={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},oi=["fragment","vertex"],ui=["setup","analyze","generate"],li=[...oi,"compute"],di=["x","y","z","w"],ci={analyze:"setup",generate:"analyze"};let hi=0;class pi extends u{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=ii.NONE,this.updateBeforeType=ii.NONE,this.updateAfterType=ii.NONE,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=hi++,this.stackTrace=null,!0===pi.captureStackTrace&&(this.stackTrace=new Vs)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=l.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,ii.FRAME)}onRenderUpdate(e){return this.onUpdate(e,ii.RENDER)}onObjectUpdate(e){return this.onUpdate(e,ii.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const r of Object.getOwnPropertyNames(this)){const s=this[r];if(!0!==r.startsWith("_")&&!e.has(s))if(!0===Array.isArray(s))for(let e=0;e<s.length;e++){const i=s[e];i&&!0===i.isNode&&t.push({property:r,index:e,childNode:i})}else if(s&&!0===s.isNode)t.push({property:r,childNode:s});else if(s&&Object.getPrototypeOf(s)===Object.prototype)for(const e in s){if(!0===e.startsWith("_"))continue;const i=s[e];i&&!0===i.isNode&&t.push({property:r,index:e,childNode:i})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const r=[];for(const{property:s,childNode:i}of this._getChildren(t))r.push(Gs(s.slice(0,-4)),i.getCacheKey(e,t));this._cacheKey=$s(zs(r),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e,t=null){const r=e.getDataFromNode(this);let s;return null!==t?(r.typeFromOutput=r.typeFromOutput||{},s=r.typeFromOutput[t],void 0===s&&(s=this.generateNodeType(e,t),r.typeFromOutput[t]=s)):(s=r.type,void 0===s&&(s=this.generateNodeType(e),r.type=s)),s}generateNodeType(e,t=null){const r=e.getNodeProperties(this);return r.outputNode?r.outputNode.getNodeType(e,t):this.nodeType}getShared(e){const t=this.getHash(e),r=e.getNodeFromHash(t);let s=null;if(r&&r!==this)s=r;else if(e.context.overrideNodes){const t=e.context.overrideNodes.get(this);if(t){const r=e.getDataFromNode(this);!0!==r.isOverwritten?(r.isOverwritten=!0,s=t(e).overrideNode(this,null),r.sharedNode=s):s=r.sharedNode}}return s||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let r=0;for(const e of this.getChildren())t["node"+r++]=e;return t.outputNode||null}analyze(e,t=null){const r=e.increaseUsage(this);if(!0===this.parents){const r=e.getDataFromNode(this,"any");r.stages=r.stages||{},r.stages[e.shaderStage]=r.stages[e.shaderStage]||[],r.stages[e.shaderStage].push(t)}if(1===r){const t=e.getNodeProperties(this);for(const r of Object.values(t))r&&!0===r.isNode&&r.build(e,this)}}generate(e,t){const{outputNode:r}=e.getNodeProperties(this);if(r&&!0===r.isNode)return r.build(e,t)}updateBefore(){d("Abstract function.")}updateAfter(){d("Abstract function.")}update(){d("Abstract function.")}before(e){return null===this._beforeNodes&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const r=this.getShared(e);if(this!==r)return r.build(e,t);if(null!==this._beforeNodes){const r=this._beforeNodes;this._beforeNodes=null;for(const s of r)s.build(e,t);this._beforeNodes=r}const s=e.getDataFromNode(this);s.buildStages=s.buildStages||{},s.buildStages[e.buildStage]=!0;const i=ci[e.buildStage];if(i&&!0!==s.buildStages[i]){const t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){e.addNode(this),this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const r of Object.values(t))if(r&&!0===r.isNode){if(!0===r.parents){const t=e.getNodeProperties(r);t.parents=t.parents||[],t.parents.push(this)}r.build(e)}e.addSequentialNode(this)}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(this.generate.length<2){const r=this.getNodeType(e),s=e.getDataFromNode(this);n=s.snippet,void 0===n?void 0===s.generated?(s.generated=!0,n=this.generate(e)||"",s.snippet=n):(d("Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==s.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,r,t)}else n=this.generate(e,t)||"";""===n&&null!==t&&"void"!==t&&"OutputType"!==t&&(o(`TSL: Invalid generated code, expected a "${t}".`),n=e.generateConst(t))}return e.removeChain(this),n}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),r={};for(const{property:s,index:i,childNode:n}of t)void 0!==i?(void 0===r[s]&&(r[s]=Number.isInteger(i)?[]:{}),r[s][i]=n.toJSON(e.meta).uuid):r[s]=n.toJSON(e.meta).uuid;Object.keys(r).length>0&&(e.inputNodes=r)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const r in e.inputNodes)if(Array.isArray(e.inputNodes[r])){const s=[];for(const i of e.inputNodes[r])s.push(t[i]);this[r]=s}else if("object"==typeof e.inputNodes[r]){const s={};for(const i in e.inputNodes[r]){const n=e.inputNodes[r][i];s[i]=t[n]}this[r]=s}else{const s=e.inputNodes[r];this[r]=t[s]}}}toJSON(e){const{uuid:t,type:r}=this,s=void 0===e||"string"==typeof e;s&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(void 0===i&&(i={uuid:t,type:r,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==s&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),s){const t=n(e.textures),r=n(e.images),s=n(e.nodes);t.length>0&&(i.textures=t),r.length>0&&(i.images=r),s.length>0&&(i.nodes=s)}return i}}pi.captureStackTrace=!1;class gi extends pi{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class mi extends pi{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let r=null;for(const s of this.convertTo.split("|"))null!==r&&e.getTypeLength(t)!==e.getTypeLength(s)||(r=s);return r}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const r=this.node,s=this.getNodeType(e),i=r.build(e,s);return e.format(i,s,t)}}class fi extends pi{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const r=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(void 0!==s.propertyName)return e.format(s.propertyName,r,t);if("void"!==r&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,r),n=e.getVarFromNode(this,null,r),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${i}`,this),s.snippet=i,s.propertyName=a,e.format(s.propertyName,r,t)}}return super.build(e,t)}}class yi extends fi{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,r)=>t+e.getTypeLength(r.getNodeType(e)),0))}generate(e,t){const r=this.getNodeType(e),s=e.getTypeLength(r),i=this.nodes,n=e.getComponentType(r),a=[];let u=0;for(const t of i){if(u>=s){o(`TSL: Length of parameters exceeds maximum length of function '${r}()' type.`,this.stackTrace);break}let i,l=t.getNodeType(e),d=e.getTypeLength(l);u+d>s&&(o(`TSL: Length of '${r}()' data exceeds maximum length of output type.`,this.stackTrace),d=s-u,l=e.getTypeFromLength(d)),u+=d,i=t.build(e,l);if(e.getComponentType(l)!==n){const t=e.getTypeFromLength(d,n);i=e.format(i,l,t)}a.push(i)}const l=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(l,r,t)}}const bi=di.join("");class xi extends pi{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(di.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const r=this.node,s=e.getTypeLength(r.getNodeType(e));let i=null;if(s>1){let n=null;this.getVectorLength()>=s&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=r.build(e,n);i=this.components.length===s&&this.components===bi.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=r.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Ti extends fi{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:r,targetNode:s}=this,i=this.getNodeType(e),n=e.getComponentType(s.getNodeType(e)),a=e.getTypeFromLength(r.length,n),o=s.build(e,a),u=t.build(e,i),l=e.getTypeLength(i),d=[];for(let e=0;e<l;e++){const t=di[e];t===r[0]?(d.push(o),e+=r.length-1):d.push(u+"."+t)}return`${e.getType(i)}( ${d.join(", ")} )`}}class _i extends fi{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:r}=this,s=this.getNodeType(e),i=r.build(e),n=e.getVarFromNode(this),a=e.getPropertyName(n);e.addLineFlowCode(a+" = "+i,this);const o=e.getTypeLength(s),u=[];let l=0;for(let e=0;e<o;e++){const r=di[e];r===t[l]?(u.push("1.0 - "+a+"."+r),l++):u.push(a+"."+r)}return`${e.getType(s)}( ${u.join(", ")} )`}}class vi extends pi{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return null===this.nodeType?Ks(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=Ks(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=ei(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Zs(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){d("Abstract function.")}}const Ni=/float|u?int/;class Si extends vi{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const r=this.getNodeType(e);return Ni.test(r)&&Ni.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),r,t)}}class Ei extends pi{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}generateNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){d(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let Ri=null;const wi=new Map;function Ai(e,t){if(wi.has(e))d(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);wi.set(e,t),"assign"!==e&&(pi.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},pi.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const Ci=e=>(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");pi.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Ri?Ri.assign(this,...e):o("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Vs),this;{const t=wi.get("assign");return this.addToStack(t(...e))}},pi.prototype.toVarIntent=function(){return this},pi.prototype.get=function(e){return new Ei(this,e)};const Mi={};function Bi(e,t,r){Mi[e]=Mi[t]=Mi[r]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new xi(this,e),this._cache[e]=t),t},set(t){this[e].assign(sn(t))}};const s=e.toUpperCase(),i=t.toUpperCase(),n=r.toUpperCase();pi.prototype["set"+s]=pi.prototype["set"+i]=pi.prototype["set"+n]=function(t){const r=Ci(e);return new Ti(this,r,sn(t))},pi.prototype["flip"+s]=pi.prototype["flip"+i]=pi.prototype["flip"+n]=function(){const t=Ci(e);return new _i(this,t)}}const Li=["x","y","z","w"],Fi=["r","g","b","a"],Pi=["s","t","p","q"];for(let e=0;e<4;e++){let t=Li[e],r=Fi[e],s=Pi[e];Bi(t,r,s);for(let i=0;i<4;i++){t=Li[e]+Li[i],r=Fi[e]+Fi[i],s=Pi[e]+Pi[i],Bi(t,r,s);for(let n=0;n<4;n++){t=Li[e]+Li[i]+Li[n],r=Fi[e]+Fi[i]+Fi[n],s=Pi[e]+Pi[i]+Pi[n],Bi(t,r,s);for(let a=0;a<4;a++)t=Li[e]+Li[i]+Li[n]+Li[a],r=Fi[e]+Fi[i]+Fi[n]+Fi[a],s=Pi[e]+Pi[i]+Pi[n]+Pi[a],Bi(t,r,s)}}}for(let e=0;e<32;e++)Mi[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new gi(this,new Si(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(sn(t))}};Object.defineProperties(pi.prototype,Mi);const Ui=function(e,t=null){for(const r in e)e[r]=sn(e[r],t);return e},Di=function(e,t=null){const r=e.length;for(let s=0;s<r;s++)e[s]=sn(e[s],t);return e},Oi=function(e,t=null,r=null,s=null){function i(e){return null!==s?(e=sn(Object.assign(e,s)),!0===s.intent&&(e=e.toVarIntent())):e=sn(e),e}let n,a,u,l=t;function d(t){let r;return r=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==a&&t.length<a?(o(`TSL: "${r}" parameter length is less than minimum required.`,new Vs),t.concat(new Array(a-t.length).fill(0))):void 0!==u&&t.length>u?(o(`TSL: "${r}" parameter length exceeds limit.`,new Vs),t.slice(0,u)):t}return null===t?n=(...t)=>i(new e(...on(d(t)))):null!==r?(r=sn(r),n=(...s)=>i(new e(t,...on(d(s)),r))):n=(...r)=>i(new e(t,...on(d(r)))),n.setParameterLength=(...e)=>(1===e.length?a=u=e[0]:2===e.length&&([a,u]=e),n),n.setName=e=>(l=e,n),n},Ii=function(e,...t){return new e(...on(t))};class Vi extends pi{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=i,e.fnCall=this;let u=null;if(t.layout){if(r){const s=t.layout.inputs;if(ki(r)){const t=r;for(let r=0;r<s.length;r++){const s=t[r];s&&s.isNode&&s.build(e)}}else{const t=r[0];for(const r of s){const s=t[r.name];s&&s.isNode&&s.build(e)}}}const s=e.buildFunctionNode(t);e.addInclude(s);const i=r?function(e){let t;an(e),t=ki(e)?[...e]:e[0];return t}(r):null;u=s.call(i)}else{const s=new Proxy(e,{get:(e,t,r)=>{let s;return s=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,r),s}}),i=r?function(e){let t=0;return an(e),new Proxy(e,{get:(r,s,i)=>{let n;if("length"===s)return n=e.length,n;if(Symbol.iterator===s)n=function*(){for(const t of e)yield sn(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const r=e[0];n=void 0===r[s]?r[t++]:Reflect.get(r,s,i)}else e[0]instanceof pi&&(n=void 0===e[s]?e[t++]:Reflect.get(e,s,i));else n=Reflect.get(r,s,i);n=sn(n)}return n}})}(r):null,n=Array.isArray(r)?r.length>0:null!==r,a=t.jsFunc,o=n||a.length>1?a(i,s):a(s);u=sn(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(s[n]=u),u}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),r=e.getSubBuildOutput(this);return t[r]=t[r]||this.setupOutput(e),t[r].subBuild=e.getClosestSubBuild(this),t[r]}build(e,t=null){let r=null;const s=e.getBuildStage(),i=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===s){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[n]=this.getOutputNode(e),i[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const r=e.getDataFromNode(t,"any");r.subBuilds=r.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)r.subBuilds.add(e)}r=i[n]}else"analyze"===s?a.build(e,t):"generate"===s&&(r=a.build(e,t)||"");return e.fnCall=o,r}}function ki(e){return e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)}class Gi extends pi{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Vi(this,e)}setup(){return this.call()}}const zi=[!1,!0],$i=[0,1,2,3],Wi=[-1,-2],Hi=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],ji=new Map;for(const e of zi)ji.set(e,new Si(e));const qi=new Map;for(const e of $i)qi.set(e,new Si(e,"uint"));const Xi=new Map([...qi].map(e=>new Si(e.value,"int")));for(const e of Wi)Xi.set(e,new Si(e,"int"));const Yi=new Map([...Xi].map(e=>new Si(e.value)));for(const e of Hi)Yi.set(e,new Si(e));for(const e of Hi)Yi.set(-e,new Si(-e));const Qi={bool:ji,uint:qi,ints:Xi,float:Yi},Ki=new Map([...ji,...Yi]),Zi=(e,t)=>Ki.has(e)?Ki.get(e):!0===e.isNode?e:new Si(e,t),Ji=function(e,t=null){return(...r)=>{for(const t of r)if(void 0===t)return o(`TSL: Invalid parameter for the type "${e}".`,new Vs),new Si(0,e);if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(r=[Zs(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return nn(t.get(r[0]));if(1===r.length){const t=Zi(r[0],e);return t.nodeType===e?nn(t):nn(new mi(t,e))}const s=r.map(e=>Zi(e));return nn(new yi(s,e))}};function en(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}const tn=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function rn(e,t){return new Gi(e,t)}const sn=(e,t=null)=>function(e,t=null){const r=Ks(e);return"node"===r?e:null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?sn(Zi(e,t)):"shader"===r?e.isFn?e:gn(e):e}(e,t),nn=(e,t=null)=>sn(e,t).toVarIntent(),an=(e,t=null)=>new Ui(e,t),on=(e,t=null)=>new Di(e,t),un=(e,t=null,r=null,s=null)=>new Oi(e,t,r,s),ln=(e,...t)=>new Ii(e,...t),dn=(e,t=null,r=null,s={})=>new Oi(e,t,r,{...s,intent:!0}),cn=(e,t)=>new Proxy(e,{get:(e,r,s)=>Reflect.get(t,r,s),set:(e,r,s)=>Reflect.set(t,r,s)});let hn=0;class pn extends pi{constructor(e,t=null){super();let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:o("TSL: Invalid layout type.",new Vs),t=null)),this.shaderNode=new rn(e,r),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const r={name:"fn"+hn++,type:t,inputs:[]};for(const t in e)"return"!==t&&r.inputs.push({name:t,type:e[t]});e=r}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return o('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function gn(e,t=null){const r=new pn(e,t);return new Proxy(()=>{},{apply:(e,t,s)=>r.call(...s),get:(e,t,s)=>Reflect.get(r,t,s),set:(e,t,s,i)=>Reflect.set(r,t,s,i)})}const mn=e=>{Ri=e},fn=()=>Ri,yn=(...e)=>Ri.If(...e);function bn(e){return Ri&&Ri.addToStack(e),e}Ai("toStack",bn);const xn=new Ji("color"),Tn=new Ji("float",Qi.float),_n=new Ji("int",Qi.ints),vn=new Ji("uint",Qi.uint),Nn=new Ji("bool",Qi.bool),Sn=new Ji("vec2"),En=new Ji("ivec2"),Rn=new Ji("uvec2"),wn=new Ji("bvec2"),An=new Ji("vec3"),Cn=new Ji("ivec3"),Mn=new Ji("uvec3"),Bn=new Ji("bvec3"),Ln=new Ji("vec4"),Fn=new Ji("ivec4"),Pn=new Ji("uvec4"),Un=new Ji("bvec4"),Dn=new Ji("mat2"),On=new Ji("mat3"),In=new Ji("mat4");Ai("toColor",xn),Ai("toFloat",Tn),Ai("toInt",_n),Ai("toUint",vn),Ai("toBool",Nn),Ai("toVec2",Sn),Ai("toIVec2",En),Ai("toUVec2",Rn),Ai("toBVec2",wn),Ai("toVec3",An),Ai("toIVec3",Cn),Ai("toUVec3",Mn),Ai("toBVec3",Bn),Ai("toVec4",Ln),Ai("toIVec4",Fn),Ai("toUVec4",Pn),Ai("toBVec4",Un),Ai("toMat2",Dn),Ai("toMat3",On),Ai("toMat4",In);const Vn=un(gi).setParameterLength(2),kn=(e,t)=>new mi(sn(e),t);Ai("element",Vn),Ai("convert",kn);Ai("append",e=>(d("TSL: .append() has been renamed to .toStack().",new Vs),bn(e)));class Gn extends pi{static get type(){return"PropertyNode"}constructor(e,t=null,r=!1,s=null){super(e),this.name=t,this.varying=r,this.placeholderNode=sn(s),this.isPropertyNode=!0,this.global=!0}getNodeType(e){const t=super.getNodeType(e);return"output"===t?e.getOutputType():t}customCacheKey(){return Gs(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;if(!0===this.varying)t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0;else if(t=e.getVarFromNode(this,this.name),null!==this.placeholderNode&&!1===e.hasWriteUsage(this)){const r=this.placeholderNode.build(e,this.getNodeType(e));e.addLineFlowCode(`${e.getPropertyName(t)} = ${r}`,this)}return e.getPropertyName(t)}}const zn=(e,t,r=null)=>new Gn(e,t,!1,r),$n=(e,t,r=null)=>new Gn(e,t,!0,r),Wn=ln(Gn,"vec4","DiffuseColor"),Hn=ln(Gn,"vec3","DiffuseContribution"),jn=ln(Gn,"vec3","EmissiveColor"),qn=ln(Gn,"float","Roughness"),Xn=ln(Gn,"float","Metalness"),Yn=ln(Gn,"float","Clearcoat"),Qn=ln(Gn,"float","ClearcoatRoughness"),Kn=ln(Gn,"vec3","Sheen"),Zn=ln(Gn,"float","SheenRoughness"),Jn=ln(Gn,"float","Iridescence"),ea=ln(Gn,"float","IridescenceIOR"),ta=ln(Gn,"float","IridescenceThickness"),ra=ln(Gn,"float","AlphaT"),sa=ln(Gn,"float","Anisotropy"),ia=ln(Gn,"vec3","AnisotropyT"),na=ln(Gn,"vec3","AnisotropyB"),aa=ln(Gn,"color","SpecularColor"),oa=ln(Gn,"color","SpecularColorBlended"),ua=ln(Gn,"float","SpecularF90"),la=ln(Gn,"float","Shininess"),da=ln(Gn,"output","Output"),ca=ln(Gn,"float","dashSize"),ha=ln(Gn,"float","gapSize"),pa=ln(Gn,"float","pointWidth"),ga=ln(Gn,"float","IOR"),ma=ln(Gn,"float","Transmission"),fa=ln(Gn,"float","Thickness"),ya=ln(Gn,"float","AttenuationDistance"),ba=ln(Gn,"color","AttenuationColor"),xa=ln(Gn,"float","Dispersion"),Ta=ln(Gn,"float","AmbientOcclusion",!1,1);class _a extends pi{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1,s=null){super("string"),this.name=e,this.shared=t,this.order=r,this.updateType=s,this.isUniformGroup=!0}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const va=(e,t=1,r=null)=>new _a(e,!1,t,r),Na=(e,t=0,r=null)=>new _a(e,!0,t,r),Sa=Na("frame",0,ii.FRAME),Ea=Na("render",0,ii.RENDER),Ra=va("object",1,ii.OBJECT);class wa extends vi{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Ra}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Vs),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const r=e(t,this);void 0!==r&&(this.value=r)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const r=this.getNodeType(e),s=this.getUniformHash(e);let i=e.getNodeFromHash(s);void 0===i&&(e.setHashNode(this,s),i=this);const n=i.getInputType(e),a=e.getUniformFromNode(i,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let u=o;if("bool"===r){const t=e.getDataFromNode(this);let s=t.propertyName;if(void 0===s){const i=e.getVarFromNode(this,null,"bool");s=e.getPropertyName(i),t.propertyName=s,u=e.format(o,n,r),e.addLineFlowCode(`${s} = ${u}`,this)}u=s}return e.format(u,r,t)}}const Aa=(e,t)=>{const r=tn(t||e);if(r===e&&(e=Zs(r)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new wa(e,r)};class Ca extends fi{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,this.isArrayNode=!0}getArrayCount(){return this.count}generateNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const Ma=(...e)=>{let t;if(1===e.length){const r=e[0];t=new Ca(null,r.length,r)}else{const r=e[0],s=e[1];t=new Ca(r,s)}return sn(t)};Ai("toArray",(e,t)=>Ma(Array(t).fill(e)));class Ba extends fi{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const r=e.getTypeLength(t.node.getNodeType(e));return di.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=t.getScope();e.getDataFromNode(s).assign=!0;const i=e.getNodeProperties(this);i.sourceNode=r,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.build(e),a=r.getNodeType(e),o=s.build(e,a),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=n);else if(i){const s=e.getVarFromNode(this,null,a),i=e.getPropertyName(s);e.addLineFlowCode(`${i} = ${o}`,this);const u=r.node,l=u.node.context({assign:!0}).build(e);for(let t=0;t<u.components.length;t++){const r=u.components[t];e.addLineFlowCode(`${l}.${r} = ${i}[ ${t} ]`,this)}"void"!==t&&(d=n)}else d=`${n} = ${o}`,"void"!==t&&"void"!==u||(e.addLineFlowCode(d,this),"void"!==t&&(d=n));return l.initialized=!0,e.format(d,a,t)}}const La=un(Ba).setParameterLength(2);Ai("assign",La);class Fa extends fi{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}generateNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],r=this.functionNode,s=r.getInputs(e),i=this.parameters,n=(t,r)=>{const s=r.type;let i;return i="pointer"===s?"&"+t.build(e):t.build(e,s),i};if(Array.isArray(i)){if(i.length>s.length)o("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=s.length;else if(i.length<s.length)for(o("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");i.length<s.length;)i.push(Tn(0));for(let e=0;e<i.length;e++)t.push(n(i[e],s[e]))}else for(const e of s){const r=i[e.name];void 0!==r?t.push(n(r,e)):(o(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(Tn(0),e)))}return`${r.build(e,"property")}( ${t.join(", ")} )`}}const Pa=(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?on(t):an(t[0]),new Fa(sn(e),t));Ai("call",Pa);const Ua={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Da extends fi{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new Da(e,t,r);for(let t=0;t<s.length-1;t++)i=new Da(e,i,s[t]);t=i,r=s[s.length-1]}this.op=e,this.aNode=t,this.bNode=r,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(Ua[this.op],t)}generateNodeType(e,t=null){const r=this.op,s=this.aNode,i=this.bNode,n=s.getNodeType(e),a=i?i.getNodeType(e):null;if("void"===n||"void"===a)return t||"void";if("%"===r)return n;if("~"===r||"&"===r||"|"===r||"^"===r||">>"===r||"<<"===r)return e.getIntegerType(n);if("&&"===r||"||"===r||"^^"===r)return"bool";if("!"===r){const t=e.getTypeLength(n);return t>1?`bvec${t}`:"bool"}if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=s.getNodeType(e),o=i?i.getNodeType(e):null,"<"===r||">"===r||"<="===r||">="===r||"=="===r||"!="===r?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===r||"<<"===r?(a=n,o=e.changeComponentType(o,"uint")):"%"===r?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const u=s.build(e,a),l=i?i.build(e,o):null,d=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===c;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${l} )`,n,t):e.format(`( ${u} ${r} ${l} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${l} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${l} )`,n,t);if("!"===r)return s&&e.isVector(a)?e.format(`not( ${u} )`,t):e.format(`( ${r} ${u} )`,a,t);if("~"===r)return e.format(`( ${r} ${u} )`,a,t);if(d)return e.format(`${d}( ${u}, ${l} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${l} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${l}`,n,t);{let i=`( ${u} ${r} ${l} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return d?e.format(`${d}( ${u}, ${l} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${l} ${r} ${u}`,n,t):e.format(`${u} ${r} ${l}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Oa=dn(Da,"+").setParameterLength(2,1/0).setName("add"),Ia=dn(Da,"-").setParameterLength(2,1/0).setName("sub"),Va=dn(Da,"*").setParameterLength(2,1/0).setName("mul"),ka=dn(Da,"/").setParameterLength(2,1/0).setName("div"),Ga=dn(Da,"%").setParameterLength(2).setName("mod"),za=dn(Da,"==").setParameterLength(2).setName("equal"),$a=dn(Da,"!=").setParameterLength(2).setName("notEqual"),Wa=dn(Da,"<").setParameterLength(2).setName("lessThan"),Ha=dn(Da,">").setParameterLength(2).setName("greaterThan"),ja=dn(Da,"<=").setParameterLength(2).setName("lessThanEqual"),qa=dn(Da,">=").setParameterLength(2).setName("greaterThanEqual"),Xa=dn(Da,"&&").setParameterLength(2,1/0).setName("and"),Ya=dn(Da,"||").setParameterLength(2,1/0).setName("or"),Qa=dn(Da,"!").setParameterLength(1).setName("not"),Ka=dn(Da,"^^").setParameterLength(2).setName("xor"),Za=dn(Da,"&").setParameterLength(2).setName("bitAnd"),Ja=dn(Da,"~").setParameterLength(1).setName("bitNot"),eo=dn(Da,"|").setParameterLength(2).setName("bitOr"),to=dn(Da,"^").setParameterLength(2).setName("bitXor"),ro=dn(Da,"<<").setParameterLength(2).setName("shiftLeft"),so=dn(Da,">>").setParameterLength(2).setName("shiftRight"),io=gn(([e])=>(e.addAssign(1),e)),no=gn(([e])=>(e.subAssign(1),e)),ao=gn(([e])=>{const t=_n(e).toConst();return e.addAssign(1),t}),oo=gn(([e])=>{const t=_n(e).toConst();return e.subAssign(1),t});Ai("add",Oa),Ai("sub",Ia),Ai("mul",Va),Ai("div",ka),Ai("mod",Ga),Ai("equal",za),Ai("notEqual",$a),Ai("lessThan",Wa),Ai("greaterThan",Ha),Ai("lessThanEqual",ja),Ai("greaterThanEqual",qa),Ai("and",Xa),Ai("or",Ya),Ai("not",Qa),Ai("xor",Ka),Ai("bitAnd",Za),Ai("bitNot",Ja),Ai("bitOr",eo),Ai("bitXor",to),Ai("shiftLeft",ro),Ai("shiftRight",so),Ai("incrementBefore",io),Ai("decrementBefore",no),Ai("increment",ao),Ai("decrement",oo);class uo extends fi{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===uo.MAX||e===uo.MIN)&&arguments.length>3){let i=new uo(e,t,r);for(let t=3;t<arguments.length-1;t++)i=new uo(e,i,arguments[t]);t=i,r=arguments[arguments.length-1],s=null}this.method=e,this.aNode=t,this.bNode=r,this.cNode=s,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),r=this.bNode?this.bNode.getNodeType(e):null,s=this.cNode?this.cNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(r)?0:e.getTypeLength(r),a=e.isMatrix(s)?0:e.getTypeLength(s);return i>n&&i>a?t:n>a?r:a>i?s:t}generateNodeType(e){const t=this.method;return t===uo.LENGTH||t===uo.DISTANCE||t===uo.DOT?"float":t===uo.CROSS?"vec3":t===uo.ALL||t===uo.ANY?"bool":t===uo.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:r,method:s}=this;let i=null;if(s===uo.ONE_MINUS)i=Ia(1,t);else if(s===uo.RECIPROCAL)i=ka(1,t);else if(s===uo.DIFFERENCE)i=zo(Ia(t,r));else if(s===uo.TRANSFORM_DIRECTION){let s,n;e.isMatrix(t.getNodeType(e))?(s=t,n=r):(s=r,n=t),i=Ao(Va(s,Ln(An(n),0)).xyz)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let r=this.method;const s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,u=e.renderer.coordinateSystem;if(r===uo.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const l=[];return r===uo.CROSS?l.push(n.build(e,s),a.build(e,s)):u===c&&r===uo.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==c||r!==uo.MIN&&r!==uo.MAX?r===uo.REFRACT?l.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===uo.MIX?l.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===h&&r===uo.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==uo.DFDX&&r!==uo.DFDY||(d(`TSL: '${r}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),r="/*"+r+"*/"),l.push(n.build(e,i)),null!==a&&l.push(a.build(e,i)),null!==o&&l.push(o.build(e,i))):l.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${l.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}uo.ALL="all",uo.ANY="any",uo.RADIANS="radians",uo.DEGREES="degrees",uo.EXP="exp",uo.EXP2="exp2",uo.LOG="log",uo.LOG2="log2",uo.SQRT="sqrt",uo.INVERSE_SQRT="inversesqrt",uo.FLOOR="floor",uo.CEIL="ceil",uo.NORMALIZE="normalize",uo.FRACT="fract",uo.SIN="sin",uo.SINH="sinh",uo.COS="cos",uo.COSH="cosh",uo.TAN="tan",uo.TANH="tanh",uo.ASIN="asin",uo.ASINH="asinh",uo.ACOS="acos",uo.ACOSH="acosh",uo.ATAN="atan",uo.ATANH="atanh",uo.ABS="abs",uo.SIGN="sign",uo.LENGTH="length",uo.NEGATE="negate",uo.ONE_MINUS="oneMinus",uo.DFDX="dFdx",uo.DFDY="dFdy",uo.ROUND="round",uo.RECIPROCAL="reciprocal",uo.TRUNC="trunc",uo.FWIDTH="fwidth",uo.TRANSPOSE="transpose",uo.DETERMINANT="determinant",uo.INVERSE="inverse",uo.EQUALS="equals",uo.MIN="min",uo.MAX="max",uo.STEP="step",uo.REFLECT="reflect",uo.DISTANCE="distance",uo.DIFFERENCE="difference",uo.DOT="dot",uo.CROSS="cross",uo.POW="pow",uo.TRANSFORM_DIRECTION="transformDirection",uo.MIX="mix",uo.CLAMP="clamp",uo.REFRACT="refract",uo.SMOOTHSTEP="smoothstep",uo.FACEFORWARD="faceforward";const lo=Tn(1e-6),co=Tn(1e6),ho=Tn(Math.PI),po=Tn(2*Math.PI),go=Tn(2*Math.PI),mo=Tn(.5*Math.PI),fo=dn(uo,uo.ALL).setParameterLength(1),yo=dn(uo,uo.ANY).setParameterLength(1),bo=dn(uo,uo.RADIANS).setParameterLength(1),xo=dn(uo,uo.DEGREES).setParameterLength(1),To=dn(uo,uo.EXP).setParameterLength(1),_o=dn(uo,uo.EXP2).setParameterLength(1),vo=dn(uo,uo.LOG).setParameterLength(1),No=dn(uo,uo.LOG2).setParameterLength(1),So=dn(uo,uo.SQRT).setParameterLength(1),Eo=dn(uo,uo.INVERSE_SQRT).setParameterLength(1),Ro=dn(uo,uo.FLOOR).setParameterLength(1),wo=dn(uo,uo.CEIL).setParameterLength(1),Ao=dn(uo,uo.NORMALIZE).setParameterLength(1),Co=dn(uo,uo.FRACT).setParameterLength(1),Mo=dn(uo,uo.SIN).setParameterLength(1),Bo=dn(uo,uo.SINH).setParameterLength(1),Lo=dn(uo,uo.COS).setParameterLength(1),Fo=dn(uo,uo.COSH).setParameterLength(1),Po=dn(uo,uo.TAN).setParameterLength(1),Uo=dn(uo,uo.TANH).setParameterLength(1),Do=dn(uo,uo.ASIN).setParameterLength(1),Oo=dn(uo,uo.ASINH).setParameterLength(1),Io=dn(uo,uo.ACOS).setParameterLength(1),Vo=dn(uo,uo.ACOSH).setParameterLength(1),ko=dn(uo,uo.ATAN).setParameterLength(1,2),Go=dn(uo,uo.ATANH).setParameterLength(1),zo=dn(uo,uo.ABS).setParameterLength(1),$o=dn(uo,uo.SIGN).setParameterLength(1),Wo=dn(uo,uo.LENGTH).setParameterLength(1),Ho=dn(uo,uo.NEGATE).setParameterLength(1),jo=dn(uo,uo.ONE_MINUS).setParameterLength(1),qo=dn(uo,uo.DFDX).setParameterLength(1),Xo=dn(uo,uo.DFDY).setParameterLength(1),Yo=dn(uo,uo.ROUND).setParameterLength(1),Qo=dn(uo,uo.RECIPROCAL).setParameterLength(1),Ko=dn(uo,uo.TRUNC).setParameterLength(1),Zo=dn(uo,uo.FWIDTH).setParameterLength(1),Jo=dn(uo,uo.TRANSPOSE).setParameterLength(1),eu=dn(uo,uo.DETERMINANT).setParameterLength(1),tu=dn(uo,uo.INVERSE).setParameterLength(1),ru=dn(uo,uo.MIN).setParameterLength(2,1/0),su=dn(uo,uo.MAX).setParameterLength(2,1/0),iu=dn(uo,uo.STEP).setParameterLength(2),nu=dn(uo,uo.REFLECT).setParameterLength(2),au=dn(uo,uo.DISTANCE).setParameterLength(2),ou=dn(uo,uo.DIFFERENCE).setParameterLength(2),uu=dn(uo,uo.DOT).setParameterLength(2),lu=dn(uo,uo.CROSS).setParameterLength(2),du=dn(uo,uo.POW).setParameterLength(2),cu=e=>Va(e,e),hu=e=>Va(e,e,e),pu=e=>Va(e,e,e,e),gu=dn(uo,uo.TRANSFORM_DIRECTION).setParameterLength(2),mu=(e,t)=>Ao(Va(t,Ln(An(e),0)).xyz),fu=(e,t)=>Ao(Ln(An(e),0).mul(t).xyz),yu=e=>Va($o(e),du(zo(e),1/3)),bu=e=>uu(e,e),xu=dn(uo,uo.MIX).setParameterLength(3),Tu=(e,t=0,r=1)=>new uo(uo.CLAMP,sn(e),sn(t),sn(r)),_u=e=>Tu(e),vu=dn(uo,uo.REFRACT).setParameterLength(3),Nu=dn(uo,uo.SMOOTHSTEP).setParameterLength(3),Su=dn(uo,uo.FACEFORWARD).setParameterLength(3),Eu=gn(([e])=>{const t=uu(e.xy,Sn(12.9898,78.233)),r=Ga(t,ho);return Co(Mo(r).mul(43758.5453))}),Ru=(e,t,r)=>xu(t,r,e),wu=(e,t,r)=>Nu(t,r,e),Au=(e,t)=>iu(t,e),Cu=Su,Mu=Eo;Ai("all",fo),Ai("any",yo),Ai("radians",bo),Ai("degrees",xo),Ai("exp",To),Ai("exp2",_o),Ai("log",vo),Ai("log2",No),Ai("sqrt",So),Ai("inverseSqrt",Eo),Ai("floor",Ro),Ai("ceil",wo),Ai("normalize",Ao),Ai("fract",Co),Ai("sin",Mo),Ai("sinh",Bo),Ai("cos",Lo),Ai("cosh",Fo),Ai("tan",Po),Ai("tanh",Uo),Ai("asin",Do),Ai("asinh",Oo),Ai("acos",Io),Ai("acosh",Vo),Ai("atan",ko),Ai("atanh",Go),Ai("abs",zo),Ai("sign",$o),Ai("length",Wo),Ai("lengthSq",bu),Ai("negate",Ho),Ai("oneMinus",jo),Ai("dFdx",qo),Ai("dFdy",Xo),Ai("round",Yo),Ai("reciprocal",Qo),Ai("trunc",Ko),Ai("fwidth",Zo),Ai("min",ru),Ai("max",su),Ai("step",Au),Ai("reflect",nu),Ai("distance",au),Ai("dot",uu),Ai("cross",lu),Ai("pow",du),Ai("pow2",cu),Ai("pow3",hu),Ai("pow4",pu),Ai("transformDirection",gu),Ai("transformNormalByViewMatrix",mu),Ai("transformNormalByInverseViewMatrix",fu),Ai("mix",Ru),Ai("clamp",Tu),Ai("refract",vu),Ai("smoothstep",wu),Ai("faceForward",Su),Ai("difference",ou),Ai("saturate",_u),Ai("cbrt",yu),Ai("transpose",Jo),Ai("determinant",eu),Ai("inverse",tu),Ai("rand",Eu);class Bu extends pi{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}generateNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const s=t.getNodeType(e);if(null!==r){const t=r.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(s))return t}return s}setup(e){const t=this.condNode,r=this.ifNode.isolate(),s=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?r:r.context({nodeBlock:r}),a.elseNode=s?n?s:s.context({nodeBlock:s}):null}generate(e,t){const r=this.getNodeType(e),s=e.getDataFromNode(this);if(void 0!==s.nodeProperty)return s.nodeProperty;const{condNode:i,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,u="void"!==t,l=u?zn(r).build(e):"";s.nodeProperty=l;const c=i.build(e,"bool");if(e.context.uniformFlow&&null!==a){const s=n.build(e,r),i=a.build(e,r),o=e.getTernary(c,s,i);return e.format(o,r,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=n.build(e,r);if(h&&(u?h=l+" = "+h+";":(h="return "+h+";",null===o&&(d("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),h="// "+h))),e.removeFlowTab().addFlowCode(e.tab+"\t"+h+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(d("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const Lu=un(Bu).setParameterLength(2,3);Ai("select",Lu);class Fu extends pi{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const r=e.addContext(this.value),s=this.node.build(e,t);return e.setContext(r),s}}const Pu=(e=null,t={})=>{let r=e;return null!==r&&!0===r.isNode||(t=r||t,r=null),new Fu(r,t)},Uu=e=>Pu(e,{uniformFlow:!0}),Du=(e,t)=>Pu(e,{nodeName:t});function Ou(e,t,r=null){return Pu(r,{getShadow:({light:r,shadowColorNode:s})=>t===r?s.mul(e):s})}function Iu(e,t=null){return Pu(t,{getAO:(t,{material:r})=>!0===r.transparent?t:null!==t?t.mul(e):e})}function Vu(e,t){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),Du(e,t)}Ai("context",Pu),Ai("label",Vu),Ai("uniformFlow",Uu),Ai("setName",Du),Ai("builtinShadowContext",(e,t,r)=>Ou(t,r,e)),Ai("builtinAOContext",(e,t)=>Iu(t,e));class ku extends pi{static get type(){return"VarNode"}constructor(e,t=null,r=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=r,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0],r=this.getShared(t);if(this!==r)return r.build(...e);if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const r=t.getBaseStack();e?r.addToStackBefore(this):r.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,u=!1;s&&(a=e.isDeterministic(t),u=n?s:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&o('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const d=e.getVectorType(l),c=t.build(e,d),h=e.getVarFromNode(this,r,d,void 0,u),p=e.getPropertyName(h);let g=p;if(u)if(n)g=a?`const ${p}`:`let ${p}`;else{const r=t.getArrayCount(e);g=`const ${e.getVar(h.type,p,r)}`}return e.addLineFlowCode(`${g} = ${c}`,this),p}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Gu=un(ku),zu=(e,t=null)=>Gu(e,t).toStack(),$u=(e,t=null)=>Gu(e,t,!0).toStack(),Wu=e=>Gu(e).setIntent(!0).toStack();Ai("toVar",zu),Ai("toConst",$u),Ai("toVarIntent",Wu);class Hu extends pi{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const r=this.node.build(e,...t);return e.removeSubBuild(),r}}const ju=(e,t,r=null)=>new Hu(sn(e),t,r);class qu extends pi{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=ju(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let r=t.varying;if(void 0===r){const s=this.name,i=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=r=e.getVaryingFromNode(this,s,i,n,a),t.node=ju(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(si.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(si.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),r=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===r[t]){const i=this.getNodeType(e),n=e.getPropertyName(s,si.VERTEX);if(e.shaderStage===si.VERTEX){const t=r.node.build(e,i);e.addLineFlowCode(`${n} = ${t}`,this)}else e.flowNodeFromShaderStage(si.VERTEX,r.node,i,n);r[t]=n}return e.getPropertyName(s)}}const Xu=un(qu).setParameterLength(1,2),Yu=e=>Xu(e);Ai("toVarying",Xu),Ai("toVertexStage",Yu);const Qu=gn(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return xu(t,r,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Ku=gn(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return xu(t,r,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Zu="WorkingColorSpace";class Ju extends fi{static get type(){return"ColorSpaceNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.source=t,this.target=r}resolveColorSpace(e,t){return t===Zu?p.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,r=this.resolveColorSpace(e,this.source),s=this.resolveColorSpace(e,this.target);let i=t;return!1!==p.enabled&&r!==s&&r&&s?(p.getTransfer(r)===g&&(i=Ln(Qu(i.rgb),i.a)),p.getPrimaries(r)!==p.getPrimaries(s)&&(i=Ln(On(p._getMatrix(new n,r,s)).mul(i.rgb),i.a)),p.getTransfer(s)===g&&(i=Ln(Ku(i.rgb),i.a)),i):i}}const el=(e,t)=>new Ju(sn(e),Zu,t),tl=(e,t)=>new Ju(sn(e),t,Zu);Ai("workingToColorSpace",el),Ai("colorSpaceToWorking",tl);let rl=class extends gi{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class sl extends pi{static get type(){return"ReferenceBaseNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.updateType=ii.OBJECT}setGroup(e){return this.group=e,this}element(e){return new rl(this,sn(e))}setNodeType(e){const t=Aa(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}generateNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;e<t.length;e++)r=r[t[e]];return r}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}class il extends sl{static get type(){return"RendererReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.renderer=r,this.setGroup(Ea)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const nl=(e,t,r=null)=>new il(e,t,r);class al extends fi{static get type(){return"ToneMappingNode"}constructor(e,t=ul,r=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return $s(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,r=this._toneMapping;if(r===m)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=Ln(i(t.rgb,this.exposureNode),t.a):(o("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const ol=(e,t,r)=>new al(e,sn(t),sn(r)),ul=nl("toneMappingExposure","float");Ai("toneMapping",(e,t,r)=>ol(t,r,e));const ll=new WeakMap;function dl(e,t){let r=ll.get(e);return void 0===r&&(r=new b(e,t),ll.set(e,r)),r}class cl extends vi{static get type(){return"BufferAttributeNode"}constructor(e,t=null,r=0,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=r,this.bufferOffset=s,this.usage=f,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){let t;if(0===this.bufferStride&&0===this.bufferOffset){let r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.node.id}else t=this.id;return String(t)}generateNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),r=e.getTypeLength(t),s=this.value,i=this.bufferStride||r,n=this.bufferOffset;let a;a=!0===s.isInterleavedBuffer?s:!0===s.isBufferAttribute?dl(s.array,i):dl(s,i);const o=new y(a,r,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),r=e.context.nodeName;void 0!==r&&delete e.context.nodeName;const s=e.getBufferAttributeFromNode(this,t,r),i=e.getPropertyName(s);let n=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,n=i;else{let s;r&&(s=r+"Varying");n=Xu(this,s).build(e,t)}return n}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function hl(e,t=null,r=0,s=0,i=f,n=!1){return"mat3"===t||null===t&&9===e.itemSize?On(new cl(e,"vec3",9,0).setUsage(i).setInstanced(n),new cl(e,"vec3",9,3).setUsage(i).setInstanced(n),new cl(e,"vec3",9,6).setUsage(i).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?In(new cl(e,"vec4",16,0).setUsage(i).setInstanced(n),new cl(e,"vec4",16,4).setUsage(i).setInstanced(n),new cl(e,"vec4",16,8).setUsage(i).setInstanced(n),new cl(e,"vec4",16,12).setUsage(i).setInstanced(n)):new cl(e,t,r,s).setUsage(i)}const pl=(e,t=null,r=0,s=0)=>hl(e,t,r,s),gl=(e,t=null,r=0,s=0)=>hl(e,t,r,s,f,!0),ml=(e,t=null,r=0,s=0)=>hl(e,t,r,s,x,!0);Ai("toAttribute",e=>pl(e.value));class fl extends pi{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),r=this.scope;let s,i;if(r===fl.VERTEX)s=e.getVertexIndex();else if(r===fl.INSTANCE)s=e.getInstanceIndex();else if(r===fl.DRAW)s=e.getDrawIndex();else if(r===fl.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===fl.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==fl.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=Xu(this).build(e,t)}return i}}fl.VERTEX="vertex",fl.INSTANCE="instance",fl.SUBGROUP="subgroup",fl.INVOCATION_LOCAL="invocationLocal",fl.INVOCATION_SUBGROUP="invocationSubgroup",fl.DRAW="draw";const yl=ln(fl,fl.VERTEX),bl=ln(fl,fl.INSTANCE),xl=ln(fl,fl.SUBGROUP),Tl=ln(fl,fl.INVOCATION_SUBGROUP),_l=ln(fl,fl.INVOCATION_LOCAL),vl=ln(fl,fl.DRAW);class Nl extends pi{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=ii.OBJECT,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Vs),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=Aa(this.count,"uint").onObjectUpdate(()=>this.count));const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:r}=e;if("compute"===r){const t=this.computeNode.build(e,"void");if(""!==t&&e.addLineFlowCode(t,this),null!==this.count&&!0===e.allowEarlyReturns){const t=this.countNode.build(e,"uint"),r=bl.build(e,"uint");e.flow.code=`${e.tab}if ( ${r} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const r=e.getNodeProperties(this).outputComputeNode;if(r)return r.build(e,t)}}}const Sl=(e,t=[64])=>{(0===t.length||t.length>3)&&o("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Vs);for(let e=0;e<t.length;e++){const r=t[e];("number"!=typeof r||r<=0||!Number.isInteger(r))&&o(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new Vs)}for(;t.length<3;)t.push(1);return new Nl(sn(e),t)},El=(e,t,r)=>{const s=Sl(e,r);return"number"==typeof t?s.count=t:s.dispatchSize=t,s};Ai("compute",El),Ai("computeKernel",Sl);class Rl extends pi{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){const t=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const s=this.node.getNodeType(e);return e.setCache(t),s}build(e,...t){const r=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.build(e,...t);return e.setCache(r),i}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const wl=e=>new Rl(sn(e));function Al(e,t=!0){return d('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),wl(e).setParent(t)}Ai("cache",Al),Ai("isolate",wl);class Cl extends pi{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Ml=un(Cl).setParameterLength(2);Ai("bypass",Ml);const Bl=gn(([e,t,r,s=Tn(0),i=Tn(1),n=Nn(!1)])=>{let a=e.sub(t).div(r.sub(t));return en(n)&&(a=a.clamp()),a.mul(i.sub(s)).add(s)});function Ll(e,t,r,s=Tn(0),i=Tn(1)){return Bl(e,t,r,s,i,!0)}Ai("remap",Bl),Ai("remapClamp",Ll);class Fl extends pi{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const r=this.getNodeType(e),s=this.snippet;if("void"!==r)return e.format(s,r,t);e.addLineFlowCode(s,this)}}const Pl=un(Fl).setParameterLength(1,2),Ul=e=>(e?Lu(e,Pl("discard")):Pl("discard")).toStack();Ai("discard",Ul);const Dl=gn(([e])=>Ln(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),Ol=gn(([e])=>e.a.equal(0).select(Ln(0),Ln(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class Il extends fi{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;t=Ln(t.rgb,t.a.clamp(0,1)),t=Ol(t);const r=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||m,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||T;return r!==m&&(t=t.toneMapping(r)),s!==T&&s!==p.workingColorSpace&&(t=t.workingToColorSpace(s)),t=Dl(t),t}}const Vl=(e,t=null,r=null)=>new Il(sn(e),t,r);Ai("renderOutput",Vl);class kl extends fi{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,r=this.node.build(e);if(null!==t)t(e,r);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(t.length);let i="";i+="// #"+t+"#\n",i+=e.flow.code.replace(/^\t/gm,"")+"\n",i+="/* ... */ "+r+" /* ... */\n",i+="// #"+s+"#\n",_(i)}return r}}const Gl=(e,t=null)=>new kl(sn(e),t).toStack();Ai("debug",Gl);class zl extends u{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class $l extends pi{static get type(){return"InspectorNode"}constructor(e,t="",r=null){super(),this.node=e,this.name=t,this.callback=r,this.updateType=ii.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==zl&&v('TSL: ".toInspector()" is only available with WebGPU.'),t}}function Wl(e,t="",r=null){return(e=sn(e)).before(new $l(e,t,r))}Ai("toInspector",Wl);class Hl extends pi{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(e){let t=this.nodeType;if(null===t){const r=this.getAttributeName(e);if(e.hasGeometryAttribute(r)){const s=e.geometry.getAttribute(r);t=e.getTypeFromAttribute(s)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),r=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const s=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(s),n=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(n.name,i,r);return Xu(this).build(e,r)}return d(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(r)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const jl=(e,t=null)=>new Hl(e,t),ql=(e=0)=>jl("uv"+(e>0?e:""),"vec2");class Xl extends pi{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const r=this.textureNode.build(e,"property"),s=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${r}, ${s} )`,this.getNodeType(e),t)}}const Yl=un(Xl).setParameterLength(1,2);class Ql extends wa{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=ii.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,r=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(r&&void 0!==r.width){const{width:e,height:t}=r;this.value=Math.log2(Math.max(e,t))}}}const Kl=un(Ql).setParameterLength(1);class Zl extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Jl=new N;class ed extends wa{static get type(){return"TextureNode"}constructor(e=Jl,t=null,r=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=r,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.gatherNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ii.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return!0===this.value.isDepthTexture?null===this.gatherNode?"float":"vec4":this.value.type===S?"uvec4":this.value.type===E?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return ql(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Aa(this.value.matrix)),this._matrixUniform.mul(An(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=Aa(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(_n(Yl(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Zl("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const s=gn(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?ii.OBJECT:ii.NONE,t})();let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(R.TEXTURE_COMPARE))n=this.compareNode;else{const e=r.compareFunction;null===e||e===w||e===A||e===C||e===M?a=this.compareNode:(n=this.compareNode,v('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,t.gradNode=this.gradNode,t.gatherNode=this.gatherNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,r,s,i,n,a,o,u,l,d){const c=this.value;let h;return h=i?e.generateTextureBias(c,t,r,i,n,l):o?e.generateTextureGrad(c,t,r,o,n,l):u?a?e.generateTextureGatherCompare(c,t,r,a,n,l,d):e.generateTextureGather(c,t,r,u,n,l,d):a?e.generateTextureCompare(c,t,r,a,n,l):!1===this.sampler?e.generateTextureLoad(c,t,r,s,n,l):s?e.generateTextureLevel(c,t,r,s,n,l):e.generateTexture(c,t,r,n,l),h}generate(e,t){const r=this.value,s=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this);let a=this.getNodeType(e),o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:u,biasNode:l,compareNode:d,compareStepNode:c,depthNode:h,gradNode:p,gatherNode:g,offsetNode:m}=s,f=this.generateUV(e,t),y=u?u.build(e,"float"):null,b=l?l.build(e,"float"):null,x=h?h.build(e,"int"):null,T=d?d.build(e,"float"):null,_=c?c.build(e,"float"):null,v=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,N=g?g.build(e,"int"):null,S=m?this.generateOffset(e,m):null,E=this._flipYUniform?this._flipYUniform.build(e,"bool"):null;N&&(a="vec4");let R=x;null===R&&r.isArrayTexture&&!0!==this.isTexture3DNode&&(R="0");const w=e.getVarFromNode(this);o=e.getPropertyName(w);let A=this.generateSnippet(e,i,f,y,b,R,T,v,N,S,E);if(null!==_){const t=r.compareFunction;A=t===C||t===M?iu(Pl(A,a),Pl(_,"float")).build(e,a):iu(Pl(_,"float"),Pl(A,a)).build(e,a)}e.addLineFlowCode(`${o} = ${A}`,this),n.snippet=A,n.propertyName=o}let u=o;return e.needsToWorkingColorSpace(r)&&(u=tl(Pl(u,a),r.colorSpace).setup(e).build(e,a)),e.format(u,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=sn(e),t.referenceNode=this.getBase(),sn(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=sn(e).mul(Kl(t)),t.referenceNode=this.getBase();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===B||r.magFilter===B)&&(d("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),sn(t)}level(e){const t=this.clone();return t.levelNode=sn(e),t.referenceNode=this.getBase(),sn(t)}size(e){return Yl(this,e)}bias(e){const t=this.clone();return t.biasNode=sn(e),t.referenceNode=this.getBase(),sn(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=sn(e),t.referenceNode=this.getBase(),sn(t)}grad(e,t){const r=this.clone();return r.gradNode=[sn(e),sn(t)],r.referenceNode=this.getBase(),sn(r)}gather(e=0){const t=this.clone();return t.gatherNode=sn(e),t.referenceNode=this.getBase(),sn(t)}depth(e){const t=this.clone();return t.depthNode=sn(e),t.referenceNode=this.getBase(),sn(t)}offset(e){const t=this.clone();return t.offsetNode=sn(e),t.referenceNode=this.getBase(),sn(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const r=this._flipYUniform;null!==r&&(r.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}}const td=un(ed).setParameterLength(1,4).setName("texture"),rd=(e=Jl,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=sn(e.clone()),i.referenceNode=e.getBase(),null!==t&&(i.uvNode=sn(t)),null!==r&&(i.levelNode=sn(r)),null!==s&&(i.biasNode=sn(s))):i=td(e,t,r,s),i},sd=(...e)=>rd(...e).setSampler(!1);class id extends wa{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const nd=(e,t,r)=>new id(e,t,r);class ad extends gi{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(e),s=this.node.getPaddedType();return e.format(t,s,r)}}class od extends id{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ks(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=ii.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;r<e.length;r++){t[4*r]=e[r]}else if("color"===r)for(let r=0;r<e.length;r++){const s=4*r,i=e[r];t[s]=i.r,t[s+1]=i.g,t[s+2]=i.b||0}else if("mat2"===r)for(let r=0;r<e.length;r++){const s=4*r,i=e[r];t[s]=i.elements[0],t[s+1]=i.elements[1],t[s+2]=i.elements[2],t[s+3]=i.elements[3]}else if("mat3"===r)for(let r=0;r<e.length;r++){const s=16*r,i=e[r];t[s]=i.elements[0],t[s+1]=i.elements[1],t[s+2]=i.elements[2],t[s+4]=i.elements[3],t[s+5]=i.elements[4],t[s+6]=i.elements[5],t[s+8]=i.elements[6],t[s+9]=i.elements[7],t[s+10]=i.elements[8],t[s+15]=1}else if("mat4"===r)for(let r=0;r<e.length;r++){const s=16*r,i=e[r];for(let e=0;e<i.elements.length;e++)t[s+e]=i.elements[e]}else for(let r=0;r<e.length;r++){const s=4*r,i=e[r];t[s]=i.x,t[s+1]=i.y,t[s+2]=i.z||0,t[s+3]=i.w||0}}setup(e){const t=this.array.length,r=this.elementType;let s=Float32Array;const i=this.paddedType,n=e.getTypeLength(i);return"i"===r.charAt(0)&&(s=Int32Array),"u"===r.charAt(0)&&(s=Uint32Array),this.value=new s(t*n),this.bufferCount=t,this.bufferType=i,this.update(),super.setup(e)}element(e){return new ad(this,sn(e))}}const ud=(e,t)=>new od(e,t);class ld extends pi{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const dd=un(ld).setParameterLength(1);let cd,hd;class pd extends pi{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===pd.DPR?"float":this.scope===pd.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=ii.NONE;return this.scope!==pd.SIZE&&this.scope!==pd.VIEWPORT&&this.scope!==pd.DPR||(e=ii.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===pd.VIEWPORT?null!==t?hd.copy(t.viewport):(e.getViewport(hd),hd.multiplyScalar(e.getPixelRatio())):this.scope===pd.DPR?this._output.value=e.getPixelRatio():null!==t?(cd.width=t.width,cd.height=t.height):e.getDrawingBufferSize(cd)}setup(){const e=this.scope;let r=null;return r=e===pd.SIZE?Aa(cd||(cd=new t)):e===pd.VIEWPORT?Aa(hd||(hd=new s)):e===pd.DPR?Aa(1):Sn(yd.div(fd)),this._output=r,r}generate(e){if(this.scope===pd.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(fd).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}pd.COORDINATE="coordinate",pd.VIEWPORT="viewport",pd.SIZE="size",pd.UV="uv",pd.DPR="dpr";const gd=ln(pd,pd.DPR),md=ln(pd,pd.UV),fd=ln(pd,pd.SIZE),yd=ln(pd,pd.COORDINATE),bd=ln(pd,pd.VIEWPORT),xd=bd.zw,Td=yd.sub(bd.xy),_d=Td.div(xd),vd=gn(()=>(d('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.',new Vs),fd),"vec2").once()();let Nd=null,Sd=null,Ed=null,Rd=null,wd=null,Ad=null,Cd=null,Md=null,Bd=null,Ld=null,Fd=null,Pd=null,Ud=null,Dd=null;const Od=Aa(0,"uint").setName("u_cameraIndex").setGroup(Na("cameraIndex")).toVarying("v_cameraIndex"),Id=Aa("float").setName("cameraNear").setGroup(Ea).onRenderUpdate(({camera:e})=>e.near),Vd=Aa("float").setName("cameraFar").setGroup(Ea).onRenderUpdate(({camera:e})=>e.far),kd=gn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);null===Sd?Sd=ud(r).setGroup(Ea).setName("cameraProjectionMatrices"):Sd.array=r,t=Sd.element(e.isMultiViewCamera?dd("gl_ViewID_OVR"):Od)}else null===Nd&&(Nd=Aa(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(Ea).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=Nd;return t}).once()(),Gd=gn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);null===Rd?Rd=ud(r).setGroup(Ea).setName("cameraProjectionMatricesInverse"):Rd.array=r,t=Rd.element(e.isMultiViewCamera?dd("gl_ViewID_OVR"):Od)}else null===Ed&&(Ed=Aa(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(Ea).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=Ed;return t}).once()(),zd=gn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);null===Ad?Ad=ud(r).setGroup(Ea).setName("cameraViewMatrices"):Ad.array=r,t=Ad.element(e.isMultiViewCamera?dd("gl_ViewID_OVR"):Od)}else null===wd&&(wd=Aa(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(Ea).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=wd;return t}).once()(),$d=gn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorld);null===Md?Md=ud(r).setGroup(Ea).setName("cameraWorldMatrices"):Md.array=r,t=Md.element(e.isMultiViewCamera?dd("gl_ViewID_OVR"):Od)}else null===Cd&&(Cd=Aa(e.matrixWorld).setName("cameraWorldMatrix").setGroup(Ea).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=Cd;return t}).once()(),Wd=gn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.normalMatrix);null===Ld?Ld=ud(r).setGroup(Ea).setName("cameraNormalMatrices"):Ld.array=r,t=Ld.element(e.isMultiViewCamera?dd("gl_ViewID_OVR"):Od)}else null===Bd&&(Bd=Aa(e.normalMatrix).setName("cameraNormalMatrix").setGroup(Ea).onRenderUpdate(({camera:e})=>e.normalMatrix)),t=Bd;return t}).once()(),Hd=gn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t<i;t++)s.push(new r);null===Pd?Pd=ud(s).setGroup(Ea).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const r=e.cameras,s=t.array;for(let e=0,t=r.length;e<t;e++)s[e].setFromMatrixPosition(r[e].matrixWorld)}):Pd.array=s,t=Pd.element(e.isMultiViewCamera?dd("gl_ViewID_OVR"):Od)}else null===Fd&&(Fd=Aa(new r).setName("cameraPosition").setGroup(Ea).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),t=Fd;return t}).once()(),jd=gn(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.viewport);null===Dd?Dd=ud(r,"vec4").setGroup(Ea).setName("cameraViewports"):Dd.array=r,t=Dd.element(Od)}else null===Ud&&(Ud=Ln(0,0,fd.x,fd.y).toConst("cameraViewport")),t=Ud;return t}).once()(),qd=new L;class Xd extends pi{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ii.OBJECT,this.uniformNode=new wa(null)}generateNodeType(){const e=this.scope;return e===Xd.WORLD_MATRIX?"mat4":e===Xd.POSITION||e===Xd.VIEW_POSITION||e===Xd.DIRECTION||e===Xd.SCALE?"vec3":e===Xd.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Xd.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Xd.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Xd.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Xd.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===Xd.VIEW_POSITION){const i=e.camera;s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Xd.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),qd.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=qd.radius}}generate(e){const t=this.scope;return t===Xd.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Xd.POSITION||t===Xd.VIEW_POSITION||t===Xd.DIRECTION||t===Xd.SCALE?this.uniformNode.nodeType="vec3":t===Xd.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Xd.WORLD_MATRIX="worldMatrix",Xd.POSITION="position",Xd.SCALE="scale",Xd.VIEW_POSITION="viewPosition",Xd.DIRECTION="direction",Xd.RADIUS="radius";const Yd=un(Xd,Xd.DIRECTION).setParameterLength(1),Qd=un(Xd,Xd.WORLD_MATRIX).setParameterLength(1),Kd=un(Xd,Xd.POSITION).setParameterLength(1),Zd=un(Xd,Xd.SCALE).setParameterLength(1),Jd=un(Xd,Xd.VIEW_POSITION).setParameterLength(1),ec=un(Xd,Xd.RADIUS).setParameterLength(1);class tc extends Xd{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const rc=ln(tc,tc.DIRECTION),sc=ln(tc,tc.WORLD_MATRIX),ic=ln(tc,tc.POSITION),nc=ln(tc,tc.SCALE),ac=ln(tc,tc.VIEW_POSITION),oc=ln(tc,tc.RADIUS),uc=Aa(new n).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),lc=Aa(new a).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),dc=gn(e=>e.context.modelViewMatrix||cc).once()().toVar("modelViewMatrix"),cc=zd.mul(sc),hc=gn(e=>(e.context.isHighPrecisionModelViewMatrix=!0,Aa("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),pc=gn(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Aa("mat3").onObjectUpdate(({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),gc=gn(e=>"fragment"!==e.shaderStage?(v("TSL: `clipSpace` is only available in fragment stage."),Ln()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),mc=jl("position","vec3"),fc=mc.toVarying("positionLocal"),yc=mc.toVarying("positionPrevious"),bc=gn(e=>sc.mul(fc).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),xc=gn(()=>fc.transformDirection(sc).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Tc=gn(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=Gd.mul(gc);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),_c=gn(e=>{let t;return t=e.camera.isOrthographicCamera?An(0,0,1):Tc.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class vc extends pi{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return t.side===F?"false":e.getFrontFacing()}}const Nc=ln(vc),Sc=Tn(Nc).mul(2).sub(1),Ec=gn(([e],{material:t})=>{const r=t.side;return r===F?e=e.mul(-1):r===P&&(e=e.mul(Sc)),e}),Rc=jl("normal","vec3"),wc=gn(e=>!1===e.geometry.hasAttribute("normal")?(d('TSL: Vertex attribute "normal" not found on geometry.'),An(0,1,0)):Rc,"vec3").once()().toVar("normalLocal"),Ac=Tc.dFdx().cross(Tc.dFdy()).normalize().toVar("normalFlat"),Cc=gn(e=>{let t;return t=e.isFlatShading()?Ac:Uc(wc).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Mc=gn(e=>{let t=Cc.transformNormalByInverseViewMatrix(zd);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Bc=gn(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=Cc,!0!==e.isFlatShading()&&(t=Ec(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Lc=Bc.transformNormalByInverseViewMatrix(zd).toVar("normalWorld"),Fc=gn(({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Bc:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Pc=gn(([e,t=sc])=>On(t).inverse().transpose().mul(e).normalize());Ai("transformNormal",Pc);const Uc=gn(([e],t)=>{const r=t.context.modelNormalViewMatrix;if(r)return e.transformNormalByViewMatrix(r);return uc.mul(e).transformNormalByViewMatrix(zd)}),Dc=gn(()=>(d('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Bc)).once(["NORMAL","VERTEX"])(),Oc=gn(()=>(d('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Lc)).once(["NORMAL","VERTEX"])(),Ic=gn(()=>(d('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Fc)).once(["NORMAL","VERTEX"])(),Vc=new a,kc=Aa(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Gc=Aa(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),zc=Aa(new a).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const r=(null!==t.environment||t.environmentNode&&t.environmentNode.isNode)&&null===e.envMap?t.environmentRotation:e.envMapRotation;return r?Vc.makeRotationFromEuler(r).transpose():Vc.identity(),Vc}),$c=_c.negate().reflect(Bc),Wc=_c.negate().refract(Bc,kc),Hc=$c.transformDirection($d).toVar("reflectVector"),jc=Wc.transformDirection($d).toVar("refractVector"),qc=new U;class Xc extends ed{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===D?Hc:e.mapping===O?jc:(o('CubeTextureNode: Mapping "%s" not supported.',e.mapping),An(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!0===r.isDepthTexture?e.renderer.coordinateSystem===h?An(t.x,t.y.negate(),t.z):t:(t=zc.mul(t),e.renderer.coordinateSystem!==h&&r.isRenderTargetTexture||(t=An(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const Yc=un(Xc).setParameterLength(1,4).setName("cubeTexture"),Qc=(e=qc,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=sn(e.clone()),i.referenceNode=e,null!==t&&(i.uvNode=sn(t)),null!==r&&(i.levelNode=sn(r)),null!==s&&(i.biasNode=sn(s))):i=Yc(e,t,r,s),i};class Kc extends gi{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(e),s=this.getNodeType(e);return e.format(t,r,s)}}class Zc extends pi{static get type(){return"ReferenceNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.name=null,this.updateType=ii.OBJECT}element(e){return new Kc(this,sn(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;null!==this.count?t=nd(null,e,this.count):Array.isArray(this.getValueFromReference())?(t=ud(null,e),t.updateType=ii.OBJECT):t="texture"===e?rd(null):"cubeTexture"===e?Qc(null):Aa(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}generateNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;e<t.length;e++)r=r[t[e]];return r}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Jc=(e,t,r)=>new Zc(e,t,r),eh=(e,t,r,s)=>new Zc(e,t,s,r);class th extends Zc{static get type(){return"MaterialReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.material=r,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const rh=(e,t,r=null)=>new th(e,t,r),sh=ql(),ih=Tc.dFdx(),nh=Tc.dFdy(),ah=sh.dFdx(),oh=sh.dFdy(),uh=Bc,lh=nh.cross(uh),dh=uh.cross(ih),ch=lh.mul(ah.x).add(dh.mul(oh.x)),hh=lh.mul(ah.y).add(dh.mul(oh.y)),ph=ch.dot(ch).max(hh.dot(hh)),gh=ph.equal(0).select(0,ph.inverseSqrt()),mh=ch.mul(gh).toVar("tangentViewFrame"),fh=hh.mul(gh).toVar("bitangentViewFrame"),yh=jl("tangent","vec4"),bh=yh.xyz.toVar("tangentLocal"),xh=gn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?dc.mul(Ln(bh,0)).xyz.toVarying("v_tangentView").normalize():mh,!0!==e.isFlatShading()&&(t=Ec(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),Th=xh.transformDirection($d).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),_h=gn(([e,t],r)=>{let s=e.mul(yh.w).xyz;return"NORMAL"===r.subBuildFn&&!0!==r.isFlatShading()&&(s=s.toVarying(t)),s}).once(["NORMAL"]),vh=_h(Rc.cross(yh),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Nh=_h(wc.cross(bh),"v_bitangentLocal").normalize().toVar("bitangentLocal"),Sh=gn(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?_h(Bc.cross(xh),"v_bitangentView").normalize():fh,!0!==e.isFlatShading()&&(t=Ec(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Eh=_h(Lc.cross(Th),"v_bitangentWorld").normalize().toVar("bitangentWorld"),Rh=On(xh,Sh,Bc).toVar("TBNViewMatrix"),wh=_c.mul(Rh),Ah=gn(()=>{let e=na.cross(_c);return e=e.cross(na).normalize(),e=xu(e,Bc,sa.mul(qn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),Ch=e=>sn(e).mul(.5).add(.5),Mh=e=>sn(e).mul(2).sub(1),Bh=e=>An(e,So(_u(Tn(1).sub(uu(e,e)))));class Lh extends fi{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=I,this.unpackNormalMode=V}setup(e){const{normalMapType:t,scaleNode:r,unpackNormalMode:s}=this;let i=this.node.mul(2).sub(1);if(t===I?s===k?i=Bh(i.xy):s===G?i=Bh(i.yw):s!==V&&o(`THREE.NodeMaterial: Unexpected unpack normal mode: ${s}`):s!==V&&o(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${s}'`),null!==r){let t=r;!0===e.isFlatShading()&&(t=Ec(t)),i=An(i.xy.mul(t),i.z)}let n=null;return t===z?n=Uc(i):t===I?n=Rh.mul(i).normalize():(o(`NodeMaterial: Unsupported normal map type: ${t}`),n=Bc),n}}const Fh=un(Lh).setParameterLength(1,2),Ph=gn(({textureNode:e,bumpScale:t})=>{const r=t=>e.isolate().context({getUV:e=>t(e.uvNode||ql()),forceUVContext:!0}),s=Tn(r(e=>e));return Sn(Tn(r(e=>e.add(e.dFdx()))).sub(s),Tn(r(e=>e.add(e.dFdy()))).sub(s)).mul(t)}),Uh=gn(e=>{const{surf_pos:t,surf_norm:r,dHdxy:s}=e,i=t.dFdx().normalize(),n=r,a=t.dFdy().normalize().cross(n),o=n.cross(i),u=i.dot(a).mul(Sc),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()});class Dh extends fi{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(e){if(!0===e.material.wireframe)return Bc;const t=null!==this.scaleNode?this.scaleNode:1,r=Ph({textureNode:this.textureNode,bumpScale:t});return Uh({surf_pos:Tc,surf_norm:Bc,dHdxy:r})}}const Oh=un(Dh).setParameterLength(1,2),Ih=new Map;class Vh extends pi{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=Ih.get(e);return void 0===r&&(r=rh(e,t),Ih.set(e,r)),r}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,r=this.scope;let s=null;if(r===Vh.COLOR){const e=void 0!==t.color?this.getColor(r):An();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Vh.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Vh.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Tn(1);else if(r===Vh.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Vh.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Vh.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Vh.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Vh.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(r).mul(e);s=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(r)):i}else if(r===Vh.NORMAL)t.normalMap?(s=Fh(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType,t.normalMap.format!=$&&t.normalMap.format!=W&&t.normalMap.format!=H||(s.unpackNormalMode=k)):s=t.bumpMap?Oh(this.getTexture("bump").r,this.getFloat("bumpScale")):Bc;else if(r===Vh.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Vh.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Vh.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Fh(this.getTexture(r),this.getCache(r+"Scale","vec2")):Bc;else if(r===Vh.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));s=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(r===Vh.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(1e-4,1)}else if(r===Vh.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=Dn(Np.x,Np.y,Np.y.negate(),Np.x).mul(e.rg.mul(2).sub(Sn(1)).normalize().mul(e.b))}else s=Np;else if(r===Vh.IRIDESCENCE_THICKNESS){const e=Jc("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=Jc("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Vh.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Vh.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Vh.IOR)s=this.getFloat(r);else if(r===Vh.LIGHT_MAP)s=t.lightMap?this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity")):An(0);else if(r===Vh.AO)s=t.aoMap?this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1):Tn(1);else if(r===Vh.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):Tn(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Vh.ALPHA_TEST="alphaTest",Vh.COLOR="color",Vh.OPACITY="opacity",Vh.SHININESS="shininess",Vh.SPECULAR="specular",Vh.SPECULAR_STRENGTH="specularStrength",Vh.SPECULAR_INTENSITY="specularIntensity",Vh.SPECULAR_COLOR="specularColor",Vh.REFLECTIVITY="reflectivity",Vh.ROUGHNESS="roughness",Vh.METALNESS="metalness",Vh.NORMAL="normal",Vh.CLEARCOAT="clearcoat",Vh.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Vh.CLEARCOAT_NORMAL="clearcoatNormal",Vh.EMISSIVE="emissive",Vh.ROTATION="rotation",Vh.SHEEN="sheen",Vh.SHEEN_ROUGHNESS="sheenRoughness",Vh.ANISOTROPY="anisotropy",Vh.IRIDESCENCE="iridescence",Vh.IRIDESCENCE_IOR="iridescenceIOR",Vh.IRIDESCENCE_THICKNESS="iridescenceThickness",Vh.IOR="ior",Vh.TRANSMISSION="transmission",Vh.THICKNESS="thickness",Vh.ATTENUATION_DISTANCE="attenuationDistance",Vh.ATTENUATION_COLOR="attenuationColor",Vh.LINE_SCALE="scale",Vh.LINE_DASH_SIZE="dashSize",Vh.LINE_GAP_SIZE="gapSize",Vh.LINE_WIDTH="linewidth",Vh.LINE_DASH_OFFSET="dashOffset",Vh.POINT_SIZE="size",Vh.DISPERSION="dispersion",Vh.LIGHT_MAP="light",Vh.AO="ao";const kh=ln(Vh,Vh.ALPHA_TEST),Gh=ln(Vh,Vh.COLOR),zh=ln(Vh,Vh.SHININESS),$h=ln(Vh,Vh.EMISSIVE),Wh=ln(Vh,Vh.OPACITY),Hh=ln(Vh,Vh.SPECULAR),jh=ln(Vh,Vh.SPECULAR_INTENSITY),qh=ln(Vh,Vh.SPECULAR_COLOR),Xh=ln(Vh,Vh.SPECULAR_STRENGTH),Yh=ln(Vh,Vh.REFLECTIVITY),Qh=ln(Vh,Vh.ROUGHNESS),Kh=ln(Vh,Vh.METALNESS),Zh=ln(Vh,Vh.NORMAL),Jh=ln(Vh,Vh.CLEARCOAT),ep=ln(Vh,Vh.CLEARCOAT_ROUGHNESS),tp=ln(Vh,Vh.CLEARCOAT_NORMAL),rp=ln(Vh,Vh.ROTATION),sp=ln(Vh,Vh.SHEEN),ip=ln(Vh,Vh.SHEEN_ROUGHNESS),np=ln(Vh,Vh.ANISOTROPY),ap=ln(Vh,Vh.IRIDESCENCE),op=ln(Vh,Vh.IRIDESCENCE_IOR),up=ln(Vh,Vh.IRIDESCENCE_THICKNESS),lp=ln(Vh,Vh.TRANSMISSION),dp=ln(Vh,Vh.THICKNESS),cp=ln(Vh,Vh.IOR),hp=ln(Vh,Vh.ATTENUATION_DISTANCE),pp=ln(Vh,Vh.ATTENUATION_COLOR),gp=ln(Vh,Vh.LINE_SCALE),mp=ln(Vh,Vh.LINE_DASH_SIZE),fp=ln(Vh,Vh.LINE_GAP_SIZE),yp=ln(Vh,Vh.LINE_WIDTH),bp=ln(Vh,Vh.LINE_DASH_OFFSET),xp=ln(Vh,Vh.POINT_SIZE),Tp=ln(Vh,Vh.DISPERSION),_p=ln(Vh,Vh.LIGHT_MAP),vp=ln(Vh,Vh.AO),Np=Aa(new t).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),Sp=gn(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class Ep extends pi{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===Ep.OBJECT?this.updateType=ii.OBJECT:e===Ep.MATERIAL?this.updateType=ii.RENDER:e===Ep.FRAME?this.updateType=ii.FRAME:e===Ep.BEFORE_OBJECT?this.updateBeforeType=ii.OBJECT:e===Ep.BEFORE_MATERIAL?this.updateBeforeType=ii.RENDER:e===Ep.BEFORE_FRAME&&(this.updateBeforeType=ii.FRAME)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}Ep.OBJECT="object",Ep.MATERIAL="material",Ep.FRAME="frame",Ep.BEFORE_OBJECT="beforeObject",Ep.BEFORE_MATERIAL="beforeMaterial",Ep.BEFORE_FRAME="beforeFrame";const Rp=(e,t)=>new Ep(e,t).toStack(),wp=e=>Rp(Ep.OBJECT,e),Ap=e=>Rp(Ep.FRAME,e);class Cp extends gi{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const r=this.storageBufferNode.structTypeNode;return r?r.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let r;const s=e.isContextAssign();if(r=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===s||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}const Mp=un(Cp).setParameterLength(2);class Bp extends id{static get type(){return"StorageBufferNode"}constructor(e,t=null,r=0){let s,i=null;t&&t.isStructTypeNode?(s="struct",i=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(r=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(s=js(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=ai.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){let t;if(0===this.bufferCount){let r=e.globalCache.getData(this.value);void 0===r&&(r={node:this},e.globalCache.setData(this.value,r)),t=r.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return Mp(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(ai.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=pl(this.value),this._varying=Xu(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:r}=this.getAttributeData(),s=r.build(e);return e.registerTransform(s,t),s}}const Lp=(e,t=null,r=0)=>new Bp(e,t,r),Fp=new WeakMap,Pp=new WeakMap,Up=new WeakMap;function Dp(e,t){let r;const s=Math.max(t.count,1);if(!0===t.isStorageInstancedBufferAttribute)r=Lp(t,"mat4",s).element(bl);else{if(16*s*4<=e.getUniformBufferLimit())r=nd(t.array,"mat4",s).element(bl);else{let e=Fp.get(t);e||(e=new q(t.array,16,1),Fp.set(t,e));const s=t.usage===x?ml:gl,i=[s(e,"vec4",16,0),s(e,"vec4",16,4),s(e,"vec4",16,8),s(e,"vec4",16,12)];r=In(...i)}}return r}const Op=$n("vec3","vInstanceColor"),Ip=gn(([e,t=null],r)=>{const s=!0===e.isStorageInstancedBufferAttribute,i=t&&!0===t.isStorageInstancedBufferAttribute,n=Dp(r,e);let a=null;if(!s){16*Math.max(e.count,1)*4>r.getUniformBufferLimit()&&(a=Fp.get(e))}let o=null,u=null;if(t)if(i)o=Lp(t,"vec3",Math.max(t.count,1)).element(bl);else{let e=Pp.get(t);e||(e=new j(t.array,3),Pp.set(t,e)),u=e;const r=t.usage===x?ml:gl;o=An(r(e,"vec3",3,0))}null===a&&null===u||Ap(()=>{null!==a&&(a.clearUpdateRanges(),a.updateRanges.push(...e.updateRanges),e.version!==a.version&&(a.version=e.version)),t&&null!==u&&(u.clearUpdateRanges(),u.updateRanges.push(...t.updateRanges),t.version!==u.version&&(u.version=t.version))});const l=n.mul(fc).xyz;if(fc.assign(l),r.needsPreviousData()){const t=r.object;wp(({object:t})=>{Up.get(t).previousInstanceMatrix.array.set(e.array)});const s=function(e,t,r){let s=Up.get(e);if(void 0===s){const i=t.clone();s={previousInstanceMatrix:i,node:Dp(r,i)},Up.set(e,s)}return s.node}(t,e,r);yc.assign(s.mul(yc).xyz)}if(r.hasGeometryAttribute("normal")){const e=Pc(wc,n);wc.assign(e)}null!==o&&Op.assign(o)},"void"),Vp=gn(([e])=>{const{instanceMatrix:t,instanceColor:r}=e;Ip(t,r)},"void"),kp=gn(([e,t])=>{const r=_n(Yl(sd(e),0).x).toConst(),s=_n(t),i=s.mod(r).toConst(),n=s.div(r).toConst();return sd(e,En(i,n))}),Gp=gn(([e,t])=>{const r=_n(Yl(sd(e),0).x).toConst(),s=_n(t).mod(r).toConst(),i=_n(t).div(r).toConst();return sd(e,En(s,i)).x}),zp=$n("vec4","vBatchColor"),$p=gn(([e],t)=>{const r=null===t.getDrawIndex()?bl:vl,s=Gp(e._indirectTexture,_n(r)),i=e._matricesTexture,n=_n(Yl(sd(i),0).x).toConst(),a=Tn(s).mul(4).toInt().toConst(),o=a.mod(n).toConst(),u=a.div(n).toConst(),l=In(sd(i,En(o,u)),sd(i,En(o.add(1),u)),sd(i,En(o.add(2),u)),sd(i,En(o.add(3),u))),d=e._colorsTexture;if(null!==d){const e=kp(d,s);zp.assign(e)}const c=On(l);fc.assign(l.mul(fc));const h=wc.div(An(c[0].dot(c[0]),c[1].dot(c[1]),c[2].dot(c[2]))),p=c.mul(h).xyz;wc.assign(p),t.hasGeometryAttribute("tangent")&&bh.mulAssign(c)},"void"),Wp=new WeakMap,Hp=new WeakMap;function jp(e,t,r,s,i,n){const a=e.element(i.x),o=e.element(i.y),u=e.element(i.z),l=e.element(i.w),d=r.mul(t),c=Oa(a.mul(n.x).mul(d),o.mul(n.y).mul(d),u.mul(n.z).mul(d),l.mul(n.w).mul(d));return s.mul(c).xyz}function qp(e,t,r,s,i,n,a){const o=e.element(n.x),u=e.element(n.y),l=e.element(n.z),d=e.element(n.w);let c=Oa(a.x.mul(o),a.y.mul(u),a.z.mul(l),a.w.mul(d));c=i.mul(c).mul(s);return{skinNormal:c.transformDirection(t).xyz,skinTangent:c.transformDirection(r).xyz}}function Xp(e,t,r,s,i){const n=e.skeleton;let a=Hp.get(n);if(void 0===a){n.update();const e=new Float32Array(n.boneMatrices);a={previousBoneMatrices:e,node:nd(e,"mat4",n.bones.length)},Hp.set(n,a)}return jp(a.node,yc,t,r,s,i)}const Yp=gn(([e],t)=>{const r=jl("skinIndex","uvec4"),s=jl("skinWeight","vec4"),i=Jc("bindMatrix","mat4"),n=Jc("bindMatrixInverse","mat4"),a=eh("skeleton.boneMatrices","mat4",e.skeleton.bones.length);if(wp(({object:e,frameId:t})=>{const r=e.skeleton;if(Wp.get(r)!==t){Wp.set(r,t);const e=Hp.get(r);void 0!==e&&e.previousBoneMatrices.set(r.boneMatrices),r.update()}}),t.needsPreviousData()){const t=Xp(e,i,n,r,s);yc.assign(t)}const o=jp(a,fc,i,n,r,s);if(fc.assign(o),t.hasGeometryAttribute("normal")){const{skinNormal:e,skinTangent:o}=qp(a,wc,bh,i,n,r,s);wc.assign(e),t.hasGeometryAttribute("tangent")&&bh.assign(o)}},"void"),Qp=gn(([e,t=null],r)=>{const s=Lp(new j(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(bl).toVar(),i=Lp(new j(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(bl).toVar(),n=Lp(new j(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(bl).toVar(),a=Aa(e.bindMatrix,"mat4"),o=Aa(e.bindMatrixInverse,"mat4"),u=nd(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),l=e.skeleton;if(wp(({frameId:e})=>{if(Wp.get(l)!==e){Wp.set(l,e);const t=Hp.get(l);void 0!==t&&t.previousBoneMatrices.set(l.boneMatrices),l.update()}}),r.needsPreviousData()){const t=Xp(e,a,o,i,n);yc.assign(t)}const d=jp(u,s,a,o,i,n);if(null!==t&&t.assign(d),r.hasGeometryAttribute("normal")){const{skinNormal:e,skinTangent:t}=qp(u,wc,bh,a,o,i,n);wc.assign(e),r.hasGeometryAttribute("tangent")&&bh.assign(t)}return d});class Kp extends pi{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const r={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],s=!0!==t.isNode&&t.name||this.getVarName(e),i=!0!==t.isNode&&t.type||"int";r[s]=Pl(s,i)}const s=e.addStack(),i=this.params[this.params.length-1](r);t.returnsNode=i.context({nodeLoop:i}),t.stackNode=s;const n=this.params[0];if(!0!==n.isNode&&"function"==typeof n.update){const e=gn(this.params[0].update)(r);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(e){const t=this.getProperties(e),r=this.params,s=t.stackNode;for(let s=0,i=r.length-1;s<i;s++){const i=r[s];let n,a=!1,u=null,l=null,d=null,c=null,h=null,p=null;if(i.isNode?"bool"===i.getNodeType(e)?(a=!0,c="bool",l=i.build(e,c)):(c="int",d=this.getVarName(s),u="0",l=i.build(e,c),h="<"):(c=i.type||"int",d=i.name||this.getVarName(s),u=i.start,l=i.end,h=i.condition,p=i.update,"number"==typeof u?u=e.generateConst(c,u):u&&u.isNode&&(u=u.build(e,c)),"number"==typeof l?l=e.generateConst(c,l):l&&l.isNode&&(l=l.build(e,c)),void 0!==u&&void 0===l?(u+=" - 1",l="0",h=">="):void 0!==l&&void 0===u&&(u="0",h="<"),void 0===h&&(h=Number(u)>Number(l)?">=":"<")),a)n=`while ( ${l} )`;else{const r={start:u,end:l},s=r.start,i=r.end;let a;const g=()=>h.includes("<")?"+=":"-=";if(null!=p)switch(typeof p){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=d+" "+g()+" "+e.generateConst(c,p);break;case"string":a=d+" "+p;break;default:p.isNode?a=d+" "+g()+" "+p.build(e):(o("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else p="int"===c||"uint"===c?h.includes("<")?"++":"--":g()+" 1.",a=d+" "+p;n=`for ( ${e.getVar(c,d)+" = "+s}; ${d+" "+h+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;t<r;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const Zp=(...e)=>new Kp(on(e,"int")).toStack(),Jp=()=>Pl("break").toStack(),eg=new WeakMap,tg=new s,rg=new WeakMap,sg=gn(({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=_n(yl).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return sd(e,En(u,o)).depth(i).xyz.mul(t)});const ig=gn(([e])=>{const{geometry:r}=e,s=void 0!==r.morphAttributes.position,i=r.hasAttribute("normal")&&void 0!==r.morphAttributes.normal,n=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,a=void 0!==n?n.length:0;if(0===a)return;let o=rg.get(e);void 0!==o&&o.count===a||(o={base:Aa(1),influences:e.morphTargetInfluences?ud(e.morphTargetInfluences,"float"):null,count:a},rg.set(e,o));const{base:u,influences:l}=o,{texture:d,stride:c,size:h}=function(e){const r=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=void 0!==n?n.length:0;let o=eg.get(e);if(void 0===o||o.count!==a){void 0!==o&&o.texture.dispose();const u=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],d=e.morphAttributes.color||[];let c=0;!0===r&&(c=1),!0===s&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,p=1;const g=4096;h>g&&(p=Math.ceil(h/g),h=g);const m=new Float32Array(h*p*4*a),f=new X(m,h,p,a);f.type=Y,f.needsUpdate=!0;const y=4*c;for(let x=0;x<a;x++){const T=u[x],_=l[x],v=d[x],N=h*p*4*x;for(let S=0;S<T.count;S++){const E=S*y;!0===r&&(tg.fromBufferAttribute(T,S),m[N+E+0]=tg.x,m[N+E+1]=tg.y,m[N+E+2]=tg.z,m[N+E+3]=0),!0===s&&(tg.fromBufferAttribute(_,S),m[N+E+4]=tg.x,m[N+E+5]=tg.y,m[N+E+6]=tg.z,m[N+E+7]=0),!0===i&&(tg.fromBufferAttribute(v,S),m[N+E+8]=tg.x,m[N+E+9]=tg.y,m[N+E+10]=tg.z,m[N+E+11]=4===v.itemSize?tg.w:1)}}function b(){f.dispose(),eg.delete(e),e.removeEventListener("dispose",b)}o={count:a,texture:f,stride:c,size:new t(h,p)},eg.set(e,o),e.addEventListener("dispose",b)}return o}(r);!0===s&&fc.mulAssign(u),!0===i&&wc.mulAssign(u);const p=_n(h.width);Zp(a,({i:t})=>{const r=Tn(0).toVar();e.count>1&&null!==e.morphTexture&&void 0!==e.morphTexture?r.assign(sd(e.morphTexture,En(_n(t).add(1),_n(bl))).r):r.assign(l.element(t).toVar()),yn(r.notEqual(0),()=>{!0===s&&fc.addAssign(sg({bufferMap:d,influence:r,stride:c,width:p,depth:t,offset:_n(0)})),!0===i&&wc.addAssign(sg({bufferMap:d,influence:r,stride:c,width:p,depth:t,offset:_n(1)}))})}),wp(({object:e})=>{const{base:t,influences:r}=o;e.geometry.morphTargetsRelative?t.value=1:t.value=1-e.morphTargetInfluences.reduce((e,t)=>e+t,0),r&&(r.array=e.morphTargetInfluences,r.update())})},"void");class ng extends pi{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class ag extends ng{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class og extends Fu{static get type(){return"LightingContextNode"}constructor(e,t=null,r=[],s=null,i=null){super(e),this.lightingModel=t,this.materialLightings=r,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{materialLightings:e,backdropNode:t,backdropAlphaNode:r}=this,s={directDiffuse:An().toVar("directDiffuse"),directSpecular:An().toVar("directSpecular"),indirectDiffuse:An().toVar("indirectDiffuse"),indirectSpecular:An().toVar("indirectSpecular")};return{radiance:An().toVar("radiance"),irradiance:An().toVar("irradiance"),iblIrradiance:An().toVar("iblIrradiance"),ambientOcclusion:Tn(1).toVar("ambientOcclusion"),reflectedLight:s,materialLightings:e,backdrop:t,backdropAlpha:r}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const ug=un(og);class lg extends ng{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const dg=new t;class cg extends ed{static get type(){return"ViewportTextureNode"}constructor(e=md,t=null,r=null){let s=null;null===r?(s=new Q,s.minFilter=K,r=s):s=r,super(r,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=s,this.isOutputTextureNode=!0,this.updateBeforeType=ii.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,r;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,r=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,r=this._cacheTextures),null===e)return t;if(!1===r.has(e)){const s=t.clone();r.set(e,s)}return r.get(e)}updateReference(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;return this.value=this.getTextureForReference(i),this.value}updateBefore(e){const t=e.renderer,r=t.getRenderTarget(),s=t.getCanvasTarget(),i=r||s;null===i?t.getDrawingBufferSize(dg):i.getDrawingBufferSize?i.getDrawingBufferSize(dg):dg.set(i.width,i.height);const n=this.getTextureForReference(i);n.image.width===dg.width&&n.image.height===dg.height||(n.image.width=dg.width,n.image.height=dg.height,n.needsUpdate=!0);const a=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const hg=un(cg).setParameterLength(0,3),pg=un(cg,null,null,{generateMipmaps:!0}).setParameterLength(0,3),gg=pg(),mg=(e=md,t=null)=>gg.sample(e,t);let fg=null;class yg extends cg{static get type(){return"ViewportDepthTextureNode"}constructor(e=md,t=null,r=null){null===r&&(null===fg&&(fg=new Z),r=fg),super(e,t,r)}}const bg=un(yg).setParameterLength(0,3);class xg extends pi{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===xg.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===xg.DEPTH_BASE)null!==r&&(s=Rg().assign(r));else if(t===xg.DEPTH)s=e.isPerspectiveCamera?vg(Tc.z,Id,Vd):Tg(Tc.z,Id,Vd);else if(t===xg.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=Sg(r,Id,Vd);s=Tg(e,Id,Vd)}else s=r;else s=Tg(Tc.z,Id,Vd);return s}}xg.DEPTH_BASE="depthBase",xg.DEPTH="depth",xg.LINEAR_DEPTH="linearDepth";const Tg=(e,t,r)=>e.add(t).div(t.sub(r)),_g=gn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?r.sub(t).mul(e).sub(r):t.sub(r).mul(e).sub(t)),vg=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),Ng=(e,t,r)=>t.mul(e.add(r)).div(e.mul(t.sub(r))),Sg=gn(([e,t,r],s)=>!0===s.renderer.reversedDepthBuffer?t.mul(r).div(t.sub(r).mul(e).sub(t)):t.mul(r).div(r.sub(t).mul(e).sub(r))),Eg=(e,t,r)=>{t=t.max(1e-6).toVar();const s=No(e.negate().div(t)),i=No(r.div(t));return s.div(i)},Rg=un(xg,xg.DEPTH_BASE),wg=ln(xg,xg.DEPTH),Ag=un(xg,xg.LINEAR_DEPTH).setParameterLength(0,1),Cg=Ag(bg());wg.assign=e=>Rg(e);class Mg extends pi{static get type(){return"ClippingNode"}constructor(e=Mg.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:r,unionPlanes:s}=t;return this.hardwareClipping=e.hardwareClipping,this.scope===Mg.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===Mg.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return gn(()=>{const r=Tn().toVar("distanceToPlane"),s=Tn().toVar("distanceToGradient"),i=Tn(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=ud(t).setGroup(Ea);Zp(n,({i:t})=>{const n=e.element(t);r.assign(Tc.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(Nu(s.negate(),s,r))})}const a=e.length;if(a>0){const t=ud(e).setGroup(Ea),n=Tn(1).toVar("intersectionClipOpacity");Zp(a,({i:e})=>{const i=t.element(e);r.assign(Tc.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(Nu(s.negate(),s,r).oneMinus())}),i.mulAssign(n.oneMinus())}Wn.a.mulAssign(i),Wn.a.equal(0).discard()})()}setupDefault(e,t){return gn(()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=ud(t).setGroup(Ea);Zp(r,({i:t})=>{const r=e.element(t);Tc.dot(r.xyz).greaterThan(r.w).discard()})}const s=e.length;if(s>0){const t=ud(e).setGroup(Ea),r=Nn(!0).toVar("clipped");Zp(s,({i:e})=>{const s=t.element(e);r.assign(Tc.dot(s.xyz).greaterThan(s.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),gn(()=>{const s=ud(e).setGroup(Ea),i=dd(t.getClipDistance());Zp(r,({i:e})=>{const t=s.element(e),r=Tc.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)})})()}}Mg.ALPHA_TO_COVERAGE="alphaToCoverage",Mg.DEFAULT="default",Mg.HARDWARE="hardware";const Bg=gn(([e])=>Co(Va(1e4,Mo(Va(17,e.x).add(Va(.1,e.y)))).mul(Oa(.1,zo(Mo(Va(13,e.y).add(e.x))))))),Lg=gn(([e])=>Bg(Sn(Bg(e.xy),e.z))),Fg=gn(([e])=>{const t=su(Wo(qo(e.xyz)),Wo(Xo(e.xyz))),r=Tn(1).div(Tn(.05).mul(t)).toVar("pixScale"),s=Sn(_o(Ro(No(r))),_o(wo(No(r)))),i=Sn(Lg(Ro(s.x.mul(e.xyz))),Lg(Ro(s.y.mul(e.xyz)))),n=Co(No(r)),a=Oa(Va(n.oneMinus(),i.x),Va(n,i.y)),o=ru(n,n.oneMinus()),u=An(a.mul(a).div(Va(2,o).mul(Ia(1,o))),a.sub(Va(.5,o)).div(Ia(1,o)),Ia(1,Ia(1,a).mul(Ia(1,a)).div(Va(2,o).mul(Ia(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return Tu(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Pg extends Hl{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let r;return r=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new s(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Ug=(e=0)=>new Pg(e);class Dg extends J{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const r=this[t];r&&!0===r.isNode&&e.push({property:t,childNode:r})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:r}of this._getNodeChildren())e.push(Gs(t.slice(0,-4)),r.getCacheKey());return this.type+zs(e)}build(e){this.setup(e)}setupObserver(e){return new Os(e)}setup(e){e.context.setupNormal=()=>ju(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,r=t.getRenderTarget();e.addStack();const s=this.setupVertex(e),i=ju(this.vertexNode||s,"VERTEX");let n;e.context.clipSpace=i,e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==r?!0===r.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupAmbientOcclusion(e),this.setupVariants(e);const s=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const i=Ln(s,Wn.a).max(0);n=this.setupOutput(e,i),da.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&da.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=t.convert(e.getOutputType())),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:r}=e.clippingContext;let s=null;if(t.length>0||r.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?s=new Mg(Mg.ALPHA_TO_COVERAGE):e.stack.addToStack(new Mg)}return s}setupHardwareClipping(e){if(e.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new Mg(Mg.HARDWARE)),e.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:r}=e;let s=this.depthNode;if(null===s){const e=t.getMRT();e&&e.has("depth")?s=e.get("depth"):!0===t.logarithmicDepthBuffer&&(s=r.isPerspectiveCamera?Eg(Tc.z,Id,Vd):Tg(Tc.z,Id,Vd))}null!==s&&wg.assign(s).toStack()}setupPositionView(){return dc.mul(fc).xyz}setupModelViewProjection(){return kd.mul(Tc)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),Sp}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&ig(t),!0===t.isSkinnedMesh&&Yp(t),this.displacementMap){const e=rh("displacementMap","texture"),t=rh("displacementScale","float"),r=rh("displacementBias","float");fc.addAssign(wc.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&$p(t),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Vp(t),null!==this.positionNode&&fc.assign(ju(this.positionNode,"POSITION","vec3")),fc}setupDiffuseColor(e){const{object:t,geometry:r}=e;null!==this.maskNode&&Nn(this.maskNode).not().discard();let s=this.colorNode?Ln(this.colorNode):Gh;!0===this.vertexColors&&r.hasAttribute("color")&&(s=s.mul(Ug())),t.instanceColor&&(s=Op.mul(s)),t.isBatchedMesh&&t._colorsTexture&&(s=zp.mul(s)),Wn.assign(s);const i=this.opacityNode?Tn(this.opacityNode):Wh;Wn.a.assign(Wn.a.mul(i));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?Tn(this.alphaTestNode):kh,!0===this.alphaToCoverage?(Wn.a=Nu(n,n.add(Zo(Wn.a)),Wn.a),Wn.a.lessThanEqual(0).discard()):Wn.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Wn.a.lessThan(Fg(fc)).discard(),e.isOpaque()&&Wn.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?An(0):Wn.rgb}setupNormal(){return this.normalNode?An(this.normalNode):Zh}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?rh("envMap","cubeTexture"):rh("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new lg(_p)),t}setupMaterialLightings(e){const t=[];if(!1===e.renderer.lighting.enabled)return t;const r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);return s&&s.isLightingNode&&t.push(s),e.context.ambientOcclusion&&t.push(new ag(e.context.ambientOcclusion)),t}setupAmbientOcclusion(e){let t=this.aoNode;null===t&&e.material.aoMap&&(t=vp),e.context.getAO&&(t=e.context.getAO(t,e)),null!==t&&(Ta.assign(t),e.context.ambientOcclusion=Ta)}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:r,backdropAlphaNode:s,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode,a=!0===this.lights?this.setupMaterialLightings(e):[],o=n?this.lightsNode||e.lightsNode:null;let u=this.setupOutgoingLight(e);if(o&&(a.length>0||o.getScope().hasLights)){const t=this.setupLightingModel(e)||null;u=ug(o,t,a,r,s)}else null!==r&&(u=An(null!==s?xu(u,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(jn.assign(An(i||$h)),u=u.add(jn)),u}setupFog(e,t){const r=e.fogNode;return r&&(da.assign(t),t=Ln(r.toVar())),t}setupPremultipliedAlpha(e,t){return Dl(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const r=e[t];void 0===this[t]&&(this[t]=r,r&&r.clone&&(this[t]=r.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const r=J.prototype.toJSON.call(this,e);r.inputNodes={};for(const{property:t,childNode:s}of this._getNodeChildren())r.inputNodes[t]=s.toJSON(e).uuid;function s(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=s(e.textures),i=s(e.images),n=s(e.nodes);t.length>0&&(r.textures=t),i.length>0&&(r.images=i),n.length>0&&(r.nodes=n)}return r}copy(e){const t=Object.getOwnPropertyDescriptors(this.constructor.prototype);for(const r in t)if(void 0!==t[r].set&&void 0!==e[r]){const t=e[r];this[r]&&void 0!==this[r].copy?this[r].copy(t):this[r]=t}for(const t in this)if(!/^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test(t)&&void 0!==this[t]&&void 0!==e[t]){const r=e[t];this[t]&&void 0!==this[t].copy?this[t].copy(r):this[t]=r}return this.clippingPlanes=e.clippingPlanes?e.clippingPlanes.map(e=>e.clone()):null,this.userData=JSON.parse(JSON.stringify(e.userData)),this}}const Og=new ee;class Ig extends Dg{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Og),this.setValues(e)}}const Vg=new te;class kg extends Dg{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Vg),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Tn(this.offsetNode):bp,t=this.dashScaleNode?Tn(this.dashScaleNode):gp,r=this.dashSizeNode?Tn(this.dashSizeNode):mp,s=this.gapSizeNode?Tn(this.gapSizeNode):fp;ca.assign(r),ha.assign(s);const i=Xu(jl("lineDistance").mul(t));(e?i.add(e):i).mod(ca.add(ha)).greaterThan(ca).discard()}}const Gg=new te,zg=$n("vec3","worldStart"),$g=$n("vec3","worldEnd"),Wg=$n("float","lineDistance"),Hg=$n("vec4","worldPos"),jg=gn(({start:e,end:t})=>{const r=kd.element(2).element(2),s=kd.element(3).element(2);return r.greaterThan(0).select(s.negate().div(r.add(1)),s.mul(-.5).div(r)).sub(e.z).div(t.z.sub(e.z))},{start:"vec4",end:"vec4",return:"float"}),qg=gn(({p1:e,p2:t,p3:r,p4:s})=>{const i=e.sub(r),n=s.sub(r),a=t.sub(e),o=i.dot(n),u=n.dot(a),l=i.dot(a),d=n.dot(n),c=a.dot(a).mul(d).sub(u.mul(u)),h=o.mul(u).sub(l.mul(d)).div(c).clamp(),p=o.add(u.mul(h)).div(d).clamp();return Sn(h,p)},{p1:"vec3",p2:"vec3",p3:"vec3",p4:"vec3",return:"vec2"}),Xg=gn(({material:e})=>{const t=e._useDash,r=e._useWorldUnits,s=jl("instanceStart"),i=jl("instanceEnd"),n=Ln(dc.mul(Ln(s,1))).toVar("start"),a=Ln(dc.mul(Ln(i,1))).toVar("end");let o,u;t&&(o=Tn(jl("instanceDistanceStart")).toVar("distanceStart"),u=Tn(jl("instanceDistanceEnd")).toVar("distanceEnd")),r&&(zg.assign(n.xyz),$g.assign(a.xyz));const l=bd.z.div(bd.w),d=kd.element(2).element(3).equal(-1);if(yn(d,()=>{yn(n.z.lessThan(0).and(a.z.greaterThan(0)),()=>{const e=jg({start:n,end:a});a.assign(Ln(xu(n.xyz,a.xyz,e),a.w)),t&&u.assign(xu(o,u,e))}).ElseIf(a.z.lessThan(0).and(n.z.greaterThanEqual(0)),()=>{const e=jg({start:a,end:n});n.assign(Ln(xu(a.xyz,n.xyz,e),n.w)),t&&o.assign(xu(u,o,e))})}),t){const t=e.dashScaleNode?Tn(e.dashScaleNode):gp,r=e.offsetNode?Tn(e.offsetNode):bp;let s=mc.y.lessThan(.5).select(t.mul(o),t.mul(u));s=s.add(r),Wg.assign(s)}const c=kd.mul(n),h=kd.mul(a),p=c.xyz.div(c.w),g=h.xyz.div(h.w),m=g.xy.sub(p.xy).toVar();m.x.assign(m.x.mul(l)),m.assign(m.normalize());const f=Ln().toVar();if(r){const e=a.xyz.sub(n.xyz).normalize(),r=xu(n.xyz,a.xyz,.5).normalize(),s=e.cross(r).normalize(),i=e.cross(s);Hg.assign(mc.y.lessThan(.5).select(n,a));const o=yp.mul(.5);Hg.addAssign(Ln(mc.x.lessThan(0).select(s.mul(o),s.mul(o).negate()),0)),t||(Hg.addAssign(Ln(mc.y.lessThan(.5).select(e.mul(o).negate(),e.mul(o)),0)),Hg.addAssign(Ln(i.mul(o),0)),yn(mc.y.greaterThan(1).or(mc.y.lessThan(0)),()=>{Hg.subAssign(Ln(i.mul(2).mul(o),0))})),f.assign(kd.mul(Hg));const u=An().toVar();u.assign(mc.y.lessThan(.5).select(p,g)),f.z.assign(u.z.mul(f.w))}else{const e=Sn(m.y,m.x.negate()).toVar("offset");m.x.assign(m.x.div(l)),e.x.assign(e.x.div(l)),e.assign(mc.x.lessThan(0).select(e.negate(),e)),yn(mc.y.lessThan(0),()=>{e.assign(e.sub(m))}).ElseIf(mc.y.greaterThan(1),()=>{e.assign(e.add(m))}),e.assign(e.mul(yp)),e.assign(e.div(bd.w.div(gd))),f.assign(mc.y.lessThan(.5).select(c,h)),e.assign(e.mul(f.w)),f.assign(f.add(Ln(e,0,0)))}return f})(),Yg=gn(({material:e,renderer:t})=>{const r=e._useAlphaToCoverage,s=e._useDash,i=e._useWorldUnits,n=ql();if(s){const t=e.dashSizeNode?Tn(e.dashSizeNode):mp,r=e.gapSizeNode?Tn(e.gapSizeNode):fp;ca.assign(t),ha.assign(r),n.y.lessThan(-1).or(n.y.greaterThan(1)).discard(),Wg.mod(ca.add(ha)).greaterThan(ca).discard()}const a=Tn(1).toVar("alpha");if(i){const e=Hg.xyz.normalize().mul(1e5),i=$g.sub(zg),n=qg({p1:zg,p2:$g,p3:An(0,0,0),p4:e}),o=zg.add(i.mul(n.x)),u=e.mul(n.y),l=o.sub(u).length().div(yp);if(!s)if(r&&t.currentSamples>0){const e=l.fwidth();a.assign(Nu(e.negate().add(.5),e.add(.5),l).oneMinus())}else l.greaterThan(.5).discard()}else if(r&&t.currentSamples>0){const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1)),r=e.mul(e).add(t.mul(t)),s=Tn(r.fwidth()).toVar("dlen");yn(n.y.abs().greaterThan(1),()=>{a.assign(Nu(s.oneMinus(),s.add(1),r).oneMinus())})}else yn(n.y.abs().greaterThan(1),()=>{const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()});return a})();class Qg extends Dg{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(Gg),this.vertexColors=e.vertexColors,this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=re,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setupDiffuseColor(e){if(super.setupDiffuseColor(e),Wn.a.mulAssign(Yg),!0===this.vertexColors&&e.geometry.hasAttribute("instanceColorStart")){const e=jl("instanceColorStart"),t=jl("instanceColorEnd"),r=mc.y.lessThan(.5).select(e,t);Wn.rgb.mulAssign(r)}this.transparent&&Wn.rgb.assign(Wn.rgb.mul(Wn.a).add(mg().rgb.mul(Wn.a.oneMinus())))}setupModelViewProjection(){return Xg}get lineColorNode(){return this.colorNode}set lineColorNode(e){v('Line2NodeMaterial: "lineColorNode" has been deprecated. Use "colorNode" instead.'),this.colorNode=e}get worldUnits(){return this._useWorldUnits}set worldUnits(e){this._useWorldUnits!==e&&(this._useWorldUnits=e,this.needsUpdate=!0)}get dashed(){return this._useDash}set dashed(e){this._useDash!==e&&(this._useDash=e,this.needsUpdate=!0)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const Kg=new se;class Zg extends Dg{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Kg),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Tn(this.opacityNode):Wh;Wn.assign(tl(Ln(Ch(Bc),e),ie))}}const Jg=gn(([e=xc])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),r=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Sn(t,r)}),em=gn(([e=ql()])=>{const t=e.x.sub(.5).mul(2*Math.PI),r=e.y.sub(.5).mul(Math.PI),s=r.cos(),i=s.mul(t.cos()),n=r.sin(),a=s.mul(t.sin());return An(i,n,a)});class tm extends ne{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const r={width:e,height:e,depth:1},s=[r,r,r,r,r,r];this.texture=new U(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const r=t.minFilter,s=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i=new ae(5,5,5),n=Jg(xc),a=new Dg;a.colorNode=rd(t,n,0),a.side=F,a.blending=re;const o=new oe(i,a),u=new ue;u.add(o),t.minFilter===K&&(t.minFilter=le);const l=new de(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.generateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,r=!0,s=!0){const i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,r,s);e.setRenderTarget(i)}}const rm=new WeakMap;class sm extends fi{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Qc(null);const t=new U;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=ii.RENDER}updateBefore(e){const{renderer:t,material:r}=e,s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:r[s.property];if(e&&e.isTexture){const r=e.mapping;if(r===ce||r===he){if(rm.has(e)){const t=rm.get(e);nm(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new tm(r.height);s.fromEquirectangularTexture(t,e),nm(s.texture,e.mapping),this._cubeTexture=s.texture,rm.set(e,s.texture),e.addEventListener("dispose",im)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function im(e){const t=e.target;t.removeEventListener("dispose",im);const r=rm.get(t);void 0!==r&&(rm.delete(t),r.dispose())}function nm(e,t){t===ce?e.mapping=D:t===he&&(e.mapping=O)}const am=un(sm).setParameterLength(1);class om extends ng{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=am(this.envNode)}}class um extends ng{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Tn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class lm{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class dm extends lm{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(Ln(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(Ln(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(Wn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case me:s.rgb.assign(xu(s.rgb,s.rgb.mul(i.rgb),Xh.mul(Yh)));break;case ge:s.rgb.assign(xu(s.rgb,i.rgb,Xh.mul(Yh)));break;case pe:s.rgb.addAssign(i.rgb.mul(Xh.mul(Yh)));break;default:d("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const cm=new fe;class hm extends Dg{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(cm),this.setValues(e)}setupNormal(){return Ec(Cc)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new om(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new um(_p)),t}setupOutgoingLight(){return Wn.rgb}setupLightingModel(){return new dm}}const pm=gn(({f0:e,f90:t,dotVH:r})=>{const s=r.mul(-5.55473).sub(6.98316).mul(r).exp2();return e.mul(s.oneMinus()).add(t.mul(s))}),gm=gn(e=>e.diffuseColor.mul(1/Math.PI)),mm=gn(({dotNH:e})=>la.mul(Tn(.5)).add(1).mul(Tn(1/Math.PI)).mul(e.pow(la))),fm=gn(({lightDirection:e})=>{const t=e.add(_c).normalize(),r=Bc.dot(t).clamp(),s=_c.dot(t).clamp(),i=pm({f0:aa,f90:1,dotVH:s}),n=Tn(.25),a=mm({dotNH:r});return i.mul(n).mul(a)});class ym extends dm{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Bc.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(gm({diffuseColor:Wn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(fm({lightDirection:e})).mul(Xh))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(gm({diffuseColor:Wn}))),s.indirectDiffuse.mulAssign(t)}}const bm=new ye;class xm extends Dg{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(bm),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new om(t):null}setupLightingModel(){return new ym(!1)}}const Tm=new be;class _m extends Dg{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Tm),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new om(t):null}setupLightingModel(){return new ym}setupVariants(){const e=(this.shininessNode?Tn(this.shininessNode):zh).max(1e-4);la.assign(e);const t=this.specularNode||Hh;aa.assign(t)}}const vm=gn(e=>{if(!1===e.geometry.hasAttribute("normal"))return Tn(0);const t=Cc.dFdx().abs().max(Cc.dFdy().abs());return t.x.max(t.y).max(t.z)}),Nm=gn(e=>{const{roughness:t}=e,r=vm();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s}),Sm=gn(({alpha:e,dotNL:t,dotNV:r})=>{const s=e.pow2(),i=t.mul(s.add(s.oneMinus().mul(r.pow2())).sqrt()),n=r.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt());return ka(.5,i.add(n).max(lo))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Em=gn(({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(An(e.mul(r),t.mul(s),a).length()),l=a.mul(An(e.mul(i),t.mul(n),o).length());return ka(.5,u.add(l).max(lo))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Rm=gn(({alpha:e,dotNH:t})=>{const r=e.pow2(),s=t.pow2().mul(r.oneMinus()).oneMinus();return r.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),wm=Tn(1/Math.PI),Am=gn(({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=An(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return wm.mul(n.mul(u.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),Cm=gn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Bc,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(_c).normalize(),d=n.dot(e).clamp(),c=n.dot(_c).clamp(),h=n.dot(l).clamp(),p=_c.dot(l).clamp();let g,m,f=pm({f0:t,f90:r,dotVH:p});if(en(a)&&(f=Jn.mix(f,i)),en(o)){const t=ia.dot(e),r=ia.dot(_c),s=ia.dot(l),i=na.dot(e),n=na.dot(_c),a=na.dot(l);g=Em({alphaT:ra,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=Am({alphaT:ra,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=Sm({alpha:u,dotNL:d,dotNV:c}),m=Rm({alpha:u,dotNH:h});return f.mul(g).mul(m)}),Mm=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Bm=null;const Lm=gn(({roughness:e,dotNV:t})=>{null===Bm&&(Bm=new xe(Mm,16,16,$,Te),Bm.name="DFG_LUT",Bm.minFilter=le,Bm.magFilter=le,Bm.wrapS=_e,Bm.wrapT=_e,Bm.generateMipmaps=!1,Bm.needsUpdate=!0);const r=Sn(e,t);return rd(Bm,r).rg}),Fm=gn(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=Cm({lightDirection:e,f0:t,f90:r,roughness:s,f:i,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),u=Bc.dot(e).clamp(),l=Bc.dot(_c).clamp(),d=Lm({roughness:s,dotNV:l}),c=Lm({roughness:s,dotNV:u}),h=t.mul(d.x).add(r.mul(d.y)),p=t.mul(c.x).add(r.mul(c.y)),g=d.x.add(d.y),m=c.x.add(c.y),f=Tn(1).sub(g),y=Tn(1).sub(m),b=t.add(t.oneMinus().mul(.047619)),x=h.mul(p).mul(b).div(Tn(1).sub(f.mul(y).mul(b).mul(b)).add(lo)),T=f.mul(y),_=x.mul(T);return o.add(_)}),Pm=gn(e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=Lm({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))}),Um=gn(({f:e,f90:t,dotVH:r})=>{const s=r.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return e.sub(An(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),Dm=gn(({roughness:e,dotNH:t})=>{const r=e.pow2(),s=Tn(1).div(r),i=t.pow2().oneMinus().max(.0078125);return Tn(2).add(s).mul(i.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),Om=gn(({dotNV:e,dotNL:t})=>Tn(1).div(Tn(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Im=gn(({lightDirection:e})=>{const t=e.add(_c).normalize(),r=Bc.dot(e).clamp(),s=Bc.dot(_c).clamp(),i=Bc.dot(t).clamp(),n=Dm({roughness:Zn,dotNH:i}),a=Om({dotNV:s,dotNL:r});return Kn.mul(n).mul(a)}),Vm=gn(({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=Sn(r,s.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),km=gn(({f:e})=>{const t=e.length();return su(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Gm=gn(({v1:e,v2:t})=>{const r=e.dot(t),s=r.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),a=i.div(n),o=r.greaterThan(0).select(a,su(r.mul(r).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),zm=gn(({N:e,V:t,P:r,mInv:s,p0:i,p1:n,p2:a,p3:o})=>{const u=n.sub(i).toVar(),l=o.sub(i).toVar(),d=u.cross(l),c=An().toVar();return yn(d.dot(r.sub(i)).greaterThanEqual(0),()=>{const u=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(u).negate(),d=s.mul(On(u,l,e).transpose()).toVar(),h=d.mul(i.sub(r)).normalize().toVar(),p=d.mul(n.sub(r)).normalize().toVar(),g=d.mul(a.sub(r)).normalize().toVar(),m=d.mul(o.sub(r)).normalize().toVar(),f=An(0).toVar();f.addAssign(Gm({v1:h,v2:p})),f.addAssign(Gm({v1:p,v2:g})),f.addAssign(Gm({v1:g,v2:m})),f.addAssign(Gm({v1:m,v2:h})),c.assign(An(km({f:f})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),$m=gn(({P:e,p0:t,p1:r,p2:s,p3:i})=>{const n=r.sub(t).toVar(),a=i.sub(t).toVar(),o=n.cross(a),u=An().toVar();return yn(o.dot(e.sub(t)).greaterThanEqual(0),()=>{const n=t.sub(e).normalize().toVar(),a=r.sub(e).normalize().toVar(),o=s.sub(e).normalize().toVar(),l=i.sub(e).normalize().toVar(),d=An(0).toVar();d.addAssign(Gm({v1:n,v2:a})),d.addAssign(Gm({v1:a,v2:o})),d.addAssign(Gm({v1:o,v2:l})),d.addAssign(Gm({v1:l,v2:n})),u.assign(An(km({f:d.abs()})))}),u}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"P",type:"vec3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Wm=1/6,Hm=e=>Va(Wm,Va(e,Va(e,e.negate().add(3)).sub(3)).add(1)),jm=e=>Va(Wm,Va(e,Va(e,Va(3,e).sub(6))).add(4)),qm=e=>Va(Wm,Va(e,Va(e,Va(-3,e).add(3)).add(3)).add(1)),Xm=e=>Va(Wm,du(e,3)),Ym=e=>Hm(e).add(jm(e)),Qm=e=>qm(e).add(Xm(e)),Km=e=>Oa(-1,jm(e).div(Hm(e).add(jm(e)))),Zm=e=>Oa(1,Xm(e).div(qm(e).add(Xm(e)))),Jm=(e,t,r)=>{const s=e.uvNode,i=Va(s,t.zw).add(.5),n=Ro(i),a=Co(i),o=Ym(a.x),u=Qm(a.x),l=Km(a.x),d=Zm(a.x),c=Km(a.y),h=Zm(a.y),p=Sn(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=Sn(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=Sn(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=Sn(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=Ym(a.y).mul(Oa(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=Qm(a.y).mul(Oa(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},ef=gn(([e,t])=>{const r=Sn(e.size(_n(t))),s=Sn(e.size(_n(t.add(1)))),i=ka(1,r),n=ka(1,s),a=Jm(e,Ln(i,r),Ro(t)),o=Jm(e,Ln(n,s),wo(t));return Co(t).mix(a,o)}),tf=gn(([e,t])=>{const r=t.mul(Kl(e));return ef(e,r)}),rf=gn(([e,t,r,s,i])=>{const n=An(vu(t.negate(),Ao(e),ka(1,s))),a=An(Wo(i[0].xyz),Wo(i[1].xyz),Wo(i[2].xyz));return Ao(n).mul(r.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),sf=gn(([e,t])=>e.mul(Tu(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),nf=pg(),af=mg(),of=gn(([e,t,r],{material:s})=>{const i=(s.side===F?nf:af).sample(e),n=No(fd.x).mul(sf(t,r));return ef(i,n)}),uf=gn(([e,t,r])=>(yn(r.notEqual(0),()=>{const s=vo(t).negate().div(r);return To(s.negate().mul(e))}),An(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),lf=gn(([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=Ln().toVar(),f=An().toVar();const i=d.sub(1).mul(g.mul(.025)),n=An(d.sub(i),d,d.add(i));Zp({start:0,end:3},({i:i})=>{const d=n.element(i),g=rf(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(Ln(y,1))),x=Sn(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(Sn(x.x,x.y.oneMinus()));const T=of(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(uf(Wo(g),h,p).element(i)))}),m.a.divAssign(3)}else{const i=rf(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(Ln(n,1))),y=Sn(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Sn(y.x,y.y.oneMinus())),m=of(y,r,d),f=s.mul(uf(Wo(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=An(Pm({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return Ln(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())}),df=On(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),cf=(e,t)=>e.sub(t).div(e.add(t)).pow2(),hf=gn(({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=xu(e,t,Nu(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();yn(a.lessThan(0),()=>An(1));const o=a.sqrt(),u=cf(n,e),l=pm({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=Tn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return An(1).add(t).div(An(1).sub(t))})(i.clamp(0,.9999)),g=cf(p,n.toVec3()),m=pm({f0:g,f90:1,dotVH:o}),f=An(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(s,o,2),b=An(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(An(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Zp({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{N.mulAssign(T);const t=((e,t)=>{const r=e.mul(2*Math.PI*1e-9),s=An(54856e-17,44201e-17,52481e-17),i=An(1681e3,1795300,2208400),n=An(43278e5,93046e5,66121e5),a=Tn(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(r.mul(2239900).add(t.x).cos()).mul(r.pow2().mul(-45282e5).exp());let o=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(r).add(t).cos()).mul(r.pow2().negate().mul(n).exp());return o=An(o.x.add(a),o.y,o.z).div(1.0685e-7),df.mul(o)})(Tn(e).mul(y),Tn(e).mul(b)).mul(2);v.addAssign(N.mul(t))}),v.max(An(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),pf=gn(({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.mul(r),n=r.add(.1).reciprocal(),a=Tn(-1.9362).add(r.mul(1.0678)).add(i.mul(.4573)).sub(n.mul(.8469)),o=Tn(-.6014).add(r.mul(.5538)).sub(i.mul(.467)).sub(n.mul(.1255));return a.mul(s).add(o).exp().saturate()}),gf=An(.04),mf=Tn(1);class ff extends lm{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=r,this.anisotropy=s,this.transmission=i,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=An().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=An().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=An().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=An().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=An().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Bc.dot(_c).clamp(),t=hf({outsideIOR:Tn(1),eta2:ea,cosTheta1:e,thinFilmThickness:ta,baseF0:aa}),r=hf({outsideIOR:Tn(1),eta2:ea,cosTheta1:e,thinFilmThickness:ta,baseF0:Wn.rgb});this.iridescenceFresnel=xu(t,r,Xn),this.iridescenceF0Dielectric=Um({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=Um({f:r,f90:1,dotVH:e}),this.iridescenceF0=xu(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Xn)}if(!0===this.transmission){const t=bc,r=Hd.sub(bc).normalize(),s=Lc,i=e.context;i.backdrop=lf(s,r,qn,Hn,oa,ua,t,sc,zd,kd,ga,fa,ba,ya,this.dispersion?xa:null),i.backdropAlpha=ma,Wn.a.mulAssign(xu(1,i.backdrop.a,ma))}super.start(e)}computeMultiscattering(e,t,r,s,i=null){const n=Bc.dot(_c).clamp(),a=Lm({roughness:qn,dotNV:n}),o=i?Jn.mix(s,i):s,u=o.mul(a.x).add(r.mul(a.y)),l=a.x.add(a.y).oneMinus(),d=o.add(o.oneMinus().mul(.047619)),c=u.mul(d).div(l.mul(d).oneMinus());e.addAssign(u),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Bc.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(s.mul(Im({lightDirection:e})));const t=pf({normal:Bc,viewDir:_c,roughness:Zn}),r=pf({normal:Bc,viewDir:e,roughness:Zn}),i=Kn.r.max(Kn.g).max(Kn.b).mul(t.max(r)).oneMinus();s.mulAssign(i)}if(!0===this.clearcoat){const r=Fc.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(Cm({lightDirection:e,f0:gf,f90:mf,roughness:Qn,normalView:Fc})))}r.directDiffuse.addAssign(s.mul(gm({diffuseColor:Hn}))),r.directSpecular.addAssign(s.mul(Fm({lightDirection:e,f0:oa,f90:1,roughness:qn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s,reflectedLight:i,ltc_1:n,ltc_2:a}){const o=t.add(r).sub(s),u=t.sub(r).sub(s),l=t.sub(r).add(s),d=t.add(r).add(s),c=Bc,h=_c,p=Tc.toVar(),g=Vm({N:c,V:h,roughness:qn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=On(An(m.x,0,m.y),An(0,1,0),An(m.z,0,m.w)).toVar(),b=oa.mul(f.x).add(ua.sub(oa).mul(f.y)).toVar();if(i.directSpecular.addAssign(e.mul(b).mul(zm({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(Hn).mul(zm({N:c,V:h,P:p,mInv:On(1,0,0,0,1,0,0,0,1),p0:o,p1:u,p2:l,p3:d}))),!0===this.clearcoat){const t=Fc,r=Vm({N:t,V:h,roughness:Qn}),s=n.sample(r),i=a.sample(r),c=On(An(s.x,0,s.y),An(0,1,0),An(s.z,0,s.w)),g=gf.mul(i.x).add(mf.sub(gf).mul(i.y));this.clearcoatSpecularDirect.addAssign(e.mul(g).mul(zm({N:t,V:h,P:p,mInv:c,p0:o,p1:u,p2:l,p3:d})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:r}=e.context,s=t.mul(gm({diffuseColor:Hn})).toVar();if(!0===this.sheen){const e=pf({normal:Bc,viewDir:_c,roughness:Zn}),t=Kn.r.max(Kn.g).max(Kn.b).mul(e).oneMinus();s.mulAssign(t)}r.indirectDiffuse.addAssign(s)}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Kn,pf({normal:Bc,viewDir:_c,roughness:Zn}))),!0===this.clearcoat){const e=Fc.dot(_c).clamp(),t=Pm({dotNV:e,specularColor:gf,specularF90:mf,roughness:Qn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=An().toVar("singleScatteringDielectric"),n=An().toVar("multiScatteringDielectric"),a=An().toVar("singleScatteringMetallic"),o=An().toVar("multiScatteringMetallic");this.computeMultiscattering(i,n,ua,aa,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,ua,Wn.rgb,this.iridescenceF0Metallic);const u=xu(i,a,Xn),l=xu(n,o,Xn),d=i.add(n),c=Hn.mul(d.oneMinus()),h=r.mul(1/Math.PI),p=t.mul(u).add(l.mul(h)).toVar(),g=c.mul(h).toVar();if(!0===this.sheen){const e=pf({normal:Bc,viewDir:_c,roughness:Zn}),t=Kn.r.max(Kn.g).max(Kn.b).mul(e).oneMinus();p.mulAssign(t),g.mulAssign(t)}s.indirectSpecular.addAssign(p),s.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Bc.dot(_c).clamp().add(t),i=qn.mul(-16).oneMinus().negate().exp2(),n=t.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),r.indirectDiffuse.mulAssign(t),r.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Fc.dot(_c).clamp(),r=pm({dotVH:e,f0:gf,f90:mf}),s=t.mul(Yn.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Yn));t.assign(s)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const yf=Tn(1),bf=Tn(-2),xf=Tn(.8),Tf=Tn(-1),_f=Tn(.4),vf=Tn(2),Nf=Tn(.305),Sf=Tn(3),Ef=Tn(.21),Rf=Tn(4),wf=Tn(4),Af=Tn(16),Cf=gn(([e])=>{const t=An(zo(e)).toVar(),r=Tn(-1).toVar();return yn(t.x.greaterThan(t.z),()=>{yn(t.x.greaterThan(t.y),()=>{r.assign(Lu(e.x.greaterThan(0),0,3))}).Else(()=>{r.assign(Lu(e.y.greaterThan(0),1,4))})}).Else(()=>{yn(t.z.greaterThan(t.y),()=>{r.assign(Lu(e.z.greaterThan(0),2,5))}).Else(()=>{r.assign(Lu(e.y.greaterThan(0),1,4))})}),r}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),Mf=gn(([e,t])=>{const r=Sn().toVar();return yn(t.equal(0),()=>{r.assign(Sn(e.z,e.y).div(zo(e.x)))}).ElseIf(t.equal(1),()=>{r.assign(Sn(e.x.negate(),e.z.negate()).div(zo(e.y)))}).ElseIf(t.equal(2),()=>{r.assign(Sn(e.x.negate(),e.y).div(zo(e.z)))}).ElseIf(t.equal(3),()=>{r.assign(Sn(e.z.negate(),e.y).div(zo(e.x)))}).ElseIf(t.equal(4),()=>{r.assign(Sn(e.x.negate(),e.z).div(zo(e.y)))}).Else(()=>{r.assign(Sn(e.x,e.y).div(zo(e.z)))}),Va(.5,r.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Bf=gn(([e])=>{const t=Tn(0).toVar();return yn(e.greaterThanEqual(xf),()=>{t.assign(yf.sub(e).mul(Tf.sub(bf)).div(yf.sub(xf)).add(bf))}).ElseIf(e.greaterThanEqual(_f),()=>{t.assign(xf.sub(e).mul(vf.sub(Tf)).div(xf.sub(_f)).add(Tf))}).ElseIf(e.greaterThanEqual(Nf),()=>{t.assign(_f.sub(e).mul(Sf.sub(vf)).div(_f.sub(Nf)).add(vf))}).ElseIf(e.greaterThanEqual(Ef),()=>{t.assign(Nf.sub(e).mul(Rf.sub(Sf)).div(Nf.sub(Ef)).add(Sf))}).Else(()=>{t.assign(Tn(-2).mul(No(Va(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Lf=gn(([e,t])=>{const r=e.toVar();r.assign(Va(2,r).sub(1));const s=An(r,1).toVar();return yn(t.equal(0),()=>{s.assign(s.zyx)}).ElseIf(t.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),Ff=gn(([e,t,r,s,i,n])=>{const a=Tn(r),o=An(t),u=Tu(Bf(a),bf,n),l=Co(u),d=Ro(u),c=An(Pf(e,o,d,s,i,n)).toVar();return yn(l.notEqual(0),()=>{const t=An(Pf(e,o,d.add(1),s,i,n)).toVar();c.assign(xu(c,t,l))}),c}),Pf=gn(([e,t,r,s,i,n])=>{const a=Tn(r).toVar(),o=An(t),u=Tn(Cf(o)).toVar(),l=Tn(su(wf.sub(a),0)).toVar();a.assign(su(a,wf));const d=Tn(_o(a)).toVar(),c=Sn(Mf(o,u).mul(d.sub(2)).add(1)).toVar();return yn(u.greaterThan(2),()=>{c.y.addAssign(d),u.subAssign(3)}),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(Va(3,Af))),c.y.addAssign(Va(4,_o(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(Sn(),Sn())}),Uf=gn(({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=Lo(s),l=r.mul(u).add(i.cross(r).mul(Mo(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return Pf(e,l,t,n,a,o)}),Df=gn(({n:e,latitudinal:t,poleAxis:r,outputDirection:s,weights:i,samples:n,dTheta:a,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})=>{const h=An(Lu(t,r,lu(r,s))).toVar();yn(h.equal(An(0)),()=>{h.assign(An(s.z,0,s.x.negate()))}),h.assign(Ao(h));const p=An().toVar();return p.addAssign(i.element(0).mul(Uf({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Zp({start:_n(1),end:e},({i:e})=>{yn(e.greaterThanEqual(n),()=>{Jp()});const t=Tn(a.mul(Tn(e))).toVar();p.addAssign(i.element(e).mul(Uf({theta:t.mul(-1),axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),p.addAssign(i.element(e).mul(Uf({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))}),Ln(p,1)}),Of=gn(([e])=>{const t=vn(e).toVar();return t.assign(t.shiftLeft(vn(16)).bitOr(t.shiftRight(vn(16)))),t.assign(t.bitAnd(vn(1431655765)).shiftLeft(vn(1)).bitOr(t.bitAnd(vn(2863311530)).shiftRight(vn(1)))),t.assign(t.bitAnd(vn(858993459)).shiftLeft(vn(2)).bitOr(t.bitAnd(vn(3435973836)).shiftRight(vn(2)))),t.assign(t.bitAnd(vn(252645135)).shiftLeft(vn(4)).bitOr(t.bitAnd(vn(4042322160)).shiftRight(vn(4)))),t.assign(t.bitAnd(vn(16711935)).shiftLeft(vn(8)).bitOr(t.bitAnd(vn(4278255360)).shiftRight(vn(8)))),Tn(t).mul(2.3283064365386963e-10)}),If=gn(([e,t])=>Sn(Tn(e).div(Tn(t)),Of(e))),Vf=gn(([e,t,r])=>{const s=r.mul(r).toConst(),i=An(1,0,0).toConst(),n=lu(t,i).toConst(),a=So(e.x).toConst(),o=Va(2,3.14159265359).mul(e.y).toConst(),u=a.mul(Lo(o)).toConst(),l=a.mul(Mo(o)).toVar(),d=Va(.5,t.z.add(1)).toConst();l.assign(d.oneMinus().mul(So(u.mul(u).oneMinus())).add(d.mul(l)));const c=i.mul(u).add(n.mul(l)).add(t.mul(So(su(0,u.mul(u).add(l.mul(l)).oneMinus()))));return Ao(An(s.mul(c.x),s.mul(c.y),su(0,c.z)))}),kf=gn(({roughness:e,mipInt:t,envMap:r,N_immutable:s,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=An(s).toVar(),l=An(0).toVar(),d=Tn(0).toVar();return yn(e.lessThan(.001),()=>{l.assign(Pf(r,u,t,n,a,o))}).Else(()=>{const s=Lu(zo(u.z).lessThan(.999),An(0,0,1),An(1,0,0)),c=Ao(lu(s,u)).toVar(),h=lu(u,c).toVar();Zp({start:vn(0),end:i},({i:s})=>{const p=If(s,i),g=Vf(p,An(0,0,1),e),m=Ao(c.mul(g.x).add(h.mul(g.y)).add(u.mul(g.z))),f=Ao(m.mul(uu(u,m).mul(2)).sub(u)),y=su(uu(u,f),0);yn(y.greaterThan(0),()=>{const e=Pf(r,f,t,n,a,o);l.addAssign(e.mul(y)),d.addAssign(y)})}),yn(d.greaterThan(0),()=>{l.assign(l.div(d))})}),Ln(l,1)}),Gf=[.125,.215,.35,.446,.526,.582],zf=20,$f=new Ne(-1,1,1,-1,0,1),Wf=new Se(90,1),Hf=new e;let jf=null,qf=0,Xf=0;const Yf=new r,Qf=new WeakMap,Kf=[3,1,5,0,4,2],Zf=Lf(ql(),jl("faceIndex")).normalize(),Jf=An(Zf.x,Zf.y,Zf.z);class ey{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Yf,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized)throw new Error('THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.');jf=this._renderer.getRenderTarget(),qf=this._renderer.getActiveCubeFace(),Xf=this._renderer.getActiveMipmapLevel();const u=o||this._allocateTarget(!0);return this._init(u),this._sceneToCubeUV(e,r,s,u,a),t>0&&this._blur(u,0,0,t),this._applyPMREM(u),this._cleanup(u),u}async fromSceneAsync(e,t=0,r=.1,s=100,i={}){return v('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized)throw new Error('THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return v('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized)throw new Error('THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return v('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=sy(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=iy(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===D||e.mapping===O?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(jf,qf,Xf),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),jf=this._renderer.getRenderTarget(),qf=this._renderer.getActiveCubeFace(),Xf=this._renderer.getActiveMipmapLevel();const r=t||this._allocateTarget(!1);return this._init(r),this._textureToCubeUV(e,r),this._applyPMREM(r),this._cleanup(r),r}_allocateTarget(e){return ty(3*Math.max(this._cubeSize,112),4*this._cubeSize,e)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=ty(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],r=[],s=[];let i=e;const n=e-4+1+Gf.length;for(let a=0;a<n;a++){const n=Math.pow(2,i);t.push(n);let o=1/n;a>e-4?o=Gf[a-e+4-1]:0===a&&(o=0),r.push(o);const u=1/(n-2),l=-u,d=1+u,c=[l,l,d,l,d,d,l,l,d,d,l,d],h=6,p=6,g=3,m=2,f=1,y=new Float32Array(g*p*h),b=new Float32Array(m*p*h),x=new Float32Array(f*p*h);for(let e=0;e<h;e++){const t=e%3*2/3-1,r=e>2?0:-1,s=[t,r,0,t+2/3,r,0,t+2/3,r+1,0,t,r,0,t+2/3,r+1,0,t,r+1,0],i=Kf[e];y.set(s,g*p*i),b.set(c,m*p*i);const n=[i,i,i,i,i,i];x.set(n,f*p*i)}const T=new ve;T.setAttribute("position",new Ae(y,g)),T.setAttribute("uv",new Ae(b,m)),T.setAttribute("faceIndex",new Ae(x,f)),s.push(new oe(T,null)),i>4&&i--}return{lodMeshes:s,sizeLods:t,sigmas:r}}(t)),this._blurMaterial=function(e,t,s){const i=ud(new Array(zf).fill(0)),n=Aa(new r(0,1,0)),a=Aa(0),o=Tn(zf),u=Aa(0),l=Aa(1),d=rd(),c=Aa(0),h=Tn(1/t),p=Tn(1/s),g=Tn(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:Jf,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=ry("blur");return f.fragmentNode=Df({...m,latitudinal:u.equal(1)}),Qf.set(f,m),f}(t,e.width,e.height),this._ggxMaterial=function(e,t,r){const s=rd(),i=Aa(0),n=Aa(0),a=Tn(1/t),o=Tn(1/r),u=Tn(e),l={envMap:s,roughness:i,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:u},d=ry("ggx");return d.fragmentNode=kf({...l,N_immutable:Jf,GGX_SAMPLES:vn(512)}),Qf.set(d,l),d}(t,e.width,e.height)}}async _compileMaterial(e){const t=new oe(new ve,e);await this._renderer.compile(t,$f)}_sceneToCubeUV(e,t,r,s,i){const n=Wf;n.near=t,n.far=r;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],u=this._renderer,l=u.autoClear;u.getClearColor(Hf),u.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new oe(new ae,new fe({name:"PMREM.Background",side:F,depthWrite:!1,depthTest:!1})));const d=this._backgroundBox,c=d.material;let h=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,h=!0):(c.color.copy(Hf),h=!0),u.setRenderTarget(s),u.clear(),h&&u.render(d,n);for(let t=0;t<6;t++){const r=t%3;0===r?(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x+o[t],i.y,i.z)):1===r?(n.up.set(0,0,a[t]),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y+o[t],i.z)):(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y,i.z+o[t]));const l=this._cubeSize;this._setViewport(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=p}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===D||e.mapping===O;s?null===this._cubemapMaterial&&(this._cubemapMaterial=sy(e)):null===this._equirectMaterial&&(this._equirectMaterial=iy(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,$f)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let t=1;t<s;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=r}_applyGGXFilter(e,t,r){const s=this._renderer,i=this._pingPongRenderTarget,n=this._ggxMaterial,a=this._lodMeshes[r];a.material=n;const o=Qf.get(n),u=r/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),d=Math.sqrt(u*u-l*l)*(0+1.25*u),{_lodMax:c}=this,h=this._sizeLods[r],p=3*h*(r>c-4?r-c+4:0),g=4*(this._cubeSize-h);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=d,o.mipInt.value=c-t,this._setViewport(i,p,g,3*h,2*h),s.setRenderTarget(i),s.render(a,$f),i.texture.frame=(i.texture.frame||0)+1,o.envMap.value=i.texture,o.roughness.value=0,o.mipInt.value=c-r,this._setViewport(e,p,g,3*h,2*h),s.setRenderTarget(e),s.render(a,$f)}_blur(e,t,r,s,i){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,r,s,"latitudinal",i),this._halfBlur(n,e,r,r,s,"longitudinal",i)}_halfBlur(e,t,r,s,i,n,a){const u=this._renderer,l=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&o("blur direction must be either latitudinal or longitudinal!");const c=this._lodMeshes[s];c.material=l;const h=Qf.get(l),p=this._sizeLods[r]-1,g=isFinite(i)?Math.PI/(2*p):2*Math.PI/39,m=i/g,f=isFinite(i)?1+Math.floor(3*m):zf;f>zf&&d(`sigmaRadians, ${i}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const y=[];let b=0;for(let e=0;e<zf;++e){const t=e/m,r=Math.exp(-t*t/2);y.push(r),0===e?b+=r:e<f&&(b+=2*r)}for(let e=0;e<y.length;e++)y[e]=y[e]/b;e.texture.frame=(e.texture.frame||0)+1,h.envMap.value=e.texture,h.samples.value=f,h.weights.array=y,h.latitudinal.value="latitudinal"===n?1:0,a&&(h.poleAxis.value=a);const{_lodMax:x}=this;h.dTheta.value=g,h.mipInt.value=x-r;const T=this._sizeLods[s],_=3*T*(s>x-4?s-x+4:0),v=4*(this._cubeSize-T);this._setViewport(t,_,v,3*T,2*T),u.setRenderTarget(t),u.render(c,$f)}_setViewport(e,t,r,s,i){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-i-r,s,i),e.scissor.set(t,e.height-i-r,s,i)):(e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i))}}function ty(e,t,r){const s=new ne(e,t,{magFilter:le,minFilter:le,generateMipmaps:!1,type:Te,format:Re,colorSpace:Ee,depthBuffer:r});return s.texture.mapping=we,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function ry(e){const t=new Dg;return t.depthTest=!1,t.depthWrite=!1,t.blending=re,t.name=`PMREM_${e}`,t}function sy(e){const t=ry("cubemap");return t.fragmentNode=Qc(e,Jf),t}function iy(e){const t=ry("equirect");return t.fragmentNode=rd(e,Jg(Jf),0),t}const ny=new WeakMap;function ay(e,t,r){const s=function(e){let t=ny.get(e);void 0===t&&(t=new WeakMap,ny.set(e,t));return t}(t);let i=s.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const r=6;for(let s=0;s<r;s++)void 0!==e[s]&&t++;return t===r}(t))return null;i=r.fromCubemap(e,i)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;i=r.fromEquirectangular(e,i)}if(i.pmremVersion=e.pmremVersion,!1===s.has(e)){const t=()=>{e.removeEventListener("dispose",t);const r=s.get(e);void 0!==r&&(r.dispose(),s.delete(e))};e.addEventListener("dispose",t)}s.set(e,i)}return i.texture}class oy extends fi{static get type(){return"PMREMNode"}constructor(e,t=null,r=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=r,this._generator=null;const s=new N;s.isRenderTargetTexture=!0,this._texture=rd(s),this._width=Aa(0),this._height=Aa(0),this._maxMip=Aa(0),this.updateBeforeType=ii.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:r,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const r=t?t.pmremVersion:-1,s=this._value;r!==s.pmremVersion&&(t=!0===s.isPMREMTexture||s.mapping===we?s:ay(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new ey(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=this._pmrem.isRenderTargetTexture?zc.mul(An(t.x,t.y.negate(),t.z)):zc.mul(t);let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),Ff(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const uy=un(oy).setParameterLength(1,3),ly=new WeakMap;class dy extends ng{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const s=r.isTextureNode?r.value:t[r.property],i=this._getPMREMNodeCache(e.renderer);let n=i.get(s);void 0===n&&(n=uy(s),i.set(s,n)),r=n}const s=!0===t.useAnisotropy||t.anisotropy>0?Ah:Bc,i=r.context(cy(qn,s)).mul(Gc),n=r.context(hy(Lc)).mul(Math.PI).mul(Gc),a=wl(i),o=wl(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(cy(Qn,Fc)).mul(Gc),t=wl(e);u.addAssign(t)}}_getPMREMNodeCache(e){let t=ly.get(e);return void 0===t&&(t=new WeakMap,ly.set(e,t)),t}}const cy=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=_c.negate().reflect(t),r=pu(e).mix(r,t).normalize(),r=r.transformDirection($d)),r),getTextureLevel:()=>e}},hy=e=>({getUV:()=>e,getTextureLevel:()=>Tn(1)}),py=new Ce;class gy extends Dg{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(py),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new dy(t):null}setupLightingModel(){return new ff}setupSpecular(){const e=xu(An(.04),Wn.rgb,Xn);aa.assign(An(.04)),oa.assign(e),ua.assign(1)}setupVariants(){const e=this.metalnessNode?Tn(this.metalnessNode):Kh;Xn.assign(e);let t=this.roughnessNode?Tn(this.roughnessNode):Qh;t=Nm({roughness:t}),qn.assign(t),this.setupSpecular(),Hn.assign(Wn.rgb.mul(e.oneMinus()))}}const my=new Me;class fy extends gy{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(my),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?Tn(this.iorNode):cp;ga.assign(e),aa.assign(ru(cu(ga.sub(1).div(ga.add(1))).mul(qh),An(1)).mul(jh)),oa.assign(xu(aa,Wn.rgb,Xn)),ua.assign(xu(jh,1,Xn))}setupLightingModel(){return new ff(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Tn(this.clearcoatNode):Jh,t=this.clearcoatRoughnessNode?Tn(this.clearcoatRoughnessNode):ep;Yn.assign(e),Qn.assign(Nm({roughness:t}))}if(this.useSheen){const e=this.sheenNode?An(this.sheenNode):sp,t=this.sheenRoughnessNode?Tn(this.sheenRoughnessNode):ip;Kn.assign(e),Zn.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Tn(this.iridescenceNode):ap,t=this.iridescenceIORNode?Tn(this.iridescenceIORNode):op,r=this.iridescenceThicknessNode?Tn(this.iridescenceThicknessNode):up;Jn.assign(e),ea.assign(t),ta.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?Sn(this.anisotropyNode):np).toVar();sa.assign(e.length()),yn(sa.equal(0),()=>{e.assign(Sn(1,0))}).Else(()=>{e.divAssign(Sn(sa)),sa.assign(sa.saturate())}),ra.assign(sa.pow2().mix(qn.pow2(),1)),ia.assign(Rh[0].mul(e.x).add(Rh[1].mul(e.y))),na.assign(Rh[1].mul(e.x).sub(Rh[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Tn(this.transmissionNode):lp,t=this.thicknessNode?Tn(this.thicknessNode):dp,r=this.attenuationDistanceNode?Tn(this.attenuationDistanceNode):hp,s=this.attenuationColorNode?An(this.attenuationColorNode):pp;if(ma.assign(e),fa.assign(t),ya.assign(r),ba.assign(s),this.useDispersion){const e=this.dispersionNode?Tn(this.dispersionNode):Tp;xa.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?An(this.clearcoatNormalNode):tp}setup(e){e.context.setupClearcoatNormal=()=>ju(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}}class yy extends ff{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1,a=!1){super(e,t,r,s,i,n),this.useSSS=a}direct({lightDirection:e,lightColor:t,reflectedLight:r},s){if(!0===this.useSSS){const i=s.material,{thicknessColorNode:n,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:d}=i,c=e.add(Bc.mul(a)).normalize(),h=Tn(_c.dot(c.negate()).saturate().pow(l).mul(d)),p=An(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class by extends fy{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=Tn(.1),this.thicknessAmbientNode=Tn(0),this.thicknessAttenuationNode=Tn(.1),this.thicknessPowerNode=Tn(2),this.thicknessScaleNode=Tn(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new yy(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useSSS)}}const xy=gn(({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=Sn(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=rh("gradientMap","texture").context({getUV:()=>i});return An(e.r)}{const e=i.fwidth().mul(.5);return xu(An(.7),An(1),Nu(Tn(.7).sub(e.x),Tn(.7).add(e.x),i.x))}});class Ty extends lm{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=xy({normal:Rc,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(gm({diffuseColor:Wn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(gm({diffuseColor:Wn}))),s.indirectDiffuse.mulAssign(t)}}const _y=new Be;class vy extends Dg{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(_y),this.setValues(e)}setupLightingModel(){return new Ty}}const Ny=gn(()=>{const e=An(_c.z,0,_c.x.negate()).normalize(),t=_c.cross(e);return Sn(e.dot(Bc),t.dot(Bc)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),Sy=new Le;class Ey extends Dg{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Sy),this.setValues(e)}setupVariants(e){const t=Ny;let r;r=e.material.matcap?rh("matcap","texture").context({getUV:()=>t}):An(xu(.2,.8,t.y)),Wn.rgb.mulAssign(r.rgb)}}class Ry extends fi{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:r}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),s=t.sin();return Dn(e,s,s.negate(),e).mul(r)}{const e=t,s=In(Ln(1,0,0,0),Ln(0,Lo(e.x),Mo(e.x).negate(),0),Ln(0,Mo(e.x),Lo(e.x),0),Ln(0,0,0,1)),i=In(Ln(Lo(e.y),0,Mo(e.y),0),Ln(0,1,0,0),Ln(Mo(e.y).negate(),0,Lo(e.y),0),Ln(0,0,0,1)),n=In(Ln(Lo(e.z),Mo(e.z).negate(),0,0),Ln(Mo(e.z),Lo(e.z),0,0),Ln(0,0,1,0),Ln(0,0,0,1));return s.mul(i).mul(n).mul(Ln(r,1)).xyz}}}const wy=un(Ry).setParameterLength(2),Ay=new Fe;class Cy extends Dg{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(Ay),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,{positionNode:s,rotationNode:i,scaleNode:n,sizeAttenuation:a}=this,o=dc.mul(An(s||0));let u=Sn(sc[0].xyz.length(),sc[1].xyz.length());null!==n&&(u=u.mul(Sn(n))),r.isPerspectiveCamera&&!1===a&&(u=u.mul(o.z.negate()));let l=mc.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>new sl(e,t,r))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=Tn(i||rp),c=wy(l,d);return Ln(o.xy.add(c),o.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const My=new Pe,By=new t;class Ly extends Cy{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(My),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return dc.mul(An(e||fc)).xyz}setupVertexSprite(e){const{material:t,camera:r}=e,{rotationNode:s,scaleNode:i,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let u=null!==n?Sn(n):xp;u=u.mul(gd),r.isPerspectiveCamera&&!0===a&&(u=u.mul(Fy.div(Tc.z.negate()))),i&&i.isNode&&(u=u.mul(Sn(i)));let l=mc.xy;if(s&&s.isNode){const e=Tn(s);l=wy(l,e)}return l=l.mul(u),l=l.div(xd.div(2)),l=l.mul(o.w),o=o.add(Ln(l,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const Fy=Aa(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(By);this.value=.5*t.y});class Py extends lm{constructor(){super(),this.shadowNode=Tn(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Wn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Wn.rgb)}}const Uy=new Ue;class Dy extends Dg{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(Uy),this.setValues(e)}setupLightingModel(){return new Py}}const Oy=zn("vec3"),Iy=zn("vec3"),Vy=zn("vec3");class ky extends lm{constructor(){super()}start(e){const{material:t}=e,r=zn("vec3"),s=zn("vec3"),i=zn("bool");yn(Hd.sub(bc).length().greaterThan(oc.mul(2)),()=>{r.assign(Hd),s.assign(bc),i.assign(!0)}).Else(()=>{r.assign(bc),s.assign(Hd),i.assign(!1)});const n=s.sub(r),a=Aa("int").onRenderUpdate(({material:e})=>e.steps),o=n.length().div(a).toVar(),u=n.normalize().toVar(),l=Tn(0).toVar(),d=An(1).toVar();t.offsetNode&&l.addAssign(t.offsetNode.mul(o)),Zp(a,()=>{const s=r.add(u.mul(l)),n=zd.mul(Ln(s,1)).xyz;let a,c;null!==t.depthNode&&(Iy.assign(Ag(vg(n.z,Id,Vd))),e.context.sceneDepthNode=Ag(t.depthNode).toVar()),e.context.positionWorld=s,e.context.shadowPositionWorld=s,e.context.positionView=n,Oy.assign(0),t.scatteringNode&&(a=t.scatteringNode({positionRay:s})),t.scatteringEmissiveNode&&(c=t.scatteringEmissiveNode({positionRay:s})),super.start(e),a&&Oy.mulAssign(a);const h=Oy.mul(.01).toVar();c&&h.addAssign(c.mul(.01));const p=Oy.mul(.01).negate().mul(o).exp();yn(i,()=>{Vy.addAssign(h.mul(d).mul(o))}).Else(()=>{Vy.assign(Vy.mul(p).add(h.mul(o)))}),d.mulAssign(p),l.addAssign(o)})}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?yn(r.greaterThanEqual(Iy),()=>{Oy.addAssign(e)}):Oy.addAssign(e)}direct({lightNode:e,lightColor:t},r){if(!0!==e.isAnalyticLightNode||void 0===e.light.distance)return;const s=t.xyz.toVar();null!==e.shadowNode&&s.mulAssign(e.shadowNode),this.scatteringLight(s,r)}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s},i){const n=t.add(r).sub(s),a=t.sub(r).sub(s),o=t.sub(r).add(s),u=t.add(r).add(s),l=i.context.positionView,d=e.xyz.mul($m({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(Vy)}}class Gy extends Dg{static get type(){return"VolumeNodeMaterial"}constructor(e){super(),this.isVolumeNodeMaterial=!0,this.steps=25,this.offsetNode=null,this.scatteringNode=null,this.lights=!0,this.transparent=!0,this.side=F,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new ky}}class zy{constructor(e,t,r){this.renderer=e,this.nodes=t,this.info=r,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,r)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,r),this.renderer._inspector.finish()};e()}stop(){null!==this._context&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class $y{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let r=this.weakMaps[t];return void 0===r&&(r=new WeakMap,this.weakMaps[t]=r),r}get(e){let t=this._getWeakMap(e);for(let r=0;r<e.length-1;r++)if(t=t.get(e[r]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let r=this._getWeakMap(e);for(let t=0;t<e.length-1;t++){const s=e[t];!1===r.has(s)&&r.set(s,new WeakMap),r=r.get(s)}return r.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let r=0;r<e.length-1;r++)if(t=t.get(e[r]),void 0===t)return!1;return t.delete(e[e.length-1])}}let Wy=0;const Hy=new WeakMap;class jy{constructor(e,t,r,s,i,n,a,o,u,l){this.id=Wy++,this._nodes=e,this._geometries=t,this.renderer=r,this.object=s,this.material=i,this.scene=n,this.camera=a,this.lightsNode=o,this.context=u,this.geometry=s.geometry,this.version=i.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=l,this.clippingContextCacheKey=null!==l?l.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this._sourceMaterial=r._currentSourceMaterial,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose),null!==this._sourceMaterial&&this._sourceMaterial.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.getNodeBuilderState().hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,r=[],s=new Set,i={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),void 0!==e&&(e.isInterleavedBufferAttribute?i[n.name]=e.data.uuid:i[n.name]=e.id)),void 0===e)continue;r.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;s.add(a)}return this.attributes=r,this.attributesId=i,this.vertexBuffers=Array.from(s.values()),r}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:r,group:s,drawRange:i}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let u=1;if(!0===r.isInstancedBufferGeometry?u=r.instanceCount:void 0!==e.count&&(u=Math.max(0,e.count)),0===u)return null;if(n.instanceCount=u,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let d=i.start*l,c=(i.start+i.count)*l;null!==s&&(d=Math.max(d,s.start*l),c=Math.min(c,(s.start+s.count)*l));const h=r.attributes.position;let p=1/0;o?p=a.count:null!=h&&(p=h.count),d=Math.max(d,0),c=Math.min(c,p);const g=c-d;return g<0||g===1/0?null:(n.vertexCount=g,n.firstVertex=d,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const r of Object.keys(e.attributes).sort()){const s=e.attributes[r];t+=r+",",s.data&&(t+=s.data.stride+","),s.offset&&(t+=s.offset+","),s.itemSize&&(t+=s.itemSize+","),s.normalized&&(t+="n,")}for(const r of Object.keys(e.morphAttributes).sort()){const s=e.morphAttributes[r];t+="morph-"+r+",";for(let e=0,r=s.length;e<r;e++){t+=s[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:r}=this;let s=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let r=Hy.get(e.constructor);if(void 0===r){r=[];let t=Object.getPrototypeOf(e);for(;t;){const e=Object.getOwnPropertyDescriptors(t);for(const t in e){const s=e[t];s&&"function"==typeof s.get&&r.push(t)}t=Object.getPrototypeOf(t)}Hy.set(e.constructor,r)}for(let e=0;e<r.length;e++)t.push(r[e]);return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const i=t[e];let n;if(null!==i){const t=typeof i;"number"===t?n="side"===e?String(i):0!==i?"1":"0":"object"===t?(n="{",i.isTexture&&(n+=i.mapping,!0===r.backend.isWebGPUBackend&&(n+=i.magFilter,n+=i.minFilter,n+=i.wrapS,n+=i.wrapT,n+=i.wrapR)),n+="}"):n=String(i)}else n=String(i);s+=n+","}return s+=this.clippingContextCacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1)&&(s+=e.uuid+","),s+=this.context.id+",",s+=e.receiveShadow+",",Gs(s)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const r=this.geometry.getAttribute(t);if(void 0===r)return!0;const s=r.isInterleavedBufferAttribute?r.data.uuid:r.id;if(e[t]!==s)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=$s(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=$s(e,1)),e=$s(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),null!==this._sourceMaterial&&this._sourceMaterial.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const qy=[];class Xy{constructor(e,t,r,s,i,n){this.renderer=e,this.nodes=t,this.geometries=r,this.pipelines=s,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,r,s,i,n,a,o){const u=this.getChainMap(o);qy[0]=e,qy[1]=t,qy[2]=n,qy[3]=i;let l=u.get(qy);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(qy,l)):(l.camera=s,l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),qy[0]=null,qy[1]=null,qy[2]=null,qy[3]=null,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new $y)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new jy(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.deleteForRender(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class Yy{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const Qy=1,Ky=2,Zy=3,Jy=4,eb=16;class tb extends Yy{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){const t=super.delete(e);return null!==t&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const r=this.get(e);if(void 0===r.version)t===Qy?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Ky?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===Zy?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===Jy&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version<t.version||t.usage===x)&&(this.backend.updateAttribute(e),r.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function rb(e){return null!==e.index?e.index.version:e.attributes.position.version}function sb(e){return null!==e.index?e.index.id:e.attributes.position.id}function ib(e){const t=[],r=e.index,s=e.attributes.position;if(null!==r){const e=r.array;for(let r=0,s=e.length;r<s;r+=3){const s=e[r+0],i=e[r+1],n=e[r+2];t.push(s,i,i,n,n,s)}}else{for(let e=0,r=s.array.length/3-1;e<r;e+=3){const r=e+0,s=e+1,i=e+2;t.push(r,s,s,i,i,r)}}const i=new(s.count>=65535?De:Oe)(t,1);return i.version=rb(e),i.__id=sb(e),i}class nb extends Yy{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const r=()=>{this.info.memory.geometries--;const s=t.index,i=e.getAttributes();null!==s&&this.attributes.delete(s);for(const e of i)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",r),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,Zy):this.updateAttribute(e,Qy);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,Ky);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,Jy)}updateAttribute(e,t){const r=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,r)):this.attributeCall.get(e.data)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e.data,r),this.attributeCall.set(e,r)):this.attributeCall.get(e)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e,r))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:r}=e;let s=t.index;if(!0===r.wireframe){const e=this.wireframes;let r=e.get(t);void 0===r?(r=ib(t),e.set(t,r)):r.version===rb(t)&&r.__id===sb(t)||(this.attributes.delete(r),r=ib(t),e.set(t,r)),s=r}return s}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class ab{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={attributes:0,attributesSize:0,geometries:0,indexAttributes:0,indexAttributesSize:0,indirectStorageAttributes:0,indirectStorageAttributesSize:0,programs:0,programsSize:0,readbackBuffers:0,readbackBuffersSize:0,renderTargets:0,storageAttributes:0,storageAttributesSize:0,textures:0,texturesSize:0,uniformBuffers:0,uniformBuffersSize:0,total:0},this.memoryMap=new Map}update(e,t,r){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=r*(t/3):e.isPoints?this.render.points+=r*t:e.isLineSegments?this.render.lines+=r*(t/2):e.isLine?this.render.lines+=r*(t-1):o("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const r=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:r,type:t}),this.memory[t]++,this.memory.total+=r,this.memory[t+"Size"]+=r}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createUniformBuffer(e){const t=e.byteLength;this.memoryMap.set(e,{size:t,type:"uniformBuffers"}),this.memory.uniformBuffers++,this.memory.total+=t,this.memory.uniformBuffersSize+=t}destroyUniformBuffer(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory.uniformBuffers--,this.memory.total-=t.size,this.memory.uniformBuffersSize-=t.size)}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===Ie||e.type===Ve?t=1:e.type===ke||e.type===Ge||e.type===Te?t=2:e.type!==E&&e.type!==S&&e.type!==Y||(t=4);let r=4;e.format===ze||e.format===$e||e.format===We||e.format===He||e.format===je?r=1:e.format===$||e.format===qe?r=2:e.format!==Xe&&e.format!==Ye||(r=3);let s=t*r;e.type===Qe||e.type===Ke?s=2:e.type!==Ze&&e.type!==Je&&e.type!==et||(s=4);const i=e.width||1,n=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=i*n*a*s;const u=e.mipmaps;if(u&&u.length>0){let e=0;for(let t=0;t<u.length;t++){const r=u[t];if(r.data)e+=r.data.byteLength;else{e+=(r.width||Math.max(1,i>>t))*(r.height||Math.max(1,n>>t))*a*s}}o+=e}else e.generateMipmaps&&(o*=1.333);return Math.round(o)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class ob{constructor(e){this.cacheKey=e,this.usedTimes=0}}class ub extends ob{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class lb extends ob{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let db=0;class cb{constructor(e,t,r,s=null,i=null){this.id=db++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class hb extends Yy{constructor(e,t,r){super(),this.backend=e,this.nodes=t,this.info=r,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:r}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new cb(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.createProgram(a),this.info.createProgram(a));const o=this._getComputeCacheKey(e,a);let u=this.caches.get(o);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(i),u=this._getComputePipeline(e,a,o,t)),u.usedTimes++,a.usedTimes++,s.version=e.version,s.pipeline=u}return s.pipeline}getForRender(e,t=null){const{backend:r}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new cb(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o),this.info.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new cb(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.createProgram(u),this.info.createProgram(u));const l=this._getRenderCacheKey(e,o,u);let d=this.caches.get(l);void 0===d?(i&&0===i.usedTimes&&this._releasePipeline(i),d=this._getRenderPipeline(e,o,u,l,t)):e.pipeline=d,d.usedTimes++,o.usedTimes++,u.usedTimes++,s.pipeline=d}return s.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const r=this.backend.get(t);return void 0!==r.pipeline&&null!==r.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,r,s){r=r||this._getComputeCacheKey(e,t);let i=this.caches.get(r);return void 0===i&&(i=new lb(r,t),this.caches.set(r,i),this.backend.createComputePipeline(i,s)),i}_getRenderPipeline(e,t,r,s,i){s=s||this._getRenderCacheKey(e,t,r);let n=this.caches.get(s);return void 0===n&&(n=new ub(s,t,r),this.caches.set(s,n),e.pipeline=n,this.backend.createRenderPipeline(e,i)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,r){return t.id+","+r.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,r=e.stage;this.programs[r].delete(t),this.info.destroyProgram(e)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class pb extends Yy{constructor(e,t,r,s,i,n){super(),this.backend=e,this.textures=r,this.pipelines=i,this.attributes=s,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings(),r=this.get(e);return!0!==r.initialized&&(this._createBindings(t),r.initialized=!0),t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings,r=this.get(e);return!0===r.initialized&&r.bindings===t||(void 0!==r.bindings&&this._destroyBindings(r.bindings),this._createBindings(t),r.initialized=!0,r.bindings=t),t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.get(e).bindings||this.nodes.getForCompute(e).bindings;this._destroyBindings(t),this.delete(e)}deleteForRender(e){const t=e.getBindings();this._destroyBindings(t),this.delete(e)}_createBindings(e){for(const t of e){const r=this.get(t);if(void 0===r.bindGroup){for(const e of t.bindings)if(e.isUniformBuffer)this.backend.createUniformBuffer(e),this.info.createUniformBuffer(e);else if(e.isSampledTexture)this.textures.updateTexture(e.texture);else if(e.isSampler)this.textures.updateSampler(e);else if(e.isStorageBuffer){const t=e.attribute,r=t.isIndirectStorageBufferAttribute?Jy:Zy;this.attributes.update(t,r)}this.backend.createBindings(t,e,0),r.bindGroup=t,r.usedTimes=1}else r.usedTimes++}}_destroyBindings(e){for(const t of e){const e=this.get(t);if(e.usedTimes--,0===e.usedTimes){for(const e of t.bindings)e.isUniformBuffer?(this.backend.destroyUniformBuffer(e),this.info.destroyUniformBuffer(e),e.release()):e.isSampler&&(!0!==e.isSampledTexture&&this.backend.destroySampler(e),e.release());this.backend.deleteBindGroupData(t),this.delete(t)}}}_updateBindings(e){for(const t of e)this._update(t,e)}_update(e,t){const{backend:r}=this;let s=!1,i=!0,n=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,i=e.isIndirectStorageBufferAttribute?Jy:Zy,n=r.get(t);this.attributes.update(e,i),n.attribute!==e&&(n.attribute=e,s=!0)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),u=t.texture,l=this.textures.get(u);o&&(this.textures.updateTexture(u),t.generation!==l.generation&&(t.generation=l.generation,s=!0),l.bindGroups.add(e));if(void 0!==r.get(u).externalTexture||l.isDefaultTexture?i=!1:(n=10*n+u.id,a+=u.version),!0===u.isStorageTexture&&!0===u.mipmapsAutoUpdate){const e=this.get(u);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(u)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(u),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t);t.samplerKey!==e&&(t.samplerKey=e,s=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}const gb=Object.freeze([]);function mb(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function fb(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function yb(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&e.side===P&&!1===e.forceSinglePass}class bb{constructor(e,t,r){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lighting=e,this.lightsNode=e.getNode(t),this.lightsArray=[],this.scene=t,this.camera=r,this.occlusionQueryCount=0,this._lastOcclusionObject=null}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,r,s,i,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:r,groupOrder:s,renderOrder:e.renderOrder,z:i,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=r,o.groupOrder=s,o.renderOrder=e.renderOrder,o.z=i,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===e.occlusionTest&&this._lastOcclusionObject!==e&&(this.occlusionQueryCount++,this._lastOcclusionObject=e),!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(yb(r)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode?(yb(r)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t,r){this.opaque.length>1&&this.opaque.sort(e||mb),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||fb),this.transparent.length>1&&this.transparent.sort(t||fb),r&&(this.opaque.reverse(),this.transparentDoublePass.reverse(),this.transparent.reverse())}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:gb);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.groupOrder=null,t.renderOrder=null,t.z=null,t.group=null,t.clippingContext=null}this._lastOcclusionObject=null}}const xb=[];class Tb{constructor(e){this.lighting=e,this.lists=new $y}get(e,t){const r=this.lists;xb[0]=e,xb[1]=t;let s=r.get(xb);return void 0===s&&(s=new bb(this.lighting,e,t),r.set(xb,s)),xb[0]=null,xb[1]=null,s}dispose(){this.lists=new $y}}let _b=0;class vb{constructor(){this.id=_b++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new s,this.scissor=!1,this.scissorValue=new s,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.isRenderContext=!0}getCacheKey(){return Nb(this)}}function Nb(e){const{textures:t,activeCubeFace:r,activeMipmapLevel:s}=e,i=[r,s];for(const e of t)i.push(e.id);return zs(i)}class Sb{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,r=0){let s;if(null===e)s="default";else{const t=e.texture.format,r=e.texture.type;s=`${e.textures.length}:${t}:${r}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const i=s+"-"+(null!==t?t.id:"default")+"-"+r;let n=this._renderContexts[i];return void 0===n&&(n=new vb,n.mrt=t,this._renderContexts[i]=n),null!==e&&(n.sampleCount=0===e.samples?1:e.samples),n.clearDepthValue=this.renderer.getClearDepth(),n.clearStencilValue=this.renderer.getClearStencil(),n}dispose(){this._renderContexts={}}}const Eb=new r;class Rb extends Yy{constructor(e,t,r){super(),this.renderer=e,this.backend=t,this.info=r,this._htmlTextures=new Set}updateRenderTarget(e,t=0){const r=this.get(e),s=0===e.samples?1:e.samples,i=r.depthTextureMips||(r.depthTextureMips={}),n=e.textures,a=this.getSize(n[0]),o=a.width>>t,u=a.height>>t;let l=e.depthTexture||i[t];const d=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;const h=void 0!==l&&void 0!==l.image&&l.image.depth>1,p=a.depth>1&&(e.useArrayDepthTexture||e.multiview||h);void 0===l&&d&&(l=new Z,l.format=e.stencilBuffer?je:He,l.type=e.stencilBuffer?Ze:S,l.image.width=o,l.image.height=u,l.image.depth=a.depth,l.renderTarget=e,i[t]=l),l&&(l.isArrayTexture=p),r.width===a.width&&a.height===r.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=u,l.image.depth=p?a.depth:1)),r.width=a.width,r.height=a.height,r.textures=n,r.depthTexture=l||null,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,r.renderTarget=e,r.sampleCount!==s&&(c=!0,l&&(l.needsUpdate=!0),r.sampleCount=s);const g={sampleCount:s};if(!0!==e.isXRRenderTarget){for(let e=0;e<n.length;e++){const t=n[e];c&&(t.needsUpdate=!0),this.updateTexture(t,g)}l&&this.updateTexture(l,g)}!0!==r.initialized&&(r.initialized=!0,this.info.memory.renderTargets++,r.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",r.onDispose))}updateTexture(e,t={}){const r=this.get(e);if(!0===r.initialized&&r.version===e.version)return;const s=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(s&&!0===r.initialized&&i.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:Ve}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;if("requestPaint"in t){if(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image),0===this._htmlTextures.size){const e=this._htmlTextures;t.onpaint=t=>{const r=t&&t.changedElements;for(const t of e)r&&!r.includes(t.image)||(t.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,s||!0===e.isStorageTexture||!0===e.isExternalTexture)i.createTexture(e,t),r.generation=e.version;else if(e.version>0){const s=e.image;if(void 0===s)d("Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)d("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const r=[];for(const t of e.images)r.push(t);t.images=r}else t.image=s;void 0!==r.isDefaultTexture&&!0!==r.isDefaultTexture||(i.createTexture(e,t),r.isDefaultTexture=!1,r.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version;!0!==r.initialized&&(r.initialized=!0,r.generation=e.version,r.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===p.enabled&&p.getTransfer(e.colorSpace)!==g&&d("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),r.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",r.onDispose)),r.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=Eb){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),e.isHTMLTexture?(t.width=r.offsetWidth||1,t.height=r.offsetHeight||1,t.depth=1):"undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement?(t.width=r.videoWidth||1,t.height=r.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&r instanceof VideoFrame?(t.width=r.displayWidth||1,t.height=r.displayHeight||1,t.depth=1):(t.width=r.width||1,t.height=r.height||1,t.depth=e.isCubeTexture?6:r.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,r){let s;return s=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),r=t.textures,s=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e<r.length;e++)this._destroyTexture(r[e]);s&&this._destroyTexture(s),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const r=t.isDefaultTexture;if(this.backend.destroyTexture(e,r),t.bindGroups)for(const r of t.bindGroups){const t=this.backend.get(r);t.groups=void 0,t.versions=void 0;for(const t of r.bindings)t.isSampler&&t.texture===e&&(!0!==t.isSampledTexture&&this.backend.destroySampler(t),t.reset(),t.release())}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}class wb extends e{constructor(e,t,r,s=1){super(e,t,r),this.a=s}set(e,t,r,s=1){return this.a=s,super.set(e,t,r)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Ab extends Fu{static get type(){return"OverrideContextNode"}constructor(e,t=null){super(t,{overrideNodes:e}),this.isOverrideContextNode=!0}getFlowContextData(){const e=[];this.traverse(t=>{!0===t.isOverrideContextNode&&e.push(t.value.overrideNodes)});const t=new Map(e.flatMap(e=>Array.from(e.entries()))),r=super.getFlowContextData();return r.overrideNodes=t,r}}function Cb(e,t=null,r=null){if(t&&t.isNode){const e=t;t=()=>e}return new Ab(new Map([[e,t]]),r)}function Mb(e,t=null){const r=new Map;for(const[t,s]of e){const e=null!==s?"function"==typeof s?s:()=>s:null;r.set(t,e)}return new Ab(r,t)}Ai("overrideNode",(e,t,r)=>Cb(t,r,e)),Ai("overrideNodes",(e,t)=>Mb(t,e));class Bb extends Gn{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const r=this.getNodeType(e),s=e.getStructTypeNode(r);let i;return null!==s?i=s.getMemberType(e,t):(o(`TSL: Member "${t}" not found in struct "${r}".`,new Vs),i="float"),i}getHash(){return String(this.id)}generate(){return this.name}}class Lb extends pi{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this._nodeDataLibrary=new Map,this.isStackNode=!0}getElementType(e){return this.outputNode?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=-1){if(!0!==e.isNode)return o("TSL: Invalid node added to stack.",new Vs),this;if(-1===t)if(this._currentNode){let e=this._nodeDataLibrary.get(this._currentNode);void 0===e&&(e={delta:0},this._nodeDataLibrary.set(this._currentNode,e)),e.delta++,t=this.nodes.indexOf(this._currentNode)+e.delta}else t=this.nodes.length;return this.nodes.splice(t,0,e),this}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const r=new rn(t);return this._currentCond=Lu(e,r),this.addToStack(this._currentCond)}ElseIf(e,t){const r=new rn(t),s=Lu(e,r);return this._currentCond.elseNode=s,this._currentCond=s,this}Else(e){return this._currentCond.elseNode=new rn(e),this}Switch(e){return this._expressionNode=sn(e),this}Case(...e){const t=[];if(e.length>=2)for(let r=0;r<e.length-1;r++)t.push(this._expressionNode.equal(sn(e[r])));else o("TSL: Invalid parameter length. Case() requires at least two parameters.",new Vs);const r=new rn(e[e.length-1]);let s=t[0];for(let e=1;e<t.length;e++)s=s.or(t[e]);const i=Lu(s,r);return null===this._currentCond?(this._currentCond=i,this.addToStack(this._currentCond)):(this._currentCond.elseNode=i,this._currentCond=i,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let r=0;for(const s of this.getChildren())s.isVarNode&&s.isIntent(e)&&!0!==s.isAssign(e)||(t["node"+r++]=s);return t.outputNode||null}build(e,...t){const r=fn(),s=e.buildStage;mn(this),e.setActiveStack(this);for(let t=0;t<this.nodes.length;t++){const r=this.nodes[t],i=this._currentNode;if(this._currentNode=r,!r.isVarNode||!r.isIntent(e)||!0===r.isAssign(e)){if("setup"===s)r.build(e);else if("analyze"===s)r.build(e,this);else if("generate"===s){const t=e.getDataFromNode(r,"any").stages,s=t&&t[e.shaderStage];if(r.isVarNode&&s&&1===s.length&&s[0]&&s[0].isStackNode)continue;r.build(e,"void")}this._currentNode=i}}let i;if(this.outputNode){const r=this.outputNode.build(e,...t);"generate"===e.buildStage&&"void"===this.outputNode.getNodeType(e)||(i=r)}else i=super.build(e,...t);return mn(r),e.removeActiveStack(this),i}}const Fb=un(Lb).setParameterLength(0,1);class Pb extends pi{static get type(){return"StructTypeNode"}constructor(e,t=null){var r;super("struct"),this.membersLayout=(r=e,Object.entries(r).map(([e,t])=>"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})),this.name=t,this.isStructTypeNode=!0}getLength(){let e=1,t=0;for(const r of this.membersLayout){const s=r.type,i=Ys(s),n=Qs(s);e=Math.max(e,n);const a=t%e%n;0!==a&&(t+=n-a),t+=i}return Math.ceil(t/e)*e}getMemberType(e,t){const r=this.membersLayout.find(e=>e.name===t);return r?r.type:"void"}generateNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class Ub extends pi{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}generateNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}_getChildren(){const e=super._getChildren(),t=e.find(e=>e.childNode===this.structTypeNode);return e.splice(e.indexOf(t),1),e.push(t),e}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class Db extends pi{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}generateNodeType(){return"OutputType"}generate(e){const t=e.getDataFromNode(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;t<r.length;t++){const i="m"+t,n=r[t].getNodeType(e);s.push({name:i,type:n,index:t})}t.membersLayout=s,t.structType=e.getOutputStructTypeFromNode(this,t.membersLayout)}const r=e.getOutputStructName(),s=this.members,i=""!==r?r+".":"";for(let r=0;r<s.length;r++){const n=s[r].build(e,t.membersLayout[r].type);e.addLineFlowCode(`${i}m${r} = ${n}`,this)}return r}}const Ob=un(Db);class Ib{constructor(e=tt){this.blending=e,this.blendSrc=rt,this.blendDst=st,this.blendEquation=it,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.premultiplyAlpha=!1}copy(e){return this.blending=e.blending,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.premultiplyAlpha=e.premultiplyAlpha,this}clone(){return(new this.constructor).copy(this)}}const Vb=new Ib(re),kb=new Ib(nt);function Gb(e,t){for(let r=0;r<e.length;r++)if(e[r].name===t)return r;return-1}class zb extends Db{static get type(){return"MRTNode"}constructor(e){super(),this.outputNodes=e,this.blendModes={output:kb},this.isMRTNode=!0}setBlendMode(e,t){return this.blendModes[e]=t,this}getBlendMode(e){return this.blendModes[e]||Vb}has(e){return void 0!==this.outputNodes[e]}get(e){return this.outputNodes[e]}merge(e){const t={...this.outputNodes,...e.outputNodes},r={...this.blendModes,...e.blendModes},s=$b(t);return s.blendings=r,s}setup(e){const t=this.outputNodes,r=[],s=e.renderer.getRenderTarget().textures;for(const i in t){const n=Gb(s,i);if(-1===n)continue;const a=e.getOutputType(n);r[n]=t[i].convert(a)}return this.members=r,super.setup(e)}}const $b=un(zb);class Wb extends fi{static get type(){return"BitcastNode"}constructor(e,t,r=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=r,this.isBitcastNode=!0}generateNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),r=e.getTypeLength(t);return e.getTypeFromLength(r,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let r="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);r=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else r=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,r)}( ${this.valueNode.build(e,r)} )`}}const Hb=dn(Wb).setParameterLength(2),jb=e=>new Wb(e,"uint","float"),qb={};class Xb extends uo{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,r){"int"===r?t.assign(Hb(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return vn;case"int":return _n;case"uvec2":return Rn;case"uvec3":return Mn;case"uvec4":return Pn;case"ivec2":return En;case"ivec3":return Cn;case"ivec4":return Fn}}_createTrailingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return gn(([e])=>{const s=vn(0);this._resolveElementType(e,s,t);const i=Tn(s.bitAnd(Ho(s))),n=jb(i).shiftRight(23).sub(127);return r(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const r=this._returnDataNode(t);return gn(([e])=>{yn(e.equal(vn(0)),()=>vn(32));const s=vn(0),i=vn(0);return this._resolveElementType(e,s,t),yn(s.shiftRight(16).equal(0),()=>{i.addAssign(16),s.shiftLeftAssign(16)}),yn(s.shiftRight(24).equal(0),()=>{i.addAssign(8),s.shiftLeftAssign(8)}),yn(s.shiftRight(28).equal(0),()=>{i.addAssign(4),s.shiftLeftAssign(4)}),yn(s.shiftRight(30).equal(0),()=>{i.addAssign(2),s.shiftLeftAssign(2)}),yn(s.shiftRight(31).equal(0),()=>{i.addAssign(1)}),r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const r=this._returnDataNode(t);return gn(([e])=>{const s=vn(0);this._resolveElementType(e,s,t),s.assign(s.sub(s.shiftRight(vn(1)).bitAnd(vn(1431655765)))),s.assign(s.bitAnd(vn(858993459)).add(s.shiftRight(vn(2)).bitAnd(vn(858993459))));const i=s.add(s.shiftRight(vn(4))).bitAnd(vn(252645135)).mul(vn(16843009)).shiftRight(vn(24));return r(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,r,s){const i=this._returnDataNode(t);return gn(([e])=>{if(1===r)return i(s(e));{const t=i(0),n=["x","y","z","w"];for(let i=0;i<r;i++){const r=n[i];t[r].assign(s(e[r]))}return t}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}setup(e){const{method:t,aNode:r}=this,{renderer:s}=e;if(s.backend.isWebGPUBackend)return super.setup(e);const i=this.getInputType(e),n=e.getElementType(i),a=e.getTypeLength(i),o=`${t}_base_${n}`,u=`${t}_${i}`;let l=qb[o];if(void 0===l){switch(t){case Xb.COUNT_LEADING_ZEROS:l=this._createLeadingZerosBaseLayout(o,n);break;case Xb.COUNT_TRAILING_ZEROS:l=this._createTrailingZerosBaseLayout(o,n);break;case Xb.COUNT_ONE_BITS:l=this._createOneBitsBaseLayout(o,n)}qb[o]=l}let d=qb[u];void 0===d&&(d=this._createMainLayout(u,i,a,l),qb[u]=d);return gn(()=>d(r))()}}Xb.COUNT_TRAILING_ZEROS="countTrailingZeros",Xb.COUNT_LEADING_ZEROS="countLeadingZeros",Xb.COUNT_ONE_BITS="countOneBits";const Yb=dn(Xb,Xb.COUNT_TRAILING_ZEROS).setParameterLength(1),Qb=dn(Xb,Xb.COUNT_LEADING_ZEROS).setParameterLength(1),Kb=dn(Xb,Xb.COUNT_ONE_BITS).setParameterLength(1),Zb=gn(([e])=>{const t=e.toUint().mul(747796405).add(2891336453),r=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return r.shiftRight(22).bitXor(r).toFloat().mul(1/2**32)}),Jb=(e,t)=>du(Va(4,e.mul(Ia(1,e))),t);class ex extends fi{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}generateNodeType(){return"uint"}generate(e){const t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}}const tx=dn(ex,"snorm").setParameterLength(1),rx=dn(ex,"unorm").setParameterLength(1),sx=dn(ex,"float16").setParameterLength(1);class ix extends fi{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}generateNodeType(){return"vec2"}generate(e){const t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}}const nx=dn(ix,"snorm").setParameterLength(1),ax=dn(ix,"unorm").setParameterLength(1),ox=dn(ix,"float16").setParameterLength(1),ux=gn(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),lx=gn(([e])=>An(ux(e.z.add(ux(e.y.mul(1)))),ux(e.z.add(ux(e.x.mul(1)))),ux(e.y.add(ux(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),dx=gn(([e,t,r])=>{const s=An(e).toVar(),i=Tn(1.4).toVar(),n=Tn(0).toVar(),a=An(s).toVar();return Zp({start:Tn(0),end:Tn(3),type:"float",condition:"<="},()=>{const e=An(lx(a.mul(2))).toVar();s.addAssign(e.add(r.mul(Tn(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=Tn(ux(s.z.add(ux(s.x.add(ux(s.y)))))).toVar();n.addAssign(o.div(i)),a.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class cx extends pi{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}generateNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let r=this._candidateFn;if(null===r){let s=null,i=-1;for(const r of this.functionNodes){const n=r.shaderNode.layout;if(null===n)throw new Error("THREE.FunctionOverloadingNode: FunctionNode must be a layout.");const a=n.inputs;if(t.length===a.length){let n=0;for(let r=0;r<t.length;r++){const s=t[r],i=a[r];s.getNodeType(e)===i.type&&n++}n>i&&(s=r,i=n)}}this._candidateFn=r=s}return r}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const hx=un(cx),px=e=>(...t)=>hx(e,...t),gx=Aa(0).setGroup(Ea).onRenderUpdate(e=>e.time),mx=Aa(0).setGroup(Ea).onRenderUpdate(e=>e.deltaTime),fx=Aa(0,"uint").setGroup(Ea).onRenderUpdate(e=>e.frameId);const yx=gn(([e,t,r=Sn(.5)])=>wy(e.sub(r),t).add(r)),bx=gn(([e,t,r=Sn(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))}),xx=gn(({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=sc.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=sc;const i=zd.mul(s);return en(t)&&(i[0][0]=sc[0].length(),i[0][1]=0,i[0][2]=0),en(r)&&(i[1][0]=0,i[1][1]=sc[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,kd.mul(i).mul(fc)}),Tx=gn(([e=null])=>{const t=Ag();return Ag(bg(e)).sub(t).lessThan(0).select(md,e)}),_x=gn(([e,t=ql(),r=Tn(0)])=>{const s=e.x,i=e.y,n=r.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=e.reciprocal(),l=Sn(a,o);return t.add(l).mul(u)}),vx=gn(([e,t=null,r=null,s=Tn(1),i=fc,n=wc])=>{let a=n.abs().normalize();a=a.div(a.dot(An(1)));const o=i.yz.mul(s),u=i.zx.mul(s),l=i.xy.mul(s),d=e.value,c=null!==t?t.value:d,h=null!==r?r.value:d,p=rd(d,o).mul(a.x),g=rd(c,u).mul(a.y),m=rd(h,l).mul(a.z);return Oa(p,g,m)}),Nx=new ut,Sx=new r,Ex=new r,Rx=new r,wx=new a,Ax=new r(0,0,-1),Cx=new s,Mx=new r,Bx=new r,Lx=new s,Fx=new t,Px=new ne,Ux=md.flipX();Px.depthTexture=new Z(1,1);let Dx=!1;class Ox extends ed{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||Px.texture,Ux),this._reflectorBaseNode=e.reflector||new Ix(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=new Ox({defaultTexture:Px.depthTexture,reflector:this._reflectorBaseNode})}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class Ix extends pi{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new at,resolutionScale:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1,samples:o=0}=t;this.textureNode=e,this.target=r,this.resolutionScale=s,void 0!==t.resolution&&(v('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=i,this.bounces=n,this.depth=a,this.samples=o,this.updateBeforeType=n?ii.RENDER:ii.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolutionScale;t.getDrawingBufferSize(Fx),e.setSize(Math.round(Fx.width*r),Math.round(Fx.height*r))}setup(e){return this._updateResolution(Px,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new ne(0,0,{type:Te,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=ot,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new Z),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&Dx)return!1;Dx=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(Fx),this._updateResolution(o,s),Ex.setFromMatrixPosition(n.matrixWorld),Rx.setFromMatrixPosition(r.matrixWorld),wx.extractRotation(n.matrixWorld),Sx.set(0,0,1),Sx.applyMatrix4(wx),Mx.subVectors(Ex,Rx);let u=!1;if(!0===Mx.dot(Sx)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(Dx=!1);u=!0}Mx.reflect(Sx).negate(),Mx.add(Ex),wx.extractRotation(r.matrixWorld),Ax.set(0,0,-1),Ax.applyMatrix4(wx),Ax.add(Rx),Bx.subVectors(Ex,Ax),Bx.reflect(Sx).negate(),Bx.add(Ex),a.coordinateSystem=r.coordinateSystem,a.position.copy(Mx),a.up.set(0,1,0),a.up.applyMatrix4(wx),a.up.reflect(Sx),a.lookAt(Bx),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),Nx.setFromNormalAndCoplanarPoint(Sx,Ex),Nx.applyMatrix4(a.matrixWorldInverse),Cx.set(Nx.normal.x,Nx.normal.y,Nx.normal.z,Nx.constant);const l=a.projectionMatrix;Lx.x=(Math.sign(Cx.x)+l.elements[8])/l.elements[0],Lx.y=(Math.sign(Cx.y)+l.elements[9])/l.elements[5],Lx.z=-1,Lx.w=(1+l.elements[10])/l.elements[14],Cx.multiplyScalar(1/Cx.dot(Lx));l.elements[2]=Cx.x,l.elements[6]=Cx.y,l.elements[10]=s.coordinateSystem===h?Cx.z-0:Cx.z+1-0,l.elements[14]=Cx.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const d=s.getRenderTarget(),c=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0;const g=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),t.name=g,s.setMRT(c),s.setRenderTarget(d),s.autoClear=p,i.visible=!0,Dx=!1,this.forceUpdate=!1}get resolution(){return v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){v('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const Vx=new Ne(-1,1,1,-1,0,1);class kx extends ve{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new lt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new lt(t,2))}}const Gx=new kx;class zx extends oe{constructor(e=null){super(Gx,e),this.camera=Vx,this.isQuadMesh=!0}async renderAsync(e){v('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,Vx)}render(e){e.render(this,Vx)}}const $x=new t;class Wx extends ed{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:Te}){const i=new ne(t,r,s);super(i.texture,ql()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=r,this.renderTarget=i,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._resolutionScale=1,this._rttNode=null,this._quadMesh=new zx(new Dg),this.updateBeforeType=ii.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){const r=Math.floor(e*this._resolutionScale),s=Math.floor(t*this._resolutionScale);this.renderTarget.setSize(r,s),this.textureNeedsUpdate=!0}setResolutionScale(e){return this._resolutionScale=e,!1===this.autoResize&&this.setSize(this.width,this.height),this}getResolutionScale(){return this._resolutionScale}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;this.textureNeedsUpdate=!1;const t=e.getRenderTarget();if(!0===this.autoResize){const t=e.getDrawingBufferSize($x),r=Math.floor(t.width*this._resolutionScale),s=Math.floor(t.height*this._resolutionScale);r===this.renderTarget.width&&s===this.renderTarget.height||(this.renderTarget.setSize(r,s),this.textureNeedsUpdate=!0)}let r="RTT";this.node.name&&(r=this.node.name+" [ "+r+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=r,e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(t)}clone(){const e=new ed(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const Hx=(e,...t)=>new Wx(sn(e),...t),jx=gn(([e,t,r],s)=>{let i;s.renderer.coordinateSystem===h?(e=Sn(e.x,e.y.oneMinus()).mul(2).sub(1),i=Ln(An(e,t),1)):i=Ln(An(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=Ln(r.mul(i));return n.xyz.div(n.w)}),qx=gn(([e,t])=>{const r=t.mul(Ln(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return Sn(s.x,s.y.oneMinus())}),Xx=gn(([e,t,r])=>{const s=Yl(sd(t)),i=En(e.mul(s)).toVar(),n=sd(t,i).toVar(),a=sd(t,i.sub(En(2,0))).toVar(),o=sd(t,i.sub(En(1,0))).toVar(),u=sd(t,i.add(En(1,0))).toVar(),l=sd(t,i.add(En(2,0))).toVar(),d=sd(t,i.add(En(0,2))).toVar(),c=sd(t,i.add(En(0,1))).toVar(),h=sd(t,i.sub(En(0,1))).toVar(),p=sd(t,i.sub(En(0,2))).toVar(),g=zo(Ia(Tn(2).mul(o).sub(a),n)).toVar(),m=zo(Ia(Tn(2).mul(u).sub(l),n)).toVar(),f=zo(Ia(Tn(2).mul(c).sub(d),n)).toVar(),y=zo(Ia(Tn(2).mul(h).sub(p),n)).toVar(),b=jx(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(jx(e.sub(Sn(Tn(1).div(s.x),0)),o,r)),b.negate().add(jx(e.add(Sn(Tn(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(jx(e.add(Sn(0,Tn(1).div(s.y))),c,r)),b.negate().add(jx(e.sub(Sn(0,Tn(1).div(s.y))),h,r)));return Ao(lu(x,T))}),Yx=gn(([e])=>Co(Tn(52.9829189).mul(Co(uu(e,Sn(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),Qx=gn(([e,t,r])=>{const s=Tn(2.399963229728653),i=So(Tn(e).add(.5).div(Tn(t))),n=Tn(e).mul(s).add(r);return Sn(Lo(n),Mo(n)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class Kx extends pi{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(ql())}sample(e){return this.callback(e)}}class Zx extends j{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class Jx extends Ae{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class eT extends pi{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const tT=ln(eT),rT=new a,sT=Aa(0).setGroup(Ea).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),iT=Aa(1).setGroup(Ea).onRenderUpdate(({scene:e})=>e.backgroundIntensity),nT=Aa(new a).setGroup(Ea).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&t.mapping!==dt||e.backgroundNode&&e.backgroundNode.isNode?rT.makeRotationFromEuler(e.backgroundRotation).transpose():rT.identity(),rT});class aT extends ed{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=ai.WRITE_ONLY}getInputType(){return"storageTexture"}getTransformedUV(e){return e}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){return null!==this.storeNode?(this.generateStore(e),""):super.generate(e,t)}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;return e.generateStorageTextureLoad(l,t,r,s,n,u)}toReadWrite(){return this.setAccess(ai.READ_WRITE)}toReadOnly(){return this.setAccess(ai.READ_ONLY)}toWriteOnly(){return this.setAccess(ai.WRITE_ONLY)}store(e,t){const r=this.clone();return r.referenceNode=this.getBase(),r.uvNode=e,r.storeNode=t,null!==t&&r.toStack(),r}generateStore(e){const t=e.getNodeProperties(this),{uvNode:r,storeNode:s,depthNode:i}=t,n=super.generate(e,"property"),a=r.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(this.value,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e.access=this.access,e}}const oT=un(aT).setParameterLength(1,3);class uT extends aT{static get type(){return"StorageTexture3DNode"}constructor(e,t,r=null){super(e,t,r),this.isStorageTexture3DNode=!0}getDefaultUV(){return An(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}}const lT=un(uT).setParameterLength(1,3),dT=gn(({texture:e,uv:t})=>{const r=1e-4,s=An().toVar();return yn(t.x.lessThan(r),()=>{s.assign(An(1,0,0))}).ElseIf(t.y.lessThan(r),()=>{s.assign(An(0,1,0))}).ElseIf(t.z.lessThan(r),()=>{s.assign(An(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{s.assign(An(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{s.assign(An(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{s.assign(An(0,0,-1))}).Else(()=>{const r=.01,i=e.sample(t.add(An(-.01,0,0))).r.sub(e.sample(t.add(An(r,0,0))).r),n=e.sample(t.add(An(0,-.01,0))).r.sub(e.sample(t.add(An(0,r,0))).r),a=e.sample(t.add(An(0,0,-.01))).r.sub(e.sample(t.add(An(0,0,r))).r);s.assign(An(i,n,a))}),s.normalize()});class cT extends ed{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return An(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return dT({texture:this,uv:e})}}const hT=un(cT).setParameterLength(1,3);class pT extends Zc{static get type(){return"UserDataNode"}constructor(e,t,r=null){super(e,t,r),this.userData=r}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const gT=new WeakMap;class mT extends fi{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=ii.OBJECT,this.updateAfterType=ii.OBJECT,this.previousModelWorldMatrix=Aa(new a),this.previousProjectionMatrix=Aa(new a).setGroup(Ea),this.previousCameraViewMatrix=Aa(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=yT(r);this.previousModelWorldMatrix.value.copy(s);const i=fT(t);i.frameId!==e&&(i.frameId=e,void 0===i.previousProjectionMatrix?(i.previousProjectionMatrix=new a,i.previousCameraViewMatrix=new a,i.currentProjectionMatrix=new a,i.currentCameraViewMatrix=new a,i.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(i.previousProjectionMatrix.copy(i.currentProjectionMatrix),i.previousCameraViewMatrix.copy(i.currentCameraViewMatrix)),i.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(i.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(i.previousCameraViewMatrix))}updateAfter({object:e}){yT(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?kd:Aa(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(dc).mul(fc),s=this.previousProjectionMatrix.mul(t).mul(yc),i=r.xy.div(r.w),n=s.xy.div(s.w);return Ia(i,n)}}function fT(e){let t=gT.get(e);return void 0===t&&(t={},gT.set(e,t)),t}function yT(e,t=0){const r=fT(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const bT=ln(mT),xT=gn(([e,t])=>ru(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),TT=gn(([e,t])=>ru(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),_T=gn(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),vT=gn(([e,t])=>xu(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),iu(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),NT=gn(([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return Ln(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(r),r)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),ST=gn(([e])=>AT(e.rgb)),ET=gn(([e,t=Tn(1)])=>t.mix(AT(e.rgb),e.rgb).max(0)),RT=gn(([e,t=Tn(0)])=>{const r=Oa(e.r,e.g,e.b).div(3),s=e.r.max(e.g.max(e.b)),i=s.sub(r).mul(t).mul(-3);return xu(e.rgb,s,i).max(0)}),wT=gn(([e,t=Tn(1)])=>{const r=An(.57735,.57735,.57735),s=t.cos();return An(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(uu(r,e.rgb).mul(s.oneMinus()))))).max(0)}),AT=(e,t=An(p.getLuminanceCoefficients(new r)))=>uu(e,t),CT=gn(([e,t=An(1),s=An(0),i=An(1),n=Tn(1),a=An(p.getLuminanceCoefficients(new r,Ee))])=>{const o=e.rgb.dot(An(a)),u=su(e.rgb.mul(t).add(s),0),l=u.pow(i);return yn(u.r.greaterThan(0),()=>{u.r.assign(l.r)}),yn(u.g.greaterThan(0),()=>{u.g.assign(l.g)}),yn(u.b.greaterThan(0),()=>{u.b.assign(l.b)}),u.assign(o.add(u.sub(o).mul(n)).max(0)),Ln(u.rgb,e.a)}),MT=gn(([e,t])=>e.mul(t).floor().div(t));let BT=null;class LT extends cg{static get type(){return"ViewportSharedTextureNode"}constructor(e=md,t=null){null===BT&&(BT=new Q),super(e,t,BT)}getTextureForReference(){return BT}updateReference(){return this}}const FT=un(LT).setParameterLength(0,2),PT=new t;class UT extends ed{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class DT extends UT{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}}class OT extends fi{static get type(){return"PassNode"}constructor(e,t,r,s={}){super("vec4"),this.scope=e,this.scene=t,this.camera=r,this.options=s,this._width=1,this._height=1;const i=new ne(this._width,this._height,{type:Te,...s});i.texture.name="output";let n=null;this.scope!==OT.DEPTH&&!1===s.depthBuffer||(n=new Z,n.isRenderTargetTexture=!0,n.name="depth",i.depthTexture=n),this.renderTarget=i,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:i.texture},null!==n&&(this._textures.depth=n),this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Aa(0),this._cameraFar=Aa(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=ii.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return d("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return d("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){if("depth"===e)throw new Error("THREE.PassNode: Depth texture is not available for this pass.");t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const r=this._textures[e],s=this.renderTarget.textures.indexOf(r);this.renderTarget.textures[s]=t,this._textures[e]=t,this._previousTextures[e]=r,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new DT(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new DT(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar;this._viewZNodes[e]=t=Sg(this.getTextureNode(e),r,s)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=Tg(i,r,s)}return t}async compileAsync(e){const t=e.getRenderTarget(),r=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(r)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),!0===e.reversedDepthBuffer&&null!==this.renderTarget.depthTexture&&(this.renderTarget.depthTexture.type=Y),this.scope===OT.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:r}=this;let s;const i=t.getOutputRenderTarget();i&&!0===i.isXRRenderTarget?(s=t.xr.getCamera(),t.xr.updateCamera(s),PT.set(i.width,i.height)):(s=this.camera,t.getDrawingBufferSize(PT)),this.setSize(PT.width,PT.height);const n=t.getRenderTarget(),a=t.getMRT(),o=t.autoClear,u=t.transparent,l=t.opaque,d=s.layers.mask,c=t.contextNode,h=r.overrideMaterial;this._cameraNear.value=s.near,this._cameraFar.value=s.far,null!==this._layers&&(s.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(r.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Pu({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const p=r.name;r.name=this.name?this.name:r.name,t.render(r,s),r.name=p,r.overrideMaterial=h,t.setRenderTarget(n),t.setMRT(a),t.autoClear=o,t.transparent=u,t.opaque=l,t.contextNode=c,s.layers.mask=d}setSize(e,t){this._width=e,this._height=t;const r=Math.floor(this._width*this._resolutionScale),s=Math.floor(this._height*this._resolutionScale);this.renderTarget.setSize(r,s),null!==this._scissor?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._resolutionScale).floor()}setScissor(e,t,r,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new s),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,r,i))}setViewport(e,t,r,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new s),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,r,i))}dispose(){this.renderTarget.dispose()}}OT.COLOR="color",OT.DEPTH="depth";class IT extends OT{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(OT.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,r=t.getRenderObjectFunction();t.setRenderObjectFunction((e,r,s,i,n,a,o,u)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const l=this._getOutlineMaterial(n);t.renderObject(e,r,s,i,l,a,o,u)}t.renderObject(e,r,s,i,n,a,o,u)}),super.updateBefore(e),t.setRenderObjectFunction(r)}_createMaterial(){const e=new Dg;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=F;const t=wc.negate(),r=kd.mul(dc),s=Tn(1),i=r.mul(Ln(fc,1)),n=r.mul(Ln(fc.add(t),1)),a=Ao(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=Ln(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const VT=gn(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),kT=gn(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp()).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),GT=gn(([e,t])=>{const r=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),s=e.mul(e.mul(6.2).add(1.7)).add(.06);return r.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),zT=gn(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),r=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(r)}),$T=gn(([e,t])=>{const r=On(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=On(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=zT(e),(e=s.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),WT=On(An(1.6605,-.1246,-.0182),An(-.5876,1.1329,-.1006),An(-.0728,-.0083,1.1187)),HT=On(An(.6274,.0691,.0164),An(.3293,.9195,.088),An(.0433,.0113,.8956)),jT=gn(([e])=>{const t=An(e).toVar(),r=An(t.mul(t)).toVar(),s=An(r.mul(r)).toVar();return Tn(15.5).mul(s.mul(r)).sub(Va(40.14,s.mul(t))).add(Va(31.96,s).sub(Va(6.868,r.mul(t))).add(Va(.4298,r).add(Va(.1191,t).sub(.00232))))}),qT=gn(([e,t])=>{const r=An(e).toVar(),s=On(An(.856627153315983,.137318972929847,.11189821299995),An(.0951212405381588,.761241990602591,.0767994186031903),An(.0482516061458583,.101439036467562,.811302368396859)),i=On(An(1.1271005818144368,-.1413297634984383,-.14132976349843826),An(-.11060664309660323,1.157823702216272,-.11060664309660294),An(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Tn(-12.47393),a=Tn(4.026069);return r.mulAssign(t),r.assign(HT.mul(r)),r.assign(s.mul(r)),r.assign(su(r,1e-10)),r.assign(No(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(Tu(r,0,1)),r.assign(jT(r)),r.assign(i.mul(r)),r.assign(du(su(An(0),r),An(2.2))),r.assign(WT.mul(r)),r.assign(Tu(r,0,1)),r}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),XT=gn(([e,t])=>{const r=Tn(.76),s=Tn(.15);e=e.mul(t);const i=ru(e.r,ru(e.g,e.b)),n=Lu(i.lessThan(.08),i.sub(Va(6.25,i.mul(i))),.04);e.subAssign(n);const a=su(e.r,su(e.g,e.b));yn(a.lessThan(r),()=>e);const o=Ia(1,r),u=Ia(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=Ia(1,ka(1,s.mul(a.sub(u)).add(1)));return xu(e,An(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class YT extends pi{static get type(){return"CodeNode"}constructor(e="",t=[],r=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=r}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const r of t)r.build(e);const r=e.getCodeFromNode(this,this.getNodeType(e));return r.code=this.code,r.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const QT=un(YT).setParameterLength(1,3);class KT extends YT{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let r=t.nodeFunction;return void 0===r&&(r=e.parser.parseFunction(this.code),t.nodeFunction=r),r}generate(e,t){super.generate(e);const r=this.getNodeFunction(e),s=r.name,i=r.type,n=e.getCodeFromNode(this,i);""!==s&&(n.name=s);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}const ZT=(e,t=[],r="")=>{const s=new KT(e,t,r);return cn((...e)=>s.call(...e),s)};function JT(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||Tc.z).negate()}const e_=gn(([e,t],r)=>{const s=JT(r);return Nu(e,t,s)}),t_=gn(([e],t)=>{const r=JT(t);return e.mul(e,r,r).negate().exp().oneMinus()}),r_=gn(([e,t],r)=>{const s=JT(r),i=t.sub(bc.y).max(0).toConst().mul(s).toConst();return e.mul(e,i,i).negate().exp().oneMinus()}),s_=gn(([e,t])=>Ln(t.toFloat().mix(da.rgb,e.toVec3()),da.a));let i_=null,n_=null;class a_ extends pi{static get type(){return"RangeNode"}constructor(e=Tn(),t=Tn()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),r=this.getConstNode(this.maxNode),s=e.getTypeLength(Ks(t.value)),i=e.getTypeLength(Ks(r.value));return s>i?s:i}generateNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(e=>{!0===e.isConstNode&&(t=e)}),null===t)throw new Zl('THREE.TSL: No "ConstNode" found in node graph.',this.stackTrace);return t}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),a=i.value,o=n.value,u=e.getTypeLength(Ks(a)),d=e.getTypeLength(Ks(o));i_=i_||new s,n_=n_||new s,i_.setScalar(0),n_.setScalar(0),1===u?i_.setScalar(a):a.isColor?i_.set(a.r,a.g,a.b,1):i_.set(a.x,a.y,a.z||0,a.w||0),1===d?n_.setScalar(o):o.isColor?n_.set(o.r,o.g,o.b,1):n_.set(o.x,o.y,o.z||0,o.w||0);const c=4,h=c*t.count,p=new Float32Array(h);for(let e=0;e<h;e++){const t=e%c,r=i_.getComponent(t),s=n_.getComponent(t);p[e]=l.lerp(r,s,Math.random())}const g=this.getNodeType(e);if(4*t.count*4<=e.getUniformBufferLimit())r=nd(p,"vec4",t.count).element(bl).convert(g);else{const t=new j(p,4);e.geometry.setAttribute("__range"+this.id,t),r=gl(t).convert(g)}}else r=Tn(0);return r}}const o_=un(a_).setParameterLength(2);class u_ extends pi{static get type(){return"ComputeBuiltinNode"}constructor(e,t){super(t),this._builtinName=e}getHash(e){return this.getBuiltinName(e)}generateNodeType(){return this.nodeType}setBuiltinName(e){return this._builtinName=e,this}getBuiltinName(){return this._builtinName}hasBuiltin(e){return e.hasBuiltin(this._builtinName)}generate(e,t){const r=this.getBuiltinName(e),s=this.getNodeType(e);return"compute"===e.shaderStage?e.format(r,s,t):(d(`ComputeBuiltinNode: Compute built-in value ${r} can not be accessed in the ${e.shaderStage} stage`),e.generateConst(s))}serialize(e){super.serialize(e),e.global=this.global,e._builtinName=this._builtinName}deserialize(e){super.deserialize(e),this.global=e.global,this._builtinName=e._builtinName}}const l_=(e,t)=>new u_(e,t),d_=l_("numWorkgroups","uvec3"),c_=l_("workgroupId","uvec3"),h_=l_("globalId","uvec3"),p_=l_("localId","uvec3"),g_=l_("subgroupSize","uint");class m_ extends pi{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}}const f_=un(m_);class y_ extends gi{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let r;const s=e.isContextAssign();if(r=super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}class b_ extends pi{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return d('TSL: "label()" has been deprecated. Use "setName()" instead.',new Vs),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new y_(this,e)}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class x_ extends pi{static get type(){return"AtomicFunctionNode"}constructor(e,t,r){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=r,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),r=t.parents,s=this.method,i=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,u=[];u.push(`&${a.build(e,n)}`),null!==o&&u.push(o.build(e,n));const l=`${e.getMethod(s,i)}( ${u.join(", ")} )`;if(!(!!r&&(1===r.length&&!0===r[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Pl(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}x_.ATOMIC_LOAD="atomicLoad",x_.ATOMIC_STORE="atomicStore",x_.ATOMIC_ADD="atomicAdd",x_.ATOMIC_SUB="atomicSub",x_.ATOMIC_MAX="atomicMax",x_.ATOMIC_MIN="atomicMin",x_.ATOMIC_AND="atomicAnd",x_.ATOMIC_OR="atomicOr",x_.ATOMIC_XOR="atomicXor";const T_=un(x_),__=(e,t,r)=>T_(e,t,r).toStack();class v_ extends fi{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=r}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,r=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(r)?0:e.getTypeLength(r))?t:r}generateNodeType(e){const t=this.method;return t===v_.SUBGROUP_ELECT?"bool":t===v_.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const r=this.method,s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(r===v_.SUBGROUP_BROADCAST||r===v_.SUBGROUP_SHUFFLE||r===v_.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,s),a.build(e,"float"===t?"int":s))}else r===v_.SUBGROUP_SHUFFLE_XOR||r===v_.SUBGROUP_SHUFFLE_DOWN||r===v_.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,s),a.build(e,"uint")):(null!==n&&o.push(n.build(e,i)),null!==a&&o.push(a.build(e,i)));const u=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(r,s)}${u}`,s,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}v_.SUBGROUP_ELECT="subgroupElect",v_.SUBGROUP_BALLOT="subgroupBallot",v_.SUBGROUP_ADD="subgroupAdd",v_.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",v_.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",v_.SUBGROUP_MUL="subgroupMul",v_.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",v_.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",v_.SUBGROUP_AND="subgroupAnd",v_.SUBGROUP_OR="subgroupOr",v_.SUBGROUP_XOR="subgroupXor",v_.SUBGROUP_MIN="subgroupMin",v_.SUBGROUP_MAX="subgroupMax",v_.SUBGROUP_ALL="subgroupAll",v_.SUBGROUP_ANY="subgroupAny",v_.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",v_.QUAD_SWAP_X="quadSwapX",v_.QUAD_SWAP_Y="quadSwapY",v_.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",v_.SUBGROUP_BROADCAST="subgroupBroadcast",v_.SUBGROUP_SHUFFLE="subgroupShuffle",v_.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",v_.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",v_.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",v_.QUAD_BROADCAST="quadBroadcast";const N_=dn(v_,v_.SUBGROUP_ELECT).setParameterLength(0),S_=dn(v_,v_.SUBGROUP_BALLOT).setParameterLength(1),E_=dn(v_,v_.SUBGROUP_ADD).setParameterLength(1),R_=dn(v_,v_.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),w_=dn(v_,v_.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),A_=dn(v_,v_.SUBGROUP_MUL).setParameterLength(1),C_=dn(v_,v_.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),M_=dn(v_,v_.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),B_=dn(v_,v_.SUBGROUP_AND).setParameterLength(1),L_=dn(v_,v_.SUBGROUP_OR).setParameterLength(1),F_=dn(v_,v_.SUBGROUP_XOR).setParameterLength(1),P_=dn(v_,v_.SUBGROUP_MIN).setParameterLength(1),U_=dn(v_,v_.SUBGROUP_MAX).setParameterLength(1),D_=dn(v_,v_.SUBGROUP_ALL).setParameterLength(0),O_=dn(v_,v_.SUBGROUP_ANY).setParameterLength(0),I_=dn(v_,v_.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),V_=dn(v_,v_.QUAD_SWAP_X).setParameterLength(1),k_=dn(v_,v_.QUAD_SWAP_Y).setParameterLength(1),G_=dn(v_,v_.QUAD_SWAP_DIAGONAL).setParameterLength(1),z_=dn(v_,v_.SUBGROUP_BROADCAST).setParameterLength(2),$_=dn(v_,v_.SUBGROUP_SHUFFLE).setParameterLength(2),W_=dn(v_,v_.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),H_=dn(v_,v_.SUBGROUP_SHUFFLE_UP).setParameterLength(2),j_=dn(v_,v_.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),q_=dn(v_,v_.QUAD_BROADCAST).setParameterLength(1);let X_;function Y_(e){X_=X_||new WeakMap;let t=X_.get(e);return void 0===t&&X_.set(e,t={}),t}function Q_(e){const t=Y_(e);return t.shadowMatrix||(t.shadowMatrix=Aa("mat4").setGroup(Ea).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function K_(e,t=bc){const r=Q_(e).mul(t);return r.xyz.div(r.w)}function Z_(e){const t=Y_(e);return t.position||(t.position=Aa(new r).setGroup(Ea).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld)))}function J_(e){const t=Y_(e);return t.targetPosition||(t.targetPosition=Aa(new r).setGroup(Ea).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld)))}function ev(e){const t=Y_(e);return t.viewPosition||(t.viewPosition=Aa(new r).setGroup(Ea).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const tv=e=>zd.transformDirection(Z_(e).sub(J_(e))),rv=zn("vec3","totalDiffuse"),sv=zn("vec3","totalSpecular"),iv=zn("vec3","outgoingLight"),nv=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},av=new WeakMap,ov=[];class uv extends pi{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=rv,this.totalSpecularNode=sv,this.outgoingLightNode=iv,this._lights=[],this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;t<e.length;t++){const r=e[t];if(ov.push(r.id),ov.push(r.castShadow?1:0),!0===r.isSpotLight){const e=null!==r.map?r.map.id:-1,t=r.colorNode?r.colorNode.getCacheKey():-1;ov.push(e,t)}}const t=zs(ov);return ov.length=0,t}getHash(e){const t=e.getDataFromNode(this);if(void 0===t.lightNodesHash){const r=this.setupLightsNode(e);t.lightNodes=r;const s=[];for(const e of r)s.push(e.getHash());t.lightNodesHash="lights-"+s.join(",")}return t.lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const r of t.nodes)r.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],r=e.getDataFromNode(this).lightNodes||null,s=(e=>e.sort((e,t)=>e.id-t.id))([...e.context.materialLightings,...this._lights]),i=e.renderer.library;for(const e of s)if(e.isNode)t.push(e);else{let s=null;if(null!==r&&(s=nv(e.id,r)),null===s){const t=i.getLightNodeClass(e.constructor);if(null===t){d(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===av.has(e)&&av.set(e,new t(e)),s=av.get(e)}t.push(s)}return t}setupDirectLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.direct({...r,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.directRectArea({...r,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const r of t)r.build(e)}getLightNodes(e){const t=e.getDataFromNode(this);return void 0===t.lightNodes&&(t.lightNodes=this.setupLightsNode(e)),t.lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let r=this.outgoingLightNode;const s=e.context,i=s.lightingModel,n=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;s.outgoingLight=r;const o=e.addStack();n.nodes=o.nodes,i.start(e);const{backdrop:u,backdropAlpha:l}=s,{directDiffuse:d,directSpecular:c,indirectDiffuse:h,indirectSpecular:p}=s.reflectedLight;let g=d.add(h);null!==u&&(g=An(null!==l?l.mix(g,u):u)),t.assign(g),a.assign(c.add(p)),r.assign(t.add(a)),i.finish(e),r=r.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,r}setLights(e){return this._lights=e,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class lv extends pi{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=ii.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){dv.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||bc)}}const dv=zn("vec3","shadowPositionWorld");function cv(t,r={}){return r.toneMapping=t.toneMapping,r.toneMappingExposure=t.toneMappingExposure,r.outputColorSpace=t.outputColorSpace,r.renderTarget=t.getRenderTarget(),r.activeCubeFace=t.getActiveCubeFace(),r.activeMipmapLevel=t.getActiveMipmapLevel(),r.renderObjectFunction=t.getRenderObjectFunction(),r.pixelRatio=t.getPixelRatio(),r.mrt=t.getMRT(),r.clearColor=t.getClearColor(r.clearColor||new e),r.clearAlpha=t.getClearAlpha(),r.autoClear=t.autoClear,r.scissorTest=t.getScissorTest(),r}function hv(e,t){return t=cv(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function pv(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}function gv(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function mv(e,t){return t=gv(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function fv(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function yv(e,t,r){return r=mv(t,r=hv(e,r))}function bv(e,t,r){pv(e,r),fv(t,r)}var xv=Object.freeze({__proto__:null,resetRendererAndSceneState:yv,resetRendererState:hv,resetSceneState:mv,restoreRendererAndSceneState:bv,restoreRendererState:pv,restoreSceneState:fv,saveRendererAndSceneState:function(e,t,r={}){return r=gv(t,r=cv(e,r))},saveRendererState:cv,saveSceneState:gv});const Tv=new WeakMap,_v=gn(({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=rd(e,t.xy).setName("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)}),vv=gn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=rd(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=Jc("mapSize","vec2",r).setGroup(Ea),a=Jc("radius","float",r).setGroup(Ea),o=Sn(1).div(n),u=a.mul(o.x),l=Yx(yd.xy).mul(6.28318530718);return Oa(i(t.xy.add(Qx(0,5,l).mul(u)),t.z),i(t.xy.add(Qx(1,5,l).mul(u)),t.z),i(t.xy.add(Qx(2,5,l).mul(u)),t.z),i(t.xy.add(Qx(3,5,l).mul(u)),t.z),i(t.xy.add(Qx(4,5,l).mul(u)),t.z)).mul(.2)}),Nv=gn(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=Jc("mapSize","vec2",r).setGroup(Ea),n=Sn(1).div(i),a=t.xy,o=Co(a.mul(i).add(.5)).toConst();a.subAssign(o.sub(.5).mul(n));const u=r=>{let i=rd(e,a).offset(r).gather();return e.isArrayTexture&&(i=i.depth(s)),i.compare(t.z)},l=u(En(-1,1)).toConst(),d=u(En(1,1)).toConst(),c=u(En(-1,-1)).toConst(),h=u(En(1,-1)).toConst();return Oa(xu(l.x,d.y,o.x).add(l.y).add(d.x).mul(o.y),xu(l.w,d.z,o.x).add(l.z).add(d.w),xu(c.x,h.y,o.x).add(c.y).add(h.x),xu(c.w,h.z,o.x).add(c.z).add(h.w).mul(o.y.oneMinus())).mul(1/9)}),Sv=gn(({depthTexture:e,shadowCoord:t,depthLayer:r},s)=>{let i=rd(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=i.x,a=su(1e-7,i.y.mul(i.y)),o=s.renderer.reversedDepthBuffer?iu(n,t.z):iu(t.z,n),u=Tn(1).toVar();return yn(o.notEqual(1),()=>{const e=t.z.sub(n);let r=a.div(a.add(e.mul(e)));r=Tu(Ia(r,.3).div(.65)),u.assign(su(o,r))}),u}),Ev=e=>{let t=Tv.get(e);return void 0===t&&(t=new Dg,t.colorNode=Ln(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=re,t.fog=!1,Tv.set(e,t)),t},Rv=e=>{const t=Tv.get(e);void 0!==t&&(t.dispose(),Tv.delete(e))},wv=new $y,Av=[],Cv=(e,t,r,s)=>{Av[0]=e,Av[1]=t;let i=wv.get(Av);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,d,c,h)=>{(!0===i.castShadow||i.receiveShadow&&r===pt)&&(s&&(Js(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,n.overrideMaterial,l),e.renderObject(i,n,a,o,u,l,d,c,h),i.onAfterShadow(e,i,a,t.camera,o,n.overrideMaterial,l))},i.shadowType=r,i.useVelocity=s,wv.set(Av,i)),Av[0]=null,Av[1]=null,i},Mv=gn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=Tn(0).toVar("meanVertical"),a=Tn(0).toVar("squareMeanVertical"),o=e.lessThanEqual(Tn(1)).select(Tn(0),Tn(2).div(e.sub(1))),u=e.lessThanEqual(Tn(1)).select(Tn(0),Tn(-1));Zp({start:_n(0),end:_n(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(Tn(e).mul(o));let d=s.sample(Oa(yd.xy,Sn(0,l).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),a.addAssign(d.mul(d))}),n.divAssign(e),a.divAssign(e);const l=So(a.sub(n.mul(n)).max(0));return Sn(n,l)}),Bv=gn(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=Tn(0).toVar("meanHorizontal"),a=Tn(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(Tn(1)).select(Tn(0),Tn(2).div(e.sub(1))),u=e.lessThanEqual(Tn(1)).select(Tn(0),Tn(-1));Zp({start:_n(0),end:_n(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(Tn(e).mul(o));let d=s.sample(Oa(yd.xy,Sn(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(Oa(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(e),a.divAssign(e);const l=So(a.sub(n.mul(n)).max(0));return Sn(n,l)}),Lv=[_v,vv,Nv,Sv];let Fv;const Pv=new zx;class Uv extends lv{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n}){const a=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1)).and(s.z.lessThanEqual(1)),o=t({depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n});return a.select(o,Tn(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=r.biasNode||Jc("bias","float",r).setGroup(Ea);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=Jc("near","float",r.camera).setGroup(Ea),s=Jc("far","float",r.camera).setGroup(Ea);n=Eg(e.negate(),t,s)}return a=An(a.x,a.y.oneMinus(),s.reversedDepthBuffer?n.sub(i):n.add(i)),a}getShadowFilterFn(e){return Lv[e]}setupRenderTarget(e,t){const r=new Z(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:A;const s=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return s.texture.name="ShadowMap",s.texture.type=e.mapType,s.depthTexture=r,{shadowMap:s,depthTexture:r}}setupShadow(e){const{renderer:t,camera:r}=e,{light:s,shadow:i}=this,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(i,e),o=t.shadowMap.type,u=t.hasCompatibility(R.TEXTURE_COMPARE);if(o!==ct&&o!==ht||!u?(n.minFilter=B,n.magFilter=B):(n.minFilter=le,n.magFilter=le),i.camera.coordinateSystem=r.coordinateSystem,i.camera.updateProjectionMatrix(),o===pt&&!0!==i.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:$,type:Te,depthBuffer:!1}));let t=rd(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=rd(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const s=Jc("blurSamples","float",i).setGroup(Ea),o=Jc("radius","float",i).setGroup(Ea),u=Jc("mapSize","vec2",i).setGroup(Ea);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Dg);l.fragmentNode=Mv({samples:s,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Dg),l.fragmentNode=Bv({samples:s,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const l=Jc("intensity","float",i).setGroup(Ea),d=Jc("normalBias","float",i).setGroup(Ea),c=Q_(s),h=Lc.mul(d);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=c.mul(dv.add(h));else{p=Aa("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(c.value,e.matrixWorld)).mul(fc).add(c.mul(Ln(h,0)))}const g=this.setupShadowCoord(e,p),m=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===m)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=o===pt&&!0!==i.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,y=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:f,shadowCoord:g,shadow:i,depthLayer:this.depthLayer});let b,x;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?b=Qc(a.texture,g.xyz):(b=rd(a.texture,g),n.isArrayTexture&&(b=b.depth(this.depthLayer)))),x=b?xu(1,y.rgb.mix(b,1),l.mul(b.a)).toVar():xu(1,y,l).toVar(),this.shadowMap=a,this.shadow.map=a;const T=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&x.toInspector(`${T} / Color`,()=>this.shadowMap.texture.isCubeTexture?Qc(this.shadowMap.texture,em()):rd(this.shadowMap.texture)),x.toInspector(`${T} / Depth`,()=>{const e=Jc("near","float",this.shadow.camera),t=Jc("far","float",this.shadow.camera);let r,s;return r=this.shadowMap.texture.isCubeTexture?Qc(this.shadowMap.depthTexture,em()).r:rd(this.shadowMap.depthTexture).r,s=this.shadow.camera.isPerspectiveCamera?Sg(r,e,t):_g(r,e,t),s=Tg(s,e,t),s.oneMinus()})}setup(e){if(!1!==e.renderer.shadowMap.enabled)return gn(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let r=this._node;return this.setupShadowPosition(e),null===r&&(this._node=r=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(r=e.material.receivedShadowNode(r)),r})()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth);const a=n.name;n.name=`Shadow Map [ ${s.name||"ID: "+s.id} ]`,i.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:r,shadow:s}=this,{renderer:i,scene:n,camera:a}=e,o=i.shadowMap.type,u=t.depthTexture.version;this._depthVersionCached=u;const l=s.camera.layers.mask;4294967294&s.camera.layers.mask||(s.camera.layers.mask=a.layers.mask);const d=i.getRenderObjectFunction(),c=i.getMRT(),h=!!c&&c.has("velocity");Fv=yv(i,n,Fv),n.overrideMaterial=Ev(r),i.setRenderObjectFunction(Cv(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===pt&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,bv(i,n,Fv)}vsmPass(e){const{shadow:t}=this,r=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,r),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,r),e.setRenderTarget(this.vsmShadowMapVertical),Pv.material=this.vsmMaterialVertical,Pv.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Pv.material=this.vsmMaterialHorizontal,Pv.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,Rv(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let r=t.needsUpdate||t.autoUpdate;r&&(this._cameraFrameId[e.camera]===e.frameId&&(r=!1),this._cameraFrameId[e.camera]=e.frameId),r&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const Dv=(e,t)=>new Uv(e,t),Ov=new e,Iv=new a,Vv=new r,kv=new r,Gv=[new r(1,0,0),new r(-1,0,0),new r(0,-1,0),new r(0,1,0),new r(0,0,1),new r(0,0,-1)],zv=[new r(0,-1,0),new r(0,-1,0),new r(0,0,-1),new r(0,0,1),new r(0,-1,0),new r(0,-1,0)],$v=[new r(1,0,0),new r(-1,0,0),new r(0,1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1)],Wv=[new r(0,-1,0),new r(0,-1,0),new r(0,0,1),new r(0,0,-1),new r(0,-1,0),new r(0,-1,0)],Hv=gn(({depthTexture:e,bd3D:t,dp:r})=>Qc(e,t).compare(r)),jv=gn(({depthTexture:e,bd3D:t,dp:r,shadow:s})=>{const i=Jc("radius","float",s).setGroup(Ea),n=Jc("mapSize","vec2",s).setGroup(Ea),a=i.div(n.x),o=zo(t),u=Ao(lu(t,o.x.greaterThan(o.z).select(An(0,1,0),An(1,0,0)))),l=lu(t,u),d=Yx(yd.xy).mul(6.28318530718),c=Qx(0,5,d),h=Qx(1,5,d),p=Qx(2,5,d),g=Qx(3,5,d),m=Qx(4,5,d);return Qc(e,t.add(u.mul(c.x).add(l.mul(c.y)).mul(a))).compare(r).add(Qc(e,t.add(u.mul(h.x).add(l.mul(h.y)).mul(a))).compare(r)).add(Qc(e,t.add(u.mul(p.x).add(l.mul(p.y)).mul(a))).compare(r)).add(Qc(e,t.add(u.mul(g.x).add(l.mul(g.y)).mul(a))).compare(r)).add(Qc(e,t.add(u.mul(m.x).add(l.mul(m.y)).mul(a))).compare(r)).mul(.2)}),qv=gn(({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s},i)=>{const n=r.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),u=Aa("float").setGroup(Ea).onRenderUpdate(()=>s.camera.near),l=Aa("float").setGroup(Ea).onRenderUpdate(()=>s.camera.far),d=Jc("bias","float",s).setGroup(Ea),c=Tn(1).toVar();return yn(o.sub(l).lessThanEqual(0).and(o.sub(u).greaterThanEqual(0)),()=>{let r;i.renderer.reversedDepthBuffer?(r=Ng(o.negate(),u,l),r.subAssign(d)):i.renderer.logarithmicDepthBuffer?(r=Eg(o.negate(),u,l),r.addAssign(d)):(r=vg(o.negate(),u,l),r.addAssign(d));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:r,shadow:s}))}),c});class Xv extends Uv{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===gt?Hv:jv}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:r,shadowCoord:s,shadow:i}){return qv({filterFn:t,depthTexture:r,shadowCoord:s,shadow:i})}setupRenderTarget(e,t){const r=new mt(e.mapSize.width);r.name="PointShadowDepthTexture",r.compareFunction=t.renderer.reversedDepthBuffer?M:A;const s=t.createCubeRenderTarget(e.mapSize.width);return s.texture.name="PointShadowMap",s.depthTexture=r,{shadowMap:s,depthTexture:r}}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.camera,o=t.matrix,u=i.coordinateSystem===h,l=u?Gv:$v,d=u?zv:Wv;r.setSize(t.mapSize.width,t.mapSize.width);const c=i.autoClear,p=i.getClearColor(Ov),g=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){i.setRenderTarget(r,e),i.clear();const u=s.distance||a.far;u!==a.far&&(a.far=u,a.updateProjectionMatrix()),Vv.setFromMatrixPosition(s.matrixWorld),a.position.copy(Vv),kv.copy(a.position),kv.add(l[e]),a.up.copy(d[e]),a.lookAt(kv),a.updateMatrixWorld(),o.makeTranslation(-Vv.x,-Vv.y,-Vv.z),Iv.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(Iv,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${s.name||"ID: "+s.id} ] - Face ${e+1}`,i.render(n,a),n.name=c}i.autoClear=c,i.setClearColor(p,g)}}const Yv=(e,t)=>new Xv(e,t);class Qv extends ng{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||Aa(this.color).setGroup(Ea),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=ii.FRAME,t&&t.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},t.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return ev(this.light).sub(e.context.positionView||Tc)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return Dv(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let r=this.shadowColorNode;if(null===r){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?sn(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(r=e.context.getShadow(this,e)),this.colorNode=r}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),r=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),r&&e.lightsNode.setupDirectRectAreaLight(e,this,r)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const Kv=gn(({lightDistance:e,cutoffDistance:t,decayExponent:r})=>{const s=e.pow(r).max(.01).reciprocal();return t.greaterThan(0).select(s.mul(e.div(t).pow4().oneMinus().clamp().pow2()),s)}),Zv=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=Kv({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class Jv extends Qv{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Aa(0).setGroup(Ea),this.decayExponentNode=Aa(2).setGroup(Ea)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return Yv(this.light)}setupDirect(e){return Zv({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const eN=gn(([e=ql()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()}),tN=gn(([e=ql()],{renderer:t,material:r})=>{const s=bu(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.currentSamples>0){const e=Tn(s.fwidth()).toVar();i=Nu(e.oneMinus(),e.add(1),s).oneMinus()}else i=Lu(s.greaterThan(1),0,1);return i}),rN=gn(([e,t,r])=>{const s=Tn(r).toVar(),i=Tn(t).toVar(),n=Nn(e).toVar();return Lu(n,i,s).uniformFlow()}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),sN=gn(([e,t])=>{const r=Nn(t).toVar(),s=Tn(e).toVar();return Lu(r,s.negate(),s).uniformFlow()}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),iN=gn(([e])=>{const t=Tn(e).toVar();return _n(Ro(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),nN=gn(([e,t])=>{const r=Tn(e).toVar();return t.assign(iN(r)),r.sub(Tn(t))}),aN=px([gn(([e,t,r,s,i,n])=>{const a=Tn(n).toVar(),o=Tn(i).toVar(),u=Tn(s).toVar(),l=Tn(r).toVar(),d=Tn(t).toVar(),c=Tn(e).toVar(),h=Tn(Ia(1,o)).toVar();return Ia(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),gn(([e,t,r,s,i,n])=>{const a=Tn(n).toVar(),o=Tn(i).toVar(),u=An(s).toVar(),l=An(r).toVar(),d=An(t).toVar(),c=An(e).toVar(),h=Tn(Ia(1,o)).toVar();return Ia(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),oN=px([gn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=Tn(d).toVar(),h=Tn(l).toVar(),p=Tn(u).toVar(),g=Tn(o).toVar(),m=Tn(a).toVar(),f=Tn(n).toVar(),y=Tn(i).toVar(),b=Tn(s).toVar(),x=Tn(r).toVar(),T=Tn(t).toVar(),_=Tn(e).toVar(),v=Tn(Ia(1,p)).toVar(),N=Tn(Ia(1,h)).toVar();return Tn(Ia(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),gn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=Tn(d).toVar(),h=Tn(l).toVar(),p=Tn(u).toVar(),g=An(o).toVar(),m=An(a).toVar(),f=An(n).toVar(),y=An(i).toVar(),b=An(s).toVar(),x=An(r).toVar(),T=An(t).toVar(),_=An(e).toVar(),v=Tn(Ia(1,p)).toVar(),N=Tn(Ia(1,h)).toVar();return Tn(Ia(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),uN=gn(([e,t,r])=>{const s=Tn(r).toVar(),i=Tn(t).toVar(),n=vn(e).toVar(),a=vn(n.bitAnd(vn(7))).toVar(),o=Tn(rN(a.lessThan(vn(4)),i,s)).toVar(),u=Tn(Va(2,rN(a.lessThan(vn(4)),s,i))).toVar();return sN(o,Nn(a.bitAnd(vn(1)))).add(sN(u,Nn(a.bitAnd(vn(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),lN=gn(([e,t,r,s])=>{const i=Tn(s).toVar(),n=Tn(r).toVar(),a=Tn(t).toVar(),o=vn(e).toVar(),u=vn(o.bitAnd(vn(15))).toVar(),l=Tn(rN(u.lessThan(vn(8)),a,n)).toVar(),d=Tn(rN(u.lessThan(vn(4)),n,rN(u.equal(vn(12)).or(u.equal(vn(14))),a,i))).toVar();return sN(l,Nn(u.bitAnd(vn(1)))).add(sN(d,Nn(u.bitAnd(vn(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),dN=px([uN,lN]),cN=gn(([e,t,r])=>{const s=Tn(r).toVar(),i=Tn(t).toVar(),n=Mn(e).toVar();return An(dN(n.x,i,s),dN(n.y,i,s),dN(n.z,i,s))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),hN=gn(([e,t,r,s])=>{const i=Tn(s).toVar(),n=Tn(r).toVar(),a=Tn(t).toVar(),o=Mn(e).toVar();return An(dN(o.x,a,n,i),dN(o.y,a,n,i),dN(o.z,a,n,i))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),pN=px([cN,hN]),gN=gn(([e])=>{const t=Tn(e).toVar();return Va(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),mN=gn(([e])=>{const t=Tn(e).toVar();return Va(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),fN=px([gN,gn(([e])=>{const t=An(e).toVar();return Va(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),yN=px([mN,gn(([e])=>{const t=An(e).toVar();return Va(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),bN=gn(([e,t])=>{const r=_n(t).toVar(),s=vn(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(_n(32).sub(r)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),xN=gn(([e,t,r])=>{e.subAssign(r),e.bitXorAssign(bN(r,_n(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(bN(e,_n(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(bN(t,_n(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(bN(r,_n(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(bN(e,_n(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(bN(t,_n(4))),t.addAssign(e)}),TN=gn(([e,t,r])=>{const s=vn(r).toVar(),i=vn(t).toVar(),n=vn(e).toVar();return s.bitXorAssign(i),s.subAssign(bN(i,_n(14))),n.bitXorAssign(s),n.subAssign(bN(s,_n(11))),i.bitXorAssign(n),i.subAssign(bN(n,_n(25))),s.bitXorAssign(i),s.subAssign(bN(i,_n(16))),n.bitXorAssign(s),n.subAssign(bN(s,_n(4))),i.bitXorAssign(n),i.subAssign(bN(n,_n(14))),s.bitXorAssign(i),s.subAssign(bN(i,_n(24))),s}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),_N=gn(([e])=>{const t=vn(e).toVar();return Tn(t).div(Tn(vn(_n(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),vN=gn(([e])=>{const t=Tn(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),NN=px([gn(([e])=>{const t=_n(e).toVar(),r=vn(vn(1)).toVar(),s=vn(vn(_n(3735928559)).add(r.shiftLeft(vn(2))).add(vn(13))).toVar();return TN(s.add(vn(t)),s,s)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),gn(([e,t])=>{const r=_n(t).toVar(),s=_n(e).toVar(),i=vn(vn(2)).toVar(),n=vn().toVar(),a=vn().toVar(),o=vn().toVar();return n.assign(a.assign(o.assign(vn(_n(3735928559)).add(i.shiftLeft(vn(2))).add(vn(13))))),n.addAssign(vn(s)),a.addAssign(vn(r)),TN(n,a,o)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),gn(([e,t,r])=>{const s=_n(r).toVar(),i=_n(t).toVar(),n=_n(e).toVar(),a=vn(vn(3)).toVar(),o=vn().toVar(),u=vn().toVar(),l=vn().toVar();return o.assign(u.assign(l.assign(vn(_n(3735928559)).add(a.shiftLeft(vn(2))).add(vn(13))))),o.addAssign(vn(n)),u.addAssign(vn(i)),l.addAssign(vn(s)),TN(o,u,l)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),gn(([e,t,r,s])=>{const i=_n(s).toVar(),n=_n(r).toVar(),a=_n(t).toVar(),o=_n(e).toVar(),u=vn(vn(4)).toVar(),l=vn().toVar(),d=vn().toVar(),c=vn().toVar();return l.assign(d.assign(c.assign(vn(_n(3735928559)).add(u.shiftLeft(vn(2))).add(vn(13))))),l.addAssign(vn(o)),d.addAssign(vn(a)),c.addAssign(vn(n)),xN(l,d,c),l.addAssign(vn(i)),TN(l,d,c)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),gn(([e,t,r,s,i])=>{const n=_n(i).toVar(),a=_n(s).toVar(),o=_n(r).toVar(),u=_n(t).toVar(),l=_n(e).toVar(),d=vn(vn(5)).toVar(),c=vn().toVar(),h=vn().toVar(),p=vn().toVar();return c.assign(h.assign(p.assign(vn(_n(3735928559)).add(d.shiftLeft(vn(2))).add(vn(13))))),c.addAssign(vn(l)),h.addAssign(vn(u)),p.addAssign(vn(o)),xN(c,h,p),c.addAssign(vn(a)),h.addAssign(vn(n)),TN(c,h,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),SN=px([gn(([e,t])=>{const r=_n(t).toVar(),s=_n(e).toVar(),i=vn(NN(s,r)).toVar(),n=Mn().toVar();return n.x.assign(i.bitAnd(_n(255))),n.y.assign(i.shiftRight(_n(8)).bitAnd(_n(255))),n.z.assign(i.shiftRight(_n(16)).bitAnd(_n(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),gn(([e,t,r])=>{const s=_n(r).toVar(),i=_n(t).toVar(),n=_n(e).toVar(),a=vn(NN(n,i,s)).toVar(),o=Mn().toVar();return o.x.assign(a.bitAnd(_n(255))),o.y.assign(a.shiftRight(_n(8)).bitAnd(_n(255))),o.z.assign(a.shiftRight(_n(16)).bitAnd(_n(255))),o}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),EN=px([gn(([e])=>{const t=Sn(e).toVar(),r=_n().toVar(),s=_n().toVar(),i=Tn(nN(t.x,r)).toVar(),n=Tn(nN(t.y,s)).toVar(),a=Tn(vN(i)).toVar(),o=Tn(vN(n)).toVar(),u=Tn(aN(dN(NN(r,s),i,n),dN(NN(r.add(_n(1)),s),i.sub(1),n),dN(NN(r,s.add(_n(1))),i,n.sub(1)),dN(NN(r.add(_n(1)),s.add(_n(1))),i.sub(1),n.sub(1)),a,o)).toVar();return fN(u)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),gn(([e])=>{const t=An(e).toVar(),r=_n().toVar(),s=_n().toVar(),i=_n().toVar(),n=Tn(nN(t.x,r)).toVar(),a=Tn(nN(t.y,s)).toVar(),o=Tn(nN(t.z,i)).toVar(),u=Tn(vN(n)).toVar(),l=Tn(vN(a)).toVar(),d=Tn(vN(o)).toVar(),c=Tn(oN(dN(NN(r,s,i),n,a,o),dN(NN(r.add(_n(1)),s,i),n.sub(1),a,o),dN(NN(r,s.add(_n(1)),i),n,a.sub(1),o),dN(NN(r.add(_n(1)),s.add(_n(1)),i),n.sub(1),a.sub(1),o),dN(NN(r,s,i.add(_n(1))),n,a,o.sub(1)),dN(NN(r.add(_n(1)),s,i.add(_n(1))),n.sub(1),a,o.sub(1)),dN(NN(r,s.add(_n(1)),i.add(_n(1))),n,a.sub(1),o.sub(1)),dN(NN(r.add(_n(1)),s.add(_n(1)),i.add(_n(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return yN(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),RN=px([gn(([e])=>{const t=Sn(e).toVar(),r=_n().toVar(),s=_n().toVar(),i=Tn(nN(t.x,r)).toVar(),n=Tn(nN(t.y,s)).toVar(),a=Tn(vN(i)).toVar(),o=Tn(vN(n)).toVar(),u=An(aN(pN(SN(r,s),i,n),pN(SN(r.add(_n(1)),s),i.sub(1),n),pN(SN(r,s.add(_n(1))),i,n.sub(1)),pN(SN(r.add(_n(1)),s.add(_n(1))),i.sub(1),n.sub(1)),a,o)).toVar();return fN(u)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),gn(([e])=>{const t=An(e).toVar(),r=_n().toVar(),s=_n().toVar(),i=_n().toVar(),n=Tn(nN(t.x,r)).toVar(),a=Tn(nN(t.y,s)).toVar(),o=Tn(nN(t.z,i)).toVar(),u=Tn(vN(n)).toVar(),l=Tn(vN(a)).toVar(),d=Tn(vN(o)).toVar(),c=An(oN(pN(SN(r,s,i),n,a,o),pN(SN(r.add(_n(1)),s,i),n.sub(1),a,o),pN(SN(r,s.add(_n(1)),i),n,a.sub(1),o),pN(SN(r.add(_n(1)),s.add(_n(1)),i),n.sub(1),a.sub(1),o),pN(SN(r,s,i.add(_n(1))),n,a,o.sub(1)),pN(SN(r.add(_n(1)),s,i.add(_n(1))),n.sub(1),a,o.sub(1)),pN(SN(r,s.add(_n(1)),i.add(_n(1))),n,a.sub(1),o.sub(1)),pN(SN(r.add(_n(1)),s.add(_n(1)),i.add(_n(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return yN(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),wN=px([gn(([e])=>{const t=Tn(e).toVar(),r=_n(iN(t)).toVar();return _N(NN(r))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),gn(([e])=>{const t=Sn(e).toVar(),r=_n(iN(t.x)).toVar(),s=_n(iN(t.y)).toVar();return _N(NN(r,s))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),gn(([e])=>{const t=An(e).toVar(),r=_n(iN(t.x)).toVar(),s=_n(iN(t.y)).toVar(),i=_n(iN(t.z)).toVar();return _N(NN(r,s,i))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),gn(([e])=>{const t=Ln(e).toVar(),r=_n(iN(t.x)).toVar(),s=_n(iN(t.y)).toVar(),i=_n(iN(t.z)).toVar(),n=_n(iN(t.w)).toVar();return _N(NN(r,s,i,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),AN=px([gn(([e])=>{const t=Tn(e).toVar(),r=_n(iN(t)).toVar();return An(_N(NN(r,_n(0))),_N(NN(r,_n(1))),_N(NN(r,_n(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),gn(([e])=>{const t=Sn(e).toVar(),r=_n(iN(t.x)).toVar(),s=_n(iN(t.y)).toVar();return An(_N(NN(r,s,_n(0))),_N(NN(r,s,_n(1))),_N(NN(r,s,_n(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),gn(([e])=>{const t=An(e).toVar(),r=_n(iN(t.x)).toVar(),s=_n(iN(t.y)).toVar(),i=_n(iN(t.z)).toVar();return An(_N(NN(r,s,i,_n(0))),_N(NN(r,s,i,_n(1))),_N(NN(r,s,i,_n(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),gn(([e])=>{const t=Ln(e).toVar(),r=_n(iN(t.x)).toVar(),s=_n(iN(t.y)).toVar(),i=_n(iN(t.z)).toVar(),n=_n(iN(t.w)).toVar();return An(_N(NN(r,s,i,n,_n(0))),_N(NN(r,s,i,n,_n(1))),_N(NN(r,s,i,n,_n(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),CN=gn(([e,t,r,s])=>{const i=Tn(s).toVar(),n=Tn(r).toVar(),a=_n(t).toVar(),o=An(e).toVar(),u=Tn(0).toVar(),l=Tn(1).toVar();return Zp(a,()=>{u.addAssign(l.mul(EN(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),MN=gn(([e,t,r,s])=>{const i=Tn(s).toVar(),n=Tn(r).toVar(),a=_n(t).toVar(),o=An(e).toVar(),u=An(0).toVar(),l=Tn(1).toVar();return Zp(a,()=>{u.addAssign(l.mul(RN(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),BN=gn(([e,t,r,s])=>{const i=Tn(s).toVar(),n=Tn(r).toVar(),a=_n(t).toVar(),o=An(e).toVar();return Sn(CN(o,a,n,i),CN(o.add(An(_n(19),_n(193),_n(17))),a,n,i))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),LN=gn(([e,t,r,s])=>{const i=Tn(s).toVar(),n=Tn(r).toVar(),a=_n(t).toVar(),o=An(e).toVar(),u=An(MN(o,a,n,i)).toVar(),l=Tn(CN(o.add(An(_n(19),_n(193),_n(17))),a,n,i)).toVar();return Ln(u,l)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),FN=px([gn(([e,t,r,s,i,n,a])=>{const o=_n(a).toVar(),u=Tn(n).toVar(),l=_n(i).toVar(),d=_n(s).toVar(),c=_n(r).toVar(),h=_n(t).toVar(),p=Sn(e).toVar(),g=An(AN(Sn(h.add(d),c.add(l)))).toVar(),m=Sn(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=Sn(Sn(Tn(h),Tn(c)).add(m)).toVar(),y=Sn(f.sub(p)).toVar();return yn(o.equal(_n(2)),()=>zo(y.x).add(zo(y.y))),yn(o.equal(_n(3)),()=>su(zo(y.x),zo(y.y))),uu(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),gn(([e,t,r,s,i,n,a,o,u])=>{const l=_n(u).toVar(),d=Tn(o).toVar(),c=_n(a).toVar(),h=_n(n).toVar(),p=_n(i).toVar(),g=_n(s).toVar(),m=_n(r).toVar(),f=_n(t).toVar(),y=An(e).toVar(),b=An(AN(An(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=An(An(Tn(f),Tn(m),Tn(g)).add(b)).toVar(),T=An(x.sub(y)).toVar();return yn(l.equal(_n(2)),()=>zo(T.x).add(zo(T.y)).add(zo(T.z))),yn(l.equal(_n(3)),()=>su(zo(T.x),zo(T.y),zo(T.z))),uu(T,T)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),PN=gn(([e,t,r])=>{const s=_n(r).toVar(),i=Tn(t).toVar(),n=Sn(e).toVar(),a=_n().toVar(),o=_n().toVar(),u=Sn(nN(n.x,a),nN(n.y,o)).toVar(),l=Tn(1e6).toVar();return Zp({start:-1,end:_n(1),name:"x",condition:"<="},({x:e})=>{Zp({start:-1,end:_n(1),name:"y",condition:"<="},({y:t})=>{const r=Tn(FN(u,e,t,a,o,i,s)).toVar();l.assign(ru(l,r))})}),yn(s.equal(_n(0)),()=>{l.assign(So(l))}),l}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),UN=gn(([e,t,r])=>{const s=_n(r).toVar(),i=Tn(t).toVar(),n=Sn(e).toVar(),a=_n().toVar(),o=_n().toVar(),u=Sn(nN(n.x,a),nN(n.y,o)).toVar(),l=Sn(1e6,1e6).toVar();return Zp({start:-1,end:_n(1),name:"x",condition:"<="},({x:e})=>{Zp({start:-1,end:_n(1),name:"y",condition:"<="},({y:t})=>{const r=Tn(FN(u,e,t,a,o,i,s)).toVar();yn(r.lessThan(l.x),()=>{l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.y.assign(r)})})}),yn(s.equal(_n(0)),()=>{l.assign(So(l))}),l}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),DN=gn(([e,t,r])=>{const s=_n(r).toVar(),i=Tn(t).toVar(),n=Sn(e).toVar(),a=_n().toVar(),o=_n().toVar(),u=Sn(nN(n.x,a),nN(n.y,o)).toVar(),l=An(1e6,1e6,1e6).toVar();return Zp({start:-1,end:_n(1),name:"x",condition:"<="},({x:e})=>{Zp({start:-1,end:_n(1),name:"y",condition:"<="},({y:t})=>{const r=Tn(FN(u,e,t,a,o,i,s)).toVar();yn(r.lessThan(l.x),()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.z.assign(l.y),l.y.assign(r)}).ElseIf(r.lessThan(l.z),()=>{l.z.assign(r)})})}),yn(s.equal(_n(0)),()=>{l.assign(So(l))}),l}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),ON=px([PN,gn(([e,t,r])=>{const s=_n(r).toVar(),i=Tn(t).toVar(),n=An(e).toVar(),a=_n().toVar(),o=_n().toVar(),u=_n().toVar(),l=An(nN(n.x,a),nN(n.y,o),nN(n.z,u)).toVar(),d=Tn(1e6).toVar();return Zp({start:-1,end:_n(1),name:"x",condition:"<="},({x:e})=>{Zp({start:-1,end:_n(1),name:"y",condition:"<="},({y:t})=>{Zp({start:-1,end:_n(1),name:"z",condition:"<="},({z:r})=>{const n=Tn(FN(l,e,t,r,a,o,u,i,s)).toVar();d.assign(ru(d,n))})})}),yn(s.equal(_n(0)),()=>{d.assign(So(d))}),d}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),IN=px([UN,gn(([e,t,r])=>{const s=_n(r).toVar(),i=Tn(t).toVar(),n=An(e).toVar(),a=_n().toVar(),o=_n().toVar(),u=_n().toVar(),l=An(nN(n.x,a),nN(n.y,o),nN(n.z,u)).toVar(),d=Sn(1e6,1e6).toVar();return Zp({start:-1,end:_n(1),name:"x",condition:"<="},({x:e})=>{Zp({start:-1,end:_n(1),name:"y",condition:"<="},({y:t})=>{Zp({start:-1,end:_n(1),name:"z",condition:"<="},({z:r})=>{const n=Tn(FN(l,e,t,r,a,o,u,i,s)).toVar();yn(n.lessThan(d.x),()=>{d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.y.assign(n)})})})}),yn(s.equal(_n(0)),()=>{d.assign(So(d))}),d}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),VN=px([DN,gn(([e,t,r])=>{const s=_n(r).toVar(),i=Tn(t).toVar(),n=An(e).toVar(),a=_n().toVar(),o=_n().toVar(),u=_n().toVar(),l=An(nN(n.x,a),nN(n.y,o),nN(n.z,u)).toVar(),d=An(1e6,1e6,1e6).toVar();return Zp({start:-1,end:_n(1),name:"x",condition:"<="},({x:e})=>{Zp({start:-1,end:_n(1),name:"y",condition:"<="},({y:t})=>{Zp({start:-1,end:_n(1),name:"z",condition:"<="},({z:r})=>{const n=Tn(FN(l,e,t,r,a,o,u,i,s)).toVar();yn(n.lessThan(d.x),()=>{d.z.assign(d.y),d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.z.assign(d.y),d.y.assign(n)}).ElseIf(n.lessThan(d.z),()=>{d.z.assign(n)})})})}),yn(s.equal(_n(0)),()=>{d.assign(So(d))}),d}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),kN=gn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=_n(e).toVar(),h=Sn(t).toVar(),p=Sn(r).toVar(),g=Sn(s).toVar(),m=Tn(i).toVar(),f=Tn(n).toVar(),y=Tn(a).toVar(),b=Nn(o).toVar(),x=_n(u).toVar(),T=Tn(l).toVar(),_=Tn(d).toVar(),v=h.mul(p).add(g),N=Tn(0).toVar();return yn(c.equal(_n(0)),()=>{N.assign(RN(v))}),yn(c.equal(_n(1)),()=>{N.assign(AN(v))}),yn(c.equal(_n(2)),()=>{N.assign(VN(v,m,_n(0)))}),yn(c.equal(_n(3)),()=>{N.assign(MN(An(v,0),x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),yn(b,()=>{N.assign(Tu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),GN=gn(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=_n(e).toVar(),h=An(t).toVar(),p=An(r).toVar(),g=An(s).toVar(),m=Tn(i).toVar(),f=Tn(n).toVar(),y=Tn(a).toVar(),b=Nn(o).toVar(),x=_n(u).toVar(),T=Tn(l).toVar(),_=Tn(d).toVar(),v=h.mul(p).add(g),N=Tn(0).toVar();return yn(c.equal(_n(0)),()=>{N.assign(RN(v))}),yn(c.equal(_n(1)),()=>{N.assign(AN(v))}),yn(c.equal(_n(2)),()=>{N.assign(VN(v,m,_n(0)))}),yn(c.equal(_n(3)),()=>{N.assign(MN(v,x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),yn(b,()=>{N.assign(Tu(N,f,y))}),N}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),zN=gn(([e])=>{const t=e.y,r=e.z,s=An().toVar();return yn(t.lessThan(1e-4),()=>{s.assign(An(r,r,r))}).Else(()=>{let i=e.x;i=i.sub(Ro(i)).mul(6).toVar();const n=_n(Ko(i)),a=i.sub(Tn(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());yn(n.equal(_n(0)),()=>{s.assign(An(r,l,o))}).ElseIf(n.equal(_n(1)),()=>{s.assign(An(u,r,o))}).ElseIf(n.equal(_n(2)),()=>{s.assign(An(o,r,l))}).ElseIf(n.equal(_n(3)),()=>{s.assign(An(o,u,r))}).ElseIf(n.equal(_n(4)),()=>{s.assign(An(l,o,r))}).Else(()=>{s.assign(An(r,o,u))})}),s}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),$N=gn(([e])=>{const t=An(e).toVar(),r=Tn(t.x).toVar(),s=Tn(t.y).toVar(),i=Tn(t.z).toVar(),n=Tn(ru(r,ru(s,i))).toVar(),a=Tn(su(r,su(s,i))).toVar(),o=Tn(a.sub(n)).toVar(),u=Tn().toVar(),l=Tn().toVar(),d=Tn().toVar();return d.assign(a),yn(a.greaterThan(0),()=>{l.assign(o.div(a))}).Else(()=>{l.assign(0)}),yn(l.lessThanEqual(0),()=>{u.assign(0)}).Else(()=>{yn(r.greaterThanEqual(a),()=>{u.assign(s.sub(i).div(o))}).ElseIf(s.greaterThanEqual(a),()=>{u.assign(Oa(2,i.sub(r).div(o)))}).Else(()=>{u.assign(Oa(4,r.sub(s).div(o)))}),u.mulAssign(1/6),yn(u.lessThan(0),()=>{u.addAssign(1)})}),An(u,l,d)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),WN=gn(([e])=>{const t=An(e).toVar(),r=Bn(Ha(t,An(.04045))).toVar(),s=An(t.div(12.92)).toVar(),i=An(du(su(t.add(An(.055)),An(0)).div(1.055),An(2.4))).toVar();return xu(s,i,r)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),HN=(e,t)=>{e=Tn(e),t=Tn(t);const r=Sn(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Nu(e.sub(r),e.add(r),t)},jN=(e,t,r,s)=>xu(e,t,r[s].clamp()),qN=(e,t,r,s,i)=>xu(e,t,HN(r,s[i])),XN=gn(([e,t,r])=>{const s=Ao(e).toVar(),i=Ia(Tn(.5).mul(t.sub(r)),bc).div(s).toVar(),n=Ia(Tn(-.5).mul(t.sub(r)),bc).div(s).toVar(),a=An().toVar();a.x=s.x.greaterThan(Tn(0)).select(i.x,n.x),a.y=s.y.greaterThan(Tn(0)).select(i.y,n.y),a.z=s.z.greaterThan(Tn(0)).select(i.z,n.z);const o=ru(a.x,a.y,a.z).toVar();return bc.add(s.mul(o)).toVar().sub(r)}),YN=gn(([e,t])=>{const r=e.x,s=e.y,i=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(s)),n=n.add(t.element(2).mul(1.023328).mul(i)),n=n.add(t.element(3).mul(1.023328).mul(r)),n=n.add(t.element(4).mul(.858086).mul(r).mul(s)),n=n.add(t.element(5).mul(.858086).mul(s).mul(i)),n=n.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(r).mul(i)),n=n.add(t.element(8).mul(.429043).mul(Va(r,r).sub(Va(s,s)))),n});var QN=Object.freeze({__proto__:null,BRDF_GGX:Cm,BRDF_Lambert:gm,BasicPointShadowFilter:Hv,BasicShadowFilter:_v,Break:Jp,Const:$u,Continue:()=>Pl("continue").toStack(),DFGLUT:Lm,D_GGX:Rm,Discard:Ul,EPSILON:lo,F_Schlick:pm,Fn:gn,HALF_PI:mo,INFINITY:co,If:yn,Loop:Zp,NodeAccess:ai,NodeShaderStage:si,NodeType:ni,NodeUpdateType:ii,OnBeforeFrameUpdate:e=>Rp(Ep.BEFORE_FRAME,e),OnBeforeMaterialUpdate:e=>Rp(Ep.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>Rp(Ep.BEFORE_OBJECT,e),OnFrameUpdate:Ap,OnMaterialUpdate:e=>Rp(Ep.MATERIAL,e),OnObjectUpdate:wp,PCFShadowFilter:vv,PCFSoftShadowFilter:Nv,PI:ho,PI2:po,PointShadowFilter:jv,Return:()=>Pl("return").toStack(),Schlick_to_F0:Um,ShaderNode:rn,Stack:bn,Switch:(...e)=>Ri.Switch(...e),TBNViewMatrix:Rh,TWO_PI:go,VSMShadowFilter:Sv,V_GGX_SmithCorrelated:Sm,Var:zu,VarIntent:Wu,abs:zo,acesFilmicToneMapping:$T,acos:Io,acosh:Vo,add:Oa,addMethodChaining:Ai,addNodeElement:function(e){d("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:qT,all:fo,alphaT:ra,ambientOcclusion:Ta,and:Xa,anisotropy:sa,anisotropyB:na,anisotropyT:ia,any:yo,append:e=>(d("TSL: append() has been renamed to Stack().",new Vs),bn(e)),array:Ma,asin:Do,asinh:Oo,assign:La,atan:ko,atanh:Go,atomicAdd:(e,t)=>__(x_.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>__(x_.ATOMIC_AND,e,t),atomicFunc:__,atomicLoad:e=>__(x_.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>__(x_.ATOMIC_MAX,e,t),atomicMin:(e,t)=>__(x_.ATOMIC_MIN,e,t),atomicOr:(e,t)=>__(x_.ATOMIC_OR,e,t),atomicStore:(e,t)=>__(x_.ATOMIC_STORE,e,t),atomicSub:(e,t)=>__(x_.ATOMIC_SUB,e,t),atomicXor:(e,t)=>__(x_.ATOMIC_XOR,e,t),attenuationColor:ba,attenuationDistance:ya,attribute:jl,attributeArray:(e,t="float")=>{let r,s;!0===t.isStructTypeNode?(r=t.getLength(),s=qs("float")):(r=Xs(t),s=qs(t));const i=new Jx(e,r,s);return Lp(i,t,e)},backgroundBlurriness:sT,backgroundIntensity:iT,backgroundRotation:nT,batch:$p,batchColor:zp,bentNormalView:Ah,billboarding:xx,bitAnd:Za,bitNot:Ja,bitOr:eo,bitXor:to,bitangentGeometry:vh,bitangentLocal:Nh,bitangentView:Sh,bitangentWorld:Eh,bitcast:Hb,blendBurn:xT,blendColor:NT,blendDodge:TT,blendOverlay:vT,blendScreen:_T,blur:Df,bool:Nn,buffer:nd,bufferAttribute:pl,builtin:dd,builtinAOContext:Iu,builtinShadowContext:Ou,bumpMap:Oh,bvec2:wn,bvec3:Bn,bvec4:Un,bypass:Ml,cache:Al,call:Pa,cameraFar:Vd,cameraIndex:Od,cameraNear:Id,cameraNormalMatrix:Wd,cameraPosition:Hd,cameraProjectionMatrix:kd,cameraProjectionMatrixInverse:Gd,cameraViewMatrix:zd,cameraViewport:jd,cameraWorldMatrix:$d,cbrt:yu,cdl:CT,ceil:wo,checker:eN,cineonToneMapping:GT,clamp:Tu,clearcoat:Yn,clearcoatNormalView:Fc,clearcoatRoughness:Qn,clipSpace:gc,code:QT,color:xn,colorSpaceToWorking:tl,colorToDirection:e=>(v('TSL: "colorToDirection()" has been renamed to "unpackRGBToNormal()".'),Mh(e)),compute:El,computeKernel:Sl,computeSkinning:Qp,context:Pu,convert:kn,convertColorSpace:(e,t,r)=>new Ju(sn(e),t,r),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():Hx(e,...t),cos:Lo,cosh:Fo,countLeadingZeros:Qb,countOneBits:Kb,countTrailingZeros:Yb,cross:lu,cubeTexture:Qc,cubeTextureBase:Yc,dFdx:qo,dFdy:Xo,dashSize:ca,debug:Gl,decrement:oo,decrementBefore:no,defaultBuildStages:ui,defaultShaderStages:oi,defined:en,degrees:xo,deltaTime:mx,densityFogFactor:t_,depth:wg,depthPass:(e,t,r)=>new OT(OT.DEPTH,e,t,r),determinant:eu,difference:ou,diffuseColor:Wn,diffuseContribution:Hn,directPointLight:Zv,directionToColor:e=>(v('TSL: "directionToColor()" has been renamed to "packNormalToRGB()".'),Ch(e)),directionToFaceDirection:e=>(v('TSL: "directionToFaceDirection()" has been renamed to "negateOnBackSide()".'),Ec(e)),dispersion:xa,disposeShadowMaterial:Rv,distance:au,div:ka,dot:uu,drawIndex:vl,dynamicBufferAttribute:(e,t=null,r=0,s=0)=>hl(e,t,r,s,x),element:Vn,emissive:jn,equal:za,equirectDirection:em,equirectUV:Jg,exp:To,exp2:_o,exponentialHeightFogFactor:r_,expression:Pl,faceDirection:Sc,faceForward:Su,faceforward:Cu,float:Tn,floatBitsToInt:e=>new Wb(e,"int","float"),floatBitsToUint:jb,floor:Ro,fog:s_,fract:Co,frameGroup:Sa,frameId:fx,frontFacing:Nc,fwidth:Zo,gain:(e,t)=>e.lessThan(.5)?Jb(e.mul(2),t).div(2):Ia(1,Jb(Va(Ia(1,e),2),t).div(2)),gapSize:ha,getConstNodeType:tn,getCurrentStack:fn,getDirection:Lf,getDistanceAttenuation:Kv,getGeometryRoughness:vm,getNormalFromDepth:Xx,getParallaxCorrectNormal:XN,getRoughness:Nm,getScreenPosition:qx,getShIrradianceAt:YN,getShadowMaterial:Ev,getShadowRenderObjectFunction:Cv,getTextureIndex:Gb,getViewPosition:jx,ggxConvolution:kf,globalId:h_,glsl:(e,t)=>QT(e,t,"glsl"),glslFn:(e,t)=>ZT(e,t,"glsl"),grayscale:ST,greaterThan:Ha,greaterThanEqual:qa,hash:Zb,highpModelNormalViewMatrix:pc,highpModelViewMatrix:hc,hue:wT,increment:ao,incrementBefore:io,inspector:Wl,instance:Ip,instanceColor:Op,instanceIndex:bl,instancedArray:(e,t="float")=>{let r,s;!0===t.isStructTypeNode?(r=t.getLength(),s=qs("float")):(r=Xs(t),s=qs(t));const i=new Zx(e,r,s);return Lp(i,t,i.count)},instancedBufferAttribute:gl,instancedDynamicBufferAttribute:ml,instancedMesh:Vp,int:_n,intBitsToFloat:e=>new Wb(e,"float","int"),interleavedGradientNoise:Yx,inverse:tu,inverseSqrt:Eo,inversesqrt:Mu,invocationLocalIndex:_l,invocationSubgroupIndex:Tl,ior:ga,iridescence:Jn,iridescenceIOR:ea,iridescenceThickness:ta,isolate:wl,ivec2:En,ivec3:Cn,ivec4:Fn,js:(e,t)=>QT(e,t,"js"),label:Vu,length:Wo,lengthSq:bu,lessThan:Wa,lessThanEqual:ja,lightPosition:Z_,lightProjectionUV:K_,lightShadowMatrix:Q_,lightTargetDirection:tv,lightTargetPosition:J_,lightViewPosition:ev,lightingContext:ug,lights:(e=[])=>(new uv).setLights(e),linearDepth:Ag,linearToneMapping:VT,localId:p_,log:vo,log2:No,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul(vo(r.div(t)));return Tn(Math.E).pow(s).mul(t).negate()},luminance:AT,mat2:Dn,mat3:On,mat4:In,matcapUV:Ny,materialAO:vp,materialAlphaTest:kh,materialAnisotropy:np,materialAnisotropyVector:Np,materialAttenuationColor:pp,materialAttenuationDistance:hp,materialClearcoat:Jh,materialClearcoatNormal:tp,materialClearcoatRoughness:ep,materialColor:Gh,materialDispersion:Tp,materialEmissive:$h,materialEnvIntensity:Gc,materialEnvRotation:zc,materialIOR:cp,materialIridescence:ap,materialIridescenceIOR:op,materialIridescenceThickness:up,materialLightMap:_p,materialLineDashOffset:bp,materialLineDashSize:mp,materialLineGapSize:fp,materialLineScale:gp,materialLineWidth:yp,materialMetalness:Kh,materialNormal:Zh,materialOpacity:Wh,materialPointSize:xp,materialReference:rh,materialReflectivity:Yh,materialRefractionRatio:kc,materialRotation:rp,materialRoughness:Qh,materialSheen:sp,materialSheenRoughness:ip,materialShininess:zh,materialSpecular:Hh,materialSpecularColor:qh,materialSpecularIntensity:jh,materialSpecularStrength:Xh,materialThickness:dp,materialTransmission:lp,max:su,maxMipLevel:Kl,mediumpModelViewMatrix:cc,metalness:Xn,min:ru,mix:xu,mixElement:Ru,mod:Ga,modelDirection:rc,modelNormalMatrix:uc,modelPosition:ic,modelRadius:oc,modelScale:nc,modelViewMatrix:dc,modelViewPosition:ac,modelViewProjection:Sp,modelWorldMatrix:sc,modelWorldMatrixInverse:lc,morphReference:ig,mrt:$b,mul:Va,mx_aastep:HN,mx_add:(e,t=Tn(0))=>Oa(e,t),mx_atan2:(e=Tn(0),t=Tn(1))=>ko(e,t),mx_cell_noise_float:(e=ql())=>wN(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>Tn(e).sub(r).mul(t).add(r),mx_divide:(e,t=Tn(1))=>ka(e,t),mx_fractal_noise_float:(e=ql(),t=3,r=2,s=.5,i=1)=>CN(e,_n(t),r,s).mul(i),mx_fractal_noise_vec2:(e=ql(),t=3,r=2,s=.5,i=1)=>BN(e,_n(t),r,s).mul(i),mx_fractal_noise_vec3:(e=ql(),t=3,r=2,s=.5,i=1)=>MN(e,_n(t),r,s).mul(i),mx_fractal_noise_vec4:(e=ql(),t=3,r=2,s=.5,i=1)=>LN(e,_n(t),r,s).mul(i),mx_frame:()=>fx,mx_heighttonormal:(e,t)=>(e=An(e),t=Tn(t),Oh(e,t)),mx_hsvtorgb:zN,mx_ifequal:(e,t,r,s)=>e.equal(t).mix(r,s),mx_ifgreater:(e,t,r,s)=>e.greaterThan(t).mix(r,s),mx_ifgreatereq:(e,t,r,s)=>e.greaterThanEqual(t).mix(r,s),mx_invert:(e,t=Tn(1))=>Ia(t,e),mx_modulo:(e,t=Tn(1))=>Ga(e,t),mx_multiply:(e,t=Tn(1))=>Va(e,t),mx_noise_float:(e=ql(),t=1,r=0)=>EN(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=ql(),t=1,r=0)=>RN(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=ql(),t=1,r=0)=>{e=e.convert("vec2|vec3");return Ln(RN(e),EN(e.add(Sn(19,73)))).mul(t).add(r)},mx_place2d:(e,t=Sn(.5,.5),r=Sn(1,1),s=Tn(0),i=Sn(0,0))=>{let n=e;if(t&&(n=n.sub(t)),r&&(n=n.mul(r)),s){const e=s.mul(Math.PI/180),t=e.cos(),r=e.sin();n=Sn(n.x.mul(t).sub(n.y.mul(r)),n.x.mul(r).add(n.y.mul(t)))}return t&&(n=n.add(t)),i&&(n=n.add(i)),n},mx_power:(e,t=Tn(1))=>du(e,t),mx_ramp4:(e,t,r,s,i=ql())=>{const n=i.x.clamp(),a=i.y.clamp(),o=xu(e,t,n),u=xu(r,s,n);return xu(o,u,a)},mx_ramplr:(e,t,r=ql())=>jN(e,t,r,"x"),mx_ramptb:(e,t,r=ql())=>jN(e,t,r,"y"),mx_rgbtohsv:$N,mx_rotate2d:(e,t)=>{e=Sn(e);const r=(t=Tn(t)).mul(Math.PI/180);return wy(e,r)},mx_rotate3d:(e,t,r)=>{e=An(e),t=Tn(t),r=An(r);const s=t.mul(Math.PI/180),i=r.normalize(),n=s.cos(),a=s.sin(),o=Tn(1).sub(n);return e.mul(n).add(i.cross(e).mul(a)).add(i.mul(i.dot(e)).mul(o))},mx_safepower:(e,t=1)=>(e=Tn(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},s=t.replace(/^out/,"").toLowerCase();if(void 0!==r[s])return e.element(r[s])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==r[t])return e.element(r[t])}return e},mx_splitlr:(e,t,r,s=ql())=>qN(e,t,r,s,"x"),mx_splittb:(e,t,r,s=ql())=>qN(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:WN,mx_subtract:(e,t=Tn(0))=>Ia(e,t),mx_timer:()=>gx,mx_transform_uv:(e=1,t=0,r=ql())=>r.mul(e).add(t),mx_unifiednoise2d:(e,t=ql(),r=Sn(1,1),s=Sn(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>kN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_unifiednoise3d:(e,t=ql(),r=Sn(1,1),s=Sn(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>GN(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_worley_noise_float:(e=ql(),t=1)=>ON(e.convert("vec2|vec3"),t,_n(1)),mx_worley_noise_vec2:(e=ql(),t=1)=>IN(e.convert("vec2|vec3"),t,_n(1)),mx_worley_noise_vec3:(e=ql(),t=1)=>VN(e.convert("vec2|vec3"),t,_n(1)),negate:Ho,negateOnBackSide:Ec,neutralToneMapping:XT,nodeArray:on,nodeImmutable:ln,nodeObject:sn,nodeObjectIntent:nn,nodeObjects:an,nodeProxy:un,nodeProxyConstructor:cn,nodeProxyIntent:dn,normalFlat:Ac,normalGeometry:Rc,normalLocal:wc,normalMap:Fh,normalView:Bc,normalViewGeometry:Cc,normalWorld:Lc,normalWorldGeometry:Mc,normalize:Ao,not:Qa,notEqual:$a,numWorkgroups:d_,objectDirection:Yd,objectGroup:Ra,objectPosition:Kd,objectRadius:ec,objectScale:Zd,objectViewPosition:Jd,objectWorldMatrix:Qd,oneMinus:jo,or:Ya,orthographicDepthToViewZ:_g,oscSawtooth:(e=gx)=>e.fract(),oscSine:(e=gx)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=gx)=>e.fract().round(),oscTriangle:(e=gx)=>e.add(.5).fract().mul(2).sub(1).abs(),output:da,outputStruct:Ob,overloadingFn:px,overrideNode:Cb,overrideNodes:Mb,packHalf2x16:sx,packNormalToRGB:Ch,packSnorm2x16:tx,packUnorm2x16:rx,parabola:Jb,parallaxDirection:wh,parallaxUV:(e,t)=>e.sub(wh.mul(t)),parameter:(e,t)=>new Bb(e,t),pass:(e,t,r)=>new OT(OT.COLOR,e,t,r),passTexture:(e,t)=>new UT(e,t),pcurve:(e,t,r)=>du(ka(du(e,t),Oa(du(e,t),du(Ia(1,e),r))),1/t),perspectiveDepthToViewZ:Sg,pmremTexture:uy,pointShadow:Yv,pointUV:tT,pointWidth:pa,positionGeometry:mc,positionLocal:fc,positionPrevious:yc,positionView:Tc,positionViewDirection:_c,positionWorld:bc,positionWorldDirection:xc,posterize:MT,pow:du,pow2:cu,pow3:hu,pow4:pu,premultiplyAlpha:Dl,property:zn,quadBroadcast:q_,quadSwapDiagonal:G_,quadSwapX:V_,quadSwapY:k_,radians:bo,rand:Eu,range:o_,rangeFogFactor:e_,reciprocal:Qo,reference:Jc,referenceBuffer:eh,reflect:nu,reflectVector:Hc,reflectView:$c,reflector:e=>new Ox(e),refract:vu,refractVector:jc,refractView:Wc,reinhardToneMapping:kT,remap:Bl,remapClamp:Ll,renderGroup:Ea,renderOutput:Vl,rendererReference:nl,replaceDefaultUV:function(e,t=null){return Pu(t,{getUV:"function"==typeof e?e:()=>e})},rotate:wy,rotateUV:yx,roughness:qn,round:Yo,rtt:Hx,sRGBTransferEOTF:Qu,sRGBTransferOETF:Ku,sample:(e,t=null)=>new Kx(e,sn(t)),sampler:e=>(!0===e.isNode?e:rd(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:rd(e)).convert("samplerComparison"),saturate:_u,saturation:ET,screenCoordinate:yd,screenDPR:gd,screenSize:fd,screenUV:md,select:Lu,setCurrentStack:mn,setName:Du,shaderStages:li,shadow:Dv,shadowPositionWorld:dv,shapeCircle:tN,sharedUniformGroup:Na,sheen:Kn,sheenRoughness:Zn,shiftLeft:ro,shiftRight:so,shininess:la,sign:$o,sin:Mo,sinc:(e,t)=>Mo(ho.mul(t.mul(e).sub(1))).div(ho.mul(t.mul(e).sub(1))),sinh:Bo,skinning:Yp,smoothstep:Nu,smoothstepElement:wu,specularColor:aa,specularColorBlended:oa,specularF90:ua,spherizeUV:bx,split:(e,t)=>new xi(sn(e),t),spritesheetUV:_x,sqrt:So,stack:Fb,step:iu,stepElement:Au,storage:Lp,storageBarrier:()=>f_("storage").toStack(),storageTexture:oT,storageTexture3D:lT,struct:(e,t=null)=>{const r=new Pb(e,t);return cn((...t)=>{let s=null;if(t.length>0)if(t[0].isNode){s={};const r=Object.keys(e);for(let e=0;e<t.length;e++)s[r[e]]=t[e]}else s=t[0];return new Ub(r,s)},r)},sub:Ia,subBuild:ju,subgroupAdd:E_,subgroupAll:D_,subgroupAnd:B_,subgroupAny:O_,subgroupBallot:S_,subgroupBroadcast:z_,subgroupBroadcastFirst:I_,subgroupElect:N_,subgroupExclusiveAdd:w_,subgroupExclusiveMul:M_,subgroupInclusiveAdd:R_,subgroupInclusiveMul:C_,subgroupIndex:xl,subgroupMax:U_,subgroupMin:P_,subgroupMul:A_,subgroupOr:L_,subgroupShuffle:$_,subgroupShuffleDown:j_,subgroupShuffleUp:H_,subgroupShuffleXor:W_,subgroupSize:g_,subgroupXor:F_,tan:Po,tangentGeometry:yh,tangentLocal:bh,tangentView:xh,tangentWorld:Th,tanh:Uo,texture:rd,texture3D:hT,texture3DLevel:(e,t,r)=>hT(e,t).level(r),texture3DLoad:(...e)=>hT(...e).setSampler(!1),textureBarrier:()=>f_("texture").toStack(),textureBicubic:tf,textureBicubicLevel:ef,textureCubeUV:Ff,textureLevel:(e,t,r)=>rd(e,t).level(r),textureLoad:sd,textureSize:Yl,textureStore:(e,t,r)=>{let s;return!0===e.isStorageTextureNode?s=e.store(t,r):(s=oT(e,t,r),null!==r&&s.toStack()),s},thickness:fa,time:gx,toneMapping:ol,toneMappingExposure:ul,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>new IT(t,r,sn(s),sn(i),sn(n)),transformDirection:gu,transformNormal:Pc,transformNormalByInverseViewMatrix:fu,transformNormalByViewMatrix:mu,transformNormalToView:Uc,transformedClearcoatNormalView:Ic,transformedNormalView:Dc,transformedNormalWorld:Oc,transmission:ma,transpose:Jo,triNoise3D:dx,triplanarTexture:(...e)=>vx(...e),triplanarTextures:vx,trunc:Ko,uint:vn,uintBitsToFloat:e=>new Wb(e,"float","uint"),uniform:Aa,uniformArray:ud,uniformCubeTexture:(e=qc)=>Yc(e),uniformFlow:Uu,uniformGroup:va,uniformTexture:(e=Jl)=>rd(e),unpackHalf2x16:ox,unpackNormal:Bh,unpackRGBToNormal:Mh,unpackSnorm2x16:nx,unpackUnorm2x16:ax,unpremultiplyAlpha:Ol,userData:(e,t,r)=>new pT(e,t,r),uv:ql,uvec2:Rn,uvec3:Mn,uvec4:Pn,varying:Xu,varyingProperty:$n,vec2:Sn,vec3:An,vec4:Ln,vectorComponents:di,velocity:bT,vertexColor:Ug,vertexIndex:yl,vertexStage:Yu,vibrance:RT,viewZToLogarithmicDepth:Eg,viewZToOrthographicDepth:Tg,viewZToPerspectiveDepth:vg,viewZToReversedOrthographicDepth:(e,t,r)=>e.add(r).div(r.sub(t)),viewZToReversedPerspectiveDepth:Ng,viewport:bd,viewportCoordinate:Td,viewportDepthTexture:bg,viewportLinearDepth:Cg,viewportMipTexture:pg,viewportOpaqueMipTexture:mg,viewportResolution:vd,viewportSafeUV:Tx,viewportSharedTexture:FT,viewportSize:xd,viewportTexture:hg,viewportUV:_d,vogelDiskSample:Qx,wgsl:(e,t)=>QT(e,t,"wgsl"),wgslFn:(e,t)=>ZT(e,t,"wgsl"),workgroupArray:(e,t)=>new b_("Workgroup",e,t),workgroupBarrier:()=>f_("workgroup").toStack(),workgroupId:c_,workingToColorSpace:el,xor:Ka});const KN=new wb;class ZN extends Yy{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,r){const s=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===i)s._clearColor.getRGB(KN),KN.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(KN),KN.a=1,n=!0;else if(!0===i.isNode){const u=this.get(e),l=i;KN.copy(s._clearColor);let d=u.backgroundMesh;if(void 0===d){const h=Ln(l).mul(iT).context({getUV:()=>nT.mul(Mc),getTextureLevel:()=>sT}),p=kd.element(3).element(3).equal(1),g=ka(1,kd.element(1).element(1)).mul(3),m=p.select(fc.mul(g),fc),f=dc.mul(Ln(m,0));let y=kd.mul(Ln(f.xyz,1));y=y.setZ(y.w);const b=new Dg;function x(){i.removeEventListener("dispose",x),d.material.dispose(),d.geometry.dispose()}b.name="Background.material",b.side=F,b.depthTest=!1,b.depthWrite=!1,b.allowOverride=!1,b.fog=!1,b.lights=!1,b.vertexNode=y,b.colorNode=h,u.backgroundMeshNode=h,u.backgroundMesh=d=new oe(new ft(1,32,32),b),d.frustumCulled=!1,d.name="Background.mesh",i.addEventListener("dispose",x)}const c=l.getCacheKey();u.backgroundCacheKey!==c&&(u.backgroundMeshNode.node=Ln(l).mul(iT),u.backgroundMeshNode.needsUpdate=!0,d.material.needsUpdate=!0,u.backgroundCacheKey=c),t.unshift(d,d.geometry,d.material,0,0,null,null)}else o("Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?KN.set(0,0,0,1):"alpha-blend"===a&&KN.set(0,0,0,0),!0===s.autoClear||!0===n){const T=r.clearColorValue;T.r=KN.r,T.g=KN.g,T.b=KN.b,T.a=KN.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(T.r*=T.a,T.g*=T.a,T.b*=T.a),r.depthClearValue=s.getClearDepth(),r.stencilClearValue=s.getClearStencil(),r.clearColor=!0===s.autoClearColor,r.clearDepth=!0===s.autoClearDepth,r.clearStencil=!0===s.autoClearStencil}else r.clearColor=!1,r.clearDepth=!1,r.clearStencil=!1}}let JN=0;class eS{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=JN++}}class tS{constructor(e,t,r,s,i,n,a,o,u,l,d=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=r,this.transforms=d,this.nodeAttributes=s,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=u,this.hardwareClipping=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const r=new eS(t.name,[]);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class rS{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class sS{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class iS{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class nS extends iS{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class aS{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let oS=0;class uS{constructor(e=null){this.id=oS++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class lS{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class dS{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class cS extends dS{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class hS extends dS{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class pS extends dS{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class gS extends dS{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class mS extends dS{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class fS extends dS{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class yS extends dS{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class bS extends dS{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class xS extends cS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class TS extends hS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class _S extends pS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class vS extends gS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class NS extends mS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class SS extends fS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ES extends yS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class RS extends bS{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let wS=0;const AS=new WeakMap,CS=new WeakMap,MS=new WeakMap,BS=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),LS=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0"),FS=e=>{if(e.writeUsageCount>0)return!0;if(void 0!==e.subBuildsCache)for(const t in e.subBuildsCache)if(FS(e.subBuildsCache[t]))return!0;return!1};class PS{constructor(e,t,r){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=r,this.scene=null,this.camera=null,this.nodes=new Set,this.sequentialNodes=new Set,this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.hardwareClipping=!1,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=Fb(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new uS,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:wS++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&e.blending===tt&&!1===e.alphaToCoverage}createRenderTarget(e,t,r){return new ne(e,t,r)}createCubeRenderTarget(e,t){return new tm(e,t)}includes(e){return this.nodes.has(e)}getOutputType(e=0){let t="vec4";const r=this.renderer.getRenderTarget();if(null!==r){const s=r.textures[e].type,i=r.textures[e].format;let n="vec";s===E?n="ivec":s===S&&(n="uvec"),t=i===$e||i===We?s===E?"int":s===S?"uint":"float":i===$||i===qe?`${n}2`:i===Xe||i===Ye?`${n}3`:`${n}4`}return t}getOutputStructName(){}_getBindGroup(e,t){const r=t[0].groupNode;let s,i=r.shared;if(i)for(let e=1;e<t.length;e++)r!==t[e].groupNode&&(i=!1);if(i){let r="";for(const e of t)if(e.isNodeUniformsGroup){e.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)r+=t.nodeUniform.node.id}else r+=e.nodeUniform.id;const i=this.renderer._currentRenderContext||this.renderer;let n=AS.get(i);void 0===n&&(n=new Map,AS.set(i,n));const a=Gs(r);s=n.get(a),void 0===s&&(s=new eS(e,t),n.set(a,s))}else s=new eS(e,t);return s}getBindGroupArray(e,t){const r=this.bindings[t];let s=r[e];return void 0===s&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),r[e]=s=[]),s}getBindings(){let e=this.bindGroups;if(null===e){const t={},r=this.bindings;for(const e of li)for(const s in r[e]){const i=r[e][s],n=t[s]||(t[s]=[]);for(const e of i)!1===n.includes(e)&&n.push(e)}e=[];for(const r in t){const s=t[r],i=this._getBindGroup(r,s);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const r=e[t];this.bindingsIndexes[r.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.has(e)&&(this.nodes.add(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.getUpdateBeforeType(),r=e.getUpdateAfterType();t===ii.NONE&&r===ii.NONE||this.sequentialNodes.add(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==ii.NONE&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),r=e.getUpdateAfterType();t!==ii.NONE&&this.updateBeforeNodes.push(e),r!==ii.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===le||e.magFilter===yt||e.magFilter===bt||e.magFilter===K||e.minFilter===le||e.minFilter===yt||e.minFilter===bt||e.minFilter===K}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("THREE.NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const r=this.getDataFromNode(e);return void 0===r.cache&&(r.cache=new uS(t?this.getCache():null)),r.cache}isAvailable(){return!1}getVertexIndex(){d("Abstract function.")}getInstanceIndex(){d("Abstract function.")}getDrawIndex(){d("Abstract function.")}getFrontFacing(){d("Abstract function.")}getFragCoord(){d("Abstract function.")}isFlipY(){return!1}isContextAssign(){return!0===this.context.assign}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,this.isContextAssign()?t.writeUsageCount=void 0===t.writeUsageCount?1:t.writeUsageCount+1:t.readUsageCount=void 0===t.readUsageCount?1:t.readUsageCount+1,t.usageCount}hasWriteUsage(e){const t=e.getShared(this),r=(t.isGlobal(this)?this.globalCache:this.cache).getData(t);if(void 0!==r)for(const e in r)if(FS(r[e]))return!0;return!1}generateTexture(){d("Abstract function.")}generateTextureLod(){d("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,r=null){let s=this.generateArrayDeclaration(e,t)+"( ";for(let i=0;i<t;i++){const n=r?r[i]:null;s+=null!==n?n.build(this,e):this.generateConst(e),i<t-1&&(s+=", ")}return s+=" )",s}generateStruct(e,t,r=null){const s=[];for(const e of t){const{name:t,type:i}=e;r&&r[t]&&r[t].isNode?s.push(r[t].build(this,i)):s.push(this.generateConst(i))}return e+"( "+s.join(", ")+" )"}generateConst(i,n=null){if(null===n&&("float"===i||"int"===i||"uint"===i?n=0:"bool"===i?n=!1:"color"===i?n=new e:"vec2"===i||"uvec2"===i||"ivec2"===i?n=new t:"vec3"===i||"uvec3"===i||"ivec3"===i?n=new r:"vec4"!==i&&"uvec4"!==i&&"ivec4"!==i||(n=new s)),"float"===i)return LS(n);if("int"===i)return`${Math.round(n)}`;if("uint"===i)return n>=0?`${Math.round(n)}u`:"0u";if("bool"===i)return n?"true":"false";if("color"===i)return`${this.getType("vec3")}( ${LS(n.r)}, ${LS(n.g)}, ${LS(n.b)} )`;const a=this.getTypeLength(i),o=this.getComponentType(i),u=e=>this.generateConst(o,e);if(2===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)} )`;if(3===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)} )`;if(4===a&&"mat2"!==i)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)}, ${u(n.w)} )`;if(a>=4&&n&&(n.isMatrix2||n.isMatrix3||n.isMatrix4))return`${this.getType(i)}( ${n.elements.map(u).join(", ")} )`;if(a>4)return`${this.getType(i)}()`;throw new Error(`THREE.NodeBuilder: Type '${i}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const r=this.attributes;for(const t of r)if(t.name===e)return t;const s=new rS(e,t);return this.registerDeclaration(s),r.push(s),s}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;return!0===e.isDepthTexture?"float":t===E?"int":t===S?"uint":"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let r=js(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return BS.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const r=t.array,s=e.itemSize,i=e.normalized;let n;return e instanceof xt||!0===i||(n=this.getTypeFromArray(r)),this.getTypeFromLength(s,n)}getTypeLength(e){const t=this.getVectorType(e),r=/vec([2-4])/.exec(t);return null!==r?Number(r[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("THREE.NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=Fb(this.stack);const e=fn();return this.stacks.push(e),mn(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,mn(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,r=null){let s=(r=null===r?e.isGlobal(this)?this.globalCache:this.cache:r).getData(e);void 0===s&&(s={},r.setData(e,s)),void 0===s[t]&&(s[t]={});let i=s[t];if(0===this.subBuildLayers.length)return i;const n=s.any?s.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=n),i}getNodeProperties(e,t="any"){const r=this.getDataFromNode(e,t);return r.properties||(r.properties={outputNode:null})}getBufferAttributeFromNode(e,t,r=null){const s=this.getDataFromNode(e,"vertex");let i=s.bufferAttribute;if(void 0===i){const n=this.uniforms.index++;null===r&&(r="nodeAttribute"+n),i=new rS(r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,r=null,s=this.shaderStage){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.structType;if(void 0===n){const a=this.structs.index++;null===r&&(r="StructType"+a),n=new lS(r,t),this.structs[s].push(n),this.types[s][r]=e,i.structType=n}return n}getOutputStructTypeFromNode(e,t){const r=this.getStructTypeFromNode(e,t,"OutputType","fragment");return r.output=!0,r}getUniformFromNode(e,t,r=this.shaderStage,s=null){const i=this.getDataFromNode(e,r,this.globalCache);let n=i.uniform;if(void 0===n){const a=this.uniforms.index++;n=new sS(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getVarFromNode(e,t=null,r=e.getNodeType(this),s=this.shaderStage,i=!1){const n=this.getDataFromNode(e,s),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const u=i?"_const":"_var",l=this.vars[s]||(this.vars[s]=[]),d=this.vars[u]||(this.vars[u]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+d,this.vars[u]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new iS(t,r,i,c),i||l.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,r=e.getNodeType(this),s=null,i=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,u=e.length;null===t&&(t="nodeVarying"+u),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new nS(t,r,s,i),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,r=this.declarations[t]||(this.declarations[t]={}),s=e.name;let i=s,n=this.getPropertyName(e),a=1;for(;void 0!==r[n];)i=s+"_"+a++,e.name=i,n=this.getPropertyName(e);i!==s&&d(`TSL: Declaration name '${s}' of '${e.type}' already in use. Renamed to '${i}'.`),r[n]=e}getCodeFromNode(e,t,r=this.shaderStage){const s=this.getDataFromNode(e);let i=s.code;if(void 0===i){const e=this.codes[r]||(this.codes[r]=[]),n=e.length;i=new aS("nodeCode"+n,t),e.push(i),s.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:r,flowCodeBlock:s}=this.getDataFromNode(e);let i=!0,n=t;for(;n;){if(!0===s.get(n)){i=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(i)for(const e of r)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,r){const s=this.getDataFromNode(e),i=s.flowCodes||(s.flowCodes=[]),n=s.flowCodeBlock||(s.flowCodeBlock=new WeakMap);i.push(t),n.set(r,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),r=this.flowChildNode(e,t);return this.flowsData.set(e,r),r}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=this.renderer.backend;let r=CS.get(t);void 0===r&&(r=new WeakMap,CS.set(t,r));let s=r.get(e);if(void 0===s){s=new KT;const t=this.currentFunctionNode;this.currentFunctionNode=s,s.code=this.buildFunctionCode(e),this.currentFunctionNode=t,r.set(e,s)}return s}flowShaderNode(e){const t=e.layout,r={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)r[e.name]=new Bb(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,i}flowBuildStage(e,t,r=null){const s=this.getBuildStage();this.setBuildStage(t);const i=e.build(this,r);return this.setBuildStage(s),i}flowStagesNode(e,t=null){const r=this.flow,s=this.vars,i=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new uS,this.stack=Fb();for(const r of ui)this.setBuildStage(r),u.result=e.build(this,t);return u.vars=this.getVars(this.shaderStage),this.flow=r,this.vars=s,this.declarations=i,this.cache=n,this.stack=o,this.setBuildStage(a),u}getFunctionOperator(){return null}buildFunctionCode(){d("Abstract function.")}flowChildNode(e,t=null){const r=this.flow,s={code:""};return this.flow=s,s.result=e.build(this,t),this.flow=r,s}flowNodeFromShaderStage(e,t,r=null,s=null){const i=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const u={...this.context};delete u.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=u;let l=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,r);null!==s&&(i.code+=`${this.tab+s} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=i,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){d("Abstract function.")}getVaryings(){d("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e,t=!1){const r=[],s=this.vars[e];if(void 0!==s)for(const e of s)r.push(`${this.getVar(e.type,e.name,e.count)};`);return r.join(t?"\n":"\n\t")}getUniforms(){d("Abstract function.")}getCodes(e){const t=this.codes[e];let r="";if(void 0!==t)for(const e of t)r+=e.code+"\n";return r}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){d("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const r=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const s=t[e];if(r.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let r,s;return r=null!==t?this.getClosestSubBuild(t):this.subBuildFn,s=r?e?r+"_"+e:r:e,s}prebuild(){const{object:e,renderer:t,material:r}=this;if(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:o('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),r&&r.contextNode&&(!0===r.contextNode.isContextNode?this.context={...this.context,...r.contextNode.getFlowContextData()}:o('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==r){let e=t.library.fromMaterial(r);null===e&&(o(`NodeBuilder: Material "${r.type}" is not compatible.`),e=new Dg),e.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of ui){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of li){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(const e of ui){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of li){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"generate"===e?this.flowNode(t):t.build(this);await Tt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=MS.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const r=this.getSharedDataFromNode(e);let s=r.cache;if(void 0===s){if("float"===t||"int"===t||"uint"===t)s=new xS(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)s=new TS(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)s=new _S(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)s=new vS(e);else if("color"===t)s=new NS(e);else if("mat2"===t)s=new SS(e);else if("mat3"===t)s=new ES(e);else{if("mat4"!==t)throw new Error(`THREE.NodeBuilder: Uniform "${t}" not implemented.`);s=new RS(e)}r.cache=s}return s}format(e,t,r){if((t=this.getVectorType(t))===(r=this.getVectorType(r))||null===r||this.isReference(r))return e;const s=this.getTypeLength(t),i=this.getTypeLength(r);return 16===s&&9===i?`${this.getType(r)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===s&&4===i?`${this.getType(r)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:s>4||i>4||0===i?e:s===i?`${this.getType(r)}( ${e} )`:s>i?(e="bool"===r?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),r)):4===i&&s>1?`${this.getType(r)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===s?`${this.getType(r)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===s&&i>1&&t!==this.getComponentType(r)&&(e=`${this.getType(this.getComponentType(r))}( ${e} )`),`${this.getType(r)}( ${e} )`)}getSignature(){return`// Three.js r${_t} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Js(this.object).useVelocity}}class US{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let r=e.get(t);return void 0===r&&(r={renderId:0,frameId:0},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===ii.FRAME){const t=this._getMaps(this.updateBeforeMap,r);if(t.frameId!==this.frameId){const r=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=r)}}else if(t===ii.RENDER){const t=this._getMaps(this.updateBeforeMap,r);if(t.renderId!==this.renderId){const r=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=r)}}else t===ii.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===ii.FRAME){const t=this._getMaps(this.updateAfterMap,r);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===ii.RENDER){const t=this._getMaps(this.updateAfterMap,r);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===ii.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===ii.FRAME){const t=this._getMaps(this.updateMap,r);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===ii.RENDER){const t=this._getMaps(this.updateMap,r);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===ii.OBJECT&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class DS{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}DS.isNodeFunctionInput=!0;class OS extends Qv{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class IS extends Qv{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:tv(this.light),lightColor:e}}}class VS extends Qv{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=Z_(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Aa(new e).setGroup(Ea)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:r,lightDirectionNode:s}=this,i=Lc.dot(s).mul(.5).add(.5),n=xu(r,t,i);e.context.irradiance.addAssign(n)}}class kS extends Qv{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Aa(0).setGroup(Ea),this.penumbraCosNode=Aa(0).setGroup(Ea),this.cutoffDistanceNode=Aa(0).setGroup(Ea),this.decayExponentNode=Aa(0).setGroup(Ea),this.colorNode=Aa(this.color).setGroup(Ea)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:r,penumbraCosNode:s}=this;return Nu(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=K_(this.light,e.context.positionWorld),t.projectionUV=r),r}setupDirect(e){const{colorNode:t,cutoffDistanceNode:r,decayExponentNode:s,light:i}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(tv(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=Kv({lightDistance:l,cutoffDistance:r,decayExponent:s});let c,h,p=t.mul(u).mul(d);if(i.colorNode?(h=this.getLightCoord(e),c=i.colorNode(h)):i.map&&(h=this.getLightCoord(e),c=rd(i.map,h.xy).onRenderUpdate(()=>i.map)),c){p=h.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class GS extends kS{static get type(){return"IESSpotLightNode"}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){const r=this.light.iesMap;let s=null;if(r&&!0===r.isTexture){const e=t.acos().mul(1/Math.PI);this._iesTextureNode=rd(r,Sn(e,0),0),s=this._iesTextureNode.r}else s=super.getSpotAttenuation(e,t);return s}update(e){super.update(e),null!==this._iesTextureNode&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}}class zS extends Qv{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new r);this.lightProbe=ud(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=YN(Lc,this.lightProbe);e.context.irradiance.addAssign(t)}}const $S=gn(([e,t])=>{const r=e.abs().sub(t);return Wo(su(r,0)).add(ru(su(r.x,r.y),0))});class WS extends kS{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=Tn(0),r=this.penumbraCosNode,s=Q_(this.light).mul(e.context.positionWorld||bc);return yn(s.w.greaterThan(0),()=>{const e=s.xyz.div(s.w),i=$S(e.xy.sub(Sn(.5)),Sn(.5)),n=ka(-1,Ia(1,Io(r)).sub(1));t.assign(_u(i.mul(-2).mul(n)))}),t}}const HS=new a,jS=new a;let qS=null;class XS extends Qv{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Aa(new r).setGroup(Ea),this.halfWidth=Aa(new r).setGroup(Ea),this.updateType=ii.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;jS.identity(),HS.copy(t.matrixWorld),HS.premultiply(r),jS.extractRotation(HS),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(jS),this.halfHeight.value.applyMatrix4(jS)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=rd(qS.LTC_FLOAT_1),r=rd(qS.LTC_FLOAT_2)):(t=rd(qS.LTC_HALF_1),r=rd(qS.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:ev(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){qS=e}}class YS{parseFunction(){d("Abstract function.")}}class QS{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){d("Abstract function.")}}QS.isNodeFunction=!0;const KS=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,ZS=/[a-z_0-9]+/gi,JS="#pragma main";class eE extends QS{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(JS),r=-1!==t?e.slice(t+12):e,s=r.match(KS);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=ZS.exec(i));)n.push(a);const o=[];let u=0;for(;u<n.length;){const e="const"===n[u][0];!0===e&&u++;let t=n[u][0];"in"===t||"out"===t||"inout"===t?u++:t="";const r=n[u++][0];let s=Number.parseInt(n[u][0]);!1===Number.isNaN(s)?u++:s=null;const i=n[u++][0];o.push(new DS(r,i,s,t,e))}const l=r.substring(s[0].length),d=void 0!==s[3]?s[3]:"";return{type:s[2],inputs:o,name:d,precision:void 0!==s[1]?s[1]:"",inputsCode:i,blockCode:l,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("THREE.FunctionNode: Function is not a GLSL code.")})(e);super(t,r,s,i),this.inputsCode=n,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const r=this.blockCode;if(""!==r){const{type:s,inputsCode:i,headerCode:n,precision:a}=this;let o=`${s} ${e} ( ${i.trim()} )`;""!==a&&(o=`${a} ${o}`),t=n+o+r}else t="";return t}}class tE extends YS{parseFunction(e){return new eE(e)}}const rE=[],sE=[],iE=Aa(0,"int").setGroup(Ea);class nE extends Yy{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new US,this.nodeBuilderCache=new Map,this.callHashCache=new $y,this.groupsData=new $y,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;if(t.updateType===ii.OBJECT)return!0;rE[0]=t,rE[1]=e;let r=this.groupsData.get(rE);return void 0===r&&this.groupsData.set(rE,r={}),rE[0]=null,rE[1]=null,r.version!==t.version&&(r.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){const r=this.backend.createNodeBuilder(e.object,this.renderer);return r.scene=e.scene,r.material=t,r.camera=e.camera,r.context.material=t,r.lightsNode=e.lightsNode,r.environmentNode=this.getEnvironmentNode(e.scene),r.fogNode=this.getFogNode(e.scene),r.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&r.enableMultiview(),r}getForRender(e,t=!1){const r=this.get(e);let s=r.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:i}=this,n=this.getForRenderCacheKey(e);if(s=i.get(n),void 0===s){if(t)return(async()=>{let r=this._createNodeBuilder(e,e.material);try{t?await r.buildAsync():r.build()}catch(s){r=this._createNodeBuilder(e,new Dg),t?await r.buildAsync():r.build(),o("TSL: "+s)}return r})().then(e=>(s=this._createNodeBuilderState(e),i.set(n,s),s.usedTimes++,r.nodeBuilderState=s,s));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(r){t=this._createNodeBuilder(e,new Dg),t.build();let s=r.stackTrace;!s&&r.stack&&(s=new Vs(r.stack)),o("TSL: "+r,s)}s=this._createNodeBuilderState(t),i.set(n,s)}}s.usedTimes++,r.nodeBuilderState=s}return s}getForRenderAsync(e){const t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){const t=this.get(e);if(void 0!==t.nodeBuilderState)return t.nodeBuilderState;const r=this.getForRenderCacheKey(e),s=this.nodeBuilderCache.get(r);return void 0!==s?(s.usedTimes++,t.nodeBuilderState=s,s):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){const t=this.get(e);let r=t.nodeBuilderState;if(void 0===r||t.version!==e.version){const s=this.backend.createNodeBuilder(e,this.renderer);s.build(),r=this._createNodeBuilderState(s),t.nodeBuilderState=r,t.version=e.version}return r}_createNodeBuilderState(e){return new tS(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.hardwareClipping,e.transforms)}getEnvironmentNode(e){if(!1===this.renderer.lighting.enabled)return null;this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const r=this.get(e);r.environmentNode&&(t=r.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const r=this.get(e);r.backgroundNode&&(t=r.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){rE[0]=e,rE[1]=t;const r=this.renderer.info.calls,s=this.callHashCache.get(rE)||{};if(s.callId!==r){if(sE.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),sE.push(this.renderer.lighting.enabled?1:0),this.renderer.lighting.enabled){sE.push(t.getCacheKey(!0)),sE.push(this.renderer.shadowMap.enabled?1:0),sE.push(this.renderer.shadowMap.type);const r=this.getEnvironmentNode(e);r&&sE.push(r.getCacheKey())}const i=this.getFogNode(e);i&&sE.push(i.getCacheKey()),s.callId=r,s.cacheKey=zs(sE),this.callHashCache.set(rE,s),sE.length=0}return rE[0]=null,rE[1]=null,s.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),r=e.background;if(r){const s=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,()=>{if(!0===r.isCubeTexture||r.mapping===ce||r.mapping===he||r.mapping===we){if(e.backgroundBlurriness>0||r.mapping===we)return uy(r);{let e;return e=!0===r.isCubeTexture?Qc(r):rd(r),am(e)}}if(!0===r.isTexture)return rd(r,md.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&o("WebGPUNodes: Unsupported background configuration.",r)},s);t.backgroundNode=i,t.background=r,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,r,s=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=i.get(t);return(void 0===n||s)&&(n=r(),i.set(t,n)),n}updateFog(e){const t=this.get(e),r=e.fog;if(r){if(t.fog!==r){const e=this.getCacheNode("fog",r,()=>{if(r.isFogExp2){const e=Jc("color","color",r).setGroup(Ea),t=Jc("density","float",r).setGroup(Ea);return s_(e,t_(t))}if(r.isFog){const e=Jc("color","color",r).setGroup(Ea),t=Jc("near","float",r).setGroup(Ea),s=Jc("far","float",r).setGroup(Ea);return s_(e,e_(t,s))}o("Renderer: Unsupported fog configuration.",r)});t.fogNode=e,t.fog=r}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),r=e.environment;if(r){if(t.environment!==r){const e=this.getCacheNode("environment",r,()=>!0===r.isCubeTexture?Qc(r):!0===r.isTexture?rd(r):void o("Nodes: Unsupported environment configuration.",r));t.environmentNode=e,t.environment=r}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,r=null,s=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=r,n.camera=s,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;let r;return r=e.isArrayTexture?this.backend.isWebGLBackend?rd(e,md).depth(dd("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):rd(e,md).depth(iE).renderOutput(t.toneMapping,t.currentColorSpace):rd(e,md).renderOutput(t.toneMapping,t.currentColorSpace),r}setOutputLayerIndex(e){iE.value=e}updateBefore(e){const t=e.getNodeBuilderState();for(const r of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(r)}updateAfter(e){const t=e.getNodeBuilderState();for(const r of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(r)}updateForCompute(e){const t=this.getNodeFrame(),r=this.getForCompute(e);for(const e of r.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),r=e.getNodeBuilderState();for(const e of r.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new US,this.nodeBuilderCache=new Map,this.cacheLib={}}}const aE=new ut;class oE{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewMatrix=new a,this.viewNormalMatrix=new n,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewMatrix=e.viewMatrix,this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass)}projectPlanes(e,t,r){const s=e.length;for(let i=0;i<s;i++){aE.copy(e[i]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const s=t[r+i],n=aE.normal;s.x=-n.x,s.y=-n.y,s.z=-n.z,s.w=aE.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix.copy(t.matrixWorldInverse),this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let r=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,n=i.length;let a,o;if(this.clipIntersection?(a=this.intersectionPlanes,o=e.intersectionPlanes.length):(a=this.unionPlanes,o=e.unionPlanes.length),a.length!==o+n){a.length=o+n;for(let e=0;e<n;e++)a[o+e]=new s;r=!0}this.projectPlanes(i,a,o),r&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return void 0===t&&(t=new oE(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class uE{constructor(e,t,r){this.bundleGroup=e,this.camera=t,this.renderContext=r}}const lE=[];class dE{constructor(){this.bundles=new $y}get(e,t,r){const s=this.bundles;lE[0]=e,lE[1]=t,lE[2]=r;let i=s.get(lE);return void 0===i&&(i=new uE(e,t,r),s.set(lE,i)),lE[0]=null,lE[1]=null,lE[2]=null,i}dispose(){this.bundles=new $y}}class cE{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const r=this.getMaterialNodeClass(e.type);if(null!==r){t=new r;for(const r in e)t[r]=e[r]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,r){if(r.has(t))d(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`THREE.NodeLibrary: Base class ${t} is not a class.`);r.set(t,e)}}addClass(e,t,r){if(r.has(t))d(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`THREE.NodeLibrary: Base class ${t.name} is not a class.`);r.set(t,e)}}}const hE=new uv,pE=new WeakMap;class gE{constructor(){this.enabled=!0,this._cache=[]}createNode(e=[]){return(new uv).setLights(e)}getNode(e){if(!0!==e.isScene&&!0!==e.isGroup)return hE;let t=pE.get(e);return void 0===t&&(t=this.createNode(),pE.set(e,t)),t}beginRender(e){this._cache.push(this.getNode(e).getLights())}finishRender(e){this.getNode(e).setLights(this._cache.pop())}}class mE extends ne{constructor(e=1,t=1,r={}){super(e,t,r),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const fE=new r,yE=new r,bE=new WeakMap;class xE extends u{constructor(e,r=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Se,this._cameraL.viewport=new s,this._cameraL.matrixWorldAutoUpdate=!1,this._cameraR=new Se,this._cameraR.viewport=new s,this._cameraR.matrixWorldAutoUpdate=!1,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new vt,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._supportsWebGPUBinding=void 0!==globalThis.XRGPUBinding,this._createXRLayer=SE.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSamples=null,this._currentSize=new t,this._onSessionEvent=_E.bind(this),this._onSessionEnd=vE.bind(this),this._onInputSourcesChange=NE.bind(this),this._onAnimationFrame=EE.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._webgpuBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=r,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){return this._foveation}setFoveation(e){this._foveation=e,null!==this._glProjLayer&&(this._glProjLayer.fixedFoveation=e),null!==this._glBaseLayer&&void 0!==this._glBaseLayer.fixedFoveation&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,!0===this.isPresenting&&d("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&d("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(null!==this._session)return this._session.environmentBlendMode}getBaseLayer(){return null!==this._glProjLayer?this._glProjLayer:this._glBaseLayer}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}foveateBoundTexture(e){if(!0!==e.isPostProcessingRenderTarget)return;if(!0!==this.isPresenting)return;if(null===this._glProjLayer)return;const t=this._renderer.backend;if(void 0===t||!0!==t.isWebGLBackend)return;if(null===t.state)return;const r=this._renderer.getOutputRenderTarget();if(null===r||!0!==r.isXRRenderTarget)return;const s=this.getBinding();if(null===s||"function"!=typeof s.foveateBoundTexture)return;this._renderer._textures.updateRenderTarget(e);const{textureGPU:i,glTextureType:n}=t.get(e.texture);if(void 0!==i&&void 0!==n&&e._xrFoveationTextureGPU!==i){e._xrFoveationTextureGPU=i,t.state.bindTexture(n,i);try{s.foveateBoundTexture(n,this.getFoveation())}catch(e){v(`XRManager: Unable to foveate bound XR post-processing texture. ${e.name}: ${e.message}`)}finally{t.state.unbindTexture()}}}getWebGPUBinding(){return null===this._webgpuBinding&&this._supportsWebGPUBinding&&(this._webgpuBinding=new globalThis.XRGPUBinding(this._session,this._renderer.backend.device)),this._webgpuBinding}_isWebGPUSession(){return!0===this._renderer.backend.isWebGPUBackend&&null!==this._session&&this._session.enabledFeatures.includes("webgpu")}_validateWebGPUSession(){const e=this._renderer;if(!0===e.backend.isWebGPUBackend){if(!1===this._session.enabledFeatures.includes("webgpu"))throw new Error('THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.');e.samples>0&&(v("THREE.XRManager: WebGPU XR does not support MSAA yet. Disabling MSAA for this XR session."),null===this._currentSamples&&(this._currentSamples=e.samples),e._samples=0)}}async _initWebGPUSession(e){const t=this.getWebGPUBinding(),r=t.createProjectionLayer({colorFormat:t.getPreferredColorFormat(),depthStencilFormat:"depth24plus"});this._glProjLayer=r,e.updateRenderState({layers:[r]}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._xrRenderTarget=new ne(r.textureWidth,r.textureHeight,{depth:2,minFilter:le,magFilter:le,depthBuffer:!0,multiview:!1,useArrayDepthTexture:!0,samples:0}),this._xrRenderTarget.texture.isArrayTexture=!0,!0===this._useMultiviewIfPossible&&v("THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session."),this._useMultiview=!1}_disposeWebGPUSession(){const e=this._renderer,t=this._xrRenderTarget;if(null===t||!0!==e.backend.isWebGPUBackend)return;const r=e.backend,s=e._textures,i=r.get?r.get(t):null;i&&(i.descriptors=void 0);const n=e=>{null!=e&&(r.delete&&r.delete(e),s.delete&&s.delete(e))};for(let e=0;e<t.textures.length;e++)n(t.textures[e]);n(t.depthTexture),n(t),e._renderContexts&&e._renderContexts.dispose&&e._renderContexts.dispose(),t.dispose()}_getWebGPUViewData(e){const t=this.getWebGPUBinding(),r={colorTexture:null,viewDescriptors:[],viewports:[]};for(let s=0;s<e.length;s++){const i=t.getViewSubImage(this._glProjLayer,e[s]);null===r.colorTexture&&(r.colorTexture=i.colorTexture),r.viewports.push(i.viewport),i.getViewDescriptor&&r.viewDescriptors.push(i.getViewDescriptor())}return r}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,r,s,i,n,a,o={}){const u=new Nt(e,t),l=new mE(i,n,{format:Re,type:Ve,depthTexture:new Z(i,n,o.stencil?Ze:S,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?je:He),stencilBuffer:o.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});l._autoAllocateDepthBuffer=!0;const d=new fe({color:16777215,side:St});d.map=l.texture,d.map.offset.y=1,d.map.repeat.y=-1;const c=new oe(u,d);c.position.copy(r),c.quaternion.copy(s);const h={type:"quad",width:e,height:t,translation:r,quaternion:s,pixelwidth:i,pixelheight:n,plane:c,material:d,rendercall:a,renderTarget:l};if(this._layers.push(h),null!==this._session){h.plane.material=new fe({color:16777215,side:St}),h.plane.material.blending=Et,h.plane.material.blendEquation=it,h.plane.material.blendSrc=Rt,h.plane.material.blendDst=Rt,h.xrlayer=this._createXRLayer(h);const e=this._session.renderState.layers;e.unshift(h.xrlayer),this._session.updateRenderState({layers:e})}else l.isXRRenderTarget=!1;return c}createCylinderLayer(e,t,r,s,i,n,a,o,u={}){const l=new wt(e,e,e*t/r,64,64,!0,Math.PI-t/2,t),d=new mE(n,a,{format:Re,type:Ve,depthTexture:new Z(n,a,u.stencil?Ze:S,void 0,void 0,void 0,void 0,void 0,void 0,u.stencil?je:He),stencilBuffer:u.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});d._autoAllocateDepthBuffer=!0;const c=new fe({color:16777215,side:F});c.map=d.texture,c.map.offset.y=1,c.map.repeat.y=-1;const h=new oe(l,c);h.position.copy(s),h.quaternion.copy(i);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:r,translation:s,quaternion:i,pixelwidth:n,pixelheight:a,plane:h,material:c,rendercall:o,renderTarget:d};if(this._layers.push(p),null!==this._session){p.plane.material=new fe({color:16777215,side:F}),p.plane.material.blending=Et,p.plane.material.blendEquation=it,p.plane.material.blendSrc=Rt,p.plane.material.blendDst=Rt,p.xrlayer=this._createXRLayer(p);const e=this._session.renderState.layers;e.unshift(p.xrlayer),this._session.updateRenderState({layers:e})}else d.isXRRenderTarget=!1;return h}renderLayers(){const e=new r,s=new At,i=this._renderer,n=this.isPresenting;this.isPresenting=!1;const a=new t;i.getSize(a);const o=i.getRenderTarget();for(const t of this._layers){t.renderTarget.isXRRenderTarget=null!==this._session,t.renderTarget._hasExternalTextures=t.renderTarget.isXRRenderTarget;const r=i.contextNode;let n;if(t.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){t.xrlayer.transform=new XRRigidTransform(t.plane.getWorldPosition(e),t.plane.getWorldQuaternion(s));const a=this._glBinding.getSubImage(t.xrlayer,this._xrFrame);i.backend.setXRRenderTargetTextures(t.renderTarget,a.colorTexture,void 0),i._setXRLayerSize(t.renderTarget.width,t.renderTarget.height),n=bE.get(r),void 0===n&&(n=r.context({getOutput:e=>Vl(e,i.toneMapping,i.outputColorSpace)}),bE.set(r,n))}else n=r;i.contextNode=n,i.setRenderTarget(t.renderTarget),t.rendercall(),i.contextNode=r}i.setRenderTarget(o),i._setXRLayerSize(a.x,a.y),this.isPresenting=n}getSession(){return this._session}async setSession(e){const t=this._renderer;!1===t.initialized&&await t.init(),this._gl=t.getContext();const r=this._gl;if(this._session=e,null!==e){if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),this._validateWebGPUSession(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._isWebGPUSession())await this._initWebGPUSession(e);else if(!0===this._supportsLayers){let s=null,i=null,n=null;const a=r.getContextAttributes();await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation()),t.depth&&(n=t.stencil?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24,s=t.stencil?je:He,i=t.stencil?Ze:S);const o={colorFormat:r.RGBA8,depthFormat:n,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const u=this._glBinding.createProjectionLayer(o),l=[u];this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const d=this._useMultiview?2:1,c=new Z(u.textureWidth,u.textureHeight,i,void 0,void 0,void 0,void 0,void 0,void 0,s,d);if(this._xrRenderTarget=new mE(u.textureWidth,u.textureHeight,{format:Re,type:Ve,colorSpace:t.outputColorSpace,depthTexture:c,stencilBuffer:t.stencil,samples:a.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const e of this._layers)e.plane.material=new fe({color:16777215,side:"cylinder"===e.type?F:St}),e.plane.material.blending=Et,e.plane.material.blendEquation=it,e.plane.material.blendSrc=Rt,e.plane.material.blendDst=Rt,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());const s={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,r,s);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new mE(i.framebufferWidth,i.framebufferHeight,{format:Re,type:Ve,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const r=e.near,s=e.far,i=this._cameraXR,n=this._cameraL,a=this._cameraR;i.near=a.near=n.near=r,i.far=a.far=n.far=s,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=6|e.layers.mask,n.layers.mask=-5&i.layers.mask,a.layers.mask=-3&i.layers.mask;const o=e.parent,u=i.cameras;TE(i,o);for(let e=0;e<u.length;e++)TE(u[e],o);2===u.length?function(e,t,r){fE.setFromMatrixPosition(t.matrixWorld),yE.setFromMatrixPosition(r.matrixWorld);const s=fE.distanceTo(yE),i=t.projectionMatrix.elements,n=r.projectionMatrix.elements,a=i[14]/(i[10]-1),o=i[14]/(i[10]+1),u=(i[9]+1)/i[5],l=(i[9]-1)/i[5],d=(i[8]-1)/i[0],c=(n[8]+1)/n[0],h=a*d,p=a*c,g=s/(-d+c),m=g*-d;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(g),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===i[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+g,r=o+g,i=h-m,n=p+(s-m),d=u*o/r*t,c=l*o/r*t;e.projectionMatrix.makePerspective(i,n,d,c,t,r),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(i,n,a):i.projectionMatrix.copy(n.projectionMatrix),function(e,t,r){null===r?e.matrix.copy(t.matrixWorld):(e.matrix.copy(r.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*Mt*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,i,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Ct,this._controllers[e]=t),t}}function TE(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function _E(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const r=this._controllers[t];if(void 0!==r){const t=this.getReferenceSpace();r.update(e.inputSource,e.frame,t),r.dispatchEvent({type:e.type,data:e.inputSource})}}function vE(){const e=this._session,t=this._renderer;e.removeEventListener("select",this._onSessionEvent),e.removeEventListener("selectstart",this._onSessionEvent),e.removeEventListener("selectend",this._onSessionEvent),e.removeEventListener("squeeze",this._onSessionEvent),e.removeEventListener("squeezestart",this._onSessionEvent),e.removeEventListener("squeezeend",this._onSessionEvent),e.removeEventListener("end",this._onSessionEnd),e.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){const t=this._controllerInputSources[e];null!==t&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,null!==this._currentSamples&&(t._samples=this._currentSamples,this._currentSamples=null),t._resetXRState(),this._disposeWebGPUSession(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._webgpuBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new mE(e.pixelwidth,e.pixelheight,{format:Re,type:Ve,depthTexture:new Z(e.pixelwidth,e.pixelheight,e.stencilBuffer?Ze:S,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?je:He),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function NE(e){const t=this._controllers,r=this._controllerInputSources;for(let s=0;s<e.removed.length;s++){const i=e.removed[s],n=r.indexOf(i);n>=0&&(r[n]=null,t[n].disconnect(i))}for(let s=0;s<e.added.length;s++){const i=e.added[s];let n=r.indexOf(i);if(-1===n){for(let e=0;e<t.length;e++){if(e>=r.length){r.push(i),n=e;break}if(null===r[e]){r[e]=i,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(i)}}function SE(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function EE(e,t){if(void 0===t)return;const r=this._cameraXR,i=this._renderer,n=i.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),u=t.getViewerPose(o);if(this._xrFrame=t,null!==u){const e=u.views,t=this._isWebGPUSession()?this._getWebGPUViewData(e):null;null!==this._glBaseLayer&&null===t&&n.setXRTarget(a.framebuffer);let o=!1;e.length!==r.cameras.length&&(r.cameras.length=0,o=!0);for(let i=0;i<e.length;i++){const u=e[i];let l;if(null!==t)l=t.viewports[i];else if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,u);l=e.viewport,0===i&&n.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else l=a.getViewport(u);let d=this._cameras[i];void 0===d&&(d=new Se,d.layers.enable(i),d.viewport=new s,d.matrixWorldAutoUpdate=!1,this._cameras[i]=d),d.matrix.fromArray(u.transform.matrix),d.matrix.decompose(d.position,d.quaternion,d.scale),d.projectionMatrix.fromArray(u.projectionMatrix),d.projectionMatrixInverse.copy(d.projectionMatrix).invert(),d.viewport.set(l.x,l.y,l.width,l.height),0===i&&(r.matrix.copy(d.matrix),r.matrix.decompose(r.position,r.quaternion,r.scale)),!0===o&&r.cameras.push(d)}null!==t&&null!==t.colorTexture&&n.setXRRenderTargetTextures(this._xrRenderTarget,t.colorTexture,t.viewDescriptors),i.setOutputRenderTarget(this._xrRenderTarget);const l=i._getFrameBufferTarget();i.xr.foveateBoundTexture(l)}for(let e=0;e<this._controllers.length;e++){const r=this._controllerInputSources[e],s=this._controllers[e];null!==r&&void 0!==s&&s.update(r,t,o)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class RE extends u{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new s(0,0,this._width,this._height),this._scissor=new s(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Q,this.depthTexture=new Z}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=r,this.domElement.width=Math.floor(e*r),this.domElement.height=Math.floor(t*r),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===r&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,r,s){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,r,s)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,r,s,i=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,r,s),a.minDepth=i,a.maxDepth=n}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const wE=new ue,AE=new t,CE=new s,ME=new Lt,BE=new Bt,LE=new a,FE=new s,PE={[St]:F,[F]:St,[P]:P};class UE{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:r=!1,reversedDepthBuffer:s=!1,alpha:i=!0,depth:n=!0,stencil:a=!1,antialias:o=!1,samples:u=0,getFallback:l=null,outputBufferType:d=Te,multiview:c=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=r,this.reversedDepthBuffer=s,this.outputColorSpace=ie,this.toneMapping=m,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=n,this.stencil=a,this.info=new ab,this.contextNode=Pu(),this.library=new cE,this.lighting=new gE,this._samples=u||!0===o?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new RE(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new zl,this._inspector.setRenderer(this),this._getFallback=l,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const h=!0===this.alpha?0:1;this._clearColor=new wb(0,0,0,h),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this.onError=this._onError,this._outputBufferType=d,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this._currentSourceMaterial=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:ct},this.xr=new xE(this,c),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,r)=>{await this.compileAsync(r,t,e);const s=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,i=this._renderLists.get(e,t),n=this._renderContexts.get(s,this._mrt),a=e.overrideMaterial||r.material,o=this._objects.get(r,a,e,t,i.lightsNode,n,n.clippingContext),{fragmentShader:u,vertexShader:l}=o.getNodeBuilderState();return{fragmentShader:u,vertexShader:l}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let r=this.backend;try{await r.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=r=this._getFallback(e),await r.init(this)}catch(e){return void t(e)}}this._nodes=new nE(this,r),this._animation=new zy(this,this._nodes,this.info),this._attributes=new tb(r,this.info),this._background=new ZN(this,this._nodes),this._geometries=new nb(this._attributes,this.info),this._textures=new Rb(this,r,this.info),this._pipelines=new hb(r,this._nodes,this.info),this._bindings=new pb(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Xy(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Tb(this.lighting),this._bundles=new dE,this._renderContexts=new Sb(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,r=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const s=this._nodes.nodeFrame,i=s.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,u=this._compilationPromises;null===r&&(r=e);const l=!0===e.isScene?e:!0===r.isScene?r:wE,d=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,c=this._renderContexts.get(d,this._mrt),h=this._activeMipmapLevel,p=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,s.renderId++,s.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new oE),c.clippingContext.updateGlobal(l,t),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t=this._updateCamera(t),l.onBeforeRender(this,e,t,d);const g=t.isArrayCamera?BE:ME;t.isArrayCamera?g.setFromArrayCamera(t):(LE.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),g.setFromProjectionMatrix(LE,t.coordinateSystem,t.reversedDepth));const m=this._renderLists.get(l,t);if(m.begin(),this._projectObject(e,t,0,m,c.clippingContext),r!==e&&r.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&m.pushLight(e)}),m.finish(),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;r!==e?this._background.update(r,m,c):this._background.update(l,m,c);const f=m.opaque,y=m.transparent,b=m.transparentDoublePass,x=m.lightsNode;!0===this.opaque&&f.length>0&&this._renderObjects(f,t,l,x),!0===this.transparent&&y.length>0&&this._renderTransparents(y,b,t,l,x),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=u;for(const e of p){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,await this._nodes.getForRenderAsync(t),this._nodes.updateBefore(t),this._geometries.updateForRender(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t);const r=[];this._pipelines.getForRender(t,r),r.length>0&&await Promise.all(r),this._nodes.updateAfter(t),await Tt()}}async renderAsync(e,t){v('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){o("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=hc,t.modelNormalViewMatrix=pc):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===hc&&e.modelNormalViewMatrix===pc}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return v('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),o(t),this._isDeviceLost=!0}_onError(e){let t=`WebGPURenderer: Uncaptured ${e.api} ${e.type}`;e.message&&(t+=`: ${e.message}`),o(t)}_bundleNeedsUpdate(e,t){return void 0===t.bundleGPU||e.version!==t.version}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i,a),u=this.backend.get(o);if(this._bundleNeedsUpdate(s,u)){this.backend.beginBundle(a),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:l,opaque:d}=n;!0===this.opaque&&d.length>0&&this._renderObjects(d,i,t,r),!0===this.transparent&&l.length>0&&this._renderTransparents(l,e,i,t,r),this._currentRenderBundle=null,this.backend.finishBundle(a,o),u.version=s.version}else{const{renderObjects:e}=u;for(let t=0,r=e.length;t<r;t++){const r=e[t];this._nodes.needsRefresh(r)&&(this._nodes.updateBefore(r),this._geometries.updateForRender(r),this._nodes.updateForRender(r),this._bindings.updateForRender(r),this._nodes.updateAfter(r))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)throw new Error('THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_renderOutputLayers(e,t){if(!0!==t.texture.isArrayTexture||t.texture.image.depth<=1)return void this._renderScene(e,e.camera,!1);const r=this._activeCubeFace;try{for(let r=0;r<t.texture.image.depth;r++)this._nodes.setOutputLayerIndex(r),this._activeCubeFace=r,this._renderScene(e,e.camera,!1)}finally{this._nodes.setOutputLayerIndex(0),this._activeCubeFace=r}}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,r=e!==m,s=t!==p.workingColorSpace;if(!1===r&&!1===s)return null;const{width:i,height:n}=this.getDrawingBufferSize(AE),{depth:a,stencil:o}=this,u=this._outputRenderTarget||this._canvasTarget;let l=this._frameBufferTargets.get(u);if(void 0===l){l=new ne(i,n,{depthBuffer:a,stencilBuffer:o,type:this._outputBufferType,format:Re,colorSpace:p.workingColorSpace,generateMipmaps:!1,minFilter:le,magFilter:le,samples:this.samples}),l.isPostProcessingRenderTarget=!0;const e=()=>{u.removeEventListener("dispose",e),l.dispose(),this._frameBufferTargets.delete(u)};u.addEventListener("dispose",e),this._frameBufferTargets.set(u,l)}const d=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=o,null!==d?l.setSize(d.width,d.height,d.depth):l.setSize(i,n,1);const c=this._outputRenderTarget?this._outputRenderTarget.viewport:u._viewport,h=this._outputRenderTarget?this._outputRenderTarget.scissor:u._scissor,g=this._outputRenderTarget?1:u._pixelRatio,f=this._outputRenderTarget?this._outputRenderTarget.scissorTest:u._scissorTest;return l.viewport.copy(c),l.scissor.copy(h),l.viewport.multiplyScalar(g),l.scissor.multiplyScalar(g),l.scissorTest=f,l.multiview=null!==d&&d.multiview,l.useArrayDepthTexture=null!==d&&d.useArrayDepthTexture,l.resolveDepthBuffer=null===d||d.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==d&&d._autoAllocateDepthBuffer,l}_renderScene(e,t,r=!0){if(!0===this._isDeviceLost)return;const s=r?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,n=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,u=this._handleObjectFunction;this.lighting.beginRender(e),this._callDepth++;const l=!0===e.isScene?e:wE,d=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,h=this._activeMipmapLevel;let p;if(null!==s?(p=s,this.setRenderTarget(p)):p=d,null!==p&&!0===p.depthBuffer){const e=this._textures.get(p);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const g=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,p),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t=this._updateCamera(t);const m=this._canvasTarget;let f=m._viewport,y=m._scissor,b=m._pixelRatio;null!==p&&(f=p.viewport,y=p.scissor,b=1),this.getDrawingBufferSize(AE),CE.set(0,0,AE.width,AE.height);const x=void 0===f.minDepth?0:f.minDepth,T=void 0===f.maxDepth?1:f.maxDepth;g.viewportValue.copy(f).multiplyScalar(b).floor(),g.viewportValue.width>>=h,g.viewportValue.height>>=h,g.viewportValue.minDepth=x,g.viewportValue.maxDepth=T,g.viewport=!1===g.viewportValue.equals(CE),g.scissorValue.copy(y).multiplyScalar(b).floor(),g.scissor=m._scissorTest&&!1===g.scissorValue.equals(CE),g.scissorValue.width>>=h,g.scissorValue.height>>=h,g.clippingContext||(g.clippingContext=new oE),g.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,p);const _=t.isArrayCamera?BE:ME;t.isArrayCamera?_.setFromArrayCamera(t):(LE.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),_.setFromProjectionMatrix(LE,t.coordinateSystem,t.reversedDepth));const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v,g.clippingContext),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort,t.reversedDepth),null!==p){this._textures.updateRenderTarget(p,h);const e=this._textures.get(p);g.textures=e.textures,g.depthTexture=e.depthTexture,g.width=e.width,g.height=e.height,g.renderTarget=p,g.depth=p.depthBuffer,g.stencil=p.stencilBuffer}else g.textures=null,g.depthTexture=null,g.width=AE.width,g.height=AE.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=h,g.height>>=h,g.activeCubeFace=c,g.activeMipmapLevel=h,g.occlusionQueryCount=v.occlusionQueryCount,g.scissorValue.max(FE.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),this._background.update(l,v,g),g.camera=t,this.backend.beginRender(g);const{bundles:N,lightsNode:S,transparentDoublePass:E,transparent:R,opaque:w}=v;return N.length>0&&this._renderBundles(N,l,S),!0===this.opaque&&w.length>0&&this._renderObjects(w,t,l,S),!0===this.transparent&&R.length>0&&this._renderTransparents(R,E,t,l,S),this.backend.finishRender(g),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=u,this.lighting.finishRender(e),this._callDepth--,null!==s&&(this.setRenderTarget(d,c,h),this._renderOutput(p)),l.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let r,s=this._quadCache.get(e.texture);if(void 0===s){r=new zx(new Dg),r.name="Output Color Transform",r.material.name="outputColorTransform",r.material.fragmentNode=this._nodes.getOutputNode(e.texture),s={quad:r,cacheKey:t},this._quadCache.set(e.texture,s);const i=()=>{r.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",i)};e.texture.addEventListener("dispose",i)}else r=s.quad,s.cacheKey!==t&&(r.material.fragmentNode=this._nodes.getOutputNode(e.texture),r.material.needsUpdate=!0,s.cacheKey=t);const i=this.autoClear,n=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(r,e),this.autoClear=i,this.xr.enabled=n}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,r=0,s=-1){if(null!==t&&t.isReadbackBuffer&&!1===this.info.memoryMap.has(t)){this.info.createReadbackBuffer(t);const e=()=>{t.removeEventListener("dispose",e),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",e)}if(r%4!=0||s>0&&s%4!=0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,r,s)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,r)}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,r)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,r,s){this._canvasTarget.setScissor(e,t,r,s)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,r,s,i=0,n=1){this._canvasTarget.setViewport(e,t,r,s,i,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)throw new Error('THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.');const s=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==s){this._textures.updateRenderTarget(s);const e=this._textures.get(s);i=this._renderContexts.get(s,null,-1),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=s,i.depth=s.depthBuffer,i.stencil=s.stencilBuffer;const t=this.backend.getClearColor();i.clearColorValue.r=t.r,i.clearColorValue.g=t.g,i.clearColorValue.b=t.b,i.clearColorValue.a=t.a,i.clearDepthValue=this.getClearDepth(),i.clearStencilValue=this.getClearStencil(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel(),!0===s.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){v('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,r)}async clearColorAsync(){v('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){v('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){v('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==m,t=this.currentColorSpace!==p.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:m}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:p.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){if(!0===this._initialized){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return d("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const r=this._nodes.nodeFrame,s=r.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const i=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,u=Array.isArray(e)?e:[e];if(void 0===u[0]||!0!==u[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const r of u){if(!1===n.has(r)){const e=()=>{r.removeEventListener("dispose",e),n.delete(r),a.deleteForCompute(r),o.delete(r)};r.addEventListener("dispose",e);const t=r.onInitFunction;null!==t&&t.call(r,{renderer:this})}o.updateForCompute(r),a.updateForCompute(r);const s=a.getForCompute(r),u=n.getForCompute(r,s);i.compute(e,r,s,u,t)}i.finishCompute(e),r.renderId=s,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return v('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){v('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),r=this._renderContexts.get(e);r.textures=t.textures,r.depthTexture=t.depthTexture,r.width=t.width,r.height=t.height,r.renderTarget=e,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,this.backend.initRenderTarget(r)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=FE.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void o("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=FE.copy(t).floor()}else t=FE.set(0,0,e.image.width,e.image.height);let r,s=this._currentRenderContext;null!==s?r=s.renderTarget:(r=this._renderTarget||this._getFrameBufferTarget(),null!==r&&(this._textures.updateRenderTarget(r),s=this._textures.get(r))),this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,s,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,r,s,i,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,r,s,i,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,r,s,i,a)}_projectObject(e,t,r,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)r=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)s.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?BE:ME;if(!e.frustumCulled||n.intersectsSprite(e)){!0===this.sortObjects&&FE.setFromMatrixPosition(e.matrixWorld).applyMatrix4(LE);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,FE.z,null,i)}}else if(e.isLineLoop)o("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?BE:ME;if(!e.frustumCulled||n.intersectsObject(e)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),FE.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(LE)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o<u;o++){const u=a[o],l=n[u.materialIndex];l&&l.visible&&s.push(e,t,l,r,FE.z,u,i)}}else n.visible&&s.push(e,t,n,r,FE.z,null,i)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const n=s;s=this._renderLists.get(e,t);const a=this._bundles.get(e,t,this._currentRenderContext),o=this.backend.get(a);if(this._bundleNeedsUpdate(e,o)){s.begin(),void 0===o.renderObjects?o.renderObjects=[]:o.renderObjects.length=0;const n=e.children;for(let e=0,a=n.length;e<a;e++)this._projectObject(n[e],t,r,s,i);s.finish()}return void n.pushBundle({bundleGroup:e,camera:t,renderList:s})}const n=e.children;for(let e=0,a=n.length;e<a;e++)this._projectObject(n[e],t,r,s,i)}_renderBundles(e,t,r){for(const s of e)this._renderBundle(s,t,r)}_renderTransparents(e,t,r,s,i){if(t.length>0){for(const{material:e}of t)e.side=F;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=St;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=P}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n<a;n++){const{object:a,geometry:o,material:u,group:l,clippingContext:d}=e[n];this._currentRenderObjectFunction(a,r,t,o,u,l,s,d,i)}}_getShadowNodes(e){const t=e.version;let r=this._cacheShadowNodes.get(e);if(void 0===r||r.version!==t){const s=e.map&&e.map.isTexture,i=e.colorNode&&e.colorNode.isNode,n=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let o=null,u=null,l=null;if(s||i||n||a){let t,r;if(n?(t=e.castShadowNode.rgb,r=e.castShadowNode.a,!0!==this.shadowMap.transmitted&&v("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=An(0),r=Tn(1)),s&&(r=r.mul(Jc("map","texture",e).a)),i&&(r=r.mul(e.colorNode.a)),u=Ln(t,r),a){const t=e.maskShadowNode||e.maskNode;u=gn(([e])=>(t.not().discard(),e))(u)}}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),r={version:t,colorNode:u,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,r)}return r}_updateCamera(e){const t=this.xr;if(!1===t.isPresenting){let t=!1;if(!0===this.reversedDepthBuffer&&!0!==e.reversedDepth){if(e._reversedDepth=!0,e.isArrayCamera)for(const t of e.cameras)t._reversedDepth=!0;t=!0}const r=this.coordinateSystem;if(e.coordinateSystem!==r){if(e.coordinateSystem=r,e.isArrayCamera)for(const t of e.cameras)t.coordinateSystem=r;t=!0}if(!0===t&&(e.updateProjectionMatrix(),e.isArrayCamera))for(const t of e.cameras)t.updateProjectionMatrix()}return null===e.parent&&!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),!0===t.enabled&&!0===t.isPresenting&&(!0===t.cameraAutoUpdate&&t.updateCamera(e),e=t.getCamera()),e}renderObject(e,t,r,s,i,n,a,o=null,u=null){let l,d,c,h,p,g,m,f=!1;const y=this._currentSourceMaterial;if(e.onBeforeRender(this,t,r,s,i,n),!0===i.allowOverride&&null!==t.overrideMaterial){this._currentSourceMaterial=i;const e=t.overrideMaterial;if(f=!0,l=e.isNodeMaterial?e.colorNode:null,d=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,h=t.overrideMaterial.side,p=e.displacementMap,g=e.displacementScale,m=e.displacementBias,i.positionNode&&i.positionNode.isNode&&(e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.displacementMap=i.displacementMap,e.displacementScale=i.displacementScale,e.displacementBias=i.displacementBias,e.transparent=i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:r,positionNode:s}=this._getShadowNodes(i);this.shadowMap.type===pt?e.side=null!==i.shadowSide?i.shadowSide:i.side:e.side=null!==i.shadowSide?i.shadowSide:PE[i.side],null!==t&&(e.colorNode=t),null!==r&&(e.depthNode=r),null!==s&&(e.positionNode=s)}i=e}!0===i.transparent&&i.side===P&&!1===i.forceSinglePass?(i.side=F,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=St,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=P):this._handleObjectFunction(e,i,t,r,a,n,o,u),f&&(t.overrideMaterial.colorNode=l,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=h,t.overrideMaterial.displacementMap=p,t.overrideMaterial.displacementScale=g,t.overrideMaterial.displacementBias=m),this._currentSourceMaterial=y,e.onAfterRender(this,t,r,s,i,n)}hasCompatibility(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);if(u.drawRange=e.geometry.drawRange,u.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}const l=this._nodes.needsRefresh(u);l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),this._pipelines.isReady(u)&&(this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u))}_createObjectPipeline(e,t,r,s,i,n,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:r,camera:s,lightsNode:i,group:n,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n,this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u),this._pipelines.getForRender(u,this._compilationPromises),this._nodes.updateAfter(u)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class DE{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}function OE(e){return e+(eb-e%eb)%eb}class IE extends DE{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return OE(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}}class VE extends IE{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let kE=0;class GE extends VE{constructor(e,t){super("UniformBuffer_"+kE++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get byteLength(){return OE(this.buffer.byteLength)}get buffer(){return this.nodeUniform.value}}class zE extends VE{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map,this._addedIndices=new Set}addUniformUpdateRange(e){const t=e.index;if(this._addedIndices.has(t))return;let r=this._updateRangeCache.get(t);void 0===r&&(r={start:0,count:0},this._updateRangeCache.set(t,r)),r.start=e.offset,r.count=e.itemSize,this._addedIndices.add(t),this.updateRanges.push(r)}clearUpdateRanges(){this._addedIndices.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r<s;r++){const s=this.uniforms[r],i=s.boundary,n=s.itemSize*e,a=t%eb,o=a%i,u=a+o;t+=o,0!==u&&eb-u<n&&(t+=eb-u),s.offset=t/e,s.index=r,t+=n}return Math.ceil(t/eb)*eb}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}release(){super.release(),this._values=null}updateByType(e){return e.isNumberUniform?this.updateNumber(e):e.isVector2Uniform?this.updateVector2(e):e.isVector3Uniform?this.updateVector3(e):e.isVector4Uniform?this.updateVector4(e):e.isColorUniform?this.updateColor(e):e.isMatrix3Uniform?this.updateMatrix3(e):e.isMatrix4Uniform?this.updateMatrix4(e):void o("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset,n=e.getType();if(r[i]!==s){this._getBufferForType(n)[i]=r[i]=s,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset,n=e.getType();if(r[i+0]!==s.x||r[i+1]!==s.y){const a=this._getBufferForType(n);a[i+0]=r[i+0]=s.x,a[i+1]=r[i+1]=s.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset,n=e.getType();if(r[i+0]!==s.x||r[i+1]!==s.y||r[i+2]!==s.z){const a=this._getBufferForType(n);a[i+0]=r[i+0]=s.x,a[i+1]=r[i+1]=s.y,a[i+2]=r[i+2]=s.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset,n=e.getType();if(r[i+0]!==s.x||r[i+1]!==s.y||r[i+2]!==s.z||r[i+3]!==s.w){const a=this._getBufferForType(n);a[i+0]=r[i+0]=s.x,a[i+1]=r[i+1]=s.y,a[i+2]=r[i+2]=s.z,a[i+3]=r[i+3]=s.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const r=this.values,s=e.getValue(),i=e.offset;if(r[i+0]!==s.r||r[i+1]!==s.g||r[i+2]!==s.b){const n=this.buffer;n[i+0]=r[i+0]=s.r,n[i+1]=r[i+1]=s.g,n[i+2]=r[i+2]=s.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const r=this.values,s=e.getValue().elements,i=e.offset;if(r[i+0]!==s[0]||r[i+1]!==s[1]||r[i+2]!==s[2]||r[i+4]!==s[3]||r[i+5]!==s[4]||r[i+6]!==s[5]||r[i+8]!==s[6]||r[i+9]!==s[7]||r[i+10]!==s[8]){const n=this.buffer;n[i+0]=r[i+0]=s[0],n[i+1]=r[i+1]=s[1],n[i+2]=r[i+2]=s[2],n[i+4]=r[i+4]=s[3],n[i+5]=r[i+5]=s[4],n[i+6]=r[i+6]=s[5],n[i+8]=r[i+8]=s[6],n[i+9]=r[i+9]=s[7],n[i+10]=r[i+10]=s[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const r=this.values,s=e.getValue().elements,i=e.offset;if(!1===function(e,t,r){for(let s=0,i=t.length;s<i;s++)if(e[r+s]!==t[s])return!1;return!0}(r,s,i)){this.buffer.set(s,i),function(e,t,r){for(let s=0,i=t.length;s<i;s++)e[r+s]=t[s]}(r,s,i),t=!0,this.addUniformUpdateRange(e)}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let $E=0;class WE extends zE{constructor(e,t){super(e),this.id=$E++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class HE extends DE{constructor(e,t){super(e),this._texture=t,this.version=-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture=e,this.reset())}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}reset(){this.generation=null,this.version=-1}release(){this._texture=null}}let jE=0;class qE extends HE{constructor(e,t){super(e,t),this.id=jE++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class XE extends qE{constructor(e,t,r,s=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r,this.access=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class YE extends XE{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledCubeTexture=!0}}class QE extends XE{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledTexture3D=!0}}const KE={bitcast_int_uint:new YT("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new YT("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }"),textureGather:new YT("\nvec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ) );\n\tvec2 st = floor( coord * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, ij.xw, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.zw, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.zy, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.xy, 0.0 )[ comp ]\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherArray:new YT("\nvec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ).xy );\n\tvec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherCompare:new YT("\nvec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ) );\n\tvec2 st = floor( coord * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, vec3( ij.xw, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.zw, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.zy, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.xy, ref ), 0.0 )\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherCompareArray:new YT("\nvec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ).xy );\n\tvec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttexture( map, vec4( ij.xw, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.zw, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.zy, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.xy, coord.z, ref ) )\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n")},ZE={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},JE={low:"lowp",medium:"mediump",high:"highp"},eR={swizzleAssign:!0,storageBuffer:!1},tR={perspective:"smooth",linear:"noperspective"},rR={centroid:"centroid"},sR="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class iR extends PS{constructor(e,t){super(e,t,new tE),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==T}_include(e){const t=KE[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==KE[e]&&this._include(e),ZE[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`${e} ? ${t} : ${r}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${s.join(", ")} ) {\n\n\t${r.vars}\n\n${r.code}\n\treturn ${r.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,r=t.count*t.itemSize,{itemSize:s}=t,i=t.array.constructor.name.toLowerCase().includes("int");let n=i?We:$e;2===s?n=i?qe:$:3===s?n=i?Ye:Xe:4===s&&(n=i?Ft:Re);const a={Float32Array:Y,Uint8Array:Ve,Uint16Array:Ge,Uint32Array:S,Int8Array:Ie,Int16Array:ke,Int32Array:E,Uint8ClampedArray:Ve},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(r/s))));let u=Math.ceil(r/s/o);o*u*s<r&&u++;const l=o*u*s,d=new e.constructor(l);d.set(e,0),t.array=d;const c=new xe(t.array,o,u,n,a[t.array.constructor.name]||Y);c.needsUpdate=!0,c.isPBOTexture=!0;const h=new ed(c,null,null);h.setPrecision("high"),t.pboNode=h,t.pbo=h.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:r}=e,s=t.value;if(this.renderer.backend.has(s)){this.renderer.backend.get(s).pbo=s.pbo}const i=this.getUniformFromNode(s.pboNode,"texture",this.shaderStage,this.context.nodeName),n=this.getPropertyName(i);this.increaseUsage(r);const a=r.build(this,"uint"),o=this.getDataFromNode(e);let u=o.propertyName;if(void 0===u){const r=this.getVarFromNode(e);u=this.getPropertyName(r);const i=this.getDataFromNode(t);let l=i.propertySizeName;void 0===l&&(l=u+"Size",this.getVarFromNode(t,l,"uint"),this.addLineFlowCode(`${l} = uint( textureSize( ${n}, 0 ).x )`,e),i.propertySizeName=l);const{itemSize:d}=s,c="."+di.join("").slice(0,d),h=`ivec2(${a} % ${l}, ${a} / ${l})`,p=this.generateTextureLoad(null,n,h,"0",null,null);let g="vec4";s.pbo.type===S?g="uvec4":s.pbo.type===E&&(g="ivec4"),this.addLineFlowCode(`${u} = ${g}(${p})${c}`,e),o.propertyName=u}return u}generateTextureLoad(e,t,r,s,i,n){let a;return null===s&&(s="0"),a=i?n?`texelFetchOffset( ${t}, ivec3( ${r}, ${i} ), int( ${s} ), ${n} )`:`texelFetch( ${t}, ivec3( ${r}, ${i} ), int( ${s} ) )`:n?`texelFetchOffset( ${t}, ${r}, int( ${s} ), ${n} )`:`texelFetch( ${t}, ${r}, int( ${s} ) )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,r,s,i){return s&&(r=`vec3( ${r}, ${s} )`),e.isDepthTexture?i?`textureOffset( ${t}, ${r}, ${i} ).x`:`texture( ${t}, ${r} ).x`:i?`textureOffset( ${t}, ${r}, ${i} )`:`texture( ${t}, ${r} )`}generateTextureLevel(e,t,r,s,i,n){return i&&(r=`vec3( ${r}, ${i} )`),n?`textureLodOffset( ${t}, ${r}, ${s}, ${n} )`:`textureLod( ${t}, ${r}, ${s} )`}generateTextureBias(e,t,r,s,i,n){return i&&(r=`vec3( ${r}, ${i} )`),n?`textureOffset( ${t}, ${r}, ${n}, ${s} )`:`texture( ${t}, ${r}, ${s} )`}generateTextureGrad(e,t,r,s,i,n){return i&&(r=`vec3( ${r}, ${i} )`),n?`textureGradOffset( ${t}, ${r}, ${s[0]}, ${s[1]}, ${n} )`:`textureGrad( ${t}, ${r}, ${s[0]}, ${s[1]} )`}generateTextureCompare(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return e.isCubeTexture?`texture( ${t}, vec4( ${r}, ${s} ) )`:i?n?`textureOffset( ${t}, vec4( ${r}, ${i}, ${s} ), ${n} )`:`texture( ${t}, vec4( ${r}, ${i}, ${s} ) )`:n?`textureOffset( ${t}, vec3( ${r}, ${s} ), ${n} )`:`texture( ${t}, vec3( ${r}, ${s} ) )`;o(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,r,s,i,n,a){return e.isDepthTexture&&(s="0"),null===n&&(n="ivec2( 0 )"),null===a&&(a="false"),i?(this._include("textureGatherArray"),`tsl_textureGather_array( ${s}, ${t}, vec3( ${r}, ${i} ), ${n}, ${a} )`):(this._include("textureGather"),`tsl_textureGather( ${s}, ${t}, ${r}, ${n}, ${a} )`)}generateTextureGatherCompare(e,t,r,s,i,n,a){return null===n&&(n="ivec2( 0 )"),null===a&&(a="false"),i?(this._include("textureGatherCompareArray"),`tsl_textureGatherCompare_array( ${t}, vec3( ${r}, ${i} ), ${n}, ${s}, ${a} )`):(this._include("textureGatherCompare"),`tsl_textureGatherCompare( ${t}, ${r}, ${n}, ${s}, ${a} )`)}getUniforms(e){const t=this.uniforms[e],r=[],s={};for(const e of t){let t=null,i=!1;if("texture"===e.type||"texture3D"===e.type){const r=e.node,s=r.value;let i="";!0!==s.isDataTexture&&!0!==s.isData3DTexture||(s.type===S?i="u":s.type===E&&(i="i")),t="texture3D"===e.type&&!1===s.isArrayTexture?`${i}sampler3D ${e.name};`:s.compareFunction&&null!==r.compareNode?!0===s.isArrayTexture?`sampler2DArrayShadow ${e.name};`:`sampler2DShadow ${e.name};`:!0===s.isArrayTexture||!0===s.isDataArrayTexture||!0===s.isCompressedArrayTexture?`${i}sampler2DArray ${e.name};`:`${i}sampler2D ${e.name};`}else if("cubeTexture"===e.type)t=`samplerCube ${e.name};`;else if("cubeDepthTexture"===e.type){t=e.node.value.compareFunction?`samplerCubeShadow ${e.name};`:`samplerCube ${e.name};`}else if("buffer"===e.type){const r=e.node,s=this.getType(r.bufferType),i=r.bufferCount,n=i>0?i:"";t=`${r.name} {\n\t${s} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===s[t]){const e=this.uniformGroups[t];if(void 0!==e){const r=[];for(const t of e.uniforms){const e=t.getType(),s=this.getVectorType(e),i=t.nodeUniform.node.precision;let n=`${s} ${t.name};`;null!==i&&(n=JE[i]+" "+n),r.push("\t"+n)}s[t]=r}}i=!0}if(!i){const s=e.node.precision;null!==s&&(t=JE[s]+" "+t),t="uniform "+t,r.push(t)}}let i="";for(const e in s){const t=s[e];i+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==E){let r=e;e.isInterleavedBufferAttribute&&(r=e.data);const s=r.array;!1==(s instanceof Uint32Array||s instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let r=0;for(const s of e)t+=`layout( location = ${r++} ) in ${s.type} ${s.name};\n`}return t}getStructMembers(e){const t=[];for(const r of e.members)t.push(`\t${r.type} ${r.name};`);return t.join("\n")}getStructs(e){const t=[],r=this.structs[e],s=[];for(const e of r)if(e.output)for(const t of e.members)s.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let r="struct "+e.name+" {\n";r+=this.getStructMembers(e),r+="\n};\n",t.push(r)}return"fragment"===e&&0===s.length&&s.push(`layout( location = 0 ) out ${this.getOutputType()} fragColor;`),"\n"+s.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const r=this.varyings;if("vertex"===e||"compute"===e)for(const s of r){"compute"===e&&(s.needsInterpolation=!0);const r=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){t+=`${tR[s.interpolationType]||s.interpolationType} ${rR[s.interpolationSampling]||""} out ${r} ${s.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}out ${r} ${s.name};\n`}else t+=`${r} ${s.name};\n`}else if("fragment"===e)for(const e of r)if(e.needsInterpolation){const r=this.getType(e.type);if(e.interpolationType){t+=`${tR[e.interpolationType]||e.interpolationType} ${rR[e.interpolationSampling]||""} in ${r} ${e.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}in ${r} ${e.name};\n`}}for(const r of this.builtins[e])t+=`${r};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){o("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){o("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){o("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,r=this.shaderStage){const s=this.extensions[r]||(this.extensions[r]=new Map);!1===s.has(e)&&s.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const r=this.extensions[e];if(void 0!==r)for(const{name:e,behavior:s}of r.values())t.push(`#extension ${e} : ${s}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=eR[e];if(void 0===t){let r;switch(t=!1,e){case"float32Filterable":r="OES_texture_float_linear";break;case"clipDistance":r="WEBGL_clip_cull_distance"}if(void 0!==r){const e=this.renderer.backend.extensions;e.has(r)&&(e.get(r),t=!0)}eR[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let r=0;r<e.length;r++){const s=e[r],i=this.getPropertyName(s.attributeNode);i&&(t+=`${s.varyingName} = ${i};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${sR}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${sR}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let r="// code\n\n";r+=this.flowCode[t];const s=this.flowNodes[t],i=s[s.length-1];for(const e of s){const s=this.getFlowData(e),n=e.name;n&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${n}\n\t`),r+=`${s.code}\n\t`,e===i&&"compute"!==t&&(r+="// result\n\t","vertex"===t?(r+="gl_Position = ",r+=`${this.format(s.result,i.getNodeType(this),"vec4")};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(r+="fragColor = ",r+=`${this.format(s.result,i.getNodeType(this),this.getOutputType())};`)))}const n=e[t];if(n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t,!0),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(n.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);let a=n.uniformGPU;if(void 0===a){const s=e.groupNode,o=s.name,u=this.getBindGroupArray(o,r);if("texture"===t)a=new XE(i.name,i.node,s),u.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new YE(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new QE(i.name,i.node,s),u.push(a);else if("buffer"===t){i.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let r=t.buffer;void 0===r&&(e.name=`NodeBuffer_${e.id}`,r=new GE(e,s),r.name=e.name,t.buffer=r),u.push(r),a=r}else{let e=this.uniformGroups[o];void 0===e?(e=new WE(o,s),this.uniformGroups[o]=e,u.push(e)):-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}}let nR=null,aR=null;class oR{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Pt.RENDER]:null,[Pt.COMPUTE]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}setXRTarget(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}createUniformBuffer(){}destroyUniformBuffer(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),r=this.renderer.info.frame;let s;s=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=s+":"+e.id+":f"+r}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?Pt.COMPUTE:Pt.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}get hasTimestamp(){return!1}hasTimestampQuery(e){return this._getQueryPool(e).hasTimestampQuery(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void v("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return nR=nR||new t,this.renderer.getDrawingBufferSize(nR)}setScissorTest(){}getClearColor(){const e=this.renderer;return aR=aR||new wb,e.getClearColor(aR),aR.getRGB(aR),aR}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Ut(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${_t} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let uR,lR,dR=0;class cR{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class hR{constructor(e){this.backend=e}createAttribute(e,t){const r=this.backend,{gl:s}=r,i=e.array,n=e.usage||s.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a);let u,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(s,t,i,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),i instanceof Float32Array)u=s.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)u=s.HALF_FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?s.HALF_FLOAT:s.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=s.SHORT;else if(i instanceof Uint32Array)u=s.UNSIGNED_INT;else if(i instanceof Int32Array)u=s.INT;else if(i instanceof Int8Array)u=s.BYTE;else if(i instanceof Uint8Array)u=s.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=s.UNSIGNED_BYTE}let d={bufferGPU:l,bufferType:t,type:u,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===s.INT||u===s.UNSIGNED_INT||e.gpuType===E,id:dR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new cR(d,e)}r.set(e,d)}updateAttribute(e){const t=this.backend,{gl:r}=t,s=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(r.bindBuffer(a,n.bufferGPU),0===o.length)r.bufferSubData(a,0,s);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];r.bufferSubData(a,t.start*s.BYTES_PER_ELEMENT,s,t.start,t.count)}i.clearUpdateRanges()}r.bindBuffer(a,null),n.version=i.version}destroyAttribute(e){const t=this.backend,{gl:r}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const s=t.get(e);r.deleteBuffer(s.bufferGPU),t.delete(e)}async getArrayBufferAsync(e,t=null,r=0,s=-1){const i=this.backend,{gl:n}=i,a=e.isInterleavedBufferAttribute?e.data:e,o=i.get(a),{bufferGPU:u}=o,l=-1===s?o.byteLength-r:s;let d;if(null===t)d=new Uint8Array(new ArrayBuffer(l));else if(t.isReadbackBuffer){if(!0===t._mapped)throw new Error("THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.");const e=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),d=new Uint8Array(new ArrayBuffer(l)),t.buffer=d.buffer}else d=new Uint8Array(t);return n.bindBuffer(n.COPY_READ_BUFFER,u),n.getBufferSubData(n.COPY_READ_BUFFER,r,d),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:d.buffer}_createBuffer(e,t,r,s){const i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,r,s),e.bindBuffer(t,null),i}}class pR{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;uR={[it]:e.FUNC_ADD,[Ot]:e.FUNC_SUBTRACT,[Dt]:e.FUNC_REVERSE_SUBTRACT},lR={[Rt]:e.ZERO,[Ht]:e.ONE,[Wt]:e.SRC_COLOR,[rt]:e.SRC_ALPHA,[$t]:e.SRC_ALPHA_SATURATE,[zt]:e.DST_COLOR,[Gt]:e.DST_ALPHA,[kt]:e.ONE_MINUS_SRC_COLOR,[st]:e.ONE_MINUS_SRC_ALPHA,[Vt]:e.ONE_MINUS_DST_COLOR,[It]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),r=e.getParameter(e.VIEWPORT);this.currentScissor=(new s).fromArray(t),this.currentViewport=(new s).fromArray(r),this._tempVec4=new s}enable(e){const{enabled:t}=this;!0!==t[e]&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;!1!==t[e]&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;e!==jt?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===qt?t.cullFace(t.BACK):e===Xt?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:r}=this;e!==t&&(r.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,r){const s=this.gl,i=this.backend.drawBuffersIndexedExt;if(i)for(let n=0;n<e.length;n++){const a=e[n];let o=null;if(null!==t){const e=t.getBlendMode(a.name);e.blending===nt?o=r:e.blending!==re&&(o=e)}else o=r;null!==o?this._setMRTBlendingIndex(n,o):i.blendFuncSeparateiOES(n,s.ONE,s.ZERO,s.ONE,s.ZERO)}else v("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.")}_setMRTBlendingIndex(e,t){const{gl:r}=this,s=this.backend.drawBuffersIndexedExt,i=t.blending,n=t.blendSrc,a=t.blendDst,o=t.blendEquation,u=t.premultipliedAlpha;if(i===Et){const r=null!==t.blendSrcAlpha?t.blendSrcAlpha:n,i=null!==t.blendDstAlpha?t.blendDstAlpha:a,u=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;s.blendEquationSeparateiOES(e,uR[o],uR[u]),s.blendFuncSeparateiOES(e,lR[n],lR[a],lR[r],lR[i])}else if(s.blendEquationSeparateiOES(e,r.FUNC_ADD,r.FUNC_ADD),u)switch(i){case tt:s.blendFuncSeparateiOES(e,r.ONE,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case Kt:s.blendFuncSeparateiOES(e,r.ONE,r.ONE,r.ONE,r.ONE);break;case Qt:s.blendFuncSeparateiOES(e,r.ZERO,r.ONE_MINUS_SRC_COLOR,r.ZERO,r.ONE);break;case Yt:s.blendFuncSeparateiOES(e,r.DST_COLOR,r.ONE_MINUS_SRC_ALPHA,r.ZERO,r.ONE);break;default:s.blendFuncSeparateiOES(e,r.ONE,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)}else switch(i){case tt:s.blendFuncSeparateiOES(e,r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case Kt:s.blendFuncSeparateiOES(e,r.SRC_ALPHA,r.ONE,r.ONE,r.ONE);break;case Qt:s.blendFuncSeparateiOES(e,r.ZERO,r.ONE_MINUS_SRC_COLOR,r.ZERO,r.ONE);break;case Yt:s.blendFuncSeparateiOES(e,r.DST_COLOR,r.ONE_MINUS_SRC_ALPHA,r.ZERO,r.ONE);break;default:s.blendFuncSeparateiOES(e,r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)}}setBlending(e,t,r,s,i,n,a,u){const{gl:l}=this;if(e!==re){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),e===Et)i=i||t,n=n||r,a=a||s,t===this.currentBlendEquation&&i===this.currentBlendEquationAlpha||(l.blendEquationSeparate(uR[t],uR[i]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=i),r===this.currentBlendSrc&&s===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(l.blendFuncSeparate(lR[r],lR[s],lR[n],lR[a]),this.currentBlendSrc=r,this.currentBlendDst=s,this.currentBlendSrcAlpha=n,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||u!==this.currentPremultipledAlpha){if(this.currentBlendEquation===it&&this.currentBlendEquationAlpha===it||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=it,this.currentBlendEquationAlpha=it),u)switch(e){case tt:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case Kt:l.blendFunc(l.ONE,l.ONE);break;case Qt:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case Yt:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:o("WebGLState: Invalid blending: ",e)}else switch(e){case tt:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case Kt:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case Qt:o("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Yt:o("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:o("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=u}}else!0===this.currentBlendingEnabled&&(this.disable(l.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=ar[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case nr:t.depthFunc(t.NEVER);break;case ir:t.depthFunc(t.ALWAYS);break;case sr:t.depthFunc(t.LESS);break;case rr:t.depthFunc(t.LEQUAL);break;case tr:t.depthFunc(t.EQUAL);break;case er:t.depthFunc(t.GEQUAL);break;case Jt:t.depthFunc(t.GREATER);break;case Zt:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,r,s){const i=this._tempVec4.set(e,t,r,s);if(!1===this.currentScissor.equals(i)){const{gl:e}=this;e.scissor(i.x,i.y,i.z,i.w),this.currentScissor.copy(i)}}viewport(e,t,r,s){const i=this._tempVec4.set(e,t,r,s);if(!1===this.currentViewport.equals(i)){const{gl:e}=this;e.viewport(i.x,i.y,i.z,i.w),this.currentViewport.copy(i)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,r){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===r||(this.gl.stencilFunc(e,t,r),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=r)}setStencilOp(e,t,r){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===r||(this.gl.stencilOp(e,t,r),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=r)}setMaterial(e,t,r){const{gl:s}=this;e.side===P?this.disable(s.CULL_FACE):this.enable(s.CULL_FACE);let i=e.side===F;t&&(i=!i),this.setFlipSided(i),e.blending===tt&&!1===e.transparent?this.setBlending(re):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const n=e.stencilWrite;if(this.setStencilTest(n),n&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage&&this.backend.renderer.currentSamples>0?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE),r>0&&this.currentClippingPlanes!==r){const e=12288;for(let t=0;t<8;t++)t<r?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,r){const{gl:s}=this;e?(this.enable(s.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===r||(s.polygonOffset(t,r),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=r)):this.disable(s.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const r=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(r.bindVertexArray(e),null!==t&&r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0)}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:r,currentBoundFramebuffers:s}=this;return s[e]!==t&&(r.bindFramebuffer(e,t),s[e]=t,e===r.DRAW_FRAMEBUFFER&&(s[r.FRAMEBUFFER]=t),e===r.FRAMEBUFFER&&(s[r.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:r}=this;let s=[],i=!1;if(null!==e.textures){s=this.currentDrawbuffers.get(t),void 0===s&&(s=[],this.currentDrawbuffers.set(t,s));const n=e.textures;if(s.length!==n.length||s[0]!==r.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e<t;e++)s[e]=r.COLOR_ATTACHMENT0+e;s.length=n.length,i=!0}}else s[0]!==r.BACK&&(s[0]=r.BACK,i=!0);i&&r.drawBuffers(s)}activeTexture(e){const{gl:t,currentTextureSlot:r,maxTextures:s}=this;void 0===e&&(e=t.TEXTURE0+s-1),r!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,r){const{gl:s,currentTextureSlot:i,currentBoundTextures:n,maxTextures:a}=this;void 0===r&&(r=null===i?s.TEXTURE0+a-1:i);let o=n[r];void 0===o&&(o={type:void 0,texture:void 0},n[r]=o),o.type===e&&o.texture===t||(i!==r&&(s.activeTexture(r),this.currentTextureSlot=r),s.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,r){const{gl:s}=this,i=`${e}-${t}`;return this.currentBoundBufferBases[i]!==r&&(s.bindBufferBase(e,t,r),this.currentBoundBufferBases[i]=r,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:r}=this,s=r[t];void 0!==s&&void 0!==s.type&&(e.bindTexture(s.type,null),s.type=void 0,s.texture=void 0)}getParameter(e){const{gl:t,parameters:r}=this;return void 0!==r[e]?r[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:r,parameters:s}=this;s[e]!==t&&(r.pixelStorei(e,t),s[e]=t)}}class gR{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=T){const{gl:r,extensions:s}=this;let i;const n=p.getTransfer(t);if(e===Ve)return r.UNSIGNED_BYTE;if(e===Qe)return r.UNSIGNED_SHORT_4_4_4_4;if(e===Ke)return r.UNSIGNED_SHORT_5_5_5_1;if(e===Je)return r.UNSIGNED_INT_5_9_9_9_REV;if(e===et)return r.UNSIGNED_INT_10F_11F_11F_REV;if(e===Ie)return r.BYTE;if(e===ke)return r.SHORT;if(e===Ge)return r.UNSIGNED_SHORT;if(e===E)return r.INT;if(e===S)return r.UNSIGNED_INT;if(e===Y)return r.FLOAT;if(e===Te)return r.HALF_FLOAT;if(e===ze)return r.ALPHA;if(e===Xe)return r.RGB;if(e===Re)return r.RGBA;if(e===He)return r.DEPTH_COMPONENT;if(e===je)return r.DEPTH_STENCIL;if(e===$e)return r.RED;if(e===We)return r.RED_INTEGER;if(e===$)return r.RG;if(e===qe)return r.RG_INTEGER;if(e===Ft)return r.RGBA_INTEGER;if(e===or||e===ur||e===lr||e===dr)if(n===g){if(i=s.get("WEBGL_compressed_texture_s3tc_srgb"),null===i)return null;if(e===or)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===ur)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===lr)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===dr)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(i=s.get("WEBGL_compressed_texture_s3tc"),null===i)return null;if(e===or)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===ur)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===lr)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===dr)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===cr||e===hr||e===pr||e===gr){if(i=s.get("WEBGL_compressed_texture_pvrtc"),null===i)return null;if(e===cr)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===hr)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===pr)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===gr)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===mr||e===fr||e===yr||e===br||e===xr||e===H||e===Tr){if(i=s.get("WEBGL_compressed_texture_etc"),null===i)return null;if(e===mr||e===fr)return n===g?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(e===yr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(e===br)return i.COMPRESSED_R11_EAC;if(e===xr)return i.COMPRESSED_SIGNED_R11_EAC;if(e===H)return i.COMPRESSED_RG11_EAC;if(e===Tr)return i.COMPRESSED_SIGNED_RG11_EAC}if(e===_r||e===vr||e===Nr||e===Sr||e===Er||e===Rr||e===wr||e===Ar||e===Cr||e===Mr||e===Br||e===Lr||e===Fr||e===Pr){if(i=s.get("WEBGL_compressed_texture_astc"),null===i)return null;if(e===_r)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===vr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Nr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Sr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Er)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Rr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===wr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Ar)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Cr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Mr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Br)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Lr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Fr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Pr)return n===g?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===Ur||e===Dr||e===Or){if(i=s.get("EXT_texture_compression_bptc"),null===i)return null;if(e===Ur)return n===g?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(e===Dr)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(e===Or)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(e===Ir||e===Vr||e===W||e===kr){if(i=s.get("EXT_texture_compression_rgtc"),null===i)return null;if(e===Ir)return i.COMPRESSED_RED_RGTC1_EXT;if(e===Vr)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===W)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===kr)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===Ze?r.UNSIGNED_INT_24_8:void 0!==r[e]?r[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((r,s)=>{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void s();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),r()):requestAnimationFrame(i)}()})}}let mR,fR,yR,bR=!1;class xR{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===bR&&(this._init(),bR=!0)}_init(){const e=this.gl;mR={[zr]:e.REPEAT,[_e]:e.CLAMP_TO_EDGE,[Gr]:e.MIRRORED_REPEAT},fR={[B]:e.NEAREST,[$r]:e.NEAREST_MIPMAP_NEAREST,[bt]:e.NEAREST_MIPMAP_LINEAR,[le]:e.LINEAR,[yt]:e.LINEAR_MIPMAP_NEAREST,[K]:e.LINEAR_MIPMAP_LINEAR},yR={[qr]:e.NEVER,[jr]:e.ALWAYS,[w]:e.LESS,[A]:e.LEQUAL,[Hr]:e.EQUAL,[M]:e.GEQUAL,[C]:e.GREATER,[Wr]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let r;return r=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,r}getInternalFormat(e,t,r,s,i,n=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];d("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let u=null;s&&(u=o.get("EXT_texture_norm16"),u||d("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let l=t;if(t===a.RED&&(r===a.FLOAT&&(l=a.R32F),r===a.HALF_FLOAT&&(l=a.R16F),r===a.UNSIGNED_BYTE&&(l=a.R8),r===a.BYTE&&(l=a.R8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.R16_EXT),r===a.SHORT&&u&&(l=u.R16_SNORM_EXT)),t===a.RED_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.R8UI),r===a.UNSIGNED_SHORT&&(l=a.R16UI),r===a.UNSIGNED_INT&&(l=a.R32UI),r===a.BYTE&&(l=a.R8I),r===a.SHORT&&(l=a.R16I),r===a.INT&&(l=a.R32I)),t===a.RG&&(r===a.FLOAT&&(l=a.RG32F),r===a.HALF_FLOAT&&(l=a.RG16F),r===a.UNSIGNED_BYTE&&(l=a.RG8),r===a.BYTE&&(l=a.RG8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RG16_EXT),r===a.SHORT&&u&&(l=u.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RG8UI),r===a.UNSIGNED_SHORT&&(l=a.RG16UI),r===a.UNSIGNED_INT&&(l=a.RG32UI),r===a.BYTE&&(l=a.RG8I),r===a.SHORT&&(l=a.RG16I),r===a.INT&&(l=a.RG32I)),t===a.RGB){const e=n?Xr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGB32F),r===a.HALF_FLOAT&&(l=a.RGB16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8:a.RGB8),r===a.BYTE&&(l=a.RGB8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGB16_EXT),r===a.SHORT&&u&&(l=u.RGB16_SNORM_EXT),r===a.UNSIGNED_SHORT_5_6_5&&(l=a.RGB565),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGB4),r===a.UNSIGNED_INT_5_9_9_9_REV&&(l=a.RGB9_E5),r===a.UNSIGNED_INT_10F_11F_11F_REV&&(l=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGB8UI),r===a.UNSIGNED_SHORT&&(l=a.RGB16UI),r===a.UNSIGNED_INT&&(l=a.RGB32UI),r===a.BYTE&&(l=a.RGB8I),r===a.SHORT&&(l=a.RGB16I),r===a.INT&&(l=a.RGB32I)),t===a.RGBA){const e=n?Xr:p.getTransfer(i);r===a.FLOAT&&(l=a.RGBA32F),r===a.HALF_FLOAT&&(l=a.RGBA16F),r===a.UNSIGNED_BYTE&&(l=e===g?a.SRGB8_ALPHA8:a.RGBA8),r===a.BYTE&&(l=a.RGBA8_SNORM),r===a.UNSIGNED_SHORT&&u&&(l=u.RGBA16_EXT),r===a.SHORT&&u&&(l=u.RGBA16_SNORM_EXT),r===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGBA4),r===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(r===a.UNSIGNED_BYTE&&(l=a.RGBA8UI),r===a.UNSIGNED_SHORT&&(l=a.RGBA16UI),r===a.UNSIGNED_INT&&(l=a.RGBA32UI),r===a.BYTE&&(l=a.RGBA8I),r===a.SHORT&&(l=a.RGBA16I),r===a.INT&&(l=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(r===a.UNSIGNED_SHORT&&(l=a.DEPTH_COMPONENT16),r===a.UNSIGNED_INT&&(l=a.DEPTH_COMPONENT24),r===a.FLOAT&&(l=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&r===a.UNSIGNED_INT_24_8&&(l=a.DEPTH24_STENCIL8),l!==a.R16F&&l!==a.R32F&&l!==a.RG16F&&l!==a.RG32F&&l!==a.RGBA16F&&l!==a.RGBA32F||o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,{state:n}=this.backend,a=p.getPrimaries(p.workingColorSpace),o=t.colorSpace===T?null:p.getPrimaries(t.colorSpace),u=t.colorSpace===T||a===o?r.NONE:r.BROWSER_DEFAULT_WEBGL;n.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,u),r.texParameteri(e,r.TEXTURE_WRAP_S,mR[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,mR[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,mR[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,fR[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,d=t.minFilter===le&&l?K:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,fR[d]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,yR[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===B)return;if(t.minFilter!==bt&&t.minFilter!==K)return;if(t.type===Y&&!1===s.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=s.get("EXT_texture_filter_anisotropic");r.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:r,defaultTextures:s}=this,i=this.getGLTextureType(e);let n=s[i];void 0===n&&(n=t.createTexture(),r.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),s[i]=n),r.set(e,{textureGPU:n,glTextureType:i})}createTexture(e,t){const{gl:r,backend:s}=this;let i,n,a,o,u;if(!0===e.isExternalTexture)i=e.sourceTexture,n=this.getGLTextureType(e);else{const{levels:l,width:d,height:c,depth:h}=t;a=s.utils.convert(e.format,e.colorSpace),o=s.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,a,o,e.normalized,e.colorSpace,e.isVideoTexture),i=r.createTexture(),n=this.getGLTextureType(e),s.state.bindTexture(n,i),this.setTextureParameters(n,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?r.texStorage3D(r.TEXTURE_2D_ARRAY,l,u,d,c,h):e.isData3DTexture?r.texStorage3D(r.TEXTURE_3D,l,u,d,c,h):e.isVideoTexture||r.texStorage2D(n,l,u,d,c)}s.set(e,{textureGPU:i,glTextureType:n,glFormat:a,glType:o,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:r,backend:s}=this,{state:i}=s,{textureGPU:n,glTextureType:a,glFormat:o,glType:u}=s.get(t),{width:l,height:d}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(a,n),i.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(a,0,0,0,l,d,o,u,0),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),s.state.unbindTexture()}updateTexture(e,t){const{gl:r}=this,{width:s,height:i}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:u,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const s=e.mipmaps,i=t.image;for(let t=0;t<s.length;t++){const n=s[t];e.isCompressedArrayTexture?e.format!==r.RGBA?null!==o?r.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,i.depth,o,n.data):d("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):r.texSubImage3D(r.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,i.depth,o,u,n.data):null!==o?r.compressedTexSubImage2D(r.TEXTURE_2D,t,0,0,n.width,n.height,o,n.data):d("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const n=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=TR(n[e]);r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,s,i,o,u,t);for(let t=0;t<a.length;t++){const s=TR(a[t].images[e]);r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,s.width,s.height,o,u,s)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const s=t.image;if(e.layerUpdates.size>0){const t=Yr(s.width,s.height,e.format,e.type);for(const i of e.layerUpdates){const e=s.data.subarray(i*t/s.data.BYTES_PER_ELEMENT,(i+1)*t/s.data.BYTES_PER_ELEMENT);r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,i,s.width,s.height,1,o,u,e)}e.clearLayerUpdates()}else r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,s.width,s.height,s.depth,o,u,s.data)}else if(e.isData3DTexture){const e=t.image;r.texSubImage3D(r.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,u,e.data)}else if(e.isVideoTexture)e.update(),r.texImage2D(a,0,l,o,u,t.image);else if(e.isHTMLTexture)"function"==typeof r.texElementImage2D&&(3===r.texElementImage2D.length?r.texElementImage2D(r.TEXTURE_2D,r.RGBA8,t.image):r.texElementImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t.image));else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e<t;e++){const t=n[e],s=TR(t);r.texSubImage2D(a,e,0,0,t.width,t.height,o,u,s)}else{const e=TR(t.image);r.texSubImage2D(a,0,0,0,s,i,o,u,e)}}}generateMipmaps(e){const{gl:t,backend:r}=this,{textureGPU:s,glTextureType:i}=r.get(e);r.state.bindTexture(i,s),t.generateMipmap(i)}deallocateRenderBuffers(e){const{gl:t,backend:r}=this;if(e){const s=r.get(e);if(s.renderBufferStorageSetup=void 0,s.framebuffers){for(const e in s.framebuffers)t.deleteFramebuffer(s.framebuffers[e]);delete s.framebuffers}if(s.depthRenderbuffer&&(t.deleteRenderbuffer(s.depthRenderbuffer),delete s.depthRenderbuffer),s.stencilRenderbuffer&&(t.deleteRenderbuffer(s.stencilRenderbuffer),delete s.stencilRenderbuffer),s.msaaFrameBuffer&&(t.deleteFramebuffer(s.msaaFrameBuffer),delete s.msaaFrameBuffer),s.msaaRenderbuffers){for(let e=0;e<s.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(s.msaaRenderbuffers[e]);delete s.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:r,backend:s}=this,{textureGPU:i,renderTarget:n}=s.get(e);this.deallocateRenderBuffers(n),!1===t&&!0!==e.isExternalTexture&&r.deleteTexture(i),s.delete(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){const{gl:a,backend:o}=this,{state:u}=this.backend,{textureGPU:l,glTextureType:d,glType:c,glFormat:h}=o.get(t);let p,g,m,f,y,b,x,T,_;u.bindTexture(d,l);const v=e.isCompressedTexture?e.mipmaps[n]:e.image;if(null!==r)p=r.max.x-r.min.x,g=r.max.y-r.min.y,m=r.isBox3?r.max.z-r.min.z:1,f=r.min.x,y=r.min.y,b=r.isBox3?r.min.z:0;else{const t=Math.pow(2,-i);p=Math.floor(v.width*t),g=Math.floor(v.height*t),m=e.isDataArrayTexture||e.isArrayTexture?v.depth:e.isData3DTexture?Math.floor(v.depth*t):1,f=0,y=0,b=0}null!==s?(x=s.x,T=s.y,_=s.z):(x=0,T=0,_=0),u.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),u.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),u.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const N=u.getParameter(a.UNPACK_ROW_LENGTH),S=u.getParameter(a.UNPACK_IMAGE_HEIGHT),E=u.getParameter(a.UNPACK_SKIP_PIXELS),R=u.getParameter(a.UNPACK_SKIP_ROWS),w=u.getParameter(a.UNPACK_SKIP_IMAGES);u.pixelStorei(a.UNPACK_ROW_LENGTH,v.width),u.pixelStorei(a.UNPACK_IMAGE_HEIGHT,v.height),u.pixelStorei(a.UNPACK_SKIP_PIXELS,f),u.pixelStorei(a.UNPACK_SKIP_ROWS,y),u.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const A=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const r=o.get(e),s=o.get(t),d=o.get(r.renderTarget),c=o.get(s.renderTarget),h=d.framebuffers[r.cacheKey],v=c.framebuffers[s.cacheKey],N=u.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,S=u.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;u.bindFramebuffer(a.READ_FRAMEBUFFER,h),u.bindFramebuffer(a.DRAW_FRAMEBUFFER,v);for(let e=0;e<m;e++)A&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,r.textureGPU,i,b+e),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,l,n,_+e)),a.blitFramebuffer(f,y,p,g,x,T,p,g,a.DEPTH_BUFFER_BIT,a.NEAREST);u.bindFramebuffer(a.READ_FRAMEBUFFER,N),u.bindFramebuffer(a.DRAW_FRAMEBUFFER,S)}else if(0!==i||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer());const r=u.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,s=u.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;u.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),u.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<m;e++)A?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,t.textureGPU,i,b+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,i),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,l,n,_+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,l,n),0!==i?a.blitFramebuffer(f,y,p,g,x,T,p,g,a.COLOR_BUFFER_BIT,a.NEAREST):C?a.copyTexSubImage3D(d,n,x,T,_+e,f,y,p,g):a.copyTexSubImage2D(d,n,x,T,f,y,p,g);u.bindFramebuffer(a.READ_FRAMEBUFFER,r),u.bindFramebuffer(a.DRAW_FRAMEBUFFER,s)}else C?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(d,n,x,T,_,p,g,m,h,c,v.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(d,n,x,T,_,p,g,m,h,v.data):a.texSubImage3D(d,n,x,T,_,p,g,m,h,c,v):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,n,x,T,p,g,h,c,v.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,n,x,T,v.width,v.height,h,v.data):a.texSubImage2D(a.TEXTURE_2D,n,x,T,p,g,h,c,v);u.pixelStorei(a.UNPACK_ROW_LENGTH,N),u.pixelStorei(a.UNPACK_IMAGE_HEIGHT,S),u.pixelStorei(a.UNPACK_SKIP_PIXELS,E),u.pixelStorei(a.UNPACK_SKIP_ROWS,R),u.pixelStorei(a.UNPACK_SKIP_IMAGES,w),0===n&&t.generateMipmaps&&a.generateMipmap(d),u.unbindTexture()}copyFramebufferToTexture(e,t,r){const{gl:s}=this,{state:i}=this.backend,{textureGPU:n}=this.backend.get(e),{x:a,y:o,z:u,w:l}=r,d=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){const r=0!==a||0!==o;let d,h;if(!0===e.isDepthTexture?(d=s.DEPTH_BUFFER_BIT,h=s.DEPTH_ATTACHMENT,t.stencil&&(d|=s.STENCIL_BUFFER_BIT)):(d=s.COLOR_BUFFER_BIT,h=s.COLOR_ATTACHMENT0),r){const e=this.backend.get(t.renderTarget),r=e.framebuffers[t.getCacheKey()],h=e.msaaFrameBuffer;i.bindFramebuffer(s.DRAW_FRAMEBUFFER,r),i.bindFramebuffer(s.READ_FRAMEBUFFER,h);const p=c-o-l;s.blitFramebuffer(a,p,a+u,p+l,a,p,a+u,p+l,d,s.NEAREST),i.bindFramebuffer(s.READ_FRAMEBUFFER,r),i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,p,u,l),i.unbindTexture()}else{const e=s.createFramebuffer();i.bindFramebuffer(s.DRAW_FRAMEBUFFER,e),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,h,s.TEXTURE_2D,n,0),s.blitFramebuffer(0,0,u,l,0,0,u,l,d,s.NEAREST),s.deleteFramebuffer(e)}}else i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,c-l-o,u,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,r,s=!1){const{gl:i}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:u,width:l,height:d}=n;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!u){let t=i.DEPTH_COMPONENT24;if(!0===s){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,n.samples,t,l,d)}else r>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,r,t,l,d)):i.renderbufferStorage(i.RENDERBUFFER,t,l,d);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&u&&(r>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,r,i.DEPTH24_STENCIL8,l,d):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,d),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,r,s,i,n){const{backend:a,gl:o}=this,{textureGPU:u,glFormat:l,glType:d}=this.backend.get(e),c=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c);const h=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,u,0);const p=this._getTypedArrayType(d),g=s*i*this._getBytesPerTexel(d,l),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,g,o.STREAM_READ),o.readPixels(t,r,s,i,l,d,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(g/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`THREE.WebGLTextureUtils: Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:r}=this;let s=0;return e===r.UNSIGNED_BYTE&&(s=1),e!==r.UNSIGNED_SHORT_4_4_4_4&&e!==r.UNSIGNED_SHORT_5_5_5_1&&e!==r.UNSIGNED_SHORT_5_6_5&&e!==r.UNSIGNED_SHORT&&e!==r.HALF_FLOAT||(s=2),e!==r.UNSIGNED_INT&&e!==r.FLOAT||(s=4),t===r.RGBA?4*s:t===r.RGB?3*s:t===r.ALPHA?s:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function TR(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class _R{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class vR{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}getUniformBufferLimit(){if(null!==this.maxUniformBlockSize)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const NR={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class SR{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:r,mode:s,object:i,type:n,info:a,index:o}=this;0!==o?r.drawElements(s,t,n,e):r.drawArrays(s,e,t),a.update(i,t,1)}renderInstances(e,t,r){const{gl:s,mode:i,type:n,index:a,object:o,info:u}=this;0!==r&&(0!==a?s.drawElementsInstanced(i,t,n,e,r):s.drawArraysInstanced(i,e,t,r),u.update(o,t,r))}renderMultiDraw(e,t,r){const{extensions:s,mode:i,object:n,info:a}=this;if(0===r)return;const o=s.get("WEBGL_multi_draw");if(null===o)for(let s=0;s<r;s++)this.render(e[s],t[s]);else{0!==this.index?o.multiDrawElementsWEBGL(i,t,0,this.type,e,0,r):o.multiDrawArraysWEBGL(i,e,0,t,0,r);let s=0;for(let e=0;e<r;e++)s+=t[e];a.update(n,s,1)}}}class ER{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return void 0===t&&(d(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestampQuery(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class RR extends ER{constructor(e,t,r=2048){if(super(r),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return d("EXT_disjoint_timer_query not supported; timestamps will be disabled."),void(this.trackTimestamp=!1);this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return v(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const r=this.queries[t];if(r)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,r),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){o("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){o("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,r]of this.queryOffsets){if("ended"===this.queryStates.get(r)){const s=this.queries[r];e.set(t,this.resolveQuery(s))}}if(0===e.size)return this.lastValue;const t={},r=[];for(const[s,i]of e){const e=s.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===r.includes(n)&&r.push(n),void 0===t[n]&&(t[n]=0);const a=await i;this.timestamps.set(s,a),t[n]+=a}const s=t[r[r.length-1]];return this.lastValue=s,this.frames=r,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return o("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let r,s=!1;const i=e=>{s||(s=!0,r&&(clearTimeout(r),r=null),t(e))},n=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(r=setTimeout(n,1));const s=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(s)/1e6)}catch(e){o("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class wR extends oR{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,r={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},s=void 0!==t.context?t.context:e.domElement.getContext("webgl2",r);function i(t){t.preventDefault();const r={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(r)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new _R(this),this.capabilities=new vR(this),this.attributeUtils=new hR(this),this.textureUtils=new xR(this),this.bufferRenderer=new SR(this),this.state=new pR(this),this.utils=new gR(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(d("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return c}get hasTimestamp(){return null!==this.disjoint}async getArrayBufferAsync(e,t=null,r=0,s=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,r,s)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,r=null){const s=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:s.RGBA8}),null!==r){const t=e.stencilBuffer?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:r,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&d("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new RR(this.gl,e,2048));const r=this.timestampQueryPool[e];null!==r.allocateQueriesForContext(t)&&r.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,r=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.viewport(0,0,e,r)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.scissor(0,0,e,r)}this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e)),r.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const s=e.occlusionQueryCount;s>0&&(r.currentOcclusionQueries=r.occlusionQueries,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,r.lastOcclusionObject=null,r.occlusionQueries=new Array(s),r.occlusionQueryObjects=new Array(s),r.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:r}=this,s=this.get(e),i=s.previousContext;r.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>s.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e<a.length;e++){const t=a[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=i,this._resolveRenderTarget(e),null!==i){if(this._setFramebuffer(i),i.viewport)this.updateViewport(i);else{const{width:e,height:t}=this.getDrawingBufferSize();r.viewport(0,0,e,t)}if(i.scissor)this.updateScissor(i);else{const{width:e,height:t}=this.getDrawingBufferSize();r.scissor(0,0,e,t)}}this.prepareTimestampBuffer(Pt.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:r,currentOcclusionQueryObjects:s}=t;if(r&&s){const e=new WeakSet,{gl:i}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const n=()=>{let a=0;for(let t=0;t<r.length;t++){const n=r[t];null!==n&&(i.getQueryParameter(n,i.QUERY_RESULT_AVAILABLE)&&(0===i.getQueryParameter(n,i.QUERY_RESULT)&&e.add(s[t]),r[t]=null,i.deleteQuery(n),a++))}a<r.length?requestAnimationFrame(n):t.occluded=e};n()}}isOccluded(e,t){const r=this.get(e);return r.occluded&&r.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:r,y:s,width:i,height:n}=e.viewportValue;t.viewport(r,e.height-n-s,i,n)}updateScissor(e){const{state:t}=this,{x:r,y:s,width:i,height:n}=e.scissorValue;t.scissor(r,e.height-n-s,i,n)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,r,s=null,i=!0,n=!0){const{gl:a,renderer:o}=this;if(null===s){s={textures:null,clearColorValue:this.getClearColor()}}let u=0;if(e&&(u|=a.COLOR_BUFFER_BIT),t&&(u|=a.DEPTH_BUFFER_BIT),r&&(u|=a.STENCIL_BUFFER_BIT),0!==u){let l;l=s.clearColorValue?s.clearColorValue:this.getClearColor();const d=o.getClearDepth(),c=o.getClearStencil();if(t&&this.state.setDepthMask(!0),null===s.textures)a.clearColor(l.r,l.g,l.b,l.a),a.clear(u);else{if(i&&this._setFramebuffer(s),e)for(let e=0;e<s.textures.length;e++)0===e?a.clearBufferfv(a.COLOR,e,[l.r,l.g,l.b,l.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1]);t&&r?a.clearBufferfi(a.DEPTH_STENCIL,0,d,c):t?a.clearBufferfv(a.DEPTH,0,[d]):r&&a.clearBufferiv(a.STENCIL,0,[c]),i&&n&&this._resolveRenderTarget(s),i&&null!==this._currentContext&&this._currentContext!==s&&this._setFramebuffer(this._currentContext)}}}beginCompute(e){const{state:t,gl:r}=this;t.bindFramebuffer(r.FRAMEBUFFER,null),this.initTimestampQuery(Pt.COMPUTE,this.getTimestampUID(e))}compute(e,t,r,s,i=null){const{state:n,gl:a}=this;!1===this.discard&&(n.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:u,attributes:l}=this.get(s),d=this._getVaoKey(l),c=this.vaoCache[d];void 0===c?this.vaoCache[d]=this._createVao(l):n.setVertexState(c),n.useProgram(o),this._bindUniforms(r);const h=this._getTransformFeedback(u);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,h),a.beginTransformFeedback(a.POINTS),i=null!==i?i:t.count,Array.isArray(i)?(v("WebGLBackend.compute(): The count parameter must be a single number, not an array."),i=i[0]):i&&"object"==typeof i&&i.isIndirectStorageBufferAttribute&&(v("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),i=t.count),l[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,i):a.drawArrays(a.POINTS,0,i),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let e=0;e<u.length;e++){const t=u[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const{state:t,gl:r}=this;this.discard=!1,t.disable(r.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Pt.COMPUTE,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,r,s,i,n){if(e.isBatchedMesh)if(!1===this.hasFeature("WEBGL_multi_draw")){const{gl:r}=this,s=r.getUniformLocation(n,"nodeUniformDrawId"),i=e._multiDrawStarts,a=e._multiDrawCounts,o=e._multiDrawCount;for(let e=0;e<o;e++)r.uniform1ui(s,e),t.render(i[e],a[e])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else i>1?t.renderInstances(r,s,i):t.render(r,s)}draw(e){const{object:t,pipeline:r,material:s,context:i,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(r),{gl:o,state:u}=this,l=this.get(i),d=e.getDrawParameters();if(null===d)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinantAffine()<0;u.setMaterial(s,c,n),null!==i.mrt&&null!==i.textures&&u.setMRTBlending(i.textures,i.mrt,s),u.useProgram(a);const h=e.getAttributes(),p=this.get(h);let g=p.vaoGPU;if(void 0===g){const e=this._getVaoKey(h);g=this.vaoCache[e],void 0===g&&(g=this._createVao(h),this.vaoCache[e]=g,p.vaoGPU=g)}const m=e.getIndex(),f=null!==m?this.get(m).bufferGPU:null;u.setVertexState(g,f);const y=l.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===s.wireframe?(u.setLineWidth(s.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:x,instanceCount:T}=d;let{firstVertex:_}=d;if(b.object=t,null!==m){_*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);b.index=m.count,b.type=e.type}else b.index=0;if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const r=this.get(e.camera),s=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===r.indexesGPU||r.indexesGPU.length!==s.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let r=0,i=s.length;r<i;r++){const s=o.createBuffer();e[0]=r,o.bindBuffer(o.UNIFORM_BUFFER,s),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(s)}r.indexesGPU=t}let n=0;e:for(const t of e.getBindings())for(const e of t.bindings){if(e===i)break e;(e.isUniformsGroup||e.isUniformBuffer)&&n++}const l=this.renderer.getPixelRatio(),d=this._currentContext.renderTarget,c=this._isRenderCameraDepthArray(this._currentContext),h=this._currentContext.activeCubeFace;if(c){const e=this.get(d.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=d;for(let e=0,r=s.length;e<r;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=h,this._currentContext.activeCubeFace=h}}for(let i=0,d=s.length;i<d;i++){const d=s[i];if(t.layers.test(d.layers)){c&&(this.renderer._activeCubeFace=i,this._currentContext.activeCubeFace=i,this._setFramebuffer(this._currentContext));const s=d.viewport;if(void 0!==s){const t=s.x*l,r=s.y*l,i=s.width*l,n=s.height*l;u.viewport(Math.floor(t),Math.floor(e.context.height-n-r),Math.floor(i),Math.floor(n))}u.bindBufferBase(o.UNIFORM_BUFFER,n,r.indexesGPU[i]),this._draw(t,b,_,x,T,a)}this._currentContext.activeCubeFace=h,this.renderer._activeCubeFace=h}}else this._draw(t,b,_,x,T,a)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,r,s,i,n){return this.textureUtils.copyTextureToBuffer(e,t,r,s,i,n)}updateSampler(){return""}createNodeBuilder(e,t){return new iR(e,t)}createProgram(e){const t=this.gl,{stage:r,code:s}=e,i="fragment"===r?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(i,s),t.compileShader(i),this.set(e,{shaderGPU:i})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const r=this.gl,s=e.pipeline,{fragmentProgram:i,vertexProgram:n}=s,a=r.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU;if(r.attachShader(a,o),r.attachShader(a,u),r.linkProgram(a),this.set(s,{programGPU:a,fragmentShader:o,vertexShader:u}),null!==t&&this.parallel){const i=new Promise(t=>{const i=this.parallel,n=()=>{r.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,s),t()):requestAnimationFrame(n)};n()});return void t.push(i)}this._completeCompile(e,s)}_handleSource(e,t){const r=e.split("\n"),s=[],i=Math.max(t-6,0),n=Math.min(t+6,r.length);for(let e=i;e<n;e++){const i=e+1;s.push(`${i===t?">":" "} ${i}: ${r[e]}`)}return s.join("\n")}_getShaderErrors(e,t,r){const s=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||"").trim();if(s&&""===i)return"";const n=/ERROR: 0:(\d+)/.exec(i);if(n){const s=parseInt(n[1]);return r.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),s)}return i}_logProgramError(e,t,r){if(this.renderer.debug.checkShaderErrors){const s=this.gl,i=(s.getProgramInfoLog(e)||"").trim();if(!1===s.getProgramParameter(e,s.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(s,e,r,t);else{const n=this._getShaderErrors(s,r,"vertex"),a=this._getShaderErrors(s,t,"fragment");o("WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(e,s.VALIDATE_STATUS)+"\n\nProgram Info Log: "+i+"\n"+n+"\n"+a)}else""!==i&&d("WebGLProgram: Program Info Log:",i)}}_completeCompile(e,t){const{state:r,gl:s}=this,i=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=i;!1===s.getProgramParameter(n,s.LINK_STATUS)&&this._logProgramError(n,a,o),r.useProgram(n);const u=e.getBindings();this._setupBindings(u,n),this.set(t,{programGPU:n,pipeline:n})}createComputePipeline(e,t){const{state:r,gl:s}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:n}=e,a=s.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU,l=n.transforms,d=[],c=[];for(let e=0;e<l.length;e++){const t=l[e];d.push(t.varyingName),c.push(t.attributeNode)}s.attachShader(a,o),s.attachShader(a,u),s.transformFeedbackVaryings(a,d,s.SEPARATE_ATTRIBS),s.linkProgram(a),!1===s.getProgramParameter(a,s.LINK_STATUS)&&this._logProgramError(a,o,u),r.useProgram(a),this._setupBindings(t,a);const h=n.attributes,p=[],g=[];for(let e=0;e<h.length;e++){const t=h[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,s.ARRAY_BUFFER)}for(let e=0;e<c.length;e++){const t=c[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,s.ARRAY_BUFFER);const r=this.get(t);g.push(r)}this.set(e,{programGPU:a,transformBuffers:g,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,r=0;for(const s of t){this.set(s,{textures:r,uniformBuffers:e});for(const t of s.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&r++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this;for(const r of e.bindings){const e=this.get(r);if(r.isUniformsGroup||r.isUniformBuffer){const s=r.buffer,i=e.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,i);const n=r.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),0===n.length)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{const e=Qr(s),r=e?1:s.BYTES_PER_ELEMENT;for(let i=0,a=n.length;i<a;i++){const a=n[i],o=a.start*r,u=a.count*r,l=o*(e?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,l,s,o,u)}}this.set(r,e)}else if(r.isSampledTexture){const{textureGPU:t,glTextureType:s}=this.get(r.texture);e.textureGPU=t,e.glTextureType=s,this.set(r,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const r=this.get(e).bufferGPU,s=e.buffer,i=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,r),0===i.length)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{const e=Qr(s),r=e?1:s.BYTES_PER_ELEMENT;let n=i[0].start;for(let a=0,o=i.length;a<o;a++){const o=i[a],u=i[a+1],l=o.start+o.count;if(void 0!==u&&u.start===l)continue;const d=n*r,c=(l-n)*r,h=d*(e?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,h,s,d,c),void 0!==u&&(n=u.start)}}}}createUniformBuffer(e){const t=this.get(e);if(void 0===t.bufferGPU){const r=this.gl,s=e.buffer;t.bufferGPU=r.createBuffer(),r.bindBuffer(r.UNIFORM_BUFFER,t.bufferGPU),r.bufferData(r.UNIFORM_BUFFER,s.byteLength,r.DYNAMIC_DRAW)}}destroyUniformBuffer(e){const t=this.get(e);this.gl.deleteBuffer(t.bufferGPU),this.delete(e)}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(NR).filter(t=>NR[t]===e),r=this.extensions;for(let e=0;e<t.length;e++)if(r.has(t[e]))return!0;return!1}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this.textureUtils.copyTextureToTexture(e,t,r,s,i,n)}copyFramebufferToTexture(e,t,r){this.textureUtils.copyFramebufferToTexture(e,t,r)}hasCompatibility(e){return e===R.TEXTURE_COMPARE||super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:r}=this;this._setFramebuffer(e),r.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:r}=this;let s=null;if(null!==e.textures){const i=e.renderTarget,n=this.get(i),{samples:a,depthBuffer:o,stencilBuffer:u}=i,l=!0===i.isCubeRenderTarget,d=!0===i.isRenderTarget3D,c=i.depth>1,h=!0===i.isXRRenderTarget,p=!0===h&&!0===i._hasExternalTextures;let g=n.msaaFrameBuffer,m=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(i),x=Nb(e);let T;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),T=n.cubeFramebuffers[x]):h&&!1===p?T=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),T=n.framebuffers[x]),void 0===T){T=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,T);const s=e.textures,o=[];if(l){n.cubeFramebuffers[x]=T;const{textureGPU:e}=this.get(s[0]),r=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,i)}else{n.framebuffers[x]=T;for(let r=0;r<s.length;r++){const n=s[r],o=this.get(n);o.renderTarget=e.renderTarget,o.cacheKey=x;const u=t.COLOR_ATTACHMENT0+r;if(i.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,u,o.textureGPU,0,a,0,2);else if(d||c){const e=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,u,o.textureGPU,r,e)}else if(b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,u,t.TEXTURE_2D,o.textureGPU,0,a);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,u,t.TEXTURE_2D,o.textureGPU,e)}}}const h=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===i._autoAllocateDepthBuffer){const r=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(r,e,0,b),n.xrDepthRenderbuffer=r,o.push(u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,h,t.RENDERBUFFER,r)}else if(null!==e.depthTexture){o.push(u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const r=this.get(e.depthTexture);if(r.renderTarget=e.renderTarget,r.cacheKey=x,i.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,h,r.textureGPU,0,a,0,2);else if(p&&b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,h,t.TEXTURE_2D,r.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,h,r.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){const e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,r.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_2D,r.textureGPU,0)}n.depthInvalidationArray=o}else{if(this._isRenderCameraDepthArray(e)){r.bindFramebuffer(t.FRAMEBUFFER,T);const s=this.renderer._activeCubeFace,i=this.get(e.depthTexture),n=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,n,i.textureGPU,0,s)}if((h||b||i.multiview)&&!0!==i._isOpaqueFramebuffer){r.bindFramebuffer(t.FRAMEBUFFER,T);const s=this.get(e.textures[0]);i.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,s.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s.textureGPU,0);const o=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===i._autoAllocateDepthBuffer){const e=n.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{const r=this.get(e.depthTexture);i.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,r.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,r.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,r.textureGPU,0)}}}if(a>0&&!1===b&&!i.multiview){if(void 0===g){const s=[];g=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,g);const i=[],l=e.textures;for(let r=0;r<l.length;r++){i[r]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,i[r]),s.push(t.COLOR_ATTACHMENT0+r);const n=e.textures[r],o=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,o.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+r,t.RENDERBUFFER,i[r])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),n.msaaFrameBuffer=g,n.msaaRenderbuffers=i,o&&void 0===m){m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,a),n.depthRenderbuffer=m;const r=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;s.push(r)}n.invalidationArray=s}s=n.msaaFrameBuffer}else s=T;r.drawBuffers(e,T)}r.bindFramebuffer(t.FRAMEBUFFER,s)}_getVaoKey(e){let t="";for(let r=0;r<e.length;r++){t+=":"+this.get(e[r]).id}return t}_createVao(e){const{gl:t}=this,r=t.createVertexArray();t.bindVertexArray(r);for(let r=0;r<e.length;r++){const s=e[r],i=this.get(s);let n,a;t.bindBuffer(t.ARRAY_BUFFER,i.bufferGPU),t.enableVertexAttribArray(r),!0===s.isInterleavedBufferAttribute?(n=s.data.stride*i.bytesPerElement,a=s.offset*i.bytesPerElement):(n=0,a=0),i.isInteger?t.vertexAttribIPointer(r,s.itemSize,i.type,n,a):t.vertexAttribPointer(r,s.itemSize,i.type,s.normalized,n,a),s.isInstancedBufferAttribute&&!s.isInterleavedBufferAttribute?t.vertexAttribDivisor(r,s.meshPerAttribute):s.isInterleavedBufferAttribute&&s.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(r,s.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),r}_getTransformFeedback(e){let t="";for(let r=0;r<e.length;r++)t+=":"+e[r].id;let r=this.transformFeedbackCache[t];if(void 0!==r)return r;const{gl:s}=this;r=s.createTransformFeedback(),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,r);for(let t=0;t<e.length;t++){const r=e[t];s.bindBufferBase(s.TRANSFORM_FEEDBACK_BUFFER,t,r.transformBuffer)}return s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=r,r}_setupBindings(e,t){const r=this.gl;let s=0,i=0;for(const n of e)for(const e of n.bindings)if(e.isUniformsGroup||e.isUniformBuffer){const i=s++,n=r.getUniformBlockIndex(t,e.name);r.uniformBlockBinding(t,n,i)}else if(e.isSampledTexture){const s=i++,n=r.getUniformLocation(t,e.name);r.uniform1i(n,s)}}_bindUniforms(e){const{gl:t,state:r}=this;let s=0,i=0;for(const n of e)for(const e of n.bindings){const n=this.get(e);if(e.isUniformsGroup||e.isUniformBuffer){const e=s++;r.bindBufferBase(t.UNIFORM_BUFFER,e,n.bufferGPU)}else if(e.isSampledTexture){const e=i++;r.bindTexture(n.glTextureType,n.textureGPU,t.TEXTURE0+e)}}}_resolveRenderTarget(e){const{gl:t,state:r}=this,s=e.renderTarget;if(null!==e.textures&&s){const i=this.get(s);if(s.samples>0&&!1===this._useMultisampledExtension(s)){const n=i.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;s.resolveDepthBuffer&&(s.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),s.stencilBuffer&&s.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=i.msaaFrameBuffer,u=i.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,o),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),d)for(let e=0;e<l.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let r=0;r<l.length;r++){if(d){const{textureGPU:e}=this.get(l[r]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,u[r]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:r,y:s,width:i,height:n}=e.scissorValue,o=e.height-n-s;t.blitFramebuffer(r,o,r+i,o+n,r,o,r+i,o+n,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(d)for(let e=0;e<l.length;e++){const{textureGPU:r}=this.get(l[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,u[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,r,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,i.invalidationArray)}else if(!1===s.resolveDepthBuffer&&i.framebuffers){const s=i.framebuffers[e.getCacheKey()];r.bindFramebuffer(t.DRAW_FRAMEBUFFER,s),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,i.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const AR="point-list",CR="line-list",MR="line-strip",BR="triangle-list",LR="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},FR="never",PR="less",UR="equal",DR="less-equal",OR="greater",IR="not-equal",VR="greater-equal",kR="always",GR="store",zR="load",$R="clear",WR="ccw",HR="cw",jR="none",qR="back",XR="uint16",YR="uint32",QR="r8unorm",KR="r8snorm",ZR="r8uint",JR="r8sint",ew="r16uint",tw="r16sint",rw="r16float",sw="rg8unorm",iw="rg8snorm",nw="rg8uint",aw="rg8sint",ow="r16unorm",uw="r16snorm",lw="r32uint",dw="r32sint",cw="r32float",hw="rg16uint",pw="rg16sint",gw="rg16float",mw="rgba8unorm",fw="rgba8unorm-srgb",yw="rgba8snorm",bw="rgba8uint",xw="rgba8sint",Tw="bgra8unorm",_w="bgra8unorm-srgb",vw="rg16unorm",Nw="rg16snorm",Sw="rgb9e5ufloat",Ew="rgb10a2unorm",Rw="rg11b10ufloat",ww="rg32uint",Aw="rg32sint",Cw="rg32float",Mw="rgba16uint",Bw="rgba16sint",Lw="rgba16float",Fw="rgba16unorm",Pw="rgba16snorm",Uw="rgba32uint",Dw="rgba32sint",Ow="rgba32float",Iw="depth16unorm",Vw="depth24plus",kw="depth24plus-stencil8",Gw="depth32float",zw="depth32float-stencil8",$w="bc1-rgba-unorm",Ww="bc1-rgba-unorm-srgb",Hw="bc2-rgba-unorm",jw="bc2-rgba-unorm-srgb",qw="bc3-rgba-unorm",Xw="bc3-rgba-unorm-srgb",Yw="bc4-r-unorm",Qw="bc4-r-snorm",Kw="bc5-rg-unorm",Zw="bc5-rg-snorm",Jw="bc6h-rgb-ufloat",eA="bc6h-rgb-float",tA="bc7-rgba-unorm",rA="bc7-rgba-unorm-srgb",sA="etc2-rgb8unorm",iA="etc2-rgb8unorm-srgb",nA="etc2-rgb8a1unorm",aA="etc2-rgb8a1unorm-srgb",oA="etc2-rgba8unorm",uA="etc2-rgba8unorm-srgb",lA="eac-r11unorm",dA="eac-r11snorm",cA="eac-rg11unorm",hA="eac-rg11snorm",pA="astc-4x4-unorm",gA="astc-4x4-unorm-srgb",mA="astc-5x4-unorm",fA="astc-5x4-unorm-srgb",yA="astc-5x5-unorm",bA="astc-5x5-unorm-srgb",xA="astc-6x5-unorm",TA="astc-6x5-unorm-srgb",_A="astc-6x6-unorm",vA="astc-6x6-unorm-srgb",NA="astc-8x5-unorm",SA="astc-8x5-unorm-srgb",EA="astc-8x6-unorm",RA="astc-8x6-unorm-srgb",wA="astc-8x8-unorm",AA="astc-8x8-unorm-srgb",CA="astc-10x5-unorm",MA="astc-10x5-unorm-srgb",BA="astc-10x6-unorm",LA="astc-10x6-unorm-srgb",FA="astc-10x8-unorm",PA="astc-10x8-unorm-srgb",UA="astc-10x10-unorm",DA="astc-10x10-unorm-srgb",OA="astc-12x10-unorm",IA="astc-12x10-unorm-srgb",VA="astc-12x12-unorm",kA="astc-12x12-unorm-srgb",GA="clamp-to-edge",zA="repeat",$A="mirror-repeat",WA="linear",HA="nearest",jA="zero",qA="one",XA="src",YA="one-minus-src",QA="src-alpha",KA="one-minus-src-alpha",ZA="dst",JA="one-minus-dst",eC="dst-alpha",tC="one-minus-dst-alpha",rC="src-alpha-saturated",sC="constant",iC="one-minus-constant",nC="add",aC="subtract",oC="reverse-subtract",uC="min",lC="max",dC=0,cC=15,hC="keep",pC="zero",gC="replace",mC="invert",fC="increment-clamp",yC="decrement-clamp",bC="increment-wrap",xC="decrement-wrap",TC="storage",_C="read-only-storage",vC="write-only",NC="read-only",SC="read-write",EC="non-filtering",RC="comparison",wC="float",AC="unfilterable-float",CC="depth",MC="sint",BC="uint",LC="2d",FC="3d",PC="2d",UC="2d-array",DC="cube",OC="3d",IC="all",VC="vertex",kC="instance",GC={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},zC={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class $C extends HE{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class WC extends IE{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let HC=0;class jC extends WC{constructor(e,t){super("StorageBuffer_"+HC++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:ai.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}const qC=[null];class XC{constructor(e){this.backend=e,this._preferredCanvasFormat=null}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?zw:kw:!0===this.backend.renderer.reversedDepthBuffer?Gw:Vw),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,r=e.getRenderTarget();t=r?r.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=this.getSampleCount(t||1);const r=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:r?1:t,isMSAA:r}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?AR:e.isLineSegments||e.isMesh&&!0===t.wireframe?CR:e.isLine?MR:e.isMesh?BR:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return null===this._preferredCanvasFormat&&(this._preferredCanvasFormat=navigator.gpu.getPreferredCanvasFormat()),this._preferredCanvasFormat;if(e===Ve)return Tw;if(e===Te)return Lw;throw new Error("THREE.WebGPUUtils: Unsupported output buffer type.")}}function YC(e,t){qC[0]=t,e.queue.submit(qC),qC[0]=null}class QC{constructor(){this.label="",this.layout=null,this.entries=[]}reset(){this.label="",this.layout=null,this.entries.length=0}}class KC{constructor(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}reset(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}}class ZC{constructor(){this.label=""}reset(){this.label=""}}class JC{constructor(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}reset(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}}class eM{constructor(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}reset(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}}class tM{constructor(){this.label="",this.colorAttachments=[],this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}reset(){this.label="",this.colorAttachments.length=0,this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}}class rM{constructor(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new sM,this.fragment=null}reset(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample.reset(),this.fragment=null}}class sM{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}}class iM{constructor(){this.label="",this.code="",this.compilationHints=[]}reset(){this.label="",this.code="",this.compilationHints.length=0}}class nM{constructor(){this.label="",this.size={width:0,height:1,depthOrArrayLayers:1},this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats=[],this.textureBindingViewDimension=void 0}reset(){this.label="",this.size.width=0,this.size.height=1,this.size.depthOrArrayLayers=1,this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats.length=0,this.textureBindingViewDimension=void 0}}class aM{constructor(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}reset(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}}const oM=new QC,uM=new KC,lM=new ZC,dM=new JC,cM=new tM,hM=new rM,pM=new eM,gM=new iM,mM=new nM,fM=new aM;class yM extends Yy{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:WA}),this.flipYSampler=e.createSampler({minFilter:HA}),uM.size=4,uM.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(uM),uM.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),uM.size=4,uM.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(uM),uM.reset(),this.transferPipelines={},gM.label="mipmap",gM.code="\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar<uniform> flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d<f32>;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array<f32>;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube<f32>;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n",this.mipmapShaderModule=e.createShaderModule(gM),gM.reset()}getTransferPipeline(e,t){const r=`${e}-${t=t||"2d-array"}`;let s=this.transferPipelines[r];return void 0===s&&(hM.label=`mipmap-${e}-${t}`,hM.vertex={module:this.mipmapShaderModule},hM.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},hM.layout="auto",s=this.device.createRenderPipeline(hM),hM.reset(),this.transferPipelines[r]=s),s}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size;mM.size.width=i,mM.size.height=n,mM.format=s,mM.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;const a=this.device.createTexture(mM);mM.reset();const o=this.getTransferPipeline(s,e.textureBindingViewDimension),u=this.getTransferPipeline(s,a.textureBindingViewDimension),l=this.device.createCommandEncoder(lM),d=(e,t,r,s,i,n)=>{const a=e.getBindGroupLayout(0);fM.dimension=t.textureBindingViewDimension||"2d-array",fM.mipLevelCount=1;const o=t.createView(fM);fM.reset(),oM.layout=a,oM.entries.push({binding:0,resource:this.flipYSampler},{binding:1,resource:o},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}});const u=this.device.createBindGroup(oM);oM.reset(),fM.dimension="2d",fM.mipLevelCount=1,fM.baseArrayLayer=i,fM.arrayLayerCount=1;const d=s.createView(fM);fM.reset(),pM.view=d,pM.loadOp=$R,pM.storeOp=GR,cM.colorAttachments.push(pM);const c=l.beginRenderPass(cM);cM.reset(),pM.reset(),c.setPipeline(e),c.setBindGroup(0,u),c.draw(3,1,0,r),c.end()};d(o,e,r,a,0,!1),d(u,a,0,e,r,!0),YC(this.device,l.finish()),a.destroy()}generateMipmaps(e,t=null){const r=this.get(e),s=r.layers||this._mipmapCreateBundles(e);let i=t;null===i&&(lM.label="mipmapEncoder",i=this.device.createCommandEncoder(lM),lM.reset()),this._mipmapRunBundles(i,s),null===t&&YC(this.device,i.finish()),r.layers=s}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",r=this.getTransferPipeline(e.format,t),s=r.getBindGroupLayout(0),i=[];for(let n=1;n<e.mipLevelCount;n++)for(let a=0;a<e.depthOrArrayLayers;a++){fM.dimension=t,fM.baseMipLevel=n-1,fM.mipLevelCount=1;const o=e.createView(fM);fM.reset(),oM.layout=s,oM.entries.push({binding:0,resource:this.mipmapSampler},{binding:1,resource:o},{binding:2,resource:{buffer:this.noFlipUniformBuffer}});const u=this.device.createBindGroup(oM);oM.reset(),fM.dimension="2d",fM.baseMipLevel=n,fM.mipLevelCount=1,fM.baseArrayLayer=a,fM.arrayLayerCount=1;const l=e.createView(fM);fM.reset();const d=new eM;d.view=l,d.loadOp=$R,d.storeOp=GR;const c=new tM;c.colorAttachments.push(d),dM.colorFormats=[e.format];const h=this.device.createRenderBundleEncoder(dM);dM.reset(),h.setPipeline(r),h.setBindGroup(0,u),h.draw(3,1,0,a),i.push({renderBundles:[h.finish()],passDescriptor:c})}return i}_mipmapRunBundles(e,t){const r=t.length;for(let s=0;s<r;s++){const r=t[s],i=e.beginRenderPass(r.passDescriptor);i.executeBundles(r.renderBundles),i.end()}}}class bM{constructor(){this.texture=null,this.mipLevel=0,this.origin={x:0,y:0,z:0},this.aspect="all"}reset(){this.texture=null,this.mipLevel=0,this.origin.x=0,this.origin.y=0,this.origin.z=0,this.aspect="all"}}class xM{constructor(){this.width=0,this.height=1,this.depthOrArrayLayers=1}reset(){this.width=0,this.height=1,this.depthOrArrayLayers=1}}const TM=new KC,_M=new ZC,vM=new class{constructor(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}reset(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}},NM=new bM,SM=new class{constructor(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},EM=new class{constructor(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},RM=new class{constructor(){this.source=null,this.origin={x:0,y:0},this.flipY=!1}reset(){this.source=null,this.origin.x=0,this.origin.y=0,this.flipY=!1}},wM=new class extends bM{constructor(){super(),this.colorSpace="srgb",this.premultipliedAlpha=!1}reset(){super.reset(),this.colorSpace="srgb",this.premultipliedAlpha=!1}},AM=new nM,CM=new xM,MM={[qr]:"never",[w]:"less",[Hr]:"equal",[A]:"less-equal",[C]:"greater",[M]:"greater-equal",[jr]:"always",[Wr]:"not-equal"},BM=[0,1,3,2,4,5];function LM(e,t,r,s,i,n,a,o,u,l){NM.texture=t,NM.mipLevel=r,NM.origin.z=s,EM.offset=s*n,EM.bytesPerRow=a,EM.rowsPerImage=o,CM.width=u,CM.height=l,e.queue.writeTexture(NM,i.data,EM,CM),NM.reset(),EM.reset(),CM.reset()}class FM{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,r=e.texture,s=e.textureNode,i=r.minFilter+"-"+r.magFilter+"-"+r.wrapS+"-"+r.wrapT+"-"+(r.wrapR||"0")+"-"+r.anisotropy+"-"+(!0===r.isDepthTexture?1:0)+"-"+(null!==r.compareFunction&&null!==s.compareNode?r.compareFunction:0);let n=this._samplerCache.get(i);if(void 0===n){vM.addressModeU=this._convertAddressMode(r.wrapS),vM.addressModeV=this._convertAddressMode(r.wrapT),vM.addressModeW=this._convertAddressMode(r.wrapR),vM.magFilter=this._convertFilterMode(r.magFilter),vM.minFilter=this._convertFilterMode(r.minFilter),vM.mipmapFilter=this._convertMipmapFilterMode(r.minFilter),!r.isDepthTexture||null!==r.compareFunction&&null!==s.compareNode||(vM.magFilter=HA,vM.minFilter=HA,vM.mipmapFilter=HA),vM.magFilter===WA&&vM.minFilter===WA&&vM.mipmapFilter===WA&&(vM.maxAnisotropy=r.anisotropy),r.isDepthTexture&&null!==r.compareFunction&&null!==s.compareNode&&t.hasCompatibility(R.TEXTURE_COMPARE)&&(vM.compare=MM[r.compareFunction]);const e=t.device.createSampler(vM);vM.reset(),n={sampler:e,usedTimes:0},this._samplerCache.set(i,n)}const a=t.get(e);return a.sampler!==n.sampler&&(this._releaseSampler(a),a.samplerKey=i,a.sampler=n.sampler,n.usedTimes++),i}destroySampler(e){this._releaseSampler(this.backend.get(e))}_releaseSampler(e){if(void 0!==e.sampler){const t=this._samplerCache.get(e.samplerKey);t.usedTimes--,0===t.usedTimes&&this._samplerCache.delete(e.samplerKey),e.sampler=void 0,e.samplerKey=void 0}}createDefaultTexture(e){let t;const r=PM(e,this.backend.device);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(r):this._getDefaultTextureGPU(r),this.backend.get(e).texture=t}createTexture(e,t={}){const r=this.backend,s=r.get(e);if(s.initialized){if(!0===s.externalTexture)return;throw new Error("THREE.WebGPUTextureUtils: Texture already initialized.")}if(e.isExternalTexture)return s.texture=e.sourceTexture,void(s.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:i,height:n,depth:a,levels:o}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const u=this._getDimension(e),l=e.internalFormat||t.format||PM(e,r.device);s.format=l;const{samples:c,primarySamples:h,isMSAA:p}=r.utils.getTextureSampleData(e);let g=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(g|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&l!==Sw&&(g|=GPUTextureUsage.RENDER_ATTACHMENT);const m=new nM;if(m.label=e.name,m.size.width=i,m.size.height=n,m.size.depthOrArrayLayers=a,m.mipLevelCount=o,m.sampleCount=h,m.dimension=u,m.format=l,m.usage=g,void 0===l)return d("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(m.textureBindingViewDimension=DC);try{s.texture=r.device.createTexture(m)}catch(t){return d("WebGPURenderer: Failed to create texture with descriptor:",m),void this.createDefaultTexture(e)}if(p){const e=Object.assign({},m);e.label=e.label+"-msaa",e.sampleCount=c,e.mipLevelCount=1,s.msaaTexture=r.device.createTexture(e)}s.initialized=!0,s.textureDescriptorGPU=m}destroyTexture(e,t=!1){const r=this.backend,s=r.get(e);void 0!==s.texture&&!1===t&&!0!==e.isExternalTexture&&s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),r.delete(e)}generateMipmaps(e,t=null){const r=this.backend.get(e);this._generateMipmaps(r.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:r,height:s}=e.getDrawingBufferSize(),i=e.renderer.currentSamples,n=t.colorTexture,a=e.get(n);if(n.width===r&&n.height===s&&n.samples===i)return a.texture;let o=a.texture;return o&&o.destroy(),AM.label="colorBuffer",AM.size.width=r,AM.size.height=s,AM.sampleCount=e.utils.getSampleCount(e.renderer.currentSamples),AM.format=e.utils.getPreferredCanvasFormat(),AM.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,o=e.device.createTexture(AM),AM.reset(),n.source.width=r,n.source.height=s,n.samples=i,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const r=this.backend,s=r.renderer.getCanvasTarget(),{width:i,height:n}=r.getDrawingBufferSize(),a=r.renderer.currentSamples,o=s.depthTexture;if(o.width===i&&o.height===n&&o.samples===a&&o.depth===e&&o.stencil===t)return r.get(o).texture;const u=r.get(o).texture;let l,d;if(t?(l=je,d=!0===r.renderer.reversedDepthBuffer?Y:Ze):e&&(l=He,d=!0===r.renderer.reversedDepthBuffer?Y:S),void 0!==u){if(o.image.width===i&&o.image.height===n&&o.format===l&&o.type===d&&o.samples===a)return u;this.destroyTexture(o)}return o.name="depthBuffer",o.format=l,o.type=d,o.image.width=i,o.image.height=n,o.samples=a,this.createTexture(o,{width:i,height:n}),r.get(o).texture}updateTexture(e,t){const r=this.backend.get(e),s=e.mipmaps,{textureDescriptorGPU:i}=r;if(!e.isRenderTargetTexture&&void 0!==i){if(e.isDataTexture)if(s.length>0)for(let t=0,n=s.length;t<n;t++){const n=s[t];this._copyBufferToTexture(n,r.texture,i,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,r.texture,i,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(const s of e.layerUpdates)this._copyBufferToTexture(t.image,r.texture,i,s,e.flipY,s);e.clearLayerUpdates()}else for(let s=0;s<t.image.depth;s++)this._copyBufferToTexture(t.image,r.texture,i,s,e.flipY,s);else if(e.isCompressedTexture||e.isCompressedArrayTexture)e.isCompressedArrayTexture&&e.layerUpdates.size>0?(this._copyCompressedBufferToTexture(e.mipmaps,r.texture,i,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,r.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,r.texture,i);else if(e.isHTMLTexture){const t=this.backend.device,s=this.backend.renderer.domElement,n=e.image;if("function"!=typeof t.queue.copyElementImageToTexture)return;if(!r.hasPaintCallback)return r.hasPaintCallback=!0,void s.requestPaint();const a=i.size.width,o=i.size.height;2===t.queue.copyElementImageToTexture.length?t.queue.copyElementImageToTexture({source:n},{destination:{texture:r.texture},width:a,height:o}):t.queue.copyElementImageToTexture(n,a,o,{texture:r.texture}),e.flipY&&this._flipY(r.texture,i)}else if(s.length>0)for(let t=0,n=s.length;t<n;t++){const n=s[t];this._copyImageToTexture(n,r.texture,i,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,r.texture,i,0,e.flipY,e.premultiplyAlpha);r.version=e.version}}async copyTextureToBuffer(e,t,r,s,i,n){const a=this.backend.device,o=this.backend.get(e),u=o.texture,l=o.textureDescriptorGPU.format,d=this._getBytesPerTexel(l);let c=s*d;c=256*Math.ceil(c/256),TM.size=(i-1)*c+s*d,TM.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const h=a.createBuffer(TM);TM.reset();const p=a.createCommandEncoder(_M);NM.texture=u,NM.origin.x=t,NM.origin.y=r,NM.origin.z=n,SM.buffer=h,SM.bytesPerRow=c,CM.width=s,CM.height=i,p.copyTextureToBuffer(NM,SM,CM),NM.reset(),SM.reset(),CM.reset();const g=this._getTypedArrayType(l);YC(a,p.finish()),await h.mapAsync(GPUMapMode.READ);const m=h.getMappedRange().slice();return h.destroy(),new g(m)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const r=new N;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,format:e}),this.defaultTexture[e]=t=r}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const r=new U;r.minFilter=B,r.magFilter=B,this.createTexture(r,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=r}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,r){const s=e.images,i=e.mipmaps;for(let n=0;n<6;n++){const a=s[n],o=!0===e.flipY?BM[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,r,o,e.flipY):this._copyImageToTexture(a,t,r,o,e.flipY,e.premultiplyAlpha);for(let s=0;s<i.length;s++){const a=i[s].images[n];a.isDataTexture?this._copyBufferToTexture(a.image,t,r,o,e.flipY,0,s+1):this._copyImageToTexture(a,t,r,o,e.flipY,e.premultiplyAlpha,s+1)}}}_copyImageToTexture(e,t,r,s,i,n,a=0){const o=this.backend.device,u=a>0?e.width:r.size.width,l=a>0?e.height:r.size.height;RM.source=e,RM.flipY=i,wM.texture=t,wM.mipLevel=a,wM.origin.z=s,wM.premultipliedAlpha=n,CM.width=u,CM.height=l;try{o.queue.copyExternalImageToTexture(RM,wM,CM)}catch(e){}finally{RM.reset(),wM.reset(),CM.reset()}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new yM(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,r=0){this._getPassUtils().flipY(e,t,r)}_copyBufferToTexture(e,t,r,s,i,n=0,a=0){const o=this.backend.device,u=e.data,l=this._getBytesPerTexel(r.format),d=e.width*l;NM.texture=t,NM.mipLevel=a,NM.origin.z=s,EM.offset=e.width*e.height*l*n,EM.bytesPerRow=d,CM.width=e.width,CM.height=e.height,o.queue.writeTexture(NM,u,EM,CM),NM.reset(),EM.reset(),CM.reset(),!0===i&&this._flipY(t,r,s)}_copyCompressedBufferToTexture(e,t,r,s=null){const i=this.backend.device,n=this._getBlockData(r.format),a=r.size.depthOrArrayLayers>1,o=s&&s.size>0?s:null;for(let s=0;s<e.length;s++){const u=e[s],l=u.width,d=u.height,c=a?r.size.depthOrArrayLayers:1,h=Math.ceil(l/n.width)*n.byteLength,p=Math.ceil(d/n.height),g=h*p,m=Math.ceil(l/n.width)*n.width,f=p*n.height;if(null!==o)for(const e of o)LM(i,t,s,e,u,g,h,p,m,f);else for(let e=0;e<c;e++)LM(i,t,s,e,u,g,h,p,m,f)}}_getBlockData(e){return e===$w||e===Ww?{byteLength:8,width:4,height:4}:e===Hw||e===jw||e===qw||e===Xw?{byteLength:16,width:4,height:4}:e===Yw||e===Qw?{byteLength:8,width:4,height:4}:e===Kw||e===Zw||e===Jw||e===eA||e===tA||e===rA?{byteLength:16,width:4,height:4}:e===sA||e===iA||e===nA||e===aA?{byteLength:8,width:4,height:4}:e===oA||e===uA?{byteLength:16,width:4,height:4}:e===lA||e===dA?{byteLength:8,width:4,height:4}:e===cA||e===hA||e===pA||e===gA?{byteLength:16,width:4,height:4}:e===mA||e===fA?{byteLength:16,width:5,height:4}:e===yA||e===bA?{byteLength:16,width:5,height:5}:e===xA||e===TA?{byteLength:16,width:6,height:5}:e===_A||e===vA?{byteLength:16,width:6,height:6}:e===NA||e===SA?{byteLength:16,width:8,height:5}:e===EA||e===RA?{byteLength:16,width:8,height:6}:e===wA||e===AA?{byteLength:16,width:8,height:8}:e===CA||e===MA?{byteLength:16,width:10,height:5}:e===BA||e===LA?{byteLength:16,width:10,height:6}:e===FA||e===PA?{byteLength:16,width:10,height:8}:e===UA||e===DA?{byteLength:16,width:10,height:10}:e===OA||e===IA?{byteLength:16,width:12,height:10}:e===VA||e===kA?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=GA;return e===zr?t=zA:e===Gr&&(t=$A),t}_convertFilterMode(e){let t=WA;return e!==B&&e!==$r&&e!==bt||(t=HA),t}_convertMipmapFilterMode(e){return e===bt||e===K?WA:HA}_getBytesPerTexel(e){return e===QR||e===KR||e===ZR||e===JR?1:e===ew||e===tw||e===rw||e===sw||e===iw||e===nw||e===aw||e===ow||e===uw?2:e===lw||e===dw||e===cw||e===hw||e===pw||e===gw||e===mw||e===fw||e===yw||e===bw||e===xw||e===Tw||e===_w||e===vw||e===Nw||e===Sw||e===Ew||e===Rw||e===Gw||e===Vw||e===kw||e===zw?4:e===ww||e===Aw||e===Cw||e===Mw||e===Bw||e===Lw||e===Fw||e===Pw?8:e===Uw||e===Dw||e===Ow?16:void 0}_getTypedArrayType(e){return e===ZR?Uint8Array:e===JR?Int8Array:e===QR?Uint8Array:e===KR?Int8Array:e===nw?Uint8Array:e===aw?Int8Array:e===sw?Uint8Array:e===iw?Int8Array:e===bw?Uint8Array:e===xw?Int8Array:e===mw||e===fw?Uint8Array:e===yw?Int8Array:e===ew?Uint16Array:e===tw?Int16Array:e===hw?Uint16Array:e===pw?Int16Array:e===Mw?Uint16Array:e===Bw?Int16Array:e===rw||e===gw||e===Lw||e===ow?Uint16Array:e===uw?Int16Array:e===vw?Uint16Array:e===Nw?Int16Array:e===Fw?Uint16Array:e===Pw?Int16Array:e===lw?Uint32Array:e===dw?Int32Array:e===cw?Float32Array:e===ww?Uint32Array:e===Aw?Int32Array:e===Cw?Float32Array:e===Uw?Uint32Array:e===Dw?Int32Array:e===Ow?Float32Array:e===Tw||e===_w?Uint8Array:e===Ew||e===Sw||e===Rw?Uint32Array:e===Gw?Float32Array:e===Vw||e===kw?Uint32Array:e===zw?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?FC:LC,t}}function PM(e,t){const r=e.format,s=e.type,i=e.normalized,n=e.colorSpace,a=p.getTransfer(n);let u,l=!1;if(i&&(l=t.features.has(GC.TextureFormatsTier1),!1===l&&d("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(r){case or:case ur:u=a===g?Ww:$w;break;case lr:u=a===g?jw:Hw;break;case dr:u=a===g?Xw:qw;break;case Ir:u=Yw;break;case Vr:u=Qw;break;case W:u=Kw;break;case kr:u=Zw;break;case Ur:u=a===g?rA:tA;break;case Dr:u=eA;break;case Or:u=Jw;break;case fr:case mr:u=a===g?iA:sA;break;case yr:u=a===g?uA:oA;break;case br:u=lA;break;case xr:u=dA;break;case H:u=cA;break;case Tr:u=hA;break;case _r:u=a===g?gA:pA;break;case vr:u=a===g?fA:mA;break;case Nr:u=a===g?bA:yA;break;case Sr:u=a===g?TA:xA;break;case Er:u=a===g?vA:_A;break;case Rr:u=a===g?SA:NA;break;case wr:u=a===g?RA:EA;break;case Ar:u=a===g?AA:wA;break;case Cr:u=a===g?MA:CA;break;case Mr:u=a===g?LA:BA;break;case Br:u=a===g?PA:FA;break;case Lr:u=a===g?DA:UA;break;case Fr:u=a===g?IA:OA;break;case Pr:u=a===g?kA:VA;break;case Re:u=a===g?fw:mw;break;default:o("WebGPURenderer: Unsupported texture format.",r)}else switch(r){case Re:switch(s){case Ie:u=yw;break;case ke:u=l?Pw:Bw;break;case Ge:u=l?Fw:Mw;break;case S:u=Uw;break;case E:u=Dw;break;case Ve:u=a===g?fw:mw;break;case Te:u=Lw;break;case Y:u=Ow;break;default:o("WebGPURenderer: Unsupported texture type with RGBAFormat.",s)}break;case Xe:switch(s){case Je:u=Sw;break;case et:u=Rw;break;default:o("WebGPURenderer: Unsupported texture type with RGBFormat.",s)}break;case $e:switch(s){case Ie:u=KR;break;case ke:u=l?uw:tw;break;case Ge:u=l?ow:ew;break;case S:u=lw;break;case E:u=dw;break;case Ve:u=QR;break;case Te:u=rw;break;case Y:u=cw;break;default:o("WebGPURenderer: Unsupported texture type with RedFormat.",s)}break;case $:switch(s){case Ie:u=iw;break;case ke:u=l?Nw:pw;break;case Ge:u=l?vw:hw;break;case S:u=ww;break;case E:u=Aw;break;case Ve:u=sw;break;case Te:u=gw;break;case Y:u=Cw;break;default:o("WebGPURenderer: Unsupported texture type with RGFormat.",s)}break;case He:switch(s){case Ge:u=Iw;break;case S:u=Vw;break;case Y:u=Gw;break;default:o("WebGPURenderer: Unsupported texture type with DepthFormat.",s)}break;case je:switch(s){case Ze:u=kw;break;case Y:t&&!1===t.features.has(GC.Depth32FloatStencil8)&&o('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),u=zw;break;default:o("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",s)}break;case We:switch(s){case E:u=dw;break;case S:u=lw;break;default:o("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",s)}break;case qe:switch(s){case E:u=Aw;break;case S:u=ww;break;default:o("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",s)}break;case Ft:switch(s){case E:u=Dw;break;case S:u=Uw;break;default:o("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",s)}break;default:o("WebGPURenderer: Unsupported texture format.",r)}return u}const UM=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,DM=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,OM={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class IM extends QS{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(UM);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=DM.exec(r));)s.push({name:i[1],type:i[2]});const n=[];for(let e=0;e<s.length;e++){const{name:t,type:r}=s[e];let i=r;i.startsWith("ptr")?i="pointer":(i.startsWith("texture")&&(i=r.split("<")[0]),i=OM[i]),n.push(new DS(i,t))}const a=e.substring(t[0].length),o=t[3]||"void",u=void 0!==t[1]?t[1]:"";return{type:OM[o]||o,inputs:n,name:u,inputsCode:r,blockCode:a,outputType:o}}throw new Error("THREE.WGSLNodeFunction: Function is not a WGSL code.")})(e);super(t,r,s),this.inputsCode=i,this.blockCode=n,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class VM extends YS{parseFunction(e){return new IM(e)}}const kM={[ai.READ_ONLY]:"read",[ai.WRITE_ONLY]:"write",[ai.READ_WRITE]:"read_write"},GM={[zr]:"repeat",[_e]:"clamp",[Gr]:"mirror"},zM={vertex:LR.VERTEX,fragment:LR.FRAGMENT,compute:LR.COMPUTE},$M={instance:!0,swizzleAssign:!1,storageBuffer:!0},WM={"^^":"tsl_xor"},HM={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},jM={},qM={tsl_xor:new YT("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new YT("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new YT("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new YT("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new YT("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new YT("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new YT("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new YT("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new YT("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new YT("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new YT("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new YT("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),inverse_mat2:new YT("\nfn tsl_inverse_mat2( m : mat2x2<f32> ) -> mat2x2<f32> {\n\n\tlet det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];\n\n\treturn mat2x2<f32>(\n\t\tm[ 1 ][ 1 ], - m[ 0 ][ 1 ],\n\t\t- m[ 1 ][ 0 ], m[ 0 ][ 0 ]\n\t) * ( 1.0 / det );\n\n}\n"),inverse_mat3:new YT("\nfn tsl_inverse_mat3( m : mat3x3<f32> ) -> mat3x3<f32> {\n\n\tlet a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];\n\tlet a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];\n\tlet a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];\n\n\tlet b01 = a22 * a11 - a12 * a21;\n\tlet b11 = - a22 * a10 + a12 * a20;\n\tlet b21 = a21 * a10 - a11 * a20;\n\n\tlet det = a00 * b01 + a01 * b11 + a02 * b21;\n\n\treturn mat3x3<f32>(\n\t\tb01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),\n\t\tb11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),\n\t\tb21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )\n\t) * ( 1.0 / det );\n\n}\n"),inverse_mat4:new YT("\nfn tsl_inverse_mat4( m : mat4x4<f32> ) -> mat4x4<f32> {\n\n\tlet a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];\n\tlet a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];\n\tlet a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];\n\tlet a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];\n\n\tlet b00 = a00 * a11 - a01 * a10;\n\tlet b01 = a00 * a12 - a02 * a10;\n\tlet b02 = a00 * a13 - a03 * a10;\n\tlet b03 = a01 * a12 - a02 * a11;\n\tlet b04 = a01 * a13 - a03 * a11;\n\tlet b05 = a02 * a13 - a03 * a12;\n\tlet b06 = a20 * a31 - a21 * a30;\n\tlet b07 = a20 * a32 - a22 * a30;\n\tlet b08 = a20 * a33 - a23 * a30;\n\tlet b09 = a21 * a32 - a22 * a31;\n\tlet b10 = a21 * a33 - a23 * a31;\n\tlet b11 = a22 * a33 - a23 * a32;\n\n\tlet det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n\treturn mat4x4<f32>(\n\t\ta11 * b11 - a12 * b10 + a13 * b09,\n\t\ta02 * b10 - a01 * b11 - a03 * b09,\n\t\ta31 * b05 - a32 * b04 + a33 * b03,\n\t\ta22 * b04 - a21 * b05 - a23 * b03,\n\t\ta12 * b08 - a10 * b11 - a13 * b07,\n\t\ta00 * b11 - a02 * b08 + a03 * b07,\n\t\ta32 * b02 - a30 * b05 - a33 * b01,\n\t\ta20 * b05 - a22 * b02 + a23 * b01,\n\t\ta10 * b10 - a11 * b08 + a13 * b06,\n\t\ta01 * b08 - a00 * b10 - a03 * b06,\n\t\ta30 * b04 - a31 * b02 + a33 * b00,\n\t\ta21 * b02 - a20 * b04 - a23 * b00,\n\t\ta11 * b07 - a10 * b09 - a12 * b06,\n\t\ta00 * b09 - a01 * b07 + a02 * b06,\n\t\ta31 * b01 - a30 * b03 - a32 * b00,\n\t\ta20 * b03 - a21 * b01 + a22 * b00\n\t) * ( 1.0 / det );\n\n}\n"),biquadraticTexture:new YT("\nfn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new YT("\nfn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},XM={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inverse_mat2:"tsl_inverse_mat2",inverse_mat3:"tsl_inverse_mat3",inverse_mat4:"tsl_inverse_mat4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let YM="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(YM+="diagnostic( off, derivative_uniformity );\n");class QM extends PS{constructor(e,t){super(e,t,new VM),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,r,s,i,n=this.shaderStage){return"fragment"===n?s?i?`textureSample( ${t}, ${t}_sampler, ${r}, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:i?`textureSample( ${t}, ${t}_sampler, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this.generateTextureSampleLevel(e,t,r,"0",s)}generateTextureSampleLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateWrapFunction(e){const t=`tsl_coord_${GM[e.wrapS]}S_${GM[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}`;let r=jM[t];if(void 0===r){const s=[],i=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===zr?(s.push(qM.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===_e?(s.push(qM.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Gr?(s.push(qM.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,d(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",jM[t]=r=new YT(n,s)}return r.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,r){const s=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===s.dimensionsSnippet&&(s.dimensionsSnippet={});let i=s.dimensionsSnippet[r];if(void 0===s.dimensionsSnippet[r]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),u=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=u||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new ku(new Fl(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(s.arrayLayerCount=new ku(new Fl(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new ku(new Fl("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s,i="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,i);return s&&(r=`${r} + vec2<f32>(${s}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${r} ), ${o}, u32( ${n} ), u32( ${i} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${r} ), ${o}, u32( ${i} ) )`)}generateTextureLod(e,t,r,s,i,n="0u"){if(!0===e.isCubeTexture){i&&(r=`${r} + vec3<f32>(${i})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),u=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";i&&(r=`${r} + ${u}<f32>(${i}) / ${u}<f32>( ${o} )`);return r=`${u}<u32>( clamp( floor( ${a}( ${r} ) * ${u}<f32>( ${o} ) ), ${`${u}<f32>( 0 )`}, ${`${u}<f32>( ${o} - ${"vec3"===u?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,r,n,s,null)}generateStorageTextureLoad(e,t,r,s,i,n){let a;return n&&(r=`${r} + ${n}`),a=i?`textureLoad( ${t}, ${r}, ${i} )`:`textureLoad( ${t}, ${r} )`,a}generateTextureLoad(e,t,r,s,i,n){let a;return null===s&&(s="0u"),n&&(r=`${r} + ${n}`),i?a=`textureLoad( ${t}, ${r}, ${i}, u32( ${s} ) )`:(a=`textureLoad( ${t}, ${r}, u32( ${s} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,r,s,i){let n;return n=s?`textureStore( ${t}, ${r}, ${s}, ${i} )`:`textureStore( ${t}, ${r}, ${i} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(R.TEXTURE_COMPARE)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===Y||!1===this.isSampleCompare(e)&&e.minFilter===B&&e.magFilter===B||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,i,"0",n):this._generateTextureSample(e,t,r,s,i,n),a}generateTextureGrad(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${i}, ${s[0]}, ${s[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;o(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,r,s,i,n){const a=!0===e.isDepthTexture?"":`${s}, `;return i?n?`textureGather( ${a}${t}, ${t}_sampler, ${r}, ${i}, ${n} )`:`textureGather( ${a}${t}, ${t}_sampler, ${r}, ${i} )`:n?`textureGather( ${a}${t}, ${t}_sampler, ${r}, ${n} )`:`textureGather( ${a}${t}, ${t}_sampler, ${r})`}generateTextureGatherCompare(e,t,r,s,i,n){return i?n?`textureGatherCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s})`:n?`textureGatherCompare( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${r}, ${s})`}generateTextureLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?i?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s,i):this.generateTextureLod(e,t,r,i,n,s)}generateTextureBias(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return i?n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;o(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,r=e.type;return"texture"===r||"cubeTexture"===r||"cubeDepthTexture"===r||"storageTexture"===r||"texture3D"===r?t:"buffer"===r||"storageBuffer"===r||"indirectStorageBuffer"===r?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=WM[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(d("WebGPURenderer: Atomic operations are only supported in compute shaders."),ai.READ_WRITE):ai.READ_ONLY:e.access}getStorageAccess(e,t){return kM[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,u=o.name,l=this.getBindGroupArray(u,r);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);"texture"===t||"storageTexture"===t?s=!0===e.value.is3DTexture?new QE(i.name,i.node,o,n):new XE(i.name,i.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?s=new YE(i.name,i.node,o,n):"texture3D"===t&&(s=new QE(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.mipLevel=s.store?e.mipLevel:0,s.setVisibility(zM[r]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===s.store||null!==e.gatherNode){const e=new $C(`${i.name}_sampler`,i.node,o);e.setVisibility(zM[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let u=n.buffer;if(void 0===u){u=new("buffer"===t?GE:jC)(e,o),n.buffer=u}u.setVisibility(u.getVisibility()|zM[r]),l.push(u),a=u,i.name=s||"NodeBuffer_"+i.id}else{let e=this.uniformGroups[u];void 0===e&&(e=new WE(u,o),e.setVisibility(LR.VERTEX|LR.FRAGMENT|LR.COMPUTE),this.uniformGroups[u]=e),-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(i,t);const r=a.name;e.uniforms.some(e=>e.name===r)||e.addUniform(a)}n.uniformGPU=a}return i}getBuiltin(e,t,r,s=this.shaderStage){const i=this.builtins[s]||(this.builtins[s]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:r}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${s.join(", ")} ) -> ${this.getType(t.type)} {\n${r.vars}\n${r.code}\n`;return r.result&&(i+=`\treturn ${r.result};\n`),i+="\n}\n",i}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],r=this.directives[e];if(void 0!==r)for(const e of r)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],r=this.builtins[e];if(void 0!==r)for(const{name:e,property:s,type:i}of r.values())t.push(`@builtin( ${e} ) ${s} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,r,s){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:r,bufferCount:s}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:r,bufferType:s,bufferCount:i}of this.scopedArrays.values()){const n=this.getType(s);t.push(`var<${r}> ${e}: array< ${n}, ${i} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const r=this.getAttributesArray();for(let e=0,s=r.length;e<s;e++){const s=r[e],i=s.name,n=this.getType(s.type);t.push(`@location( ${e} ) ${i} : ${n}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const r of e.members){const s=e.output?"@location( "+r.index+" ) ":"";let i=this.getType(r.type);r.atomic&&(i="atomic< "+i+" >"),t.push(`\t${s+r.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const r=this.structs[e];if(r.length>0){const e=[];for(const t of r){let r=`struct ${t.name} {\n`;r+=this.getStructMembers(t),r+="\n};",e.push(r)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,r=null,s=""){let i=`var${s} ${t} : `;return i+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),i}getVars(e,t=!1){let r="";t&&(r="<private>");const s=[],i=this.vars[e];if(void 0!==i)for(const e of i)s.push(`${this.getVar(e.type,e.name,e.count,r)};`);return t?s.join("\n"):`\n\t${s.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];let i=0;for(let n=0;n<r.length;n++){const a=r[n];if(a.needsInterpolation){let e=`@location( ${i++} )`;if(a.interpolationType){const t=null!==a.interpolationSampling?`, ${a.interpolationSampling} )`:" )";e+=` @interpolate( ${a.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(a.type)&&(e+=" @interpolate(flat, either)");t.push(`${e} ${a.name} : ${this.getType(a.type)}`)}else"vertex"===e&&!1===s.includes(a)&&s.push(a)}}const r=this.getBuiltins(e);r&&t.push(r);const s=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+s):s}isCustomStruct(e){const t=e.value,r=e.node,s=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==r.structTypeNode,i=r.value&&r.value.array&&"number"==typeof r.value.itemSize&&r.value.array.length>r.value.itemSize;return s&&!i}getUniforms(e){const t=this.renderer.backend,r=this.uniforms[e],s=[],i=[],n=[],a={};for(const n of r){const r=n.groupNode.name,o=this.bindingsIndexes[r];if("texture"===n.type||"cubeTexture"===n.type||"cubeDepthTexture"===n.type||"storageTexture"===n.type||"texture3D"===n.type){const r=n.node,i=r.value;let a;(!0===i.isCubeTexture||!1===this.isUnfilterable(i)&&!0!==r.isStorageTextureNode||null!==r.gatherNode)&&(this.isSampleCompare(i)&&null!==r.compareNode?s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler_comparison;`):s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler;`));let u="";const{primarySamples:l}=t.utils.getTextureSampleData(i);if(l>1&&(u="_multisampled"),!0===i.isCubeTexture&&!0===i.isDepthTexture)a="texture_depth_cube";else if(!0===i.isCubeTexture)a="texture_cube<f32>";else if(!0===i.isDepthTexture)a=t.compatibilityMode&&null===i.compareFunction?`texture${u}_2d<f32>`:`texture_depth${u}_2d${!0===i.isArrayTexture?"_array":""}`;else if(!0===n.node.isStorageTextureNode){const r=PM(i,t.device),s=this.getStorageAccess(n.node,e),o=n.node.value.is3DTexture,u=n.node.value.isArrayTexture;a=`texture_storage_${o?"3d":"2d"+(u?"_array":"")}<${r}, ${s}>`}else if(!0===i.isArrayTexture||!0===i.isDataArrayTexture||!0===i.isCompressedArrayTexture)a="texture_2d_array<f32>";else if(!0===i.is3DTexture||!0===i.isData3DTexture)a="texture_3d<f32>";else{a=`texture${u}_2d<${this.getComponentTypeFromTexture(i).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name} : ${a};`)}else if("buffer"===n.type||"storageBuffer"===n.type||"indirectStorageBuffer"===n.type){const t=n.node,r=this.getType(t.getNodeType(this)),s=t.bufferCount,a=s>0&&"buffer"===n.type?", "+s:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(n))i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${u}> ${n.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${a} >`;i.push(this._getWGSLStructBinding(n.name,e,u,o.binding++,o.group))}}else{const e=n.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const r=[];for(const e of t.uniforms){const t=e.getType(),s=this.getType(this.getVectorType(t));r.push(`\t${e.name} : ${s}`)}let s=this.uniformGroupsBindings[e];void 0===s&&(s={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=s),a[e]={index:s.index,id:s.id,snippets:r}}}}}for(const e in a){const t=a[e];n.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...s,...i,...n].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=this.allowGlobalVariables,s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t,r),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,u=void 0!==o&&!0===o.isOutputStructNode;for(const e of n){const r=this.getFlowData(e),n=e.name;if(n&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${n}\n`),i+=`${r.code}\n\t`,e===a&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.builtinClipSpace = ${r.result};`;else if("fragment"===t)if(u)s.returnType=o.getNodeType(this),s.structs+="var<private> output : "+s.returnType+";",i+=`return ${r.result};`;else{let e=`\t@location( 0 ) color: ${this.getType(this.getOutputType())}`;const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar<private> output : OutputStruct;",i+=`output.color = ${this.format(r.result,a.getNodeType(this),this.getOutputType())};\n\n\treturn output;`}}s.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,r){return`select( ${r}, ${t}, ${e} )`}getType(e){return HM[e]||e}isAvailable(e){let t=$M[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),$M[e]=t),t}_getWGSLMethod(e){return void 0!==qM[e]&&this._include(e),XM[e]}_include(e){const t=qM[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${YM}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[r,s,i]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${r}, ${s}, ${i} )\nfn main( ${e.attributes} ) {\n\n\t// local vars\n\t${this.allowGlobalVariables?"":e.vars}\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${r} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${r} * numWorkgroups.x ) * ( ${s} * numWorkgroups.y );\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}const KM=new KC,ZM=new ZC,JM=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&JM.set(Float16Array,["float16"]);const eB=new Map([[xt,["float16"]]]),tB=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class rB{constructor(e){this.backend=e}createAttribute(e,t){const r=this._getBufferAttribute(e),s=this.backend,i=s.get(r);let n=i.buffer;if(void 0===n){const a=s.device;let o,u=r.array;if(!1===e.normalized)if(u.constructor===Int16Array||u.constructor===Int8Array)u=new Int32Array(u);else if((u.constructor===Uint16Array||u.constructor===Uint8Array)&&(u=new Uint32Array(u),t&GPUBufferUsage.INDEX))for(let e=0;e<u.length;e++)65535===u[e]&&(u[e]=4294967295);if(r.array=u,(r.isStorageBufferAttribute||r.isStorageInstancedBufferAttribute)&&3===r.itemSize)o=4;else if(r.itemSize>1&&r.itemSize*u.BYTES_PER_ELEMENT%4!=0){const e=r.itemSize*u.BYTES_PER_ELEMENT;o=4*Math.floor((e+3)/4)/u.BYTES_PER_ELEMENT}if(void 0!==o){const e=r.itemSize,t=new u.constructor(r.count*o);for(let s=0;s<r.count;s++)t.set(u.subarray(s*e,s*e+e),s*o);(r.isStorageBufferAttribute||r.isStorageInstancedBufferAttribute)&&(r.itemSize=o,r.array=t),u=t,i._itemSize=e,i._paddedItemSize=o}const l=u.byteLength,d=l+(4-l%4)%4;KM.label=r.name,KM.size=d,KM.usage=t,KM.mappedAtCreation=!0,n=a.createBuffer(KM),KM.reset(),new u.constructor(n.getMappedRange()).set(u),n.unmap(),i.buffer=n}}updateAttribute(e){const t=this._getBufferAttribute(e),r=this.backend,s=r.device,i=r.get(t),n=r.get(t).buffer;let a=t.array;const o=i._itemSize,u=i._paddedItemSize;if(void 0!==u){a=new a.constructor(t.count*u);for(let e=0;e<t.count;e++)a.set(t.array.subarray(e*o,e*o+o),e*u);(t.isStorageBufferAttribute||t.isStorageInstancedBufferAttribute)&&(t.array=a)}const l=t.updateRanges;if(0===l.length)s.queue.writeBuffer(n,0,a,0);else{const e=Qr(a),r=e?1:a.BYTES_PER_ELEMENT;for(let t=0,i=l.length;t<i;t++){const i=l[t];let d,c;if(void 0!==u){const e=Math.floor(i.start/o);d=e*u*r,c=(Math.ceil((i.start+i.count)/o)-e)*u*r}else d=i.start*r,c=i.count*r;const h=d*(e?a.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(n,h,a,d,c)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),r=new Map;for(let e=0;e<t.length;e++){const s=t[e],i=s.array.BYTES_PER_ELEMENT,n=this._getBufferAttribute(s);let a=r.get(n);if(void 0===a){let e,t;!0===s.isInterleavedBufferAttribute?(e=s.data.stride*i,t=s.data.isInstancedInterleavedBuffer?kC:VC):(e=s.itemSize*i,t=s.isInstancedBufferAttribute?kC:VC,s.itemSize>1&&e%4!=0&&(e=4*Math.floor((e+3)/4))),!1!==s.normalized||s.array.constructor!==Int16Array&&s.array.constructor!==Uint16Array||(e=4),a={arrayStride:e,attributes:[],stepMode:t},r.set(n,a)}const o=this._getVertexFormat(s),u=!0===s.isInterleavedBufferAttribute?s.offset*i:0;a.attributes.push({shaderLocation:e,offset:u,format:o})}return Array.from(r.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,r=0,s=-1){const i=this.backend,n=i.device,a=i.get(this._getBufferAttribute(e)).buffer,o=-1===s?a.size-r:s;let u;if(null!==t&&t.isReadbackBuffer){const e=i.get(t);if(!0===t._mapped)throw new Error("THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,void 0===e.readBufferGPU){KM.label=`${t.name}_readback`,KM.size=t.maxByteLength,KM.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,u=n.createBuffer(KM),KM.reset();const r=()=>{t.buffer=null,t._mapped=!1,u.unmap()},s=()=>{t.buffer=null,t._mapped=!1,u.destroy(),i.delete(t),t.removeEventListener("release",r),t.removeEventListener("dispose",s)};t.addEventListener("release",r),t.addEventListener("dispose",s),e.readBufferGPU=u}else u=e.readBufferGPU}else KM.label=`${e.name}_readback`,KM.size=o,KM.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,u=n.createBuffer(KM),KM.reset();ZM.label=`readback_encoder_${e.name}`;const l=n.createCommandEncoder(ZM);ZM.reset(),l.copyBufferToBuffer(a,r,u,0,o);if(YC(n,l.finish()),await u.mapAsync(GPUMapMode.READ,0,o),null===t){const e=u.getMappedRange(0,o).slice();return u.destroy(),e}if(t.isReadbackBuffer)return t.buffer=u.getMappedRange(0,o),t;{const e=u.getMappedRange(0,o);return new Uint8Array(t).set(new Uint8Array(e)),u.destroy(),t}}_getVertexFormat(e){const{itemSize:t,normalized:r}=e,s=e.array.constructor,i=e.constructor;let n;if(1===t)n=tB.get(s);else{const e=(eB.get(i)||JM.get(s))[r?1:0];if(e){const r=s.BYTES_PER_ELEMENT*t,i=4*Math.floor((r+3)/4)/s.BYTES_PER_ELEMENT;if(i%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${i}`}}return n||o("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}const sB=new QC,iB=new KC,nB=new aM;class aB{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class oB{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,r=t.device,s=t.get(e);if(s.layout)return s.layout.layoutGPU;const i=this._createLayoutEntries(e),n=Gs(JSON.stringify(i));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new aB(r.createBindGroupLayout({entries:i})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,s.layout=a,s.layoutKey=n,a.layoutGPU}createBindings(e,t,r,s=0){const{backend:i}=this,n=i.get(e),a=this.createBindingsLayout(e);let o;r>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[r]===s&&(o=n.groups[r])),void 0===o&&(o=this.createBindGroup(e,a),r>0&&(n.groups[r]=o,n.versions[r]=s)),n.group=o}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer,n=e.updateRanges;if(0===n.length)r.queue.writeBuffer(i,0,s,0);else{const e=Qr(s),t=e?1:s.BYTES_PER_ELEMENT;let a=n[0].start;for(let o=0,u=n.length;o<u;o++){const u=n[o],l=n[o+1],d=u.start+u.count;if(void 0!==l&&l.start===d)continue;const c=a*t,h=(d-a)*t,p=c*(e?s.BYTES_PER_ELEMENT:1);r.queue.writeBuffer(i,p,s,c,h),void 0!==l&&(a=l.start)}}}createBindGroupIndex(e,t){const r=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0];iB.label="bindingCameraIndex_"+i,iB.size=16,iB.usage=s;const n=r.createBuffer(iB);iB.reset(),r.queue.writeBuffer(n,0,e,0),sB.label="bindGroupCameraIndex_"+i,sB.layout=t,sB.entries.push({binding:0,resource:{buffer:n}});const a=r.createBindGroup(sB);return sB.reset(),a}createBindGroup(e,t){const r=this.backend,s=r.device;let i=0;sB.label="bindGroup_"+e.name,sB.layout=t;for(const t of e.bindings){if(t.isUniformBuffer){const e=r.get(t);sB.entries.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=r.get(t.attribute).buffer;sB.entries.push({binding:i,resource:{buffer:e}})}else if(t.isSampledTexture){const e=r.get(t.texture);let n;if(void 0!==e.externalTexture)n=s.importExternalTexture({source:e.externalTexture});else{const r=t.store?1:e.texture.mipLevelCount,s=t.store?t.mipLevel:0;let i=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${r}-${s}`,n=e[i],void 0===n){const a=IC;let o;o=t.isSampledCubeTexture?DC:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?UC:t.isSampledTexture3D?OC:PC,nB.aspect=a,nB.dimension=o,nB.mipLevelCount=r,nB.baseMipLevel=s,n=e[i]=e.texture.createView(nB),nB.reset()}}sB.entries.push({binding:i,resource:n})}else if(t.isSampler){const e=r.get(t);sB.entries.push({binding:i,resource:e.sampler})}i++}const n=s.createBindGroup(sB);return sB.reset(),n}_createLayoutEntries(e){const t=[];let r=0;for(const s of e.bindings){const e=this.backend,i={binding:r,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const e={};s.isStorageBuffer&&(s.visibility&LR.COMPUTE&&(s.access===ai.READ_WRITE||s.access===ai.WRITE_ONLY)?e.type=TC:e.type=_C),i.buffer=e}else if(s.isSampledTexture&&s.store){const e={};e.format=this.backend.get(s.texture).texture.format;const t=s.access;e.access=t===ai.READ_WRITE?SC:t===ai.WRITE_ONLY?vC:NC,s.texture.isArrayTexture?e.viewDimension=UC:s.texture.is3DTexture&&(e.viewDimension=OC),i.storageTexture=e}else if(s.isSampledTexture){const t={},{primarySamples:r}=e.utils.getTextureSampleData(s.texture);if(r>1&&(t.multisampled=!0,s.texture.isDepthTexture||(t.sampleType=AC)),s.texture.isDepthTexture)e.compatibilityMode&&null===s.texture.compareFunction?t.sampleType=AC:t.sampleType=CC;else{const e=s.texture.type;e===E?t.sampleType=MC:e===S?t.sampleType=BC:e===Y&&(this.backend.hasFeature("float32-filterable")?t.sampleType=wC:t.sampleType=AC)}s.isSampledCubeTexture?t.viewDimension=DC:s.texture.isArrayTexture||s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?t.viewDimension=UC:s.isSampledTexture3D&&(t.viewDimension=OC),i.texture=t}else if(s.isSampler){const t={};s.texture.isDepthTexture&&(null!==s.texture.compareFunction&&null!==s.textureNode.compareNode&&e.hasCompatibility(R.TEXTURE_COMPARE)?t.type=RC:t.type=EC),i.sampler=t}else o(`WebGPUBindingUtils: Unsupported binding "${s}".`);t.push(i),r++}return t}deleteBindGroupData(e){const{backend:t}=this,r=t.get(e);r.layout&&(r.layout.usedTimes--,0===r.layout.usedTimes&&this._bindGroupLayoutCache.delete(r.layoutKey),r.layout=void 0,r.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class uB{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}const lB=new class{constructor(){this.label="",this.layout=null,this.compute=null}reset(){this.label="",this.layout=null,this.compute=null}},dB=new class{constructor(){this.label="",this.bindGroupLayouts=null}reset(){this.label="",this.bindGroupLayouts=null}},cB=new JC,hB=new rM;class pB{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:r,material:s,geometry:i,pipeline:n}=e,{vertexProgram:a,fragmentProgram:u}=n,l=this.backend,d=l.device,c=l.utils,h=l.get(n),p=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:r}=e.layout;p.push(r)}const g=l.attributeUtils.createShaderVertexBuffers(e);let m;s.blending===re||s.blending===tt&&!1===s.transparent||(m=this._getBlending(s));let f={};!0===s.stencilWrite&&(f={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const y=this._getColorWriteMask(s),b=[];if(null!==e.context.textures){const t=e.context.textures,r=e.context.mrt;for(let e=0;e<t.length;e++){const s=t[e],i=c.getTextureFormatGPU(s);let n;if(null!==r)if(!0!==this.backend.compatibilityMode){const e=r.getBlendMode(s.name);e.blending===nt?n=m:e.blending!==re&&(n=this._getBlending(e))}else v("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),n=m;else n=m;b.push({format:i,blend:n,writeMask:y})}}else{const t=c.getCurrentColorFormat(e.context);b.push({format:t,blend:m,writeMask:y})}const x=l.get(a).module,T=l.get(u).module,_=this._getPrimitiveState(r,i,s),N=this._getDepthCompare(s),S=c.getCurrentDepthStencilFormat(e.context),E=this._getSampleCount(e.context);dB.bindGroupLayouts=p;const R=d.createPipelineLayout(dB);dB.reset(),hB.label=`renderPipeline_${s.name||s.type}_${s.id}`,hB.vertex=Object.assign({},x,{buffers:g}),hB.fragment=Object.assign({},T,{targets:b}),hB.primitive=_,hB.multisample.count=E,hB.multisample.alphaToCoverageEnabled=s.alphaToCoverage&&E>1,hB.layout=R;const w={},A=e.context.depth,C=e.context.stencil;!0!==A&&!0!==C||(!0===A&&(w.format=S,w.depthWriteEnabled=s.depthWrite,w.depthCompare=N),!0===C&&(w.stencilFront=f,w.stencilBack=f,w.stencilReadMask=s.stencilFuncMask,w.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&_.topology===BR&&(w.depthBias=s.polygonOffsetUnits,w.depthBiasSlopeScale=s.polygonOffsetFactor,w.depthBiasClamp=0),hB.depthStencil=w),d.pushErrorScope("validation");const M=[{program:a,module:x.module},{program:u,module:T.module}],B=hB.label;if(null===t)h.pipeline=d.createRenderPipeline(hB),hB.reset(),d.popErrorScope().then(e=>{null!==e&&(h.error=!0,o(`WebGPURenderer: Render pipeline creation failed (${B}): ${e.message}`),this._reportShaderDiagnostics(M,B))});else{const e=new Promise(async e=>{try{let e=null,t=null;try{t=d.createRenderPipelineAsync(hB)}catch(t){e=t}if(hB.reset(),null!==t)try{h.pipeline=await t}catch(t){e=t}const r=await d.popErrorScope();if(null!==r||null!==e){h.error=!0;const t=r&&r.message||e&&e.message||"unknown";o(`WebGPURenderer: Async render pipeline creation failed (${B}): ${t}`),await this._reportShaderDiagnostics(M,B)}}finally{e()}});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a=s.getCurrentColorFormats(e),o=this._getSampleCount(e);cB.label=t,cB.colorFormats=a,cB.depthStencilFormat=n,cB.sampleCount=o;const u=i.createRenderBundleEncoder(cB);return cB.reset(),u}createComputePipeline(e,t){const r=this.backend,s=r.device,i=r.get(e.computeProgram).module,n=r.get(e),a=[];for(const e of t){const t=r.get(e),{layoutGPU:s}=t.layout;a.push(s)}const u=e.computeProgram,l=`computePipeline_${u.stage}${u.name?`_${u.name}`:""}`;s.pushErrorScope("validation"),dB.bindGroupLayouts=a;const d=s.createPipelineLayout(dB);dB.reset(),lB.label=l,lB.compute=i,lB.layout=d,n.pipeline=s.createComputePipeline(lB),lB.reset(),s.popErrorScope().then(e=>{null!==e&&(n.error=!0,o(`WebGPURenderer: Compute pipeline creation failed (${l}): ${e.message}`),this._reportShaderDiagnostics([{program:u,module:i.module}],l))})}async _reportShaderDiagnostics(e,t){for(const{program:r,module:s}of e){const e=await s.getCompilationInfo();if(0===e.messages.length)continue;const i=r.code.split("\n");for(const s of e.messages){const e=s.lineNum>0?` at line ${s.lineNum}${s.linePos>0?`:${s.linePos}`:""}`:"",n=`WebGPURenderer [${t} / ${r.stage} ${s.type}]${e}: ${s.message}`;let a="";s.lineNum>0&&s.lineNum<=i.length&&(a=`\n ${i[s.lineNum-1]}`,s.linePos>0&&(a+=`\n ${" ".repeat(s.linePos-1)}^`)),("error"===s.type?o:d)(n+a)}}}_getBlending(e){let t,r;const s=e.blending,i=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(s===Et){const s=null!==e.blendSrcAlpha?e.blendSrcAlpha:i,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,u=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},r={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(u)}}else{const i=(e,s,i,n)=>{t={srcFactor:e,dstFactor:s,operation:nC},r={srcFactor:i,dstFactor:n,operation:nC}};if(e.premultipliedAlpha)switch(s){case tt:i(qA,KA,qA,KA);break;case Kt:i(qA,qA,qA,qA);break;case Qt:i(jA,YA,jA,qA);break;case Yt:i(ZA,KA,jA,qA)}else switch(s){case tt:i(QA,KA,qA,KA);break;case Kt:i(QA,qA,qA,qA);break;case Qt:o(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case Yt:o(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};o("WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Rt:t=jA;break;case Ht:t=qA;break;case Wt:t=XA;break;case kt:t=YA;break;case rt:t=QA;break;case st:t=KA;break;case zt:t=ZA;break;case Vt:t=JA;break;case Gt:t=eC;break;case It:t=tC;break;case $t:t=rC;break;case 211:t=sC;break;case 212:t=iC;break;default:o("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case is:t=FR;break;case ss:t=kR;break;case rs:t=PR;break;case ts:t=DR;break;case es:t=UR;break;case Jr:t=VR;break;case Zr:t=OR;break;case Kr:t=IR;break;default:o("WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case hs:t=hC;break;case cs:t=pC;break;case ds:t=gC;break;case ls:t=mC;break;case us:t=fC;break;case os:t=yC;break;case as:t=bC;break;case ns:t=xC;break;default:o("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case it:t=nC;break;case Ot:t=aC;break;case Dt:t=oC;break;case gs:t=uC;break;case ps:t=lC;break;default:o("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?XR:YR);let n=r.side===F;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(n=!n),s.frontFace=!0===n?HR:WR,s.cullMode=r.side===P?jR:qR,s}_getColorWriteMask(e){return!0===e.colorWrite?cC:dC}_getDepthCompare(e){let t;if(!1===e.depthTest)t=kR;else{const r=this.backend.parameters.reversedDepthBuffer?ar[e.depthFunc]:e.depthFunc;switch(r){case nr:t=FR;break;case ir:t=kR;break;case sr:t=PR;break;case rr:t=DR;break;case tr:t=UR;break;case er:t=VR;break;case Jt:t=OR;break;case Zt:t=IR;break;default:o("WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class gB{constructor(){this.label="",this.type=void 0,this.count=0}reset(){this.label="",this.type=void 0,this.count=0}}const mB=new KC,fB=new ZC,yB=new gB;class bB extends ER{constructor(e,t,r=2048){super(r),this.device=e,this.type=t,yB.label=`queryset_global_timestamp_${t}`,yB.type="timestamp",yB.count=this.maxQueries,this.querySet=this.device.createQuerySet(yB),yB.reset();const s=8*this.maxQueries;mB.label=`buffer_timestamp_resolve_${t}`,mB.size=s,mB.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(mB),mB.reset(),mB.label=`buffer_timestamp_result_${t}`,mB.size=s,mB.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(mB),mB.reset()}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return v(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,r=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const s=this.device.createCommandEncoder(fB);s.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),s.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,r);const i=s.finish();if(YC(this.device,i),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,r),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,r)),a={},o=[];for(const[t,r]of e){const e=t.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===o.includes(s)&&o.push(s),void 0===a[s]&&(a[s]=0);const i=n[r],u=n[r+1],l=Number(u-i)/1e6;this.timestamps.set(t,l),a[s]+=l}const u=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=u,this.frames=o,u}catch(e){return o("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){o("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){o("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class xB{constructor(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}reset(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}}const TB={r:0,g:0,b:0,a:1},_B=new KC,vB=new ZC,NB=new class{constructor(){this.label="",this.timestampWrites=void 0}reset(){this.label="",this.timestampWrites=void 0}},SB=new gB,EB=new iM,RB=new class{constructor(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}reset(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}},wB=new bM,AB=new bM,CB=new aM,MB=new xM;class BB extends oR{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new XC(this),this.attributeUtils=new rB(this),this.bindingUtils=new oB(this),this.capabilities=new uB(this),this.pipelineUtils=new pB(this),this.textureUtils=new FM(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[R.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const s={powerPreference:t.powerPreference,featureLevel:"compatibility",xrCompatible:e.xr.enabled},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(s):null;if(null===i)throw new Error("THREE.WebGPUBackend: Unable to create WebGPU adapter.");const n=Object.values(GC),a=[];for(const e of n)i.features.has(e)&&a.push(e);const o={requiredFeatures:a,requiredLimits:t.requiredLimits};r=await i.requestDevice(o)}else r=t.device;this.compatibilityMode=!r.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),r.lost.then(t=>{if("destroyed"===t.reason)return;const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)}),r.onuncapturederror=t=>{const r=t.error,s=r&&r.constructor?r.constructor.name:"GPUError",i=r&&r.message||"Unknown uncaptured GPU error";e.onError({api:"WebGPU",type:s,message:i,originalEvent:t})},this.device=r,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(GC.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,r=null){this.set(e.texture,{texture:t,format:t.format,externalTexture:!0,xrViewDescriptors:r,initialized:!0})}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let r=t.context;if(void 0===r){const s=this.parameters;r=!0===e.isDefaultCanvasTarget&&void 0!==s.context?s.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${_t} webgpu`);const i=s.alpha?"premultiplied":"opaque",n=s.outputType===Te?"extended":"standard";r.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:n}}),t.context=r}return r}get coordinateSystem(){return h}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,r=0,s=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,r,s)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),r=this.get(t),s=e.currentSamples;let i=r.descriptor;if(void 0===i||r.samples!==s){if(i=new tM,i.colorAttachments.push(new eM),!0===e.depth||!0===e.stencil){const t=new xB;t.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),i.depthStencilAttachment=t}const t=i.colorAttachments[0];s>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,r.descriptor=i,r.samples=s}const n=i.colorAttachments[0];return s>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),i}_isRenderCameraDepthArray(e){const t=e.camera;return e.depthTexture&&!0===e.depthTexture.isArrayTexture&&null!==t&&!0===t.isArrayCamera}_hasExternalTexture(e){const t=e.textures;if(null===t)return!1;for(let e=0;e<t.length;e++)if(!0===this.get(t[e]).externalTexture)return!0;return!1}_createExternalTextureViews(e,t){const r=[],s=e.camera;if(t.xrViewDescriptors&&null!==s&&!0===s.isArrayCamera)for(let e=0;e<t.xrViewDescriptors.length;e++)r.push({view:t.texture.createView(t.xrViewDescriptors[e]),resolveTarget:void 0,depthSlice:void 0});else r.push({view:t.texture.createView({dimension:PC,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1}),resolveTarget:void 0,depthSlice:void 0});return r}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r),i=this._hasExternalTexture(e);let n=s.descriptors;(void 0===n||s.width!==r.width||s.height!==r.height||s.samples!==r.samples||i)&&(n={},s.descriptors=n);const a=e.getCacheKey();let o=n[a];if(void 0===o||i){const t=e.textures,i=[];let u;const l=this._isRenderCameraDepthArray(e);for(let s=0;s<t.length;s++){const n=this.get(t[s]);if(!0!==n.externalTexture){if(CB.label=`colorAttachment_${s}`,CB.baseMipLevel=e.activeMipmapLevel,CB.mipLevelCount=1,CB.baseArrayLayer=e.activeCubeFace,CB.arrayLayerCount=1,CB.dimension=PC,r.isRenderTarget3D)u=e.activeCubeFace,CB.baseArrayLayer=0,CB.dimension=OC;else if(r.isRenderTarget&&t[s].image.depth>1)if(!0===l){const t=e.camera.cameras;for(let e=0;e<t.length;e++){CB.baseArrayLayer=e,CB.arrayLayerCount=1,CB.dimension=PC;const t=n.texture.createView(CB);i.push({view:t,resolveTarget:void 0,depthSlice:void 0})}}else CB.dimension=UC;if(!0!==l){const e=n.texture.createView(CB);let t,r;void 0!==n.msaaTexture?(t=n.msaaTexture.createView(),r=e):(t=e,r=void 0),i.push({view:t,resolveTarget:r,depthSlice:u})}CB.reset()}else i.push(...this._createExternalTextureViews(e,n))}const d=[];for(let e=0;e<i.length;e++){const t=i[e],r=new eM;r.view=t.view,r.depthSlice=t.depthSlice,r.resolveTarget=t.resolveTarget,d.push(r)}if(o={textureViews:i,colorAttachments:d,descriptor:new tM},e.depth){const t=this.get(e.depthTexture);(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(CB.dimension=PC,CB.arrayLayerCount=1,CB.baseArrayLayer=e.activeCubeFace);const r=new xB;r.view=t.texture.createView(CB),o.depthStencilAttachment=r,CB.reset()}n[a]=o,s.width=r.width,s.height=r.height,s.samples=r.samples,s.activeMipmapLevel=e.activeMipmapLevel,s.activeCubeFace=e.activeCubeFace}const u=o.descriptor;u.reset();for(let e=0;e<o.colorAttachments.length;e++){const r=o.colorAttachments[e];let s={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(s=t.clearValue),r.loadOp=t.loadOp||zR,r.storeOp=t.storeOp||GR,r.clearValue=s,u.colorAttachments.push(r)}return o.depthStencilAttachment&&(u.depthStencilAttachment=o.depthStencilAttachment),u}beginRender(e){const t=this.get(e),r=this.device,s=e.occlusionQueryCount;let i,n;s>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,SB.label=`occlusionQuerySet_${e.id}`,SB.type="occlusion",SB.count=s,i=r.createQuerySet(SB),SB.reset(),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(s),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:zR}),this.initTimestampQuery(Pt.RENDER,this.getTimestampUID(e),n),n.occlusionQuerySet=i;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let r=0;r<t.length;r++){const s=t[r];e.clearColor?(0===r?s.clearValue=e.clearColorValue:(TB.r=0,TB.g=0,TB.b=0,TB.a=1,s.clearValue=TB),s.loadOp=$R):s.loadOp=zR,s.storeOp=GR}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=$R):t.loadOp=zR,t.storeOp=GR}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=$R):a.depthLoadOp=zR,a.depthStoreOp=GR),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=$R):a.stencilLoadOp=zR,a.stencilStoreOp=GR),vB.label="renderContext_"+e.id;const o=r.createCommandEncoder(vB);if(vB.reset(),!0===this._isRenderCameraDepthArray(e)){const r=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===r.length?this._updateArrayCameraLayerDescriptors(e,t,r):this._createArrayCameraLayerDescriptors(e,t,n,r),t.bundleEncoders=[],t.bundleSets=[];for(let s=0;s<r.length;s++){const r=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+s),i={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(r),t.bundleSets.push(i)}t.currentPass=null}else{const r=o.beginRenderPass(n);t.currentPass=r,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=n,t.encoder=o,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createArrayCameraLayerDescriptors(e,t,r,s){const i=r.depthStencilAttachment;t.layerDescriptors=[];const n=this.get(e.depthTexture);n.viewCache||(n.viewCache=[]);for(let a=0;a<s.length;a++){const s=r.colorAttachments[0],o=new eM;o.view=r.colorAttachments[a].view,o.depthSlice=s.depthSlice,o.resolveTarget=s.resolveTarget,o.loadOp=s.loadOp,o.storeOp=s.storeOp,o.clearValue=s.clearValue;const u=new tM;if(u.label=r.label,u.occlusionQuerySet=r.occlusionQuerySet,u.timestampWrites=r.timestampWrites,u.colorAttachments.push(o),r.depthStencilAttachment){const t=a;n.viewCache[t]||(CB.dimension=PC,CB.baseArrayLayer=a,CB.arrayLayerCount=1,n.viewCache[t]=n.texture.createView(CB),CB.reset());const r=new xB;r.view=n.viewCache[t],r.depthLoadOp=i.depthLoadOp||$R,r.depthStoreOp=i.depthStoreOp||GR,r.depthClearValue=i.depthClearValue||1,e.stencil&&(r.stencilLoadOp=i.stencilLoadOp,r.stencilStoreOp=i.stencilStoreOp,r.stencilClearValue=i.stencilClearValue),u.depthStencilAttachment=r}else{const e=new xB;e.view=i.view,e.depthLoadOp=i.depthLoadOp,e.depthStoreOp=i.depthStoreOp,e.depthClearValue=i.depthClearValue,e.depthReadOnly=i.depthReadOnly,e.stencilLoadOp=i.stencilLoadOp,e.stencilStoreOp=i.stencilStoreOp,e.stencilClearValue=i.stencilClearValue,e.stencilReadOnly=i.stencilReadOnly,u.depthStencilAttachment=e}t.layerDescriptors.push(u)}}_updateArrayCameraLayerDescriptors(e,t,r){for(let s=0;s<r.length;s++){const r=t.layerDescriptors[s];if(r.depthStencilAttachment){const t=r.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=$R):t.depthLoadOp=zR),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=$R):t.stencilLoadOp=zR)}}}finishRender(e){const t=this.get(e),r=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),r>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const r=[];for(let e=0;e<t.bundleEncoders.length;e++){const s=t.bundleEncoders[e];r.push(s.finish())}for(let i=0;i<t.layerDescriptors.length;i++)if(i<r.length){const n=t.layerDescriptors[i],a=s.beginRenderPass(n);if(e.viewport){const{x:t,y:r,width:s,height:i,minDepth:n,maxDepth:o}=e.viewportValue;a.setViewport(t,r,s,i,n,o)}if(e.scissor){const{x:t,y:r,width:s,height:i}=e.scissorValue;a.setScissorRect(t,r,s,i)}a.executeBundles([r[i]]),a.end()}}else t.currentPass&&t.currentPass.end();if(r>0){const s=8*r;let i=this.occludedResolveCache.get(s);void 0===i&&(_B.size=s,_B.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,i=this.device.createBuffer(_B),_B.reset(),this.occludedResolveCache.set(s,i)),_B.size=s,_B.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const n=this.device.createBuffer(_B);_B.reset(),t.encoder.resolveQuerySet(t.occlusionQuerySet,0,r,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,s),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(YC(this.device,t.encoder.finish()),null!==e.textures){const t=e.textures;for(let e=0;e<t.length;e++){const r=t[e];!0===r.generateMipmaps&&this.textureUtils.generateMipmaps(r)}}}isOccluded(e,t){const r=this.get(e);return r.occluded&&r.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:r,currentOcclusionQueryObjects:s}=t;if(r&&s){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await r.mapAsync(GPUMapMode.READ);const i=r.getMappedRange(),n=new BigUint64Array(i);for(let t=0;t<s.length;t++)n[t]===BigInt(0)&&e.add(s[t]);r.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:r,y:s,width:i,height:n,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(r,s,i,n,a,o)}updateScissor(e){const{currentPass:t}=this.get(e),{x:r,y:s,width:i,height:n}=e.scissorValue;t.setScissorRect(r,s,i,n)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,r,s=null){const i=this.device,n=this.renderer;let a,o,u,l=[];if(e){const e=this.getClearColor();TB.r=e.r,TB.g=e.g,TB.b=e.b,TB.a=e.a}if(null===s){o=n.depth,u=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){l=t.colorAttachments;const e=l[0];e.clearValue=TB,e.loadOp=$R,e.storeOp=GR}(o||u)&&(a=t.depthStencilAttachment)}else{o=s.depth,u=s.stencil;const i={loadOp:e?$R:zR,clearValue:e?TB:void 0};o&&(i.depthLoadOp=t?$R:zR,i.depthClearValue=t?n.getClearDepth():void 0,i.depthStoreOp=GR),u&&(i.stencilLoadOp=r?$R:zR,i.stencilClearValue=r?n.getClearStencil():void 0,i.stencilStoreOp=GR);const d=this._getRenderPassDescriptor(s,i);l=d.colorAttachments,a=d.depthStencilAttachment}o&&a&&(t?(a.depthLoadOp=$R,a.depthClearValue=n.getClearDepth(),a.depthStoreOp=GR):(a.depthLoadOp=zR,a.depthStoreOp=GR)),u&&a&&(r?(a.stencilLoadOp=$R,a.stencilClearValue=n.getClearStencil(),a.stencilStoreOp=GR):(a.stencilLoadOp=zR,a.stencilStoreOp=GR)),vB.label="clear";const d=i.createCommandEncoder(vB);vB.reset();d.beginRenderPass({colorAttachments:l,depthStencilAttachment:a}).end(),YC(i,d.finish())}beginCompute(e){const t=this.get(e),r="computeGroup_"+e.id;NB.label=r,vB.label=r,this.initTimestampQuery(Pt.COMPUTE,this.getTimestampUID(e),NB),t.cmdEncoderGPU=this.device.createCommandEncoder(vB),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(NB),t.currentPipeline=null,vB.reset(),NB.reset()}compute(e,t,r,s,i=null){const n=this.get(t),a=this.get(e),{passEncoderGPU:o}=a,u=this.get(s).pipeline;a.currentPipeline!==u&&(o.setPipeline(u),a.currentPipeline=u);for(let e=0,t=r.length;e<t;e++){const t=r[e],s=this.get(t);o.setBindGroup(e,s.group)}if(null===i&&(i=t.dispatchSize||t.count),i&&i.isIndirectStorageBufferAttribute){const e=this.get(i).buffer;return void o.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof i){const e=i;if(void 0===n.dispatchSize||n.count!==e){n.dispatchSize=[0,1,1],n.count=e;const r=t.workgroupSize;let s=r[0];for(let e=1;e<r.length;e++)s*=r[e];const a=Math.ceil(e/s),o=this.device.limits.maxComputeWorkgroupsPerDimension;i=[a,1,1],a>o&&(i[0]=Math.min(a,o),i[1]=Math.ceil(a/o)),n.dispatchSize=i}i=n.dispatchSize}o.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),YC(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,r,s,i,n,a,o,u){const{object:l,material:d,context:c}=e,h=e.getIndex(),p=null!==h;u.pipeline!==s&&(o.setPipeline(s),u.pipeline=s);const g=u.bindingGroups;for(let e=0,t=i.length;e<t;e++){const t=i[e];if(g[e]!==t.id){const r=this.get(t);o.setBindGroup(e,r.group),g[e]=t.id}}if(!0===p&&u.index!==h){const e=this.get(h).buffer,t=h.array instanceof Uint16Array?XR:YR;o.setIndexBuffer(e,t),u.index=h}for(let e=0,t=n.length;e<t;e++){const t=n[e];if(u.attributes[e]!==t){const r=this.get(t).buffer;o.setVertexBuffer(e,r),u.attributes[e]=t}}if(!0===c.stencil&&!0===d.stencilWrite&&r.currentStencilRef!==d.stencilRef&&(o.setStencilReference(d.stencilRef),r.currentStencilRef=d.stencilRef),!0===l.isBatchedMesh){const e=l._multiDrawStarts,r=l._multiDrawCounts,s=l._multiDrawCount;let i=!0===p?h.array.BYTES_PER_ELEMENT:1;d.wireframe&&(i=l.geometry.attributes.position.count>65535?4:2);for(let n=0;n<s;n++)!0===p?o.drawIndexed(r[n],1,e[n]/i,0,n):o.draw(r[n],1,e[n],n),t.update(l,r[n],1)}else if(!0===p){const{vertexCount:r,instanceCount:s,firstVertex:i}=a,n=e.getIndirect();if(null!==n){const t=this.get(n).buffer,r=e.getIndirectOffset(),s=Array.isArray(r)?r:[r];for(let e=0;e<s.length;e++)o.drawIndexedIndirect(t,s[e])}else o.drawIndexed(r,s,i,0,0);t.update(l,r,s)}else{const{vertexCount:r,instanceCount:s,firstVertex:i}=a,n=e.getIndirect();if(null!==n){const t=this.get(n).buffer,r=e.getIndirectOffset(),s=Array.isArray(r)?r:[r];for(let e=0;e<s.length;e++)o.drawIndirect(t,s[e])}else o.draw(r,s,i,0);t.update(l,r,s)}}draw(e,t){const{object:r,context:s,pipeline:i}=e,n=this.get(s),a=this.get(i),o=a.pipeline;if(!0===a.error)return;const u=e.getDrawParameters();if(null===u)return;const l=e.getBindings(),d=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const i=this.get(e.camera),a=e.camera.cameras,c=e.getBindingGroup("cameraIndex");if(void 0===i.indexesGPU||i.indexesGPU.length!==a.length){const e=this.get(c),t=[],r=new Uint32Array([0,0,0,0]);for(let s=0,i=a.length;s<i;s++){r[0]=s;const{layoutGPU:i}=e.layout,n=this.bindingUtils.createBindGroupIndex(r,i);t.push(n)}i.indexesGPU=t}const h=this.renderer.getPixelRatio();for(let p=0,g=a.length;p<g;p++){const g=a[p];if(r.layers.test(g.layers)){const r=g.viewport;let a=n.currentPass,m=n.currentSets;const f=void 0!==n.bundleEncoders;if(f){a=n.bundleEncoders[p],m=n.bundleSets[p]}if(r&&!f&&a.setViewport(Math.floor(r.x*h),Math.floor(r.y*h),Math.floor(r.width*h),Math.floor(r.height*h),s.viewportValue.minDepth,s.viewportValue.maxDepth),c&&i.indexesGPU){const e=l.indexOf(c);a.setBindGroup(e,i.indexesGPU[p]),m.bindingGroups[e]=c.id}this._draw(e,t,n,o,l,d,u,a,m)}}}else if(n.currentPass){if(void 0!==n.occlusionQuerySet){const e=n.lastOcclusionObject;e!==r&&(null!==e&&!0===e.occlusionTest&&(n.currentPass.endOcclusionQuery(),n.occlusionQueryIndex++),!0===r.occlusionTest&&(n.currentPass.beginOcclusionQuery(n.occlusionQueryIndex),n.occlusionQueryObjects[n.occlusionQueryIndex]=r),n.lastOcclusionObject=r)}this._draw(e,t,n,o,l,d,u,n.currentPass,n.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:r,material:s}=e,i=this.utils,n=i.getSampleCountRenderContext(e.context),a=i.getCurrentColorSpace(e.context),o=i.getCurrentColorFormat(e.context),u=i.getCurrentDepthStencilFormat(e.context),l=i.getPrimitiveTopology(r,s),d=r.isMesh&&r.matrixWorld.determinantAffine()<0;let c=!1;return t.material===s&&t.materialVersion===s.version&&t.transparent===s.transparent&&t.blending===s.blending&&t.premultipliedAlpha===s.premultipliedAlpha&&t.blendSrc===s.blendSrc&&t.blendDst===s.blendDst&&t.blendEquation===s.blendEquation&&t.blendSrcAlpha===s.blendSrcAlpha&&t.blendDstAlpha===s.blendDstAlpha&&t.blendEquationAlpha===s.blendEquationAlpha&&t.colorWrite===s.colorWrite&&t.depthWrite===s.depthWrite&&t.depthTest===s.depthTest&&t.depthFunc===s.depthFunc&&t.stencilWrite===s.stencilWrite&&t.stencilFunc===s.stencilFunc&&t.stencilFail===s.stencilFail&&t.stencilZFail===s.stencilZFail&&t.stencilZPass===s.stencilZPass&&t.stencilFuncMask===s.stencilFuncMask&&t.stencilWriteMask===s.stencilWriteMask&&t.side===s.side&&t.alphaToCoverage===s.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===u&&t.primitiveTopology===l&&t.frontFaceCW===d&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=s,t.materialVersion=s.version,t.transparent=s.transparent,t.blending=s.blending,t.premultipliedAlpha=s.premultipliedAlpha,t.blendSrc=s.blendSrc,t.blendDst=s.blendDst,t.blendEquation=s.blendEquation,t.blendSrcAlpha=s.blendSrcAlpha,t.blendDstAlpha=s.blendDstAlpha,t.blendEquationAlpha=s.blendEquationAlpha,t.colorWrite=s.colorWrite,t.depthWrite=s.depthWrite,t.depthTest=s.depthTest,t.depthFunc=s.depthFunc,t.stencilWrite=s.stencilWrite,t.stencilFunc=s.stencilFunc,t.stencilFail=s.stencilFail,t.stencilZFail=s.stencilZFail,t.stencilZPass=s.stencilZPass,t.stencilFuncMask=s.stencilFuncMask,t.stencilWriteMask=s.stencilWriteMask,t.side=s.side,t.alphaToCoverage=s.alphaToCoverage,t.sampleCount=n,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=u,t.primitiveTopology=l,t.frontFaceCW=d,t.clippingContextCacheKey=e.clippingContextCacheKey,c=!0),c}getRenderCacheKey(e){const{object:t,material:r}=e,s=this.utils,i=e.context,n=t.isMesh&&t.matrixWorld.determinantAffine()<0;return[r.transparent,r.blending,r.premultipliedAlpha,r.blendSrc,r.blendDst,r.blendEquation,r.blendSrcAlpha,r.blendDstAlpha,r.blendEquationAlpha,r.colorWrite,r.depthWrite,r.depthTest,r.depthFunc,r.stencilWrite,r.stencilFunc,r.stencilFail,r.stencilZFail,r.stencilZPass,r.stencilFuncMask,r.stencilWriteMask,r.side,n,s.getSampleCountRenderContext(i),s.getCurrentColorSpace(i),s.getCurrentColorFormat(i),s.getCurrentDepthStencilFormat(i),s.getPrimitiveTopology(t,r),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,r,s,i,n){return this.textureUtils.copyTextureToBuffer(e,t,r,s,i,n)}initTimestampQuery(e,t,r){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new bB(this.device,e,2048));const s=this.timestampQueryPool[e],i=s.allocateQueriesForContext(t);RB.querySet=s.querySet,RB.beginningOfPassWriteIndex=i,RB.endOfPassWriteIndex=i+1,r.timestampWrites=RB}createNodeBuilder(e,t){return new QM(e,t)}createProgram(e){const t=this.get(e);EB.label=e.stage+(""!==e.name?`_${e.name}`:""),EB.code=e.code,t.module={module:this.device.createShaderModule(EB),entryPoint:"main"},EB.reset()}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const r=this.get(e),s=r.currentPass.finish();this.get(t).bundleGPU=s,r.currentSets=r._currentSets,r.currentPass=r._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createUniformBuffer(e){const t=this.get(e);if(void 0===t.buffer){const r=e.byteLength,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=[];e.visibility&LR.VERTEX&&i.push("vertex"),e.visibility&LR.FRAGMENT&&i.push("fragment"),e.visibility&LR.COMPUTE&&i.push("compute");const n=`(${i.join(",")})`;_B.label=`bindingBuffer${e.id}_${e.name}_${n}`,_B.size=r,_B.usage=s;const a=this.device.createBuffer(_B);_B.reset(),t.buffer=a}}destroyUniformBuffer(e){this.get(e).buffer.destroy(),this.delete(e)}createBindings(e,t,r,s){this.bindingUtils.createBindings(e,t,r,s)}updateBindings(e,t,r,s){this.bindingUtils.createBindings(e,t,r,s)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}hasFeature(e){return void 0!==zC[e]&&(e=zC[e]),this.device.features.has(e)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){let a=0,o=0,u=0,l=0,d=0,c=0,h=e.image.width,p=e.image.height,g=1;null!==r&&(!0===r.isBox3?(l=r.min.x,d=r.min.y,c=r.min.z,h=r.max.x-r.min.x,p=r.max.y-r.min.y,g=r.max.z-r.min.z):(l=r.min.x,d=r.min.y,h=r.max.x-r.min.x,p=r.max.y-r.min.y,g=1)),null!==s&&(a=s.x,o=s.y,u=s.z||0),vB.label="copyTextureToTexture_"+e.id+"_"+t.id;const m=this.device.createCommandEncoder(vB);vB.reset();const f=this.get(e).texture,y=this.get(t).texture;wB.texture=f,wB.mipLevel=i,wB.origin.x=l,wB.origin.y=d,wB.origin.z=c,AB.texture=y,AB.mipLevel=n,AB.origin.x=a,AB.origin.y=o,AB.origin.z=u,MB.width=h,MB.height=p,MB.depthOrArrayLayers=g,m.copyTextureToTexture(wB,AB,MB),wB.reset(),AB.reset(),MB.reset(),YC(this.device,m.finish()),0===n&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,r){const s=this.get(t);let i=null;i=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const n=this.get(e).texture;if(i.format!==n.format)return void o("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",i.format,n.format);let a;if(s.currentPass?(s.currentPass.end(),a=s.encoder):(vB.label="copyFramebufferToTexture_"+e.id,a=this.device.createCommandEncoder(vB),vB.reset()),wB.texture=i,wB.origin.x=r.x,wB.origin.y=r.y,AB.texture=n,MB.width=r.z,MB.height=r.w,a.copyTextureToTexture(wB,AB,MB),wB.reset(),AB.reset(),MB.reset(),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,a),s.currentPass){const{descriptor:e}=s;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=zR;t.depth&&(e.depthStencilAttachment.depthLoadOp=zR),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=zR),s.currentPass=a.beginRenderPass(e),s.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else YC(this.device,a.finish())}hasCompatibility(e){return void 0!==this._compatibility[e]?this._compatibility[e]:super.hasCompatibility(e)}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))null!==e&&e.dispose();void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class LB extends ms{constructor(e,t,r,s,i,n){super(e,t,r,s,i,n),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class FB extends ms{constructor(e,t,r,s,i,n){super(e,t,r,s,i,n),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class PB extends cE{constructor(){super(),this.addMaterial(_m,"MeshPhongMaterial"),this.addMaterial(gy,"MeshStandardMaterial"),this.addMaterial(fy,"MeshPhysicalMaterial"),this.addMaterial(vy,"MeshToonMaterial"),this.addMaterial(hm,"MeshBasicMaterial"),this.addMaterial(xm,"MeshLambertMaterial"),this.addMaterial(Zg,"MeshNormalMaterial"),this.addMaterial(Ey,"MeshMatcapMaterial"),this.addMaterial(Ig,"LineBasicMaterial"),this.addMaterial(kg,"LineDashedMaterial"),this.addMaterial(Ly,"PointsMaterial"),this.addMaterial(Cy,"SpriteMaterial"),this.addMaterial(Dy,"ShadowMaterial"),this.addLight(Jv,fs),this.addLight(IS,ys),this.addLight(XS,bs),this.addLight(kS,ms),this.addLight(OS,xs),this.addLight(VS,Ts),this.addLight(zS,_s),this.addLight(GS,LB),this.addLight(WS,FB),this.addToneMapping(VT,vs),this.addToneMapping(kT,Ns),this.addToneMapping(GT,Ss),this.addToneMapping($T,Es),this.addToneMapping(qT,Rs),this.addToneMapping(XT,ws)}}class UB extends UE{constructor(e={}){let t;e.forceWebGL?t=wR:(t=BB,e.getFallback=()=>(d("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new wR(e)));super(new t(e),e),this.library=new PB,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class DB extends As{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class OB{constructor(e,t=Ln(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new Dg;r.name="RenderPipeline",this._quadMesh=new zx(r),this._quadMesh.name="Render Pipeline",this._context=null,this._toneMapping=e.toneMapping,this._outputColorSpace=e.outputColorSpace}render(){const e=this.renderer;this._update(),null!==this._context.onBeforeRenderPipeline&&this._context.onBeforeRenderPipeline();const t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=m,e.outputColorSpace=p.workingColorSpace;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r,null!==this._context.onAfterRenderPipeline&&this._context.onAfterRenderPipeline()}get context(){return this._context}dispose(){this._quadMesh.material.dispose()}_update(){if(this._toneMapping!==this.renderer.toneMapping&&(this._toneMapping=this.renderer.toneMapping,this.needsUpdate=!0),this._outputColorSpace!==this.renderer.outputColorSpace&&(this._outputColorSpace=this.renderer.outputColorSpace,this.needsUpdate=!0),!0===this.needsUpdate){const e=this._toneMapping,t=this._outputColorSpace,r={renderPipeline:this,onBeforeRenderPipeline:null,onAfterRenderPipeline:null};let s=this.outputNode;!0===this.outputColorTransform?(s=s.context(r),s=Vl(s,e,t)):(r.toneMapping=e,r.outputColorSpace=t,s=s.context(r)),this._context=r,this._quadMesh.material.fragmentNode=s,this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){v('RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.renderer.init(),this.render()}}class IB extends OB{constructor(e,t){v('PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.'),super(e,t)}}class VB extends u{constructor(e){super(),this.name="",this.buffer=null,this.maxByteLength=e,this.isReadbackBuffer=!0,this._mapped=!1}release(){this.dispatchEvent({type:"release"})}dispose(){this.dispatchEvent({type:"dispose"})}}class kB extends N{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=le,this.minFilter=le,this.isStorageTexture=!0,this.mipmapsAutoUpdate=!0}setSize(e,t){this.image.width===e&&this.image.height===t||(this.image.width=e,this.image.height=t,this.dispose())}}class GB extends N{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!1,this.image={width:e,height:t,depth:r},this.magFilter=le,this.minFilter=le,this.wrapR=_e,this.isStorageTexture=!0,this.is3DTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class zB extends N{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!0,this.image={width:e,height:t,depth:r},this.magFilter=le,this.minFilter=le,this.isStorageTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class $B extends Jx{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class WB extends Cs{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new Ms(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,r=>{try{t(this.parse(JSON.parse(r)))}catch(t){s?s(t):o(t),this.manager.itemError(e)}},r,s)}parseNodes(e){const t={};if(void 0!==e){for(const r of e){const{uuid:e,type:s}=r;t[e]=this.createNodeFromType(s),t[e].uuid=e}const r={nodes:t,textures:this.textures};for(const s of e){s.meta=r;t[s.uuid].deserialize(s),delete s.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const r={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=r,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}setNodes(e){return this.nodes=e,this}createNodeFromType(e){return void 0===this.nodes[e]?(o("NodeLoader: Node type not found:",e),Tn()):new this.nodes[e]}}class HB extends Bs{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),r=this.nodes,s=e.inputNodes;for(const e in s){const i=s[e];t[e]=r[i]}return t}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}createMaterialFromType(e){const t=this.nodeMaterials[e];return void 0!==t?new t:super.createMaterialFromType(e)}}class jB extends Ls{constructor(e){super(e),this.nodes={},this.nodeMaterials={},this._nodesJSON=null}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}parse(e,t){this._nodesJSON=e.nodes;const r=super.parse(e,t);return this._nodesJSON=null,r}async parseAsync(e){this._nodesJSON=e.nodes;const t=await super.parseAsync(e);return this._nodesJSON=null,t}parseNodes(e,t){if(void 0!==e){const r=new WB;return r.setNodes(this.nodes),r.setTextures(t),r.parseNodes(e)}return{}}parseMaterials(e,t){const r={};if(void 0!==e){const s=this.parseNodes(this._nodesJSON,t),i=new HB;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t<s;t++){const s=e[t];r[s.uuid]=i.parse(s)}}return r}}class qB extends cE{constructor(){super(),this.addLight(Jv,fs),this.addLight(IS,ys),this.addLight(XS,bs),this.addLight(kS,ms),this.addLight(OS,xs),this.addLight(VS,Ts),this.addLight(zS,_s),this.addLight(GS,LB),this.addLight(WS,FB),this.addToneMapping(VT,vs),this.addToneMapping(kT,Ns),this.addToneMapping(GT,Ss),this.addToneMapping($T,Es),this.addToneMapping(qT,Rs),this.addToneMapping(XT,ws)}}class XB extends As{constructor(){super(),this.isClippingGroup=!0,this.clippingPlanes=[],this.enabled=!0,this.clipIntersection=!1,this.clipShadows=!1}}export{Es as ACESFilmicToneMapping,ag as AONode,it as AddEquation,pe as AddOperation,Kt as AdditiveBlending,Rs as AgXToneMapping,ze as AlphaFormat,jr as AlwaysCompare,ir as AlwaysDepth,ss as AlwaysStencilFunc,xs as AmbientLight,OS as AmbientLightNode,Qv as AnalyticLightNode,vt as ArrayCamera,gi as ArrayElementNode,Ca as ArrayNode,Ba as AssignNode,x_ as AtomicFunctionNode,Hl as AttributeNode,F as BackSide,oR as Backend,m_ as BarrierNode,om as BasicEnvironmentNode,um as BasicLightMapNode,qB as BasicNodeLibrary,gt as BasicShadowMap,Wb as BitcastNode,Xb as BitcountNode,Ib as BlendMode,ae as BoxGeometry,Ae as BufferAttribute,cl as BufferAttributeNode,ve as BufferGeometry,id as BufferNode,ld as BuiltinNode,Dh as BumpMapNode,DB as BundleGroup,Cl as BypassNode,Ie as ByteType,RE as CanvasTarget,Ss as CineonToneMapping,_e as ClampToEdgeWrapping,XB as ClippingGroup,Mg as ClippingNode,YT as CodeNode,e as Color,p as ColorManagement,Ju as ColorSpaceNode,R as Compatibility,u_ as ComputeBuiltinNode,Nl as ComputeNode,Bu as ConditionalNode,Si as ConstNode,Fu as ContextNode,mi as ConvertNode,de as CubeCamera,mt as CubeDepthTexture,sm as CubeMapNode,D as CubeReflectionMapping,O as CubeRefractionMapping,tm as CubeRenderTarget,U as CubeTexture,Xc as CubeTextureNode,we as CubeUVReflectionMapping,qt as CullFaceBack,Xt as CullFaceFront,jt as CullFaceNone,Et as CustomBlending,wt as CylinderGeometry,X as DataArrayTexture,xe as DataTexture,kl as DebugNode,os as DecrementStencilOp,ns as DecrementWrapStencilOp,He as DepthFormat,je as DepthStencilFormat,Z as DepthTexture,ys as DirectionalLight,IS as DirectionalLightNode,P as DoubleSide,Gt as DstAlphaFactor,zt as DstColorFactor,x as DynamicDrawUsage,dy as EnvironmentNode,Hr as EqualCompare,tr as EqualDepth,es as EqualStencilFunc,ce as EquirectangularReflectionMapping,he as EquirectangularRefractionMapping,u as EventDispatcher,Ep as EventNode,Fl as ExpressionNode,Ms as FileLoader,_i as FlipNode,xt as Float16BufferAttribute,lt as Float32BufferAttribute,Y as FloatType,Q as FramebufferTexture,vc as FrontFacingNode,St as FrontSide,Lt as Frustum,Bt as FrustumArray,Fa as FunctionCallNode,KT as FunctionNode,cx as FunctionOverloadingNode,iR as GLSLNodeBuilder,tE as GLSLNodeParser,C as GreaterCompare,Jt as GreaterDepth,M as GreaterEqualCompare,er as GreaterEqualDepth,Jr as GreaterEqualStencilFunc,Zr as GreaterStencilFunc,As as Group,Te as HalfFloatType,Ts as HemisphereLight,VS as HemisphereLightNode,LB as IESSpotLight,GS as IESSpotLightNode,us as IncrementStencilOp,as as IncrementWrapStencilOp,fl as IndexNode,$B as IndirectStorageBufferAttribute,vi as InputNode,zl as InspectorBase,$l as InspectorNode,j as InstancedBufferAttribute,q as InstancedInterleavedBuffer,E as IntType,b as InterleavedBuffer,y as InterleavedBufferAttribute,ls as InvertStencilOp,lg as IrradianceNode,Rl as IsolateNode,yi as JoinNode,hs as KeepStencilOp,w as LessCompare,sr as LessDepth,A as LessEqualCompare,rr as LessEqualDepth,ts as LessEqualStencilFunc,rs as LessStencilFunc,_s as LightProbe,zS as LightProbeNode,gE as Lighting,og as LightingContextNode,lm as LightingModel,ng as LightingNode,uv as LightsNode,Qg as Line2NodeMaterial,ee as LineBasicMaterial,Ig as LineBasicNodeMaterial,te as LineDashedMaterial,kg as LineDashedNodeMaterial,le as LinearFilter,ot as LinearMipMapLinearFilter,K as LinearMipmapLinearFilter,yt as LinearMipmapNearestFilter,Ee as LinearSRGBColorSpace,vs as LinearToneMapping,Xr as LinearTransfer,Cs as Loader,Kp as LoopNode,zb as MRTNode,J as Material,nt as MaterialBlending,Bs as MaterialLoader,Vh as MaterialNode,th as MaterialReferenceNode,uo as MathNode,l as MathUtils,i as Matrix2,n as Matrix3,a as Matrix4,ps as MaxEquation,Ql as MaxMipLevelNode,Ei as MemberNode,oe as Mesh,fe as MeshBasicMaterial,hm as MeshBasicNodeMaterial,ye as MeshLambertMaterial,xm as MeshLambertNodeMaterial,Le as MeshMatcapMaterial,Ey as MeshMatcapNodeMaterial,se as MeshNormalMaterial,Zg as MeshNormalNodeMaterial,be as MeshPhongMaterial,_m as MeshPhongNodeMaterial,Me as MeshPhysicalMaterial,fy as MeshPhysicalNodeMaterial,by as MeshSSSNodeMaterial,Ce as MeshStandardMaterial,gy as MeshStandardNodeMaterial,Be as MeshToonMaterial,vy as MeshToonNodeMaterial,gs as MinEquation,Gr as MirroredRepeatWrapping,ge as MixOperation,tc as ModelNode,Yt as MultiplyBlending,me as MultiplyOperation,B as NearestFilter,bt as NearestMipmapLinearFilter,$r as NearestMipmapNearestFilter,ws as NeutralToneMapping,qr as NeverCompare,nr as NeverDepth,is as NeverStencilFunc,re as NoBlending,T as NoColorSpace,V as NoNormalPacking,m as NoToneMapping,pi as Node,ai as NodeAccess,rS as NodeAttribute,PS as NodeBuilder,uS as NodeCache,aS as NodeCode,Zl as NodeError,US as NodeFrame,DS as NodeFunctionInput,WB as NodeLoader,Dg as NodeMaterial,HB as NodeMaterialLoader,Os as NodeMaterialObserver,jB as NodeObjectLoader,si as NodeShaderStage,ni as NodeType,sS as NodeUniform,ii as NodeUpdateType,ri as NodeUtils,iS as NodeVar,nS as NodeVarying,tt as NormalBlending,G as NormalGAPacking,Lh as NormalMapNode,k as NormalRGPacking,Wr as NotEqualCompare,Zt as NotEqualDepth,Kr as NotEqualStencilFunc,at as Object3D,Xd as Object3DNode,Ls as ObjectLoader,z as ObjectSpaceNormalMap,Ht as OneFactor,It as OneMinusDstAlphaFactor,Vt as OneMinusDstColorFactor,st as OneMinusSrcAlphaFactor,kt as OneMinusSrcColorFactor,Da as OperatorNode,Ne as OrthographicCamera,Db as OutputStructNode,Ab as OverrideContextNode,ct as PCFShadowMap,ht as PCFSoftShadowMap,ey as PMREMGenerator,oy as PMREMNode,ex as PackFloatNode,Bb as ParameterNode,OT as PassNode,Se as PerspectiveCamera,ym as PhongLightingModel,ff as PhysicalLightingModel,ut as Plane,Nt as PlaneGeometry,fs as PointLight,Jv as PointLightNode,Xv as PointShadowNode,eT as PointUVNode,Pe as PointsMaterial,Ly as PointsNodeMaterial,IB as PostProcessing,FB as ProjectorLight,WS as ProjectorLightNode,Gn as PropertyNode,zx as QuadMesh,At as Quaternion,br as R11_EAC_Format,W as RED_GREEN_RGTC2_Format,Ir as RED_RGTC1_Format,_t as REVISION,H as RG11_EAC_Format,Re as RGBAFormat,Ft as RGBAIntegerFormat,Lr as RGBA_ASTC_10x10_Format,Cr as RGBA_ASTC_10x5_Format,Mr as RGBA_ASTC_10x6_Format,Br as RGBA_ASTC_10x8_Format,Fr as RGBA_ASTC_12x10_Format,Pr as RGBA_ASTC_12x12_Format,_r as RGBA_ASTC_4x4_Format,vr as RGBA_ASTC_5x4_Format,Nr as RGBA_ASTC_5x5_Format,Sr as RGBA_ASTC_6x5_Format,Er as RGBA_ASTC_6x6_Format,Rr as RGBA_ASTC_8x5_Format,wr as RGBA_ASTC_8x6_Format,Ar as RGBA_ASTC_8x8_Format,Ur as RGBA_BPTC_Format,yr as RGBA_ETC2_EAC_Format,gr as RGBA_PVRTC_2BPPV1_Format,pr as RGBA_PVRTC_4BPPV1_Format,ur as RGBA_S3TC_DXT1_Format,lr as RGBA_S3TC_DXT3_Format,dr as RGBA_S3TC_DXT5_Format,Xe as RGBFormat,Ye as RGBIntegerFormat,Dr as RGB_BPTC_SIGNED_Format,Or as RGB_BPTC_UNSIGNED_Format,mr as RGB_ETC1_Format,fr as RGB_ETC2_Format,hr as RGB_PVRTC_2BPPV1_Format,cr as RGB_PVRTC_4BPPV1_Format,or as RGB_S3TC_DXT1_Format,$ as RGFormat,qe as RGIntegerFormat,Wx as RTTNode,a_ as RangeNode,VB as ReadbackBuffer,bs as RectAreaLight,XS as RectAreaLightNode,$e as RedFormat,We as RedIntegerFormat,sl as ReferenceBaseNode,Zc as ReferenceNode,Ox as ReflectorNode,Ns as ReinhardToneMapping,Il as RenderOutputNode,OB as RenderPipeline,ne as RenderTarget,UE as Renderer,il as RendererReferenceNode,xv as RendererUtils,zr as RepeatWrapping,ds as ReplaceStencilOp,Dt as ReverseSubtractEquation,Ry as RotateNode,xr as SIGNED_R11_EAC_Format,kr as SIGNED_RED_GREEN_RGTC2_Format,Vr as SIGNED_RED_RGTC1_Format,Tr as SIGNED_RG11_EAC_Format,ie as SRGBColorSpace,g as SRGBTransfer,Kx as SampleNode,ue as Scene,pd as ScreenNode,Ti as SetNode,lv as ShadowBaseNode,Ue as ShadowMaterial,Uv as ShadowNode,Dy as ShadowNodeMaterial,ke as ShortType,L as Sphere,ft as SphereGeometry,xi as SplitNode,ms as SpotLight,kS as SpotLightNode,Fe as SpriteMaterial,Cy as SpriteNodeMaterial,rt as SrcAlphaFactor,$t as SrcAlphaSaturateFactor,Wt as SrcColorFactor,Lb as StackNode,Vs as StackTrace,PB as StandardNodeLibrary,f as StaticDrawUsage,GB as Storage3DTexture,Cp as StorageArrayElementNode,zB as StorageArrayTexture,Jx as StorageBufferAttribute,Bp as StorageBufferNode,Zx as StorageInstancedBufferAttribute,kB as StorageTexture,uT as StorageTexture3DNode,aT as StorageTextureNode,Ub as StructNode,Pb as StructTypeNode,Hu as SubBuildNode,v_ as SubgroupFunctionNode,Ot as SubtractEquation,Qt as SubtractiveBlending,QN as TSL,I as TangentSpaceNormalMap,fi as TempNode,N as Texture,cT as Texture3DNode,ed as TextureNode,Xl as TextureSizeNode,Pt as TimestampQuery,al as ToneMappingNode,IT as ToonOutlinePassNode,dt as UVMapping,Oe as Uint16BufferAttribute,De as Uint32BufferAttribute,od as UniformArrayNode,_a as UniformGroupNode,wa as UniformNode,ix as UnpackFloatNode,Ve as UnsignedByteType,et as UnsignedInt101111Type,Ze as UnsignedInt248Type,Je as UnsignedInt5999Type,S as UnsignedIntType,Qe as UnsignedShort4444Type,Ke as UnsignedShort5551Type,Ge as UnsignedShortType,pT as UserDataNode,pt as VSMShadowMap,ku as VarNode,qu as VaryingNode,t as Vector2,r as Vector3,s as Vector4,mT as VelocityNode,Pg as VertexColorNode,xg as ViewportDepthNode,yg as ViewportDepthTextureNode,LT as ViewportSharedTextureNode,cg as ViewportTextureNode,Gy as VolumeNodeMaterial,QM as WGSLNodeBuilder,wR as WebGLBackend,vR as WebGLCapabilities,c as WebGLCoordinateSystem,BB as WebGPUBackend,h as WebGPUCoordinateSystem,UB as WebGPURenderer,Ct as WebXRController,b_ as WorkgroupInfoNode,Rt as ZeroFactor,cs as ZeroStencilOp,Ut as createCanvasElement,ui as defaultBuildStages,oi as defaultShaderStages,o as error,_ as log,li as shaderStages,di as vectorComponents,d as warn,v as warnOnce};