@luma.gl/engine 9.4.0-alpha.3 → 9.4.0-beta.1

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 (255) hide show
  1. package/LICENSE +5 -1
  2. package/dist/animation/animation-clip.d.ts +18 -0
  3. package/dist/animation/animation-clip.d.ts.map +1 -0
  4. package/dist/animation/animation-clip.js +15 -0
  5. package/dist/animation/animation-clip.js.map +1 -0
  6. package/dist/animation/animation-interpolation.d.ts +18 -0
  7. package/dist/animation/animation-interpolation.d.ts.map +1 -0
  8. package/dist/animation/animation-interpolation.js +101 -0
  9. package/dist/animation/animation-interpolation.js.map +1 -0
  10. package/dist/animation/animation-mixer.d.ts +88 -0
  11. package/dist/animation/animation-mixer.d.ts.map +1 -0
  12. package/dist/animation/animation-mixer.js +287 -0
  13. package/dist/animation/animation-mixer.js.map +1 -0
  14. package/dist/animation/animation-track.d.ts +42 -0
  15. package/dist/animation/animation-track.d.ts.map +1 -0
  16. package/dist/animation/animation-track.js +34 -0
  17. package/dist/animation/animation-track.js.map +1 -0
  18. package/dist/animation/animator.js +1 -1
  19. package/dist/animation/animator.js.map +1 -1
  20. package/dist/animation/key-frames.js +1 -1
  21. package/dist/animation/key-frames.js.map +1 -1
  22. package/dist/animation/morph-targets.d.ts +15 -0
  23. package/dist/animation/morph-targets.d.ts.map +1 -0
  24. package/dist/animation/morph-targets.js +151 -0
  25. package/dist/animation/morph-targets.js.map +1 -0
  26. package/dist/animation/skin.d.ts +18 -0
  27. package/dist/animation/skin.d.ts.map +1 -0
  28. package/dist/animation/skin.js +30 -0
  29. package/dist/animation/skin.js.map +1 -0
  30. package/dist/animation/timeline.js +1 -1
  31. package/dist/animation/timeline.js.map +1 -1
  32. package/dist/animation-loop/animation-loop-template.js +1 -1
  33. package/dist/animation-loop/animation-loop-template.js.map +1 -1
  34. package/dist/animation-loop/animation-loop.d.ts +5 -4
  35. package/dist/animation-loop/animation-loop.d.ts.map +1 -1
  36. package/dist/animation-loop/animation-loop.js +3 -3
  37. package/dist/animation-loop/animation-loop.js.map +1 -1
  38. package/dist/animation-loop/animation-props.d.ts +1 -1
  39. package/dist/animation-loop/animation-props.js +1 -1
  40. package/dist/animation-loop/animation-props.js.map +1 -1
  41. package/dist/animation-loop/make-animation-loop.d.ts +9 -1
  42. package/dist/animation-loop/make-animation-loop.d.ts.map +1 -1
  43. package/dist/animation-loop/make-animation-loop.js +24 -5
  44. package/dist/animation-loop/make-animation-loop.js.map +1 -1
  45. package/dist/animation-loop/request-animation-frame.js +1 -1
  46. package/dist/animation-loop/request-animation-frame.js.map +1 -1
  47. package/dist/application-utils/load-file.js +1 -1
  48. package/dist/application-utils/load-file.js.map +1 -1
  49. package/dist/application-utils/random.js +1 -1
  50. package/dist/application-utils/random.js.map +1 -1
  51. package/dist/compute/buffer-transform.d.ts +1 -1
  52. package/dist/compute/buffer-transform.d.ts.map +1 -1
  53. package/dist/compute/buffer-transform.js +1 -1
  54. package/dist/compute/buffer-transform.js.map +1 -1
  55. package/dist/compute/computation.d.ts +4 -1
  56. package/dist/compute/computation.d.ts.map +1 -1
  57. package/dist/compute/computation.js +34 -15
  58. package/dist/compute/computation.js.map +1 -1
  59. package/dist/compute/swap.js +1 -1
  60. package/dist/compute/swap.js.map +1 -1
  61. package/dist/compute/texture-transform.js +1 -1
  62. package/dist/compute/texture-transform.js.map +1 -1
  63. package/dist/controls/orbit-controls.d.ts +61 -0
  64. package/dist/controls/orbit-controls.d.ts.map +1 -0
  65. package/dist/controls/orbit-controls.js +179 -0
  66. package/dist/controls/orbit-controls.js.map +1 -0
  67. package/dist/debug/copy-texture-to-image.js +1 -1
  68. package/dist/debug/copy-texture-to-image.js.map +1 -1
  69. package/dist/debug/debug-framebuffer.js +1 -1
  70. package/dist/debug/debug-framebuffer.js.map +1 -1
  71. package/dist/debug/debug-shader-layout.js +1 -1
  72. package/dist/debug/debug-shader-layout.js.map +1 -1
  73. package/dist/debug/pixel-data-utils.js +1 -1
  74. package/dist/debug/pixel-data-utils.js.map +1 -1
  75. package/dist/dist.dev.js +7605 -6249
  76. package/dist/dist.min.js +31 -31
  77. package/dist/dynamic-buffer/dynamic-buffer.js +1 -1
  78. package/dist/dynamic-buffer/dynamic-buffer.js.map +1 -1
  79. package/dist/dynamic-texture/dynamic-texture.d.ts.map +1 -1
  80. package/dist/dynamic-texture/dynamic-texture.js +3 -2
  81. package/dist/dynamic-texture/dynamic-texture.js.map +1 -1
  82. package/dist/dynamic-texture/texture-binding-source.js +1 -1
  83. package/dist/dynamic-texture/texture-binding-source.js.map +1 -1
  84. package/dist/dynamic-texture/texture-data.js +1 -1
  85. package/dist/dynamic-texture/texture-data.js.map +1 -1
  86. package/dist/dynamic-texture/video-texture.js +1 -1
  87. package/dist/dynamic-texture/video-texture.js.map +1 -1
  88. package/dist/geometries/cone-geometry.js +1 -1
  89. package/dist/geometries/cone-geometry.js.map +1 -1
  90. package/dist/geometries/cube-geometry.js +1 -1
  91. package/dist/geometries/cube-geometry.js.map +1 -1
  92. package/dist/geometries/cylinder-geometry.js +1 -1
  93. package/dist/geometries/cylinder-geometry.js.map +1 -1
  94. package/dist/geometries/ico-sphere-geometry.js +1 -1
  95. package/dist/geometries/ico-sphere-geometry.js.map +1 -1
  96. package/dist/geometry/geometry-table.js +1 -1
  97. package/dist/geometry/geometry-table.js.map +1 -1
  98. package/dist/geometry/geometry-utils.js +1 -1
  99. package/dist/geometry/geometry-utils.js.map +1 -1
  100. package/dist/geometry/geometry.js +1 -1
  101. package/dist/geometry/geometry.js.map +1 -1
  102. package/dist/geometry/gpu-geometry.js +1 -1
  103. package/dist/geometry/gpu-geometry.js.map +1 -1
  104. package/dist/geometry/mesh-simplification.d.ts +29 -0
  105. package/dist/geometry/mesh-simplification.d.ts.map +1 -0
  106. package/dist/geometry/mesh-simplification.js +402 -0
  107. package/dist/geometry/mesh-simplification.js.map +1 -0
  108. package/dist/index.cjs +9874 -1407
  109. package/dist/index.cjs.map +3 -4
  110. package/dist/index.d.ts +17 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +9 -1
  113. package/dist/index.js.map +1 -1
  114. package/dist/material/material-factory.js +1 -1
  115. package/dist/material/material-factory.js.map +1 -1
  116. package/dist/material/material.js +1 -1
  117. package/dist/material/material.js.map +1 -1
  118. package/dist/model/model.d.ts +1 -1
  119. package/dist/model/model.d.ts.map +1 -1
  120. package/dist/model/model.js +35 -10
  121. package/dist/model/model.js.map +1 -1
  122. package/dist/model/split-uniforms-and-bindings.js +1 -1
  123. package/dist/model/split-uniforms-and-bindings.js.map +1 -1
  124. package/dist/models/billboard-texture-model.js +1 -1
  125. package/dist/models/billboard-texture-model.js.map +1 -1
  126. package/dist/models/billboard-texture-module.js +1 -1
  127. package/dist/models/billboard-texture-module.js.map +1 -1
  128. package/dist/models/clip-space.js +1 -1
  129. package/dist/models/clip-space.js.map +1 -1
  130. package/dist/models/directional-light-model.js +1 -1
  131. package/dist/models/directional-light-model.js.map +1 -1
  132. package/dist/models/light-model-utils.js +1 -1
  133. package/dist/models/light-model-utils.js.map +1 -1
  134. package/dist/models/point-light-model.js +1 -1
  135. package/dist/models/point-light-model.js.map +1 -1
  136. package/dist/models/spot-light-model.js +1 -1
  137. package/dist/models/spot-light-model.js.map +1 -1
  138. package/dist/modules/picking/color-picking.js +1 -1
  139. package/dist/modules/picking/color-picking.js.map +1 -1
  140. package/dist/modules/picking/index-color-picking.js +1 -1
  141. package/dist/modules/picking/index-color-picking.js.map +1 -1
  142. package/dist/modules/picking/index-picking.js +1 -1
  143. package/dist/modules/picking/index-picking.js.map +1 -1
  144. package/dist/modules/picking/legacy-color-picking.js +1 -1
  145. package/dist/modules/picking/legacy-color-picking.js.map +1 -1
  146. package/dist/modules/picking/legacy-picking-manager.js +1 -1
  147. package/dist/modules/picking/legacy-picking-manager.js.map +1 -1
  148. package/dist/modules/picking/picking-manager.js +1 -1
  149. package/dist/modules/picking/picking-manager.js.map +1 -1
  150. package/dist/modules/picking/picking-uniforms.js +1 -1
  151. package/dist/modules/picking/picking-uniforms.js.map +1 -1
  152. package/dist/modules/picking/picking.js +1 -1
  153. package/dist/modules/picking/picking.js.map +1 -1
  154. package/dist/passes/get-fragment-shader.js +1 -1
  155. package/dist/passes/get-fragment-shader.js.map +1 -1
  156. package/dist/passes/shader-pass-renderer.d.ts +19 -1
  157. package/dist/passes/shader-pass-renderer.d.ts.map +1 -1
  158. package/dist/passes/shader-pass-renderer.js +180 -11
  159. package/dist/passes/shader-pass-renderer.js.map +1 -1
  160. package/dist/passes/texture-transform-module.js +1 -1
  161. package/dist/passes/texture-transform-module.js.map +1 -1
  162. package/dist/scenegraph/group-node.d.ts.map +1 -1
  163. package/dist/scenegraph/group-node.js +7 -1
  164. package/dist/scenegraph/group-node.js.map +1 -1
  165. package/dist/scenegraph/model-node.js +1 -1
  166. package/dist/scenegraph/model-node.js.map +1 -1
  167. package/dist/scenegraph/scenegraph-bounds.js +1 -1
  168. package/dist/scenegraph/scenegraph-bounds.js.map +1 -1
  169. package/dist/scenegraph/scenegraph-node.js +4 -4
  170. package/dist/scenegraph/scenegraph-node.js.map +1 -1
  171. package/dist/shader-inputs.js +1 -1
  172. package/dist/shader-inputs.js.map +1 -1
  173. package/dist/utils/buffer-layout-helper.js +1 -1
  174. package/dist/utils/buffer-layout-helper.js.map +1 -1
  175. package/dist/utils/buffer-layout-order.js +1 -1
  176. package/dist/utils/buffer-layout-order.js.map +1 -1
  177. package/dist/utils/deep-equal.js +1 -1
  178. package/dist/utils/deep-equal.js.map +1 -1
  179. package/dist/utils/shader-module-utils.js +1 -1
  180. package/dist/utils/shader-module-utils.js.map +1 -1
  181. package/dist/utils/uid.js +1 -1
  182. package/dist/utils/uid.js.map +1 -1
  183. package/package.json +2 -2
  184. package/src/animation/animation-clip.ts +28 -0
  185. package/src/animation/animation-interpolation.ts +175 -0
  186. package/src/animation/animation-mixer.ts +370 -0
  187. package/src/animation/animation-track.ts +70 -0
  188. package/src/animation/animator.ts +1 -1
  189. package/src/animation/key-frames.ts +1 -1
  190. package/src/animation/morph-targets.ts +191 -0
  191. package/src/animation/skin.ts +50 -0
  192. package/src/animation/timeline.ts +1 -1
  193. package/src/animation-loop/animation-loop-template.ts +1 -1
  194. package/src/animation-loop/animation-loop.ts +8 -7
  195. package/src/animation-loop/animation-props.ts +2 -2
  196. package/src/animation-loop/make-animation-loop.ts +36 -6
  197. package/src/animation-loop/request-animation-frame.ts +1 -1
  198. package/src/application-utils/load-file.ts +1 -1
  199. package/src/application-utils/random.ts +1 -1
  200. package/src/compute/buffer-transform.ts +2 -2
  201. package/src/compute/computation.ts +47 -20
  202. package/src/compute/swap.ts +1 -1
  203. package/src/compute/texture-transform.ts +1 -1
  204. package/src/controls/orbit-controls.ts +248 -0
  205. package/src/debug/copy-texture-to-image.ts +1 -1
  206. package/src/debug/debug-framebuffer.ts +1 -1
  207. package/src/debug/debug-shader-layout.ts +1 -1
  208. package/src/debug/pixel-data-utils.ts +1 -1
  209. package/src/dynamic-buffer/dynamic-buffer.ts +1 -1
  210. package/src/dynamic-texture/dynamic-texture.ts +3 -2
  211. package/src/dynamic-texture/texture-binding-source.ts +1 -1
  212. package/src/dynamic-texture/texture-data.ts +1 -1
  213. package/src/dynamic-texture/video-texture.ts +1 -1
  214. package/src/geometries/cone-geometry.ts +1 -1
  215. package/src/geometries/cube-geometry.ts +1 -1
  216. package/src/geometries/cylinder-geometry.ts +1 -1
  217. package/src/geometries/ico-sphere-geometry.ts +1 -1
  218. package/src/geometry/geometry-table.ts +1 -1
  219. package/src/geometry/geometry-utils.ts +1 -1
  220. package/src/geometry/geometry.ts +1 -1
  221. package/src/geometry/gpu-geometry.ts +1 -1
  222. package/src/geometry/mesh-simplification.ts +554 -0
  223. package/src/index.ts +32 -1
  224. package/src/material/material-factory.ts +1 -1
  225. package/src/material/material.ts +1 -1
  226. package/src/model/model.ts +67 -12
  227. package/src/model/split-uniforms-and-bindings.ts +1 -1
  228. package/src/models/billboard-texture-model.ts +1 -1
  229. package/src/models/billboard-texture-module.ts +1 -1
  230. package/src/models/clip-space.ts +1 -1
  231. package/src/models/directional-light-model.ts +1 -1
  232. package/src/models/light-model-utils.ts +1 -1
  233. package/src/models/point-light-model.ts +1 -1
  234. package/src/models/spot-light-model.ts +1 -1
  235. package/src/modules/picking/color-picking.ts +1 -1
  236. package/src/modules/picking/index-color-picking.ts +1 -1
  237. package/src/modules/picking/index-picking.ts +1 -1
  238. package/src/modules/picking/legacy-color-picking.ts +1 -1
  239. package/src/modules/picking/legacy-picking-manager.ts +1 -1
  240. package/src/modules/picking/picking-manager.ts +1 -1
  241. package/src/modules/picking/picking-uniforms.ts +1 -1
  242. package/src/modules/picking/picking.ts +1 -1
  243. package/src/passes/get-fragment-shader.ts +1 -1
  244. package/src/passes/shader-pass-renderer.ts +246 -14
  245. package/src/passes/texture-transform-module.ts +1 -1
  246. package/src/scenegraph/group-node.ts +8 -1
  247. package/src/scenegraph/model-node.ts +1 -1
  248. package/src/scenegraph/scenegraph-bounds.ts +1 -1
  249. package/src/scenegraph/scenegraph-node.ts +4 -4
  250. package/src/shader-inputs.ts +1 -1
  251. package/src/utils/buffer-layout-helper.ts +1 -1
  252. package/src/utils/buffer-layout-order.ts +1 -1
  253. package/src/utils/deep-equal.ts +1 -1
  254. package/src/utils/shader-module-utils.ts +1 -1
  255. package/src/utils/uid.ts +1 -1
package/dist/dist.min.js CHANGED
@@ -4,7 +4,7 @@
4
4
  else if (typeof define === 'function' && define.amd) define([], factory);
5
5
  else if (typeof exports === 'object') exports['luma'] = factory();
6
6
  else root['luma'] = factory();})(globalThis, function () {
7
- "use strict";var __exports__=(()=>{var jr=Object.create;var Ge=Object.defineProperty;var Gr=Object.getOwnPropertyDescriptor;var $r=Object.getOwnPropertyNames;var Ur=Object.getPrototypeOf,Vr=Object.prototype.hasOwnProperty;var Xr=(i,e,t)=>e in i?Ge(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var $i=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Hr=(i,e)=>{for(var t in e)Ge(i,t,{get:e[t],enumerable:!0})},ct=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $r(e))!Vr.call(i,r)&&r!==t&&Ge(i,r,{get:()=>e[r],enumerable:!(n=Gr(e,r))||n.enumerable});return i},ht=(i,e,t)=>(ct(i,e,"default"),t&&ct(t,e,"default")),L=(i,e,t)=>(t=i!=null?jr(Ur(i)):{},ct(e||!i||!i.__esModule?Ge(t,"default",{value:i,enumerable:!0}):t,i)),Yr=i=>ct(Ge({},"__esModule",{value:!0}),i);var q=(i,e,t)=>(Xr(i,typeof e!="symbol"?e+"":e,t),t);var R=$i((Oa,Ui)=>{Ui.exports=globalThis.luma});var ae=$i((Qa,qi)=>{qi.exports=globalThis.luma});var nt={};Hr(nt,{AnimationClipController:()=>ut,AnimationLoop:()=>pe,AnimationLoopTemplate:()=>mt,Animator:()=>dt,AsyncTexture:()=>Pa,BackgroundTextureModel:()=>Le,BufferTransform:()=>Xe,ClipSpace:()=>he,Computation:()=>Je,ConeGeometry:()=>le,CubeGeometry:()=>jt,CylinderGeometry:()=>Gt,DirectionalLightModel:()=>Nt,DynamicBuffer:()=>j,DynamicTexture:()=>K,GPUGeometry:()=>Me,Geometry:()=>G,GroupNode:()=>ye,IcoSphereGeometry:()=>$t,KeyFrames:()=>ft,LegacyPickingManager:()=>Zt,Material:()=>Pe,MaterialFactory:()=>Se,Model:()=>Y,ModelNode:()=>zt,PickingManager:()=>Qe,PlaneGeometry:()=>Ut,PointLightModel:()=>kt,ScenegraphNode:()=>re,ShaderInputs:()=>V,ShaderPassRenderer:()=>Yt,SphereGeometry:()=>Oe,SpotLightModel:()=>Rt,Swap:()=>De,SwapBuffers:()=>Ht,SwapFramebuffers:()=>Be,TextureTransform:()=>vt,Timeline:()=>lt,TruncatedConeGeometry:()=>de,VideoTexture:()=>Xt,_resolveLoadFileUrl:()=>Vt,cancelAnimationFramePolyfill:()=>gt,colorPicking:()=>tt,getIndexPickingModule:()=>kr,indexColorPicking:()=>Kt,indexPicking:()=>it,legacyColorPicking:()=>Nr,loadImage:()=>mr,loadImageBitmap:()=>fr,makeAnimationLoop:()=>Wi,makeInterleavedGeometry:()=>xt,makeRandomGenerator:()=>hr,picking:()=>Or,requestAnimationFramePolyfill:()=>pt,resolvePickingBackend:()=>Lr,resolvePickingMode:()=>qt,setPathPrefix:()=>lr,supportsIndexPicking:()=>et});ht(nt,L(R(),1));var Vi=L(R(),1),ut=class{name;playing=!0;speed=1;startTime=0;constructor(e={}){this.name=e.name||"unnamed",Object.assign(this,e)}setTime(e){if(!this.playing)return;let n=(e/1e3-this.startTime)*this.speed;this.applyTime(n)}},dt=class{clips;animations;constructor(e){this.clips=e,this.animations=e}animate(e){Vi.log.warn(`${this.constructor.name}#animate is deprecated. Use ${this.constructor.name}#setTime instead`)(),this.setTime(e)}setTime(e){this.clips.forEach(t=>t.setTime(e))}getAnimations(){return this.clips}};var Wr=1,qr=1,lt=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(e){let{delay:t=0,duration:n=Number.POSITIVE_INFINITY,rate:r=1,repeat:s=1}=e,o=Wr++,a={time:0,delay:t,duration:n,rate:r,repeat:s};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(e){this.channels.delete(e);for(let[t,n]of this.animations)n.channel===e&&this.detachAnimation(t)}isFinished(e){let t=this.channels.get(e);return t===void 0?!1:this.time>=t.delay+t.duration*t.repeat}getTime(e){if(e===void 0)return this.time;let t=this.channels.get(e);return t===void 0?-1:t.time}setTime(e){this.time=Math.max(0,e);let t=this.channels.values();for(let r of t)this._setChannelTime(r,this.time);let n=this.animations.values();for(let r of n){let{animation:s,channel:o}=r;s.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(e,t){let n=qr++;return this.animations.set(n,{animation:e,channel:t}),e.setTime(this.getTime(t)),n}detachAnimation(e){this.animations.delete(e)}update(e){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=e),this.setTime(this.time+(e-this.lastEngineTime)),this.lastEngineTime=e)}_setChannelTime(e,t){let n=t-e.delay,r=e.duration*e.repeat;n>=r?e.time=e.duration*e.rate:(e.time=Math.max(0,n)%e.duration,e.time*=e.rate)}};var ft=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(e){this.setKeyFrames(e),this.setTime(0)}setKeyFrames(e){let t=e.length;this.times.length=t,this.values.length=t;for(let n=0;n<t;++n)this.times[n]=e[n][0],this.values[n]=e[n][1];this._calculateKeys(this._lastTime)}setTime(e){e=Math.max(0,e),e!==this._lastTime&&(this._calculateKeys(e),this._lastTime=e)}getStartTime(){return this.times[this.startIndex]}getEndTime(){return this.times[this.endIndex]}getStartData(){return this.values[this.startIndex]}getEndData(){return this.values[this.endIndex]}_calculateKeys(e){let t=0,n=this.times.length;for(t=0;t<n-2&&!(this.times[t+1]>e);++t);this.startIndex=t,this.endIndex=t+1;let r=this.times[this.startIndex],s=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(e-r)/(s-r)),1)}};var mt=class{constructor(e){}async onInitialize(e){return null}};var Hi=L(R(),1);function pt(i){let e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,i):setTimeout(()=>i(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function gt(i){let e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,i);return}clearTimeout(i)}function $e(){let i;if(typeof window<"u"&&window.performance)i=window.performance.now();else if(typeof process<"u"&&process.hrtime){let e=process.hrtime();i=e[0]*1e3+e[1]/1e6}else i=Date.now();return i}var me=class{constructor(e,t){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=e,this.type=t,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(e){return this.sampleSize=e,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(e){return this._count+=e,this._samples++,this._checkSampling(),this}subtractCount(e){return this._count-=e,this._samples++,this._checkSampling(),this}addTime(e){return this._time+=e,this.lastTiming=e,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=$e(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime($e()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var Ie=class{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,t="count"){return this._getOrCreate({name:e,type:t})}get size(){return Object.keys(this.stats).length}reset(){for(let e of Object.values(this.stats))e.reset();return this}forEach(e){for(let t of Object.values(this.stats))e(t)}getTable(){let e={};return this.forEach(t=>{e[t.name]={time:t.time||0,count:t.count||0,average:t.getAverageTime()||0,hz:t.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(t=>this._getOrCreate(t))}_getOrCreate(e){let{name:t,type:n}=e,r=this.stats[t];return r||(e instanceof me?r=e:r=new me(t,n),this.stats[t]=r),r}};var Kr=0,Zr="Animation Loop",Xi={requestAnimationFrame:i=>pt(i),cancelAnimationFrame:i=>gt(i)},Jt=class{device=null;canvas=null;props;animationProps=null;timeline=null;stats;sharedStats;cpuTime;gpuTime;frameRate;display;_needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;_lastFrameTime=0;constructor(e){if(this.props={...Jt.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new Ie({id:`animation-loop-${Kr++}`}),this.sharedStats=Hi.luma.stats.get(Zr),this.frameRate=this.stats.get("Frame Rate"),this.frameRate.setSampleSize(1),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.setProps({autoResizeViewport:e.autoResizeViewport,animationFrameProvider:e.animationFrameProvider}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null),this.device?._disableDebugGPUTime()}delete(){this.destroy()}reportError(e){this.props.onError(e),this._error=e}setNeedsRedraw(e){return this._needsRedraw=this._needsRedraw||e,this}needsRedraw(){let e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){if("autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),"animationFrameProvider"in e){let t=e.animationFrameProvider||Xi;if(t!==this.props.animationFrameProvider){let n=this._animationFrameId!==null;n&&this._cancelAnimationFrame(),this.props.animationFrameProvider=t,n&&this._requestAnimationFrame()}}return this}async start(){if(this._running)return this;this._running=!0;try{let e;if(!this._initialized){if(this._initialized=!0,await this._initDevice(),this._initialize(),!this._running)return null;await this.props.onInitialize(this._getAnimationProps())}return this._running?(e!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(e){let t=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(t),t}}stop(){return this._running&&(this.animationProps&&!this._error&&this.props.onFinalize(this.animationProps),this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1,this._lastFrameTime=0),this}redraw(e,t=null){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),this._setupFrame(),this.animationProps&&(this.animationProps.animationFrame=t),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(e){return this.timeline=e,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(e=>{this._resolveNextFrame=e})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeViewport(),this.device?._enableDebugGPUTime()}_setDisplay(e){this.display&&(this.display.destroy(),this.display.animationLoop=null),e&&(e.animationLoop=this),this.display=e}_requestAnimationFrame(){this._running&&(this._animationFrameId=this.props.animationFrameProvider.requestAnimationFrame(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(this.props.animationFrameProvider.cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e,t){this._running&&(this.redraw(e,t??null),this._requestAnimationFrame())}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}this.props.onRender(this._getAnimationProps()),this.device&&this.device.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){let e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");let t=e?.canvas,n=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:t,useDevicePixels:n,timeline:this.timeline,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,animationFrame:null,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:e,height:t,aspect:n}=this._getSizeAndAspect();(e!==this.animationProps.width||t!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),n!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=e,this.animationProps.height=t,this.animationProps.aspect=n,this.animationProps.needsRedraw=this._needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.getDefaultCanvasContext().canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";let t=document.createElement("div");t.style.position="absolute",t.style.left="10px",t.style.bottom="10px",t.style.width="300px",t.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(t);let n=this.props.onAddHTML(t);n&&(t.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[e,t]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),n=e>0&&t>0?e/t:1;return{width:e,height:t,aspect:n}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(e){let t=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let n=t-this._lastFrameTime;n>0&&this.frameRate.addTime(n)}this._lastFrameTime=t,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let e=this.device.commandEncoder._gpuTimeMs;e!==void 0&&(this.gpuTime.addTime(e),this.device.commandEncoder._gpuTimeMs=void 0)}_updateSharedStats(){if(this.stats!==this.sharedStats){for(let e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{let t=this.sharedStats.get(e.name,e.type);t.sampleSize=e.sampleSize,t.time=e.time,t.count=e.count,t.samples=e.samples,t.lastTiming=e.lastTiming,t.lastSampleTime=e.lastSampleTime,t.lastSampleCount=e.lastSampleCount,t._count=e._count,t._time=e._time,t._samples=e._samples,t._startTime=e._startTime,t._timerPending=e._timerPending})}}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(e){e instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[e.offsetX,e.offsetY])}_onMouseleave(e){this._getAnimationProps()._mousePosition=null}},pe=Jt;q(pe,"defaultAnimationLoopProps",{device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>{console.error(e)},stats:void 0,autoResizeViewport:!1,animationFrameProvider:Xi});var Yi=L(R(),1);function Wi(i,e){let t=null,n=e?.device||Yi.luma.createDevice({id:"animation-loop",adapters:e?.adapters,createCanvasContext:!0}),r=new pe({...e,device:n,async onInitialize(s){Qr(s.animationLoop.device);try{return t=new i(s),await t?.onInitialize(s)}catch(o){return console.error(o),t=null,Jr(s.animationLoop.device,o),s.animationLoop.stop(),null}},onRender:s=>t?.onRender(s),onFinalize:s=>t?.onFinalize(s)});return r.getInfo=()=>this.AnimationLoopTemplateCtor.info,r}function Jr(i,e){if(!i)return;let t=i.getDefaultCanvasContext().canvas;if(t instanceof HTMLCanvasElement){t.style.overflow="visible";let n=document.getElementById("animation-loop-error");n?.remove(),n=document.createElement("h1"),n.id="animation-loop-error",n.innerHTML=e.message,n.style.position="absolute",n.style.top="10px",n.style.left="10px",n.style.color="black",n.style.backgroundColor="red",t.parentElement?.appendChild(n)}}function Qr(i){if(!i)return;let e=document.getElementById("animation-loop-error");e&&e.remove()}var T=L(R(),1),Ee=L(ae(),1);var ti=L(R(),1);var Ki=L(R(),1);var Qt={};function S(i="id"){Qt[i]=Qt[i]||1;let e=Qt[i]++;return`${i}-${e}`}var G=class{id;topology;vertexCount;indices;attributes;bufferLayout;userData={};constructor(e){let{attributes:t={},indices:n=null,vertexCount:r=null}=e;this.id=e.id||S("geometry"),this.topology=e.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(let[s,o]of Object.entries(t)){let a=ArrayBuffer.isView(o)?{value:o}:o;if(!ArrayBuffer.isView(a.value))throw new Error(`${this._print(s)}: must be typed array or object with value as typed array`);if((s==="POSITION"||s==="positions")&&!a.size&&(a.size=3),s==="indices"){if(this.indices)throw new Error("Multiple indices detected");this.indices=a}else{let c=ge(s),u=Object.keys(this.attributes).find(h=>ge(h)===c);u&&delete this.attributes[u],this.attributes[s]=a}}this.indices&&this.indices.isIndexed!==void 0&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=r||this._calculateVertexCount(this.attributes,this.indices),this.bufferLayout=e.bufferLayout||es(this.attributes)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(e){return`Geometry ${this.id} attribute ${e}`}_setAttributes(e,t){return this}_calculateVertexCount(e,t){if(t)return t.value.length;let n=1/0;for(let r of Object.values(e)){if(!r)continue;let{value:s,size:o,constant:a}=r;!a&&s&&o!==void 0&&o>=1&&(n=Math.min(n,s.length/o))}return n}};function ge(i){switch(i){case"POSITION":return"positions";case"NORMAL":return"normals";case"TEXCOORD_0":return"texCoords";case"TEXCOORD_1":return"texCoords1";case"COLOR_0":return"colors";default:return i}}function es(i){let e=[];for(let[t,n]of Object.entries(i)){if(!n)continue;let{value:r,size:s,normalized:o}=n;if(s===void 0)throw new Error(`Attribute ${t} is missing a size`);e.push({name:ge(t),format:Ki.vertexFormatDecoder.getVertexFormatFromAttribute(r,s,o)})}return e}var ei=L(R(),1);function Ji(i){let{indices:e,attributes:t}=i;if(!e)return i;let n=e.value.length,r={};for(let s in t){let o=t[s];if(!o)continue;let{value:a,size:c}=o;if(o.constant||!c)continue;let h=a.constructor,l=new h(n*c);for(let d=0;d<n;++d){let m=e.value[d];for(let p=0;p<c;p++)l[d*c+p]=a[m*c+p]}r[s]={size:c,value:l}}return{attributes:Object.assign({},t,r)}}function xt(i,e={}){let t=e.bufferName||"geometry";if(ts(i,t))return i;let n=e.minAttributeAlignment||4,r=is(i,e.attributes),s=[],o=0,a=1/0;for(let[h,l]of r){if(!l)continue;if(l.constant)throw new Error(`Attribute ${h} is constant`);let{value:d,size:m,normalized:p}=l;if(!ArrayBuffer.isView(d))throw new Error(`Attribute ${h} is missing typed array data`);if(m===void 0)throw new Error(`Attribute ${h} is missing a size`);let f=ei.vertexFormatDecoder.getVertexFormatFromAttribute(d,m,p),x=ei.vertexFormatDecoder.getVertexFormatInfo(f);o=Zi(o,n),s.push({sourceName:h,attributeName:ge(h),value:d,size:m,format:f,byteOffset:o,byteLength:x.byteLength}),o+=x.byteLength;let y=d.length/m;if(!Number.isInteger(y))throw new Error(`Attribute ${h} length is not divisible by size`);a=Math.min(a,y)}if(s.length===0||!Number.isFinite(a))throw new Error(`Geometry ${i.id} has no interleavable attributes`);let c=Zi(o,n),u=new ArrayBuffer(a*c);for(let h of s)ns(u,a,c,h);return new G({id:i.id,topology:i.topology||"triangle-list",vertexCount:i.vertexCount,indices:i.indices,attributes:{[t]:{value:new Uint8Array(u),size:c,byteStride:c}},bufferLayout:[{name:t,stepMode:"vertex",byteStride:c,attributes:s.map(h=>({attribute:h.attributeName,format:h.format,byteOffset:h.byteOffset}))}]})}function ts(i,e){if(i.bufferLayout.length!==1)return!1;let t=i.bufferLayout[0];return t.name===e&&Boolean(t.attributes?.length)&&Boolean(i.attributes[e])}function is(i,e){return e?e.map(t=>[t,i.attributes[t]]):Object.entries(i.attributes)}function ns(i,e,t,n){let r=n.value.constructor,s=r.BYTES_PER_ELEMENT;if(n.byteOffset%s!==0||t%s!==0)throw new Error(`Attribute ${n.sourceName} is not aligned to its component type`);let o=new r(i),a=n.value,c=n.byteOffset/s,u=t/s;for(let h=0;h<e;h++){let l=h*n.size,d=h*u+c;for(let m=0;m<n.size;m++)o[d+m]=a[l+m]}}function Zi(i,e){return Math.ceil(i/e)*e}var Me=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||S("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&ti.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function Qi(i,e){if(e instanceof Me)return e;let t=xt(e),n=rs(i,t),{attributes:r,bufferLayout:s}=ss(i,t);return new Me({topology:t.topology||"triangle-list",bufferLayout:s,vertexCount:t.vertexCount,indices:n,attributes:r})}function rs(i,e){if(!e.indices)return;let t=e.indices.value;return i.createBuffer({usage:ti.Buffer.INDEX,data:t})}function ss(i,e){let t={};for(let[n,r]of Object.entries(e.attributes)){let s=e.bufferLayout.find(o=>o.name===n)?.name||ge(n);r&&(t[s]=i.createBuffer({data:r.value,id:`${n}-buffer`}))}return{attributes:t,bufferLayout:e.bufferLayout,vertexCount:e.vertexCount}}function en(i,e){let t={},n="Values";if(i.attributes.length===0&&!i.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let r of i.attributes)if(r){let s=`${r.location} ${r.name}: ${r.type}`;t[`in ${s}`]={[n]:r.stepMode||"vertex"}}for(let r of i.varyings||[]){let s=`${r.location} ${r.name}`;t[`out ${s}`]={[n]:JSON.stringify(r)}}return t}var tn="__debugFramebufferState";function rn(i,e,t){if(i.device.type!=="webgl")return;let n=cs(i.device);if(!n.flushing){if(us(i)){os(i,t,n);return}e&&hs(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function os(i,e,t){if(t.queuedFramebuffers.length===0)return;let n=i.device,{gl:r}=n,s=r.getParameter(36010),o=r.getParameter(36006),[a,c]=i.device.getDefaultCanvasContext().getDrawingBufferSize(),u=nn(e.top,8),h=nn(e.left,8);t.flushing=!0;try{for(let l of t.queuedFramebuffers){let[d,m,p,f,x]=as({framebuffer:l,targetWidth:a,targetHeight:c,topPx:u,leftPx:h,minimap:e.minimap});r.bindFramebuffer(36008,l.handle),r.bindFramebuffer(36009,null),r.blitFramebuffer(0,0,l.width,l.height,d,m,p,f,16384,9728),u+=x+8}}finally{r.bindFramebuffer(36008,s),r.bindFramebuffer(36009,o),t.flushing=!1}}function as(i){let{framebuffer:e,targetWidth:t,targetHeight:n,topPx:r,leftPx:s,minimap:o}=i,a=o?Math.max(Math.floor(t/4),1):t,c=o?Math.max(Math.floor(n/4),1):n,u=Math.min(a/e.width,c/e.height),h=Math.max(Math.floor(e.width*u),1),l=Math.max(Math.floor(e.height*u),1),d=s,m=Math.max(n-r-l,0),p=d+h,f=m+l;return[d,m,p,f,l]}function cs(i){return i.userData[tn]||={flushing:!1,queuedFramebuffers:[]},i.userData[tn]}function hs(i){return"colorAttachments"in i}function us(i){let e=i.props.framebuffer;return!e||e.handle===null}function nn(i,e){if(!i)return e;let t=Number.parseInt(i,10);return Number.isFinite(t)?t:e}function ve(i,e,t){if(i===e)return!0;if(!t||!i||!e)return!1;if(Array.isArray(i)){if(!Array.isArray(e)||i.length!==e.length)return!1;for(let n=0;n<i.length;n++)if(!ve(i[n],e[n],t-1))return!1;return!0}if(Array.isArray(e))return!1;if(typeof i=="object"&&typeof e=="object"){let n=Object.keys(i),r=Object.keys(e);if(n.length!==r.length)return!1;for(let s of n)if(!e.hasOwnProperty(s)||!ve(i[s],e[s],t-1))return!1;return!0}return!1}var sn=L(R(),1),Te=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return(0,sn.getBufferLayoutAttributeNames)(e)}mergeBufferLayouts(e,t){let n=[...e];for(let r of t){let s=n.findIndex(o=>o.name===r.name);s<0?n.push(r):n[s]=r}return n}};var ce=L(R(),1);function on(i,e){let t=(0,ce.getShaderAttributeLocationMap)(i),n=e.slice();return n.sort((r,s)=>{let o=(0,ce.getMinimumAttributeLocation)((0,ce.getBufferLayoutAttributeNames)(r).map(c=>t[c])),a=(0,ce.getMinimumAttributeLocation)((0,ce.getBufferLayoutAttributeNames)(s).map(c=>t[c]));return o-a}),n}function we(i,e){if(!i||!e.some(n=>n.bindingLayout?.length))return i;let t={...i,bindings:i.bindings.map(n=>({...n}))};"attributes"in(i||{})&&(t.attributes=i?.attributes||[]);for(let n of e)for(let r of n.bindingLayout||[])for(let s of ds(r.name)){let o=t.bindings.find(a=>a.name===s);o?.group===0&&(o.group=r.group),o&&r.visibility!==void 0&&(o.visibility=r.visibility)}return t}function an(i,e,t=[]){return i?e?{...i,attributes:i.attributes.length?ms(i.attributes,e.attributes.filter(n=>t.includes(n.name))):e.attributes,bindings:fs(i.bindings,e.bindings)}:i:e}function Ae(i){return Boolean(i.uniformTypes&&!ls(i.uniformTypes))}function bt(i,e){let t=[],n=new Set;for(let r of[...i||[],...e||[]])n.has(r.name)||(n.add(r.name),t.push(r));return t}function ds(i){let e=new Set([i,`${i}Uniforms`]);return i.endsWith("Uniforms")||e.add(`${i}Sampler`),[...e]}function ls(i){for(let e in i)return!1;return!0}function fs(i,e){let t=i.map(s=>({...s})),n=new Set(i.map(s=>s.name)),r=new Set(i.map(s=>`${s.group}:${s.location}`));for(let s of e){let o=`${s.group}:${s.location}`;!n.has(s.name)&&!r.has(o)&&t.push({...s})}return t}function ms(i,e){let t=i.map(s=>({...s})),n=new Map(i.map(s=>[s.name,s])),r=new Map(i.map(s=>[s.location,s]));for(let s of e){let o=n.get(s.name);if(o){if(o.type!==s.type||o.location!==s.location)throw new Error(`Shader attribute "${s.name}" conflicts with its inferred type or location`);continue}let a=r.get(s.location);if(a)throw new Error(`Shader attributes "${a.name}" and "${s.name}" both use location ${s.location}`);t.push({...s})}return t}var yt=L(R(),1),ii=L(ae(),1);function cn(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function hn(i){return Array.isArray(i)?i.length===0||typeof i[0]=="number":!1}function Ue(i){return cn(i)||hn(i)}function ps(i){return Ue(i)||typeof i=="number"||typeof i=="boolean"}function un(i,e={}){let t={bindings:{},uniforms:{}};return Object.keys(i).forEach(n=>{let r=i[n];Object.prototype.hasOwnProperty.call(e,n)||ps(r)?t.uniforms[n]=r:t.bindings[n]=r}),t}var V=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;directBindings={};constructor(e,t){Object.assign(this.options,t);let n=(0,ii.getShaderModuleDependencies)(Object.values(e).filter(gs));for(let r of n)e[r.name]=r;yt.log.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[r,s]of Object.entries(e))s&&(this._addModule(s),s.name&&r!==s.name&&!this.options.disableWarnings&&yt.log.warn(`Module name: ${r} vs ${s.name}`)())}destroy(){}setProps(e){e.bindings&&Object.assign(this.directBindings,e.bindings);for(let t of Object.keys(e)){if(t==="bindings")continue;let n=t,r=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||yt.log.warn(`Module ${t} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(r,o)||r,{uniforms:u,bindings:h}=un(c,s.uniformTypes);this.moduleUniforms[n]=dn(o,u,s.uniformTypes),this.moduleBindings[n]={...a,...h}}}}getModules(){return Object.values(this.modules)}addModules(e){let t=(0,ii.getShaderModuleDependencies)(e);for(let n of t){let r=n.name;this.modules[r]||(this.modules[r]=n,this._addModule(n))}}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let t of Object.values(this.moduleBindings))Object.assign(e,t);return Object.assign(e,this.directBindings),e}getModuleBindingValues(e){let t=this.moduleBindings[e];return t?{...t}:{}}getDebugTable(){let e={};for(let[t,n]of Object.entries(this.moduleUniforms))for(let[r,s]of Object.entries(n))e[`${t}.${r}`]={type:this.modules[t].uniformTypes?.[r],value:String(s)};return e}_addModule(e){let t=e.name;this.moduleUniforms[t]=dn({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[t]={}}};function dn(i={},e={},t={}){let n={...i};for(let[r,s]of Object.entries(e))s!==void 0&&(n[r]=ni(i[r],s,t[r]));return n}function ni(i,e,t){if(!t||typeof t=="string")return Ve(e);if(Array.isArray(t)){if(ri(e)||!Array.isArray(e))return Ve(e);let o=Array.isArray(i)&&!ri(i)?[...i]:[],a=o.slice();for(let c=0;c<e.length;c++){let u=e[c];u!==void 0&&(a[c]=ni(o[c],u,t[0]))}return a}if(!si(e))return Ve(e);let n=t,r=si(i)?i:{},s={...r};for(let[o,a]of Object.entries(e))a!==void 0&&(s[o]=ni(r[o],a,n[o]));return s}function Ve(i){return ArrayBuffer.isView(i)?Array.prototype.slice.call(i):Array.isArray(i)?ri(i)?i.slice():i.map(t=>t===void 0?void 0:Ve(t)):si(i)?Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t===void 0?void 0:Ve(t)])):i}function ri(i){return ArrayBuffer.isView(i)||Array.isArray(i)&&(i.length===0||typeof i[0]=="number")}function si(i){return Boolean(i)&&typeof i=="object"&&!Array.isArray(i)&&!ArrayBuffer.isView(i)}function gs(i){return Boolean(i?.dependencies)}var oi=L(R(),1);var xs=oi.Buffer.DEBUG_DATA_MAX_LENGTH,j=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:r,ownsBuffer:s=!0,...o}=t;if(r&&r.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(r&&(o.byteLength!==void 0||o.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||r?.id||S("dynamic-buffer"),c={...o,id:a,usage:o.usage??r?.usage,indexType:o.indexType??r?.indexType};(c.usage||0)&oi.Buffer.INDEX&&!c.indexType&&(o.data instanceof Uint32Array?c.indexType="uint32":o.data instanceof Uint16Array?c.indexType="uint16":o.data instanceof Uint8Array&&(c.indexType="uint8")),delete c.data,delete c.byteOffset,this.device=e,this.id=a,this.props=c,this.usage=c.usage||0,this._debugDataEnabled=Boolean(n),this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:xs,this._ownsBuffer=s,this._buffer=r??this.device.createBuffer({...o,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),o.data&&this._writeDebugData(o.data,o.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let r=null;await this._buffer.mapAndWriteAsync(async(s,o)=>{await e(s,o),r=new Uint8Array(s.slice(0,n))},t,n),this._touch(),r&&this._writeDebugData(r,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let r=null,s=await this._buffer.mapAndReadAsync(async(o,a)=>(r=new Uint8Array(o.slice(0)),await e(o,a)),t,n);return r&&this._writeDebugData(r,t)&&this._touch(),s}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let r=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),s=this._buffer,o=this.debugData.slice(0),{data:a,byteOffset:c,...u}=this.props,h=this.device.createBuffer({...u,byteLength:t});return n&&r>0&&this._copyBufferContents(s,h,r),this._buffer=h,this._resetDebugData(t),n&&o.byteLength>0&&this._writeDebugData(o,0),this._ownsBuffer&&s.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let r=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,s=this.device.createCommandEncoder();s.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:r}),this.device.submit(s.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=new Uint8Array(this.debugData),s=Math.min(n.byteLength,r.byteLength-t);return r.set(n.subarray(0,s),t),s>0}};function xe(i){return i!==null&&typeof i=="object"&&"buffer"in i}function ln(i){return i instanceof j?i:xe(i)&&i.buffer instanceof j?i.buffer:null}function bs(i){return i instanceof j?i.buffer:i}function _t(i){return{buffer:bs(i.buffer),offset:i.offset,size:i.size}}var fn=L(R(),1);function ie(i){return i!==null&&typeof i=="object"&&"resolveTextureBinding"in i&&typeof i.resolveTextureBinding=="function"}function ys(i){return i?.type==="texture"||i?.type==="external-texture"}function It(i,e,t){let n=(0,fn.getShaderLayoutBinding)(i,e,{ignoreWarnings:!0});return ys(n)?n:i.bindings.length===0&&t?.fallbackGroup!==void 0?{type:"texture",name:e,group:t.fallbackGroup,location:0}:null}var Q=2,_s=1e4,ai="render pipeline initialization failed",Is=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],ci=class{device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;material=null;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_lastDrawTimestamp=-1;_bindingTable=[];get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(e,t){this.props={...ci.defaultProps,...t},t=this.props,this.id=t.id||S("model"),this.device=e,Object.assign(this.userData,t.userData),this.material=t.material||null;let n=As(e),r=(0,Ee.resolveShaderPlugins)(this.props.plugins,n.shaderLanguage),s=(0,Ee.mergeShaderPluginModules)(this.props.modules,r.modules),o=Object.fromEntries(s.map(l=>[l.name,l])),a=t.shaderInputs||new V(o,{disableWarnings:this.props.disableWarnings});t.shaderInputs&&r.modules.length>0&&a.addModules(r.modules),this.setShaderInputs(a);let c=bt(this.props.modules,a.getModules()),u={...r.defines,...this.props.defines};if(this.props.shaderLayout=we(this.props.shaderLayout,c)||null,this.device.type==="webgpu"&&this.props.source){let{source:l,getUniforms:d,bindingTable:m}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:n,...this.props,modules:c,defines:u,pluginInjections:r.injections,pluginVertexInputs:r.vertexInputs,pluginVaryings:r.varyings});this.source=l,this._getModuleUniforms=d,this._bindingTable=m;let p=e.getShaderLayout?.(this.source),f=Ms(p,r.vertexInputs),x=an(this.props.shaderLayout,f,Object.keys(r.vertexInputs));this.props.shaderLayout=we(x||null,c)||null}else{let{vs:l,fs:d,getUniforms:m}=this.props.shaderAssembler.assembleGLSLShaderPair({platformInfo:n,...this.props,modules:c,defines:u,pluginInjections:r.injections,pluginVertexInputs:r.vertexInputs,pluginVaryings:r.varyings});this.vs=l,this.fs=d,this._getModuleUniforms=m,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,t.geometry&&this.setGeometry(t.geometry),this.pipelineFactory=t.pipelineFactory||T.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||T.ShaderFactory.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=e.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in t&&(this.isInstanced=t.isInstanced),t.instanceCount&&this.setInstanceCount(t.instanceCount),t.vertexCount&&this.setVertexCount(t.vertexCount),t.indexBuffer&&this.setIndexBuffer(t.indexBuffer),t.attributes&&this.setAttributes(t.attributes),t.constantAttributes&&this.setConstantAttributes(t.constantAttributes),t.bindings&&this.setBindings(t.bindings),t.transformFeedback&&(this.transformFeedback=t.transformFeedback)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.material?.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e){if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return T.log.info(Q,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;let t=this._areBindingsLoading();if(t)return T.log.info(Q,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),this.device.type==="webgpu"?(this.updateShaderInputs(),this.material?.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}finally{e.popDebugGroup()}let n,r=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),r=this.pipeline.isErrored,r)T.log.info(Q,`>>> DRAWING ABORTED ${this.id}: ${ai}`)(),n=!1;else{let s=this.vertexArray.getDrawValidationError();if(s)T.log.info(Q,`>>> DRAWING ABORTED ${this.id}: ${s}`)(),this._drawBlockedReason=s,n=!1;else{let o=this._getCurrentShaderLayout(),a=this._getBindings(o),c=this._getBindGroups(o,a),{indexBuffer:u}=this.vertexArray,h=u?this.indexCount??u.byteLength/(u.indexType==="uint32"?4:2):void 0;e.setPipeline(this.pipeline),e.setBindings(c,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=this.isInstanced===!0&&this.instanceCount===0?!0:e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:h,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):r?(this._needsRedraw=ai,this._drawBlockedReason=ai):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){this._gpuGeometry?.destroy();let t=e&&Qi(this.device,e);if(t){this.setTopology(t.topology||"triangle-list");let n=new Te(this.bufferLayout);this.bufferLayout=n.mergeBufferLayouts(t.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(t)}this._gpuGeometry=t}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){let t=new Te(this.bufferLayout),n=this._gpuGeometry?t.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e;ve(n,this.bufferLayout,-1)||(this.bufferLayout=n,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry))}setParameters(e){ve(e,this.parameters,2)||(this.parameters=e,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this.setNeedsRedraw("vertexCount")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new T.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(Ae(n)&&!this.material?.ownsModule(t)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())),this.setNeedsRedraw("shaderInputs")}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){let t=e instanceof j?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof j?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){this._drawBlockedReason=!1;let n=t?.disableWarnings??this.props.disableWarnings;e.indices&&T.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=on(this.pipeline.shaderLayout,this.bufferLayout);let r=new Te(this.bufferLayout);for(let[s,o]of Object.entries(e)){let a=o instanceof j?o.buffer:o,c=r.getBufferLayout(s);if(!c){n||T.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let u=r.getAttributeNamesForBuffer(c),h=!1;for(let l of u){let d=this._attributeInfos[l];if(d){let m=this.device.type==="webgpu"?this.vertexArray.getBufferSlot(d.bufferName):d.location;if(m===null){n||T.log.warn(`Model(${this.id}): Missing vertex array slot for buffer "${d.bufferName}".`)();continue}this.vertexArray.setBuffer(m,a),o instanceof j?this._dynamicAttributeBufferSources[m]={source:o,generation:o.generation}:delete this._dynamicAttributeBufferSources[m],h=!0}}!h&&!n&&T.log.warn(`Model(${this.id}): Ignoring buffer "${a.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(let[n,r]of Object.entries(e)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,r):(t?.disableWarnings??this.props.disableWarnings)||T.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(ie(e)&&!e.isReady)return e.id;for(let e of Object.values(this.material?.bindings||{}))if(ie(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){let t={};for(let[n,r]of Object.entries(this.bindings)){let s=vs(n,r,e);s&&(t[n]=s)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){let n=e.bindings.length?(0,T.normalizeBindingsByGroup)(e,t):{0:t};if(!this.material)return n;for(let[r,s]of Object.entries(this.material.getBindingsByGroup(e))){let o=Number(r);n[o]={...n[o]||{},...s}}return n}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(let t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(let t of Object.values(this.bindings))t instanceof T.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof T.Buffer||t instanceof T.Texture||t instanceof T.ExternalTexture||t instanceof j?e=Math.max(e,t.updateTimestamp):ie(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:xe(t)&&(e=Math.max(e,(t.buffer instanceof j,t.buffer.updateTimestamp)));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){let t={...e.attributes};for(let[n]of Object.entries(t))!this.pipeline.shaderLayout.attributes.find(r=>r.name===n)&&n!=="positions"&&delete t[n];this.vertexCount=e.vertexCount,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(t,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,t=null;this.pipeline&&(T.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,t=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),r=null;this.source?r=n:this.fs&&(r=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:r}),this._attributeInfos=(0,T.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=T.log.level>3?0:_s;T.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,T.log.group(Q,`>>> DRAWING MODEL ${this.id}`,{collapsed:T.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=en(this.pipeline.shaderLayout,this.id);T.log.table(Q,e)();let t=this.shaderInputs.getDebugTable();T.log.table(Q,t)();let n=this._getAttributeDebugTable();T.log.table(Q,this._attributeInfos)(),T.log.table(Q,n)(),T.log.groupEnd(Q)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;let n=e.props.framebuffer;rn(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[t,n]of Object.entries(this._attributeInfos)){let r=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:r?this._getBufferOrConstantValues(r,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:t}=this.vertexArray,n=t.indexType==="uint32"?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){let n=T.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof T.Buffer?new n(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;let t={};for(let[n,r]of Object.entries(e))this.material.ownsBinding(n)||(t[n]=r);return t}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){let e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(let[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if(this.device.type!=="webgpu")return;let t=e.framebuffer||e.props.framebuffer,n=e.props,r=n.colorAttachmentFormats??t?.colorAttachments?.map(o=>Ts(o?.texture?.format)),s=n.depthStencilAttachmentFormat===!1?void 0:n.depthStencilAttachmentFormat??ws(t?.depthStencilAttachment?.texture?.format);(!ve(this._colorAttachmentFormats,r,1)||this._depthStencilAttachmentFormat!==s)&&(this._colorAttachmentFormats=r,this._depthStencilAttachmentFormat=s,this._setPipelineNeedsUpdate("attachment formats"))}},Y=ci;q(Y,"defaultProps",{...T.RenderPipeline.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],geometry:null,indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,material:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:Ee.ShaderAssembler.getDefaultShaderAssembler(),debugShaders:void 0,disableWarnings:void 0});function Ms(i,e){return!i||Object.keys(e).length===0?i:{...i,attributes:i.attributes.map(t=>{let n=t.name.startsWith("_luma_")?t.name.slice(6):null;return n&&e[n]?{...t,name:n}:t})}}function vs(i,e,t){if(ie(e)){let n=It(t,i,{fallbackGroup:0});return n?e.resolveTextureBinding(n):null}return e instanceof j?e.buffer:xe(e)?_t(e):e}function Ts(i){return i&&!mn(i)?i:null}function ws(i){return i&&mn(i)?i:void 0}function mn(i){return Is.includes(i)}function As(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}var ee=L(R(),1);var Ce=3,Se=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(e,t={}){this.device=e,this.modules=t.modules||[];let n=new V(Object.fromEntries(this.modules.map(r=>[r.name,r])));this._materialBindingNames=Es(n),this._materialModuleNames=Ss(n)}createMaterial(e={}){return new Pe(this.device,{...e,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(e){if(this._materialBindingNames.has(e))return!0;let t=hi(e);return t?this._materialModuleNames.has(t):!1}ownsModule(e){return this._materialModuleNames.has(e)}getBindingsByGroup(e){return Object.keys(e).length>0?{[Ce]:e}:{}}};function hi(i){return i.endsWith("Uniforms")?i.slice(0,-8):null}function Es(i){let e=new Set;for(let t of Object.values(i.modules))for(let n of t.bindingLayout||[])n.group===Ce&&e.add(n.name);return e}function Ss(i){let e=new Set;for(let t of Object.values(i.modules))t.name&&t.bindingLayout?.some(n=>n.group===Ce&&n.name===t.name)&&e.add(t.name);return e}var Pe=class{id;device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};_dynamicResourceGenerations={};constructor(e,t={}){this.id=t.id||S("material"),this.device=e,this.factory=t.factory||new Se(e,{modules:t.modules||t.shaderInputs?.getModules()||[]});let n=Object.fromEntries((t.shaderInputs?.getModules()||this.factory.modules).map(r=>[r.name,r]));this.shaderInputs=t.shaderInputs||new V(n),this._uniformStore=new ee.UniformStore(this.device,this.shaderInputs.modules);for(let[r,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(r)&&Ae(s)){let o=this._uniformStore.getManagedUniformBuffer(r);this.bindings[`${r}Uniforms`]=o}this.updateShaderInputs(),t.bindings&&this._replaceOwnedBindings(t.bindings)}destroy(){this._uniformStore.destroy()}clone(e={}){let t=this.factory.createMaterial({id:e.id,shaderInputs:e.shaderInputs,bindings:{...this.getResourceBindings(),...e.bindings}});return e.shaderInputs||t.setProps(this.shaderInputs.getUniformValues()),e.moduleProps&&t.setProps(e.moduleProps),t.updateShaderInputs(),t}ownsBinding(e){return this.factory.ownsBinding(e)}ownsModule(e){return this.factory.ownsModule(e)}setProps(e){this.shaderInputs.setProps(e)}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this._setOwnedBindings(this.shaderInputs.getBindingValues())&&(this._bindGroupCacheToken={})}getResourceBindings(){let e={};for(let[t,n]of Object.entries(this.bindings))hi(t)||(e[t]=n);return e}getBindings(e={bindings:[]}){this._syncDynamicResourceGenerations();let t={},n=t;for(let[r,s]of Object.entries(this.bindings))if(ie(s)){let o=It(e,r,{fallbackGroup:Ce}),a=o?s.resolveTextureBinding(o):null;a&&(n[r]=a)}else s instanceof j?n[r]=s.buffer:xe(s)?n[r]=_t(s):n[r]=s;return this._syncDynamicResourceGenerations(),t}getBindingsByGroup(e={bindings:[]}){return this.factory.getBindingsByGroup(this.getBindings(e))}getBindGroupCacheKey(e){return this._syncDynamicResourceGenerations(),e===Ce?this._bindGroupCacheToken:null}getBindingsUpdateTimestamp(){let e=0;for(let t of Object.values(this.bindings))t instanceof ee.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof ee.Buffer||t instanceof ee.Texture||t instanceof ee.ExternalTexture||t instanceof j?e=Math.max(e,t.updateTimestamp):ie(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:xe(t)&&(e=Math.max(e,(t.buffer instanceof j,t.buffer.updateTimestamp)));return e}_replaceOwnedBindings(e){this._setOwnedBindings(e)&&(this._bindGroupCacheToken={})}_setOwnedBindings(e){let t=!1;for(let[n,r]of Object.entries(e))r!==void 0&&this.ownsBinding(n)&&this.bindings[n]!==r&&(this.bindings[n]=r,t=!0);return t}_syncDynamicResourceGenerations(){let e={},t=!1;for(let[n,r]of Object.entries(this.bindings)){let s=Cs(r);s!==null&&(e[n]=s,this._dynamicResourceGenerations[n]!==s&&(t=!0))}Object.keys(e).length!==Object.keys(this._dynamicResourceGenerations).length&&(t=!0),this._dynamicResourceGenerations=e,t&&(this._bindGroupCacheToken={})}};function Cs(i){return ie(i)?i.generation:ln(i)?.generation??null}var pn=L(R(),1),gn=L(ae(),1);var Ps=35980,Ls=35981,Mt=class{device;model;transformFeedback;static isSupported(e){return e?.info?.type==="webgl"}constructor(e,t=Mt.defaultProps){if(!Mt.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.model=new Y(this.device,{id:t.id||"buffer-transform-model",fs:t.fs||(0,gn.getPassthroughFS)(),topology:t.topology||"point-list",varyings:t.outputs||t.varyings,...t,bufferMode:t.bufferMode||(t.feedbackBufferMode==="interleaved"?Ps:Ls)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:t.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){e?.inputBuffers&&this.model.setAttributes(e.inputBuffers),e?.outputBuffers&&this.transformFeedback.setBuffers(e.outputBuffers);let t=this.device.beginRenderPass({discard:!0,...e});this.model.draw(t),t.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof pn.Buffer)return t.readAsync();let{buffer:n,byteOffset:r=0,byteLength:s=n.byteLength}=t;return n.readAsync(r,s)}},Xe=Mt;q(Xe,"defaultProps",{...Y.defaultProps,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0});var xn=L(ae(),1);var Os="transform_output",vt=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(e,t){this.device=e,this.sampler=e.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new Y(this.device,{id:t.id||S("texture-transform-model"),fs:t.fs||(0,xn.getPassthroughFS)({input:t.targetTextureVarying,inputChannels:t.targetTextureChannels,output:Os}),vertexCount:t.vertexCount,...t}),this._initialize(t),Object.seal(this)}destroy(){this.model.destroy();for(let e of this.bindings)e.framebuffer?.destroy()}delete(){this.destroy()}run(e){let{framebuffer:t}=this.bindings[this.currentIndex],n=this.device.beginRenderPass({framebuffer:t,...e});this.model.draw(n),n.end(),this.device.submit()}getTargetTexture(){let{targetTexture:e}=this.bindings[this.currentIndex];return e}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(e){this._updateBindings(e)}_updateBindings(e){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],e)}_updateBinding(e,{sourceBuffers:t,sourceTextures:n,targetTexture:r}){if(e||(e={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(e.sourceTextures,n),Object.assign(e.sourceBuffers,t),r){e.targetTexture=r;let{width:s,height:o}=r;e.framebuffer&&e.framebuffer.destroy(),e.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:s,height:o,colorAttachments:[r]}),e.framebuffer.resize({width:s,height:o})}return e}_setSourceTextureParameters(){let e=this.currentIndex,{sourceTextures:t}=this.bindings[e];for(let n in t)t[n].sampler=this.sampler}};var ks=`struct VertexInputs {
7
+ "use strict";var __exports__=(()=>{var os=Object.create;var ct=Object.defineProperty;var as=Object.getOwnPropertyDescriptor;var cs=Object.getOwnPropertyNames;var hs=Object.getPrototypeOf,us=Object.prototype.hasOwnProperty;var nn=(i,e)=>()=>{try{return e||i((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ls=(i,e)=>{for(var t in e)ct(i,t,{get:e[t],enumerable:!0})},at=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of cs(e))!us.call(i,r)&&r!==t&&ct(i,r,{get:()=>e[r],enumerable:!(n=as(e,r))||n.enumerable});return i},ht=(i,e,t)=>(at(i,e,"default"),t&&at(t,e,"default")),R=(i,e,t)=>(t=i!=null?os(hs(i)):{},at(e||!i||!i.__esModule?ct(t,"default",{value:i,enumerable:!0}):t,i)),ds=i=>at(ct({},"__esModule",{value:!0}),i);var N=nn((mc,rn)=>{rn.exports=globalThis.luma});var ce=nn((Fh,Xn)=>{Xn.exports=globalThis.luma});var it={};ls(it,{AnimationAction:()=>Ve,AnimationClip:()=>pt,AnimationClipController:()=>ut,AnimationLoop:()=>Ee,AnimationLoopTemplate:()=>St,AnimationMixer:()=>gt,AnimationTrack:()=>mt,Animator:()=>lt,AsyncTexture:()=>dc,BackgroundTextureModel:()=>Be,BufferTransform:()=>Nt,ClipSpace:()=>ue,Computation:()=>Ge,ConeGeometry:()=>fe,CubeGeometry:()=>Yt,CylinderGeometry:()=>Wt,DirectionalLightModel:()=>jt,DynamicBuffer:()=>G,DynamicTexture:()=>K,GPUGeometry:()=>Ce,Geometry:()=>z,GroupNode:()=>Vt,IcoSphereGeometry:()=>qt,KeyFrames:()=>At,LegacyPickingManager:()=>ri,Material:()=>De,MaterialFactory:()=>ke,Model:()=>Y,ModelNode:()=>Xt,OrbitControls:()=>Pt,PickingManager:()=>ti,PlaneGeometry:()=>Kt,PointLightModel:()=>Ft,ScenegraphNode:()=>re,ShaderInputs:()=>X,ShaderPassRenderer:()=>ei,SphereGeometry:()=>Fe,SpotLightModel:()=>zt,Swap:()=>ze,SwapBuffers:()=>Jt,SwapFramebuffers:()=>je,TextureTransform:()=>Dt,Timeline:()=>wt,TruncatedConeGeometry:()=>de,VideoTexture:()=>Qt,_resolveLoadFileUrl:()=>Zt,applyMorphTargets:()=>hi,cancelAnimationFramePolyfill:()=>Ct,colorPicking:()=>et,decodeMorphTargetAttribute:()=>ci,evaluateAnimationSampler:()=>dt,getIndexPickingModule:()=>Jr,indexColorPicking:()=>ni,indexPicking:()=>tt,legacyColorPicking:()=>ts,loadImage:()=>Nr,loadImageBitmap:()=>kr,makeAnimationLoop:()=>Vn,makeInterleavedGeometry:()=>Me,makeRandomGenerator:()=>Pr,picking:()=>Qr,requestAnimationFramePolyfill:()=>Et,resolvePickingBackend:()=>Zr,resolvePickingMode:()=>ii,setPathPrefix:()=>Rr,simplifyMesh:()=>Cr,supportsIndexPicking:()=>Je,updateMorphTargetBuffers:()=>hn,updateSkinJointMatrices:()=>jn});ht(it,R(N(),1));var sn=R(N(),1),ut=class{name;playing=!0;speed=1;startTime=0;constructor(e={}){this.name=e.name||"unnamed",Object.assign(this,e)}setTime(e){if(!this.playing)return;let n=(e/1e3-this.startTime)*this.speed;this.applyTime(n)}},lt=class{clips;animations;constructor(e){this.clips=e,this.animations=e}animate(e){sn.log.warn(`${this.constructor.name}#animate is deprecated. Use ${this.constructor.name}#setTime instead`)(),this.setTime(e)}setTime(e){this.clips.forEach(t=>t.setTime(e))}getAnimations(){return this.clips}};function dt(i,e,t="vector"){let{input:n,output:r,interpolation:s="LINEAR"}=e;if(!n.length||!r.length||!Number.isFinite(i))return null;let o=n.length-1;if(i<=n[0]||o===0)return si(r,s,0,t);if(i>=n[o])return si(r,s,o,t);let a=0,c=o;for(;c-a>1;){let f=Math.floor((a+c)/2);n[f]<=i?a=f:c=f}let h=n[a],d=n[c]-h;if(d<=0||s==="STEP")return si(r,s,a,t);let l=(i-h)/d;switch(s){case"LINEAR":{let f=r[a],m=r[c];return!f||!m?null:t==="quaternion"?ft(f,m,l):fs(f,m,l)}case"CUBICSPLINE":{let f=r[a*3+1],m=r[a*3+2],p=r[c*3],b=r[c*3+1];if(!f||!m||!p||!b)return null;let _=ms(f,m,p,b,d,l);return t==="quaternion"?ve(_):_}default:return null}}function ft(i,e,t){let n=ve(i),r=ve(e),s=n.reduce((d,l,f)=>d+l*r[f],0),o=s<0?-1:1;if(s=Math.min(Math.abs(s),1),s>.9995)return ve(n.map((d,l)=>d+t*(r[l]*o-d)));let a=Math.acos(s),c=Math.sin(a),h=Math.sin((1-t)*a)/c,u=Math.sin(t*a)/c*o;return ve(n.map((d,l)=>d*h+r[l]*u))}function si(i,e,t,n){let r=i[e==="CUBICSPLINE"?t*3+1:t];return r?n==="quaternion"?ve(r):[...r]:null}function fs(i,e,t){return i.map((n,r)=>(1-t)*n+t*e[r])}function ms(i,e,t,n,r,s){let o=s*s,a=o*s;return i.map((c,h)=>(2*a-3*o+1)*c+(a-2*o+s)*e[h]*r+(-2*a+3*o)*n[h]+(a-o)*t[h]*r)}function ve(i){let e=Math.hypot(...i);return e>0?i.map(t=>t/e):[0,0,0,1]}var mt=class{name;times;values;interpolation;valueType;binding;constructor(e){this.name=e.name||e.binding.id||"unnamed",this.times=e.times,this.values=e.values,this.interpolation=e.interpolation||"LINEAR",this.valueType=e.valueType||"vector",this.binding=e.binding}get duration(){return this.times[this.times.length-1]||0}get sampler(){return{input:this.times,output:this.values,interpolation:this.interpolation}}evaluate(e){return dt(e,this.sampler,this.valueType)}};var pt=class{name;tracks;duration;constructor(e){this.name=e.name||"unnamed",this.tracks=e.tracks,this.duration=e.duration??Math.max(0,...e.tracks.map(t=>t.duration))}};var Ve=class{clip;mixer;time=0;timeScale;weight;loop;repetitions;paused=!1;playing=!1;elapsedTime=0;fade=null;constructor(e,t,n={}){this.mixer=e,this.clip=t,this.loop=n.loop||"repeat",this.repetitions=n.repetitions??Number.POSITIVE_INFINITY,this.timeScale=n.timeScale??1,this.weight=n.weight??1}play(){return this.playing=!0,this.paused=!1,this}pause(){return this.paused=!0,this}resume(){return this.playing=!0,this.paused=!1,this}stop(){return this.playing=!1,this.paused=!1,this.fade=null,this.reset()}reset(){return this.elapsedTime=0,this.time=0,this}setTime(e){return this.elapsedTime=e,this.time=this.resolveLocalTime(e),this}setLoop(e,t=Number.POSITIVE_INFINITY){return this.loop=e,this.repetitions=t,this.time=this.resolveLocalTime(this.elapsedTime),this}setEffectiveWeight(e){return this.weight=Math.max(0,e),this.fade=null,this}setEffectiveTimeScale(e){return this.timeScale=e,this}fadeIn(e){return this.scheduleFade(1,e)}fadeOut(e){return this.scheduleFade(0,e)}crossFadeTo(e,t){return e.weight=0,e.play().fadeIn(t),this.fadeOut(t)}crossFadeFrom(e,t){return e.crossFadeTo(this,t),this}advance(e){!this.playing||this.paused||(this.advanceFade(Math.abs(e)),this.elapsedTime+=e*this.timeScale,this.time=this.resolveLocalTime(this.elapsedTime),this.hasFinished()&&(this.playing=!1))}get shouldApply(){return(this.playing||this.hasFinished())&&this.weight>0}scheduleFade(e,t){return t<=0?(this.weight=e,this.fade=null,this):(this.fade={duration:t,elapsedTime:0,startWeight:this.weight,endWeight:e},this)}advanceFade(e){if(!this.fade)return;this.fade.elapsedTime+=e;let t=Math.min(this.fade.elapsedTime/this.fade.duration,1);this.weight=this.fade.startWeight+(this.fade.endWeight-this.fade.startWeight)*t,t===1&&(this.fade=null)}hasFinished(){let e=this.clip.duration;return e<=0?this.loop==="once":this.loop==="once"?this.elapsedTime>=e||this.elapsedTime<0:Number.isFinite(this.repetitions)&&Math.abs(this.elapsedTime)>=e*this.repetitions}resolveLocalTime(e){let t=this.clip.duration;if(t<=0)return 0;if(this.loop==="once")return Math.min(Math.max(e,0),t);if(Number.isFinite(this.repetitions)&&Math.abs(e)>=t*this.repetitions)return this.loop==="ping-pong"&&this.repetitions%2===0||e<0?0:t;let n=e>=0&&e<t?e:(e%t+t)%t;if(this.loop==="repeat")return n;let r=Math.floor(e/t);return Math.abs(r%2)===0?n:t-n}},gt=class{time=0;timeScale=1;clips=new Map;actions=new Map;initialValues=new Map;constructor(e=[]){e.forEach(t=>this.addClip(t))}addClip(e){return this.clips.set(e.name,e),this}clipAction(e,t){let n=typeof e=="string"?this.clips.get(e):e;if(!n)throw new Error(`Unknown animation clip: ${e}`);this.addClip(n);let r=this.actions.get(n);return r||(r=new Ve(this,n,t),this.actions.set(n,r)),r}getAction(e){let t=this.clips.get(e);return t?this.actions.get(t):void 0}update(e){return this.advance(e),this.applyValues(),this}advance(e){let t=e*this.timeScale;return this.time+=t,this.actions.forEach(n=>n.advance(t)),this}setTime(e){return this.time=e,this.actions.forEach(t=>{t.paused||t.setTime(e*t.timeScale)}),this.applyValues(),this}stopAllAction(){return this.actions.forEach(e=>e.stop()),this}applyValues(){let e=new Map;this.actions.forEach(t=>{!t.shouldApply&&!(t.playing&&t.weight===0)||t.clip.tracks.forEach(n=>{let r=n.evaluate(t.time);if(!r)return;let s=n.binding.id||n.binding;if(!this.initialValues.has(s)){let h=n.binding.getValue?.();h&&this.initialValues.set(s,[...h])}if(t.weight===0&&!this.initialValues.has(s))return;let o=e.get(s);if(!o){e.set(s,{binding:n.binding,value:[...r],valueType:n.valueType,weight:t.weight});return}if(t.weight===0)return;let a=o.weight+t.weight,c=t.weight/a;o.value=n.valueType==="quaternion"?ft(o.value,r,c):o.value.map((h,u)=>h+(r[u]-h)*c),o.weight=a})}),e.forEach(({binding:t,value:n,valueType:r,weight:s},o)=>{let a=s<1?this.initialValues.get(o):void 0;a&&a.length===n.length&&(n=r==="quaternion"?ft(a,n,s):n.map((c,h)=>a[h]+(c-a[h])*s)),t.setValue(n)})}};var on=R(N(),1);var oi={};function O(i="id"){oi[i]=oi[i]||1;let e=oi[i]++;return`${i}-${e}`}var z=class{id;topology;vertexCount;indices;attributes;bufferLayout;userData={};constructor(e){let{attributes:t={},indices:n=null,vertexCount:r=null}=e;this.id=e.id||O("geometry"),this.topology=e.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(let[s,o]of Object.entries(t)){let a=ArrayBuffer.isView(o)?{value:o}:o;if(!ArrayBuffer.isView(a.value))throw new Error(`${this._print(s)}: must be typed array or object with value as typed array`);if((s==="POSITION"||s==="positions")&&!a.size&&(a.size=3),s==="indices"){if(this.indices)throw new Error("Multiple indices detected");this.indices=a}else{let c=ge(s),h=Object.keys(this.attributes).find(u=>ge(u)===c);h&&delete this.attributes[h],this.attributes[s]=a}}this.indices&&this.indices.isIndexed!==void 0&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=r||this._calculateVertexCount(this.attributes,this.indices),this.bufferLayout=e.bufferLayout||ps(this.attributes)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(e){return`Geometry ${this.id} attribute ${e}`}_setAttributes(e,t){return this}_calculateVertexCount(e,t){if(t)return t.value.length;let n=1/0;for(let r of Object.values(e)){if(!r)continue;let{value:s,size:o,constant:a}=r;!a&&s&&o!==void 0&&o>=1&&(n=Math.min(n,s.length/o))}return n}};function ge(i){switch(i){case"POSITION":return"positions";case"NORMAL":return"normals";case"TEXCOORD_0":return"texCoords";case"TEXCOORD_1":return"texCoords1";case"COLOR_0":return"colors";default:return i}}function ps(i){let e=[];for(let[t,n]of Object.entries(i)){if(!n)continue;let{value:r,size:s,normalized:o}=n;if(s===void 0)throw new Error(`Attribute ${t} is missing a size`);e.push({name:ge(t),format:on.vertexFormatDecoder.getVertexFormatFromAttribute(r,s,o)})}return e}var ai=R(N(),1);function cn(i){let{indices:e,attributes:t}=i;if(!e)return i;let n=e.value.length,r={};for(let s in t){let o=t[s];if(!o)continue;let{value:a,size:c}=o;if(o.constant||!c)continue;let u=a.constructor,d=new u(n*c);for(let l=0;l<n;++l){let f=e.value[l];for(let m=0;m<c;m++)d[l*c+m]=a[f*c+m]}r[s]={size:c,value:d}}return{attributes:Object.assign({},t,r)}}function Me(i,e={}){let t=e.bufferName||"geometry";if(gs(i,t))return i;let n=e.minAttributeAlignment||4,r=xs(i,e.attributes),s=[],o=0,a=1/0;for(let[u,d]of r){if(!d)continue;if(d.constant)throw new Error(`Attribute ${u} is constant`);let{value:l,size:f,normalized:m}=d;if(!ArrayBuffer.isView(l))throw new Error(`Attribute ${u} is missing typed array data`);if(f===void 0)throw new Error(`Attribute ${u} is missing a size`);let p=ai.vertexFormatDecoder.getVertexFormatFromAttribute(l,f,m),b=ai.vertexFormatDecoder.getVertexFormatInfo(p);o=an(o,n),s.push({sourceName:u,attributeName:ge(u),value:l,size:f,format:p,byteOffset:o,byteLength:b.byteLength}),o+=b.byteLength;let _=l.length/f;if(!Number.isInteger(_))throw new Error(`Attribute ${u} length is not divisible by size`);a=Math.min(a,_)}if(s.length===0||!Number.isFinite(a))throw new Error(`Geometry ${i.id} has no interleavable attributes`);let c=an(o,n),h=new ArrayBuffer(a*c);for(let u of s)bs(h,a,c,u);return new z({id:i.id,topology:i.topology||"triangle-list",vertexCount:i.vertexCount,indices:i.indices,attributes:{[t]:{value:new Uint8Array(h),size:c,byteStride:c}},bufferLayout:[{name:t,stepMode:"vertex",byteStride:c,attributes:s.map(u=>({attribute:u.attributeName,format:u.format,byteOffset:u.byteOffset}))}]})}function gs(i,e){if(i.bufferLayout.length!==1)return!1;let t=i.bufferLayout[0];return t.name===e&&!!t.attributes?.length&&!!i.attributes[e]}function xs(i,e){return e?e.map(t=>[t,i.attributes[t]]):Object.entries(i.attributes)}function bs(i,e,t,n){let r=n.value.constructor,s=r.BYTES_PER_ELEMENT;if(n.byteOffset%s!==0||t%s!==0)throw new Error(`Attribute ${n.sourceName} is not aligned to its component type`);let o=new r(i),a=n.value,c=n.byteOffset/s,h=t/s;for(let u=0;u<e;u++){let d=u*n.size,l=u*h+c;for(let f=0;f<n.size;f++)o[l+f]=a[d+f]}}function an(i,e){return Math.ceil(i/e)*e}function ci(i){let e=i.value;if(e instanceof Float32Array)return e;let t=new Float32Array(e.length),n=un(e),r=e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array;for(let s=0;s<e.length;s++){let o=Number(e[s]);t[s]=i.normalized&&n?r?Math.max(o/n,-1):o/n:o}return t}function hi(i,e,t){let n={};for(let r of["POSITION","NORMAL","TANGENT"]){let s=i[r];if(!s)continue;let o=new Float32Array(s),a=r==="TANGENT"?4:3,c=Math.floor(s.length/a);for(let h=0;h<Math.min(e.length,t.length);h++){let u=t[h],d=e[h][r];if(!u||!d)continue;let l=r==="TANGENT"&&d.length===c*4?4:3;for(let f=0;f<c;f++){let m=f*a,p=f*l;for(let b=0;b<3;b++)o[m+b]+=(d[p+b]||0)*u}}r!=="POSITION"&&_s(o,a),n[r]=o}return n}function hn(i,e,t,n){let r={};for(let d of["POSITION","NORMAL","TANGENT"]){let l=e.attributes[d];l&&(r[d]=ci(l))}let s=hi(r,t,n),o={};for(let[d,l]of Object.entries(e.attributes))l&&(o[d]=l);for(let d of["POSITION","NORMAL","TANGENT"]){let l=s[d],f=o[d];l&&f&&(o[d]={...f,value:ys(f,l)})}let a=new z({id:e.id,topology:e.topology||"triangle-list",vertexCount:e.vertexCount,indices:e.indices,attributes:o,bufferLayout:e.bufferLayout}),h=Me(a).attributes.geometry?.value,u=i._gpuGeometry?.attributes.geometry||i.bufferAttributes.geometry;if(h&&u){u.write(h);return}for(let d of["POSITION","NORMAL","TANGENT"]){let l=s[d];if(l){let f=d==="POSITION"?"positions":d==="NORMAL"?"normals":"TANGENT";i.bufferAttributes[f]?.write(l)}}}function ys(i,e){if(i.value instanceof Float32Array)return e;let t=i.value.slice(),n=un(t),r=t instanceof Int8Array||t instanceof Int16Array||t instanceof Int32Array;for(let s=0;s<e.length;s++){let o=e[s];t[s]=i.normalized&&n?Math.round(Math.max(r?-1:0,Math.min(1,o))*n):o}return t}function un(i){return i instanceof Int8Array?127:i instanceof Uint8Array||i instanceof Uint8ClampedArray?255:i instanceof Int16Array?32767:i instanceof Uint16Array?65535:i instanceof Int32Array?2147483647:i instanceof Uint32Array?4294967295:0}function _s(i,e){for(let t=0;t<i.length;t+=e){let n=Math.hypot(i[t],i[t+1],i[t+2]);n>0&&(i[t]/=n,i[t+1]/=n,i[t+2]/=n)}}var Pc=1/Math.PI*180,Lc=1/180*Math.PI,Is={EPSILON:1e-12,debug:!1,precision:4,printTypes:!1,printDegrees:!1,printRowMajor:!0,_cartographicRadians:!1};globalThis.mathgl=globalThis.mathgl||{config:{...Is}};var $=globalThis.mathgl.config;function ln(i,{precision:e=$.precision}={}){return i=vs(i),`${parseFloat(i.toPrecision(e))}`}function Te(i){return Array.isArray(i)||ArrayBuffer.isView(i)&&!(i instanceof DataView)}function ui(i,e,t){let n=$.EPSILON;t&&($.EPSILON=t);try{if(i===e)return!0;if(Te(i)&&Te(e)){if(i.length!==e.length)return!1;for(let r=0;r<i.length;++r)if(!ui(i[r],e[r]))return!1;return!0}return i&&i.equals?i.equals(e):e&&e.equals?e.equals(i):typeof i=="number"&&typeof e=="number"?Math.abs(i-e)<=$.EPSILON*Math.max(1,Math.abs(i),Math.abs(e)):!1}finally{$.EPSILON=n}}function vs(i){return Math.round(i/$.EPSILON)*$.EPSILON}var we=class extends Array{clone(){return new this.constructor().copy(this)}fromArray(e,t=0){for(let n=0;n<this.ELEMENTS;++n)this[n]=e[n+t];return this.check()}toArray(e=[],t=0){for(let n=0;n<this.ELEMENTS;++n)e[t+n]=this[n];return e}toObject(e){return e}from(e){return Array.isArray(e)?this.copy(e):this.fromObject(e)}to(e){return e===this?this:Te(e)?this.toArray(e):this.toObject(e)}toTarget(e){return e?this.to(e):this}toFloat32Array(){return new Float32Array(this)}toString(){return this.formatString($)}formatString(e){let t="";for(let n=0;n<this.ELEMENTS;++n)t+=(n>0?", ":"")+ln(this[n],e);return`${e.printTypes?this.constructor.name:""}[${t}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(!ui(this[t],e[t]))return!1;return!0}exactEquals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(this[t]!==e[t])return!1;return!0}negate(){for(let e=0;e<this.ELEMENTS;++e)this[e]=-this[e];return this.check()}lerp(e,t,n){if(n===void 0)return this.lerp(this,e,t);for(let r=0;r<this.ELEMENTS;++r){let s=e[r],o=typeof t=="number"?t:t[r];this[r]=s+n*(o-s)}return this.check()}min(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.min(e[t],this[t]);return this.check()}max(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.max(e[t],this[t]);return this.check()}clamp(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e[n]),t[n]);return this.check()}add(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]+=t[n];return this.check()}subtract(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]-=t[n];return this.check()}scale(e){if(typeof e=="number")for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;else for(let t=0;t<this.ELEMENTS&&t<e.length;++t)this[t]*=e[t];return this.check()}multiplyByScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}check(){if($.debug&&!this.validate())throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);return this}validate(){let e=this.length===this.ELEMENTS;for(let t=0;t<this.ELEMENTS;++t)e=e&&Number.isFinite(this[t]);return e}sub(e){return this.subtract(e)}setScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=e;return this.check()}addScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]+=e;return this.check()}subScalar(e){return this.addScalar(-e)}multiplyScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}divideScalar(e){return this.multiplyByScalar(1/e)}clampScalar(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e),t);return this.check()}get elements(){return this}};function Ms(i,e){if(i.length!==e)return!1;for(let t=0;t<i.length;++t)if(!Number.isFinite(i[t]))return!1;return!0}function V(i){if(!Number.isFinite(i))throw new Error(`Invalid number ${JSON.stringify(i)}`);return i}function xt(i,e,t=""){if($.debug&&!Ms(i,e))throw new Error(`math.gl: ${t} some fields set to invalid numbers'`);return i}function li(i,e){if(!i)throw new Error(`math.gl assertion ${e}`)}var bt=class extends we{get x(){return this[0]}set x(e){this[0]=V(e)}get y(){return this[1]}set y(e){this[1]=V(e)}len(){return Math.sqrt(this.lengthSquared())}magnitude(){return this.len()}lengthSquared(){let e=0;for(let t=0;t<this.ELEMENTS;++t)e+=this[t]*this[t];return e}magnitudeSquared(){return this.lengthSquared()}distance(e){return Math.sqrt(this.distanceSquared(e))}distanceSquared(e){let t=0;for(let n=0;n<this.ELEMENTS;++n){let r=this[n]-e[n];t+=r*r}return V(t)}dot(e){let t=0;for(let n=0;n<this.ELEMENTS;++n)t+=this[n]*e[n];return V(t)}normalize(){let e=this.magnitude();if(e!==0)for(let t=0;t<this.ELEMENTS;++t)this[t]/=e;return this.check()}multiply(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]*=t[n];return this.check()}divide(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]/=t[n];return this.check()}lengthSq(){return this.lengthSquared()}distanceTo(e){return this.distance(e)}distanceToSquared(e){return this.distanceSquared(e)}getComponent(e){return li(e>=0&&e<this.ELEMENTS,"index is out of range"),V(this[e])}setComponent(e,t){return li(e>=0&&e<this.ELEMENTS,"index is out of range"),this[e]=t,this.check()}addVectors(e,t){return this.copy(e).add(t)}subVectors(e,t){return this.copy(e).subtract(t)}multiplyVectors(e,t){return this.copy(e).multiply(t)}addScaledVector(e,t){return this.add(new this.constructor(e).multiplyScalar(t))}};var te=typeof Float32Array<"u"?Float32Array:Array;var Uc=Math.PI/180;function Ts(){let i=new te(2);return te!=Float32Array&&(i[0]=0,i[1]=0),i}function mn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[4]*r+t[12],i[1]=t[1]*n+t[5]*r+t[13],i}var $c=(function(){let i=Ts();return function(e,t,n,r,s,o){let a,c;for(t||(t=2),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],s(i,i,o),e[a]=i[0],e[a+1]=i[1];return e}})();function pn(i,e,t){let n=e[0],r=e[1],s=t[3]*n+t[7]*r||1;return i[0]=(t[0]*n+t[4]*r)/s,i[1]=(t[1]*n+t[5]*r)/s,i}function yt(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s||1;return i[0]=(t[0]*n+t[4]*r+t[8]*s)/o,i[1]=(t[1]*n+t[5]*r+t[9]*s)/o,i[2]=(t[2]*n+t[6]*r+t[10]*s)/o,i}function gn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[2]*r,i[1]=t[1]*n+t[3]*r,i[2]=e[2],i}function As(){let i=new te(3);return te!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0),i}function Ss(i,e){return i[0]*e[0]+i[1]*e[1]+i[2]*e[2]}function xn(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[0],a=t[1],c=t[2];return i[0]=r*c-s*a,i[1]=s*o-n*c,i[2]=n*a-r*o,i}function _t(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s+t[15];return o=o||1,i[0]=(t[0]*n+t[4]*r+t[8]*s+t[12])/o,i[1]=(t[1]*n+t[5]*r+t[9]*s+t[13])/o,i[2]=(t[2]*n+t[6]*r+t[10]*s+t[14])/o,i}function bn(i,e,t){let n=e[0],r=e[1],s=e[2];return i[0]=n*t[0]+r*t[3]+s*t[6],i[1]=n*t[1]+r*t[4]+s*t[7],i[2]=n*t[2]+r*t[5]+s*t[8],i}function yn(i,e,t){let n=t[0],r=t[1],s=t[2],o=t[3],a=e[0],c=e[1],h=e[2],u=r*h-s*c,d=s*a-n*h,l=n*c-r*a,f=r*l-s*d,m=s*u-n*l,p=n*d-r*u,b=o*2;return u*=b,d*=b,l*=b,f*=2,m*=2,p*=2,i[0]=a+u+f,i[1]=c+d+m,i[2]=h+l+p,i}function _n(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0],s[1]=r[1]*Math.cos(n)-r[2]*Math.sin(n),s[2]=r[1]*Math.sin(n)+r[2]*Math.cos(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function In(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[2]*Math.sin(n)+r[0]*Math.cos(n),s[1]=r[1],s[2]=r[2]*Math.cos(n)-r[0]*Math.sin(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function vn(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0]*Math.cos(n)-r[1]*Math.sin(n),s[1]=r[0]*Math.sin(n)+r[1]*Math.cos(n),s[2]=r[2],i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Mn(i,e){let t=i[0],n=i[1],r=i[2],s=e[0],o=e[1],a=e[2],c=Math.sqrt((t*t+n*n+r*r)*(s*s+o*o+a*a)),h=c&&Ss(i,e)/c;return Math.acos(Math.min(Math.max(h,-1),1))}var Xc=(function(){let i=As();return function(e,t,n,r,s,o){let a,c;for(t||(t=3),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],i[2]=e[a+2],s(i,i,o),e[a]=i[0],e[a+1]=i[1],e[a+2]=i[2];return e}})();var fi=[0,0,0],It,H=class i extends bt{static get ZERO(){return It||(It=new i(0,0,0),Object.freeze(It)),It}constructor(e=0,t=0,n=0){super(-0,-0,-0),arguments.length===1&&Te(e)?this.copy(e):($.debug&&(V(e),V(t),V(n)),this[0]=e,this[1]=t,this[2]=n)}set(e,t,n){return this[0]=e,this[1]=t,this[2]=n,this.check()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this.check()}fromObject(e){return $.debug&&(V(e.x),V(e.y),V(e.z)),this[0]=e.x,this[1]=e.y,this[2]=e.z,this.check()}toObject(e){return e.x=this[0],e.y=this[1],e.z=this[2],e}get ELEMENTS(){return 3}get z(){return this[2]}set z(e){this[2]=V(e)}angle(e){return Mn(this,e)}cross(e){return xn(this,this,e),this.check()}rotateX({radians:e,origin:t=fi}){return _n(this,this,t,e),this.check()}rotateY({radians:e,origin:t=fi}){return In(this,this,t,e),this.check()}rotateZ({radians:e,origin:t=fi}){return vn(this,this,t,e),this.check()}transform(e){return this.transformAsPoint(e)}transformAsPoint(e){return _t(this,this,e),this.check()}transformAsVector(e){return yt(this,this,e),this.check()}transformByMatrix3(e){return bn(this,this,e),this.check()}transformByMatrix2(e){return gn(this,this,e),this.check()}transformByQuaternion(e){return yn(this,this,e),this.check()}};var vt=class extends we{toString(){let e="[";if($.printRowMajor){e+="row-major:";for(let t=0;t<this.RANK;++t)for(let n=0;n<this.RANK;++n)e+=` ${this[n*this.RANK+t]}`}else{e+="column-major:";for(let t=0;t<this.ELEMENTS;++t)e+=` ${this[t]}`}return e+="]",e}getElementIndex(e,t){return t*this.RANK+e}getElement(e,t){return this[t*this.RANK+e]}setElement(e,t,n){return this[t*this.RANK+e]=V(n),this}getColumn(e,t=new Array(this.RANK).fill(-0)){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)t[r]=this[n+r];return t}setColumn(e,t){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)this[n+r]=t[r];return this}};function Cs(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function Tn(i,e){if(i===e){let t=e[1],n=e[2],r=e[3],s=e[6],o=e[7],a=e[11];i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=t,i[6]=e[9],i[7]=e[13],i[8]=n,i[9]=s,i[11]=e[14],i[12]=r,i[13]=o,i[14]=a}else i[0]=e[0],i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=e[1],i[5]=e[5],i[6]=e[9],i[7]=e[13],i[8]=e[2],i[9]=e[6],i[10]=e[10],i[11]=e[14],i[12]=e[3],i[13]=e[7],i[14]=e[11],i[15]=e[15];return i}function wn(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=e[4],a=e[5],c=e[6],h=e[7],u=e[8],d=e[9],l=e[10],f=e[11],m=e[12],p=e[13],b=e[14],_=e[15],M=t*a-n*o,y=t*c-r*o,I=t*h-s*o,g=n*c-r*a,x=n*h-s*a,v=r*h-s*c,w=u*p-d*m,T=u*b-l*m,P=u*_-f*m,S=d*b-l*p,A=d*_-f*p,L=l*_-f*b,C=M*L-y*A+I*S+g*P-x*T+v*w;return C?(C=1/C,i[0]=(a*L-c*A+h*S)*C,i[1]=(r*A-n*L-s*S)*C,i[2]=(p*v-b*x+_*g)*C,i[3]=(l*x-d*v-f*g)*C,i[4]=(c*P-o*L-h*T)*C,i[5]=(t*L-r*P+s*T)*C,i[6]=(b*I-m*v-_*y)*C,i[7]=(u*v-l*I+f*y)*C,i[8]=(o*A-a*P+h*w)*C,i[9]=(n*P-t*A-s*w)*C,i[10]=(m*x-p*I+_*M)*C,i[11]=(d*I-u*x-f*M)*C,i[12]=(a*T-o*S-c*w)*C,i[13]=(t*S-n*T+r*w)*C,i[14]=(p*y-m*g-b*M)*C,i[15]=(u*g-d*y+l*M)*C,i):null}function An(i){let e=i[0],t=i[1],n=i[2],r=i[3],s=i[4],o=i[5],a=i[6],c=i[7],h=i[8],u=i[9],d=i[10],l=i[11],f=i[12],m=i[13],p=i[14],b=i[15],_=e*o-t*s,M=e*a-n*s,y=t*a-n*o,I=h*m-u*f,g=h*p-d*f,x=u*p-d*m,v=e*x-t*g+n*I,w=s*x-o*g+a*I,T=h*y-u*M+d*_,P=f*y-m*M+p*_;return c*v-r*w+b*T-l*P}function mi(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3],a=e[4],c=e[5],h=e[6],u=e[7],d=e[8],l=e[9],f=e[10],m=e[11],p=e[12],b=e[13],_=e[14],M=e[15],y=t[0],I=t[1],g=t[2],x=t[3];return i[0]=y*n+I*a+g*d+x*p,i[1]=y*r+I*c+g*l+x*b,i[2]=y*s+I*h+g*f+x*_,i[3]=y*o+I*u+g*m+x*M,y=t[4],I=t[5],g=t[6],x=t[7],i[4]=y*n+I*a+g*d+x*p,i[5]=y*r+I*c+g*l+x*b,i[6]=y*s+I*h+g*f+x*_,i[7]=y*o+I*u+g*m+x*M,y=t[8],I=t[9],g=t[10],x=t[11],i[8]=y*n+I*a+g*d+x*p,i[9]=y*r+I*c+g*l+x*b,i[10]=y*s+I*h+g*f+x*_,i[11]=y*o+I*u+g*m+x*M,y=t[12],I=t[13],g=t[14],x=t[15],i[12]=y*n+I*a+g*d+x*p,i[13]=y*r+I*c+g*l+x*b,i[14]=y*s+I*h+g*f+x*_,i[15]=y*o+I*u+g*m+x*M,i}function Sn(i,e,t){let n=t[0],r=t[1],s=t[2],o,a,c,h,u,d,l,f,m,p,b,_;return e===i?(i[12]=e[0]*n+e[4]*r+e[8]*s+e[12],i[13]=e[1]*n+e[5]*r+e[9]*s+e[13],i[14]=e[2]*n+e[6]*r+e[10]*s+e[14],i[15]=e[3]*n+e[7]*r+e[11]*s+e[15]):(o=e[0],a=e[1],c=e[2],h=e[3],u=e[4],d=e[5],l=e[6],f=e[7],m=e[8],p=e[9],b=e[10],_=e[11],i[0]=o,i[1]=a,i[2]=c,i[3]=h,i[4]=u,i[5]=d,i[6]=l,i[7]=f,i[8]=m,i[9]=p,i[10]=b,i[11]=_,i[12]=o*n+u*r+m*s+e[12],i[13]=a*n+d*r+p*s+e[13],i[14]=c*n+l*r+b*s+e[14],i[15]=h*n+f*r+_*s+e[15]),i}function En(i,e,t){let n=t[0],r=t[1],s=t[2];return i[0]=e[0]*n,i[1]=e[1]*n,i[2]=e[2]*n,i[3]=e[3]*n,i[4]=e[4]*r,i[5]=e[5]*r,i[6]=e[6]*r,i[7]=e[7]*r,i[8]=e[8]*s,i[9]=e[9]*s,i[10]=e[10]*s,i[11]=e[11]*s,i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],i}function Cn(i,e,t,n){let r=n[0],s=n[1],o=n[2],a=Math.sqrt(r*r+s*s+o*o),c,h,u,d,l,f,m,p,b,_,M,y,I,g,x,v,w,T,P,S,A,L,C,U;return a<1e-6?null:(a=1/a,r*=a,s*=a,o*=a,h=Math.sin(t),c=Math.cos(t),u=1-c,d=e[0],l=e[1],f=e[2],m=e[3],p=e[4],b=e[5],_=e[6],M=e[7],y=e[8],I=e[9],g=e[10],x=e[11],v=r*r*u+c,w=s*r*u+o*h,T=o*r*u-s*h,P=r*s*u-o*h,S=s*s*u+c,A=o*s*u+r*h,L=r*o*u+s*h,C=s*o*u-r*h,U=o*o*u+c,i[0]=d*v+p*w+y*T,i[1]=l*v+b*w+I*T,i[2]=f*v+_*w+g*T,i[3]=m*v+M*w+x*T,i[4]=d*P+p*S+y*A,i[5]=l*P+b*S+I*A,i[6]=f*P+_*S+g*A,i[7]=m*P+M*S+x*A,i[8]=d*L+p*C+y*U,i[9]=l*L+b*C+I*U,i[10]=f*L+_*C+g*U,i[11]=m*L+M*C+x*U,e!==i&&(i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i)}function Pn(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[4],o=e[5],a=e[6],c=e[7],h=e[8],u=e[9],d=e[10],l=e[11];return e!==i&&(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[4]=s*r+h*n,i[5]=o*r+u*n,i[6]=a*r+d*n,i[7]=c*r+l*n,i[8]=h*r-s*n,i[9]=u*r-o*n,i[10]=d*r-a*n,i[11]=l*r-c*n,i}function Ln(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],h=e[8],u=e[9],d=e[10],l=e[11];return e!==i&&(i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r-h*n,i[1]=o*r-u*n,i[2]=a*r-d*n,i[3]=c*r-l*n,i[8]=s*n+h*r,i[9]=o*n+u*r,i[10]=a*n+d*r,i[11]=c*n+l*r,i}function On(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],h=e[4],u=e[5],d=e[6],l=e[7];return e!==i&&(i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r+h*n,i[1]=o*r+u*n,i[2]=a*r+d*n,i[3]=c*r+l*n,i[4]=h*r-s*n,i[5]=u*r-o*n,i[6]=d*r-a*n,i[7]=l*r-c*n,i}function Rn(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=t+t,a=n+n,c=r+r,h=t*o,u=n*o,d=n*a,l=r*o,f=r*a,m=r*c,p=s*o,b=s*a,_=s*c;return i[0]=1-d-m,i[1]=u+_,i[2]=l-b,i[3]=0,i[4]=u-_,i[5]=1-h-m,i[6]=f+p,i[7]=0,i[8]=l+b,i[9]=f-p,i[10]=1-h-d,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function kn(i,e,t,n,r,s,o){let a=1/(t-e),c=1/(r-n),h=1/(s-o);return i[0]=s*2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s*2*c,i[6]=0,i[7]=0,i[8]=(t+e)*a,i[9]=(r+n)*c,i[10]=(o+s)*h,i[11]=-1,i[12]=0,i[13]=0,i[14]=o*s*2*h,i[15]=0,i}function Ps(i,e,t,n,r){let s=1/Math.tan(e/2);if(i[0]=s/t,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,r!=null&&r!==1/0){let o=1/(n-r);i[10]=(r+n)*o,i[14]=2*r*n*o}else i[10]=-1,i[14]=-2*n;return i}var Nn=Ps;function Ls(i,e,t,n,r,s,o){let a=1/(e-t),c=1/(n-r),h=1/(s-o);return i[0]=-2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*c,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=2*h,i[11]=0,i[12]=(e+t)*a,i[13]=(r+n)*c,i[14]=(o+s)*h,i[15]=1,i}var Dn=Ls;function Bn(i,e,t,n){let r,s,o,a,c,h,u,d,l,f,m=e[0],p=e[1],b=e[2],_=n[0],M=n[1],y=n[2],I=t[0],g=t[1],x=t[2];return Math.abs(m-I)<1e-6&&Math.abs(p-g)<1e-6&&Math.abs(b-x)<1e-6?Cs(i):(d=m-I,l=p-g,f=b-x,r=1/Math.sqrt(d*d+l*l+f*f),d*=r,l*=r,f*=r,s=M*f-y*l,o=y*d-_*f,a=_*l-M*d,r=Math.sqrt(s*s+o*o+a*a),r?(r=1/r,s*=r,o*=r,a*=r):(s=0,o=0,a=0),c=l*a-f*o,h=f*s-d*a,u=d*o-l*s,r=Math.sqrt(c*c+h*h+u*u),r?(r=1/r,c*=r,h*=r,u*=r):(c=0,h=0,u=0),i[0]=s,i[1]=c,i[2]=d,i[3]=0,i[4]=o,i[5]=h,i[6]=l,i[7]=0,i[8]=a,i[9]=u,i[10]=f,i[11]=0,i[12]=-(s*m+o*p+a*b),i[13]=-(c*m+h*p+u*b),i[14]=-(d*m+l*p+f*b),i[15]=1,i)}function Rs(){let i=new te(4);return te!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0,i[3]=0),i}function Fn(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3];return i[0]=t[0]*n+t[4]*r+t[8]*s+t[12]*o,i[1]=t[1]*n+t[5]*r+t[9]*s+t[13]*o,i[2]=t[2]*n+t[6]*r+t[10]*s+t[14]*o,i[3]=t[3]*n+t[7]*r+t[11]*s+t[15]*o,i}var ih=(function(){let i=Rs();return function(e,t,n,r,s,o){let a,c;for(t||(t=4),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],i[2]=e[a+2],i[3]=e[a+3],s(i,i,o),e[a]=i[0],e[a+1]=i[1],e[a+2]=i[2],e[a+3]=i[3];return e}})();var xi;(function(i){i[i.COL0ROW0=0]="COL0ROW0",i[i.COL0ROW1=1]="COL0ROW1",i[i.COL0ROW2=2]="COL0ROW2",i[i.COL0ROW3=3]="COL0ROW3",i[i.COL1ROW0=4]="COL1ROW0",i[i.COL1ROW1=5]="COL1ROW1",i[i.COL1ROW2=6]="COL1ROW2",i[i.COL1ROW3=7]="COL1ROW3",i[i.COL2ROW0=8]="COL2ROW0",i[i.COL2ROW1=9]="COL2ROW1",i[i.COL2ROW2=10]="COL2ROW2",i[i.COL2ROW3=11]="COL2ROW3",i[i.COL3ROW0=12]="COL3ROW0",i[i.COL3ROW1=13]="COL3ROW1",i[i.COL3ROW2=14]="COL3ROW2",i[i.COL3ROW3=15]="COL3ROW3"})(xi||(xi={}));var Ns=45*Math.PI/180,Ds=1,pi=.1,gi=500,Bs=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),k=class extends vt{static get IDENTITY(){return zs()}static get ZERO(){return Fs()}get ELEMENTS(){return 16}get RANK(){return 4}get INDICES(){return xi}constructor(e){super(-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0),arguments.length===1&&Array.isArray(e)?this.copy(e):this.identity()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this[4]=e[4],this[5]=e[5],this[6]=e[6],this[7]=e[7],this[8]=e[8],this[9]=e[9],this[10]=e[10],this[11]=e[11],this[12]=e[12],this[13]=e[13],this[14]=e[14],this[15]=e[15],this.check()}set(e,t,n,r,s,o,a,c,h,u,d,l,f,m,p,b){return this[0]=e,this[1]=t,this[2]=n,this[3]=r,this[4]=s,this[5]=o,this[6]=a,this[7]=c,this[8]=h,this[9]=u,this[10]=d,this[11]=l,this[12]=f,this[13]=m,this[14]=p,this[15]=b,this.check()}setRowMajor(e,t,n,r,s,o,a,c,h,u,d,l,f,m,p,b){return this[0]=e,this[1]=s,this[2]=h,this[3]=f,this[4]=t,this[5]=o,this[6]=u,this[7]=m,this[8]=n,this[9]=a,this[10]=d,this[11]=p,this[12]=r,this[13]=c,this[14]=l,this[15]=b,this.check()}toRowMajor(e){return e[0]=this[0],e[1]=this[4],e[2]=this[8],e[3]=this[12],e[4]=this[1],e[5]=this[5],e[6]=this[9],e[7]=this[13],e[8]=this[2],e[9]=this[6],e[10]=this[10],e[11]=this[14],e[12]=this[3],e[13]=this[7],e[14]=this[11],e[15]=this[15],e}identity(){return this.copy(Bs)}fromObject(e){return this.check()}fromQuaternion(e){return Rn(this,e),this.check()}frustum(e){let{left:t,right:n,bottom:r,top:s,near:o=pi,far:a=gi}=e;return a===1/0?js(this,t,n,r,s,o):kn(this,t,n,r,s,o,a),this.check()}lookAt(e){let{eye:t,center:n=[0,0,0],up:r=[0,1,0]}=e;return Bn(this,t,n,r),this.check()}ortho(e){let{left:t,right:n,bottom:r,top:s,near:o=pi,far:a=gi}=e;return Dn(this,t,n,r,s,o,a),this.check()}orthographic(e){let{fovy:t=Ns,aspect:n=Ds,focalDistance:r=1,near:s=pi,far:o=gi}=e;zn(t);let a=t/2,c=r*Math.tan(a),h=c*n;return this.ortho({left:-h,right:h,bottom:-c,top:c,near:s,far:o})}perspective(e){let{fovy:t=45*Math.PI/180,aspect:n=1,near:r=.1,far:s=500}=e;return zn(t),Nn(this,t,n,r,s),this.check()}determinant(){return An(this)}getScale(e=[-0,-0,-0]){return e[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]),e[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]),e[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]),e}getTranslation(e=[-0,-0,-0]){return e[0]=this[12],e[1]=this[13],e[2]=this[14],e}getRotation(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=0,e[4]=this[4]*r,e[5]=this[5]*s,e[6]=this[6]*o,e[7]=0,e[8]=this[8]*r,e[9]=this[9]*s,e[10]=this[10]*o,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}getRotationMatrix3(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=this[4]*r,e[4]=this[5]*s,e[5]=this[6]*o,e[6]=this[8]*r,e[7]=this[9]*s,e[8]=this[10]*o,e}transpose(){return Tn(this,this),this.check()}invert(){return wn(this,this),this.check()}multiplyLeft(e){return mi(this,e,this),this.check()}multiplyRight(e){return mi(this,this,e),this.check()}rotateX(e){return Pn(this,this,e),this.check()}rotateY(e){return Ln(this,this,e),this.check()}rotateZ(e){return On(this,this,e),this.check()}rotateXYZ(e){return this.rotateX(e[0]).rotateY(e[1]).rotateZ(e[2])}rotateAxis(e,t){return Cn(this,this,e,t),this.check()}scale(e){return En(this,this,Array.isArray(e)?e:[e,e,e]),this.check()}translate(e){return Sn(this,this,e),this.check()}transform(e,t){return e.length===4?(t=Fn(t||[-0,-0,-0,-0],e,this),xt(t,4),t):this.transformAsPoint(e,t)}transformAsPoint(e,t){let{length:n}=e,r;switch(n){case 2:r=mn(t||[-0,-0],e,this);break;case 3:r=_t(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return xt(r,e.length),r}transformAsVector(e,t){let n;switch(e.length){case 2:n=pn(t||[-0,-0],e,this);break;case 3:n=yt(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return xt(n,e.length),n}transformPoint(e,t){return this.transformAsPoint(e,t)}transformVector(e,t){return this.transformAsPoint(e,t)}transformDirection(e,t){return this.transformAsVector(e,t)}makeRotationX(e){return this.identity().rotateX(e)}makeTranslation(e,t,n){return this.identity().translate([e,t,n])}},Mt,Tt;function Fs(){return Mt||(Mt=new k([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Object.freeze(Mt)),Mt}function zs(){return Tt||(Tt=new k,Object.freeze(Tt)),Tt}function zn(i){if(i>Math.PI*2)throw Error("expected radians")}function js(i,e,t,n,r,s){let o=2*s/(t-e),a=2*s/(r-n),c=(t+e)/(t-e),h=(r+n)/(r-n),u=-1,d=-1,l=-2*s;return i[0]=o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=a,i[6]=0,i[7]=0,i[8]=c,i[9]=h,i[10]=u,i[11]=d,i[12]=0,i[13]=0,i[14]=l,i[15]=0,i}function jn(i){let{joints:e,meshNode:t,worldMatrices:n,inverseBindMatrices:r,target:s}=i,o=e.length,a=s&&s.length===o*16?s:new Float32Array(o*16),c=t?n.get(t)||t.matrix:void 0,h=c?new k(c).invert():null;for(let u=0;u<o;u++){let d=e[u],l=n.get(d)||d.matrix,f=h?new k(h).multiplyRight(l):new k(l),m=u*16;if(r&&r.length>=m+16){let p=new k;for(let b=0;b<16;b++)p[b]=r[m+b];f.multiplyRight(p)}a.set(f,m)}return a}var Gs=1,Us=1,wt=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(e){let{delay:t=0,duration:n=Number.POSITIVE_INFINITY,rate:r=1,repeat:s=1}=e,o=Gs++,a={time:0,delay:t,duration:n,rate:r,repeat:s};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(e){this.channels.delete(e);for(let[t,n]of this.animations)n.channel===e&&this.detachAnimation(t)}isFinished(e){let t=this.channels.get(e);return t===void 0?!1:this.time>=t.delay+t.duration*t.repeat}getTime(e){if(e===void 0)return this.time;let t=this.channels.get(e);return t===void 0?-1:t.time}setTime(e){this.time=Math.max(0,e);let t=this.channels.values();for(let r of t)this._setChannelTime(r,this.time);let n=this.animations.values();for(let r of n){let{animation:s,channel:o}=r;s.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(e,t){let n=Us++;return this.animations.set(n,{animation:e,channel:t}),e.setTime(this.getTime(t)),n}detachAnimation(e){this.animations.delete(e)}update(e){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=e),this.setTime(this.time+(e-this.lastEngineTime)),this.lastEngineTime=e)}_setChannelTime(e,t){let n=t-e.delay,r=e.duration*e.repeat;n>=r?e.time=e.duration*e.rate:(e.time=Math.max(0,n)%e.duration,e.time*=e.rate)}};var At=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(e){this.setKeyFrames(e),this.setTime(0)}setKeyFrames(e){let t=e.length;this.times.length=t,this.values.length=t;for(let n=0;n<t;++n)this.times[n]=e[n][0],this.values[n]=e[n][1];this._calculateKeys(this._lastTime)}setTime(e){e=Math.max(0,e),e!==this._lastTime&&(this._calculateKeys(e),this._lastTime=e)}getStartTime(){return this.times[this.startIndex]}getEndTime(){return this.times[this.endIndex]}getStartData(){return this.values[this.startIndex]}getEndData(){return this.values[this.endIndex]}_calculateKeys(e){let t=0,n=this.times.length;for(t=0;t<n-2&&!(this.times[t+1]>e);++t);this.startIndex=t,this.endIndex=t+1;let r=this.times[this.startIndex],s=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(e-r)/(s-r)),1)}};var St=class{constructor(e){}async onInitialize(e){return null}};var Un=R(N(),1);function Et(i){let e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,i):setTimeout(()=>i(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function Ct(i){let e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,i);return}clearTimeout(i)}function Xe(){let i;if(typeof window<"u"&&window.performance)i=window.performance.now();else if(typeof process<"u"&&process.hrtime){let e=process.hrtime();i=e[0]*1e3+e[1]/1e6}else i=Date.now();return i}var xe=class{constructor(e,t){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=e,this.type=t,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(e){return this.sampleSize=e,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(e){return this._count+=e,this._samples++,this._checkSampling(),this}subtractCount(e){return this._count-=e,this._samples++,this._checkSampling(),this}addTime(e){return this._time+=e,this.lastTiming=e,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=Xe(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(Xe()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var Se=class{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,t="count"){return this._getOrCreate({name:e,type:t})}get size(){return Object.keys(this.stats).length}reset(){for(let e of Object.values(this.stats))e.reset();return this}forEach(e){for(let t of Object.values(this.stats))e(t)}getTable(){let e={};return this.forEach(t=>{e[t.name]={time:t.time||0,count:t.count||0,average:t.getAverageTime()||0,hz:t.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(t=>this._getOrCreate(t))}_getOrCreate(e){let{name:t,type:n}=e,r=this.stats[t];return r||(e instanceof xe?r=e:r=new xe(t,n),this.stats[t]=r),r}};var $s=0,Vs="Animation Loop",Gn={requestAnimationFrame:i=>Et(i),cancelAnimationFrame:i=>Ct(i)},Ee=class i{static defaultAnimationLoopProps={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>{console.error(e)},stats:void 0,autoResizeViewport:!1,animationFrameProvider:Gn};device=null;canvas=null;props;animationProps=null;timeline=null;stats;sharedStats;cpuTime;gpuTime;frameRate;display;_needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;_lastFrameTime=0;constructor(e){if(this.props={...i.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new Se({id:`animation-loop-${$s++}`}),this.sharedStats=Un.luma.stats.get(Vs),this.frameRate=this.stats.get("Frame Rate"),this.frameRate.setSampleSize(1),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.setProps({autoResizeViewport:e.autoResizeViewport,animationFrameProvider:e.animationFrameProvider}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null),this.device?._disableDebugGPUTime()}delete(){this.destroy()}reportError(e){this.props.onError(e),this._error=e}setNeedsRedraw(e){return this._needsRedraw=this._needsRedraw||e,this}needsRedraw(){let e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){if("autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),"animationFrameProvider"in e){let t=e.animationFrameProvider||Gn;if(t!==this.props.animationFrameProvider){let n=this._animationFrameId!==null;n&&this._cancelAnimationFrame(),this.props.animationFrameProvider=t,n&&this._requestAnimationFrame()}}return this}async start(){if(this._running)return this;this._running=!0;try{let e;if(!this._initialized){if(this._initialized=!0,await this._initDevice(),this._initialize(),!this._running)return null;await this.props.onInitialize(this._getAnimationProps())}return this._running?(e!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(e){let t=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(t),t}}stop(){return this._running&&(this.animationProps&&!this._error&&this.props.onFinalize(this.animationProps),this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1,this._lastFrameTime=0),this}redraw(e,t=null){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),this._setupFrame(),this.animationProps&&(this.animationProps.animationFrame=t),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(e){return this.timeline=e,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(e=>{this._resolveNextFrame=e})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeViewport(),this.device?._enableDebugGPUTime()}_setDisplay(e){this.display&&(this.display.destroy(),this.display.animationLoop=null),e&&(e.animationLoop=this),this.display=e}_requestAnimationFrame(){this._running&&(this._animationFrameId=this.props.animationFrameProvider.requestAnimationFrame(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(this.props.animationFrameProvider.cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e,t){this._running&&(this.redraw(e,t??null),this._requestAnimationFrame())}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}let t=this.props.onRender(this._getAnimationProps());this.device&&t!==!1&&this.device.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){let e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");let t=e?.canvas,n=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:t,useDevicePixels:n,timeline:this.timeline,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,animationFrame:null,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:e,height:t,aspect:n}=this._getSizeAndAspect();(e!==this.animationProps.width||t!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),n!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=e,this.animationProps.height=t,this.animationProps.aspect=n,this.animationProps.needsRedraw=this._needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.getDefaultCanvasContext().canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";let t=document.createElement("div");t.style.position="absolute",t.style.left="10px",t.style.bottom="10px",t.style.width="300px",t.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(t);let n=this.props.onAddHTML(t);n&&(t.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[e,t]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),n=e>0&&t>0?e/t:1;return{width:e,height:t,aspect:n}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(e){let t=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let n=t-this._lastFrameTime;n>0&&this.frameRate.addTime(n)}this._lastFrameTime=t,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let e=this.device.commandEncoder._gpuTimeMs;e!==void 0&&(this.gpuTime.addTime(e),this.device.commandEncoder._gpuTimeMs=void 0)}_updateSharedStats(){if(this.stats!==this.sharedStats){for(let e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{let t=this.sharedStats.get(e.name,e.type);t.sampleSize=e.sampleSize,t.time=e.time,t.count=e.count,t.samples=e.samples,t.lastTiming=e.lastTiming,t.lastSampleTime=e.lastSampleTime,t.lastSampleCount=e.lastSampleCount,t._count=e._count,t._time=e._time,t._samples=e._samples,t._startTime=e._startTime,t._timerPending=e._timerPending})}}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(e){e instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[e.offsetX,e.offsetY])}_onMouseleave(e){this._getAnimationProps()._mousePosition=null}};var $n=R(N(),1);function Vn(i,e){let t=null,n=e?.device||$n.luma.createDevice({id:"animation-loop",adapters:e?.adapters,createCanvasContext:!0}),r=new Ee({...e,device:n,async onInitialize(o){Hs(o.animationLoop.device);try{return t=new i(o),await t?.onInitialize(o)}catch(a){return console.error(a),t=null,Xs(o.animationLoop.device,a),o.animationLoop.stop(),null}},onRender(o){let a=t?.onRender(o),c=e?.onAfterRender?.(o,t);return e?.onAfterRender?a!==!1||c!==!1:a},onFinalize(o){try{t?.onFinalize(o)}finally{t=null}}}),s=r;return s.getAnimationLoopTemplate=()=>t,r.getInfo=()=>this.AnimationLoopTemplateCtor.info,s}function Xs(i,e){if(!i)return;let t=i.getDefaultCanvasContext().canvas;if(t instanceof HTMLCanvasElement){t.style.overflow="visible";let n=document.getElementById("animation-loop-error");n?.remove(),n=document.createElement("h1"),n.id="animation-loop-error",n.innerHTML=e.message,n.style.position="absolute",n.style.top="10px",n.style.left="10px",n.style.color="black",n.style.backgroundColor="red",t.parentElement?.appendChild(n)}}function Hs(i){if(!i)return;let e=document.getElementById("animation-loop-error");e&&e.remove()}var Ys={target:[0,0,0],distance:10,yaw:0,pitch:.25,minDistance:1,maxDistance:100,minPitch:-Math.PI/2+.01,maxPitch:Math.PI/2-.01,rotateSpeed:.006,zoomSpeed:.001,enabled:!0,enableZoom:!0,enablePan:!1,panSpeed:.0018,autoRotate:!1,autoRotateSpeed:.1},Pt=class{canvas;props;yaw;pitch;distance;dragging=!1;pointerId=null;lastPointer=[0,0];previousTimeMilliseconds=null;previousCursor;previousTouchAction;constructor(e,t={}){this.canvas=e,this.props={...Ys,...t},this.props.target=[...this.props.target],this.yaw=this.props.yaw,this.pitch=ie(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.distance=ie(this.props.distance,this.props.minDistance,this.props.maxDistance),this.previousCursor=e.style.cursor,this.previousTouchAction=e.style.touchAction,e.style.cursor="grab",e.style.touchAction="none",e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("pointerup",this.handlePointerUp),e.addEventListener("pointercancel",this.handlePointerUp),e.addEventListener("wheel",this.handleWheel,{passive:!1})}update(e){if(this.previousTimeMilliseconds!==null&&this.props.enabled&&this.props.autoRotate&&!this.dragging){let t=Math.min(Math.max(e-this.previousTimeMilliseconds,0)/1e3,.1);this.yaw+=this.props.autoRotateSpeed*t}this.previousTimeMilliseconds=e}getEyePosition(){let e=this.distance*Math.cos(this.pitch);return[this.props.target[0]+e*Math.sin(this.yaw),this.props.target[1]+this.distance*Math.sin(this.pitch),this.props.target[2]+e*Math.cos(this.yaw)]}setAutoRotate(e){this.props.autoRotate=e}setProps(e){Object.assign(this.props,e),e.enabled===!1&&this.dragging&&this.endPointerInteraction(),e.target&&(this.props.target=[...e.target]),e.yaw!==void 0&&(this.yaw=e.yaw),(e.pitch!==void 0||e.minPitch!==void 0||e.maxPitch!==void 0)&&(this.pitch=ie(e.pitch??this.pitch,this.props.minPitch,this.props.maxPitch)),(e.distance!==void 0||e.minDistance!==void 0||e.maxDistance!==void 0)&&(this.distance=ie(e.distance??this.distance,this.props.minDistance,this.props.maxDistance))}reset(){this.yaw=this.props.yaw,this.pitch=ie(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.distance=ie(this.props.distance,this.props.minDistance,this.props.maxDistance)}destroy(){this.canvas.removeEventListener("pointerdown",this.handlePointerDown),this.canvas.removeEventListener("pointermove",this.handlePointerMove),this.canvas.removeEventListener("pointerup",this.handlePointerUp),this.canvas.removeEventListener("pointercancel",this.handlePointerUp),this.canvas.removeEventListener("wheel",this.handleWheel),this.pointerId!==null&&this.canvas.hasPointerCapture(this.pointerId)&&this.canvas.releasePointerCapture(this.pointerId),this.canvas.style.cursor=this.previousCursor,this.canvas.style.touchAction=this.previousTouchAction}handlePointerDown=e=>{!this.props.enabled||e.button!==0||(this.props.onInteractionStart?.(),this.dragging=!0,this.pointerId=e.pointerId,this.lastPointer=[e.clientX,e.clientY],this.canvas.setPointerCapture(e.pointerId),this.canvas.style.cursor="grabbing")};handlePointerMove=e=>{if(!this.props.enabled||!this.dragging||e.pointerId!==this.pointerId)return;let t=e.clientX-this.lastPointer[0],n=e.clientY-this.lastPointer[1];if(this.lastPointer=[e.clientX,e.clientY],this.props.enablePan&&e.shiftKey){let r=this.distance*this.props.panSpeed;this.props.target=[this.props.target[0]-Math.cos(this.yaw)*t*r,this.props.target[1]+n*r,this.props.target[2]+Math.sin(this.yaw)*t*r]}else this.yaw-=t*this.props.rotateSpeed,this.pitch=ie(this.pitch-n*(this.props.pitchSpeed??this.props.rotateSpeed),this.props.minPitch,this.props.maxPitch)};handlePointerUp=e=>{e.pointerId===this.pointerId&&this.endPointerInteraction()};endPointerInteraction(){this.dragging=!1,this.pointerId!==null&&this.canvas.hasPointerCapture(this.pointerId)&&this.canvas.releasePointerCapture(this.pointerId),this.pointerId=null,this.canvas.style.cursor="grab"}handleWheel=e=>{if(!this.props.enabled||!this.props.enableZoom)return;e.preventDefault(),this.props.onInteractionStart?.();let t=ie(e.deltaY,-240,240);this.distance=ie(this.distance*Math.exp(t*this.props.zoomSpeed),this.props.minDistance,this.props.maxDistance)}};function ie(i,e,t){return Math.min(Math.max(i,e),t)}var E=R(N(),1),ye=R(ce(),1);var bi=R(N(),1);var Ce=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||O("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&bi.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function Hn(i,e){if(e instanceof Ce)return e;let t=Me(e),n=Ws(i,t),{attributes:r,bufferLayout:s}=qs(i,t);return new Ce({topology:t.topology||"triangle-list",bufferLayout:s,vertexCount:t.vertexCount,indices:n,attributes:r})}function Ws(i,e){if(!e.indices)return;let t=e.indices.value;return i.createBuffer({usage:bi.Buffer.INDEX,data:t})}function qs(i,e){let t={};for(let[n,r]of Object.entries(e.attributes)){let s=e.bufferLayout.find(o=>o.name===n)?.name||ge(n);r&&(t[s]=i.createBuffer({data:r.value,id:`${n}-buffer`}))}return{attributes:t,bufferLayout:e.bufferLayout,vertexCount:e.vertexCount}}function Yn(i,e){let t={},n="Values";if(i.attributes.length===0&&!i.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let r of i.attributes)if(r){let s=`${r.location} ${r.name}: ${r.type}`;t[`in ${s}`]={[n]:r.stepMode||"vertex"}}for(let r of i.varyings||[]){let s=`${r.location} ${r.name}`;t[`out ${s}`]={[n]:JSON.stringify(r)}}return t}var Wn="__debugFramebufferState";function Kn(i,e,t){if(i.device.type!=="webgl")return;let n=Qs(i.device);if(!n.flushing){if(eo(i)){Ks(i,t,n);return}e&&Js(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function Ks(i,e,t){if(t.queuedFramebuffers.length===0)return;let n=i.device,{gl:r}=n,s=r.getParameter(36010),o=r.getParameter(36006),[a,c]=i.device.getDefaultCanvasContext().getDrawingBufferSize(),h=qn(e.top,8),u=qn(e.left,8);t.flushing=!0;try{for(let d of t.queuedFramebuffers){let[l,f,m,p,b]=Zs({framebuffer:d,targetWidth:a,targetHeight:c,topPx:h,leftPx:u,minimap:e.minimap});r.bindFramebuffer(36008,d.handle),r.bindFramebuffer(36009,null),r.blitFramebuffer(0,0,d.width,d.height,l,f,m,p,16384,9728),h+=b+8}}finally{r.bindFramebuffer(36008,s),r.bindFramebuffer(36009,o),t.flushing=!1}}function Zs(i){let{framebuffer:e,targetWidth:t,targetHeight:n,topPx:r,leftPx:s,minimap:o}=i,a=o?Math.max(Math.floor(t/4),1):t,c=o?Math.max(Math.floor(n/4),1):n,h=Math.min(a/e.width,c/e.height),u=Math.max(Math.floor(e.width*h),1),d=Math.max(Math.floor(e.height*h),1),l=s,f=Math.max(n-r-d,0),m=l+u,p=f+d;return[l,f,m,p,d]}function Qs(i){return i.userData[Wn]||={flushing:!1,queuedFramebuffers:[]},i.userData[Wn]}function Js(i){return"colorAttachments"in i}function eo(i){let e=i.props.framebuffer;return!e||e.handle===null}function qn(i,e){if(!i)return e;let t=Number.parseInt(i,10);return Number.isFinite(t)?t:e}function Pe(i,e,t){if(i===e)return!0;if(!t||!i||!e)return!1;if(Array.isArray(i)){if(!Array.isArray(e)||i.length!==e.length)return!1;for(let n=0;n<i.length;n++)if(!Pe(i[n],e[n],t-1))return!1;return!0}if(Array.isArray(e))return!1;if(typeof i=="object"&&typeof e=="object"){let n=Object.keys(i),r=Object.keys(e);if(n.length!==r.length)return!1;for(let s of n)if(!e.hasOwnProperty(s)||!Pe(i[s],e[s],t-1))return!1;return!0}return!1}var Zn=R(N(),1),Le=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return(0,Zn.getBufferLayoutAttributeNames)(e)}mergeBufferLayouts(e,t){let n=[...e];for(let r of t){let s=n.findIndex(o=>o.name===r.name);s<0?n.push(r):n[s]=r}return n}};var he=R(N(),1);function Qn(i,e){let t=(0,he.getShaderAttributeLocationMap)(i),n=e.slice();return n.sort((r,s)=>{let o=(0,he.getMinimumAttributeLocation)((0,he.getBufferLayoutAttributeNames)(r).map(c=>t[c])),a=(0,he.getMinimumAttributeLocation)((0,he.getBufferLayoutAttributeNames)(s).map(c=>t[c]));return o-a}),n}function Oe(i,e){if(!i||!e.some(n=>n.bindingLayout?.length))return i;let t={...i,bindings:i.bindings.map(n=>({...n}))};"attributes"in(i||{})&&(t.attributes=i?.attributes||[]);for(let n of e)for(let r of n.bindingLayout||[])for(let s of to(r.name)){let o=t.bindings.find(a=>a.name===s);o?.group===0&&(o.group=r.group),o&&r.visibility!==void 0&&(o.visibility=r.visibility)}return t}function Jn(i,e,t=[]){return i?e?{...i,attributes:i.attributes.length?ro(i.attributes,e.attributes.filter(n=>t.includes(n.name))):e.attributes,bindings:no(i.bindings,e.bindings)}:i:e}function Re(i){return!!(i.uniformTypes&&!io(i.uniformTypes))}function Lt(i,e){let t=[],n=new Set;for(let r of[...i||[],...e||[]])n.has(r.name)||(n.add(r.name),t.push(r));return t}function to(i){let e=new Set([i,`${i}Uniforms`]);return i.endsWith("Uniforms")||e.add(`${i}Sampler`),[...e]}function io(i){for(let e in i)return!1;return!0}function no(i,e){let t=i.map(s=>({...s})),n=new Set(i.map(s=>s.name)),r=new Set(i.map(s=>`${s.group}:${s.location}`));for(let s of e){let o=`${s.group}:${s.location}`;!n.has(s.name)&&!r.has(o)&&t.push({...s})}return t}function ro(i,e){let t=i.map(s=>({...s})),n=new Map(i.map(s=>[s.name,s])),r=new Map(i.map(s=>[s.location,s]));for(let s of e){let o=n.get(s.name);if(o){if(o.type!==s.type||o.location!==s.location)throw new Error(`Shader attribute "${s.name}" conflicts with its inferred type or location`);continue}let a=r.get(s.location);if(a)throw new Error(`Shader attributes "${a.name}" and "${s.name}" both use location ${s.location}`);t.push({...s})}return t}var Ot=R(N(),1),yi=R(ce(),1);function er(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function tr(i){return Array.isArray(i)?i.length===0||typeof i[0]=="number":!1}function He(i){return er(i)||tr(i)}function so(i){return He(i)||typeof i=="number"||typeof i=="boolean"}function ir(i,e={}){let t={bindings:{},uniforms:{}};return Object.keys(i).forEach(n=>{let r=i[n];Object.prototype.hasOwnProperty.call(e,n)||so(r)?t.uniforms[n]=r:t.bindings[n]=r}),t}var X=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;directBindings={};constructor(e,t){Object.assign(this.options,t);let n=(0,yi.getShaderModuleDependencies)(Object.values(e).filter(oo));for(let r of n)e[r.name]=r;Ot.log.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[r,s]of Object.entries(e))s&&(this._addModule(s),s.name&&r!==s.name&&!this.options.disableWarnings&&Ot.log.warn(`Module name: ${r} vs ${s.name}`)())}destroy(){}setProps(e){e.bindings&&Object.assign(this.directBindings,e.bindings);for(let t of Object.keys(e)){if(t==="bindings")continue;let n=t,r=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||Ot.log.warn(`Module ${t} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(r,o)||r,{uniforms:h,bindings:u}=ir(c,s.uniformTypes);this.moduleUniforms[n]=nr(o,h,s.uniformTypes),this.moduleBindings[n]={...a,...u}}}}getModules(){return Object.values(this.modules)}addModules(e){let t=(0,yi.getShaderModuleDependencies)(e);for(let n of t){let r=n.name;this.modules[r]||(this.modules[r]=n,this._addModule(n))}}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let t of Object.values(this.moduleBindings))Object.assign(e,t);return Object.assign(e,this.directBindings),e}getModuleBindingValues(e){let t=this.moduleBindings[e];return t?{...t}:{}}getDebugTable(){let e={};for(let[t,n]of Object.entries(this.moduleUniforms))for(let[r,s]of Object.entries(n))e[`${t}.${r}`]={type:this.modules[t].uniformTypes?.[r],value:String(s)};return e}_addModule(e){let t=e.name;this.moduleUniforms[t]=nr({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[t]={}}};function nr(i={},e={},t={}){let n={...i};for(let[r,s]of Object.entries(e))s!==void 0&&(n[r]=_i(i[r],s,t[r]));return n}function _i(i,e,t){if(!t||typeof t=="string")return Ye(e);if(Array.isArray(t)){if(Ii(e)||!Array.isArray(e))return Ye(e);let o=Array.isArray(i)&&!Ii(i)?[...i]:[],a=o.slice();for(let c=0;c<e.length;c++){let h=e[c];h!==void 0&&(a[c]=_i(o[c],h,t[0]))}return a}if(!vi(e))return Ye(e);let n=t,r=vi(i)?i:{},s={...r};for(let[o,a]of Object.entries(e))a!==void 0&&(s[o]=_i(r[o],a,n[o]));return s}function Ye(i){return ArrayBuffer.isView(i)?Array.prototype.slice.call(i):Array.isArray(i)?Ii(i)?i.slice():i.map(t=>t===void 0?void 0:Ye(t)):vi(i)?Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t===void 0?void 0:Ye(t)])):i}function Ii(i){return ArrayBuffer.isView(i)||Array.isArray(i)&&(i.length===0||typeof i[0]=="number")}function vi(i){return!!i&&typeof i=="object"&&!Array.isArray(i)&&!ArrayBuffer.isView(i)}function oo(i){return!!i?.dependencies}var Mi=R(N(),1);var ao=Mi.Buffer.DEBUG_DATA_MAX_LENGTH,G=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:r,ownsBuffer:s=!0,...o}=t;if(r&&r.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(r&&(o.byteLength!==void 0||o.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||r?.id||O("dynamic-buffer"),c={...o,id:a,usage:o.usage??r?.usage,indexType:o.indexType??r?.indexType};(c.usage||0)&Mi.Buffer.INDEX&&!c.indexType&&(o.data instanceof Uint32Array?c.indexType="uint32":o.data instanceof Uint16Array?c.indexType="uint16":o.data instanceof Uint8Array&&(c.indexType="uint8")),delete c.data,delete c.byteOffset,this.device=e,this.id=a,this.props=c,this.usage=c.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:ao,this._ownsBuffer=s,this._buffer=r??this.device.createBuffer({...o,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),o.data&&this._writeDebugData(o.data,o.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let r=null;await this._buffer.mapAndWriteAsync(async(s,o)=>{await e(s,o),r=new Uint8Array(s.slice(0,n))},t,n),this._touch(),r&&this._writeDebugData(r,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let r=null,s=await this._buffer.mapAndReadAsync(async(o,a)=>(r=new Uint8Array(o.slice(0)),await e(o,a)),t,n);return r&&this._writeDebugData(r,t)&&this._touch(),s}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let r=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),s=this._buffer,o=this.debugData.slice(0),{data:a,byteOffset:c,...h}=this.props,u=this.device.createBuffer({...h,byteLength:t});return n&&r>0&&this._copyBufferContents(s,u,r),this._buffer=u,this._resetDebugData(t),n&&o.byteLength>0&&this._writeDebugData(o,0),this._ownsBuffer&&s.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let r=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,s=this.device.createCommandEncoder();s.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:r}),this.device.submit(s.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=new Uint8Array(this.debugData),s=Math.min(n.byteLength,r.byteLength-t);return r.set(n.subarray(0,s),t),s>0}};function be(i){return i!==null&&typeof i=="object"&&"buffer"in i}function rr(i){return i instanceof G?i:be(i)&&i.buffer instanceof G?i.buffer:null}function co(i){return i instanceof G?i.buffer:i}function Rt(i){return{buffer:co(i.buffer),offset:i.offset,size:i.size}}var sr=R(N(),1);function ne(i){return i!==null&&typeof i=="object"&&"resolveTextureBinding"in i&&typeof i.resolveTextureBinding=="function"}function ho(i){return i?.type==="texture"||i?.type==="external-texture"}function kt(i,e,t){let n=(0,sr.getShaderLayoutBinding)(i,e,{ignoreWarnings:!0});return ho(n)?n:i.bindings.length===0&&t?.fallbackGroup!==void 0?{type:"texture",name:e,group:t.fallbackGroup,location:0}:null}var Q=2,uo=1e4,Ti="render pipeline initialization failed",lo=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],Y=class i{static defaultProps={...E.RenderPipeline.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],geometry:null,indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,material:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:ye.ShaderAssembler.getDefaultShaderAssembler("glsl"),debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;material=null;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_lastDrawTimestamp=-1;_bindingTable=[];get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(e,t){let n=i.defaultProps.shaderAssembler;this.props={...i.defaultProps,...t,shaderAssembler:t.shaderAssembler??(wi(n,e.info.shadingLanguage)?n:ye.ShaderAssembler.getDefaultShaderAssembler(e.info.shadingLanguage))},t=this.props,this.id=t.id||O("model"),this.device=e,Object.assign(this.userData,t.userData),this.material=t.material||null;let r=xo(e),s=(0,ye.resolveShaderPlugins)(this.props.plugins,r.shaderLanguage),o=(0,ye.mergeShaderPluginModules)(this.props.modules,s.modules),a=Object.fromEntries(o.map(l=>[l.name,l])),c=t.shaderInputs||new X(a,{disableWarnings:this.props.disableWarnings});t.shaderInputs&&s.modules.length>0&&c.addModules(s.modules),this.setShaderInputs(c);let h=Lt(this.props.modules,c.getModules()),u={...s.defines,...this.props.defines};if(this.props.shaderLayout=Oe(this.props.shaderLayout,h)||null,this.device.type==="webgpu"&&this.props.source){let l=this.props.shaderAssembler;(0,E.assert)(wi(l,"wgsl"));let{source:f,getUniforms:m,bindingTable:p,shaderLayout:b}=l.assembleWGSLShader({platformInfo:r,...this.props,modules:h,defines:u,pluginInjections:s.injections,pluginVertexInputs:s.vertexInputs,pluginVaryings:s.varyings});this.source=f,this._getModuleUniforms=m,this._bindingTable=p;let _=b??e.getShaderLayout?.(this.source),M=fo(_,s.vertexInputs),y=Jn(this.props.shaderLayout,M,Object.keys(s.vertexInputs));this.props.shaderLayout=Oe(y||null,h)||null}else{let l=this.props.shaderAssembler;(0,E.assert)(wi(l,"glsl"));let{vs:f,fs:m,getUniforms:p}=l.assembleGLSLShaderPair({platformInfo:r,...this.props,modules:h,defines:u,pluginInjections:s.injections,pluginVertexInputs:s.vertexInputs,pluginVaryings:s.varyings});this.vs=f,this.fs=m,this._getModuleUniforms=p,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,t.geometry&&this.setGeometry(t.geometry),this.pipelineFactory=t.pipelineFactory||E.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||E.ShaderFactory.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=e.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in t&&(this.isInstanced=t.isInstanced),t.instanceCount&&this.setInstanceCount(t.instanceCount),t.vertexCount&&this.setVertexCount(t.vertexCount),t.indexBuffer&&this.setIndexBuffer(t.indexBuffer),t.attributes&&this.setAttributes(t.attributes),t.constantAttributes&&this.setConstantAttributes(t.constantAttributes),t.bindings&&this.setBindings(t.bindings),t.transformFeedback&&(this.transformFeedback=t.transformFeedback)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.material?.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e){if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return E.log.info(Q,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;let t=this._areBindingsLoading();if(t)return E.log.info(Q,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),this.device.type==="webgpu"?(this.updateShaderInputs(),this.material?.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}finally{e.popDebugGroup()}let n,r=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),r=this.pipeline.isErrored,r)E.log.info(Q,`>>> DRAWING ABORTED ${this.id}: ${Ti}`)(),n=!1;else{let s=this.vertexArray.getDrawValidationError();if(s)E.log.info(Q,`>>> DRAWING ABORTED ${this.id}: ${s}`)(),this._drawBlockedReason=s,n=!1;else{let o=this._getCurrentShaderLayout(),a=this._getBindings(o),c=this._getBindGroups(o,a),{indexBuffer:h}=this.vertexArray,u=h?this.indexCount??h.byteLength/(h.indexType==="uint32"?4:2):void 0;e.setPipeline(this.pipeline),e.setBindings(c,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=this.isInstanced===!0&&this.instanceCount===0?!0:e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:u,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):r?(this._needsRedraw=Ti,this._drawBlockedReason=Ti):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){this._gpuGeometry?.destroy();let t=e&&Hn(this.device,e);if(t){this.setTopology(t.topology||"triangle-list");let n=new Le(this.bufferLayout);this.bufferLayout=n.mergeBufferLayouts(t.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(t)}this._gpuGeometry=t}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){let t=new Le(this.bufferLayout),n=this._gpuGeometry?t.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e;Pe(n,this.bufferLayout,-1)||(this.bufferLayout=n,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry))}setParameters(e){Pe(e,this.parameters,2)||(this.parameters=e,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this.setNeedsRedraw("vertexCount")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new E.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(Re(n)&&!this.material?.ownsModule(t)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())),this.setNeedsRedraw("shaderInputs")}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){let t=e instanceof G?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof G?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){this._drawBlockedReason=!1;let n=t?.disableWarnings??this.props.disableWarnings;e.indices&&E.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=Qn(this.pipeline.shaderLayout,this.bufferLayout);let r=new Le(this.bufferLayout);for(let[s,o]of Object.entries(e)){let a=o instanceof G?o.buffer:o,c=r.getBufferLayout(s);if(!c){n||E.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let h=r.getAttributeNamesForBuffer(c),u=!1;for(let d of h){let l=this._attributeInfos[d];if(l){let f=this.device.type==="webgpu"?this.vertexArray.getBufferSlot(l.bufferName):l.location;if(f===null){n||E.log.warn(`Model(${this.id}): Missing vertex array slot for buffer "${l.bufferName}".`)();continue}this.vertexArray.setBuffer(f,a),o instanceof G?this._dynamicAttributeBufferSources[f]={source:o,generation:o.generation}:delete this._dynamicAttributeBufferSources[f],u=!0}}!u&&!n&&E.log.warn(`Model(${this.id}): Ignoring buffer "${a.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(let[n,r]of Object.entries(e)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,r):(t?.disableWarnings??this.props.disableWarnings)||E.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(ne(e)&&!e.isReady)return e.id;for(let e of Object.values(this.material?.bindings||{}))if(ne(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){let t={};for(let[n,r]of Object.entries(this.bindings)){let s=mo(n,r,e);s&&(t[n]=s)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){let n=e.bindings.length?(0,E.normalizeBindingsByGroup)(e,t):{0:t};if(!this.material)return n;for(let[r,s]of Object.entries(this.material.getBindingsByGroup(e))){let o=Number(r);n[o]={...n[o]||{},...s}}return n}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(let t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(let t of Object.values(this.bindings))t instanceof E.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof E.Buffer||t instanceof E.Texture||t instanceof E.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):ne(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:be(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){let t={...e.attributes};for(let[n]of Object.entries(t))!this.pipeline.shaderLayout.attributes.find(r=>r.name===n)&&n!=="positions"&&delete t[n];this.vertexCount=e.vertexCount,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(t,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,t=null;this.pipeline&&(E.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,t=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),r=null;this.source?r=n:this.fs&&(r=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:r}),this._attributeInfos=(0,E.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=E.log.level>3?0:uo;E.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,E.log.group(Q,`>>> DRAWING MODEL ${this.id}`,{collapsed:E.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=Yn(this.pipeline.shaderLayout,this.id);E.log.table(Q,e)();let t=this.shaderInputs.getDebugTable();E.log.table(Q,t)();let n=this._getAttributeDebugTable();E.log.table(Q,this._attributeInfos)(),E.log.table(Q,n)(),E.log.groupEnd(Q)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;let n=e.props.framebuffer;Kn(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[t,n]of Object.entries(this._attributeInfos)){let r=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:r?this._getBufferOrConstantValues(r,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:t}=this.vertexArray,n=t.indexType==="uint32"?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){let n=E.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof E.Buffer?new n(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;let t={};for(let[n,r]of Object.entries(e))this.material.ownsBinding(n)||(t[n]=r);return t}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){let e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(let[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if(this.device.type!=="webgpu")return;let t=e.framebuffer||e.props.framebuffer,n=e.props,r=n.colorAttachmentFormats??t?.colorAttachments?.map(o=>po(o?.texture?.format)),s=n.depthStencilAttachmentFormat===!1?void 0:n.depthStencilAttachmentFormat??go(t?.depthStencilAttachment?.texture?.format);(!Pe(this._colorAttachmentFormats,r,1)||this._depthStencilAttachmentFormat!==s)&&(this._colorAttachmentFormats=r,this._depthStencilAttachmentFormat=s,this._setPipelineNeedsUpdate("attachment formats"))}};function wi(i,e){return i.shaderLanguage!==void 0&&i.shaderLanguage!==e?!1:e==="glsl"?"assembleGLSLShaderPair"in i&&typeof i.assembleGLSLShaderPair=="function":"assembleWGSLShader"in i&&typeof i.assembleWGSLShader=="function"}function fo(i,e){return!i||Object.keys(e).length===0?i:{...i,attributes:i.attributes.map(t=>{let n=t.name.startsWith("_luma_")?t.name.slice(6):null;return n&&e[n]?{...t,name:n}:t})}}function mo(i,e,t){if(ne(e)){let n=kt(t,i,{fallbackGroup:0});return n?e.resolveTextureBinding(n):null}return e instanceof G?e.buffer:be(e)?Rt(e):e}function po(i){return i&&!or(i)?i:null}function go(i){return i&&or(i)?i:void 0}function or(i){return lo.includes(i)}function xo(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}var J=R(N(),1);var Ne=3,ke=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(e,t={}){this.device=e,this.modules=t.modules||[];let n=new X(Object.fromEntries(this.modules.map(r=>[r.name,r])));this._materialBindingNames=bo(n),this._materialModuleNames=yo(n)}createMaterial(e={}){return new De(this.device,{...e,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(e){if(this._materialBindingNames.has(e))return!0;let t=Ai(e);return t?this._materialModuleNames.has(t):!1}ownsModule(e){return this._materialModuleNames.has(e)}getBindingsByGroup(e){return Object.keys(e).length>0?{[Ne]:e}:{}}};function Ai(i){return i.endsWith("Uniforms")?i.slice(0,-8):null}function bo(i){let e=new Set;for(let t of Object.values(i.modules))for(let n of t.bindingLayout||[])n.group===Ne&&e.add(n.name);return e}function yo(i){let e=new Set;for(let t of Object.values(i.modules))t.name&&t.bindingLayout?.some(n=>n.group===Ne&&n.name===t.name)&&e.add(t.name);return e}var De=class{id;device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};_dynamicResourceGenerations={};constructor(e,t={}){this.id=t.id||O("material"),this.device=e,this.factory=t.factory||new ke(e,{modules:t.modules||t.shaderInputs?.getModules()||[]});let n=Object.fromEntries((t.shaderInputs?.getModules()||this.factory.modules).map(r=>[r.name,r]));this.shaderInputs=t.shaderInputs||new X(n),this._uniformStore=new J.UniformStore(this.device,this.shaderInputs.modules);for(let[r,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(r)&&Re(s)){let o=this._uniformStore.getManagedUniformBuffer(r);this.bindings[`${r}Uniforms`]=o}this.updateShaderInputs(),t.bindings&&this._replaceOwnedBindings(t.bindings)}destroy(){this._uniformStore.destroy()}clone(e={}){let t=this.factory.createMaterial({id:e.id,shaderInputs:e.shaderInputs,bindings:{...this.getResourceBindings(),...e.bindings}});return e.shaderInputs||t.setProps(this.shaderInputs.getUniformValues()),e.moduleProps&&t.setProps(e.moduleProps),t.updateShaderInputs(),t}ownsBinding(e){return this.factory.ownsBinding(e)}ownsModule(e){return this.factory.ownsModule(e)}setProps(e){this.shaderInputs.setProps(e)}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this._setOwnedBindings(this.shaderInputs.getBindingValues())&&(this._bindGroupCacheToken={})}getResourceBindings(){let e={};for(let[t,n]of Object.entries(this.bindings))Ai(t)||(e[t]=n);return e}getBindings(e={bindings:[]}){this._syncDynamicResourceGenerations();let t={},n=t;for(let[r,s]of Object.entries(this.bindings))if(ne(s)){let o=kt(e,r,{fallbackGroup:Ne}),a=o?s.resolveTextureBinding(o):null;a&&(n[r]=a)}else s instanceof G?n[r]=s.buffer:be(s)?n[r]=Rt(s):n[r]=s;return this._syncDynamicResourceGenerations(),t}getBindingsByGroup(e={bindings:[]}){return this.factory.getBindingsByGroup(this.getBindings(e))}getBindGroupCacheKey(e){return this._syncDynamicResourceGenerations(),e===Ne?this._bindGroupCacheToken:null}getBindingsUpdateTimestamp(){let e=0;for(let t of Object.values(this.bindings))t instanceof J.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof J.Buffer||t instanceof J.Texture||t instanceof J.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):ne(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:be(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return e}_replaceOwnedBindings(e){this._setOwnedBindings(e)&&(this._bindGroupCacheToken={})}_setOwnedBindings(e){let t=!1;for(let[n,r]of Object.entries(e))r!==void 0&&this.ownsBinding(n)&&this.bindings[n]!==r&&(this.bindings[n]=r,t=!0);return t}_syncDynamicResourceGenerations(){let e={},t=!1;for(let[n,r]of Object.entries(this.bindings)){let s=_o(r);s!==null&&(e[n]=s,this._dynamicResourceGenerations[n]!==s&&(t=!0))}Object.keys(e).length!==Object.keys(this._dynamicResourceGenerations).length&&(t=!0),this._dynamicResourceGenerations=e,t&&(this._bindGroupCacheToken={})}};function _o(i){return ne(i)?i.generation:rr(i)?.generation??null}var ar=R(N(),1),cr=R(ce(),1);var Io=35980,vo=35981,Nt=class i{device;model;transformFeedback;static defaultProps={...Y.defaultProps,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,t=i.defaultProps){if(!i.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.model=new Y(this.device,{id:t.id||"buffer-transform-model",fs:t.fs||(0,cr.getPassthroughFS)(),topology:t.topology||"point-list",varyings:t.outputs||t.varyings,...t,bufferMode:t.bufferMode||(t.feedbackBufferMode==="interleaved"?Io:vo)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:t.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){e?.inputBuffers&&this.model.setAttributes(e.inputBuffers),e?.outputBuffers&&this.transformFeedback.setBuffers(e.outputBuffers);let t=this.device.beginRenderPass({discard:!0,...e});this.model.draw(t),t.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof ar.Buffer)return t.readAsync();let{buffer:n,byteOffset:r=0,byteLength:s=n.byteLength}=t;return n.readAsync(r,s)}};var hr=R(ce(),1);var Mo="transform_output",Dt=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(e,t){this.device=e,this.sampler=e.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new Y(this.device,{id:t.id||O("texture-transform-model"),fs:t.fs||(0,hr.getPassthroughFS)({input:t.targetTextureVarying,inputChannels:t.targetTextureChannels,output:Mo}),vertexCount:t.vertexCount,...t}),this._initialize(t),Object.seal(this)}destroy(){this.model.destroy();for(let e of this.bindings)e.framebuffer?.destroy()}delete(){this.destroy()}run(e){let{framebuffer:t}=this.bindings[this.currentIndex],n=this.device.beginRenderPass({framebuffer:t,...e});this.model.draw(n),n.end(),this.device.submit()}getTargetTexture(){let{targetTexture:e}=this.bindings[this.currentIndex];return e}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(e){this._updateBindings(e)}_updateBindings(e){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],e)}_updateBinding(e,{sourceBuffers:t,sourceTextures:n,targetTexture:r}){if(e||(e={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(e.sourceTextures,n),Object.assign(e.sourceBuffers,t),r){e.targetTexture=r;let{width:s,height:o}=r;e.framebuffer&&e.framebuffer.destroy(),e.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:s,height:o,colorAttachments:[r]}),e.framebuffer.resize({width:s,height:o})}return e}_setSourceTextureParameters(){let e=this.currentIndex,{sourceTextures:t}=this.bindings[e];for(let n in t)t[n].sampler=this.sampler}};var To=`struct VertexInputs {
8
8
  @location(0) clipSpacePositions: vec2<f32>,
9
9
  @location(1) texCoords: vec2<f32>,
10
10
  @location(2) coordinates: vec2<f32>
@@ -26,7 +26,7 @@ fn vertexMain(inputs: VertexInputs) -> FragmentInputs {
26
26
  outputs.uv = inputs.texCoords;
27
27
  return outputs;
28
28
  }
29
- `,Rs=`#version 300 es
29
+ `,wo=`#version 300 es
30
30
  in vec2 clipSpacePositions;
31
31
  in vec2 texCoords;
32
32
  in vec2 coordinates;
@@ -41,8 +41,8 @@ void main(void) {
41
41
  coordinate = coordinates;
42
42
  uv = texCoords;
43
43
  }
44
- `,bn=[-1,-1,1,-1,-1,1,1,1],he=class extends Y{constructor(e,t){let n=bn.map(r=>r===-1?0:r);t.source&&(t={...t,source:`${ks}
45
- ${t.source}`}),super(e,{id:t.id||S("clip-space"),...t,vs:Rs,vertexCount:4,geometry:new G({topology:"triangle-strip",vertexCount:4,attributes:{clipSpacePositions:{size:2,value:new Float32Array(bn)},texCoords:{size:2,value:new Float32Array(n)},coordinates:{size:2,value:new Float32Array(n)}}})})}};var N=L(R(),1);var We=L(R(),1);var ui={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function He(i){return i?Array.isArray(i)?i[0]??null:i:null}function yn(i){let{dimension:e,data:t}=i;if(!t)return null;switch(e){case"1d":{let n=He(t);if(!n)return null;let{width:r}=Ye(n);return{width:r,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=He(t);return n?Ye(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=He(t[0]);return n?Ye(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let r=t[n],s=He(r);return s?Ye(s):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],r=Object.keys(n)[0]??null;if(!r)return null;let s=He(n[r]);return s?Ye(s):null}default:return null}}function Ye(i){if((0,We.isExternalImage)(i))return(0,We.getExternalImageSize)(i);if(typeof i=="object"&&"width"in i&&"height"in i)return{width:i.width,height:i.height};throw new Error("Unsupported mip-level data")}function Ns(i){return typeof i=="object"&&i!==null&&"data"in i&&"width"in i&&"height"in i}function Ds(i){return ArrayBuffer.isView(i)}function di(i){let{textureFormat:e,format:t}=i;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function _n(i){let e=ui[i];if(e===void 0)throw new Error(`Invalid cube face: ${i}`);return e}function Bs(i,e){return 6*i+_n(e)}function li(i){throw new Error("setTexture1DData not supported in WebGL.")}function Fs(i){return Array.isArray(i)?i:[i]}function be(i,e,t,n){let r=Fs(e),s=i,o=[];for(let a=0;a<r.length;a++){let c=r[a];if((0,We.isExternalImage)(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(Ns(c))o.push({type:"texture-data",data:c,textureFormat:di(c),z:s,mipLevel:a});else if(Ds(c)&&t)o.push({type:"texture-data",data:{data:c,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function fi(i){let e=[];for(let t=0;t<i.length;t++)e.push(...be(t,i[t]));return e}function mi(i){let e=[];for(let t=0;t<i.length;t++)e.push(...be(t,i[t]));return e}function pi(i){let e=[];for(let[t,n]of Object.entries(i)){let r=_n(t);e.push(...be(r,n))}return e}function gi(i){let e=[];return i.forEach((t,n)=>{for(let[r,s]of Object.entries(t)){let o=Bs(n,r);e.push(...be(o,s))}}),e}var bi=class{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=S("dynamic-texture"),r=t;this.props={...bi.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(r)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?zs({...t,width:e.width,height:e.height,format:e.format}):[],r="format"in e&&e.format!==void 0,s="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let f=yn(t);return f||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=js(this.device,n,a,{format:r?e.format:void 0}),u=c.format??this.props.format,h={...this.props,...a,format:u,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(u)&&!s&&(h.usage=N.Texture.SAMPLE|N.Texture.COPY_DST);let l=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(u);if(this.device.type==="webgpu"&&l){let f=this.props.dimension==="3d"?N.Texture.SAMPLE|N.Texture.STORAGE|N.Texture.COPY_DST|N.Texture.COPY_SRC:N.Texture.SAMPLE|N.Texture.RENDER|N.Texture.COPY_DST|N.Texture.COPY_SRC;h.usage|=f}let d=this.device.getMipLevelCount(h.width,h.height),m=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?d:Math.max(1,Math.min(d,this.props.mipLevels??1)),p={...h,mipLevels:m};this._texture=this.device.createTexture(p),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!l&&N.log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),l&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),N.log.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):N.log.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof N.Sampler?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=this.device.createBuffer({byteLength:s.byteLength,usage:N.Buffer.COPY_DST|N.Buffer.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:r},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),N.log.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=ui[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=li(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=be(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=fi(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=mi(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=pi(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=gi(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:r}=t;switch(t.type){case"external-image":let{image:s,flipY:o}=t;this.texture.copyExternalImage({image:s,z:n,mipLevel:r,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=t;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${r} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:r});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await xi(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&N.log.warn(`${this} already destroyed`)}_checkReady(){this.isReady||N.log.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}},K=bi;q(K,"defaultProps",{...N.Texture.defaultProps,dimension:"2d",data:null,mipmaps:!1});function zs(i){if(!i.data)return[];let e=i.width&&i.height?{width:i.width,height:i.height}:void 0,t="format"in i?i.format:void 0;switch(i.dimension){case"1d":return li(i.data);case"2d":return be(0,i.data,e,t);case"3d":return fi(i.data);case"2d-array":return mi(i.data);case"cube":return pi(i.data);case"cube-array":return gi(i.data);default:throw new Error(`Unhandled dimension ${i.dimension}`)}}function js(i,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let r=new Map;for(let h of e){let l=r.get(h.z)??[];l.push(h),r.set(h.z,l)}let s=e.some(h=>h.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[h,l]of r){let d=[...l].sort((M,g)=>M.mipLevel-g.mipLevel),m=d[0];if(!m||m.mipLevel!==0)throw new Error(`DynamicTexture: slice ${h} is missing mip level 0`);let p=Mn(i,m);if(p.width!==t.width||p.height!==t.height)throw new Error(`DynamicTexture: slice ${h} base level dimensions ${p.width}x${p.height} do not match expected ${t.width}x${t.height}`);let f=In(m);if(f){if(o&&o!==f)throw new Error(`DynamicTexture: slice ${h} base level format "${f}" does not match texture format "${o}"`);o=f}let x=o&&i.isTextureFormatCompressed(o)?Gs(i,p.width,p.height,o):i.getMipLevelCount(p.width,p.height),y=0;for(let M=0;M<d.length;M++){let g=d[M];if(!g||g.mipLevel!==M||M>=x)break;let b=Mn(i,g),_=Math.max(1,p.width>>M),I=Math.max(1,p.height>>M);if(b.width!==_||b.height!==I)break;let A=In(g);if(A&&(o||(o=A),A!==o))break;y++,c.push(g)}a=Math.min(a,y)}let u=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(h=>h.mipLevel<u),mipLevels:u,format:o,hasExplicitMipChain:s}}function In(i){if(i.type==="texture-data")return i.textureFormat??di(i.data)}function Mn(i,e){switch(e.type){case"external-image":return i.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function Gs(i,e,t,n){let{blockWidth:r=1,blockHeight:s=1}=i.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,e>>a),u=Math.max(1,t>>a);if(c<r||u<s)break;o++}return o}async function xi(i){if(i=await i,Array.isArray(i))return await Promise.all(i.map(xi));if(i&&typeof i=="object"&&i.constructor===Object){let e=i,t=await Promise.all(Object.values(e).map(xi)),n=Object.keys(e),r={};for(let s=0;s<n.length;s++)r[n[s]]=t[s];return r}return i}var $s={name:"background",uniformTypes:{scale:"vec2<f32>",flipY:"i32"}},Us=`@group(0) @binding(auto) var backgroundTexture: texture_2d<f32>;
44
+ `,ur=[-1,-1,1,-1,-1,1,1,1],ue=class extends Y{constructor(e,t){let n=ur.map(r=>r===-1?0:r);t.source&&(t={...t,source:`${To}
45
+ ${t.source}`}),super(e,{id:t.id||O("clip-space"),...t,vs:wo,vertexCount:4,geometry:new z({topology:"triangle-strip",vertexCount:4,attributes:{clipSpacePositions:{size:2,value:new Float32Array(ur)},texCoords:{size:2,value:new Float32Array(n)},coordinates:{size:2,value:new Float32Array(n)}}})})}};var D=R(N(),1);var Ke=R(N(),1);var Si={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function We(i){return i?Array.isArray(i)?i[0]??null:i:null}function lr(i){let{dimension:e,data:t}=i;if(!t)return null;switch(e){case"1d":{let n=We(t);if(!n)return null;let{width:r}=qe(n);return{width:r,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=We(t);return n?qe(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=We(t[0]);return n?qe(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let r=t[n],s=We(r);return s?qe(s):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],r=Object.keys(n)[0]??null;if(!r)return null;let s=We(n[r]);return s?qe(s):null}default:return null}}function qe(i){if((0,Ke.isExternalImage)(i))return(0,Ke.getExternalImageSize)(i);if(typeof i=="object"&&"width"in i&&"height"in i)return{width:i.width,height:i.height};throw new Error("Unsupported mip-level data")}function Ao(i){return typeof i=="object"&&i!==null&&"data"in i&&"width"in i&&"height"in i}function So(i){return ArrayBuffer.isView(i)}function Ei(i){let{textureFormat:e,format:t}=i;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function dr(i){let e=Si[i];if(e===void 0)throw new Error(`Invalid cube face: ${i}`);return e}function Eo(i,e){return 6*i+dr(e)}function Ci(i){throw new Error("setTexture1DData not supported in WebGL.")}function Co(i){return Array.isArray(i)?i:[i]}function _e(i,e,t,n){let r=Co(e),s=i,o=[];for(let a=0;a<r.length;a++){let c=r[a];if((0,Ke.isExternalImage)(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(Ao(c))o.push({type:"texture-data",data:c,textureFormat:Ei(c),z:s,mipLevel:a});else if(So(c)&&t)o.push({type:"texture-data",data:{data:c,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function Pi(i){let e=[];for(let t=0;t<i.length;t++)e.push(..._e(t,i[t]));return e}function Li(i){let e=[];for(let t=0;t<i.length;t++)e.push(..._e(t,i[t]));return e}function Oi(i){let e=[];for(let[t,n]of Object.entries(i)){let r=dr(t);e.push(..._e(r,n))}return e}function Ri(i){let e=[];return i.forEach((t,n)=>{for(let[r,s]of Object.entries(t)){let o=Eo(n,r);e.push(..._e(o,s))}}),e}var K=class i{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=O("dynamic-texture"),r=t;this.props={...i.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(r)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?Po({...t,width:e.width,height:e.height,format:e.format}):[],r="format"in e&&e.format!==void 0,s="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let p=lr(t);return p||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=Lo(this.device,n,a,{format:r?e.format:void 0}),h=c.format??this.props.format,u={...this.props,...a,format:h,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(h)&&!s&&(u.usage=D.Texture.SAMPLE|D.Texture.COPY_DST);let d=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(h);if(this.device.type==="webgpu"&&d){let p=this.props.dimension==="3d"?D.Texture.SAMPLE|D.Texture.STORAGE|D.Texture.COPY_DST|D.Texture.COPY_SRC:D.Texture.SAMPLE|D.Texture.RENDER|D.Texture.COPY_DST|D.Texture.COPY_SRC;u.usage|=p}let l=this.device.getMipLevelCount(u.width,u.height),f=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?l:Math.max(1,Math.min(l,this.props.mipLevels??1)),m={...u,mipLevels:f};this._texture=this.device.createTexture(m),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!d&&D.log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),d&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),D.log.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):D.log.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof D.Sampler?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=this.device.createBuffer({byteLength:s.byteLength,usage:D.Buffer.COPY_DST|D.Buffer.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:r},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),D.log.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Si[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=Ci(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=_e(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=Pi(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=Li(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=Oi(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=Ri(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:r}=t;switch(t.type){case"external-image":let{image:s,flipY:o}=t;this.texture.copyExternalImage({image:s,z:n,mipLevel:r,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=t;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${r} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:r});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await ki(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&D.log.warn(`${this} already destroyed`)}_checkReady(){this.isReady||D.log.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...D.Texture.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function Po(i){if(!i.data)return[];let e=i.width&&i.height?{width:i.width,height:i.height}:void 0,t="format"in i?i.format:void 0;switch(i.dimension){case"1d":return Ci(i.data);case"2d":return _e(0,i.data,e,t);case"3d":return Pi(i.data);case"2d-array":return Li(i.data);case"cube":return Oi(i.data);case"cube-array":return Ri(i.data);default:throw new Error(`Unhandled dimension ${i.dimension}`)}}function Lo(i,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let r=new Map;for(let u of e){let d=r.get(u.z)??[];d.push(u),r.set(u.z,d)}let s=e.some(u=>u.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[u,d]of r){let l=[...d].sort((M,y)=>M.mipLevel-y.mipLevel),f=l[0];if(!f||f.mipLevel!==0)throw new Error(`DynamicTexture: slice ${u} is missing mip level 0`);let m=mr(i,f);if(m.width!==t.width||m.height!==t.height)throw new Error(`DynamicTexture: slice ${u} base level dimensions ${m.width}x${m.height} do not match expected ${t.width}x${t.height}`);let p=fr(f);if(p){if(o&&o!==p)throw new Error(`DynamicTexture: slice ${u} base level format "${p}" does not match texture format "${o}"`);o=p}let b=o&&i.isTextureFormatCompressed(o)?Oo(i,m.width,m.height,o):i.getMipLevelCount(m.width,m.height),_=0;for(let M=0;M<l.length;M++){let y=l[M];if(!y||y.mipLevel!==M||M>=b)break;let I=mr(i,y),g=Math.max(1,m.width>>M),x=Math.max(1,m.height>>M);if(I.width!==g||I.height!==x)break;let v=fr(y);if(v&&(o||(o=v),v!==o))break;_++,c.push(y)}a=Math.min(a,_)}let h=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(u=>u.mipLevel<h),mipLevels:h,format:o,hasExplicitMipChain:s}}function fr(i){if(i.type==="texture-data")return i.textureFormat??Ei(i.data)}function mr(i,e){switch(e.type){case"external-image":return i.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function Oo(i,e,t,n){let{blockWidth:r=1,blockHeight:s=1}=i.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,e>>a),h=Math.max(1,t>>a);if(c<r||h<s)break;o++}return o}async function ki(i){if(i=await i,Array.isArray(i))return await Promise.all(i.map(ki));if(i&&typeof i=="object"&&i.constructor===Object){let e=i,t=await Promise.all(Object.values(e).map(ki)),n=Object.keys(e),r={};for(let s=0;s<n.length;s++)r[n[s]]=t[s];return r}return i}var Ro={name:"background",uniformTypes:{scale:"vec2<f32>",flipY:"i32"}},ko=`@group(0) @binding(auto) var backgroundTexture: texture_2d<f32>;
46
46
  @group(0) @binding(auto) var backgroundTextureSampler: sampler;
47
47
  struct backgroundUniforms {
48
48
  scale: vec2<f32>,
@@ -64,7 +64,7 @@ fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4<f32> {
64
64
  let position: vec2<f32> = billboardTexture_getTextureUV(inputs.uv);
65
65
  return textureSample(backgroundTexture, backgroundTextureSampler, position);
66
66
  }
67
- `,Vs=`#version 300 es
67
+ `,No=`#version 300 es
68
68
  precision highp float;
69
69
 
70
70
  uniform sampler2D backgroundTexture;
@@ -89,7 +89,7 @@ void main(void) {
89
89
  vec2 position = billboardTexture_getTextureUV(coordinate);
90
90
  fragColor = texture(backgroundTexture, position);
91
91
  }
92
- `,Le=class extends he{backgroundTexture=null;flipY=!1;constructor(e,t){if(super(e,{...t,id:t.id||"background-texture-model",source:Us,fs:Vs,modules:[...t.modules||[],$s],parameters:{depthWriteEnabled:!1,...t.parameters||{},...t.blend?{blend:!0,blendColorOperation:"add",blendAlphaOperation:"add",blendColorSrcFactor:"one-minus-dst-alpha",blendColorDstFactor:"one",blendAlphaSrcFactor:"one-minus-dst-alpha",blendAlphaDstFactor:"one"}:{}}}),!t.backgroundTexture)throw new Error("BackgroundTextureModel requires a backgroundTexture prop");this.setProps(t)}setProps(e){let{backgroundTexture:t}=e;if(e.flipY!==void 0&&(this.flipY=e.flipY,this.backgroundTexture&&this.updateScale(this.backgroundTexture)),t)if(this.setBindings({backgroundTexture:t}),t.isReady){let n=t instanceof K?t.texture:t;this.backgroundTexture=n,this.updateScale(n)}else t.ready.then(n=>{this.backgroundTexture=n,this.updateScale(n)})}predraw(e){super.predraw(e)}updateScale(e){if(!e){this.shaderInputs.setProps({background:{scale:[1,1],flipY:0}});return}let[t,n]=this.device.getCanvasContext().getDrawingBufferSize(),r=e.width,s=e.height,o=t/n,a=r/s,c=1,u=1;o>a?u=o/a:c=a/o,this.shaderInputs.setProps({background:{scale:[c,u],flipY:this.flipY?1:0}})}};var Oe=class extends G{constructor(e={}){let{id:t=S("sphere-geometry")}=e,{indices:n,attributes:r}=Xs(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Xs(i){let{nlat:e=10,nlong:t=10}=i,s=Math.PI-0,o=0,c=2*Math.PI-o,u=(e+1)*(t+1),h=(y,M,g,b,_)=>i.radius||1,l=new Float32Array(u*3),d=new Float32Array(u*3),m=new Float32Array(u*2),p=u>65535?Uint32Array:Uint16Array,f=new p(e*t*6);for(let y=0;y<=e;y++)for(let M=0;M<=t;M++){let g=M/t,b=y/e,_=M+y*(t+1),I=_*2,A=_*3,O=c*g,C=s*b,k=Math.sin(O),v=Math.cos(O),E=Math.sin(C),P=Math.cos(C),w=v*E,$=P,te=k*E,Z=h(w,$,te,g,b);l[A+0]=Z*w,l[A+1]=Z*$,l[A+2]=Z*te,d[A+0]=w,d[A+1]=$,d[A+2]=te,m[I+0]=g,m[I+1]=1-b}let x=t+1;for(let y=0;y<t;y++)for(let M=0;M<e;M++){let g=(y*e+M)*6;f[g+0]=M*x+y,f[g+1]=M*x+y+1,f[g+2]=(M+1)*x+y,f[g+3]=(M+1)*x+y,f[g+4]=M*x+y+1,f[g+5]=(M+1)*x+y+1}return{indices:{size:1,value:f},attributes:{POSITION:{size:3,value:l},NORMAL:{size:3,value:d},TEXCOORD_0:{size:2,value:m}}}}var ph=1/Math.PI*180,gh=1/180*Math.PI,Hs={EPSILON:1e-12,debug:!1,precision:4,printTypes:!1,printDegrees:!1,printRowMajor:!0,_cartographicRadians:!1};globalThis.mathgl=globalThis.mathgl||{config:{...Hs}};var U=globalThis.mathgl.config;function vn(i,{precision:e=U.precision}={}){return i=Ys(i),`${parseFloat(i.toPrecision(e))}`}function ke(i){return Array.isArray(i)||ArrayBuffer.isView(i)&&!(i instanceof DataView)}function yi(i,e,t){let n=U.EPSILON;t&&(U.EPSILON=t);try{if(i===e)return!0;if(ke(i)&&ke(e)){if(i.length!==e.length)return!1;for(let r=0;r<i.length;++r)if(!yi(i[r],e[r]))return!1;return!0}return i&&i.equals?i.equals(e):e&&e.equals?e.equals(i):typeof i=="number"&&typeof e=="number"?Math.abs(i-e)<=U.EPSILON*Math.max(1,Math.abs(i),Math.abs(e)):!1}finally{U.EPSILON=n}}function Ys(i){return Math.round(i/U.EPSILON)*U.EPSILON}var Re=class extends Array{clone(){return new this.constructor().copy(this)}fromArray(e,t=0){for(let n=0;n<this.ELEMENTS;++n)this[n]=e[n+t];return this.check()}toArray(e=[],t=0){for(let n=0;n<this.ELEMENTS;++n)e[t+n]=this[n];return e}toObject(e){return e}from(e){return Array.isArray(e)?this.copy(e):this.fromObject(e)}to(e){return e===this?this:ke(e)?this.toArray(e):this.toObject(e)}toTarget(e){return e?this.to(e):this}toFloat32Array(){return new Float32Array(this)}toString(){return this.formatString(U)}formatString(e){let t="";for(let n=0;n<this.ELEMENTS;++n)t+=(n>0?", ":"")+vn(this[n],e);return`${e.printTypes?this.constructor.name:""}[${t}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(!yi(this[t],e[t]))return!1;return!0}exactEquals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(this[t]!==e[t])return!1;return!0}negate(){for(let e=0;e<this.ELEMENTS;++e)this[e]=-this[e];return this.check()}lerp(e,t,n){if(n===void 0)return this.lerp(this,e,t);for(let r=0;r<this.ELEMENTS;++r){let s=e[r],o=typeof t=="number"?t:t[r];this[r]=s+n*(o-s)}return this.check()}min(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.min(e[t],this[t]);return this.check()}max(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.max(e[t],this[t]);return this.check()}clamp(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e[n]),t[n]);return this.check()}add(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]+=t[n];return this.check()}subtract(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]-=t[n];return this.check()}scale(e){if(typeof e=="number")for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;else for(let t=0;t<this.ELEMENTS&&t<e.length;++t)this[t]*=e[t];return this.check()}multiplyByScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}check(){if(U.debug&&!this.validate())throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);return this}validate(){let e=this.length===this.ELEMENTS;for(let t=0;t<this.ELEMENTS;++t)e=e&&Number.isFinite(this[t]);return e}sub(e){return this.subtract(e)}setScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=e;return this.check()}addScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]+=e;return this.check()}subScalar(e){return this.addScalar(-e)}multiplyScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}divideScalar(e){return this.multiplyByScalar(1/e)}clampScalar(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e),t);return this.check()}get elements(){return this}};function Ws(i,e){if(i.length!==e)return!1;for(let t=0;t<i.length;++t)if(!Number.isFinite(i[t]))return!1;return!0}function X(i){if(!Number.isFinite(i))throw new Error(`Invalid number ${JSON.stringify(i)}`);return i}function Tt(i,e,t=""){if(U.debug&&!Ws(i,e))throw new Error(`math.gl: ${t} some fields set to invalid numbers'`);return i}function _i(i,e){if(!i)throw new Error(`math.gl assertion ${e}`)}var wt=class extends Re{get x(){return this[0]}set x(e){this[0]=X(e)}get y(){return this[1]}set y(e){this[1]=X(e)}len(){return Math.sqrt(this.lengthSquared())}magnitude(){return this.len()}lengthSquared(){let e=0;for(let t=0;t<this.ELEMENTS;++t)e+=this[t]*this[t];return e}magnitudeSquared(){return this.lengthSquared()}distance(e){return Math.sqrt(this.distanceSquared(e))}distanceSquared(e){let t=0;for(let n=0;n<this.ELEMENTS;++n){let r=this[n]-e[n];t+=r*r}return X(t)}dot(e){let t=0;for(let n=0;n<this.ELEMENTS;++n)t+=this[n]*e[n];return X(t)}normalize(){let e=this.magnitude();if(e!==0)for(let t=0;t<this.ELEMENTS;++t)this[t]/=e;return this.check()}multiply(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]*=t[n];return this.check()}divide(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]/=t[n];return this.check()}lengthSq(){return this.lengthSquared()}distanceTo(e){return this.distance(e)}distanceToSquared(e){return this.distanceSquared(e)}getComponent(e){return _i(e>=0&&e<this.ELEMENTS,"index is out of range"),X(this[e])}setComponent(e,t){return _i(e>=0&&e<this.ELEMENTS,"index is out of range"),this[e]=t,this.check()}addVectors(e,t){return this.copy(e).add(t)}subVectors(e,t){return this.copy(e).subtract(t)}multiplyVectors(e,t){return this.copy(e).multiply(t)}addScaledVector(e,t){return this.add(new this.constructor(e).multiplyScalar(t))}};var ne=typeof Float32Array<"u"?Float32Array:Array;var Eh=Math.PI/180;function qs(){let i=new ne(2);return ne!=Float32Array&&(i[0]=0,i[1]=0),i}function An(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[4]*r+t[12],i[1]=t[1]*n+t[5]*r+t[13],i}var Sh=function(){let i=qs();return function(e,t,n,r,s,o){let a,c;for(t||(t=2),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],s(i,i,o),e[a]=i[0],e[a+1]=i[1];return e}}();function En(i,e,t){let n=e[0],r=e[1],s=t[3]*n+t[7]*r||1;return i[0]=(t[0]*n+t[4]*r)/s,i[1]=(t[1]*n+t[5]*r)/s,i}function At(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s||1;return i[0]=(t[0]*n+t[4]*r+t[8]*s)/o,i[1]=(t[1]*n+t[5]*r+t[9]*s)/o,i[2]=(t[2]*n+t[6]*r+t[10]*s)/o,i}function Sn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[2]*r,i[1]=t[1]*n+t[3]*r,i[2]=e[2],i}function Ks(){let i=new ne(3);return ne!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0),i}function Zs(i,e){return i[0]*e[0]+i[1]*e[1]+i[2]*e[2]}function Cn(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[0],a=t[1],c=t[2];return i[0]=r*c-s*a,i[1]=s*o-n*c,i[2]=n*a-r*o,i}function Et(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s+t[15];return o=o||1,i[0]=(t[0]*n+t[4]*r+t[8]*s+t[12])/o,i[1]=(t[1]*n+t[5]*r+t[9]*s+t[13])/o,i[2]=(t[2]*n+t[6]*r+t[10]*s+t[14])/o,i}function Pn(i,e,t){let n=e[0],r=e[1],s=e[2];return i[0]=n*t[0]+r*t[3]+s*t[6],i[1]=n*t[1]+r*t[4]+s*t[7],i[2]=n*t[2]+r*t[5]+s*t[8],i}function Ln(i,e,t){let n=t[0],r=t[1],s=t[2],o=t[3],a=e[0],c=e[1],u=e[2],h=r*u-s*c,l=s*a-n*u,d=n*c-r*a,m=r*d-s*l,p=s*h-n*d,f=n*l-r*h,x=o*2;return h*=x,l*=x,d*=x,m*=2,p*=2,f*=2,i[0]=a+h+m,i[1]=c+l+p,i[2]=u+d+f,i}function On(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0],s[1]=r[1]*Math.cos(n)-r[2]*Math.sin(n),s[2]=r[1]*Math.sin(n)+r[2]*Math.cos(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function kn(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[2]*Math.sin(n)+r[0]*Math.cos(n),s[1]=r[1],s[2]=r[2]*Math.cos(n)-r[0]*Math.sin(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Rn(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0]*Math.cos(n)-r[1]*Math.sin(n),s[1]=r[0]*Math.sin(n)+r[1]*Math.cos(n),s[2]=r[2],i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Nn(i,e){let t=i[0],n=i[1],r=i[2],s=e[0],o=e[1],a=e[2],c=Math.sqrt((t*t+n*n+r*r)*(s*s+o*o+a*a)),u=c&&Zs(i,e)/c;return Math.acos(Math.min(Math.max(u,-1),1))}var Lh=function(){let i=Ks();return function(e,t,n,r,s,o){let a,c;for(t||(t=3),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],i[2]=e[a+2],s(i,i,o),e[a]=i[0],e[a+1]=i[1],e[a+2]=i[2];return e}}();var Mi=[0,0,0],St,H=class extends wt{static get ZERO(){return St||(St=new H(0,0,0),Object.freeze(St)),St}constructor(e=0,t=0,n=0){super(-0,-0,-0),arguments.length===1&&ke(e)?this.copy(e):(U.debug&&(X(e),X(t),X(n)),this[0]=e,this[1]=t,this[2]=n)}set(e,t,n){return this[0]=e,this[1]=t,this[2]=n,this.check()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this.check()}fromObject(e){return U.debug&&(X(e.x),X(e.y),X(e.z)),this[0]=e.x,this[1]=e.y,this[2]=e.z,this.check()}toObject(e){return e.x=this[0],e.y=this[1],e.z=this[2],e}get ELEMENTS(){return 3}get z(){return this[2]}set z(e){this[2]=X(e)}angle(e){return Nn(this,e)}cross(e){return Cn(this,this,e),this.check()}rotateX({radians:e,origin:t=Mi}){return On(this,this,t,e),this.check()}rotateY({radians:e,origin:t=Mi}){return kn(this,this,t,e),this.check()}rotateZ({radians:e,origin:t=Mi}){return Rn(this,this,t,e),this.check()}transform(e){return this.transformAsPoint(e)}transformAsPoint(e){return Et(this,this,e),this.check()}transformAsVector(e){return At(this,this,e),this.check()}transformByMatrix3(e){return Pn(this,this,e),this.check()}transformByMatrix2(e){return Sn(this,this,e),this.check()}transformByQuaternion(e){return Ln(this,this,e),this.check()}};var Ct=class extends Re{toString(){let e="[";if(U.printRowMajor){e+="row-major:";for(let t=0;t<this.RANK;++t)for(let n=0;n<this.RANK;++n)e+=` ${this[n*this.RANK+t]}`}else{e+="column-major:";for(let t=0;t<this.ELEMENTS;++t)e+=` ${this[t]}`}return e+="]",e}getElementIndex(e,t){return t*this.RANK+e}getElement(e,t){return this[t*this.RANK+e]}setElement(e,t,n){return this[t*this.RANK+e]=X(n),this}getColumn(e,t=new Array(this.RANK).fill(-0)){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)t[r]=this[n+r];return t}setColumn(e,t){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)this[n+r]=t[r];return this}};function Js(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function Dn(i,e){if(i===e){let t=e[1],n=e[2],r=e[3],s=e[6],o=e[7],a=e[11];i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=t,i[6]=e[9],i[7]=e[13],i[8]=n,i[9]=s,i[11]=e[14],i[12]=r,i[13]=o,i[14]=a}else i[0]=e[0],i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=e[1],i[5]=e[5],i[6]=e[9],i[7]=e[13],i[8]=e[2],i[9]=e[6],i[10]=e[10],i[11]=e[14],i[12]=e[3],i[13]=e[7],i[14]=e[11],i[15]=e[15];return i}function Bn(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=e[4],a=e[5],c=e[6],u=e[7],h=e[8],l=e[9],d=e[10],m=e[11],p=e[12],f=e[13],x=e[14],y=e[15],M=t*a-n*o,g=t*c-r*o,b=t*u-s*o,_=n*c-r*a,I=n*u-s*a,A=r*u-s*c,O=h*f-l*p,C=h*x-d*p,k=h*y-m*p,v=l*x-d*f,E=l*y-m*f,P=d*y-m*x,w=M*P-g*E+b*v+_*k-I*C+A*O;return w?(w=1/w,i[0]=(a*P-c*E+u*v)*w,i[1]=(r*E-n*P-s*v)*w,i[2]=(f*A-x*I+y*_)*w,i[3]=(d*I-l*A-m*_)*w,i[4]=(c*k-o*P-u*C)*w,i[5]=(t*P-r*k+s*C)*w,i[6]=(x*b-p*A-y*g)*w,i[7]=(h*A-d*b+m*g)*w,i[8]=(o*E-a*k+u*O)*w,i[9]=(n*k-t*E-s*O)*w,i[10]=(p*I-f*b+y*M)*w,i[11]=(l*b-h*I-m*M)*w,i[12]=(a*C-o*v-c*O)*w,i[13]=(t*v-n*C+r*O)*w,i[14]=(f*g-p*_-x*M)*w,i[15]=(h*_-l*g+d*M)*w,i):null}function Fn(i){let e=i[0],t=i[1],n=i[2],r=i[3],s=i[4],o=i[5],a=i[6],c=i[7],u=i[8],h=i[9],l=i[10],d=i[11],m=i[12],p=i[13],f=i[14],x=i[15],y=e*o-t*s,M=e*a-n*s,g=t*a-n*o,b=u*p-h*m,_=u*f-l*m,I=h*f-l*p,A=e*I-t*_+n*b,O=s*I-o*_+a*b,C=u*g-h*M+l*y,k=m*g-p*M+f*y;return c*A-r*O+x*C-d*k}function vi(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3],a=e[4],c=e[5],u=e[6],h=e[7],l=e[8],d=e[9],m=e[10],p=e[11],f=e[12],x=e[13],y=e[14],M=e[15],g=t[0],b=t[1],_=t[2],I=t[3];return i[0]=g*n+b*a+_*l+I*f,i[1]=g*r+b*c+_*d+I*x,i[2]=g*s+b*u+_*m+I*y,i[3]=g*o+b*h+_*p+I*M,g=t[4],b=t[5],_=t[6],I=t[7],i[4]=g*n+b*a+_*l+I*f,i[5]=g*r+b*c+_*d+I*x,i[6]=g*s+b*u+_*m+I*y,i[7]=g*o+b*h+_*p+I*M,g=t[8],b=t[9],_=t[10],I=t[11],i[8]=g*n+b*a+_*l+I*f,i[9]=g*r+b*c+_*d+I*x,i[10]=g*s+b*u+_*m+I*y,i[11]=g*o+b*h+_*p+I*M,g=t[12],b=t[13],_=t[14],I=t[15],i[12]=g*n+b*a+_*l+I*f,i[13]=g*r+b*c+_*d+I*x,i[14]=g*s+b*u+_*m+I*y,i[15]=g*o+b*h+_*p+I*M,i}function zn(i,e,t){let n=t[0],r=t[1],s=t[2],o,a,c,u,h,l,d,m,p,f,x,y;return e===i?(i[12]=e[0]*n+e[4]*r+e[8]*s+e[12],i[13]=e[1]*n+e[5]*r+e[9]*s+e[13],i[14]=e[2]*n+e[6]*r+e[10]*s+e[14],i[15]=e[3]*n+e[7]*r+e[11]*s+e[15]):(o=e[0],a=e[1],c=e[2],u=e[3],h=e[4],l=e[5],d=e[6],m=e[7],p=e[8],f=e[9],x=e[10],y=e[11],i[0]=o,i[1]=a,i[2]=c,i[3]=u,i[4]=h,i[5]=l,i[6]=d,i[7]=m,i[8]=p,i[9]=f,i[10]=x,i[11]=y,i[12]=o*n+h*r+p*s+e[12],i[13]=a*n+l*r+f*s+e[13],i[14]=c*n+d*r+x*s+e[14],i[15]=u*n+m*r+y*s+e[15]),i}function jn(i,e,t){let n=t[0],r=t[1],s=t[2];return i[0]=e[0]*n,i[1]=e[1]*n,i[2]=e[2]*n,i[3]=e[3]*n,i[4]=e[4]*r,i[5]=e[5]*r,i[6]=e[6]*r,i[7]=e[7]*r,i[8]=e[8]*s,i[9]=e[9]*s,i[10]=e[10]*s,i[11]=e[11]*s,i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],i}function Gn(i,e,t,n){let r=n[0],s=n[1],o=n[2],a=Math.sqrt(r*r+s*s+o*o),c,u,h,l,d,m,p,f,x,y,M,g,b,_,I,A,O,C,k,v,E,P,w,$;return a<1e-6?null:(a=1/a,r*=a,s*=a,o*=a,u=Math.sin(t),c=Math.cos(t),h=1-c,l=e[0],d=e[1],m=e[2],p=e[3],f=e[4],x=e[5],y=e[6],M=e[7],g=e[8],b=e[9],_=e[10],I=e[11],A=r*r*h+c,O=s*r*h+o*u,C=o*r*h-s*u,k=r*s*h-o*u,v=s*s*h+c,E=o*s*h+r*u,P=r*o*h+s*u,w=s*o*h-r*u,$=o*o*h+c,i[0]=l*A+f*O+g*C,i[1]=d*A+x*O+b*C,i[2]=m*A+y*O+_*C,i[3]=p*A+M*O+I*C,i[4]=l*k+f*v+g*E,i[5]=d*k+x*v+b*E,i[6]=m*k+y*v+_*E,i[7]=p*k+M*v+I*E,i[8]=l*P+f*w+g*$,i[9]=d*P+x*w+b*$,i[10]=m*P+y*w+_*$,i[11]=p*P+M*w+I*$,e!==i&&(i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i)}function $n(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[4],o=e[5],a=e[6],c=e[7],u=e[8],h=e[9],l=e[10],d=e[11];return e!==i&&(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[4]=s*r+u*n,i[5]=o*r+h*n,i[6]=a*r+l*n,i[7]=c*r+d*n,i[8]=u*r-s*n,i[9]=h*r-o*n,i[10]=l*r-a*n,i[11]=d*r-c*n,i}function Un(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],u=e[8],h=e[9],l=e[10],d=e[11];return e!==i&&(i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r-u*n,i[1]=o*r-h*n,i[2]=a*r-l*n,i[3]=c*r-d*n,i[8]=s*n+u*r,i[9]=o*n+h*r,i[10]=a*n+l*r,i[11]=c*n+d*r,i}function Vn(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],u=e[4],h=e[5],l=e[6],d=e[7];return e!==i&&(i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r+u*n,i[1]=o*r+h*n,i[2]=a*r+l*n,i[3]=c*r+d*n,i[4]=u*r-s*n,i[5]=h*r-o*n,i[6]=l*r-a*n,i[7]=d*r-c*n,i}function Xn(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=t+t,a=n+n,c=r+r,u=t*o,h=n*o,l=n*a,d=r*o,m=r*a,p=r*c,f=s*o,x=s*a,y=s*c;return i[0]=1-l-p,i[1]=h+y,i[2]=d-x,i[3]=0,i[4]=h-y,i[5]=1-u-p,i[6]=m+f,i[7]=0,i[8]=d+x,i[9]=m-f,i[10]=1-u-l,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function Hn(i,e,t,n,r,s,o){let a=1/(t-e),c=1/(r-n),u=1/(s-o);return i[0]=s*2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s*2*c,i[6]=0,i[7]=0,i[8]=(t+e)*a,i[9]=(r+n)*c,i[10]=(o+s)*u,i[11]=-1,i[12]=0,i[13]=0,i[14]=o*s*2*u,i[15]=0,i}function Qs(i,e,t,n,r){let s=1/Math.tan(e/2);if(i[0]=s/t,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,r!=null&&r!==1/0){let o=1/(n-r);i[10]=(r+n)*o,i[14]=2*r*n*o}else i[10]=-1,i[14]=-2*n;return i}var Yn=Qs;function eo(i,e,t,n,r,s,o){let a=1/(e-t),c=1/(n-r),u=1/(s-o);return i[0]=-2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*c,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=2*u,i[11]=0,i[12]=(e+t)*a,i[13]=(r+n)*c,i[14]=(o+s)*u,i[15]=1,i}var Wn=eo;function qn(i,e,t,n){let r,s,o,a,c,u,h,l,d,m,p=e[0],f=e[1],x=e[2],y=n[0],M=n[1],g=n[2],b=t[0],_=t[1],I=t[2];return Math.abs(p-b)<1e-6&&Math.abs(f-_)<1e-6&&Math.abs(x-I)<1e-6?Js(i):(l=p-b,d=f-_,m=x-I,r=1/Math.sqrt(l*l+d*d+m*m),l*=r,d*=r,m*=r,s=M*m-g*d,o=g*l-y*m,a=y*d-M*l,r=Math.sqrt(s*s+o*o+a*a),r?(r=1/r,s*=r,o*=r,a*=r):(s=0,o=0,a=0),c=d*a-m*o,u=m*s-l*a,h=l*o-d*s,r=Math.sqrt(c*c+u*u+h*h),r?(r=1/r,c*=r,u*=r,h*=r):(c=0,u=0,h=0),i[0]=s,i[1]=c,i[2]=l,i[3]=0,i[4]=o,i[5]=u,i[6]=d,i[7]=0,i[8]=a,i[9]=h,i[10]=m,i[11]=0,i[12]=-(s*p+o*f+a*x),i[13]=-(c*p+u*f+h*x),i[14]=-(l*p+d*f+m*x),i[15]=1,i)}function to(){let i=new ne(4);return ne!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0,i[3]=0),i}function Kn(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3];return i[0]=t[0]*n+t[4]*r+t[8]*s+t[12]*o,i[1]=t[1]*n+t[5]*r+t[9]*s+t[13]*o,i[2]=t[2]*n+t[6]*r+t[10]*s+t[14]*o,i[3]=t[3]*n+t[7]*r+t[11]*s+t[15]*o,i}var Vh=function(){let i=to();return function(e,t,n,r,s,o){let a,c;for(t||(t=4),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],i[2]=e[a+2],i[3]=e[a+3],s(i,i,o),e[a]=i[0],e[a+1]=i[1],e[a+2]=i[2],e[a+3]=i[3];return e}}();var Ai;(function(i){i[i.COL0ROW0=0]="COL0ROW0",i[i.COL0ROW1=1]="COL0ROW1",i[i.COL0ROW2=2]="COL0ROW2",i[i.COL0ROW3=3]="COL0ROW3",i[i.COL1ROW0=4]="COL1ROW0",i[i.COL1ROW1=5]="COL1ROW1",i[i.COL1ROW2=6]="COL1ROW2",i[i.COL1ROW3=7]="COL1ROW3",i[i.COL2ROW0=8]="COL2ROW0",i[i.COL2ROW1=9]="COL2ROW1",i[i.COL2ROW2=10]="COL2ROW2",i[i.COL2ROW3=11]="COL2ROW3",i[i.COL3ROW0=12]="COL3ROW0",i[i.COL3ROW1=13]="COL3ROW1",i[i.COL3ROW2=14]="COL3ROW2",i[i.COL3ROW3=15]="COL3ROW3"})(Ai||(Ai={}));var io=45*Math.PI/180,no=1,Ti=.1,wi=500,ro=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),D=class extends Ct{static get IDENTITY(){return oo()}static get ZERO(){return so()}get ELEMENTS(){return 16}get RANK(){return 4}get INDICES(){return Ai}constructor(e){super(-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0),arguments.length===1&&Array.isArray(e)?this.copy(e):this.identity()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this[4]=e[4],this[5]=e[5],this[6]=e[6],this[7]=e[7],this[8]=e[8],this[9]=e[9],this[10]=e[10],this[11]=e[11],this[12]=e[12],this[13]=e[13],this[14]=e[14],this[15]=e[15],this.check()}set(e,t,n,r,s,o,a,c,u,h,l,d,m,p,f,x){return this[0]=e,this[1]=t,this[2]=n,this[3]=r,this[4]=s,this[5]=o,this[6]=a,this[7]=c,this[8]=u,this[9]=h,this[10]=l,this[11]=d,this[12]=m,this[13]=p,this[14]=f,this[15]=x,this.check()}setRowMajor(e,t,n,r,s,o,a,c,u,h,l,d,m,p,f,x){return this[0]=e,this[1]=s,this[2]=u,this[3]=m,this[4]=t,this[5]=o,this[6]=h,this[7]=p,this[8]=n,this[9]=a,this[10]=l,this[11]=f,this[12]=r,this[13]=c,this[14]=d,this[15]=x,this.check()}toRowMajor(e){return e[0]=this[0],e[1]=this[4],e[2]=this[8],e[3]=this[12],e[4]=this[1],e[5]=this[5],e[6]=this[9],e[7]=this[13],e[8]=this[2],e[9]=this[6],e[10]=this[10],e[11]=this[14],e[12]=this[3],e[13]=this[7],e[14]=this[11],e[15]=this[15],e}identity(){return this.copy(ro)}fromObject(e){return this.check()}fromQuaternion(e){return Xn(this,e),this.check()}frustum(e){let{left:t,right:n,bottom:r,top:s,near:o=Ti,far:a=wi}=e;return a===1/0?ao(this,t,n,r,s,o):Hn(this,t,n,r,s,o,a),this.check()}lookAt(e){let{eye:t,center:n=[0,0,0],up:r=[0,1,0]}=e;return qn(this,t,n,r),this.check()}ortho(e){let{left:t,right:n,bottom:r,top:s,near:o=Ti,far:a=wi}=e;return Wn(this,t,n,r,s,o,a),this.check()}orthographic(e){let{fovy:t=io,aspect:n=no,focalDistance:r=1,near:s=Ti,far:o=wi}=e;Zn(t);let a=t/2,c=r*Math.tan(a),u=c*n;return this.ortho({left:-u,right:u,bottom:-c,top:c,near:s,far:o})}perspective(e){let{fovy:t=45*Math.PI/180,aspect:n=1,near:r=.1,far:s=500}=e;return Zn(t),Yn(this,t,n,r,s),this.check()}determinant(){return Fn(this)}getScale(e=[-0,-0,-0]){return e[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]),e[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]),e[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]),e}getTranslation(e=[-0,-0,-0]){return e[0]=this[12],e[1]=this[13],e[2]=this[14],e}getRotation(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=0,e[4]=this[4]*r,e[5]=this[5]*s,e[6]=this[6]*o,e[7]=0,e[8]=this[8]*r,e[9]=this[9]*s,e[10]=this[10]*o,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}getRotationMatrix3(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=this[4]*r,e[4]=this[5]*s,e[5]=this[6]*o,e[6]=this[8]*r,e[7]=this[9]*s,e[8]=this[10]*o,e}transpose(){return Dn(this,this),this.check()}invert(){return Bn(this,this),this.check()}multiplyLeft(e){return vi(this,e,this),this.check()}multiplyRight(e){return vi(this,this,e),this.check()}rotateX(e){return $n(this,this,e),this.check()}rotateY(e){return Un(this,this,e),this.check()}rotateZ(e){return Vn(this,this,e),this.check()}rotateXYZ(e){return this.rotateX(e[0]).rotateY(e[1]).rotateZ(e[2])}rotateAxis(e,t){return Gn(this,this,e,t),this.check()}scale(e){return jn(this,this,Array.isArray(e)?e:[e,e,e]),this.check()}translate(e){return zn(this,this,e),this.check()}transform(e,t){return e.length===4?(t=Kn(t||[-0,-0,-0,-0],e,this),Tt(t,4),t):this.transformAsPoint(e,t)}transformAsPoint(e,t){let{length:n}=e,r;switch(n){case 2:r=An(t||[-0,-0],e,this);break;case 3:r=Et(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return Tt(r,e.length),r}transformAsVector(e,t){let n;switch(e.length){case 2:n=En(t||[-0,-0],e,this);break;case 3:n=At(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return Tt(n,e.length),n}transformPoint(e,t){return this.transformAsPoint(e,t)}transformVector(e,t){return this.transformAsPoint(e,t)}transformDirection(e,t){return this.transformAsVector(e,t)}makeRotationX(e){return this.identity().rotateX(e)}makeTranslation(e,t,n){return this.identity().translate([e,t,n])}},Pt,Lt;function so(){return Pt||(Pt=new D([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Object.freeze(Pt)),Pt}function oo(){return Lt||(Lt=new D,Object.freeze(Lt)),Lt}function Zn(i){if(i>Math.PI*2)throw Error("expected radians")}function ao(i,e,t,n,r,s){let o=2*s/(t-e),a=2*s/(r-n),c=(t+e)/(t-e),u=(r+n)/(r-n),h=-1,l=-1,d=-2*s;return i[0]=o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=a,i[6]=0,i[7]=0,i[8]=c,i[9]=u,i[10]=h,i[11]=l,i[12]=0,i[13]=0,i[14]=d,i[15]=0,i}var co=.02,ho=.12,uo=.15,lo=.2,Ci=[0,1,0],fo=[255,255,255],mo=1,Ei=.35,Si=255,po=1,go=.01,xo={depthCompare:"less-equal",depthWriteEnabled:!1,cullMode:"none"},bo=[{name:"instancePosition",format:"float32x3",stepMode:"instance"},{name:"instanceDirection",format:"float32x3",stepMode:"instance"},{name:"instanceScale",format:"float32x3",stepMode:"instance"},{name:"instanceColor",format:"float32x4",stepMode:"instance"}],yo={name:"lightMarker",props:{},uniforms:{},uniformTypes:{viewProjectionMatrix:"mat4x4<f32>"}},_o="inputs.positions * inputs.instanceScale",Io="vec3<f32>(inputs.positions.x * inputs.instanceScale.x, (inputs.positions.y - 0.5) * inputs.instanceScale.y, inputs.positions.z * inputs.instanceScale.z)",Mo="positions * instanceScale",vo="vec3(positions.x * instanceScale.x, (positions.y - 0.5) * instanceScale.y, positions.z * instanceScale.z)",ue=class extends Y{lightModelProps;_instanceData;_managedBuffers;buildInstanceData;sizePropNames;constructor(e,t,n){let r=n.buildInstanceData(t),s=Jn(e,t.id||n.idPrefix,r),o=new V({lightMarker:yo});o.setProps({lightMarker:{viewProjectionMatrix:er(t)}});let{source:a,vs:c,fs:u}=So(n.anchorMode),h=t;super(e,{...h,id:t.id||n.idPrefix,source:a,vs:c,fs:u,geometry:n.geometry,shaderInputs:o,bufferLayout:[...bo],attributes:s,instanceCount:r.instanceCount,parameters:tr(t.parameters)}),this.lightModelProps=t,this._instanceData=r,this._managedBuffers=s,this.buildInstanceData=n.buildInstanceData,this.sizePropNames=n.sizePropNames}destroy(){super.destroy(),Qn(this._managedBuffers),this._managedBuffers={}}draw(e){return this.instanceCount===0?!0:super.draw(e)}setProps(e){this.lightModelProps={...this.lightModelProps,...e},e.parameters&&this.setParameters(tr(this.lightModelProps.parameters)),("viewMatrix"in e||"projectionMatrix"in e)&&(this.shaderInputs.setProps({lightMarker:{viewProjectionMatrix:er(this.lightModelProps)}}),this.setNeedsRedraw("lightMarker camera")),Eo(e,this.sizePropNames)&&this.rebuildInstanceData()}rebuildInstanceData(){let e=this.buildInstanceData(this.lightModelProps),t=Jn(this.device,this.id,e);this.setAttributes(t),this.setInstanceCount(e.instanceCount),Qn(this._managedBuffers),this._managedBuffers=t,this._instanceData=e}};function ir(i){let e=sr(i.lights),t=Pi(i),n=i.pointLightRadius??co*t.sceneScale*t.markerScale;return Oi(e.length,(r,s)=>({color:Li(r),direction:Ci,position:r.position,scale:[n,n,n]}),e)}function nr(i){let e=or(i.lights),t=Pi(i),n=i.spotLightLength??ho*t.sceneScale*t.markerScale;return Oi(e.length,(r,s)=>{let o=qe(r.outerConeAngle??Math.PI/4,0,Math.PI/2-go),a=Math.tan(o)*n;return{color:Li(r),direction:ar(r.direction),position:r.position,scale:[a,n,a]}},e)}function rr(i){let e=To(i.lights),t=Pi(i),n=i.directionalLightLength??uo*t.sceneScale*t.markerScale,r=n*lo;return Oi(e.length,(s,o)=>{let a=ar(s.direction),c=[t.sceneCenter[0]-a[0]*t.sceneScale*Ei,t.sceneCenter[1]-a[1]*t.sceneScale*Ei,t.sceneCenter[2]-a[2]*t.sceneScale*Ei];return{color:Li(s),direction:a,position:c,scale:[r,n,r]}},e)}function sr(i){return i.filter(e=>e.type==="point")}function or(i){return i.filter(e=>e.type==="spot")}function To(i){return i.filter(e=>e.type==="directional")}function Pi(i){let e=wo(i.lights,i.bounds),t=[(e[0][0]+e[1][0])/2,(e[0][1]+e[1][1])/2,(e[0][2]+e[1][2])/2],n=Math.max(Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1],e[1][2]-e[0][2]),po);return{bounds:e,markerScale:Math.max(i.markerScale??mo,0),sceneCenter:t,sceneScale:n}}function Li(i){let e=i.color||fo,t=Math.max(i.intensity??1,0),n=qe(.35+.3*Math.log10(t+1),.35,1);return[qe(e[0]/Si,0,1)*n,qe(e[1]/Si,0,1)*n,qe(e[2]/Si,0,1)*n,1]}function ar(i){let[e,t,n]=i||Ci,r=Math.hypot(e,t,n);return r===0?[...Ci]:[e/r,t/r,n/r]}function Oi(i,e,t=[]){let n=new Float32Array(i*3),r=new Float32Array(i*3),s=new Float32Array(i*3),o=new Float32Array(i*4);for(let[a,c]of t.entries()){let u=e(c,a);n.set(u.position,a*3),r.set(u.direction,a*3),s.set(u.scale,a*3),o.set(u.color,a*4)}return{instanceCount:i,instancePositions:n,instanceDirections:r,instanceScales:s,instanceColors:o}}function wo(i,e){if(e)return Ao(e);let t=[...sr(i).map(s=>s.position),...or(i).map(s=>s.position)];if(t.length===0)return[[-.5,-.5,-.5],[.5,.5,.5]];let n=[...t[0]],r=[...t[0]];for(let s of t.slice(1))n[0]=Math.min(n[0],s[0]),n[1]=Math.min(n[1],s[1]),n[2]=Math.min(n[2],s[2]),r[0]=Math.max(r[0],s[0]),r[1]=Math.max(r[1],s[1]),r[2]=Math.max(r[2],s[2]);return[n,r]}function Ao(i){return[[...i[0]],[...i[1]]]}function Jn(i,e,t){return{instancePosition:i.createBuffer({id:`${e}-instance-position`,data:Ot(t.instancePositions,3)}),instanceDirection:i.createBuffer({id:`${e}-instance-direction`,data:Ot(t.instanceDirections,3)}),instanceScale:i.createBuffer({id:`${e}-instance-scale`,data:Ot(t.instanceScales,3)}),instanceColor:i.createBuffer({id:`${e}-instance-color`,data:Ot(t.instanceColors,4)})}}function Ot(i,e){return i.length>0?i:new Float32Array(e)}function Qn(i){for(let e of Object.values(i))e?.destroy()}function er(i){return new D(i.projectionMatrix).multiplyRight(i.viewMatrix)}function Eo(i,e){return"lights"in i||"bounds"in i||"markerScale"in i?!0:e.some(t=>t in i)}function tr(i){return{...xo,...i||{}}}function So(i){let e=i==="apex"?Io:_o,t=i==="apex"?vo:Mo;return{source:`struct lightMarkerUniforms {
92
+ `,Be=class extends ue{backgroundTexture=null;flipY=!1;constructor(e,t){if(super(e,{...t,id:t.id||"background-texture-model",source:ko,fs:No,modules:[...t.modules||[],Ro],parameters:{depthWriteEnabled:!1,...t.parameters||{},...t.blend?{blend:!0,blendColorOperation:"add",blendAlphaOperation:"add",blendColorSrcFactor:"one-minus-dst-alpha",blendColorDstFactor:"one",blendAlphaSrcFactor:"one-minus-dst-alpha",blendAlphaDstFactor:"one"}:{}}}),!t.backgroundTexture)throw new Error("BackgroundTextureModel requires a backgroundTexture prop");this.setProps(t)}setProps(e){let{backgroundTexture:t}=e;if(e.flipY!==void 0&&(this.flipY=e.flipY,this.backgroundTexture&&this.updateScale(this.backgroundTexture)),t)if(this.setBindings({backgroundTexture:t}),t.isReady){let n=t instanceof K?t.texture:t;this.backgroundTexture=n,this.updateScale(n)}else t.ready.then(n=>{this.backgroundTexture=n,this.updateScale(n)})}predraw(e){super.predraw(e)}updateScale(e){if(!e){this.shaderInputs.setProps({background:{scale:[1,1],flipY:0}});return}let[t,n]=this.device.getCanvasContext().getDrawingBufferSize(),r=e.width,s=e.height,o=t/n,a=r/s,c=1,h=1;o>a?h=o/a:c=a/o,this.shaderInputs.setProps({background:{scale:[c,h],flipY:this.flipY?1:0}})}};var Fe=class extends z{constructor(e={}){let{id:t=O("sphere-geometry")}=e,{indices:n,attributes:r}=Do(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Do(i){let{nlat:e=10,nlong:t=10}=i,s=Math.PI-0,c=2*Math.PI-0,h=(e+1)*(t+1),u=(_,M,y,I,g)=>i.radius||1,d=new Float32Array(h*3),l=new Float32Array(h*3),f=new Float32Array(h*2),m=h>65535?Uint32Array:Uint16Array,p=new m(e*t*6);for(let _=0;_<=e;_++)for(let M=0;M<=t;M++){let y=M/t,I=_/e,g=M+_*(t+1),x=g*2,v=g*3,w=c*y,T=s*I,P=Math.sin(w),S=Math.cos(w),A=Math.sin(T),L=Math.cos(T),C=S*A,U=L,ee=P*A,q=u(C,U,ee,y,I);d[v+0]=q*C,d[v+1]=q*U,d[v+2]=q*ee,l[v+0]=C,l[v+1]=U,l[v+2]=ee,f[x+0]=y,f[x+1]=1-I}let b=t+1;for(let _=0;_<t;_++)for(let M=0;M<e;M++){let y=(_*e+M)*6;p[y+0]=M*b+_,p[y+1]=M*b+_+1,p[y+2]=(M+1)*b+_,p[y+3]=(M+1)*b+_,p[y+4]=M*b+_+1,p[y+5]=(M+1)*b+_+1}return{indices:{size:1,value:p},attributes:{POSITION:{size:3,value:d},NORMAL:{size:3,value:l},TEXCOORD_0:{size:2,value:f}}}}var Bo=.02,Fo=.12,zo=.15,jo=.2,Bi=[0,1,0],Go=[255,255,255],Uo=1,Ni=.35,Di=255,$o=1,Vo=.01,Xo={depthCompare:"less-equal",depthWriteEnabled:!1,cullMode:"none"},Ho=[{name:"instancePosition",format:"float32x3",stepMode:"instance"},{name:"instanceDirection",format:"float32x3",stepMode:"instance"},{name:"instanceScale",format:"float32x3",stepMode:"instance"},{name:"instanceColor",format:"float32x4",stepMode:"instance"}],Yo={name:"lightMarker",props:{},uniforms:{},uniformTypes:{viewProjectionMatrix:"mat4x4<f32>"}},Wo="inputs.positions * inputs.instanceScale",qo="vec3<f32>(inputs.positions.x * inputs.instanceScale.x, (inputs.positions.y - 0.5) * inputs.instanceScale.y, inputs.positions.z * inputs.instanceScale.z)",Ko="positions * instanceScale",Zo="vec3(positions.x * instanceScale.x, (positions.y - 0.5) * instanceScale.y, positions.z * instanceScale.z)",le=class extends Y{lightModelProps;_instanceData;_managedBuffers;buildInstanceData;sizePropNames;constructor(e,t,n){let r=n.buildInstanceData(t),s=pr(e,t.id||n.idPrefix,r),o=new X({lightMarker:Yo});o.setProps({lightMarker:{viewProjectionMatrix:xr(t)}});let{source:a,vs:c,fs:h}=ia(n.anchorMode),u=t;super(e,{...u,id:t.id||n.idPrefix,source:a,vs:c,fs:h,geometry:n.geometry,shaderInputs:o,bufferLayout:[...Ho],attributes:s,instanceCount:r.instanceCount,parameters:br(t.parameters)}),this.lightModelProps=t,this._instanceData=r,this._managedBuffers=s,this.buildInstanceData=n.buildInstanceData,this.sizePropNames=n.sizePropNames}destroy(){super.destroy(),gr(this._managedBuffers),this._managedBuffers={}}draw(e){return this.instanceCount===0?!0:super.draw(e)}setProps(e){this.lightModelProps={...this.lightModelProps,...e},e.parameters&&this.setParameters(br(this.lightModelProps.parameters)),("viewMatrix"in e||"projectionMatrix"in e)&&(this.shaderInputs.setProps({lightMarker:{viewProjectionMatrix:xr(this.lightModelProps)}}),this.setNeedsRedraw("lightMarker camera")),ta(e,this.sizePropNames)&&this.rebuildInstanceData()}rebuildInstanceData(){let e=this.buildInstanceData(this.lightModelProps),t=pr(this.device,this.id,e);this.setAttributes(t),this.setInstanceCount(e.instanceCount),gr(this._managedBuffers),this._managedBuffers=t,this._instanceData=e}};function yr(i){let e=vr(i.lights),t=Fi(i),n=i.pointLightRadius??Bo*t.sceneScale*t.markerScale;return ji(e.length,(r,s)=>({color:zi(r),direction:Bi,position:r.position,scale:[n,n,n]}),e)}function _r(i){let e=Mr(i.lights),t=Fi(i),n=i.spotLightLength??Fo*t.sceneScale*t.markerScale;return ji(e.length,(r,s)=>{let o=Ze(r.outerConeAngle??Math.PI/4,0,Math.PI/2-Vo),a=Math.tan(o)*n;return{color:zi(r),direction:Tr(r.direction),position:r.position,scale:[a,n,a]}},e)}function Ir(i){let e=Qo(i.lights),t=Fi(i),n=i.directionalLightLength??zo*t.sceneScale*t.markerScale,r=n*jo;return ji(e.length,(s,o)=>{let a=Tr(s.direction),c=[t.sceneCenter[0]-a[0]*t.sceneScale*Ni,t.sceneCenter[1]-a[1]*t.sceneScale*Ni,t.sceneCenter[2]-a[2]*t.sceneScale*Ni];return{color:zi(s),direction:a,position:c,scale:[r,n,r]}},e)}function vr(i){return i.filter(e=>e.type==="point")}function Mr(i){return i.filter(e=>e.type==="spot")}function Qo(i){return i.filter(e=>e.type==="directional")}function Fi(i){let e=Jo(i.lights,i.bounds),t=[(e[0][0]+e[1][0])/2,(e[0][1]+e[1][1])/2,(e[0][2]+e[1][2])/2],n=Math.max(Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1],e[1][2]-e[0][2]),$o);return{bounds:e,markerScale:Math.max(i.markerScale??Uo,0),sceneCenter:t,sceneScale:n}}function zi(i){let e=i.color||Go,t=Math.max(i.intensity??1,0),n=Ze(.35+.3*Math.log10(t+1),.35,1);return[Ze(e[0]/Di,0,1)*n,Ze(e[1]/Di,0,1)*n,Ze(e[2]/Di,0,1)*n,1]}function Tr(i){let[e,t,n]=i||Bi,r=Math.hypot(e,t,n);return r===0?[...Bi]:[e/r,t/r,n/r]}function ji(i,e,t=[]){let n=new Float32Array(i*3),r=new Float32Array(i*3),s=new Float32Array(i*3),o=new Float32Array(i*4);for(let[a,c]of t.entries()){let h=e(c,a);n.set(h.position,a*3),r.set(h.direction,a*3),s.set(h.scale,a*3),o.set(h.color,a*4)}return{instanceCount:i,instancePositions:n,instanceDirections:r,instanceScales:s,instanceColors:o}}function Jo(i,e){if(e)return ea(e);let t=[...vr(i).map(s=>s.position),...Mr(i).map(s=>s.position)];if(t.length===0)return[[-.5,-.5,-.5],[.5,.5,.5]];let n=[...t[0]],r=[...t[0]];for(let s of t.slice(1))n[0]=Math.min(n[0],s[0]),n[1]=Math.min(n[1],s[1]),n[2]=Math.min(n[2],s[2]),r[0]=Math.max(r[0],s[0]),r[1]=Math.max(r[1],s[1]),r[2]=Math.max(r[2],s[2]);return[n,r]}function ea(i){return[[...i[0]],[...i[1]]]}function pr(i,e,t){return{instancePosition:i.createBuffer({id:`${e}-instance-position`,data:Bt(t.instancePositions,3)}),instanceDirection:i.createBuffer({id:`${e}-instance-direction`,data:Bt(t.instanceDirections,3)}),instanceScale:i.createBuffer({id:`${e}-instance-scale`,data:Bt(t.instanceScales,3)}),instanceColor:i.createBuffer({id:`${e}-instance-color`,data:Bt(t.instanceColors,4)})}}function Bt(i,e){return i.length>0?i:new Float32Array(e)}function gr(i){for(let e of Object.values(i))e?.destroy()}function xr(i){return new k(i.projectionMatrix).multiplyRight(i.viewMatrix)}function ta(i,e){return"lights"in i||"bounds"in i||"markerScale"in i?!0:e.some(t=>t in i)}function br(i){return{...Xo,...i||{}}}function ia(i){let e=i==="apex"?qo:Wo,t=i==="apex"?Zo:Ko;return{source:`struct lightMarkerUniforms {
93
93
  viewProjectionMatrix: mat4x4<f32>,
94
94
  };
95
95
 
@@ -171,7 +171,7 @@ out vec4 fragColor;
171
171
  void main(void) {
172
172
  fragColor = vColor;
173
173
  }
174
- `}}function qe(i,e,t){return Math.min(t,Math.max(e,i))}var Co=new Oe({nlat:8,nlong:12,radius:1}),kt=class extends ue{constructor(e,t){super(e,t,{anchorMode:"centered",buildInstanceData:ir,geometry:Co,idPrefix:"point-light-model",sizePropNames:["pointLightRadius"]})}};var Po={x:[2,0,1],y:[0,1,2],z:[1,2,0]},de=class extends G{constructor(e={}){let{id:t=S("truncated-code-geometry")}=e,{indices:n,attributes:r}=Lo(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{POSITION:{size:3,value:r.POSITION},NORMAL:{size:3,value:r.NORMAL},TEXCOORD_0:{size:2,value:r.TEXCOORD_0},...e.attributes}})}};function Lo(i={}){let{bottomRadius:e=0,topRadius:t=0,height:n=1,nradial:r=10,nvertical:s=10,verticalAxis:o="y",topCap:a=!1,bottomCap:c=!1}=i,u=(a?2:0)+(c?2:0),h=(r+1)*(s+1+u),l=Math.atan2(e-t,n),d=Math.sin,m=Math.cos,p=Math.PI,f=m(l),x=d(l),y=a?-2:0,M=s+(c?2:0),g=r+1,b=new Uint16Array(r*(s+u)*6),_=Po[o],I=new Float32Array(h*3),A=new Float32Array(h*3),O=new Float32Array(h*2),C=0,k=0;for(let v=y;v<=M;v++){let E=v/s,P=n*E,w;v<0?(P=0,E=1,w=e):v>s?(P=n,E=1,w=t):w=e+(t-e)*(v/s),(v===-2||v===s+2)&&(w=0,E=0),P-=n/2;for(let $=0;$<g;$++){let te=d($*p*2/r),Z=m($*p*2/r);I[C+_[0]]=te*w,I[C+_[1]]=P,I[C+_[2]]=Z*w,A[C+_[0]]=v<0||v>s?0:te*f,A[C+_[1]]=v<0?-1:v>s?1:x,A[C+_[2]]=v<0||v>s?0:Z*f,O[k+0]=$/r,O[k+1]=E,k+=2,C+=3}}for(let v=0;v<s+u;v++)for(let E=0;E<r;E++){let P=(v*r+E)*6;b[P+0]=g*(v+0)+0+E,b[P+1]=g*(v+0)+1+E,b[P+2]=g*(v+1)+1+E,b[P+3]=g*(v+0)+0+E,b[P+4]=g*(v+1)+1+E,b[P+5]=g*(v+1)+0+E}return{indices:b,attributes:{POSITION:I,NORMAL:A,TEXCOORD_0:O}}}var le=class extends de{constructor(e={}){let{id:t=S("cone-geometry"),radius:n=1,cap:r=!0}=e;super({...e,id:t,topRadius:0,topCap:Boolean(r),bottomCap:Boolean(r),bottomRadius:n})}};var Oo=new le({cap:!0,nradial:16,nvertical:1,radius:1}),Rt=class extends ue{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:nr,geometry:Oo,idPrefix:"spot-light-model",sizePropNames:["spotLightLength"]})}};var ko=new le({cap:!0,nradial:12,nvertical:1,radius:1}),Nt=class extends ue{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:rr,geometry:ko,idPrefix:"directional-light-model",sizePropNames:["directionalLightLength"]})}};function ki(i,e){if(!i)throw new Error(e)}var re=class{id;matrix=new D;display=!0;position=new H;rotation=new H;scale=new H(1,1,1);userData={};props={};constructor(e={}){let{id:t}=e;this.id=t||S(this.constructor.name),this._setScenegraphNodeProps(e)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(e){return this._setScenegraphNodeProps(e),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(e){return ki(e.length===3,"setPosition requires vector argument"),this.position=e,this}setRotation(e){return ki(e.length===3||e.length===4,"setRotation requires vector argument"),this.rotation=e,this}setScale(e){return ki(e.length===3,"setScale requires vector argument"),this.scale=e,this}setMatrix(e,t=!0){t?this.matrix.copy(e):this.matrix=e}setMatrixComponents(e){let{position:t,rotation:n,scale:r,update:s=!0}=e;return t&&this.setPosition(t),n&&this.setRotation(n),r&&this.setScale(r),s&&this.updateMatrix(),this}updateMatrix(){if(this.matrix.identity(),this.matrix.translate(this.position),this.rotation.length===4){let e=new D().fromQuaternion(this.rotation);this.matrix.multiplyRight(e)}else this.matrix.rotateXYZ(this.rotation);return this.matrix.scale(this.scale),this}update({position:e,rotation:t,scale:n}={}){return e&&this.setPosition(e),t&&this.setRotation(t),n&&this.setScale(n),this.updateMatrix(),this}getCoordinateUniforms(e,t){t=t||this.matrix;let n=new D(e).multiplyRight(t),r=n.invert(),s=r.transpose();return{viewMatrix:e,modelMatrix:t,objectMatrix:t,worldMatrix:n,worldInverseMatrix:r,worldInverseTransposeMatrix:s}}_setScenegraphNodeProps(e){e?.position&&this.setPosition(e.position),e?.rotation&&this.setRotation(e.rotation),e?.scale&&this.setScale(e.scale),this.updateMatrix(),e?.matrix&&this.setMatrix(e.matrix),Object.assign(this.props,e)}};var cr=L(R(),1);function Dt(){return[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]]}function Bt(i,e,t){let n=new D(t);for(let r=0;r<8;r++){let s=new H(e[r&1?1:0][0],e[r&2?1:0][1],e[r&4?1:0][2]);n.transformAsPoint(s,s);for(let o=0;o<3;o++)i[0][o]=Math.min(i[0][o],s[o]),i[1][o]=Math.max(i[1][o],s[o])}}function Ft(i){return Number.isFinite(i[0][0])}var ye=class extends re{children;constructor(e={}){e=Array.isArray(e)?{children:e}:e;let{children:t=[]}=e;cr.log.assert(t.every(n=>n instanceof re),"every child must an instance of ScenegraphNode"),super(e),this.children=t}getBounds(){let e=Dt();return this.traverse((t,{worldMatrix:n})=>{let r=t.getBounds();if(!r)return;let s=new D(n).multiplyRight(t.matrix);Bt(e,r,s)}),Ft(e)?e:null}destroy(){this.children.forEach(e=>e.destroy()),this.removeAll(),super.destroy()}add(...e){for(let t of e)Array.isArray(t)?this.add(...t):this.children.push(t);return this}remove(e){let t=this.children,n=t.indexOf(e);return n>-1&&t.splice(n,1),this}removeAll(){return this.children=[],this}traverse(e,{worldMatrix:t=new D}={}){let n=new D(t).multiplyRight(this.matrix);for(let r of this.children)r instanceof ye?r.traverse(e,{worldMatrix:n}):e(r,{worldMatrix:n})}traverseDepthSorted(e,{viewMatrix:t,worldMatrix:n=new D,order:r="back-to-front"}){let s=new D(t),o=[];this.traverse((c,u)=>{let h=c.getBounds(),l=h?new H(h[0]).add(h[1]).divide([2,2,2]):new H,d=new D(u.worldMatrix).multiplyRight(c.matrix);d.transformAsPoint(l,l),s.transformAsPoint(l,l),o.push({node:c,context:{worldMatrix:d,bounds:h,depth:-l[2]},index:o.length})},{worldMatrix:new D(n)});let a=r==="back-to-front"?-1:1;o.sort((c,u)=>a*(c.context.depth-u.context.depth)||c.index-u.index);for(let{node:c,context:u}of o)e(c,u)}preorderTraversal(e,{worldMatrix:t=new D}={}){let n=new D(t).multiplyRight(this.matrix);e(this,{worldMatrix:n});for(let r of this.children)r instanceof ye?r.preorderTraversal(e,{worldMatrix:n}):e(r,{worldMatrix:n})}};var zt=class extends re{model;instanceMatrices;bounds=null;managedResources;constructor(e){super(e),this.model=e.model,this.managedResources=e.managedResources||[],this.instanceMatrices=e.instanceMatrices||null,this.bounds=e.bounds?this.instanceMatrices?Ro(e.bounds,this.instanceMatrices):e.bounds:null,this.setProps(e)}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach(e=>e.destroy()),this.managedResources=[]}getBounds(){return this.bounds}draw(e){return this.model.draw(e)}};function Ro(i,e){let t=Dt();for(let n of e)Bt(t,i,n);return Ft(t)?t:null}var jt=class extends G{constructor(e={}){let{id:t=S("cube-geometry"),indices:n=!0}=e;super(n?{...e,id:t,topology:"triangle-list",indices:{size:1,value:No},attributes:{...Vo,...e.attributes}}:{...e,id:t,topology:"triangle-list",indices:void 0,attributes:{...Xo,...e.attributes}})}},No=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]),Do=new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1]),Bo=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0]),Fo=new Float32Array([0,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1]),zo=new Uint32Array([0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]),jo=new Float32Array([1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1]),Go=new Float32Array([1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0]),$o=new Float32Array([1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1]),Uo=new Uint32Array([3,3,3,3,3,3,4,4,4,4,4,4,2,2,2,2,2,2,5,5,5,5,5,5,0,0,0,0,0,0,1,1,1,1,1,1]),Vo={POSITION:{size:3,value:Do},NORMAL:{size:3,value:Bo},TEXCOORD_0:{size:2,value:Fo},faceIndex:{size:1,value:zo}},Xo={POSITION:{size:3,value:jo},TEXCOORD_0:{size:2,value:Go},COLOR_0:{size:3,value:$o},faceIndex:{size:1,value:Uo}};var Gt=class extends de{constructor(e={}){let{id:t=S("cylinder-geometry"),radius:n=1}=e;super({...e,id:t,bottomRadius:n,topRadius:n})}};var Ho=[-1,0,0,0,1,0,0,0,-1,0,0,1,0,-1,0,1,0,0],Yo=[3,4,5,3,5,1,3,1,0,3,0,4,4,0,2,4,2,5,2,0,1,5,2,1],$t=class extends G{constructor(e={}){let{id:t=S("ico-sphere-geometry")}=e,{indices:n,attributes:r}=Wo(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Wo(i){let{iterations:e=0}=i,t=Math.PI,n=t*2,r=[...Ho],s=[...Yo];r.push(),s.push();let o=(()=>{let h={};return(l,d)=>{l*=3,d*=3;let m=l<d?l:d,p=l>d?l:d,f=`${m}|${p}`;if(f in h)return h[f];let x=r[l],y=r[l+1],M=r[l+2],g=r[d],b=r[d+1],_=r[d+2],I=(x+g)/2,A=(y+b)/2,O=(M+_)/2,C=Math.sqrt(I*I+A*A+O*O);I/=C,A/=C,O/=C,r.push(I,A,O);let k=r.length/3-1;return h[f]=k,k}})();for(let h=0;h<e;h++){let l=[];for(let d=0;d<s.length;d+=3){let m=o(s[d+0],s[d+1]),p=o(s[d+1],s[d+2]),f=o(s[d+2],s[d+0]);l.push(f,s[d+0],m,m,s[d+1],p,p,s[d+2],f,m,p,f)}s=l}let a=new Array(r.length),c=new Array(r.length/3*2),u=s.length;for(let h=u-3;h>=0;h-=3){let l=s[h+0],d=s[h+1],m=s[h+2],p=l*3,f=d*3,x=m*3,y=l*2,M=d*2,g=m*2,b=r[p+0],_=r[p+1],I=r[p+2],A=Math.acos(I/Math.sqrt(b*b+_*_+I*I)),O=Math.atan2(_,b)+t,C=A/t,k=1-O/n,v=r[f+0],E=r[f+1],P=r[f+2],w=Math.acos(P/Math.sqrt(v*v+E*E+P*P)),$=Math.atan2(E,v)+t,te=w/t,Z=1-$/n,rt=r[x+0],st=r[x+1],ot=r[x+2],Dr=Math.acos(ot/Math.sqrt(rt*rt+st*st+ot*ot)),Br=Math.atan2(st,rt)+t,Gi=Dr/t,at=1-Br/n,Fr=[rt-v,st-E,ot-P],zr=[b-v,_-E,I-P],W=new H(Fr).cross(zr).normalize(),B;(k===0||Z===0||at===0)&&(k===0||k>.5)&&(Z===0||Z>.5)&&(at===0||at>.5)&&(r.push(r[p+0],r[p+1],r[p+2]),B=r.length/3-1,s.push(B),c[B*2+0]=1,c[B*2+1]=C,a[B*3+0]=W.x,a[B*3+1]=W.y,a[B*3+2]=W.z,r.push(r[f+0],r[f+1],r[f+2]),B=r.length/3-1,s.push(B),c[B*2+0]=1,c[B*2+1]=te,a[B*3+0]=W.x,a[B*3+1]=W.y,a[B*3+2]=W.z,r.push(r[x+0],r[x+1],r[x+2]),B=r.length/3-1,s.push(B),c[B*2+0]=1,c[B*2+1]=Gi,a[B*3+0]=W.x,a[B*3+1]=W.y,a[B*3+2]=W.z),a[p+0]=a[f+0]=a[x+0]=W.x,a[p+1]=a[f+1]=a[x+1]=W.y,a[p+2]=a[f+2]=a[x+2]=W.z,c[y+0]=k,c[y+1]=C,c[M+0]=Z,c[M+1]=te,c[g+0]=at,c[g+1]=Gi}return{indices:{size:1,value:new Uint16Array(s)},attributes:{POSITION:{size:3,value:new Float32Array(r)},NORMAL:{size:3,value:new Float32Array(a)},TEXCOORD_0:{size:2,value:new Float32Array(c)}}}}var Ut=class extends G{constructor(e={}){let{id:t=S("plane-geometry")}=e,{indices:n,attributes:r}=qo(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function qo(i){let{type:e="x,y",offset:t=0,flipCull:n=!1,unpack:r=!1}=i,s=e.split(","),o=i[`${s[0]}len`]||1,a=i[`${s[1]}len`]||1,c=i[`n${s[0]}`]||1,u=i[`n${s[1]}`]||1,h=(c+1)*(u+1),l=new Float32Array(h*3),d=new Float32Array(h*3),m=new Float32Array(h*2);n&&(o=-o);let p=0,f=0;for(let g=0;g<=u;g++)for(let b=0;b<=c;b++){let _=b/c,I=g/u;switch(m[p+0]=n?1-_:_,m[p+1]=I,e){case"x,y":l[f+0]=o*_-o*.5,l[f+1]=a*I-a*.5,l[f+2]=t,d[f+0]=0,d[f+1]=0,d[f+2]=n?1:-1;break;case"x,z":l[f+0]=o*_-o*.5,l[f+1]=t,l[f+2]=a*I-a*.5,d[f+0]=0,d[f+1]=n?1:-1,d[f+2]=0;break;case"y,z":l[f+0]=t,l[f+1]=o*_-o*.5,l[f+2]=a*I-a*.5,d[f+0]=n?1:-1,d[f+1]=0,d[f+2]=0;break;default:throw new Error("PlaneGeometry: unknown type")}p+=2,f+=3}let x=c+1,y=new Uint16Array(c*u*6);for(let g=0;g<u;g++)for(let b=0;b<c;b++){let _=(g*c+b)*6;y[_+0]=(g+0)*x+b,y[_+1]=(g+1)*x+b,y[_+2]=(g+0)*x+b+1,y[_+3]=(g+1)*x+b,y[_+4]=(g+1)*x+b+1,y[_+5]=(g+0)*x+b+1}let M={indices:{size:1,value:y},attributes:{POSITION:{size:3,value:l},NORMAL:{size:3,value:d},TEXCOORD_0:{size:2,value:m}}};return r?Ji(M):M}function hr(){let i=1,e=1;return()=>(i=Math.sin(e*17.23),e=Math.cos(i*27.92),Ko(Math.abs(i*e)*1432.71))}function Ko(i){return i-Math.floor(i)}var dr="";function lr(i){dr=i}function Vt(i){return Zo(i)?i:dr+i}async function fr(i,e){let t=new Image,n=Vt(i);t.crossOrigin=e?.crossOrigin||"anonymous",t.src=n;try{await t.decode()}catch(r){throw ur("decode",n,r)}try{return e?await createImageBitmap(t,e):await createImageBitmap(t)}catch(r){throw ur("create",n,r)}}async function mr(i,e){return await new Promise((t,n)=>{try{let r=new Image,s=Vt(i);r.onload=()=>t(r),r.onerror=()=>n(new Error(`Could not load image ${s}.`)),r.crossOrigin=e?.crossOrigin||"anonymous",r.src=s}catch(r){n(r)}})}function ur(i,e,t){let n=t instanceof Error?t.message:String(t),r=i==="decode"?`Could not decode source image "${e}": ${n}`:`Could not create ImageBitmap from decoded image "${e}": ${n}`;return new Error(r,{cause:t})}function Zo(i){return i.startsWith("/")||/^[a-z][a-z\d+\-.]*:/i.test(i)}var _e=L(R(),1);var Xt=class{device;id;destroyed=!1;generation=0;_source;_colorSpace;_sampler;_isReady=!1;_updateTimestamp;_sourceVersion=0;_sourceFrameToken=null;_texture=null;_textureFrameToken=void 0;_externalTexture=null;get source(){return this._source}get isReady(){return this._observeSource(),this._isReady}get updateTimestamp(){return this._observeSource(),this._updateTimestamp}get[Symbol.toStringTag](){return"VideoTexture"}toString(){let e=Ri(this._source);return`VideoTexture:"${this.id}":${e.width}x${e.height}px:(${this._isReady?"ready":"loading..."})`}constructor(e,t){(0,_e.assert)(Ke(t?.source)||pr(t?.source)),this.device=e,this.id=t.id||S("video-texture"),this._source=t.source,this._colorSpace=t.colorSpace??"srgb",this._sampler=t.sampler??{},this._updateTimestamp=this.device.incrementTimestamp(),this.setSource(t.source)}setSource(e){(0,_e.assert)(Ke(e)||pr(e)),this._destroyExternalTexture(),this._source=e,this._sourceVersion++,this._sourceFrameToken=null,this._textureFrameToken=void 0,this._observeSource(),this._touchGeneration()}resolveTextureBinding(e){return this._observeSource(),!this._isReady||this.destroyed?null:e.type==="external-texture"&&this.device.type==="webgpu"?this._createNativeExternalTexture():this._resolveCopiedTexture()}setSampler(e){this._sampler=e,this._texture?.setSampler(e),this._externalTexture?.setSampler?.(e),this._touchGeneration()}destroy(){this.destroyed||(this._destroyExternalTexture(),this._texture?.destroy(),this._texture=null,this._textureFrameToken=void 0,this._isReady=!1,this.destroyed=!0,this._touchGeneration())}_resolveCopiedTexture(){let e=this._getOrCreateCopiedTexture();return Object.is(this._textureFrameToken,this._sourceFrameToken)||(e.copyExternalImage({image:this._source,colorSpace:this._colorSpace}),this._textureFrameToken=this._sourceFrameToken),e}_getOrCreateCopiedTexture(){let e=this._getResolvedSize(),t=this._texture;if(t&&t.width===e.width&&t.height===e.height)return t;t?.destroy();let n=this.device.createTexture({id:`${this.id}-texture`,width:e.width,height:e.height,format:"rgba8unorm",usage:_e.Texture.SAMPLE|_e.Texture.COPY_DST,mipLevels:1,sampler:this._sampler});return this._texture=n,this._textureFrameToken=void 0,this._touchGeneration(),n}_createNativeExternalTexture(){return this._destroyExternalTexture(),this._externalTexture=this.device.createExternalTexture({id:`${this.id}-external`,source:this._source,colorSpace:this._colorSpace,sampler:this._sampler}),this.generation++,this._externalTexture}_destroyExternalTexture(){this._externalTexture?.destroy(),this._externalTexture=null}_getResolvedSize(){let e=Ri(this._source);return(0,_e.assert)(e.width>0&&e.height>0),e}_observeSource(){if(this.destroyed)return;let e=Jo(this._source);if(e!==this._isReady&&(this._isReady=e,this._touch()),!e)return;let t=Qo(this._source,this._sourceVersion);Object.is(t,this._sourceFrameToken)||(this._sourceFrameToken=t,this._touch())}_touch(){this._updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}};function Ke(i){return!i||typeof i!="object"?!1:typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement||"videoWidth"in i&&"videoHeight"in i&&"readyState"in i&&"currentTime"in i}function pr(i){return!i||typeof i!="object"?!1:typeof VideoFrame<"u"&&i instanceof VideoFrame||"displayWidth"in i&&"displayHeight"in i&&"timestamp"in i&&!("videoWidth"in i)}function Jo(i){let e=Ri(i);return e.width<=0||e.height<=0?!1:Ke(i)?i.readyState>=2:!0}function Ri(i){return Ke(i)?{width:i.videoWidth,height:i.videoHeight}:{width:i.displayWidth,height:i.displayHeight}}function Qo(i,e){return Ke(i)?`${e}:${i.currentTime}:${i.videoWidth}x${i.videoHeight}`:`${e}:${i.timestamp}:${i.displayWidth}x${i.displayHeight}`}var Ze=L(R(),1),vr=L(ae(),1);var se=L(R(),1),De=class{id;current;next;constructor(e){this.id=e.id||"swap",this.current=e.current,this.next=e.next}destroy(){this.current?.destroy(),this.next?.destroy()}swap(){let e=this.current;this.current=this.next,this.next=e}},Be=class extends De{constructor(e,t){t={...t};let{width:n=1,height:r=1}=t,s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-0`,format:c,usage:se.Texture.SAMPLE|se.Texture.RENDER|se.Texture.COPY_SRC|se.Texture.COPY_DST,width:n,height:r})),o=e.createFramebuffer({...t,colorAttachments:s});s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-1`,format:c,usage:se.Texture.SAMPLE|se.Texture.RENDER|se.Texture.COPY_SRC|se.Texture.COPY_DST,width:n,height:r}));let a=e.createFramebuffer({...t,colorAttachments:s});super({current:o,next:a});for(let[c,u]of(t.colorAttachments||[]).entries())typeof u=="string"&&(o.attachResource(o.colorAttachments[c].texture),a.attachResource(a.colorAttachments[c].texture))}resize(e){if(e.width===this.current.width&&e.height===this.current.height)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),gr(this.current),t.destroy(),this.next=n.clone(e),gr(this.next),n.destroy(),!0}};function gr(i){for(let e of i.colorAttachments)i.attachResource(e.texture);i.depthStencilAttachment&&i.attachResource(i.depthStencilAttachment.texture)}var Ht=class extends De{constructor(e,t){super({current:e.createBuffer(t),next:e.createBuffer(t)})}resize(e){if(e.byteLength===this.current.byteLength)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),t.destroy(),this.next=n.clone(e),n.destroy(),!0}};function xr(i){let{shaderPass:e,action:t,shadingLanguage:n}=i;switch(t){case"filter":let r=`${e.name}_filterColor_ext`;return n==="wgsl"?ea(r):ia(r);case"sample":let s=`${e.name}_sampleColor`;return n==="wgsl"?ta(s):na(s);default:throw new Error(`${e.name} no fragment shader generated for shader pass`)}}function ea(i){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
174
+ `}}function Ze(i,e,t){return Math.min(t,Math.max(e,i))}var na=new Fe({nlat:8,nlong:12,radius:1}),Ft=class extends le{constructor(e,t){super(e,t,{anchorMode:"centered",buildInstanceData:yr,geometry:na,idPrefix:"point-light-model",sizePropNames:["pointLightRadius"]})}};var ra={x:[2,0,1],y:[0,1,2],z:[1,2,0]},de=class extends z{constructor(e={}){let{id:t=O("truncated-code-geometry")}=e,{indices:n,attributes:r}=sa(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{POSITION:{size:3,value:r.POSITION},NORMAL:{size:3,value:r.NORMAL},TEXCOORD_0:{size:2,value:r.TEXCOORD_0},...e.attributes}})}};function sa(i={}){let{bottomRadius:e=0,topRadius:t=0,height:n=1,nradial:r=10,nvertical:s=10,verticalAxis:o="y",topCap:a=!1,bottomCap:c=!1}=i,h=(a?2:0)+(c?2:0),u=(r+1)*(s+1+h),d=Math.atan2(e-t,n),l=Math.sin,f=Math.cos,m=Math.PI,p=f(d),b=l(d),_=a?-2:0,M=s+(c?2:0),y=r+1,I=new Uint16Array(r*(s+h)*6),g=ra[o],x=new Float32Array(u*3),v=new Float32Array(u*3),w=new Float32Array(u*2),T=0,P=0;for(let S=_;S<=M;S++){let A=S/s,L=n*A,C;S<0?(L=0,A=1,C=e):S>s?(L=n,A=1,C=t):C=e+(t-e)*(S/s),(S===-2||S===s+2)&&(C=0,A=0),L-=n/2;for(let U=0;U<y;U++){let ee=l(U*m*2/r),q=f(U*m*2/r);x[T+g[0]]=ee*C,x[T+g[1]]=L,x[T+g[2]]=q*C,v[T+g[0]]=S<0||S>s?0:ee*p,v[T+g[1]]=S<0?-1:S>s?1:b,v[T+g[2]]=S<0||S>s?0:q*p,w[P+0]=U/r,w[P+1]=A,P+=2,T+=3}}for(let S=0;S<s+h;S++)for(let A=0;A<r;A++){let L=(S*r+A)*6;I[L+0]=y*(S+0)+0+A,I[L+1]=y*(S+0)+1+A,I[L+2]=y*(S+1)+1+A,I[L+3]=y*(S+0)+0+A,I[L+4]=y*(S+1)+1+A,I[L+5]=y*(S+1)+0+A}return{indices:I,attributes:{POSITION:x,NORMAL:v,TEXCOORD_0:w}}}var fe=class extends de{constructor(e={}){let{id:t=O("cone-geometry"),radius:n=1,cap:r=!0}=e;super({...e,id:t,topRadius:0,topCap:!!r,bottomCap:!!r,bottomRadius:n})}};var oa=new fe({cap:!0,nradial:16,nvertical:1,radius:1}),zt=class extends le{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:_r,geometry:oa,idPrefix:"spot-light-model",sizePropNames:["spotLightLength"]})}};var aa=new fe({cap:!0,nradial:12,nvertical:1,radius:1}),jt=class extends le{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:Ir,geometry:aa,idPrefix:"directional-light-model",sizePropNames:["directionalLightLength"]})}};function Gi(i,e){if(!i)throw new Error(e)}var re=class{id;matrix=new k;display=!0;position=new H;rotation=new H;scale=new H(1,1,1);userData={};props={};constructor(e={}){let{id:t}=e;this.id=t||O(this.constructor.name),this._setScenegraphNodeProps(e)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(e){return this._setScenegraphNodeProps(e),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(e){return Gi(e.length===3,"setPosition requires vector argument"),this.position=e,this}setRotation(e){return Gi(e.length===3||e.length===4,"setRotation requires vector argument"),this.rotation=e,this}setScale(e){return Gi(e.length===3,"setScale requires vector argument"),this.scale=e,this}setMatrix(e,t=!0){t?this.matrix.copy(e):this.matrix=e}setMatrixComponents(e){let{position:t,rotation:n,scale:r,update:s=!0}=e;return t&&this.setPosition(t),n&&this.setRotation(n),r&&this.setScale(r),s&&this.updateMatrix(),this}updateMatrix(){if(this.matrix.identity(),this.matrix.translate(this.position),this.rotation.length===4){let e=new k().fromQuaternion(this.rotation);this.matrix.multiplyRight(e)}else this.matrix.rotateXYZ(this.rotation);return this.matrix.scale(this.scale),this}update({position:e,rotation:t,scale:n}={}){return e&&this.setPosition(e),t&&this.setRotation(t),n&&this.setScale(n),this.updateMatrix(),this}getCoordinateUniforms(e,t){t=t||this.matrix;let n=new k(e).multiplyRight(t),r=n.invert(),s=r.transpose();return{viewMatrix:e,modelMatrix:t,objectMatrix:t,worldMatrix:n,worldInverseMatrix:r,worldInverseTransposeMatrix:s}}_setScenegraphNodeProps(e){e.display!==void 0&&(this.display=e.display),e?.position&&this.setPosition(e.position),e?.rotation&&this.setRotation(e.rotation),e?.scale&&this.setScale(e.scale),this.updateMatrix(),e?.matrix&&this.setMatrix(e.matrix),Object.assign(this.props,e)}};var wr=R(N(),1);function Gt(){return[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]]}function Ut(i,e,t){let n=new k(t);for(let r=0;r<8;r++){let s=new H(e[r&1?1:0][0],e[r&2?1:0][1],e[r&4?1:0][2]);n.transformAsPoint(s,s);for(let o=0;o<3;o++)i[0][o]=Math.min(i[0][o],s[o]),i[1][o]=Math.max(i[1][o],s[o])}}function $t(i){return Number.isFinite(i[0][0])}var Vt=class i extends re{children;constructor(e={}){e=Array.isArray(e)?{children:e}:e;let{children:t=[]}=e;wr.log.assert(t.every(n=>n instanceof re),"every child must an instance of ScenegraphNode"),super(e),this.children=t}getBounds(){let e=Gt();return this.traverse((t,{worldMatrix:n})=>{let r=t.getBounds();if(!r)return;let s=new k(n).multiplyRight(t.matrix);Ut(e,r,s)}),$t(e)?e:null}destroy(){this.children.forEach(e=>e.destroy()),this.removeAll(),super.destroy()}add(...e){for(let t of e)Array.isArray(t)?this.add(...t):this.children.push(t);return this}remove(e){let t=this.children,n=t.indexOf(e);return n>-1&&t.splice(n,1),this}removeAll(){return this.children=[],this}traverse(e,{worldMatrix:t=new k}={}){if(!this.display)return;let n=new k(t).multiplyRight(this.matrix);for(let r of this.children)r.display&&(r instanceof i?r.traverse(e,{worldMatrix:n}):e(r,{worldMatrix:n}))}traverseDepthSorted(e,{viewMatrix:t,worldMatrix:n=new k,order:r="back-to-front"}){let s=new k(t),o=[];this.traverse((c,h)=>{let u=c.getBounds(),d=u?new H(u[0]).add(u[1]).divide([2,2,2]):new H,l=new k(h.worldMatrix).multiplyRight(c.matrix);l.transformAsPoint(d,d),s.transformAsPoint(d,d),o.push({node:c,context:{worldMatrix:l,bounds:u,depth:-d[2]},index:o.length})},{worldMatrix:new k(n)});let a=r==="back-to-front"?-1:1;o.sort((c,h)=>a*(c.context.depth-h.context.depth)||c.index-h.index);for(let{node:c,context:h}of o)e(c,h)}preorderTraversal(e,{worldMatrix:t=new k}={}){let n=new k(t).multiplyRight(this.matrix);e(this,{worldMatrix:n});for(let r of this.children)r instanceof i?r.preorderTraversal(e,{worldMatrix:n}):e(r,{worldMatrix:n})}};var Xt=class extends re{model;instanceMatrices;bounds=null;managedResources;constructor(e){super(e),this.model=e.model,this.managedResources=e.managedResources||[],this.instanceMatrices=e.instanceMatrices||null,this.bounds=e.bounds?this.instanceMatrices?ca(e.bounds,this.instanceMatrices):e.bounds:null,this.setProps(e)}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach(e=>e.destroy()),this.managedResources=[]}getBounds(){return this.bounds}draw(e){return this.model.draw(e)}};function ca(i,e){let t=Gt();for(let n of e)Ut(t,i,n);return $t(t)?t:null}var Vi=R(N(),1),Ar=10,ha=1e-10;function Cr(i){let{positions:e,indices:t,attributes:n=[],preserveBoundary:r=!0}=i;(0,Vi.assert)(t.length%3===0&&e.length%3===0);let s=Math.max(0,Math.min(t.length,Math.floor((i.targetIndexCount??t.length*(i.targetRatio??.5))/3)*3));if(t.length===0||s>=t.length)return{indices:t.slice(),geometricError:0};let o=e.length/3,a=Array.from({length:o},()=>({quadric:new Float64Array(Ar),neighbors:new Set,boundaryNeighbors:new Set,triangles:new Set,active:!1,version:0})),c=[],h=new Map,u=new Map,d=new Hi,l=0,f=0,m=(g,x,v)=>{let w=Math.min(g,x),T=Math.max(g,x),P=w*o+T,A=(h.get(P)||0)+v;A<=0?(h.delete(P),a[g].neighbors.delete(x),a[x].neighbors.delete(g)):(h.set(P,A),a[g].neighbors.add(x),a[x].neighbors.add(g)),A===1?(a[g].boundaryNeighbors.add(x),a[x].boundaryNeighbors.add(g)):(a[g].boundaryNeighbors.delete(x),a[x].boundaryNeighbors.delete(g))},p=g=>{let x=c[g];if(!x.active)return;let[v,w,T]=x.vertices;u.delete(Er(v,w,T)),m(v,w,-1),m(w,T,-1),m(T,v,-1),a[v].triangles.delete(g),a[w].triangles.delete(g),a[T].triangles.delete(g),x.active=!1,l--},b=g=>{let x=c[g],[v,w,T]=x.vertices;if(v===w||w===T||T===v)return!1;let P=Er(v,w,T);return u.has(P)?!1:(u.set(P,g),m(v,w,1),m(w,T,1),m(T,v,1),a[v].triangles.add(g),a[w].triangles.add(g),a[T].triangles.add(g),a[v].active=!0,a[w].active=!0,a[T].active=!0,x.active=!0,l++,!0)};for(let g=0;g<t.length;g+=3){let x=t[g],v=t[g+1],w=t[g+2];(0,Vi.assert)(x<o&&v<o&&w<o);let T={vertices:[x,v,w],active:!1},P=c.push(T)-1;b(P)&&ua(a,e,x,v,w)}let _=(g,x)=>{if(!a[g].active||!a[x].active)return;let v=da(n,g,x);if(Number.isFinite(v))for(let[w,T]of[[g,x],[x,g]]){if(r&&!Sr(a,e,w,T))continue;let P=Math.max(0,la(a,e,g,x,w));d.add({retainedVertex:w,removedVertex:T,retainedVersion:a[w].version,removedVersion:a[T].version,geometricCost:P,cost:P+v})}};for(let g=0;g<a.length;g++)for(let x of a[g].neighbors)g<x&&_(g,x);for(;l*3>s;){let g=d.remove();if(!g)break;let{retainedVertex:x,removedVertex:v}=g,w=a[x],T=a[v];if(!w.active||!T.active||w.version!==g.retainedVersion||T.version!==g.removedVersion||!w.neighbors.has(v)||r&&!Sr(a,e,x,v)||!fa(c,a,e,x,v))continue;let P=new Set([x,v,...w.neighbors,...T.neighbors]),S=[...T.triangles];for(let A of S)p(A);for(let A of S){let L=c[A];for(let C=0;C<3;C++)L.vertices[C]===v&&(L.vertices[C]=x);b(A)}for(let A=0;A<Ar;A++)w.quadric[A]+=T.quadric[A];T.active=!1,f=Math.max(f,g.geometricCost);for(let A of P)a[A].version++;for(let A of P)if(a[A].active)for(let L of a[A].neighbors)_(A,L)}let M=t.constructor,y=new M(l*3),I=0;for(let g of c)g.active&&(y[I++]=g.vertices[0],y[I++]=g.vertices[1],y[I++]=g.vertices[2]);return{indices:y,geometricError:Math.sqrt(f)}}function ua(i,e,t,n,r){let s=Xi(e,t,n,r),o=Math.hypot(s[0],s[1],s[2]);if(o===0)return;let a=s[0]/o,c=s[1]/o,h=s[2]/o,u=-(a*e[t*3]+c*e[t*3+1]+h*e[t*3+2]),d=[a,c,h,u];for(let l of[t,n,r]){let f=0;for(let m=0;m<4;m++)for(let p=m;p<4;p++)i[l].quadric[f++]+=d[m]*d[p]}}function la(i,e,t,n,r){let s=[e[r*3],e[r*3+1],e[r*3+2],1],o=0,a=0;for(let c=0;c<4;c++)for(let h=c;h<4;h++){let u=i[t].quadric[o]+i[n].quadric[o];a+=u*s[c]*s[h]*(c===h?1:2),o++}return a}function da(i,e,t){let n=0;for(let r of i){let s=r.weight??1;if(s===0)continue;let o=r.values instanceof Uint8Array||r.values instanceof Uint16Array||r.values instanceof Uint32Array;for(let a=0;a<r.size;a++){let c=r.values[e*r.size+a]-r.values[t*r.size+a];if(o&&c!==0)return 1/0;n+=c*c*s}}return n}function Sr(i,e,t,n){let r=i[t].boundaryNeighbors.size>0,s=i[n].boundaryNeighbors.size>0;if(r!==s)return!1;if(!s)return!0;let o=i[n].boundaryNeighbors;if(o.size!==2||!o.has(t))return!1;let a=[...o].find(m=>m!==t);if(a===void 0)return!1;let c=Ht(e,t,n),h=Ht(e,a,n),u=Ui(c),d=Ui(h),l=[c[1]*h[2]-c[2]*h[1],c[2]*h[0]-c[0]*h[2],c[0]*h[1]-c[1]*h[0]];return c[0]*h[0]+c[1]*h[1]+c[2]*h[2]<=0&&Ui(l)<=ha*u*d}function fa(i,e,t,n,r){for(let s of e[r].triangles){let o=i[s];if(o.vertices.includes(n))continue;let a=Xi(t,...o.vertices),c=o.vertices.map(d=>d===r?n:d),h=Xi(t,...c);if(a[0]*h[0]+a[1]*h[1]+a[2]*h[2]<=0)return!1}return!0}function Xi(i,e,t,n){let r=Ht(i,t,e),s=Ht(i,n,e);return[r[1]*s[2]-r[2]*s[1],r[2]*s[0]-r[0]*s[2],r[0]*s[1]-r[1]*s[0]]}function Ht(i,e,t){return[i[e*3]-i[t*3],i[e*3+1]-i[t*3+1],i[e*3+2]-i[t*3+2]]}function Ui(i){return i[0]*i[0]+i[1]*i[1]+i[2]*i[2]}function Er(i,e,t){return[i,e,t].sort((n,r)=>n-r).join(":")}var Hi=class{entries=[];add(e){this.entries.push(e);let t=this.entries.length-1;for(;t>0;){let n=t-1>>1;if($i(this.entries[n],e)<=0)break;this.entries[t]=this.entries[n],this.entries[n]=e,t=n}}remove(){let e=this.entries[0],t=this.entries.pop();if(!e||!t||this.entries.length===0)return e;this.entries[0]=t;let n=0;for(;;){let r=n*2+1;if(r>=this.entries.length)break;let s=r+1,o=s<this.entries.length&&$i(this.entries[s],this.entries[r])<0?s:r;if($i(this.entries[n],this.entries[o])<=0)break;[this.entries[n],this.entries[o]]=[this.entries[o],this.entries[n]],n=o}return e}};function $i(i,e){return i.cost-e.cost||i.retainedVertex-e.retainedVertex||i.removedVertex-e.removedVertex}var Yt=class extends z{constructor(e={}){let{id:t=O("cube-geometry"),indices:n=!0}=e;super(n?{...e,id:t,topology:"triangle-list",indices:{size:1,value:ma},attributes:{...Ma,...e.attributes}}:{...e,id:t,topology:"triangle-list",indices:void 0,attributes:{...Ta,...e.attributes}})}},ma=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]),pa=new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1]),ga=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0]),xa=new Float32Array([0,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1]),ba=new Uint32Array([0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]),ya=new Float32Array([1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1]),_a=new Float32Array([1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0]),Ia=new Float32Array([1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1]),va=new Uint32Array([3,3,3,3,3,3,4,4,4,4,4,4,2,2,2,2,2,2,5,5,5,5,5,5,0,0,0,0,0,0,1,1,1,1,1,1]),Ma={POSITION:{size:3,value:pa},NORMAL:{size:3,value:ga},TEXCOORD_0:{size:2,value:xa},faceIndex:{size:1,value:ba}},Ta={POSITION:{size:3,value:ya},TEXCOORD_0:{size:2,value:_a},COLOR_0:{size:3,value:Ia},faceIndex:{size:1,value:va}};var Wt=class extends de{constructor(e={}){let{id:t=O("cylinder-geometry"),radius:n=1}=e;super({...e,id:t,bottomRadius:n,topRadius:n})}};var wa=[-1,0,0,0,1,0,0,0,-1,0,0,1,0,-1,0,1,0,0],Aa=[3,4,5,3,5,1,3,1,0,3,0,4,4,0,2,4,2,5,2,0,1,5,2,1],qt=class extends z{constructor(e={}){let{id:t=O("ico-sphere-geometry")}=e,{indices:n,attributes:r}=Sa(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Sa(i){let{iterations:e=0}=i,t=Math.PI,n=t*2,r=[...wa],s=[...Aa];r.push(),s.push();let o=(()=>{let u={};return(d,l)=>{d*=3,l*=3;let f=d<l?d:l,m=d>l?d:l,p=`${f}|${m}`;if(p in u)return u[p];let b=r[d],_=r[d+1],M=r[d+2],y=r[l],I=r[l+1],g=r[l+2],x=(b+y)/2,v=(_+I)/2,w=(M+g)/2,T=Math.sqrt(x*x+v*v+w*w);x/=T,v/=T,w/=T,r.push(x,v,w);let P=r.length/3-1;return u[p]=P,P}})();for(let u=0;u<e;u++){let d=[];for(let l=0;l<s.length;l+=3){let f=o(s[l+0],s[l+1]),m=o(s[l+1],s[l+2]),p=o(s[l+2],s[l+0]);d.push(p,s[l+0],f,f,s[l+1],m,m,s[l+2],p,f,m,p)}s=d}let a=new Array(r.length),c=new Array(r.length/3*2),h=s.length;for(let u=h-3;u>=0;u-=3){let d=s[u+0],l=s[u+1],f=s[u+2],m=d*3,p=l*3,b=f*3,_=d*2,M=l*2,y=f*2,I=r[m+0],g=r[m+1],x=r[m+2],v=Math.acos(x/Math.sqrt(I*I+g*g+x*x)),w=Math.atan2(g,I)+t,T=v/t,P=1-w/n,S=r[p+0],A=r[p+1],L=r[p+2],C=Math.acos(L/Math.sqrt(S*S+A*A+L*L)),U=Math.atan2(A,S)+t,ee=C/t,q=1-U/n,nt=r[b+0],rt=r[b+1],st=r[b+2],is=Math.acos(st/Math.sqrt(nt*nt+rt*rt+st*st)),ns=Math.atan2(rt,nt)+t,tn=is/t,ot=1-ns/n,rs=[nt-S,rt-A,st-L],ss=[I-S,g-A,x-L],W=new H(rs).cross(ss).normalize(),F;(P===0||q===0||ot===0)&&(P===0||P>.5)&&(q===0||q>.5)&&(ot===0||ot>.5)&&(r.push(r[m+0],r[m+1],r[m+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=T,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z,r.push(r[p+0],r[p+1],r[p+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=ee,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z,r.push(r[b+0],r[b+1],r[b+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=tn,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z),a[m+0]=a[p+0]=a[b+0]=W.x,a[m+1]=a[p+1]=a[b+1]=W.y,a[m+2]=a[p+2]=a[b+2]=W.z,c[_+0]=P,c[_+1]=T,c[M+0]=q,c[M+1]=ee,c[y+0]=ot,c[y+1]=tn}return{indices:{size:1,value:new Uint16Array(s)},attributes:{POSITION:{size:3,value:new Float32Array(r)},NORMAL:{size:3,value:new Float32Array(a)},TEXCOORD_0:{size:2,value:new Float32Array(c)}}}}var Kt=class extends z{constructor(e={}){let{id:t=O("plane-geometry")}=e,{indices:n,attributes:r}=Ea(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Ea(i){let{type:e="x,y",offset:t=0,flipCull:n=!1,unpack:r=!1}=i,s=e.split(","),o=i[`${s[0]}len`]||1,a=i[`${s[1]}len`]||1,c=i[`n${s[0]}`]||1,h=i[`n${s[1]}`]||1,u=(c+1)*(h+1),d=new Float32Array(u*3),l=new Float32Array(u*3),f=new Float32Array(u*2);n&&(o=-o);let m=0,p=0;for(let y=0;y<=h;y++)for(let I=0;I<=c;I++){let g=I/c,x=y/h;switch(f[m+0]=n?1-g:g,f[m+1]=x,e){case"x,y":d[p+0]=o*g-o*.5,d[p+1]=a*x-a*.5,d[p+2]=t,l[p+0]=0,l[p+1]=0,l[p+2]=n?1:-1;break;case"x,z":d[p+0]=o*g-o*.5,d[p+1]=t,d[p+2]=a*x-a*.5,l[p+0]=0,l[p+1]=n?1:-1,l[p+2]=0;break;case"y,z":d[p+0]=t,d[p+1]=o*g-o*.5,d[p+2]=a*x-a*.5,l[p+0]=n?1:-1,l[p+1]=0,l[p+2]=0;break;default:throw new Error("PlaneGeometry: unknown type")}m+=2,p+=3}let b=c+1,_=new Uint16Array(c*h*6);for(let y=0;y<h;y++)for(let I=0;I<c;I++){let g=(y*c+I)*6;_[g+0]=(y+0)*b+I,_[g+1]=(y+1)*b+I,_[g+2]=(y+0)*b+I+1,_[g+3]=(y+1)*b+I,_[g+4]=(y+1)*b+I+1,_[g+5]=(y+0)*b+I+1}let M={indices:{size:1,value:_},attributes:{POSITION:{size:3,value:d},NORMAL:{size:3,value:l},TEXCOORD_0:{size:2,value:f}}};return r?cn(M):M}function Pr(){let i=1,e=1;return()=>(i=Math.sin(e*17.23),e=Math.cos(i*27.92),Ca(Math.abs(i*e)*1432.71))}function Ca(i){return i-Math.floor(i)}var Or="";function Rr(i){Or=i}function Zt(i){return Pa(i)?i:Or+i}async function kr(i,e){let t=new Image,n=Zt(i);t.crossOrigin=e?.crossOrigin||"anonymous",t.src=n;try{await t.decode()}catch(r){throw Lr("decode",n,r)}try{return e?await createImageBitmap(t,e):await createImageBitmap(t)}catch(r){throw Lr("create",n,r)}}async function Nr(i,e){return await new Promise((t,n)=>{try{let r=new Image,s=Zt(i);r.onload=()=>t(r),r.onerror=()=>n(new Error(`Could not load image ${s}.`)),r.crossOrigin=e?.crossOrigin||"anonymous",r.src=s}catch(r){n(r)}})}function Lr(i,e,t){let n=t instanceof Error?t.message:String(t),r=i==="decode"?`Could not decode source image "${e}": ${n}`:`Could not create ImageBitmap from decoded image "${e}": ${n}`;return new Error(r,{cause:t})}function Pa(i){return i.startsWith("/")||/^[a-z][a-z\d+\-.]*:/i.test(i)}var Ie=R(N(),1);var Qt=class{device;id;destroyed=!1;generation=0;_source;_colorSpace;_sampler;_isReady=!1;_updateTimestamp;_sourceVersion=0;_sourceFrameToken=null;_texture=null;_textureFrameToken=void 0;_externalTexture=null;get source(){return this._source}get isReady(){return this._observeSource(),this._isReady}get updateTimestamp(){return this._observeSource(),this._updateTimestamp}get[Symbol.toStringTag](){return"VideoTexture"}toString(){let e=Yi(this._source);return`VideoTexture:"${this.id}":${e.width}x${e.height}px:(${this._isReady?"ready":"loading..."})`}constructor(e,t){(0,Ie.assert)(Qe(t?.source)||Dr(t?.source)),this.device=e,this.id=t.id||O("video-texture"),this._source=t.source,this._colorSpace=t.colorSpace??"srgb",this._sampler=t.sampler??{},this._updateTimestamp=this.device.incrementTimestamp(),this.setSource(t.source)}setSource(e){(0,Ie.assert)(Qe(e)||Dr(e)),this._destroyExternalTexture(),this._source=e,this._sourceVersion++,this._sourceFrameToken=null,this._textureFrameToken=void 0,this._observeSource(),this._touchGeneration()}resolveTextureBinding(e){return this._observeSource(),!this._isReady||this.destroyed?null:e.type==="external-texture"&&this.device.type==="webgpu"?this._createNativeExternalTexture():this._resolveCopiedTexture()}setSampler(e){this._sampler=e,this._texture?.setSampler(e),this._externalTexture?.setSampler?.(e),this._touchGeneration()}destroy(){this.destroyed||(this._destroyExternalTexture(),this._texture?.destroy(),this._texture=null,this._textureFrameToken=void 0,this._isReady=!1,this.destroyed=!0,this._touchGeneration())}_resolveCopiedTexture(){let e=this._getOrCreateCopiedTexture();return Object.is(this._textureFrameToken,this._sourceFrameToken)||(e.copyExternalImage({image:this._source,colorSpace:this._colorSpace}),this._textureFrameToken=this._sourceFrameToken),e}_getOrCreateCopiedTexture(){let e=this._getResolvedSize(),t=this._texture;if(t&&t.width===e.width&&t.height===e.height)return t;t?.destroy();let n=this.device.createTexture({id:`${this.id}-texture`,width:e.width,height:e.height,format:"rgba8unorm",usage:Ie.Texture.SAMPLE|Ie.Texture.COPY_DST,mipLevels:1,sampler:this._sampler});return this._texture=n,this._textureFrameToken=void 0,this._touchGeneration(),n}_createNativeExternalTexture(){return this._destroyExternalTexture(),this._externalTexture=this.device.createExternalTexture({id:`${this.id}-external`,source:this._source,colorSpace:this._colorSpace,sampler:this._sampler}),this.generation++,this._externalTexture}_destroyExternalTexture(){this._externalTexture?.destroy(),this._externalTexture=null}_getResolvedSize(){let e=Yi(this._source);return(0,Ie.assert)(e.width>0&&e.height>0),e}_observeSource(){if(this.destroyed)return;let e=La(this._source);if(e!==this._isReady&&(this._isReady=e,this._touch()),!e)return;let t=Oa(this._source,this._sourceVersion);Object.is(t,this._sourceFrameToken)||(this._sourceFrameToken=t,this._touch())}_touch(){this._updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}};function Qe(i){return!i||typeof i!="object"?!1:typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement||"videoWidth"in i&&"videoHeight"in i&&"readyState"in i&&"currentTime"in i}function Dr(i){return!i||typeof i!="object"?!1:typeof VideoFrame<"u"&&i instanceof VideoFrame||"displayWidth"in i&&"displayHeight"in i&&"timestamp"in i&&!("videoWidth"in i)}function La(i){let e=Yi(i);return e.width<=0||e.height<=0?!1:Qe(i)?i.readyState>=2:!0}function Yi(i){return Qe(i)?{width:i.videoWidth,height:i.videoHeight}:{width:i.displayWidth,height:i.displayHeight}}function Oa(i,e){return Qe(i)?`${e}:${i.currentTime}:${i.videoWidth}x${i.videoHeight}`:`${e}:${i.timestamp}:${i.displayWidth}x${i.displayHeight}`}var oe=R(N(),1),Vr=R(ce(),1);var se=R(N(),1),ze=class{id;current;next;constructor(e){this.id=e.id||"swap",this.current=e.current,this.next=e.next}destroy(){this.current?.destroy(),this.next?.destroy()}swap(){let e=this.current;this.current=this.next,this.next=e}},je=class extends ze{constructor(e,t){t={...t};let{width:n=1,height:r=1}=t,s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-0`,format:c,usage:se.Texture.SAMPLE|se.Texture.RENDER|se.Texture.COPY_SRC|se.Texture.COPY_DST,width:n,height:r})),o=e.createFramebuffer({...t,colorAttachments:s});s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-1`,format:c,usage:se.Texture.SAMPLE|se.Texture.RENDER|se.Texture.COPY_SRC|se.Texture.COPY_DST,width:n,height:r}));let a=e.createFramebuffer({...t,colorAttachments:s});super({current:o,next:a});for(let[c,h]of(t.colorAttachments||[]).entries())typeof h=="string"&&(o.attachResource(o.colorAttachments[c].texture),a.attachResource(a.colorAttachments[c].texture))}resize(e){if(e.width===this.current.width&&e.height===this.current.height)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),Br(this.current),t.destroy(),this.next=n.clone(e),Br(this.next),n.destroy(),!0}};function Br(i){for(let e of i.colorAttachments)i.attachResource(e.texture);i.depthStencilAttachment&&i.attachResource(i.depthStencilAttachment.texture)}var Jt=class extends ze{constructor(e,t){super({current:e.createBuffer(t),next:e.createBuffer(t)})}resize(e){if(e.byteLength===this.current.byteLength)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),t.destroy(),this.next=n.clone(e),n.destroy(),!0}};var B=R(N(),1),me=R(ce(),1);var Wi=2,Ra=1e4,Ge=class i{static defaultProps={...B.ComputePipeline.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",modules:[],defines:{},plugins:[],bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:me.ShaderAssembler.getDefaultShaderAssembler("wgsl"),debugShaders:void 0};device;id;pipelineFactory;shaderFactory;userData={};bindings={};pipeline;source;shader;shaderInputs;_uniformStore;_pipelineNeedsUpdate="newly created";_getModuleUniforms;props;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Computation is only supported in WebGPU");this.props={...i.defaultProps,...t},t=this.props,this.id=t.id||O("model"),this.device=e,Object.assign(this.userData,t.userData);let n=ka(e),r=(0,me.resolveShaderPlugins)(this.props.plugins,n.shaderLanguage);if(Object.keys(r.vertexInputs).length>0||Object.keys(r.varyings).length>0)throw new Error("Computation does not support ShaderPlugin vertex inputs or varyings");let s=(0,me.mergeShaderPluginModules)(this.props.modules,r.modules),o=Object.fromEntries(s.map(m=>[m.name,m]));this.shaderInputs=t.shaderInputs||new X(o),t.shaderInputs&&r.modules.length>0&&this.shaderInputs.addModules(r.modules),this.setShaderInputs(this.shaderInputs);let a=Lt(this.props.modules,this.shaderInputs?.getModules()),c={...r.defines,...this.props.defines};this.props.shaderLayout=Oe(this.props.shaderLayout,a)||null,this.pipelineFactory=t.pipelineFactory||B.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||B.ShaderFactory.getDefaultShaderFactory(this.device);let h=this.props.shaderAssembler;(0,B.assert)(h instanceof me.WGSLShaderAssembler);let{source:u,getUniforms:d,shaderLayout:l}=h.assembleWGSLShader({platformInfo:n,...this.props,modules:a,defines:c,scanVertexAttributes:!1,pluginInjections:r.injections});this.source=u,this._getModuleUniforms=d;let f=l??e.getShaderLayout?.(this.source,{scanVertexAttributes:!1});this.props.shaderLayout=Oe(this.props.shaderLayout||f||null,a)||null,this.pipeline=this._updatePipeline(),t.bindings&&this.setBindings(t.bindings)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(e){this.updateShaderInputs(e)}dispatch(e,t,n,r){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatch(t,n,r)}finally{this._logDrawCallEnd()}}dispatchIndirect(e,t,n=0){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatchIndirect(t,n)}finally{this._logDrawCallEnd()}}_setPipeline(e){this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),e.setPipeline(this.pipeline),e.setBindings({})}setVertexCount(e){}setInstanceCount(e){}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new B.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(Re(n)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}}setShaderModuleProps(e){let t=this._getModuleUniforms(e),n=Object.keys(t).filter(s=>{let o=t[s];return!He(o)&&typeof o!="number"&&typeof o!="boolean"}),r={};for(let s of n)r[s]=t[s],delete t[s]}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e)}setBindings(e){Object.assign(this.bindings,e)}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||e}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null;this.pipeline&&(B.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.shader),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debugShaders:this.props.debugShaders}),this.pipeline=this.pipelineFactory.createComputePipeline({...this.props,shader:this.shader}),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=B.log.level>3?0:Ra;B.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,B.log.group(Wi,`>>> DRAWING MODEL ${this.id}`,{collapsed:B.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=this.shaderInputs.getDebugTable();B.log.table(Wi,e)(),B.log.groupEnd(Wi)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(e,t){let n=B.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof B.Buffer?new n(e.debugData):e).toString()}};function ka(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}function Fr(i){let{shaderPass:e,action:t,shadingLanguage:n}=i;switch(t){case"filter":let r=`${e.name}_filterColor_ext`;return n==="wgsl"?Na(r):Ba(r);case"sample":let s=`${e.name}_sampleColor`;return n==="wgsl"?Da(s):Fa(s);default:throw new Error(`${e.name} no fragment shader generated for shader pass`)}}function Na(i){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
175
175
  @group(0) @binding(auto) var sourceTextureSampler: sampler;
176
176
 
177
177
  @fragment
@@ -183,7 +183,7 @@ fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {
183
183
  fragColor = ${i}(fragColor, texSize, texCoord);
184
184
  return fragColor;
185
185
  }
186
- `}function ta(i){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
186
+ `}function Da(i){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
187
187
  @group(0) @binding(auto) var sourceTextureSampler: sampler;
188
188
 
189
189
  @fragment
@@ -192,7 +192,7 @@ fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {
192
192
  let texSize = vec2f(textureDimensions(sourceTexture));
193
193
  return ${i}(sourceTexture, sourceTextureSampler, texSize, texCoord);
194
194
  }
195
- `}function ia(i){return`#version 300 es
195
+ `}function Ba(i){return`#version 300 es
196
196
 
197
197
  uniform sampler2D sourceTexture;
198
198
 
@@ -210,7 +210,7 @@ void main() {
210
210
  fragColor = texture(sourceTexture, texCoord);
211
211
  fragColor = ${i}(fragColor, texSize, texCoord);
212
212
  }
213
- `}function na(i){return`#version 300 es
213
+ `}function Fa(i){return`#version 300 es
214
214
 
215
215
  uniform sampler2D sourceTexture;
216
216
 
@@ -227,7 +227,7 @@ void main() {
227
227
 
228
228
  fragColor = ${i}(sourceTexture, texSize, texCoord);
229
229
  }
230
- `}var br={name:"textureTransform",source:`
230
+ `}var zr={name:"textureTransform",source:`
231
231
  struct textureTransformUniforms {
232
232
  scale: vec2<f32>,
233
233
  flipY: i32,
@@ -264,7 +264,7 @@ vec2 shaderPassRenderer_getRenderTargetUV(vec2 textureUV) {
264
264
  vec2 unscaledCoord = (textureUV - 0.5) * textureTransform.scale + 0.5;
265
265
  return textureTransform.flipY != 0 ? unscaledCoord : vec2(unscaledCoord.x, 1.0 - unscaledCoord.y);
266
266
  }
267
- `,uniformTypes:{scale:"vec2<f32>",flipY:"i32"}};var ra=new Set(["original","previous"]),Yt=class{device;shaderInputs;passRenderers;swapFramebuffers;textureModel;constructor(e,t){this.device=e;let n=sa(t.shaderPasses);n.map(a=>(0,vr.initializeShaderModule)(a));let r=n.reduce((a,c)=>({...a,[c.name]:c}),{});this.shaderInputs=t.shaderInputs||new V(r);let s=e.getCanvasContext().getDrawingBufferSize();this.swapFramebuffers=new Be(e,{colorAttachments:[t.colorFormat||e.preferredColorFormat],width:s[0],height:s[1]}),this.textureModel=new Le(e,{backgroundTexture:this.swapFramebuffers.current.colorAttachments[0].texture,flipY:t.flipY??e.type==="webgpu"});let o=t.flipY??e.type==="webgpu";this.passRenderers=t.shaderPasses.map(a=>new Ni(e,a,this.shaderInputs,o))}destroy(){for(let e of this.passRenderers)e.destroy();this.swapFramebuffers.destroy(),this.textureModel.destroy()}resize(e){e||=this.device.getCanvasContext().getDrawingBufferSize(),this.swapFramebuffers.resize({width:e[0],height:e[1]});for(let t of this.passRenderers)t.resize(e)}resetHistory(){for(let e of this.passRenderers)e.resetHistory()}renderToScreen(e){return this.encodeToScreen(this.device.commandEncoder,e)}encodeToScreen(e,t){let n=this.encodeToTexture(e,t);if(!n)return!1;let r=this.device.getDefaultCanvasContext().getCurrentFramebuffer({depthStencilFormat:!1});this.textureModel.setProps({backgroundTexture:n}),this.textureModel.predraw(e);let s=e.beginRenderPass({id:"shader-pass-renderer-to-screen",framebuffer:r,clearDepth:!1});return this.textureModel.draw(s),s.end(),!0}renderToTexture(e){return this.encodeToTexture(this.device.commandEncoder,e)}encodeToTexture(e,t){if(e.device!==this.device)throw new Error("ShaderPassRenderer command encoder must belong to the renderer device");let{sourceTexture:n}=t;if(n instanceof K&&!n.isReady)return null;let r=n instanceof K?n.texture:n;if(this.passRenderers.length===0)return r;t.resetHistory&&this.resetHistory(),this.textureModel.setProps({backgroundTexture:r}),this.textureModel.predraw(e);let s=fa(this.swapFramebuffers,r),o=e.beginRenderPass({id:"shader-pass-renderer-seed-source",framebuffer:s,clearColor:[0,0,0,1],clearDepth:!1});this.textureModel.draw(o),o.end();let a=s,c=Fi(s),u=!1;try{for(let h of this.passRenderers){h.initializeHistoryTargets(r,this.textureModel,e);for(let l of h.subPassExecutions){let d=l.output||"previous",m=d==="previous"?la(this.swapFramebuffers,a):h.getOutputFramebuffer(d),p=Fi(m),f=h.resolveBindings({execution:l,originalTexture:r,previousTexture:c,outputTexture:p,externalBindings:t.bindings||{}}),x=ca(this.shaderInputs,l,t.uniforms||{});l.subPassRenderer.prepare({commandEncoder:e,bindings:f,textureScale:ma(f.sourceTexture||c,p),uniforms:x});let y=e.beginRenderPass({id:"shader-pass-renderer-run-pass",framebuffer:m,clearColor:[0,0,0,1],clearDepth:1});l.subPassRenderer.draw(y),y.end(),d==="previous"?(c=p,a=m):h.markTargetWritten(d)}}u=!0}finally{for(let h of this.passRenderers)h.finishFrame(u)}return c}},Ni=class{device;shaderInputs;passDefinition;renderTargets;subPassExecutions;constructor(e,t,n,r){if(this.device=e,this.shaderInputs=n,this.passDefinition=t,Tr(t)){oa(t.name,t.renderTargets||{}),this.renderTargets=ha(e,t.renderTargets||{}),this.subPassExecutions=t.steps.flatMap(s=>this.createStepExecutions(t,s,r));return}yr(t,t.name),this.renderTargets={},this.subPassExecutions=this.createPassExecutions(t,{ownerName:t.name,flipY:r})}destroy(){for(let e of this.subPassExecutions)e.subPassRenderer.destroy();ua(this.renderTargets)}resize(e){da(this.device,this.renderTargets,e)}resetHistory(){for(let e of Object.values(this.renderTargets))e.historyInitialized=!1,e.writtenThisFrame=!1}initializeHistoryTargets(e,t,n){for(let r of Object.values(this.renderTargets)){if(r.spec.lifetime!=="history"||r.historyInitialized)continue;let s=Mr(r),o=r.spec.initialize||{clearColor:[0,0,0,0]};if(o==="original"){t.setProps({backgroundTexture:e}),t.predraw(n);let a=n.beginRenderPass({id:`${r.name}-initialize-history`,framebuffer:s,clearColor:[0,0,0,0],clearDepth:!1});t.draw(a),a.end()}else n.beginRenderPass({id:`${r.name}-clear-history`,framebuffer:s,clearColor:o.clearColor,clearDepth:!1}).end();r.historyInitialized=!0}}getOutputFramebuffer(e){return this.getRenderTarget(e).framebuffer}markTargetWritten(e){this.getRenderTarget(e).writtenThisFrame=!0}finishFrame(e){for(let t of Object.values(this.renderTargets)){if(e&&t.spec.lifetime==="history"&&t.writtenThisFrame){let n=Ir(t),r=Mr(t);t.historyTexture=t.texture,t.historyFramebuffer=t.framebuffer,t.texture=n,t.framebuffer=r,t.historyInitialized=!0}t.writtenThisFrame=!1}}getRenderTarget(e){let t=this.renderTargets[e];if(!t)throw new Error(`${this.getOwnerName()}: unknown render target "${e}"`);return t}resolveBindings(e){let{execution:t,originalTexture:n,previousTexture:r,outputTexture:s,externalBindings:o}=e,a=t.inputs||{sourceTexture:"previous"},c=this.shaderInputs.getModuleBindingValues(t.shaderPass.name),u=Object.fromEntries(Object.entries(o).filter(([d])=>t.shaderPass.bindingLayout?.some(m=>m.name===d))),h={...c,...u},l=t.output||"previous";for(let[d,m]of Object.entries(a)){if(!m)continue;let p=this.resolveInputTexture(m,n,r),f=m in this.renderTargets?this.renderTargets[m]:null;if(l!=="previous"&&m===l&&f?.spec.lifetime!=="history")throw new Error(`${t.ownerName}: subpass cannot read and write render target "${l}" in the same draw`);if(d==="sourceTexture"&&p===s)throw new Error(`${t.ownerName}: subpass cannot sample from the render target it is writing to`);h[d]=p}return"sourceTexture"in h||(h.sourceTexture=r),h}createStepExecutions(e,t,n){return yr(t.shaderPass,`${e.name}/${t.shaderPass.name}`),this.createPassExecutions(t.shaderPass,{ownerName:`${e.name}/${t.shaderPass.name}`,firstInputs:t.inputs,lastOutput:t.output,uniformOverrides:t.uniforms,flipY:n})}createPassExecutions(e,t){let n=e.passes||[];return n.map((r,s)=>{let o=s===0,a=s===n.length-1,c=o&&t.firstInputs!==void 0?t.firstInputs:r.inputs,u=a&&t.lastOutput!==void 0?t.lastOutput:r.output;return aa(t.ownerName,c,u,this.renderTargets),{ownerName:t.ownerName,shaderPass:e,subPassRenderer:new Di(this.device,e,r,t.flipY),inputs:c,output:u,uniforms:Bi(t.uniformOverrides,r.uniforms)}})}resolveInputTexture(e,t,n){switch(e){case"original":return t;case"previous":return n;default:{let r=this.getRenderTarget(e);return r.spec.lifetime==="history"&&!r.writtenThisFrame?Ir(r):r.texture}}}getOwnerName(){return this.passDefinition.name}},Di=class{model;shaderPass;subPass;flipY;constructor(e,t,n,r){this.shaderPass=t,this.subPass=n,this.flipY=r;let s=n.action||n.filter&&"filter"||n.sampler&&"sample"||"filter",o=xr({shaderPass:t,action:s,shadingLanguage:e.info.shadingLanguage});this.model=new he(e,{id:`${t.name}-subpass`,source:o,fs:o,modules:[br,t],parameters:{depthWriteEnabled:!1}})}destroy(){this.model.destroy()}prepare(e){let{commandEncoder:t,bindings:n,textureScale:r,uniforms:s}=e;this.model.shaderInputs.setProps({textureTransform:{scale:r,flipY:this.flipY?1:0}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:this.shaderPass.uniforms||{}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:s||{}}),this.model.setBindings(n||{}),this.model.predraw(t)}draw(e){this.model.draw(e)}};function sa(i){return i.flatMap(e=>Tr(e)?e.steps.map(t=>t.shaderPass):[e])}function Tr(i){return"steps"in i}function yr(i,e){let t=i.renderTargets;if(t&&Object.keys(t).length>0)throw new Error(`${e}: ShaderPass.renderTargets is not supported; use ShaderPassPipeline.renderTargets instead`)}function oa(i,e){for(let t of Object.keys(e))if(ra.has(t))throw new Error(`${i}: render target name "${t}" is reserved`)}function aa(i,e,t,n){let r=e||{sourceTexture:"previous"};for(let s of Object.values(r))if(s&&s!=="original"&&s!=="previous"&&!(s in n))throw new Error(`${i}: unknown input source "${s}"`);if(t&&t!=="previous"&&!(t in n))throw new Error(`${i}: unknown output target "${t}"`)}function Bi(i,e){if(!(!i&&!e))return{...i||{},...e||{}}}function ca(i,e,t){return Bi(Bi(i.getUniformValues()[e.shaderPass.name],e.uniforms),t[e.shaderPass.name])}function ha(i,e){let t=i.getCanvasContext().getDrawingBufferSize();return Object.entries(e).reduce((n,[r,s])=>({...n,[r]:wr(i,r,s,t)}),{})}function ua(i){for(let e of Object.values(i))e.framebuffer.destroy(),e.texture.destroy(),e.historyFramebuffer?.destroy(),e.historyTexture?.destroy()}function da(i,e,t){for(let n of Object.values(e)){let r=Ar(t,n.spec.scale);if(n.texture.width===r[0]&&n.texture.height===r[1])continue;n.framebuffer.destroy(),n.texture.destroy(),n.historyFramebuffer?.destroy(),n.historyTexture?.destroy();let s=wr(i,n.name,n.spec,t);n.texture=s.texture,n.framebuffer=s.framebuffer,n.historyTexture=s.historyTexture,n.historyFramebuffer=s.historyFramebuffer,n.historyInitialized=!1,n.writtenThisFrame=!1}}function wr(i,e,t,n){let r=Ar(n,t.scale),{texture:s,framebuffer:o}=_r(i,e,t,r),a,c;if(t.lifetime==="history"){let u=_r(i,`${e}-history`,t,r);a=u.texture,c=u.framebuffer}return{name:e,spec:t,texture:s,framebuffer:o,historyTexture:a,historyFramebuffer:c,historyInitialized:!1,writtenThisFrame:!1}}function _r(i,e,t,n){let r=i.createTexture({id:`${e}-texture`,width:n[0],height:n[1],format:t.format||i.preferredColorFormat,usage:Ze.Texture.SAMPLE|Ze.Texture.RENDER|Ze.Texture.COPY_SRC|Ze.Texture.COPY_DST,...t.sampler?{sampler:t.sampler}:{}}),s=i.createFramebuffer({id:`${e}-framebuffer`,width:n[0],height:n[1],colorAttachments:[r]});return{texture:r,framebuffer:s}}function Ir(i){if(!i.historyTexture)throw new Error(`${i.name}: transient render target has no history texture`);return i.historyTexture}function Mr(i){if(!i.historyFramebuffer)throw new Error(`${i.name}: transient render target has no history framebuffer`);return i.historyFramebuffer}function Ar(i,e=[1,1]){return[Math.max(1,Math.round(i[0]*e[0])),Math.max(1,Math.round(i[1]*e[1]))]}function Fi(i){let e=i.colorAttachments[0]?.texture;if(!e)throw new Error("ShaderPassRenderer: framebuffer is missing a color attachment texture");return e}function la(i,e){return e===i.current?i.next:i.current}function fa(i,e){return Fi(i.current)===e?i.next:i.current}function ma(i,e){let t=i.width/i.height,n=e.width/e.height;return n>t?[1,n/t]:[t/n,1]}var F=L(R(),1),Fe=L(ae(),1);var zi=2,pa=1e4,ji=class{device;id;pipelineFactory;shaderFactory;userData={};bindings={};pipeline;source;shader;shaderInputs;_uniformStore;_pipelineNeedsUpdate="newly created";_getModuleUniforms;props;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Computation is only supported in WebGPU");this.props={...ji.defaultProps,...t},t=this.props,this.id=t.id||S("model"),this.device=e,Object.assign(this.userData,t.userData);let n=ga(e),r=(0,Fe.resolveShaderPlugins)(this.props.plugins,n.shaderLanguage);if(Object.keys(r.vertexInputs).length>0||Object.keys(r.varyings).length>0)throw new Error("Computation does not support ShaderPlugin vertex inputs or varyings");let s=(0,Fe.mergeShaderPluginModules)(this.props.modules,r.modules),o=Object.fromEntries(s.map(d=>[d.name,d]));this.shaderInputs=t.shaderInputs||new V(o),t.shaderInputs&&r.modules.length>0&&this.shaderInputs.addModules(r.modules),this.setShaderInputs(this.shaderInputs);let a=bt(this.props.modules,this.shaderInputs?.getModules()),c={...r.defines,...this.props.defines};this.props.shaderLayout=we(this.props.shaderLayout,a)||null,this.pipelineFactory=t.pipelineFactory||F.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||F.ShaderFactory.getDefaultShaderFactory(this.device);let{source:u,getUniforms:h}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:n,...this.props,modules:a,defines:c,pluginInjections:r.injections});this.source=u,this._getModuleUniforms=h;let l=e.getShaderLayout?.(this.source);this.props.shaderLayout=we(this.props.shaderLayout||l||null,a)||null,this.pipeline=this._updatePipeline(),t.bindings&&this.setBindings(t.bindings)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(e){this.updateShaderInputs(e)}dispatch(e,t,n,r){try{this._logDrawCallStart(),this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),e.setPipeline(this.pipeline),e.setBindings({}),e.dispatch(t,n,r)}finally{this._logDrawCallEnd()}}setVertexCount(e){}setInstanceCount(e){}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new F.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(Ae(n)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}}setShaderModuleProps(e){let t=this._getModuleUniforms(e),n=Object.keys(t).filter(s=>{let o=t[s];return!Ue(o)&&typeof o!="number"&&typeof o!="boolean"}),r={};for(let s of n)r[s]=t[s],delete t[s]}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e)}setBindings(e){Object.assign(this.bindings,e)}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||e}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null;this.pipeline&&(F.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.shader),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debugShaders:this.props.debugShaders}),this.pipeline=this.pipelineFactory.createComputePipeline({...this.props,shader:this.shader}),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=F.log.level>3?0:pa;F.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,F.log.group(zi,`>>> DRAWING MODEL ${this.id}`,{collapsed:F.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=this.shaderInputs.getDebugTable();F.log.table(zi,e)(),F.log.groupEnd(zi)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(e,t){let n=F.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof F.Buffer?new n(e.debugData):e).toString()}},Je=ji;q(Je,"defaultProps",{...F.ComputePipeline.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",modules:[],defines:{},plugins:[],bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:Fe.ShaderAssembler.getDefaultShaderAssembler(),debugShaders:void 0});function ga(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}var J=L(R(),1);var xa=[0,1,1,1],z=-1,ba={isActive:"i32",indexMode:"i32",batchIndex:"i32",isHighlightActive:"i32",highlightedBatchIndex:"i32",highlightedObjectIndex:"i32",highlightColor:"vec4<f32>"},oe=`precision highp float;
267
+ `,uniformTypes:{scale:"vec2<f32>",flipY:"i32"}};var za=new Set(["original","previous"]),ei=class{device;shaderInputs;passRenderers;swapFramebuffers;textureModel;constructor(e,t){this.device=e;let n=ja(t.shaderPasses);n.map(a=>(0,Vr.initializeShaderModule)(a));let r=n.reduce((a,c)=>({...a,[c.name]:c}),{});this.shaderInputs=t.shaderInputs||new X(r);let s=e.getCanvasContext().getDrawingBufferSize();this.swapFramebuffers=new je(e,{colorAttachments:[t.colorFormat||e.preferredColorFormat],width:s[0],height:s[1]}),this.textureModel=new Be(e,{backgroundTexture:this.swapFramebuffers.current.colorAttachments[0].texture,flipY:t.flipY??e.type==="webgpu"});let o=t.flipY??e.type==="webgpu";this.passRenderers=t.shaderPasses.map(a=>new qi(e,a,this.shaderInputs,o))}destroy(){for(let e of this.passRenderers)e.destroy();this.swapFramebuffers.destroy(),this.textureModel.destroy()}resize(e){e||=this.device.getCanvasContext().getDrawingBufferSize(),this.swapFramebuffers.resize({width:e[0],height:e[1]});for(let t of this.passRenderers)t.resize(e)}resetHistory(){for(let e of this.passRenderers)e.resetHistory()}renderToScreen(e){return this.encodeToScreen(this.device.commandEncoder,e)}encodeToScreen(e,t){let n=this.encodeToTexture(e,t);if(!n)return!1;let r=this.device.getDefaultCanvasContext().getCurrentFramebuffer({depthStencilFormat:!1});this.textureModel.setProps({backgroundTexture:n}),this.textureModel.predraw(e);let s=e.beginRenderPass({id:"shader-pass-renderer-to-screen",framebuffer:r,clearDepth:!1});return this.textureModel.draw(s),s.end(),!0}renderToTexture(e){return this.encodeToTexture(this.device.commandEncoder,e)}encodeToTexture(e,t){if(e.device!==this.device)throw new Error("ShaderPassRenderer command encoder must belong to the renderer device");let{sourceTexture:n}=t;if(n instanceof K&&!n.isReady)return null;let r=n instanceof K?n.texture:n;if(this.passRenderers.length===0)return r;t.resetHistory&&this.resetHistory(),this.textureModel.setProps({backgroundTexture:r}),this.textureModel.predraw(e);let s=Za(this.swapFramebuffers,r),o=e.beginRenderPass({id:"shader-pass-renderer-seed-source",framebuffer:s,clearColor:[0,0,0,1],clearDepth:!1});this.textureModel.draw(o),o.end();let a=s,c=Ji(s),h=!1;try{for(let u of this.passRenderers){u.initializeHistoryTargets(r,this.textureModel,e),u.runComputeOptimization({commandEncoder:e,originalTexture:r,previousTexture:c,runtimeUniforms:t.uniforms||{}});for(let d of u.subPassExecutions){let l=d.output||"previous",f=l==="previous"?Ka(this.swapFramebuffers,a):u.getOutputFramebuffer(l),m=Ji(f),p=u.resolveBindings({execution:d,originalTexture:r,previousTexture:c,outputTexture:m,externalBindings:t.bindings||{}}),b=Va(this.shaderInputs,d,t.uniforms||{});d.subPassRenderer.prepare({commandEncoder:e,bindings:p,textureScale:Qa(p.sourceTexture||c,m),uniforms:b});let _=e.beginRenderPass({id:"shader-pass-renderer-run-pass",framebuffer:f,clearColor:[0,0,0,1],clearDepth:1});d.subPassRenderer.draw(_),_.end(),l==="previous"?(c=m,a=f):u.markTargetWritten(l)}}h=!0}finally{for(let u of this.passRenderers)u.finishFrame(h)}return c}},qi=class{device;shaderInputs;passDefinition;renderTargets;subPassExecutions;computeRenderer;constructor(e,t,n,r){if(this.device=e,this.shaderInputs=n,this.passDefinition=t,Xr(t)){Ua(t.name,t.renderTargets||{}),this.renderTargets=Xa(e,t.renderTargets||{}),Ga(e,t)&&(this.computeRenderer=new Ki(e,t.compute,this.renderTargets,n));let s=this.computeRenderer?t.steps.filter(o=>!t.compute.replacedPasses.includes(o.shaderPass.name)):t.steps;this.subPassExecutions=s.flatMap(o=>this.createStepExecutions(t,o,r));return}jr(t,t.name),this.renderTargets={},this.subPassExecutions=this.createPassExecutions(t,{ownerName:t.name,flipY:r})}destroy(){this.computeRenderer?.destroy();for(let e of this.subPassExecutions)e.subPassRenderer.destroy();Wa(this.renderTargets)}resize(e){qa(this.device,this.renderTargets,e)}runComputeOptimization(e){if(!this.computeRenderer)return;let t=this.resolveInputTexture(this.computeRenderer.optimization.input,e.originalTexture,e.previousTexture);this.computeRenderer.encode(e.commandEncoder,t,e.runtimeUniforms);for(let n of Object.values(this.computeRenderer.optimization.outputs))this.markTargetWritten(n)}resetHistory(){for(let e of Object.values(this.renderTargets))e.historyInitialized=!1,e.writtenThisFrame=!1}initializeHistoryTargets(e,t,n){for(let r of Object.values(this.renderTargets)){if(r.spec.lifetime!=="history"||r.historyInitialized)continue;let s=$r(r),o=r.spec.initialize||{clearColor:[0,0,0,0]};if(o==="original"){t.setProps({backgroundTexture:e}),t.predraw(n);let a=n.beginRenderPass({id:`${r.name}-initialize-history`,framebuffer:s,clearColor:[0,0,0,0],clearDepth:!1});t.draw(a),a.end()}else n.beginRenderPass({id:`${r.name}-clear-history`,framebuffer:s,clearColor:o.clearColor,clearDepth:!1}).end();r.historyInitialized=!0}}getOutputFramebuffer(e){return this.getRenderTarget(e).framebuffer}markTargetWritten(e){this.getRenderTarget(e).writtenThisFrame=!0}finishFrame(e){for(let t of Object.values(this.renderTargets)){if(e&&t.spec.lifetime==="history"&&t.writtenThisFrame){let n=Ur(t),r=$r(t);t.historyTexture=t.texture,t.historyFramebuffer=t.framebuffer,t.texture=n,t.framebuffer=r,t.historyInitialized=!0}t.writtenThisFrame=!1}}getRenderTarget(e){let t=this.renderTargets[e];if(!t)throw new Error(`${this.getOwnerName()}: unknown render target "${e}"`);return t}resolveBindings(e){let{execution:t,originalTexture:n,previousTexture:r,outputTexture:s,externalBindings:o}=e,a=t.inputs||{sourceTexture:"previous"},c=this.shaderInputs.getModuleBindingValues(t.shaderPass.name),h=Object.fromEntries(Object.entries(o).filter(([l])=>t.shaderPass.bindingLayout?.some(f=>f.name===l))),u={...c,...h},d=t.output||"previous";for(let[l,f]of Object.entries(a)){if(!f)continue;let m=this.resolveInputTexture(f,n,r),p=f in this.renderTargets?this.renderTargets[f]:null;if(d!=="previous"&&f===d&&p?.spec.lifetime!=="history")throw new Error(`${t.ownerName}: subpass cannot read and write render target "${d}" in the same draw`);if(m===s)throw new Error(`${t.ownerName}: subpass cannot sample from the render target it is writing to`);u[l]=m}return"sourceTexture"in u||(u.sourceTexture=r),u}createStepExecutions(e,t,n){return jr(t.shaderPass,`${e.name}/${t.shaderPass.name}`),this.createPassExecutions(t.shaderPass,{ownerName:`${e.name}/${t.shaderPass.name}`,firstInputs:t.inputs,lastOutput:t.output,uniformOverrides:t.uniforms,flipY:n})}createPassExecutions(e,t){let n=e.passes||[];return n.map((r,s)=>{let o=s===0,a=s===n.length-1,c=o&&t.firstInputs!==void 0?t.firstInputs:r.inputs,h=a&&t.lastOutput!==void 0?t.lastOutput:r.output;return $a(t.ownerName,c,h,this.renderTargets),{ownerName:t.ownerName,shaderPass:e,subPassRenderer:new Zi(this.device,e,r,t.flipY),inputs:c,output:h,uniforms:Qi(t.uniformOverrides,r.uniforms)}})}resolveInputTexture(e,t,n){switch(e){case"original":return t;case"previous":return n;default:{let r=this.getRenderTarget(e);return r.spec.lifetime==="history"&&!r.writtenThisFrame?Ur(r):r.texture}}}getOwnerName(){return this.passDefinition.name}},Ki=class{optimization;renderTargets;shaderInputs;computation;parameterBuffer;constructor(e,t,n,r){this.optimization=t,this.renderTargets=n,this.shaderInputs=r,this.parameterBuffer=e.createBuffer({id:`${t.name}-parameters`,byteLength:Math.max(Math.ceil(t.uniformNames.length/4)*16,16),usage:oe.Buffer.UNIFORM|oe.Buffer.COPY_DST});let s=Object.entries(t.outputs).map(([o,a],c)=>({name:o,type:"storage",group:0,location:c+2,access:"write-only",format:n[a].texture.format}));try{this.computation=new Ge(e,{id:t.name,source:t.source,shaderLayout:{bindings:[{name:t.uniformBinding,type:"uniform",group:0,location:0},{name:"sourceTexture",type:"texture",group:0,location:1,sampleType:"unfilterable-float"},...s]}})}catch(o){throw this.parameterBuffer.destroy(),o}}encode(e,t,n){let r={...this.shaderInputs.getUniformValues()[this.optimization.uniformModule]||{},...this.optimization.uniforms,...n[this.optimization.uniformModule]||{}},s=new Float32Array(Math.max(Math.ceil(this.optimization.uniformNames.length/4)*4,4));for(let[u,d]of this.optimization.uniformNames.entries()){let l=r[d];s[u]=typeof l=="number"?l:0}this.parameterBuffer.write(s);let o=Object.entries(this.optimization.outputs),a={[this.optimization.uniformBinding]:this.parameterBuffer,sourceTexture:t.view};for(let[u,d]of o)a[u]=this.renderTargets[d].texture.view;this.computation.setBindings(a),this.computation.predraw(e);let c=this.renderTargets[o[0][1]].texture,h=e.beginComputePass({id:this.optimization.name});this.computation.dispatch(h,Math.ceil(c.width/this.optimization.workgroupSize[0]),Math.ceil(c.height/this.optimization.workgroupSize[1]),1),h.end()}destroy(){this.computation.destroy(),this.parameterBuffer.destroy()}},Zi=class{model;shaderPass;subPass;flipY;constructor(e,t,n,r){this.shaderPass=t,this.subPass=n,this.flipY=r;let s=n.action||n.filter&&"filter"||n.sampler&&"sample"||"filter",o=Fr({shaderPass:t,action:s,shadingLanguage:e.info.shadingLanguage});this.model=new ue(e,{id:`${t.name}-subpass`,source:o,fs:o,modules:[zr,t],parameters:{depthWriteEnabled:!1}})}destroy(){this.model.destroy()}prepare(e){let{commandEncoder:t,bindings:n,textureScale:r,uniforms:s}=e;this.model.shaderInputs.setProps({textureTransform:{scale:r,flipY:this.flipY?1:0}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:this.shaderPass.uniforms||{}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:s||{}}),this.model.setBindings(n||{}),this.model.predraw(t)}draw(e){this.model.draw(e)}};function ja(i){return i.flatMap(e=>Xr(e)?e.steps.map(t=>t.shaderPass):[e])}function Xr(i){return"steps"in i}function Ga(i,e){let t=e.compute;if(!t||i.type!=="webgpu")return!1;let n=Object.values(t.outputs);return n.length===0||n.length>i.limits.maxStorageTexturesPerShaderStage||t.workgroupSize[0]>i.limits.maxComputeWorkgroupSizeX||t.workgroupSize[1]>i.limits.maxComputeWorkgroupSizeY||t.workgroupSize[0]*t.workgroupSize[1]>i.limits.maxComputeInvocationsPerWorkgroup?!1:n.every(r=>{let s=e.renderTargets?.[r];if(!s?.storage)return!1;let o=s.format||i.preferredColorFormat;return i.getTextureFormatCapabilities(o).store})}function jr(i,e){let t=i.renderTargets;if(t&&Object.keys(t).length>0)throw new Error(`${e}: ShaderPass.renderTargets is not supported; use ShaderPassPipeline.renderTargets instead`)}function Ua(i,e){for(let t of Object.keys(e))if(za.has(t))throw new Error(`${i}: render target name "${t}" is reserved`)}function $a(i,e,t,n){let r=e||{sourceTexture:"previous"};for(let s of Object.values(r))if(s&&s!=="original"&&s!=="previous"&&!(s in n))throw new Error(`${i}: unknown input source "${s}"`);if(t&&t!=="previous"&&!(t in n))throw new Error(`${i}: unknown output target "${t}"`)}function Qi(i,e){if(!(!i&&!e))return{...i||{},...e||{}}}function Va(i,e,t){return Qi(Qi(i.getUniformValues()[e.shaderPass.name],e.uniforms),t[e.shaderPass.name])}function Xa(i,e){let t=i.getCanvasContext().getDrawingBufferSize(),n={};for(let[r,s]of Object.entries(e)){if(s.aliasFor){let o=n[s.aliasFor];if(!o)throw new Error(`${r}: target alias references an unknown earlier target`);let a=en(t,s.scale),c=s.format||i.preferredColorFormat;if(s.lifetime==="history"||o.spec.lifetime==="history"||!Ha(s,o.spec)||o.texture.width!==a[0]||o.texture.height!==a[1]||o.texture.format!==c||s.storage&&!o.spec.storage||!Ya(s,o.spec))throw new Error(`${r}: target alias must match a transient target's size, format, and sampler`);n[r]=o;continue}n[r]=Hr(i,r,s,t)}return n}function Ha(i,e){let t=i.scale||[1,1],n=e.scale||[1,1];return t[0]===n[0]&&t[1]===n[1]}function Ya(i,e){let t=i.sampler||{},n=e.sampler||{},r=Object.entries(t);return r.length===Object.keys(n).length&&r.every(([s,o])=>n[s]===o)}function Wa(i){for(let e of new Set(Object.values(i)))e.framebuffer.destroy(),e.texture.destroy(),e.historyFramebuffer?.destroy(),e.historyTexture?.destroy()}function qa(i,e,t){for(let n of new Set(Object.values(e))){let r=en(t,n.spec.scale);if(n.texture.width===r[0]&&n.texture.height===r[1])continue;n.framebuffer.destroy(),n.texture.destroy(),n.historyFramebuffer?.destroy(),n.historyTexture?.destroy();let s=Hr(i,n.name,n.spec,t);n.texture=s.texture,n.framebuffer=s.framebuffer,n.historyTexture=s.historyTexture,n.historyFramebuffer=s.historyFramebuffer,n.historyInitialized=!1,n.writtenThisFrame=!1}}function Hr(i,e,t,n){let r=en(n,t.scale),{texture:s,framebuffer:o}=Gr(i,e,t,r),a,c;if(t.lifetime==="history"){let h=Gr(i,`${e}-history`,t,r);a=h.texture,c=h.framebuffer}return{name:e,spec:t,texture:s,framebuffer:o,historyTexture:a,historyFramebuffer:c,historyInitialized:!1,writtenThisFrame:!1}}function Gr(i,e,t,n){let r=i.createTexture({id:`${e}-texture`,width:n[0],height:n[1],format:t.format||i.preferredColorFormat,usage:oe.Texture.SAMPLE|oe.Texture.RENDER|oe.Texture.COPY_SRC|oe.Texture.COPY_DST|(t.storage&&i.type==="webgpu"&&i.getTextureFormatCapabilities(t.format||i.preferredColorFormat).store?oe.Texture.STORAGE:0),...t.sampler?{sampler:t.sampler}:{}}),s=i.createFramebuffer({id:`${e}-framebuffer`,width:n[0],height:n[1],colorAttachments:[r]});return{texture:r,framebuffer:s}}function Ur(i){if(!i.historyTexture)throw new Error(`${i.name}: transient render target has no history texture`);return i.historyTexture}function $r(i){if(!i.historyFramebuffer)throw new Error(`${i.name}: transient render target has no history framebuffer`);return i.historyFramebuffer}function en(i,e=[1,1]){return[Math.max(1,Math.round(i[0]*e[0])),Math.max(1,Math.round(i[1]*e[1]))]}function Ji(i){let e=i.colorAttachments[0]?.texture;if(!e)throw new Error("ShaderPassRenderer: framebuffer is missing a color attachment texture");return e}function Ka(i,e){return e===i.current?i.next:i.current}function Za(i,e){return Ji(i.current)===e?i.next:i.current}function Qa(i,e){let t=i.width/i.height,n=e.width/e.height;return n>t?[1,n/t]:[t/n,1]}var Z=R(N(),1);var Ja=[0,1,1,1],j=-1,ec={isActive:"i32",indexMode:"i32",batchIndex:"i32",isHighlightActive:"i32",highlightedBatchIndex:"i32",highlightedObjectIndex:"i32",highlightColor:"vec4<f32>"},ae=`precision highp float;
268
268
  precision highp int;
269
269
 
270
270
  layout(std140) uniform pickingUniforms {
@@ -277,7 +277,7 @@ layout(std140) uniform pickingUniforms {
277
277
  int highlightedObjectIndex;
278
278
  vec4 highlightColor;
279
279
  } picking;
280
- `,ze=`struct pickingUniforms {
280
+ `,Ue=`struct pickingUniforms {
281
281
  isActive: i32,
282
282
  indexMode: i32,
283
283
  batchIndex: i32,
@@ -289,9 +289,9 @@ layout(std140) uniform pickingUniforms {
289
289
  };
290
290
 
291
291
  @group(0) @binding(auto) var<uniform> picking: pickingUniforms;
292
- `;function ya(i={},e){let t={...e};switch(i.isActive!==void 0&&(t.isActive=Boolean(i.isActive)),i.indexMode){case"instance":t.indexMode=0;break;case"attribute":t.indexMode=1;break;case"vertex":t.indexMode=2;break;case void 0:break}switch(typeof i.batchIndex=="number"&&(t.batchIndex=i.batchIndex),i.highlightedObjectIndex){case void 0:break;case null:t.isHighlightActive=!1,t.highlightedObjectIndex=z;break;default:t.isHighlightActive=!0,t.highlightedObjectIndex=i.highlightedObjectIndex}switch(i.highlightedBatchIndex){case void 0:break;case null:t.isHighlightActive=!1,t.highlightedBatchIndex=z;break;default:t.isHighlightActive=!0,t.highlightedBatchIndex=i.highlightedBatchIndex}return i.highlightColor&&(t.highlightColor=i.highlightColor),t}var fe={props:{},uniforms:{},name:"picking",uniformTypes:ba,defaultUniforms:{isActive:!1,indexMode:0,batchIndex:0,isHighlightActive:!1,highlightedBatchIndex:z,highlightedObjectIndex:z,highlightColor:xa},getUniforms:ya};var Er=1,_a=new Int32Array([z,z,0,0]);var Sr=14,je=8;function qt(i,e="color",t=i==="webgpu"){if(e==="auto")return t?"index":"color";if(e==="index"&&!t)throw new Error(`Picking mode "${e}" requires WebGPU or a WebGL device that supports renderable rg32sint textures.`);return e}function et(i){return i.type==="webgpu"||i.type==="webgl"&&i.isTextureFormatRenderable("rg32sint")}var Lr=qt;function Cr(i){return{objectIndex:i[0]===z?null:i[0],batchIndex:i[1]===z?null:i[1]}}function Pr(i){let e=i[0]+i[1]*256+i[2]*65536;if(e===0)return{objectIndex:null,batchIndex:null};let t=i[3]>0?i[3]-1:0;return{objectIndex:e-1,batchIndex:t}}var Wt=class{device;props;mode;pickInfo={batchIndex:null,objectIndex:null};framebuffer=null;lastMousePosition=null;tooltipElement=null;constructor(e,t){this.device=e,this.props={...Wt.defaultProps,...t};let n=t.mode??t.backend??Wt.defaultProps.mode;this.props.mode=n,this.props.backend=n,this.mode=qt(this.device.type,n,et(this.device))}destroy(){this.framebuffer?.destroy(),this.tooltipElement?.remove(),this.tooltipElement=null}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.mode==="index"?this.createIndexFramebuffer():this.createColorFramebuffer()),this.framebuffer}clearPickState(){this.lastMousePosition=null,this.setPickingProps({highlightedBatchIndex:null,highlightedObjectIndex:null}),this.hideTooltip()}shouldPick(e,t={}){if(!e)return this.lastMousePosition&&this.clearPickState(),!1;let[n,r]=e;return!t.force&&this.lastMousePosition&&this.lastMousePosition[0]===n&&this.lastMousePosition[1]===r?!1:(this.lastMousePosition=[n,r],!0)}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getDefaultCanvasContext().getDevicePixelSize()),this.setPickingProps({isActive:!0}),this.mode==="index"?this.device.beginRenderPass({framebuffer:e,clearColors:[new Float32Array([0,0,0,0]),_a],clearDepth:1}):this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}async updatePickInfo(e){let t=this.getFramebuffer(),n=this.getPickPosition(e),r=await this.readPickInfo(t,n);return r?(this.hasPickInfoChanged(r)&&(this.pickInfo=r,this.props.onObjectPicked(r)),this.updateTooltip(r,e),this.setPickingProps({isActive:!1,highlightedBatchIndex:r.batchIndex,highlightedObjectIndex:r.objectIndex}),this.pickInfo):null}getPickPosition(e){let t=this.device.type!=="webgpu",n=this.device.getDefaultCanvasContext().cssToDevicePixels(e,t),r=n.x+Math.floor(n.width/2),s=n.y+Math.floor(n.height/2);return[r,s]}createIndexFramebuffer(){let e=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:J.Texture.RENDER_ATTACHMENT}),t=this.device.createTexture({format:"rg32sint",width:1,height:1,usage:J.Texture.RENDER_ATTACHMENT|J.Texture.COPY_SRC});return this.device.createFramebuffer({colorAttachments:[e,t],depthStencilAttachment:"depth24plus"})}createColorFramebuffer(){let e=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:J.Texture.RENDER_ATTACHMENT|J.Texture.COPY_SRC});return this.device.createFramebuffer({colorAttachments:[e],depthStencilAttachment:"depth24plus"})}setPickingProps(e){this.props.shaderInputs?.setProps({picking:e})}async readPickInfo(e,t){return this.mode==="index"?this.readIndexPickInfo(e,t):this.readColorPickInfo(e,t)}async readIndexPickInfo(e,[t,n]){if(this.device.type==="webgpu"){let s=e.colorAttachments[Er]?.texture;if(!s)return null;let o=s.computeMemoryLayout({width:1,height:1}),a=this.device.createBuffer({byteLength:o.byteLength,usage:J.Buffer.COPY_DST|J.Buffer.MAP_READ});try{s.readBuffer({x:t,y:n,width:1,height:1},a);let c=await a.readAsync(0,o.byteLength);return Cr(new Int32Array(c.buffer,c.byteOffset,2))}finally{a.destroy()}}let r=this.device.readPixelsToArrayWebGL(e,{sourceX:t,sourceY:n,sourceWidth:1,sourceHeight:1,sourceAttachment:Er});return r?Cr(new Int32Array(r.buffer,r.byteOffset,2)):null}async readColorPickInfo(e,[t,n]){if(this.device.type==="webgpu"){let s=e.colorAttachments[0]?.texture;if(!s)return null;let o=s.computeMemoryLayout({width:1,height:1}),a=this.device.createBuffer({byteLength:o.byteLength,usage:J.Buffer.COPY_DST|J.Buffer.MAP_READ});try{s.readBuffer({x:t,y:n,width:1,height:1},a);let c=await a.readAsync(0,o.byteLength);return Pr(new Uint8Array(c.buffer,c.byteOffset,4))}finally{a.destroy()}}let r=this.device.readPixelsToArrayWebGL(e,{sourceX:t,sourceY:n,sourceWidth:1,sourceHeight:1,sourceAttachment:0});return r?Pr(new Uint8Array(r.buffer,r.byteOffset,4)):null}hasPickInfoChanged(e){return e.objectIndex!==this.pickInfo.objectIndex||e.batchIndex!==this.pickInfo.batchIndex}updateTooltip(e,t){let n=this.props.getTooltip(e);if(!n){this.hideTooltip();return}let r=this.getOrCreateTooltipElement();r&&(r.textContent=n,r.style.display="block",this.positionTooltip(r,t))}hideTooltip(){this.tooltipElement&&(this.tooltipElement.style.display="none")}getOrCreateTooltipElement(){if(this.tooltipElement)return this.tooltipElement;if(typeof document>"u"||typeof window>"u"||typeof HTMLCanvasElement>"u"||typeof this.device.getDefaultCanvasContext!="function")return null;let e=this.device.getDefaultCanvasContext().canvas;if(!(e instanceof HTMLCanvasElement)||!e.parentElement)return null;let t=document.createElement("div");t.style.position="absolute",t.style.zIndex="12",t.style.display="none",t.style.maxWidth="220px",t.style.padding="8px 10px",t.style.borderRadius="6px",t.style.background="rgba(15, 23, 42, 0.92)",t.style.color="#f8fafc",t.style.font="600 13px/1.35 system-ui, sans-serif",t.style.pointerEvents="none",t.style.whiteSpace="nowrap",t.style.boxShadow="0 10px 24px rgba(15, 23, 42, 0.22)";let n=e.parentElement;return window.getComputedStyle(n).position==="static"&&(n.style.position="relative"),n.appendChild(t),this.tooltipElement=t,t}positionTooltip(e,t){if(typeof HTMLCanvasElement>"u"||typeof this.device.getDefaultCanvasContext!="function")return;let n=this.device.getDefaultCanvasContext().canvas;if(!(n instanceof HTMLCanvasElement))return;let r=Math.max(je,n.clientWidth-e.offsetWidth-je),s=Math.max(je,n.clientHeight-e.offsetHeight-je),o=Math.min(t[0]+Sr,r),a=Math.min(t[1]+Sr,s);e.style.left=`${Math.max(je,o)}px`,e.style.top=`${Math.max(je,a)}px`}},Qe=Wt;q(Qe,"defaultProps",{shaderInputs:void 0,onObjectPicked:()=>{},getTooltip:()=>null,mode:"color",backend:"color"});var Ia=`${ze}
292
+ `;function tc(i={},e){let t={...e};switch(i.isActive!==void 0&&(t.isActive=!!i.isActive),i.indexMode){case"instance":t.indexMode=0;break;case"attribute":t.indexMode=1;break;case"vertex":t.indexMode=2;break;case void 0:break}switch(typeof i.batchIndex=="number"&&(t.batchIndex=i.batchIndex),i.highlightedObjectIndex){case void 0:break;case null:t.isHighlightActive=!1,t.highlightedObjectIndex=j;break;default:t.isHighlightActive=!0,t.highlightedObjectIndex=i.highlightedObjectIndex}switch(i.highlightedBatchIndex){case void 0:break;case null:t.isHighlightActive=!1,t.highlightedBatchIndex=j;break;default:t.isHighlightActive=!0,t.highlightedBatchIndex=i.highlightedBatchIndex}return i.highlightColor&&(t.highlightColor=i.highlightColor),t}var pe={props:{},uniforms:{},name:"picking",uniformTypes:ec,defaultUniforms:{isActive:!1,indexMode:0,batchIndex:0,isHighlightActive:!1,highlightedBatchIndex:j,highlightedObjectIndex:j,highlightColor:Ja},getUniforms:tc};var Yr=1,ic=new Int32Array([j,j,0,0]);var Wr=14,$e=8;function ii(i,e="color",t=i==="webgpu"){if(e==="auto")return t?"index":"color";if(e==="index"&&!t)throw new Error(`Picking mode "${e}" requires WebGPU or a WebGL device that supports renderable rg32sint textures.`);return e}function Je(i){return i.type==="webgpu"||i.type==="webgl"&&i.isTextureFormatRenderable("rg32sint")}var Zr=ii;function qr(i){return{objectIndex:i[0]===j?null:i[0],batchIndex:i[1]===j?null:i[1]}}function Kr(i){let e=i[0]+i[1]*256+i[2]*65536;if(e===0)return{objectIndex:null,batchIndex:null};let t=i[3]>0?i[3]-1:0;return{objectIndex:e-1,batchIndex:t}}var ti=class i{device;props;mode;pickInfo={batchIndex:null,objectIndex:null};framebuffer=null;lastMousePosition=null;tooltipElement=null;static defaultProps={shaderInputs:void 0,onObjectPicked:()=>{},getTooltip:()=>null,mode:"color",backend:"color"};constructor(e,t){this.device=e,this.props={...i.defaultProps,...t};let n=t.mode??t.backend??i.defaultProps.mode;this.props.mode=n,this.props.backend=n,this.mode=ii(this.device.type,n,Je(this.device))}destroy(){this.framebuffer?.destroy(),this.tooltipElement?.remove(),this.tooltipElement=null}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.mode==="index"?this.createIndexFramebuffer():this.createColorFramebuffer()),this.framebuffer}clearPickState(){this.lastMousePosition=null,this.setPickingProps({highlightedBatchIndex:null,highlightedObjectIndex:null}),this.hideTooltip()}shouldPick(e,t={}){if(!e)return this.lastMousePosition&&this.clearPickState(),!1;let[n,r]=e;return!t.force&&this.lastMousePosition&&this.lastMousePosition[0]===n&&this.lastMousePosition[1]===r?!1:(this.lastMousePosition=[n,r],!0)}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getDefaultCanvasContext().getDevicePixelSize()),this.setPickingProps({isActive:!0}),this.mode==="index"?this.device.beginRenderPass({framebuffer:e,clearColors:[new Float32Array([0,0,0,0]),ic],clearDepth:1}):this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}async updatePickInfo(e){let t=this.getFramebuffer(),n=this.getPickPosition(e),r=await this.readPickInfo(t,n);return r?(this.hasPickInfoChanged(r)&&(this.pickInfo=r,this.props.onObjectPicked(r)),this.updateTooltip(r,e),this.setPickingProps({isActive:!1,highlightedBatchIndex:r.batchIndex,highlightedObjectIndex:r.objectIndex}),this.pickInfo):null}getPickPosition(e){let t=this.device.type!=="webgpu",n=this.device.getDefaultCanvasContext().cssToDevicePixels(e,t),r=n.x+Math.floor(n.width/2),s=n.y+Math.floor(n.height/2);return[r,s]}createIndexFramebuffer(){let e=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:Z.Texture.RENDER_ATTACHMENT}),t=this.device.createTexture({format:"rg32sint",width:1,height:1,usage:Z.Texture.RENDER_ATTACHMENT|Z.Texture.COPY_SRC});return this.device.createFramebuffer({colorAttachments:[e,t],depthStencilAttachment:"depth24plus"})}createColorFramebuffer(){let e=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:Z.Texture.RENDER_ATTACHMENT|Z.Texture.COPY_SRC});return this.device.createFramebuffer({colorAttachments:[e],depthStencilAttachment:"depth24plus"})}setPickingProps(e){this.props.shaderInputs?.setProps({picking:e})}async readPickInfo(e,t){return this.mode==="index"?this.readIndexPickInfo(e,t):this.readColorPickInfo(e,t)}async readIndexPickInfo(e,[t,n]){if(this.device.type==="webgpu"){let s=e.colorAttachments[Yr]?.texture;if(!s)return null;let o=s.computeMemoryLayout({width:1,height:1}),a=this.device.createBuffer({byteLength:o.byteLength,usage:Z.Buffer.COPY_DST|Z.Buffer.MAP_READ});try{s.readBuffer({x:t,y:n,width:1,height:1},a);let c=await a.readAsync(0,o.byteLength);return qr(new Int32Array(c.buffer,c.byteOffset,2))}finally{a.destroy()}}let r=this.device.readPixelsToArrayWebGL(e,{sourceX:t,sourceY:n,sourceWidth:1,sourceHeight:1,sourceAttachment:Yr});return r?qr(new Int32Array(r.buffer,r.byteOffset,2)):null}async readColorPickInfo(e,[t,n]){if(this.device.type==="webgpu"){let s=e.colorAttachments[0]?.texture;if(!s)return null;let o=s.computeMemoryLayout({width:1,height:1}),a=this.device.createBuffer({byteLength:o.byteLength,usage:Z.Buffer.COPY_DST|Z.Buffer.MAP_READ});try{s.readBuffer({x:t,y:n,width:1,height:1},a);let c=await a.readAsync(0,o.byteLength);return Kr(new Uint8Array(c.buffer,c.byteOffset,4))}finally{a.destroy()}}let r=this.device.readPixelsToArrayWebGL(e,{sourceX:t,sourceY:n,sourceWidth:1,sourceHeight:1,sourceAttachment:0});return r?Kr(new Uint8Array(r.buffer,r.byteOffset,4)):null}hasPickInfoChanged(e){return e.objectIndex!==this.pickInfo.objectIndex||e.batchIndex!==this.pickInfo.batchIndex}updateTooltip(e,t){let n=this.props.getTooltip(e);if(!n){this.hideTooltip();return}let r=this.getOrCreateTooltipElement();r&&(r.textContent=n,r.style.display="block",this.positionTooltip(r,t))}hideTooltip(){this.tooltipElement&&(this.tooltipElement.style.display="none")}getOrCreateTooltipElement(){if(this.tooltipElement)return this.tooltipElement;if(typeof document>"u"||typeof window>"u"||typeof HTMLCanvasElement>"u"||typeof this.device.getDefaultCanvasContext!="function")return null;let e=this.device.getDefaultCanvasContext().canvas;if(!(e instanceof HTMLCanvasElement)||!e.parentElement)return null;let t=document.createElement("div");t.style.position="absolute",t.style.zIndex="12",t.style.display="none",t.style.maxWidth="220px",t.style.padding="8px 10px",t.style.borderRadius="6px",t.style.background="rgba(15, 23, 42, 0.92)",t.style.color="#f8fafc",t.style.font="600 13px/1.35 system-ui, sans-serif",t.style.pointerEvents="none",t.style.whiteSpace="nowrap",t.style.boxShadow="0 10px 24px rgba(15, 23, 42, 0.22)";let n=e.parentElement;return window.getComputedStyle(n).position==="static"&&(n.style.position="relative"),n.appendChild(t),this.tooltipElement=t,t}positionTooltip(e,t){if(typeof HTMLCanvasElement>"u"||typeof this.device.getDefaultCanvasContext!="function")return;let n=this.device.getDefaultCanvasContext().canvas;if(!(n instanceof HTMLCanvasElement))return;let r=Math.max($e,n.clientWidth-e.offsetWidth-$e),s=Math.max($e,n.clientHeight-e.offsetHeight-$e),o=Math.min(t[0]+Wr,r),a=Math.min(t[1]+Wr,s);e.style.left=`${Math.max($e,o)}px`,e.style.top=`${Math.max($e,a)}px`}};var nc=`${Ue}
293
293
 
294
- const COLOR_PICKING_INVALID_INDEX = ${z};
294
+ const COLOR_PICKING_INVALID_INDEX = ${j};
295
295
  const COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
296
296
  const COLOR_PICKING_MAX_BATCH_INDEX = 254;
297
297
 
@@ -360,12 +360,12 @@ fn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {
360
360
 
361
361
  return color;
362
362
  }
363
- `,Ma=`${oe}
363
+ `,rc=`${ae}
364
364
 
365
365
  const int INDEX_PICKING_MODE_INSTANCE = 0;
366
366
  const int INDEX_PICKING_MODE_CUSTOM = 1;
367
367
 
368
- const int COLOR_PICKING_INVALID_INDEX = ${z};
368
+ const int COLOR_PICKING_INVALID_INDEX = ${j};
369
369
 
370
370
  flat out int picking_objectIndex;
371
371
 
@@ -379,9 +379,9 @@ void picking_setObjectIndex(int objectIndex) {
379
379
  break;
380
380
  }
381
381
  }
382
- `,va=`${oe}
382
+ `,sc=`${ae}
383
383
 
384
- const int COLOR_PICKING_INVALID_INDEX = ${z};
384
+ const int COLOR_PICKING_INVALID_INDEX = ${j};
385
385
  const int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
386
386
  const int COLOR_PICKING_MAX_BATCH_INDEX = 254;
387
387
 
@@ -452,9 +452,9 @@ vec4 picking_filterColor(vec4 color) {
452
452
  outColor = picking_filterPickingColor(outColor);
453
453
  return outColor;
454
454
  }
455
- `,tt={...fe,name:"picking",source:Ia,vs:Ma,fs:va};var Ta=`${ze}
455
+ `,et={...pe,name:"picking",source:nc,vs:rc,fs:sc};var oc=`${Ue}
456
456
 
457
- const COLOR_PICKING_INVALID_INDEX = ${z};
457
+ const COLOR_PICKING_INVALID_INDEX = ${j};
458
458
  const COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
459
459
  const COLOR_PICKING_MAX_BATCH_INDEX = 254;
460
460
 
@@ -542,7 +542,7 @@ fn picking_filterColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {
542
542
  outColor = picking_filterPickingColor(outColor, objectIndex);
543
543
  return outColor;
544
544
  }
545
- `,wa=`${oe}
545
+ `,ac=`${ae}
546
546
 
547
547
  const int INDEX_PICKING_MODE_INSTANCE = 0;
548
548
  const int INDEX_PICKING_MODE_ATTRIBUTE = 1;
@@ -563,9 +563,9 @@ void picking_setObjectIndex(int objectIndex) {
563
563
  break;
564
564
  }
565
565
  }
566
- `,Aa=`${oe}
566
+ `,cc=`${ae}
567
567
 
568
- const int COLOR_PICKING_INVALID_INDEX = ${z};
568
+ const int COLOR_PICKING_INVALID_INDEX = ${j};
569
569
  const int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
570
570
  const int COLOR_PICKING_MAX_BATCH_INDEX = 254;
571
571
 
@@ -636,12 +636,12 @@ vec4 picking_filterColor(vec4 color) {
636
636
  outColor = picking_filterPickingColor(outColor);
637
637
  return outColor;
638
638
  }
639
- `,Kt={...fe,name:"picking",source:Ta,vs:wa,fs:Aa};var Ea=`${ze}
639
+ `,ni={...pe,name:"picking",source:oc,vs:ac,fs:cc};var hc=`${Ue}
640
640
 
641
641
  const INDEX_PICKING_MODE_INSTANCE = 0;
642
642
  const INDEX_PICKING_MODE_ATTRIBUTE = 1;
643
643
  const INDEX_PICKING_MODE_VERTEX = 2;
644
- const INDEX_PICKING_INVALID_INDEX = ${z}; // 2^32 - 1
644
+ const INDEX_PICKING_INVALID_INDEX = ${j}; // 2^32 - 1
645
645
 
646
646
  /**
647
647
  * WGSL shaders need to carry the returned object index through their own stage outputs.
@@ -696,13 +696,13 @@ fn picking_getPickingColor(objectIndex: i32) -> vec2<i32> {
696
696
  return vec2<i32>(objectIndex, picking.batchIndex);
697
697
  }
698
698
 
699
- `,Sa=`${oe}
699
+ `,uc=`${ae}
700
700
 
701
701
  const int INDEX_PICKING_MODE_INSTANCE = 0;
702
702
  const int INDEX_PICKING_MODE_ATTRIBUTE = 1;
703
703
  const int INDEX_PICKING_MODE_VERTEX = 2;
704
704
 
705
- const int INDEX_PICKING_INVALID_INDEX = ${z}; // 2^32 - 1
705
+ const int INDEX_PICKING_INVALID_INDEX = ${j}; // 2^32 - 1
706
706
 
707
707
  flat out int picking_objectIndex;
708
708
 
@@ -723,9 +723,9 @@ void picking_setObjectIndex(int objectIndex) {
723
723
  break;
724
724
  }
725
725
  }
726
- `,Ca=`${oe}
726
+ `,lc=`${ae}
727
727
 
728
- const int INDEX_PICKING_INVALID_INDEX = ${z}; // 2^32 - 1
728
+ const int INDEX_PICKING_INVALID_INDEX = ${j}; // 2^32 - 1
729
729
 
730
730
  flat in int picking_objectIndex;
731
731
 
@@ -791,6 +791,6 @@ vec4 picking_filterColor(vec4 color) {
791
791
  outColor = picking_filterPickingColor(outColor);
792
792
  return outColor;
793
793
  }
794
- `,it={...fe,name:"picking",source:Ea,vs:Sa,fs:Ca};var Or={...fe,name:"picking",source:it.source,vs:tt.vs,fs:tt.fs};function kr(i){return et(i)?it:Kt}var Zt=class{device;framebuffer=null;shaderInputs;constructor(e,t){this.device=e,this.shaderInputs=t}destroy(){this.framebuffer?.destroy()}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.device.createFramebuffer({colorAttachments:["rgba8unorm"],depthStencilAttachment:"depth24plus"})),this.framebuffer}clearPickState(){this.shaderInputs.setProps({picking:{highlightedObjectColor:null}})}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getCanvasContext().getDevicePixelSize()),this.shaderInputs.setProps({picking:{isActive:!0}}),this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}updatePickState(e){let t=this.getFramebuffer(),[n,r]=this.getPickPosition(e),o=[...this.device.readPixelsToArrayWebGL(t,{sourceX:n,sourceY:r,sourceWidth:1,sourceHeight:1})].map(c=>c/255);o[0]+o[1]+o[2]>0||(o=null),this.shaderInputs.setProps({picking:{isActive:!1,highlightedObjectColor:o}})}getPickPosition(e){let t=this.device.getCanvasContext().cssToDevicePixels(e),n=t.x+Math.floor(t.width/2),r=t.y+Math.floor(t.height/2);return[n,r]}};var Rr=L(ae(),1),Nr=Rr.picking;var Pa=K;return Yr(nt);})();
794
+ `,tt={...pe,name:"picking",source:hc,vs:uc,fs:lc};var Qr={...pe,name:"picking",source:tt.source,vs:et.vs,fs:et.fs};function Jr(i){return Je(i)?tt:ni}var ri=class{device;framebuffer=null;shaderInputs;constructor(e,t){this.device=e,this.shaderInputs=t}destroy(){this.framebuffer?.destroy()}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.device.createFramebuffer({colorAttachments:["rgba8unorm"],depthStencilAttachment:"depth24plus"})),this.framebuffer}clearPickState(){this.shaderInputs.setProps({picking:{highlightedObjectColor:null}})}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getCanvasContext().getDevicePixelSize()),this.shaderInputs.setProps({picking:{isActive:!0}}),this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}updatePickState(e){let t=this.getFramebuffer(),[n,r]=this.getPickPosition(e),o=[...this.device.readPixelsToArrayWebGL(t,{sourceX:n,sourceY:r,sourceWidth:1,sourceHeight:1})].map(c=>c/255);o[0]+o[1]+o[2]>0||(o=null),this.shaderInputs.setProps({picking:{isActive:!1,highlightedObjectColor:o}})}getPickPosition(e){let t=this.device.getCanvasContext().cssToDevicePixels(e),n=t.x+Math.floor(t.width/2),r=t.y+Math.floor(t.height/2);return[n,r]}};var es=R(ce(),1),ts=es.picking;var dc=K;return ds(it);})();
795
795
  return __exports__;
796
796
  });