@zylem/game-lib 0.7.0 → 0.8.2

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 (98) hide show
  1. package/README.md +15 -1
  2. package/dist/actions.d.ts +71 -8
  3. package/dist/actions.js +1 -1
  4. package/dist/api/game-lib.api.json +55350 -0
  5. package/dist/api/game-lib.api.md +4608 -0
  6. package/dist/api/game-lib.d.ts +8447 -0
  7. package/dist/api/game-lib.typedoc.json +352456 -0
  8. package/dist/audio.js +1 -1
  9. package/dist/{base-node-life-cycle-CnJ-7zX-.d.ts → base-node-life-cycle-BK9xebT9.d.ts} +18 -4
  10. package/dist/behavior.d.ts +2 -3
  11. package/dist/behavior.js +1 -1
  12. package/dist/blueprints-TbGY-h53.d.ts +162 -0
  13. package/dist/chunk-3PRBSSTS.js +24 -0
  14. package/dist/chunk-47DG7I7M.js +1 -0
  15. package/dist/chunk-7GYFZKK7.js +1 -0
  16. package/dist/chunk-7QF6YTEZ.js +1 -0
  17. package/dist/chunk-7WRQ2UAN.js +1 -0
  18. package/dist/chunk-BH53MBAZ.js +1 -0
  19. package/dist/chunk-BIGH6D34.js +0 -0
  20. package/dist/chunk-CD7ZOZ35.js +1 -0
  21. package/dist/chunk-CFVRRRZZ.js +1 -0
  22. package/dist/chunk-CM5YRNBJ.js +19 -0
  23. package/dist/chunk-COM6HJ2L.js +1 -0
  24. package/dist/chunk-D2PATZCC.js +1 -0
  25. package/dist/chunk-DFLI7ICU.js +0 -0
  26. package/dist/chunk-EVYHPR3J.js +1 -0
  27. package/dist/chunk-IPWUDOV5.js +1 -0
  28. package/dist/chunk-JNFFTNMH.js +1 -0
  29. package/dist/chunk-JQKS42G4.js +1 -0
  30. package/dist/chunk-KVSJE4XD.js +1 -0
  31. package/dist/chunk-MZZCDXFB.js +1 -0
  32. package/dist/chunk-ORIDWL3T.js +0 -0
  33. package/dist/{chunk-RXDTAWI2.js → chunk-PCFF4LLO.js} +1 -1
  34. package/dist/chunk-QB3NL7VQ.js +1 -0
  35. package/dist/chunk-TAUWDQZF.js +9 -0
  36. package/dist/chunk-UG22Z42P.js +1 -0
  37. package/dist/chunk-VS2D4B3W.js +1 -0
  38. package/dist/chunk-WQ3WMMZD.js +1 -0
  39. package/dist/chunk-XK63E4SX.js +1 -0
  40. package/dist/chunk-YAOXFYOD.js +1 -0
  41. package/dist/chunk-ZRT3ZQVH.js +1 -0
  42. package/dist/collision-builder-B_tm8OVy.d.ts +49 -0
  43. package/dist/core.d.ts +45 -30
  44. package/dist/core.js +1 -24
  45. package/dist/debug-state-DRoeasG2.d.ts +17 -0
  46. package/dist/debug.d.ts +71 -19
  47. package/dist/debug.js +1 -1
  48. package/dist/{default-controls-BGc61yYl.d.ts → default-controls-CAKJ5zlo.d.ts} +3 -3
  49. package/dist/entity-B9yZeBm4.d.ts +34 -0
  50. package/dist/{entity-DNkYKfdp.d.ts → entity-BGEq1yfC.d.ts} +91 -444
  51. package/dist/{entity-type-map-C94h2TDW.d.ts → entity-type-map-CW6RHQkx.d.ts} +153 -6
  52. package/dist/entity.d.ts +15 -10
  53. package/dist/entity.js +1 -1
  54. package/dist/events.d.ts +10 -1
  55. package/dist/events.js +1 -1
  56. package/dist/{game-Cuj5gy7U.d.ts → game-DbqBQiFC.d.ts} +460 -135
  57. package/dist/game-default-6AZZCNST.js +1 -0
  58. package/dist/{game-interfaces-tfpM5NBk.d.ts → game-interfaces-vF5sRi1n.d.ts} +8 -2
  59. package/dist/globals.d.ts +12 -1
  60. package/dist/globals.js +1 -1
  61. package/dist/graphics.d.ts +16 -46
  62. package/dist/graphics.js +1 -1
  63. package/dist/input-ui.d.ts +5 -4
  64. package/dist/input-ui.js +1 -1
  65. package/dist/input.d.ts +48 -4
  66. package/dist/input.js +1 -1
  67. package/dist/{material-Wz83vTTp.d.ts → material-DbSuZBbP.d.ts} +25 -50
  68. package/dist/public.d.ts +38 -0
  69. package/dist/public.js +1 -0
  70. package/dist/runtime.d.ts +7 -381
  71. package/dist/runtime.js +1 -1
  72. package/dist/schema/entity.schema.json +244 -0
  73. package/dist/schema/game-config.schema.json +643 -0
  74. package/dist/schema/input-config.schema.json +517 -0
  75. package/dist/schema/stage-config.schema.json +93 -0
  76. package/dist/schema/stage.schema.json +271 -0
  77. package/dist/schema.d.ts +550 -0
  78. package/dist/schema.js +1 -0
  79. package/dist/stage-transition-CmGpV4tc.d.ts +46 -0
  80. package/dist/vector-DN6zlPoE.d.ts +161 -0
  81. package/dist/web-components.d.ts +15 -12
  82. package/dist/web-components.js +1 -9
  83. package/dist/{zylem-stage-runtime-Cs-UDEVU.d.ts → zylem-camera-Du2UPW9O.d.ts} +74 -264
  84. package/package.json +28 -20
  85. package/dist/chunk-73VZQZUL.js +0 -1
  86. package/dist/chunk-A34ZG3L4.js +0 -1
  87. package/dist/chunk-CDPY4VOQ.js +0 -1
  88. package/dist/chunk-DR6XXZE7.js +0 -19
  89. package/dist/chunk-FM5TBEPO.js +0 -1
  90. package/dist/chunk-G2IIMSUH.js +0 -1
  91. package/dist/chunk-MSC2BEO5.js +0 -1
  92. package/dist/chunk-NIH5CONO.js +0 -1
  93. package/dist/chunk-ONWXGBWB.js +0 -1
  94. package/dist/chunk-QEDQDR27.js +0 -1
  95. package/dist/chunk-WKHW2QO2.js +0 -1
  96. package/dist/chunk-YHKXQ2ZN.js +0 -1
  97. package/dist/game-default-PZLLHYL7.js +0 -1
  98. package/dist/world-C9zdyl5d.d.ts +0 -103
@@ -0,0 +1 @@
1
+ import{b as Ge,c as at}from"./chunk-VS2D4B3W.js";import{a as m,d as we,f as Ie,g as Ze,h as ze,i as Ve}from"./chunk-JQKS42G4.js";import{a as K,b as qe}from"./chunk-YAOXFYOD.js";import{B as Xe,a as O,k as He,l as je,m as Ke,n as T,o as B,r as Qe,s as Ee,z as j}from"./chunk-KVSJE4XD.js";import{e as x,f as Me,g as Ye,h as $e}from"./chunk-CM5YRNBJ.js";import{a as Ne,b as A}from"./chunk-YHEWKN7N.js";import{a as Q,b as Je,c as Y,d as et,e as tt,f as it,g as rt,m as $}from"./chunk-D2PATZCC.js";import{c as H,d as Pe,j as S}from"./chunk-4QLJUQSJ.js";import{c as b,i as We,j as g}from"./chunk-7WRQ2UAN.js";import{a as st}from"./chunk-BH53MBAZ.js";import{l as Ue}from"./chunk-UG22Z42P.js";import{Vector2 as ct,RenderTarget as Kt,HalfFloatType as Qt}from"three";import{WebGPURenderer as Yt,RenderPipeline as $t}from"three/webgpu";import{pass as qt,renderOutput as ut,screenCoordinate as Xt,vec2 as De,vec4 as gt,fract as mt,sin as pt,dot as ht,texture as Jt,uniform as ei}from"three/tsl";import{setConsoleFunction as Ht,getConsoleFunction as jt}from"three";var nt="THREE.Abstract function.",ot=!1,lt=!1;function dt(){if(ot)return;ot=!0;let s=jt();Ht((e,t,...i)=>{if(e==="warn"&&t===nt){lt||(lt=!0,console.warn(`${nt} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(s){s(e,t,...i);return}let r=i[0],a=e==="log"?console.log:e==="error"?console.error:console.warn;r&&r.isStackTrace&&typeof r.getError=="function"?a(r.getError(t)):a(t,...i)})}var ft={x:0,y:0,width:1,height:1};async function lr(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var q=class{renderer;postProcessing=null;renderScale=1;screenResolution;_initialized=!1;_sceneRef=null;_lastAnimationTimestamp=null;_postEffects=[];_postSceneRef=null;_postCameraRef=null;_transition=null;constructor(e){this.screenResolution=e||new ct(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(dt(),this.renderer=new Yt({antialias:!0,alpha:!0}),await this.renderer.init(),this.renderer.setSize(this.screenResolution.x,this.screenResolution.y),this.renderer.shadowMap.enabled=!0,this._initialized=!0)}setScene(e){this._sceneRef=e}setupPostProcessing(e,t){this.disposePostProcessing(),this._postSceneRef=e,this._postCameraRef=t;let i=new $t(this.renderer),r=qt(e,t);this.renderScale!==1&&r.setResolutionScale(this.renderScale);let a=r;for(let l of this._postEffects)try{a=l(a,{scenePass:r,scene:e,camera:t})}catch(d){console.error("RendererManager: post-processing effect failed, skipping.",d)}i.outputColorTransform=!1;let n=ut(a),o=this._transition;if(o)try{n=gt(o.resolved.shader({fromNode:o.fromNode,toNode:n,progress:o.progressUniform})),o.composed=!0}catch(l){console.error("RendererManager: stage transition shader failed, skipping.",l)}i.outputNode=n.add(ii()),this.postProcessing=i}get transitionActive(){return this._transition!==null}beginSnapshotTransition(e,t,i){this.finishTransition();let r=new ct;this.renderer.getDrawingBufferSize(r);let a=new Kt(Math.max(1,r.x),Math.max(1,r.y),{type:Qt}),n=this.renderer.getRenderTarget();try{this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(a),this.renderer.render(t,i)}catch(o){console.error("RendererManager: failed to capture transition snapshot.",o)}finally{this.renderer.setRenderTarget(n)}this._transition={resolved:e,progressUniform:ei(0),fromNode:ut(Jt(a.texture)),elapsed:0,snapshotTarget:a,composed:!1}}finishTransition(){let e=this._transition;if(e){this._transition=null,e.progressUniform.value=1,this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef);try{e.resolved.onComplete?.()}catch(t){console.error("RendererManager: transition onComplete failed.",t)}this.releaseTransitionResources(e)}}cancelTransition(){let e=this._transition;if(e){this._transition=null;try{e.resolved.onComplete?.()}catch{}this.releaseTransitionResources(e)}}releaseTransitionResources(e){try{e.snapshotTarget?.dispose()}catch{}}advanceTransition(e){let t=this._transition;if(!t||!t.composed)return;t.elapsed+=e;let i=Math.min(t.elapsed/t.resolved.duration,1);t.progressUniform.value=t.resolved.easing(i),i>=1&&this.finishTransition()}setPostProcessingEffects(e){this._postEffects=[...e],this.postProcessing&&this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef)}setRenderScale(e){this.renderScale=Math.max(1,Number.isFinite(e)?e:1)}disposePostProcessing(){try{this.postProcessing?.dispose?.()}catch{}this.postProcessing=null}startRenderLoop(e){this._lastAnimationTimestamp=null,this.renderer.setAnimationLoop(t=>{let i=this._lastAnimationTimestamp===null?0:Math.max(0,(t-this._lastAnimationTimestamp)/1e3);this._lastAnimationTimestamp=t,this.advanceTransition(i),e(i)})}stopRenderLoop(){this._lastAnimationTimestamp=null;try{this.renderer.setAnimationLoop(null)}catch{}}renderCamera(e,t,i=!1){let r=t.viewport,a=this.screenResolution.x,n=this.screenResolution.y,o=Math.floor(r.x*a),l=Math.floor(r.y*n),d=Math.floor(r.width*a),c=Math.floor(r.height*n);this.renderer.setViewport(o,l,d,c),this.renderer.setScissor(o,l,d,c),this.renderer.setScissorTest(!0),i&&this.postProcessing?this.postProcessing.render():this.renderer.render(e,t.camera)}renderCameraToTarget(e,t){if(!t.renderTarget)return;let i=this.renderer.getRenderTarget();this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(t.renderTarget),this.renderer.clear(),this.renderer.render(e,t.camera),this.renderer.setRenderTarget(i)}renderCameras(e,t){if(!e||t.length===0)return;this.renderer.setScissorTest(!1),this.renderer.clear();let i=t.length===1&&ti(t[0].viewport);for(let r of t)this.renderCamera(e,r,i);this.renderer.setScissorTest(!1)}render(e,t){this.postProcessing?this.postProcessing.render():this.renderer.render(e,t)}resize(e,t){this.screenResolution.set(e,t),this.renderer.setSize(e,t,!1)}setPixelRatio(e){let t=Math.max(1,Number.isFinite(e)?e:1);this.renderer.setPixelRatio(t)}getDomElement(){return this.renderer.domElement}dispose(){this.stopRenderLoop(),this.cancelTransition(),this.disposePostProcessing();try{this.renderer.dispose()}catch{}this._sceneRef=null,this._postSceneRef=null,this._postCameraRef=null,this._postEffects=[],this._initialized=!1}};function ti(s){return s.x===0&&s.y===0&&s.width===1&&s.height===1}function ii(){let s=Xt.xy,e=mt(pt(ht(s,De(12.9898,78.233))).mul(43758.5453)),t=mt(pt(ht(s.add(De(13,7)),De(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return gt(i,i,i,0)}function F(s){return s?.category??"none"}function I(s){let e=F(s);return e==="environment"||e==="pack"}function R(s){return s.isInstanced===!0||s.isBundled===!0}import{BundleGroup as ri}from"three/webgpu";var X=class{bundles=new Map;entityToBundle=new Map;scene=null;setScene(e){this.scene=e}register(e,t,i,r){if(e.isBundled)return!0;let a=e.mesh??e.group;if(!a)return!1;let n=this.getOrCreateBundle(r);return a.matrixAutoUpdate=!0,a.userData.zylemEntityUuid=e.uuid,a.parent&&a.parent.remove(a),n.add(a),n.needsUpdate=!0,e.isBundled=!0,e.bundleKey=r,this.entityToBundle.set(e.uuid,r),!0}unregister(e){let t=this.entityToBundle.get(e.uuid);if(!t)return;let i=this.bundles.get(t),r=e.mesh??e.group;i&&r&&(i.remove(r),i.needsUpdate=!0),e.isBundled=!1,e.bundleKey=null,this.entityToBundle.delete(e.uuid)}getStats(){return{bundleCount:this.bundles.size,entityCount:this.entityToBundle.size}}dispose(){for(let e of this.bundles.values())this.scene&&this.scene.remove(e);this.bundles.clear(),this.entityToBundle.clear()}getOrCreateBundle(e){let t=this.bundles.get(e);return t||(t=new ri,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as yt,Matrix4 as Z,Vector3 as bt,Quaternion as ai}from"three";var z=class s{packs=new Map;entityToPack=new Map;scene=null;static DEFAULT_CAPACITY=128;static GROWTH_FACTOR=2;setScene(e){this.scene=e}static generatePackKey(e){let t={geo:`${e.geometryType}:${Me(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Ye(Me(t))}static generateEntityPackKey(e){let t=e.options;if(t.runtime?.packKeyOverride)return t.runtime.packKeyOverride;let i=e.constructor?.type?.description||"unknown",r=t.size||{x:1,y:1,z:1},a=t.material||{};return s.generatePackKey({geometryType:i,dimensions:{x:r.x,y:r.y,z:r.z},materialPath:a.path||null,shaderType:a.shader?"custom":"standard",colorHex:a.color?.getHex?.()||t.color?.getHex?.()||16777215})}register(e,t,i,r){let a=this.packs.get(r);a||(a=this.createPack(r,t,i));let n;return a.freeIndices.length>0?n=a.freeIndices.pop():(n=a.entities.length,n>=a.capacity&&this.growPack(a),a.entities.push(null)),a.entities[n]=e,a.entityMap.set(e.uuid,n),this.entityToPack.set(e.uuid,r),a.instancedMesh.count=Math.max(a.instancedMesh.count,n+1),a.activeIndices.push(n),a.dirtyIndices.add(n),n}unregister(e){let t=this.entityToPack.get(e.uuid);if(!t)return;let i=this.packs.get(t);if(!i)return;let r=i.entityMap.get(e.uuid);if(r===void 0)return;i.entities[r]=null,i.entityMap.delete(e.uuid),this.entityToPack.delete(e.uuid),i.freeIndices.push(r);let a=i.activeIndices.indexOf(r);if(a!==-1){let o=i.activeIndices.pop();a<i.activeIndices.length&&(i.activeIndices[a]=o)}i.dirtyIndices.delete(r);let n=new Z;n.makeScale(0,0,0),i.instancedMesh.setMatrixAt(r,n),i.instancedMesh.instanceMatrix.needsUpdate=!0}markDirty(e){let t=this.entityToPack.get(e.uuid);if(!t)return;let i=this.packs.get(t);if(!i)return;let r=i.entityMap.get(e.uuid);r!==void 0&&i.dirtyIndices.add(r)}update(e=0){let t=new Z,i=new bt,r=new ai,a=new bt(1,1,1);for(let n of this.packs.values()){if(n.activeIndices.length===0)continue;let o=!1;for(let l of n.activeIndices){let d=n.entities[l];if(!d)continue;if(He(d)){t.makeScale(0,0,0),n.instancedMesh.setMatrixAt(l,t),o=!0;continue}let c=n.dirtyIndices.has(l),u=!!d.body;if(!(!c&&!u)){if(!c&&u){let h=d.body;if(typeof h.isRenderSleeping=="function"&&h.isRenderSleeping())continue}this.updateInstanceMatrix(n,l,t,i,r,a,e),o=!0}}n.dirtyIndices.clear(),o&&(n.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,a,n,o){let l=e.entities[t];if(l){if(l.body){let d=l.body;if(typeof d.writeRenderPose=="function")d.writeRenderPose(o,r,a);else{let c=K(l.body,o);r.set(c.position.x,c.position.y,c.position.z),a.set(c.rotation.x,c.rotation.y,c.rotation.z,c.rotation.w)}i.compose(r,a,n)}else l.mesh?(l.mesh.updateMatrix(),i.copy(l.mesh.matrix)):l.group&&(l.group.updateMatrix(),i.copy(l.group.matrix));e.instancedMesh.setMatrixAt(t,i)}}getPackInfo(e){let t=this.entityToPack.get(e.uuid);if(!t)return null;let i=this.packs.get(t);if(!i)return null;let r=i.entityMap.get(e.uuid);return r===void 0?null:{packKey:t,instanceId:r}}getStats(){let e=0,t=[];for(let[i,r]of this.packs){let a=r.entityMap.size;e+=a,t.push({key:i,count:a,capacity:r.capacity})}return{packCount:this.packs.size,totalInstances:e,packs:t}}dispose(){for(let e of this.packs.values())this.scene&&this.scene.remove(e.instancedMesh),e.instancedMesh.dispose(),e.geometry.dispose();this.packs.clear(),this.entityToPack.clear()}createPack(e,t,i){let r=s.DEFAULT_CAPACITY,a=new yt(t,i,r);a.count=0,a.frustumCulled=!1;let n=new Z().makeScale(0,0,0);for(let l=0;l<r;l++)a.setMatrixAt(l,n);a.instanceMatrix.needsUpdate=!0;let o={key:e,instancedMesh:a,geometry:t,material:i,entityMap:new Map,entities:[],freeIndices:[],activeIndices:[],dirtyIndices:new Set,capacity:r};return this.packs.set(e,o),this.scene&&this.scene.add(a),o}growPack(e){let t=e.capacity*s.GROWTH_FACTOR,i=new yt(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new Z;for(let n=0;n<e.capacity;n++)e.instancedMesh.getMatrixAt(n,r),i.setMatrixAt(n,r);let a=new Z().makeScale(0,0,0);for(let n=e.capacity;n<t;n++)i.setMatrixAt(n,a);i.instanceMatrix.needsUpdate=!0,this.scene&&(this.scene.remove(e.instancedMesh),this.scene.add(i)),e.instancedMesh.dispose(),e.instancedMesh=i,e.capacity=t}};var J=class{bundles=new X;instances=new z;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=F(e.options);if(t==="none")return!1;if(e.isInstanced||e.isBundled)return!0;if(!e.mesh?.geometry||!e.materials?.length)return!1;let i=e.mesh.geometry,r=e.materials[0],a=z.generateEntityPackKey(e);if(t==="pack"){let n=this.instances.register(e,i,r,a);return n<0?!1:(e.packKey=a,e.instanceId=n,e.isInstanced=!0,e.mesh&&(e.mesh.visible=!1),!0)}return t==="environment"&&this.bundles.register(e,i,r,a)?(e.mesh&&(e.mesh.visible=!0),!0):!1}unregister(e){e.isInstanced&&(this.instances.unregister(e),e.isInstanced=!1,e.instanceId=-1,e.packKey=null),e.isBundled&&this.bundles.unregister(e)}update(e=0){this.instances.update(e)}dispose(){this.bundles.dispose(),this.instances.dispose()}};var ee=!1,v={},vt=0,Ct=0,V=null;function St(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function _e(){return ee?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(ee=!0),ee)}function Mr(s){ee=s,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=s)}function Te(s){_e()&&(V=s,Ct=St())}function xe(){if(!_e()||V===null)return;let s=St()-Ct;v[V]=(v[V]??0)+s,V=null}function Pt(){if(!_e()||(vt++,vt%60!==0))return;let s=Object.values(v).reduce((t,i)=>t+(i??0),0),e=Object.keys(v).sort((t,i)=>(v[i]??0)-(v[t]??0)).map(t=>{let i=v[t]??0,r=s>0?(i/s*100).toFixed(1):"0.0";return`${t}=${i.toFixed(2)}ms (${r}%)`});console.info(`[ZylemStage profile] avg over 60 frames (${s.toFixed(2)}ms/frame): ${e.join(", ")}`);for(let t of Object.keys(v))v[t]=0}function P(s,e){Te(s);try{return e()}finally{xe()}}var p={FirstPerson:"first-person",ThirdPerson:"third-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};import{Vector3 as si,Quaternion as ni,MathUtils as Re}from"three";function te(){return{position:new si(0,0,10),rotation:new ni,fov:75,zoom:1,near:.1,far:1e3}}function M(s){return{position:s.position.clone(),rotation:s.rotation.clone(),fov:s.fov,zoom:s.zoom,near:s.near,far:s.far,lookAt:s.lookAt?.clone()}}function wt(s,e){let t=M(s);return e.position&&t.position.add(e.position),e.rotation&&t.rotation.multiply(e.rotation),e.fov!=null&&t.fov!=null&&(t.fov+=e.fov),e.zoom!=null&&t.zoom!=null&&(t.zoom+=e.zoom),t}function Et(s,e,t,i){let r=1-Math.pow(1-Re.clamp(t,0,1),i*60),a=M(s);return a.position.lerp(e.position,r),a.rotation.slerp(e.rotation,r),e.fov!=null&&a.fov!=null&&(a.fov=Re.lerp(a.fov,e.fov,r)),e.zoom!=null&&a.zoom!=null&&(a.zoom=Re.lerp(a.zoom,e.zoom,r)),e.near!=null&&(a.near=e.near),e.far!=null&&(a.far=e.far),e.lookAt?a.lookAt?a.lookAt.lerp(e.lookAt,r):a.lookAt=e.lookAt.clone():a.lookAt=void 0,a}var ie=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=te();_finalPose=te();_initialized=!1;damping=.15;constructor(e){e&&(this.perspective=e,e.defaults?.damping!=null&&(this.damping=e.defaults.damping))}run(e){let t=this.perspective?this.perspective.getBasePose(e):te(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=M(t);for(let r=this.actions.length-1;r>=0;r--){let a=this.actions[r],n=a.update(e);t=wt(t,n),a.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=Et(this._finalPose,t,this.damping,e.dt):(this._finalPose=M(t),this._initialized=!0),this._finalPose}addBehavior(e,t,i){let r=this.behaviors.get(e);r?.onDetach&&i&&r.onDetach(i),this.behaviors.set(e,t),t.onAttach&&i&&t.onAttach(i)}removeBehavior(e,t){let i=this.behaviors.get(e);return i?(i.onDetach&&t&&i.onDetach(t),this.behaviors.delete(e)):!1}hasBehavior(e){return this.behaviors.has(e)}addAction(e){this.actions.push(e)}getState(){return{perspectiveId:this.perspective?.id??null,desiredPose:this._desiredPose?M(this._desiredPose):null,finalPose:this._finalPose?M(this._finalPose):null,activeBehaviors:Array.from(this.behaviors.keys()),activeActionCount:this.actions.length}}setPerspective(e){this.perspective=e,this._initialized=!1,e.defaults?.damping!=null&&(this.damping=e.defaults.damping)}getSortedBehaviors(){return Array.from(this.behaviors.values()).sort((e,t)=>(e.priority??0)-(t.priority??0))}};import{Vector3 as w,Quaternion as re}from"three";var oi={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},D=class{id="third-person";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...oi,...r},this.initialPosition=t?g(t,b):void 0,this.initialLookAt=i?g(i,b):void 0}getBasePose(e){let t=Object.keys(e.targets),i=e.targets[this.opts.targetKey];return t.length===0||!i?this.staticPose():t.length===1?this.singleTargetPose(i.position,e,this.opts.targetKey):this.multiTargetPose(e)}staticPose(){return this.initialPosition?{position:this.initialPosition.clone(),rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new w(0,0,0)}:{position:new w(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new w(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new w(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([u,h])=>this.getTrailedPosition(u,h.position,e.time)),r=new w;for(let u of i)r.add(u);r.divideScalar(i.length);let a=0;for(let u of i){let h=r.distanceTo(u);h>a&&(a=h)}let n=Math.max(a*this.opts.paddingFactor,this.opts.minDistance),o=new w(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=o.length(),d=l>0?o.clone().normalize():new w(0,.5,1).normalize(),c=r.clone().add(d.multiplyScalar(n));if(l>0){let u=this.opts.height/l;c.y=r.y+n*u}return{position:c,rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}getTrailedPosition(e,t,i){let r=this.opts.trailDelay;if(r<=0)return t;let a=this._trailBuffers.get(e);a||(a=[],this._trailBuffers.set(e,a)),a.push({time:i,pos:t.clone()});let n=i-r-.05;for(;a.length>1&&a[0].time<n;)a.shift();a.length>this.opts.trailBufferSize&&a.splice(0,a.length-this.opts.trailBufferSize);let o=i-r;if(a[0].time>=o)return a[0].pos.clone();for(let l=1;l<a.length;l++){let d=a[l-1],c=a[l];if(d.time<=o&&o<=c.time){let u=c.time-d.time,h=u>1e-6?(o-d.time)/u:0;return new w().lerpVectors(d.pos,c.pos,h)}}return a[a.length-1].pos.clone()}};import{Vector3 as Mt,Quaternion as li}from"three";var Dt={position:{x:0,y:0,z:10},zoom:10},k=class{id="fixed-2d";defaults={damping:1};opts;constructor(e){this.opts={...Dt,...e,position:g(e?.position,Dt.position)}}getBasePose(e){return{position:new Mt(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new li,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new Mt(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as ke,Quaternion as Le,Euler as xt,MathUtils as f}from"three";var di={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},G=class{id="first-person";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new Le;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...di,...r},this.initialPosition=t?g(t,b):void 0,this.initialLookAt=i?g(i,b):void 0,this._currentFov=this.opts.defaultFov,this._targetFov=this.opts.defaultFov,this._lookAtLerpSpeed=this.opts.lookAtLerpSpeed,this.initialPosition&&this.initialLookAt&&this.deriveYawPitchFromLookAt(this.initialPosition,this.initialLookAt)}look(e,t){this._yaw+=e,this._pitch=f.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=f.clamp(t,-this.opts.pitchLimit,this.opts.pitchLimit)}setEyeHeight(e){this.opts.eyeHeight=e}get yaw(){return this._yaw}get pitch(){return this._pitch}zoom(e){this._targetFov=e}resetZoom(){this._targetFov=this.opts.defaultFov}get currentFov(){return this._currentFov}lookAt(e,t){this._lookAtTarget=e,t!=null&&(this._lookAtLerpSpeed=t)}clearLookAt(){this._lookAtTarget&&this.deriveYawPitchFromQuaternion(this._currentRotation),this._lookAtTarget=null}getBasePose(e){let t=this.computePosition(e),i=this.computeRotation(t,e.dt);return this._currentFov=this.lerpFov(e.dt),{position:t,rotation:i,fov:this._currentFov,near:.1,far:1e3}}computePosition(e){let t=e.targets[this.opts.targetKey];if(t){let i=t.position.y+this.opts.eyeHeight,r=this.smoothVertical(i,e.dt);return new ke(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new ke(0,this.opts.eyeHeight,0)}smoothVertical(e,t){if(this.opts.verticalSmoothing>=1)return this._smoothedY=e,e;if(this._smoothedY==null)return this._smoothedY=e,e;let i=f.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=f.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new Le().setFromEuler(new xt(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=_t.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let a=Math.atan2(-r.x,-r.z),n=Math.asin(f.clamp(r.y,-1,1)),o=ci.setFromEuler(Tt.set(n,a,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(o,f.clamp(l,0,1)),this._currentRotation.clone()}}return this._currentRotation.copy(i),i}lerpFov(e){if(Math.abs(this._currentFov-this._targetFov)<.01)return this._targetFov;let t=1-Math.pow(1-Math.min(this.opts.fovLerpSpeed*e,1),1);return f.lerp(this._currentFov,this._targetFov,f.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=_t.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(f.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=Tt.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=f.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},_t=new ke,ci=new Le,Tt=new xt;function L(s,e){switch(s){case"third-person":return new D(e);case"first-person":return new G(e);case"isometric":return new D({distance:10,height:10,...e});case"flat-2d":return new k(e);case"fixed-2d":return new k(e);default:return new D(e)}}import{Vector2 as hi,Object3D as gi,Vector3 as ne}from"three";import{PerspectiveCamera as U,Vector3 as mi,OrthographicCamera as se,RenderTarget as pi,LinearFilter as Rt}from"three";import{Vector3 as Ae}from"three";import{OrbitControls as ui}from"three/addons/controls/OrbitControls.js";var ae=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new Ae;debugDelegate=null;debugUnsubscribe=null;debugStateSnapshot={enabled:!1,selected:[]};savedCameraPosition=null;savedCameraQuaternion=null;savedCameraZoom=null;savedCameraLocalPosition=null;savedDebugCameraPosition=null;savedDebugCameraQuaternion=null;savedDebugCameraZoom=null;savedDebugOrbitTarget=null;_userOrbitEnabled=!1;_isDebugViewCamera=!1;_defaultOrbitTarget=null;_debugPoseSeeded=!1;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}setDebugViewCamera(e){this._isDebugViewCamera=e}setDefaultOrbitTarget(e){this._defaultOrbitTarget=e,e&&!this.orbitTarget&&this.debugStateSnapshot.enabled&&(this.orbitTarget=e)}seedOrbitPose(e,t){this.camera.position.copy(e),this.camera.lookAt(t),this.orbitControls&&(this.orbitControls.target.copy(t),this.orbitControls.update()),this._debugPoseSeeded=!0}get isDebugViewCamera(){return this._isDebugViewCamera}get isDebugOrbitPoseSeeded(){return this._debugPoseSeeded}get isActive(){return this.debugStateSnapshot.enabled}get isOrbitActive(){return this.debugStateSnapshot.enabled||this._userOrbitEnabled}update(){this.orbitControls&&this.orbitTarget&&(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)),this.orbitControls?.update()}enableUserOrbitControls(){this._userOrbitEnabled=!0,this.orbitControls||this.enableOrbitControls()}disableUserOrbitControls(){this._userOrbitEnabled=!1,this.debugStateSnapshot.enabled||this.disableOrbitControls()}setDebugDelegate(e){if(this.debugDelegate===e)return;if(this.detachDebugDelegate(),this.debugDelegate=e,!e){this.applyDebugState({enabled:!1,selected:[]});return}let t=e.subscribe(i=>{this.applyDebugState(i)});this.debugUnsubscribe=()=>{t?.()}}dispose(){this.disableOrbitControls(),this.detachDebugDelegate()}get debugState(){return this.debugStateSnapshot}frameTarget(e){!this.orbitControls&&(this.debugStateSnapshot.enabled||this._userOrbitEnabled)&&this.enableOrbitControls(),this.orbitControls||this.enableOrbitControls(),this.orbitTarget=e;let t=new Ae().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=Ge(e,this.camera,t);this.orbitControls.target.copy(i.center),this.orbitControls.update()}applyDebugState(e){let t=this.debugStateSnapshot.enabled;if(this.debugStateSnapshot={enabled:e.enabled,selected:[...e.selected]},this._isDebugViewCamera){e.enabled&&!t?(this.enableOrbitControls(),this._debugPoseSeeded&&this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this._userOrbitEnabled||this.disableOrbitControls()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected);return}e.enabled&&!t?(this.saveCameraState(),this.detachCameraFromRig(),this.enableOrbitControls(),this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this.orbitTarget=null,this._userOrbitEnabled||this.disableOrbitControls(),this.reattachCameraToRig(),this.restoreCameraState()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected)}enableOrbitControls(){this.orbitControls||(this.orbitControls=new ui(this.camera,this.domElement),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.05,this.orbitControls.screenSpacePanning=!1,this.orbitControls.minDistance=1,this.orbitControls.maxDistance=500,this.orbitControls.maxPolarAngle=Math.PI/2,this.orbitControls.target.set(0,0,0))}disableOrbitControls(){this.orbitControls&&(this.orbitControls.dispose(),this.orbitControls=null)}updateOrbitTargetFromSelection(e){if(!this.debugDelegate||e.length===0){this.orbitTarget=this._defaultOrbitTarget,this.orbitControls&&(this.orbitTarget?(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)):this.orbitControls.target.set(0,0,0));return}for(let t=e.length-1;t>=0;t-=1){let i=e[t],r=this.debugDelegate.resolveTarget(i);if(r){this.orbitTarget=r,this.orbitControls&&(r.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos));return}}this.orbitTarget=this._defaultOrbitTarget,this.orbitControls&&(this.orbitTarget?(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)):this.orbitControls.target.set(0,0,0))}detachDebugDelegate(){if(this.debugUnsubscribe)try{this.debugUnsubscribe()}catch{}this.debugUnsubscribe=null,this.debugDelegate=null}saveCameraState(){this.savedCameraPosition=this.camera.position.clone(),this.savedCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedCameraZoom=this.camera.zoom)}restoreCameraState(){this.savedCameraPosition&&(this.camera.position.copy(this.savedCameraPosition),this.savedCameraPosition=null),this.savedCameraQuaternion&&(this.camera.quaternion.copy(this.savedCameraQuaternion),this.savedCameraQuaternion=null),this.savedCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedCameraZoom,this.camera.updateProjectionMatrix?.(),this.savedCameraZoom=null)}saveDebugCameraState(){this.savedDebugCameraPosition=this.camera.position.clone(),this.savedDebugCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedDebugCameraZoom=this.camera.zoom),this.orbitControls&&(this.savedDebugOrbitTarget=this.orbitControls.target.clone())}restoreDebugCameraState(){this.savedDebugCameraPosition&&this.camera.position.copy(this.savedDebugCameraPosition),this.savedDebugCameraQuaternion&&this.camera.quaternion.copy(this.savedDebugCameraQuaternion),this.savedDebugCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedDebugCameraZoom,this.camera.updateProjectionMatrix?.()),this.savedDebugOrbitTarget&&this.orbitControls&&this.orbitControls.target.copy(this.savedDebugOrbitTarget)}detachCameraFromRig(){if(!this.cameraRig||this.camera.parent!==this.cameraRig)return;this.savedCameraLocalPosition=this.camera.position.clone();let e=new Ae;this.camera.getWorldPosition(e),this.cameraRig.remove(this.camera),this.sceneRef&&this.sceneRef.add(this.camera),this.camera.position.copy(e)}reattachCameraToRig(){!this.cameraRig||this.camera.parent===this.cameraRig||(this.sceneRef&&this.camera.parent===this.sceneRef&&this.sceneRef.remove(this.camera),this.cameraRig.add(this.camera),this.savedCameraLocalPosition&&(this.camera.position.copy(this.savedCameraLocalPosition),this.savedCameraLocalPosition=null))}};var C=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...ft};targets=[];pipeline;renderTarget=null;get target(){return this.targets.length>0?this.targets[0]:null}set target(e){e?this.targets.length===0?this.targets.push(e):this.targets[0]=e:this.targets=[]}orbitController=null;_useOrbitalControls=!1;_skipDebugOrbit=!1;isDebugViewCamera=!1;_rendererManager=null;_elapsedTime=0;constructor(e,t,i=10){this._perspective=e,this.screenResolution=t,this.frustumSize=i;let r=t.x/t.y;this.camera=this.createCameraForPerspective(r),this.camera.position.set(0,0,10),this.camera.lookAt(new mi(0,0,0));let a=L(e);this.pipeline=new ie(a)}async setup(e,t){this.sceneRef=e,t&&(this._rendererManager=t),this._rendererManager&&!this._rendererManager.initialized&&await this._rendererManager.initRenderer(),this._rendererManager&&(this.orbitController=new ae(this.camera,this._rendererManager.renderer.domElement,null),this.orbitController.setScene(e),this.isDebugViewCamera&&this.orbitController.setDebugViewCamera(!0),this._useOrbitalControls&&this.orbitController.enableUserOrbitControls())}async setupLegacy(e){this._rendererManager||(this._rendererManager=new q(this.screenResolution),await this._rendererManager.initRenderer(),this._rendererManager.setupPostProcessing(e,this.camera),this._rendererManager.startRenderLoop(()=>{this._rendererManager&&this.sceneRef&&(this.isOrbitActive&&this.updateOrbitControls(),this._rendererManager.render(this.sceneRef,this.camera))})),await this.setup(e,this._rendererManager)}update(e){if(this.isDebugModeActive()||this._useOrbitalControls)return;this._elapsedTime+=e;let t=this.buildContext(e),i=this.pipeline.run(t);this.commitPose(i)}isDebugModeActive(){return this.orbitController?.isActive??!1}get isOrbitActive(){return this.orbitController?.isOrbitActive??!1}updateOrbitControls(){this.orbitController?.update()}enableOrbitalControls(){this._useOrbitalControls=!0,this.orbitController?.enableUserOrbitControls()}disableOrbitalControls(){this._useOrbitalControls=!1,this.orbitController?.disableUserOrbitControls()}get useOrbitalControls(){return this._useOrbitalControls}addTarget(e){this.targets.includes(e)||this.targets.push(e)}removeTarget(e){let t=this.targets.indexOf(e);t!==-1&&this.targets.splice(t,1)}clearTargets(){this.targets=[]}setViewport(e,t,i,r){this.viewport={x:e,y:t,width:i,height:r}}resize(e,t){if(this.screenResolution.set(e,t),this.camera instanceof U&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof se){let i=e/t;this.camera.left=this.frustumSize*i/-2,this.camera.right=this.frustumSize*i/2,this.camera.top=this.frustumSize/2,this.camera.bottom=this.frustumSize/-2,this.camera.updateProjectionMatrix()}}createRenderTarget(e=512,t=512){return this.renderTarget&&this.renderTarget.dispose(),this.renderTarget=new pi(e,t,{minFilter:Rt,magFilter:Rt}),this.renderTarget}getRenderTexture(){return this.renderTarget?.texture??null}destroy(){try{this.orbitController?.dispose()}catch{}try{this.renderTarget?.dispose()}catch{}this.renderTarget=null,this.sceneRef=null,this.targets=[],this._rendererManager=null}setDefaultOrbitTarget(e){this.orbitController?.setDefaultOrbitTarget(e)}seedDebugOrbitPose(e,t){this.isDebugViewCamera&&this.isDebugOrbitPoseSeeded()||this.orbitController?.seedOrbitPose(e,t)}isDebugOrbitPoseSeeded(){return this.orbitController?.isDebugOrbitPoseSeeded??!1}setDebugDelegate(e){this._skipDebugOrbit||this.orbitController?.setDebugDelegate(e)}frameObject(e){this.orbitController?.frameTarget(e)}move(e){(this._perspective===p.Flat2D||this._perspective===p.Fixed2D)&&(this.frustumSize=e.z),this.camera.position.set(e.x,e.y,e.z)}rotate(e,t,i){this.camera.rotateX(e),this.camera.rotateY(t),this.camera.rotateZ(i)}getDomElement(){if(this._rendererManager)return this._rendererManager.getDomElement();throw new Error("ZylemCamera: No renderer manager available. Call setup() first.")}getRendererManager(){return this._rendererManager}setRendererManager(e){this._rendererManager=e}get renderer(){return this._rendererManager?.renderer}get composer(){return this._rendererManager?.postProcessing}setPixelRatio(e){this._rendererManager?.setPixelRatio(e)}buildContext(e){let t={};for(let i=0;i<this.targets.length;i++){let r=this.targets[i],a=i===0?"primary":`target_${i}`;r.group&&(t[a]={position:r.group.position,rotation:r.group.quaternion})}return{dt:e,time:this._elapsedTime,viewport:{width:this.screenResolution.x,height:this.screenResolution.y,aspect:this.screenResolution.x/this.screenResolution.y},targets:t}}commitPose(e){if(this.camera.position.copy(e.position),e.lookAt?this.camera.lookAt(e.lookAt):this.camera.quaternion.copy(e.rotation),this.camera instanceof U&&(e.fov!=null&&(this.camera.fov=e.fov),e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()),this.camera instanceof se){if(e.zoom!=null){let t=this.screenResolution.x/this.screenResolution.y,i=e.zoom;this.camera.left=-i*t/2,this.camera.right=i*t/2,this.camera.top=i/2,this.camera.bottom=-i/2}e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()}}createCameraForPerspective(e){switch(this._perspective){case p.ThirdPerson:return new U(75,e,.1,1e3);case p.FirstPerson:return new U(75,e,.1,1e3);case p.Isometric:return new se(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);case p.Flat2D:case p.Fixed2D:return new se(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);default:return new U(75,e,.1,1e3)}}};var oe=class{cameras=new Map;_activeCameras=[];_debugCamera=null;_preDebugPrimary=null;_debugOrbitTargetAnchor=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;constructor(){}get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}get debugCamera(){return this._debugCamera}get preDebugPrimary(){return this._preDebugPrimary}get allCameras(){return Array.from(this.cameras.values())}addCamera(e,t){let i=t||e.name||`camera_${this._autoNameCounter++}`;return e.name=i,this.cameras.set(i,e),this._activeCameras.length===0&&this._activeCameras.push(e),i}removeCamera(e){let t;if(typeof e=="string")t=e;else for(let[a,n]of this.cameras.entries())if(n===e){t=a;break}if(!t)return!1;let i=this.cameras.get(t);if(!i)return!1;if(i===this._debugCamera)return console.warn("CameraManager: Cannot remove the debug camera"),!1;this.cameras.delete(t);let r=this._activeCameras.indexOf(i);return r!==-1&&this._activeCameras.splice(r,1),!0}setActiveCamera(e){let t=this.resolveCamera(e);if(!t)return console.warn(`CameraManager: Camera not found: ${e}`),!1;let i=this._activeCameras.filter(r=>r!==this._activeCameras[0]&&r.viewport.width<1);return this._activeCameras=[t,...i],!0}addActiveCamera(e){let t=this.resolveCamera(e);return t?(this._activeCameras.includes(t)||this._activeCameras.push(t),!0):!1}deactivateCamera(e){let t=this.resolveCamera(e);if(!t)return!1;let i=this._activeCameras.indexOf(t);return i!==-1?(this._activeCameras.splice(i,1),!0):!1}getCamera(e){return this.cameras.get(e)??null}async setup(e,t){this._sceneRef=e,this._rendererManager=t,this.createDebugCamera(t.screenResolution),this._debugOrbitTargetAnchor=new gi,this._debugOrbitTargetAnchor.name="__debug_orbit_target__",e.add(this._debugOrbitTargetAnchor);for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._debugCamera&&this._debugOrbitTargetAnchor&&this._debugCamera.setDefaultOrbitTarget(this._debugOrbitTargetAnchor)}activateDebugCamera(){if(!this._debugCamera)return!1;let e=this.primaryCamera;if(e===this._debugCamera)return!0;this._preDebugPrimary=e;let t=this.setActiveCamera(this._debugCamera);return t&&this.seedDebugCameraPose(e),t}deactivateDebugCamera(){if(!this._debugCamera)return!1;let e=this._preDebugPrimary;if(this._preDebugPrimary=null,e&&e!==this._debugCamera)return this.setActiveCamera(e);for(let t of this.cameras.values())if(t!==this._debugCamera)return this.setActiveCamera(t);return!1}update(e){for(let t of this._activeCameras)t.update(e)}render(e){if(!this._rendererManager||this._activeCameras.length===0)return;this.updateOrbitingCamerasForRender();let t=[],i=[];for(let r of this._activeCameras)r.renderTarget?t.push(r):i.push(r);for(let r of t)this._rendererManager.renderCameraToTarget(e,r);i.length>0&&this._rendererManager.renderCameras(e,i)}updateOrbitingCamerasForRender(){for(let e of this._activeCameras)e.isOrbitActive&&e.updateOrbitControls()}ensureDefaultCamera(){if(this.cameras.size===0||this._activeCameras.length===0){let e=this._rendererManager?.screenResolution||new hi(window.innerWidth,window.innerHeight),t=new C(p.ThirdPerson,e);return this.addCamera(t,"default"),t}return this._activeCameras[0]}dispose(){for(let e of this.cameras.values())e.destroy();this._debugCamera&&!this.cameras.has("__debug__")&&this._debugCamera.destroy(),this.cameras.clear(),this._activeCameras=[],this._debugCamera=null,this._preDebugPrimary=null,this._debugOrbitTargetAnchor&&this._sceneRef&&this._sceneRef.remove(this._debugOrbitTargetAnchor),this._debugOrbitTargetAnchor=null,this._rendererManager=null,this._sceneRef=null}createDebugCamera(e){this._debugCamera=new C(p.ThirdPerson,e),this._debugCamera.name="__debug__",this._debugCamera.isDebugViewCamera=!0,this._debugCamera.enableOrbitalControls(),this.cameras.set("__debug__",this._debugCamera)}seedDebugCameraPose(e){if(!this._debugCamera||this._debugCamera.isDebugOrbitPoseSeeded())return;let t=new ne(0,0,0),i=new ne(0,6,12);if(e&&e!==this._debugCamera){let r=e.camera.position,a=new ne().subVectors(r,t);a.lengthSq()>1&&i.copy(a.normalize().multiplyScalar(12).add(new ne(0,4,0)))}this._debugCamera.seedDebugOrbitPose(i,t)}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;if(e===this._debugCamera)return this._debugCamera;for(let t of this.cameras.values())if(t===e)return t;return null}};var y=class{cameraRef;constructor(e){this.cameraRef=e}addTarget(e){this.cameraRef.addTarget(e)}removeTarget(e){this.cameraRef.removeTarget(e)}clearTargets(){this.cameraRef.clearTargets()}enableOrbitalControls(){this.cameraRef.enableOrbitalControls()}disableOrbitalControls(){this.cameraRef.disableOrbitalControls()}setViewport(e,t,i,r){this.cameraRef.setViewport(e,t,i,r)}addBehavior(e,t){this.cameraRef.pipeline.addBehavior(e,t)}removeBehavior(e){return this.cameraRef.pipeline.removeBehavior(e)}addAction(e){this.cameraRef.pipeline.addAction(e)}setPerspective(e,t){this.cameraRef.pipeline.setPerspective(L(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function Ra(s){let e=We(s.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;s.perspective==="fixed-2d"&&(t=s.zoom||10);let i=new C(s.perspective||"third-person",e,t);s.name&&(i.name=s.name);let r=g(s.position,b),a=g(s.target,b);i.move(r),i.camera.lookAt(a);let n=s.perspective||"third-person";if(n==="fixed-2d"||n==="flat-2d"?i.pipeline.setPerspective(L(n,{zoom:t})):i.pipeline.setPerspective(L(n,{initialPosition:r.clone(),initialLookAt:a.clone()})),s.viewport&&(i.viewport={...s.viewport}),s.useOrbitalControls&&(i._useOrbitalControls=!0),s.skipDebugOrbit&&(i._skipDebugOrbit=!0),s.damping!=null&&(i.pipeline.damping=s.damping),s.behaviors)for(let[o,l]of Object.entries(s.behaviors))i.pipeline.addBehavior(o,l);if(s.renderToTexture){let{width:o=512,height:l=512}=s.renderToTexture;i.createRenderTarget(o,l)}return new y(i)}import{Vector3 as fi}from"three";function E(s){return!!s&&typeof s=="object"&&typeof s.create=="function"}function N(s){return!!s&&typeof s.then=="function"}function Oe(s){return!!s&&typeof s=="object"&&s instanceof y}function kt(s){return!s||typeof s!="object"||E(s)||Oe(s)||N(s)||typeof s.then=="function"?!1:s.constructor===Object||s.constructor?.name==="Object"}function Lt(s){return s?!!(E(s)||typeof s=="function"||N(s)):!1}var yi="/three/basis/";function de(s){return{...s,ktx2TranscoderPath:s?.ktx2TranscoderPath??yi}}var le=class{constructor(e,t,i,r,a,n,o=60,l={},d=!0,c=[]){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=a;this.variables=n;this.physicsRate=o;this.assetLoaders=l;this.defaultLighting=d;this.postProcessingEffects=c}};function bi(){return new le({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},Q,null,null,new fi(0,0,0),{},60,{},!0)}function At(s=[]){let e=bi(),t={},i=[],r=[],a=[];for(let l of s)Oe(l)?a.push(l):E(l)?i.push(l):Lt(l)&&!E(l)?r.push(l):kt(l)&&(t={...t,...l});let n=new le(t.inputs??e.inputs,t.backgroundColor??e.backgroundColor,t.backgroundImage??e.backgroundImage,t.backgroundShader??e.backgroundShader,t.gravity??e.gravity,t.variables??e.variables,t.physicsRate??e.physicsRate,t.assetLoaders??e.assetLoaders,t.defaultLighting??e.defaultLighting,t.postProcessingEffects??e.postProcessingEffects),o=a.length>0?a[0]:void 0;return{config:n,entities:i,asyncEntities:r,camera:o,cameras:a}}function Za(s){return{...s}}var vi=Symbol("vessel"),W=class extends O{static type=vi;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=Ci();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function Ci(...s){let e=new W;return s.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Ut,Vector3 as Nt}from"three";import{createSimulation as Si}from"@zylem/behaviors/core";function Be(s){return typeof s?.handlePostCollision=="function"&&typeof s?.handleIntersectionEvent=="function"}function Pi(s,e){return s<e?`${s}|${e}`:`${e}|${s}`}var ce=class s{type="World";simulation;collisionMap=new Map;collisionBehaviorMap=new Map;_removalMap=new Map;activeCollisionPairs=new Map;livePairs=new Map;handleIdToUuid=new Map;currentCollisionTimeMs=0;zeroGravity;fixedTimestep;interpolationAlpha=0;stepClock={steps:0};static async create(e,t=60){let i={x:e?.x??0,y:e?.y??0,z:e?.z??0},r=await Si({gravity:[i.x,i.y,i.z],fixedTimestep:1/t,initialCapacity:4096});return new s(r,t,i.x===0&&i.y===0&&i.z===0)}constructor(e,t=60,i=!1){this.simulation=e,this.fixedTimestep=1/t,this.zeroGravity=i,this.simulation?.setEventsEnabled?.(!1)}addEntity(e){let t={...e.bodyDesc??{}},i=e.colliderDescs?.length?e.colliderDescs:e.colliderDesc?[e.colliderDesc]:[];this.zeroGravity&&(t.lockTranslation=t.lockTranslation??[!0,!0,!0],t.lockRotation=t.lockRotation??[!0,!0,!0]),(e.controlledRotation||e instanceof j)&&e.bodyDesc?.lockRotation===void 0&&(t.lockRotation=[!0,!0,!0]);let r=this.simulation.spawn({body:t,colliders:i});if(!r){console.warn(`ZylemWorld: failed to spawn entity ${e.uuid} into simulation`);return}e.body=new qe(this.simulation,r,this.stepClock),e.physicsAttached=!0,e.physicsWorldRef=this,e.simulationHandle=r,e.runtimeHandle=r.slot,e.runtimeAttached=!0,e.wasmStageRef=this.simulation.adapter,this.handleIdToUuid.set(r.id,e.uuid),this.collisionMap.set(e.uuid,e)}setForRemoval(e){e.physicsAttached&&this._removalMap.set(e.uuid,e)}destroyEntity(e){if(!(e.physicsWorldRef===this)){this.removeEntityFromTracking(e.uuid);return}let i=e.simulationHandle;if(i){try{this.simulation.despawn(i)}catch{}this.handleIdToUuid.delete(i.id)}this.removeEntityFromTracking(e.uuid),this.clearEntityPhysicsState(e)}setup(){}update(e){let{delta:t}=e;this.currentCollisionTimeMs+=t*1e3,this.processPendingRemovals();let i=this.hasCollisionPhaseListeners();i&&!this.simulation.areEventsEnabled&&this.simulation.setEventsEnabled?.(!0);let r=this.simulation.update(t);this.stepClock.steps+=r.stepsTaken,this.interpolationAlpha=r.alpha,i&&(this.applyCollisionEvents(r.events),this.processCollisionPairs(t,this.currentCollisionTimeMs))}hasCollisionPhaseListeners(){for(let e of this.collisionMap.values())if(e?.collisionDelegate?.collision?.length)return!0;return!1}applyCollisionEvents(e){for(let t of e){if(t.type!=="collisionStarted"&&t.type!=="collisionStopped")continue;let i=t.a?this.handleIdToUuid.get(t.a.id):void 0,r=t.b?this.handleIdToUuid.get(t.b.id):void 0;if(!i||!r||i===r)continue;let a=Pi(i,r),n=this.livePairs.get(a);n||(n={uuidA:i<r?i:r,uuidB:i<r?r:i,contactCount:0,intersectionCount:0},this.livePairs.set(a,n));let o=t.type==="collisionStarted"?1:-1;t.sensor?n.intersectionCount=Math.max(0,n.intersectionCount+o):n.contactCount=Math.max(0,n.contactCount+o),n.contactCount===0&&n.intersectionCount===0&&this.livePairs.delete(a)}}snapshotLivePairs(){let e=new Map;for(let[t,i]of this.livePairs)e.set(t,{uuidA:i.uuidA,uuidB:i.uuidB,hasContact:i.contactCount>0,hasIntersection:i.intersectionCount>0});return e}updatePostCollisionBehaviors(e){let t=this.collisionBehaviorMap;for(let[i,r]of t){let a=r;if(!Be(a))continue;a.handlePostCollision({entity:a,delta:e})||this.collisionBehaviorMap.delete(i)}}processPendingRemovals(){if(this._removalMap.size!==0){for(let[,e]of this._removalMap)this.destroyEntity(e);this._removalMap.clear()}}removeEntityFromTracking(e){this.collisionMap.delete(e),this._removalMap.delete(e),this.pruneActiveCollisionPairs(e)}pruneActiveCollisionPairs(e){for(let[t,i]of this.activeCollisionPairs)(i.uuidA===e||i.uuidB===e)&&this.activeCollisionPairs.delete(t);for(let[t,i]of this.livePairs)(i.uuidA===e||i.uuidB===e)&&this.livePairs.delete(t)}entityHasCollisionPhaseListener(e,t){let i=e?.collisionDelegate.collision;if(!i?.length)return!1;for(let r of i)if(r.options.phase===t)return!0;return!1}processCollisionPairs(e,t=this.currentCollisionTimeMs){let i=this.snapshotLivePairs();for(let[r,a]of i){let n=this.collisionMap.get(a.uuidA),o=this.collisionMap.get(a.uuidB);this.activeCollisionPairs.has(r)||this.dispatchCollisionPhase(a,"enter",t),(this.entityHasCollisionPhaseListener(n,"stay")||this.entityHasCollisionPhaseListener(o,"stay"))&&this.dispatchCollisionPhase(a,"stay",t),a.hasIntersection&&this.dispatchIntersectionDelegates(a,e)}this.updatePostCollisionBehaviors(e),this.activeCollisionPairs=i}dispatchCollisionPhase(e,t,i){let r={phase:t,nowMs:i},a=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);a&&n&&a._collision(n,Pe.globals,r);let o=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);o&&l&&l._collision(o,Pe.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&Be(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let a=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);a&&n&&Be(n)&&(n.handleIntersectionEvent({entity:n,other:a,delta:t}),this.collisionBehaviorMap.set(n.uuid,n))}raycast(e,t,i){let r=this.simulation.castRay([e.x,e.y,e.z],[t.x,t.y,t.z],i,!0);return r?{uuid:r.entity?this.handleIdToUuid.get(r.entity.id)??null:null,distance:r.distance,normal:r.normal}:null}destroy(){try{for(let[,e]of this.collisionMap)try{this.clearEntityPhysicsState(e)}catch{}try{this.simulation.dispose()}catch{}this.collisionMap.clear(),this.collisionBehaviorMap.clear(),this._removalMap.clear(),this.activeCollisionPairs.clear(),this.livePairs.clear(),this.handleIdToUuid.clear()}catch{}}clearEntityPhysicsState(e){e.physicsAttached=!1,e.body=null,e.runtimeHandle=-1,e.runtimeAttached=!1,e.wasmStageRef=null,e.simulationHandle=void 0,e.physicsWorldRef===this&&(e.physicsWorldRef=null)}};import{Scene as wi,Color as Ot,AmbientLight as Ei,DirectionalLight as Mi,Vector3 as ue,GridHelper as Di,Texture as _i,SRGBColorSpace as Ti}from"three";var me=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new wi,n=i.backgroundColor instanceof Ot?i.backgroundColor:new Ot(i.backgroundColor);r.background=n,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&x.loadTexture(i.backgroundImage,{colorSpace:Ti}).then(o=>{r.background=o}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),m.enabled&&this.debugScene()}setupBackgroundShader(e,t){if(!$e(t)){console.warn("ZylemScene: GLSL background shaders are not supported on the WebGPU renderer. Provide a TSL shader (ZylemTSLShader) as backgroundShader. Keeping solid background.");return}e.background=null,e.backgroundNode=t.colorNode}setup(){this._setup&&this._setup({me:this,camera:this.zylemCamera,globals:S()})}destroy(){this.cameraManager?(this.cameraManager.dispose(),this.cameraManager=null):this.zylemCamera&&this.zylemCamera.destroy&&this.zylemCamera.destroy(),this.scene&&(this.scene.backgroundNode=null,this.scene.background instanceof _i&&(this.scene.background.dispose(),this.scene.background=null),this.scene.traverse(e=>{if(e.geometry&&e.geometry.dispose?.(),e.material){let t=Array.isArray(e.material)?e.material:[e.material];for(let i of t)i.map&&i.map.dispose?.(),i.normalMap&&i.normalMap.dispose?.(),i.aoMap&&i.aoMap.dispose?.(),i.emissiveMap&&i.emissiveMap.dispose?.(),i.roughnessMap&&i.roughnessMap.dispose?.(),i.metalnessMap&&i.metalnessMap.dispose?.(),i.envMap&&i.envMap.dispose?.(),i.lightMap&&i.lightMap.dispose?.(),i.bumpMap&&i.bumpMap.dispose?.(),i.displacementMap&&i.displacementMap.dispose?.(),i.alphaMap&&i.alphaMap.dispose?.(),i.dispose?.()}e.isLight&&e.shadow?.map&&e.shadow.map.dispose()}),this.scene.clear())}async setupCamera(e,t,i){this.addCameraToScene(e,t),i?await t.setup(e,i):await t.setupLegacy(e)}async setupCameraManager(e,t,i){this.cameraManager=t;for(let r of t.activeCameras)this.addCameraToScene(e,r);await t.setup(e,i)}addCameraToScene(e,t){t.cameraRig?e.add(t.cameraRig):e.add(t.camera)}setupLighting(e){let t=new Ei(16777215,1);e.add(t);let i=new Mi(16777215,2);i.name="Light",i.position.set(0,100,0),i.castShadow=!0,i.shadow.camera.near=.1,i.shadow.camera.far=2e3,i.shadow.camera.left=-100,i.shadow.camera.right=100,i.shadow.camera.top=100,i.shadow.camera.bottom=-100,i.shadow.mapSize.width=2048,i.shadow.mapSize.height=2048,e.add(i)}updateRenderer(e,t){if(this.cameraManager)for(let i of this.cameraManager.allCameras)i.resize(e,t);else this.zylemCamera.resize(e,t)}add(e,t=new ue(0,0,0)){e.position.set(t.x,t.y,t.z),this.scene.add(e)}addEntity(e){let t=e.group??e.mesh;!t||this.isAttachedOutsideScene(t)||this.add(t,e.options.position)}addEntityGroup(e){if(R(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=xi(e);i&&i.attachToScene(this.scene);let r=e.options.position??new ue(0,0,0);if(e.physicsAttached&&e.body)try{let a=e.body.translation();r=new ue(a.x,a.y,a.z)}catch{r=e.options.position??new ue(0,0,0)}this.add(t,r),B(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new Di(1e3,100);this.scene.add(i)}};function xi(s){return s.constructor.type===Xe?s:null}var pe=class{update=()=>{};setup=()=>{};destroy=()=>{};nodeSetup(e){typeof this._setup=="function"&&this._setup(e),this.setup&&this.setup(e)}nodeUpdate(e){typeof this._update=="function"&&this._update(e),this.update&&this.update(e)}nodeDestroy(e){this.destroy&&this.destroy(e),typeof this._destroy=="function"&&this._destroy(e)}};import{Quaternion as Ri}from"three";var Bt=new Ri;function Ft(s){let e=s._childrenMap,t=s._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval||i.isInstanced||i.isBundled||i.skipRenderPoseSync)continue;let r=i.body,a=i.group??i.mesh,n=a?K(r,t?.interpolationAlpha??0):null;a&&n&&a.position.set(n.position.x,n.position.y,n.position.z),!i.controlledRotation&&a&&n&&(Bt.set(n.rotation.x,n.rotation.y,n.rotation.z,n.rotation.w),a.setRotationFromQuaternion(Bt))}}import{nanoid as Qi}from"nanoid";import{BufferAttribute as Vt,BufferGeometry as zi,LineBasicMaterial as Vi,LineSegments as Gi,Raycaster as Ui,Vector2 as Ni}from"three";import{subscribe as Wi}from"valtio/vanilla";import{subscribe as ki}from"valtio/vanilla";var he=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),ki(m,t)}resolveTarget(e){let t=this.stage.entityDelegate.debugMap.get(e)||this.stage.entityDelegate.childrenMap.get(e)||this.stage.world?.collisionMap.get(e)||null;return t?.group??t?.mesh??null??null}snapshot(){return{enabled:m.enabled,selected:m.selectedEntity?[m.selectedEntity.uuid]:[]}}};import{Box3 as Li,BoxGeometry as It,Color as Ai,EdgesGeometry as Zt,Group as Oi,LineBasicMaterial as Bi,LineSegments as Fi,Mesh as Ii,MeshBasicMaterial as Zi,Vector3 as zt}from"three";var ge=class{scene;container;fillMesh;edgeLines;currentColor=new Ai(65280);bbox=new Li;size=new zt;center=new zt;constructor(e){this.scene=e;let t=new It(1,1,1);this.fillMesh=new Ii(t,new Zi({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new Zt(t);this.edgeLines=new Fi(i,new Bi({color:this.currentColor,linewidth:1})),this.container=new Oi,this.container.name="DebugEntityCursor",this.container.add(this.fillMesh),this.container.add(this.edgeLines),this.container.visible=!1,this.scene.add(this.container)}setColor(e){this.currentColor.set(e),this.fillMesh.material.color.set(this.currentColor),this.edgeLines.material.color.set(this.currentColor)}updateFromObject(e){if(!e){this.hide();return}if(this.bbox.setFromObject(e),!isFinite(this.bbox.min.x)||!isFinite(this.bbox.max.x)){this.hide();return}this.bbox.getSize(this.size),this.bbox.getCenter(this.center);let t=new It(Math.max(this.size.x,1e-6),Math.max(this.size.y,1e-6),Math.max(this.size.z,1e-6));this.fillMesh.geometry.dispose(),this.fillMesh.geometry=t;let i=new Zt(t);this.edgeLines.geometry.dispose(),this.edgeLines.geometry=i,this.container.position.copy(this.center),this.container.visible=!0}hide(){this.container.visible=!1}dispose(){this.scene.remove(this.container),this.fillMesh.geometry.dispose(),this.fillMesh.material.dispose(),this.edgeLines.geometry.dispose(),this.edgeLines.material.dispose()}};var Hi=2293538,ji=16724787,fe=class{stage;options;mouseNdc=new Ni(-2,-2);raycaster=new Ui;isMouseDown=!1;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;debugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;focusContextUnregister=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.syncWithDebugState(),this.debugStateUnsubscribe=Wi(m,()=>{this.syncWithDebugState()}),this.focusContextUnregister=at({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{this.ensureCameraDebugDelegate(),this.getDebugViewCamera()?.frameObject(i)},ensureDebugReady:()=>{m.enabled||(m.enabled=!0),this.activate(),this.populateDebugMap()}})}getDebugViewCamera(){return this.stage.cameraManagerRef?.primaryCamera??this.stage.cameraManagerRef?.debugCamera??this.stage.cameraRef??null}resolveEntity(e){let t=this.stage.entityDelegate.debugMap.get(e);if(t)return t;let i=this.stage.entityDelegate.childrenMap.get(e);return i||(this.stage.world?.collisionMap.get(e)??null)}populateDebugMap(){this.stage.entityDelegate.childrenMap.forEach((e,t)=>{this.stage.entityDelegate.debugMap.set(t,e)})}ensureCameraDebugDelegate(){let e=this.stage.cameraManagerRef?.debugCamera??null;e&&(this.cameraDebugDelegate||(this.cameraDebugDelegate=new he(this.stage)),e.setDebugDelegate(this.cameraDebugDelegate))}syncWithDebugState(){m.enabled?this.activate():this.deactivate()}activate(){this.domListenersAttached||(this.domListenersAttached=this.attachDomListeners()),this.populateDebugMap(),this.stage.cameraManagerRef?.activateDebugCamera();let e=this.stage.cameraManagerRef?.debugCamera??null;this.rebindPostProcessing(e),this.ensureCameraDebugDelegate(),document.pointerLockElement&&document.exitPointerLock()}deactivate(){this.disposeDebugVisuals();let e=this.stage.cameraManagerRef?.debugCamera;e&&e.setDebugDelegate(null),this.stage.cameraRef&&this.stage.cameraRef!==e&&this.stage.cameraRef.setDebugDelegate(null),this.cameraDebugDelegate=null,this.stage.cameraManagerRef?.deactivateDebugCamera();let t=this.stage.cameraManagerRef?.primaryCamera??this.stage.cameraRef??null;this.rebindPostProcessing(t)}rebindPostProcessing(e){let t=this.stage.scene?.scene,i=this.stage.rendererManager;t&&i&&e&&i.setupPostProcessing(t,e.camera)}initDebugVisuals(){this.debugLines||!this.stage.scene||(this.debugLines=new Gi(new zi,new Vi({vertexColors:!0})),this.stage.scene.scene.add(this.debugLines),this.debugLines.visible=!0,this.debugCursor=new ge(this.stage.scene.scene))}disposeDebugVisuals(){this.debugLines&&this.stage.scene&&(this.stage.scene.scene.remove(this.debugLines),this.debugLines.geometry.dispose(),this.debugLines.material.dispose(),this.debugLines=null),this.debugCursor?.dispose(),this.debugCursor=null}update(){if(!m.enabled){this.debugLines&&this.disposeDebugVisuals();return}let e=this.getDebugViewCamera();if(!this.stage.scene||!this.stage.world||!e)return;this.debugLines||this.initDebugVisuals();let{world:t}=this.stage;if(this.debugLines){let u=t.simulation.getDebugRender();u&&u.vertices.length>0?(this.debugLines.geometry.setAttribute("position",new Vt(new Float32Array(u.vertices),3)),this.debugLines.geometry.setAttribute("color",new Vt(new Float32Array(u.colors),4)),this.debugLines.geometry.attributes.position.needsUpdate=!0,this.debugLines.geometry.attributes.color.needsUpdate=!0,this.debugLines.visible=!0):this.debugLines.visible=!1}let i=we(),r=i==="select"||i==="delete";this.raycaster.setFromCamera(this.mouseNdc,e.camera);let a=this.raycaster.ray.origin.clone(),n=this.raycaster.ray.direction.clone().normalize(),o=t.raycast(a,n,this.options.maxRayDistance);if(o&&r){let u=o.uuid;if(u){let h=this.stage.entityDelegate.debugMap.get(u);h&&ze(h)}else Ve();this.isMouseDown&&this.handleActionOnHit(u??null,a,n,o.distance)}this.isMouseDown=!1;let l=Ze();if(!l){this.debugCursor?.hide();return}let d=this.stage.entityDelegate.debugMap.get(`${l}`),c=d?.group??d?.mesh??null;if(!c){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(Hi);break;case"delete":this.debugCursor?.setColor(ji);break;default:this.debugCursor?.setColor(16777215);break}this.debugCursor?.updateFromObject(c)}dispose(){this.focusContextUnregister?.(),this.focusContextUnregister=null,this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.deactivate(),this.domDisposeFns.forEach(e=>e()),this.domDisposeFns=[],this.domListenersAttached=!1}handleActionOnHit(e,t,i,r){switch(we()){case"select":{if(e){let n=this.resolveEntity(e);n&&Ie(n)}break}case"delete":{e&&this.stage.entityDelegate.removeEntityByUuid(e);break}case"scale":{if(!this.options.addEntityFactory)break;let n=t.clone().add(i.clone().multiplyScalar(r)),o=this.options.addEntityFactory({position:n});o&&Promise.resolve(o).then(l=>{l&&this.stage.entityDelegate.spawnEntity(l)}).catch(()=>{});break}default:break}}attachDomListeners(){let e=this.stage.rendererManager?.getDomElement();if(!e)return!1;let t=r=>{let a=e.getBoundingClientRect(),n=(r.clientX-a.left)/a.width*2-1,o=-((r.clientY-a.top)/a.height*2-1);this.mouseNdc.set(n,o)},i=()=>{this.isMouseDown=!0};return e.addEventListener("mousemove",t),e.addEventListener("mousedown",i),this.domDisposeFns.push(()=>e.removeEventListener("mousemove",t)),this.domDisposeFns.push(()=>e.removeEventListener("mousedown",i)),!0}};import{Vector2 as Ki}from"three";var ye=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Ki(e,t);return new C(p.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new oe;if(e)return i.addCamera(e,e.name||"main"),i;let r=t.filter(a=>a!==void 0);if(r.length>0){for(let a of r){let n=a.cameraRef;i.addCamera(n,n.name||void 0)}for(let a=1;a<r.length;a++)i.addActiveCamera(r[a].cameraRef)}else{let a=this.createDefaultCamera();i.addCamera(a,"default")}return i}};var be=class{loadingHandlers=[];stageName;stageIndex;setStageContext(e,t){this.stageName=e,this.stageIndex=t}onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let i of this.loadingHandlers)try{i(e)}catch(r){console.error("Loading handler failed",r)}let t={...e,stageName:this.stageName,stageIndex:this.stageIndex};e.type==="start"?H.emit("stage:loading:start",t):e.type==="progress"?H.emit("stage:loading:progress",t):e.type==="complete"&&H.emit("stage:loading:complete",t)}emitStart(e="Loading stage..."){this.emit({type:"start",message:e,progress:0})}emitProgress(e,t,i){let r=i>0?t/i:0;this.emit({type:"progress",message:e,progress:r,current:t,total:i})}emitComplete(e="Stage loaded"){this.emit({type:"complete",message:e,progress:1})}dispose(){this.loadingHandlers=[]}};var ve=class{scene=null;onEntityReady=null;pendingEntities=new Map;modelLoadedHandler=null;attach(e,t){this.scene=e,this.onEntityReady=t??null,this.modelLoadedHandler=i=>{this.handleModelLoaded(i.entityId,i.success)},A.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){I(e.options)||(this.scene?.addEntityGroup(e),B(e),T(e),this.onEntityReady?.(e));return}this.pendingEntities.set(e.uuid,e)}unobserve(e){this.pendingEntities.delete(e)}handleModelLoaded(e,t){let i=this.pendingEntities.get(e);if(!i||!t){this.pendingEntities.delete(e);return}this.scene?.addEntityGroup(i),B(i),T(i),I(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(A.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as Gt}from"@zylem/behaviors/core";var Ce=class s{static EMPTY_BEHAVIOR_LINKS=[];children=[];childrenMap=new Map;debugMap=new Map;pendingEntities=[];pendingPromises=[];_isLoaded=!1;entityAddedHandlers=[];behaviorSystems=[];behaviorSystemByKey=new Map;registeredSystemKeys=new Set;behaviorEntityIndex=new Map;behaviorLinksByUuid=new Map;scene=null;world=null;renderStrategy=null;camera=null;wasmStage=null;loadingDelegate;entityModelDelegate;constructor(e,t){this.loadingDelegate=e,this.entityModelDelegate=t}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}attach(e){this.scene=e.scene,this.world=e.world,this.renderStrategy=e.renderStrategy,this.camera=e.camera,this.wasmStage=e.world.simulation.adapter}async spawnEntity(e){if(!this.scene||!this.world)return;if(e instanceof W){e.create();for(let i of e.getChildren())i instanceof O&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:S(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();je(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof O&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:S(),camera:this.camera}),this.tryRegisterRenderStrategy(t),R(t)||this.scene.addEntityGroup(t),T(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),Ke(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),R(e)||this.scene.addEntityGroup(e),T(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(F(e.options)!=="environment")return;let t=e.options.collision??{};t.static!==!0&&(console.warn(`category 'environment' forces static collision for entity '${e.name||e.uuid}'`),e.options.collision={...t,static:!0}),e.bodyDesc&&e.bodyDesc.kind!==Gt.Static&&(e.bodyDesc.kind=Gt.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof j){if(e.needsDeferredModelCollision())return;e.synchronizeRuntimeCollider()}this.world.addEntity(e)}}addEntityToStage(e){this.childrenMap.set(e.uuid,e),m.enabled&&this.debugMap.set(e.uuid,e);for(let t of this.entityAddedHandlers)try{t(e)}catch(i){console.error("onEntityAdded handler failed",i)}}removeEntityByUuid(e){if(!this.scene||!this.world)return!1;let t=this.world.collisionMap.get(e),i=this.childrenMap.get(e),r=t??i??this.debugMap.get(e);return r?(this.unregisterBehaviorLinks(r),this.entityModelDelegate.unobserve(e),R(r)&&this.renderStrategy?.unregister(r),this.world.destroyEntity(r),r.group?this.scene.scene.remove(r.group):r.mesh&&this.scene.scene.remove(r.mesh),this.childrenMap.delete(e),this.debugMap.delete(e),!0):!1}getEntityByName(e){for(let t of this.childrenMap.values())if(t.name===e)return t;return console.warn(`Entity ${e} not found`),null}buildEntityState(e){return e instanceof Qe?{...e.buildInfo()}:{uuid:e.uuid,name:e.name}}onEntityAdded(e,t){return this.entityAddedHandlers.push(e),t?.replayExisting&&this._isLoaded&&this.childrenMap.forEach(i=>{try{e(i)}catch(r){console.error("onEntityAdded replay failed",r)}}),()=>{this.entityAddedHandlers=this.entityAddedHandlers.filter(i=>i!==e)}}enqueue(...e){for(let t of e)if(t){if(E(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();E(i)?this.handleEntityImmediatelyOrQueue(i):N(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}N(t)&&this.handlePromiseWithSpawnOnResolve(t)}}handleEntityImmediatelyOrQueue(e){this._isLoaded?this.spawnEntity(e):this.children.push(e)}handlePromiseWithSpawnOnResolve(e){this._isLoaded?e.then(t=>this.spawnEntity(t)).catch(t=>console.error("Failed to build async entity",t)):this.pendingPromises.push(e)}yieldToEventLoop(){return new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>e(),t.port2.postMessage(void 0)})}async runEntityLoadGenerator(){let t=0;if(this.pendingEntities.length){let a=[...this.pendingEntities];this.pendingEntities=[],this.enqueue(...a)}let i=[...this.pendingPromises];this.pendingPromises=[];let r=this.children.length+i.length;for(let a of this.children)await this.spawnEntity(a),t++,this.loadingDelegate.emitProgress(`Loaded ${a.name||"unknown"}`,t,r),t%5===0&&await this.yieldToEventLoop();for(let a of i){try{let n=await a;n&&await this.spawnEntity(n)}catch(n){console.error("Failed to resolve pending stage entity",n)}t++,this.loadingDelegate.emitProgress("Loaded async entity",t,r),t%5===0&&await this.yieldToEventLoop()}t%5!==0&&await this.yieldToEventLoop()}registerSystem(e){if(!this.world||!this.scene)return;let t;typeof e=="function"?t=e({world:this.world,scene:this.scene,getBehaviorLinks:i=>this.behaviorEntityIndex.get(i)??s.EMPTY_BEHAVIOR_LINKS,createEntity:Ee,getGlobals:S}):t=e,this.behaviorSystems.push(t)}destroyAll(){for(let e of this.behaviorSystems)e.destroy?.();this.behaviorSystems.length=0,this.behaviorSystemByKey.clear(),this.registeredSystemKeys.clear(),this.behaviorEntityIndex.clear(),this.behaviorLinksByUuid.clear(),this.childrenMap.forEach(e=>{try{e.nodeDestroy({me:e,globals:S()})}catch{}$(e)}),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[],this._isLoaded=!1,this.scene=null,this.world=null,this.renderStrategy=null,this.camera=null,this.wasmStage=null}registerBehaviorLinks(e){if(!this.world||!this.scene||typeof e?.getBehaviorRefs!="function")return;let t=e.getBehaviorRefs();if(!Array.isArray(t)||t.length===0)return;let i=[];for(let r of t){let a=r.descriptor.key,n={entity:e,ref:r};i.push(n);let o=this.behaviorEntityIndex.get(a);o||(o=new Set,this.behaviorEntityIndex.set(a,o)),o.add(n);let l=this.behaviorSystemByKey.get(a);if(!l&&!this.registeredSystemKeys.has(a)){let d=r.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:c=>this.behaviorEntityIndex.get(c)??s.EMPTY_BEHAVIOR_LINKS,createEntity:Ee,getGlobals:S});l=d,this.behaviorSystems.push(d),this.behaviorSystemByKey.set(a,d),this.registeredSystemKeys.add(a)}l?.attach?.(n)}this.behaviorLinksByUuid.set(e.uuid,i)}unregisterBehaviorLinks(e){let t=this.behaviorLinksByUuid.get(e?.uuid);if(t){for(let i of t){let r=i.ref?.descriptor?.key;if(!r)continue;let a=this.behaviorEntityIndex.get(r);a&&(this.behaviorSystemByKey.get(r)?.detach?.(i),a.delete(i),a.size===0&&this.behaviorEntityIndex.delete(r))}this.behaviorLinksByUuid.delete(e.uuid)}}};var Yi="Stage",Se=class extends pe{type=Yi;state={...Je};gravity;world;scene;renderStrategy=null;debugDelegate=null;uuid;wrapperRef=null;camera;cameras=[];cameraRef=null;cameraManagerRef=null;rendererManager=null;cameraDelegate;loadingDelegate;entityModelDelegate;childUpdateParams={};entityDelegate;constructor(e=[]){super(),this.world=null,this.scene=null,this.uuid=Qi(),this.cameraDelegate=new ye(this),this.loadingDelegate=new be,this.entityModelDelegate=new ve,this.entityDelegate=new Ce(this.loadingDelegate,this.entityModelDelegate);let t=At(e);this.camera=t.camera,this.cameras=t.cameras,this.entityDelegate.children=t.entities,t.asyncEntities.length&&this.entityDelegate.enqueue(...t.asyncEntities),this.state={...this.state,inputs:t.config.inputs,backgroundColor:t.config.backgroundColor,backgroundImage:t.config.backgroundImage,backgroundShader:t.config.backgroundShader,gravity:t.config.gravity,variables:t.config.variables,physicsRate:t.config.physicsRate,assetLoaders:t.config.assetLoaders,defaultLighting:t.config.defaultLighting,postProcessingEffects:t.config.postProcessingEffects,entities:[]},this.gravity=t.config.gravity??new Nt(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Ut?e:new Ut(e);et(i),tt(t),it(this.state.variables??{})}resolveRenderer(e){return this.rendererManager?.renderer?this.rendererManager.renderer:e.renderer?e.renderer:null}async load(e,t,i){this.setState(),i&&(this.rendererManager=i),this.rendererManager&&(this.cameraManagerRef=this.cameraDelegate.buildCameraManager(t,...this.cameras));let r=this.cameraManagerRef?.primaryCamera??this.cameraDelegate.resolveCamera(t,this.camera);this.cameraRef=r,this.scene=new me(e,r,this.state);let a=this.gravity??new Nt(0,0,0);if(this.world=await ce.create(a,this.state.physicsRate),this.scene.setup(),this.cameraManagerRef&&this.rendererManager){await this.scene.setupCameraManager(this.scene.scene,this.cameraManagerRef,this.rendererManager);let o=this.cameraManagerRef.primaryCamera;o&&(this.rendererManager.setPostProcessingEffects(this.state.postProcessingEffects??[]),this.rendererManager.setupPostProcessing(this.scene.scene,o.camera)),this.rendererManager.startRenderLoop(()=>{this.cameraManagerRef?.render(this.scene.scene)})}else await this.scene.setupCamera(this.scene.scene,r);let n=this.resolveRenderer(r);await x.configureGLTFRuntime({renderer:n,...de(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,o=>this.entityDelegate.handleLateModelReady(o)),this.renderStrategy=new J,this.renderStrategy.setScene(this.scene.scene),this.entityDelegate.attach({scene:this.scene,world:this.world,renderStrategy:this.renderStrategy,camera:r}),this.loadingDelegate.emitStart(),await this.entityDelegate.runEntityLoadGenerator(),this.entityDelegate.isLoaded=!0,this.loadingDelegate.emitComplete()}hasSetup=!1;_setup(e){if(!this.hasSetup){if(!this.scene||!this.world){this.logMissingEntities();return}this.debugDelegate=new fe(this),this.hasSetup=!0}}_update(e){let{delta:t}=e;if(!this.scene||!this.world){this.logMissingEntities();return}let i=this.world,r=this.scene;P("behaviorSystems",()=>{for(let a of this.entityDelegate.behaviorSystems)a.update(void 0,t)}),P("entityLoop",()=>{for(let a of this.entityDelegate.childrenMap.values()){let n=this.childUpdateParams;n.delta=e.delta,n.inputs=e.inputs,n.globals=e.globals,n.camera=e.camera,n.stage=e.stage,n.game=e.game,n.me=a,a.nodeUpdate(n);let o=a;o.transformStore&&st(o,o.transformStore),a.markedForRemoval&&this.entityDelegate.removeEntityByUuid(a.uuid)}}),P("worldUpdate",()=>{i.update(e)}),P("syncRenderPoses",()=>{Ft({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),P("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),P("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),P("scene",()=>{r.update({delta:t})}),Pt()}outOfLoop(){this.debugUpdate()}debugUpdate(){m.enabled&&(Te("debugUpdate"),this.debugDelegate?.update(),xe())}_destroy(e){this.entityDelegate.destroyAll(),this.world?.destroy(),this.scene?.destroy(),this.debugDelegate?.dispose(),this.debugDelegate=null,this.entityModelDelegate.dispose(),this.renderStrategy?.dispose(),this.renderStrategy=null,this.rendererManager&&this.rendererManager.stopRenderLoop(),this.world=null,this.scene=null,this.cameraRef=null,this.cameraManagerRef=null,rt(),$(this)}async spawnEntity(e){return this.entityDelegate.spawnEntity(e)}buildEntityState(e){return this.entityDelegate.buildEntityState(e)}onEntityAdded(e,t){return this.entityDelegate.onEntityAdded(e,t)}onLoading(e){return this.loadingDelegate.onLoading(e)}registerSystem(e){return this.entityDelegate.registerSystem(e),this}removeEntityByUuid(e){return this.entityDelegate.removeEntityByUuid(e)}getEntityByName(e){return this.entityDelegate.getEntityByName(e)}enqueue(...e){this.entityDelegate.enqueue(...e)}logMissingEntities(){console.warn("Zylem world or scene is null")}addCamera(e,t){return this.cameraManagerRef?this.cameraManagerRef.addCamera(e,t):(console.warn("ZylemStage: CameraManager not available. Ensure stage is loaded with a RendererManager."),null)}removeCamera(e){return this.cameraManagerRef?.removeCamera(e)??!1}setActiveCamera(e){return this.cameraManagerRef?.setActiveCamera(e)??!1}getCamera(e){return this.cameraManagerRef?.getCamera(e)??null}resize(e,t){this.scene&&this.scene.updateRenderer(e,t)}};import{proxy as $i}from"valtio/vanilla";import{Vector3 as qi}from"three";var Xi={backgroundColor:Q,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new qi(0,0,0),variables:{}},_=$i({...Xi});function Wt(s){let e=Ji(),t={};return typeof s[0]=="object"&&(t=s.shift()??{}),[{...e,...t},...s]}function Ji(){return{backgroundColor:_.backgroundColor,backgroundImage:_.backgroundImage??null,inputs:_.inputs?{..._.inputs}:void 0,gravity:_.gravity,variables:_.variables?{..._.variables}:void 0}}var Fe=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Ne;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];x.prepareGLTFRuntime(de(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=Ue(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){Y.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new Se(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(d=>{this.wrappedStage.onLoading(d)}),this.pendingLoadingCallbacks=[];let a=t instanceof y?t.cameraRef:t;await this.wrappedStage.load(e,a,i);let n=null,o=!1,l=()=>{if(o=!1,!n?.length){n=null;return}let d=n;n=null,Y.entities=[...Y.entities,...d]};this.wrappedStage.onEntityAdded(d=>{if(I(d.options))return;let c=this.wrappedStage.buildEntityState(d);n||(n=[]),n.push(c),o||(o=!0,queueMicrotask(l))},{replayExisting:!0}),this.applyLifecycleCallbacks()}applyLifecycleCallbacks(){this.wrappedStage&&(this.setupCallbacks.length>0&&(this.wrappedStage.setup=e=>{let t={...e,stage:this};this.setupCallbacks.forEach(i=>i(t))}),this.updateCallbacks.length>0&&(this.wrappedStage.update=e=>{let t={...e,stage:this};this.updateCallbacks.forEach(i=>i(t))}),this.destroyCallbacks.length>0&&(this.wrappedStage.destroy=e=>{let t={...e,stage:this};this.destroyCallbacks.forEach(i=>i(t))}))}async addEntities(e){this._pendingEntities.push(...e),this.wrappedStage&&this.wrappedStage.enqueue(...e)}add(...e){this.addToBlueprints(...e),this.addToStage(...e)}addToBlueprints(...e){this.wrappedStage||this.options.push(...e)}addToStage(...e){this.wrappedStage&&this.wrappedStage.enqueue(...e)}start(e){!this.wrappedStage||this.wrappedStage.hasSetup||this.wrappedStage.nodeSetup(e)}onUpdate(...e){return this.updateCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.update=t=>{let i={...t,stage:this};this.updateCallbacks.forEach(r=>r(i))}),this}onSetup(...e){return this.setupCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.setup=t=>{let i={...t,stage:this};this.setupCallbacks.forEach(r=>r(i))}),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.destroy=t=>{let i={...t,stage:this};this.destroyCallbacks.forEach(r=>r(i))}),this}onLoading(e){return this.wrappedStage?this.wrappedStage.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e)})}getEntityByName(e,t){return this.wrappedStage?.getEntityByName(e)}addCamera(e,t){let i=e instanceof y?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof y?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof y?this.wrappedStage?.setActiveCamera(e.cameraRef)??!1:this.wrappedStage?.setActiveCamera(e)??!1}getCamera(e){return this.wrappedStage?.getCamera(e)??null}dispatch(e,t){this.eventDelegate.dispatch(e,t),A.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function Zn(...s){let e=Wt(s);return new Fe([...e])}export{lr as a,q as b,F as c,I as d,R as e,X as f,J as g,Mr as h,p as i,M as j,ie as k,D as l,k as m,G as n,L as o,oe as p,y as q,Ra as r,Za as s,Ci as t,Fe as u,Zn as v};
@@ -0,0 +1,19 @@
1
+ import{a as R}from"./chunk-QXVH6POE.js";import{b as p,i as h}from"./chunk-7WRQ2UAN.js";var C=`
2
+ uniform vec2 uvScale;
3
+ varying vec2 vUv;
4
+
5
+ void main() {
6
+ vUv = uv;
7
+ vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
8
+ gl_Position = projectionMatrix * mvPosition;
9
+ }
10
+ `;var D=`
11
+ uniform sampler2D tDiffuse;
12
+ varying vec2 vUv;
13
+
14
+ void main() {
15
+ vec4 texel = texture2D( tDiffuse, vUv );
16
+
17
+ gl_FragColor = texel;
18
+ }
19
+ `,O={vertex:C,fragment:D};import{Color as F,RepeatWrapping as v,SRGBColorSpace as te}from"three";import{MeshBasicNodeMaterial as re,MeshStandardNodeMaterial as P}from"three/webgpu";function G(s){let e=Object.keys(s).sort().reduce((t,r)=>(t[r]=s[r],t),{});return JSON.stringify(e)}function E(s){let e=0;for(let t=0;t<s.length;t++)e=Math.imul(31,e)+s.charCodeAt(t)|0;return e.toString(36)}import{LoadingManager as ee,Cache as k}from"three";import{TextureLoader as X,RepeatWrapping as B}from"three";var b=16,L=class{loader;constructor(){this.loader=new X}isSupported(e){let t=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","bmp","tga"].includes(t||"")}async load(e,t){let r=await this.loader.loadAsync(e,a=>{t?.onProgress&&a.lengthComputable&&t.onProgress(a.loaded/a.total)});return t?.repeat&&r.repeat.copy(h(t.repeat,p)),r.wrapS=t?.wrapS??B,r.wrapT=t?.wrapT??B,t?.colorSpace!==void 0&&(r.colorSpace=t.colorSpace),r.anisotropy=t?.anisotropy??b,r}clone(e){let t=e.clone();return t.anisotropy=e.anisotropy||b,t.needsUpdate=!0,t}};import{GLTFLoader as J}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as K}from"three/addons/loaders/DRACOLoader.js";import{KTX2Loader as Z}from"three/addons/loaders/KTX2Loader.js";import{MeshoptDecoder as $}from"three/addons/libs/meshopt_decoder.module.js";import{Mesh as j}from"three";import{clone as W}from"three/addons/utils/SkeletonUtils.js";function u(s){let e=W(s),t=[],r=[];s.traverse(a=>t.push(a)),e.traverse(a=>r.push(a));for(let a=0;a<t.length;a++){let o=t[a],n=r[a];!(o instanceof j)||!(n instanceof j)||(o.geometry?.clone&&(n.geometry=o.geometry.clone()),o.material&&(n.material=Array.isArray(o.material)?o.material.map(i=>i.clone()):o.material.clone()))}return e}function I(s){let e=s.indexOf("?"),t=s.indexOf("#"),r=[e,t].filter(a=>a>=0).reduce((a,o)=>Math.min(a,o),s.length);return s.slice(0,r)}function c(s){let e=I(s),t=e.lastIndexOf("/"),r=t>=0?e.slice(t+1):e,a=r.lastIndexOf(".");return a<0||a===r.length-1?null:r.slice(a+1).toLowerCase()}var V=["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"],H="https://www.gstatic.com/draco/v1/decoders/",g=class{loader;dracoLoader;ktx2Loader=null;meshoptEnabled=!1;configuredRenderer=null;ktx2TranscoderPath=null;constructor(){this.dracoLoader=new K,this.dracoLoader.setDecoderPath(H),this.loader=new J,this.loader.setDRACOLoader(this.dracoLoader),this.setMeshoptEnabled(!0)}isSupported(e){let t=c(e);return["gltf","glb"].includes(t||"")}async configureRuntime({meshopt:e=!0,ktx2TranscoderPath:t,renderer:r=null}={}){this.setMeshoptEnabled(e!==!1);let a=this.normalizeTranscoderPath(t);if(!a){this.clearKTX2Loader();return}if(!r)throw new Error("GLTFLoaderAdapter.configureRuntime requires a renderer when ktx2TranscoderPath is provided.");(!this.ktx2Loader||this.ktx2TranscoderPath!==a)&&(this.clearKTX2Loader(),this.ktx2Loader=new Z,this.ktx2Loader.setTranscoderPath(a),this.loader.setKTX2Loader(this.ktx2Loader),this.ktx2TranscoderPath=a,this.configuredRenderer=null),!(!this.ktx2Loader||this.configuredRenderer===r)&&(this.ktx2Loader.detectSupport(r),this.configuredRenderer=r)}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=await this.loader.parseAsync(a,e);return this.applyTextureAnisotropy(o.scene),{object:o.scene,animations:o.animations,gltf:o}}catch(r){return console.error(`Async fetch GLTF load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{this.applyTextureAnisotropy(o.scene),r({object:o.scene,animations:o.animations,gltf:o})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone()),gltf:e.gltf}}applyTextureAnisotropy(e){e.traverse(t=>{let r=t.material;if(!r)return;let a=Array.isArray(r)?r:[r];for(let o of a)for(let n of V){let i=o[n];if(i&&i.isTexture){let d=i;d.anisotropy=b,d.needsUpdate=!0}}})}setMeshoptEnabled(e){if(e){if(this.meshoptEnabled)return;this.loader.setMeshoptDecoder($),this.meshoptEnabled=!0;return}this.meshoptEnabled&&(this.loader.setMeshoptDecoder(void 0),this.meshoptEnabled=!1)}clearKTX2Loader(){this.ktx2Loader&&(this.ktx2Loader.dispose(),this.ktx2Loader=null),this.loader.setKTX2Loader(void 0),this.configuredRenderer=null,this.ktx2TranscoderPath=null}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}};import{FBXLoader as _}from"three/addons/loaders/FBXLoader.js";var T=class{loader;constructor(){this.loader=new _}isSupported(e){return c(e)==="fbx"}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=this.loader.parse(a,e);return{object:o,animations:o.animations||[]}}catch(r){return console.error(`Async fetch FBX load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:o.animations||[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone())}}};import{OBJLoader as z}from"three/addons/loaders/OBJLoader.js";import{MTLLoader as Y}from"three/addons/loaders/MTLLoader.js";var y=class{loader;mtlLoader;constructor(){this.loader=new z,this.mtlLoader=new Y}isSupported(e){return c(e)==="obj"}async load(e,t){return t?.mtlPath&&await this.loadMTL(t.mtlPath),new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}async loadMTL(e){return new Promise((t,r)=>{this.mtlLoader.load(e,a=>{a.preload(),this.loader.setMaterials(a),t()},void 0,a=>r(a))})}clone(e){return{object:u(e.object),animations:[]}}};import{AudioLoader as q}from"three";var x=class{loader;constructor(){this.loader=new q}isSupported(e){let t=c(e);return["mp3","ogg","wav","flac","aac","m4a"].includes(t||"")}async load(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>r(o),o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}};import{FileLoader as Q}from"three";var m=class{loader;constructor(){this.loader=new Q}isSupported(e){return!0}async load(e,t){let r=t?.responseType??"text";return this.loader.setResponseType(r),new Promise((a,o)=>{this.loader.load(e,n=>a(n),n=>{t?.onProgress&&n.lengthComputable&&t.onProgress(n.loaded/n.total)},n=>o(n))})}},M=class{fileLoader;constructor(){this.fileLoader=new m}isSupported(e){return c(e)==="json"}async load(e,t){return await this.fileLoader.load(e,{...t,responseType:"json"})}};var w=class s{static instance=null;textureCache=new Map;modelCache=new Map;audioCache=new Map;fileCache=new Map;jsonCache=new Map;pendingGLTFRuntimePath=null;pendingGLTFRuntimePromise=null;pendingGLTFRuntimeResolve=null;textureLoader;gltfLoader;fbxLoader;objLoader;audioLoader;fileLoader;jsonLoader;loadingManager;events;stats={texturesLoaded:0,modelsLoaded:0,audioLoaded:0,filesLoaded:0,cacheHits:0,cacheMisses:0};constructor(){this.textureLoader=new L,this.gltfLoader=new g,this.fbxLoader=new T,this.objLoader=new y,this.audioLoader=new x,this.fileLoader=new m,this.jsonLoader=new M,this.loadingManager=new ee,this.loadingManager.onProgress=(e,t,r)=>{this.events.emit("batch:progress",{loaded:t,total:r})},this.events=R(),k.enabled=!0}static getInstance(){return s.instance||(s.instance=new s),s.instance}static resetInstance(){s.instance&&(s.instance.clearCache(),s.instance=null)}async loadTexture(e,t){return this.loadWithCache(e,"texture",this.textureCache,()=>this.textureLoader.load(e,t),t,r=>{if(!t?.clone)return r;let a=this.textureLoader.clone(r);return t.repeat&&a.repeat.copy(h(t.repeat,p)),t.wrapS!==void 0&&(a.wrapS=t.wrapS),t.wrapT!==void 0&&(a.wrapT=t.wrapT),a})}async loadGLTF(e,t){return await this.waitForPreparedGLTFRuntime(),this.loadWithCache(e,"gltf",this.modelCache,()=>this.gltfLoader.load(e,t),t,r=>t?.clone?this.gltfLoader.clone(r):r)}prepareGLTFRuntime(e){let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&(this.pendingGLTFRuntimePath===t&&this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePath=t,this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePromise=new Promise(r=>{this.pendingGLTFRuntimeResolve=r}))))}async configureGLTFRuntime(e){await this.gltfLoader.configureRuntime(e);let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&e?.renderer&&this.resolvePreparedGLTFRuntime(t)}async loadFBX(e,t){return this.loadWithCache(e,"fbx",this.modelCache,()=>this.fbxLoader.load(e,t),t,r=>t?.clone?this.fbxLoader.clone(r):r)}async loadOBJ(e,t){let r=t?.mtlPath?`${e}:${t.mtlPath}`:e;return this.loadWithCache(r,"obj",this.modelCache,()=>this.objLoader.load(e,t),t,a=>t?.clone?this.objLoader.clone(a):a)}async loadModel(e,t){let r=c(e);switch(r){case"gltf":case"glb":return this.loadGLTF(e,t);case"fbx":return this.loadFBX(e,t);case"obj":return this.loadOBJ(e,t);default:throw new Error(`Unsupported model format: ${r}`)}}async loadAudio(e,t){return this.loadWithCache(e,"audio",this.audioCache,()=>this.audioLoader.load(e,t),t)}async loadFile(e,t){let r=t?.responseType?`${e}:${t.responseType}`:e;return this.loadWithCache(r,"file",this.fileCache,()=>this.fileLoader.load(e,t),t)}async loadJSON(e,t){return this.loadWithCache(e,"json",this.jsonCache,()=>this.jsonLoader.load(e,t),t)}async loadBatch(e){let t=new Map,r=e.map(async a=>{try{let o;switch(a.type){case"texture":o=await this.loadTexture(a.url,a.options);break;case"gltf":o=await this.loadGLTF(a.url,a.options);break;case"fbx":o=await this.loadFBX(a.url,a.options);break;case"obj":o=await this.loadOBJ(a.url,a.options);break;case"audio":o=await this.loadAudio(a.url,a.options);break;case"file":o=await this.loadFile(a.url,a.options);break;case"json":o=await this.loadJSON(a.url,a.options);break;default:throw new Error(`Unknown asset type: ${a.type}`)}t.set(a.url,o)}catch(o){throw this.events.emit("asset:error",{url:a.url,type:a.type,error:o}),o}});return await Promise.all(r),this.events.emit("batch:complete",{urls:e.map(a=>a.url)}),t}async preload(e){await this.loadBatch(e)}isCached(e){return this.textureCache.has(e)||this.modelCache.has(e)||this.audioCache.has(e)||this.fileCache.has(e)||this.jsonCache.has(e)}clearCache(e){e?(this.textureCache.delete(e),this.modelCache.delete(e),this.audioCache.delete(e),this.fileCache.delete(e),this.jsonCache.delete(e)):(this.textureCache.clear(),this.modelCache.clear(),this.audioCache.clear(),this.fileCache.clear(),this.jsonCache.clear(),k.clear(),this.pendingGLTFRuntimePath=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimeResolve=null)}getStats(){return{...this.stats}}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}async loadWithCache(e,t,r,a,o,n){o?.forceReload&&r.delete(e);let i=r.get(e);if(i){this.stats.cacheHits++,this.events.emit("asset:loaded",{url:e,type:t,fromCache:!0});let l=await i.promise;return n?n(l):l}this.stats.cacheMisses++,this.events.emit("asset:loading",{url:e,type:t});let d=a(),f={promise:d,loadedAt:Date.now()};r.set(e,f);try{let l=await d;return f.result=l,this.updateStats(t),this.events.emit("asset:loaded",{url:e,type:t,fromCache:!1}),n?n(l):l}catch(l){throw r.delete(e),this.events.emit("asset:error",{url:e,type:t,error:l}),l}}updateStats(e){switch(e){case"texture":this.stats.texturesLoaded++;break;case"gltf":case"fbx":case"obj":this.stats.modelsLoaded++;break;case"audio":this.stats.audioLoaded++;break;case"file":case"json":this.stats.filesLoaded++;break}}async waitForPreparedGLTFRuntime(){this.pendingGLTFRuntimePromise&&await this.pendingGLTFRuntimePromise}resolvePreparedGLTFRuntime(e){this.pendingGLTFRuntimePath&&this.pendingGLTFRuntimePath!==e||(this.pendingGLTFRuntimeResolve?.(),this.pendingGLTFRuntimeResolve=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimePath=null)}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}},A=w.getInstance();import{uniform as vt,uv as Ot,time as wt,vec3 as At,vec4 as Ft,float as Pt,Fn as St}from"three/tsl";function ae(s){return"colorNode"in s}function N(s){return"fragment"in s&&"vertex"in s}function oe(s){return!!s&&N(s)&&s.vertex===O.vertex&&s.fragment===O.fragment}var U=class s{static sharedMaterialMap=new Map;static clearSharedMaterialCache(){s.sharedMaterialMap.clear()}materials=[];useTSL;constructor(e=!0){this.useTSL=e}trackSharedMaterial(e,t){let r=E(G(e)),a=s.sharedMaterialMap.get(r);if(a){let o=a.geometryMap.get(t);o?a.geometryMap.set(t,o+1):a.geometryMap.set(t,1)}else s.sharedMaterialMap.set(r,{geometryMap:new Map([[t,1]]),material:this.materials[0]})}build(e,t){let{path:r,normalMap:a,repeat:o,color:n,shader:i,opacity:d}=e,f=oe(i),l=!!i&&!f,S=!!r&&(!i||f);S?this.setTexture(r??null,o,!0,d,n):l&&i?ae(i)?this.setTSLShader(i,d):N(i)&&(console.warn("MaterialBuilder: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(n??new F("#ffffff"),!0,d)):r&&this.setTexture(r,o,!0,d,n),n&&!S&&!l&&this.withColor(n,!0,d),this.materials.length===0&&this.setColor(new F("#ffffff"),!0,d),a&&this.materials.length>0&&this.setNormalMap(a,o),this.trackSharedMaterial(e,t)}withColor(e,t=!1,r){return this.setColor(e,t,r),this}withShader(e,t){return this.setShader(e,t),this}withTSLShader(e,t){return this.setTSLShader(e,t),this}applyOpacity(e,t,r=!1){t!==void 0&&(e.opacity=t),e.transparent=r||t!==void 0&&t<1,e.needsUpdate=!0}setTexture(e=null,t=p,r=!0,a,o){if(!e)return;let n=new P;o&&(n.color=o),this.applyOpacity(n,a),this.materials.push(n),A.loadTexture(e,{clone:!0,repeat:h(t,p),colorSpace:te}).then(i=>{i.wrapS=v,i.wrapT=v,n.map=i,n.needsUpdate=!0})}setNormalMap(e,t=p){let r=this.materials[this.materials.length-1];r&&A.loadTexture(e,{clone:!0,repeat:h(t,p)}).then(a=>{a.wrapS=v,a.wrapT=v,r instanceof P&&(r.normalMap=a,r.needsUpdate=!0)})}setColor(e,t=!0,r){let a=new P;a.color=e,this.applyOpacity(a,r),this.materials.push(a)}setShader(e,t){console.warn("MaterialBuilder.setShader: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(new F("#ffffff"),!0,t)}setTSLShader(e,t){this.materials.push(se(e,t))}};function se(s,e){let t=new re;return t.colorNode=s.colorNode,s.positionNode&&(t.positionNode=s.positionNode),s.normalNode&&(t.normalNode=s.normalNode),s.blending!==void 0&&(t.blending=s.blending),s.side!==void 0&&(t.side=s.side),s.depthTest!==void 0&&(t.depthTest=s.depthTest),e!==void 0&&(t.opacity=e),t.transparent=!!s.transparent||e!==void 0&&e<1,t.needsUpdate=!0,t}export{C as a,O as b,b as c,c as d,A as e,G as f,E as g,ae as h,N as i,U as j,se as k,vt as l,Ot as m,wt as n,At as o,Ft as p,Pt as q,St as r};
@@ -0,0 +1 @@
1
+ import{a as u}from"./chunk-VS2D4B3W.js";import{DirectionalLight as b,PerspectiveCamera as f,RenderTarget as T,Scene as E,Color as v,LinearFilter as g}from"three";var w=128,h=class{cache=new Map;inFlight=new Map;renderer=null;size;constructor(e=w){this.size=e}setRenderer(e){this.renderer=e}get(e){return this.cache.get(e)??null}invalidate(e){this.cache.delete(e),this.inFlight.delete(e)}clear(){this.cache.clear(),this.inFlight.clear()}async ensure(e,i){let t=this.cache.get(e);if(t)return t;let r=this.inFlight.get(e);if(r)return r;if(!i||!this.renderer)return null;let s=this.render(e,i).then(n=>(this.inFlight.delete(e),n?(this.cache.set(e,n),n):null)).catch(n=>(this.inFlight.delete(e),console.warn("EntityThumbnailCache: failed to render thumbnail",e,n),null));return this.inFlight.set(e,s),s}async render(e,i){let t=this.renderer;if(!t)return null;let r=new E;r.background=new v(3815994);let s=new b(16777215,2);s.position.set(5,10,7),r.add(s);let n=i.clone(!0);n.position.set(0,0,0),n.rotation.set(0,0,0),n.updateMatrixWorld(!0),r.add(n);let a=new f(50,1,.1,100),l=u(n,a),o=new T(this.size,this.size,{minFilter:g,magFilter:g}),m=t.getRenderTarget(),p=t.getScissorTest();try{t.setScissorTest(!1),t.setRenderTarget(o),t.render(r,a)}finally{t.setRenderTarget(m),t.setScissorTest(p)}let y=await t.readRenderTargetPixelsAsync(o,0,0,this.size,this.size);o.dispose(),r.remove(n);let d=R(y,this.size,this.size);return d?{uuid:e,dataUrl:d,bounds:{width:l.width,height:l.height,depth:l.depth}}:null}},D=new h;function R(c,e,i){if(typeof document>"u")return null;let t=document.createElement("canvas");t.width=e,t.height=i;let r=t.getContext("2d");if(!r)return null;let s=c instanceof Uint8Array?c:new Uint8Array(c.buffer,c.byteOffset,c.byteLength),n=r.createImageData(e,i);for(let a=0;a<i;a+=1){let l=(i-1-a)*e*4,o=a*e*4;n.data.set(s.subarray(l,l+e*4),o)}return r.putImageData(n,0,0),t.toDataURL("image/png")}export{h as a,D as b};
@@ -0,0 +1 @@
1
+ import{a as s,b as d}from"./chunk-4QLJUQSJ.js";import{c as i,d as c}from"./chunk-7WRQ2UAN.js";import{Color as f,Vector3 as y}from"three";import{proxy as x,subscribe as k}from"valtio/vanilla";import{Color as V,Vector3 as b}from"three";var m=new V("#0333EC");var S=new b(i.x,i.y,i.z),E=new b(c.x,c.y,c.z);var Z={backgroundColor:m,backgroundImage:null,backgroundShader:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new y(0,0,0),variables:{},physicsRate:60,defaultLighting:!0,entities:[]},l=x({backgroundColor:new f(f.NAMES.cornflowerblue),backgroundImage:null,inputs:{p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},variables:{},gravity:new y(0,0,0),entities:[]}),A=e=>{l.backgroundColor=e},P=e=>{l.backgroundImage=e},G=e=>{l.variables={...e}},O=()=>{l.variables={}},u=new Map;function g(e){let t=u.get(e);return t||(t=x({}),u.set(e,t)),t}function z(e,t,r){let o=g(e);d(o,t,r)}function M(e,t,r){let o=g(e),a=s(o,t);return a===void 0?(d(o,t,r),r):a}function N(e,t){let r=u.get(e);if(r)return s(r,t)}function _(e,t,r){let o=g(e),a=s(o,t);return k(o,()=>{let n=s(o,t);n!==a&&(a=n,r(n))})}function D(e,t,r){let o=g(e),a=t.map(n=>s(o,n));return k(o,()=>{let n=t.map(p=>s(o,p));n.some((p,C)=>p!==a[C])&&(a=n,r(n))})}function L(e){u.delete(e)}export{m as a,Z as b,l as c,A as d,P as e,G as f,O as g,z as h,M as i,N as j,_ as k,D as l,L as m};
File without changes
@@ -0,0 +1 @@
1
+ import{c as r,d as l,h as s}from"./chunk-7WRQ2UAN.js";import{StageBodyKind as a}from"@zylem/behaviors/core";function c(t){if(t!==void 0)return typeof t=="boolean"?[t,t,t]:t}var f=new Map,d=0;function p(t){let o=f.get(t);return o===void 0&&(o=d++%16,f.set(t,o)),o}function b(t){let o=0;return t.forEach(n=>{let i=p(n);o|=1<<i}),o}function y(t,o){if(!t)return 4294967295;let n=p(t),i=o?b(o):65535;return(1<<n&65535)<<16|i&65535}var u=class{static=!1;sensor=!1;gravityScale;lockRotations;lockTranslations;build(o){let n=this.bodyDesc({isDynamicBody:!this.static}),i=this.collider(o);return this.sensor&&(i.sensor=!0),o.collisionType&&(i.collisionGroups=y(o.collisionType,o.collisionFilter)),[n,i]}withCollision(o){return this.sensor=o?.sensor??this.sensor,this.static=o?.static??this.static,this.gravityScale=o?.gravityScale??this.gravityScale,this.lockRotations=o?.lockRotations??this.lockRotations,this.lockTranslations=o?.lockTranslations??this.lockTranslations,this}collider(o){let n=s(o.size,l),i=s(o.position,r);return{shape:{type:"box",halfExtents:[n.x/2,n.y/2,n.z/2]},offset:[i.x,i.y,i.z]}}bodyDesc({isDynamicBody:o=!0}){let n={kind:o?a.Dynamic:a.Static,position:[0,0,0],gravityScale:this.gravityScale??1,canSleep:!1,ccdEnabled:!0},i=c(this.lockRotations);i&&(n.lockRotation=i);let e=c(this.lockTranslations);return e&&(n.lockTranslation=e),n}};export{c as a,y as b,u as c};
@@ -0,0 +1 @@
1
+ var c=class{duration;done=!1;persistent=!1;elapsed=0;constructor(t){this.duration=t/1e3}tick(t,i){if(this.done)return;this.elapsed+=i;let n=this.duration>0?Math.min(this.elapsed/this.duration,1):1;this.onTick(t,i,n),this.elapsed>=this.duration&&(this.done=!0)}reset(){this.elapsed=0,this.done=!1}};import{setVelocityIntent as w}from"@zylem/behaviors/core";function A(e){let t=[];for(let i of e)i.traverse(n=>{if(!n.isMesh)return;let r=n,o=s=>{!("opacity"in s)||!("transparent"in s)||t.push(s)};Array.isArray(r.material)?r.material.forEach(o):r.material&&o(r.material)});return t}function E(e,t){if(t&&t.length>0)return t;let i=e.group??e.mesh;return i?[i]:[]}function G(e,t=1,i=!1){let n=E(e,void 0);for(let r of A(n))r.transparent=i,r.opacity=t,r.needsUpdate=!0}function D(e){return new l(e)}var l=class extends c{dx;dy;dz;constructor(t){super(t.duration),this.dx=t.x??0,this.dy=t.y??0,this.dz=t.z??0}onTick(t,i,n){if(this.duration<=0)return;let r=this.dx/this.duration,o=this.dy/this.duration,s=this.dz/this.duration,a=t.transformStore;a&&w(a,"actions",{x:r,y:o,z:s},{mode:"add"})}};function P(e){return new d(e)}var d=class extends c{targetX;targetY;targetZ;dx=0;dy=0;dz=0;initialized=!1;constructor(t){super(t.duration),this.targetX=t.x,this.targetY=t.y,this.targetZ=t.z}onTick(t,i,n){if(this.duration<=0)return;if(!this.initialized){let u=t.getPosition?.(),k=u?.x??0,M=u?.y??0,T=u?.z??0;this.dx=this.targetX-k,this.dy=this.targetY-M,this.dz=this.targetZ-T,this.initialized=!0}let r=this.dx/this.duration,o=this.dy/this.duration,s=this.dz/this.duration,a=t.transformStore;a&&w(a,"actions",{x:r,y:o,z:s},{mode:"add"})}reset(){super.reset(),this.initialized=!1}};function R(e){return new p(e)}var p=class extends c{rx;ry;rz;constructor(t){super(t.duration);let i=Math.PI/180;this.rx=(t.x??0)*i,this.ry=(t.y??0)*i,this.rz=(t.z??0)*i}onTick(t,i,n){if(this.duration<=0)return;let r=this.rx/this.duration,o=this.ry/this.duration,s=this.rz/this.duration,a=t.transformStore;a.angularVelocity.x+=r,a.angularVelocity.y+=o,a.angularVelocity.z+=s,a.dirty.angularVelocity=!0}};function I(e){return new m(e)}var m=class extends c{constructor(t){super(t)}onTick(){}};function X(e){return new h(e)}var h=class extends c{fn;called=!1;constructor(t){super(0),this.fn=t}onTick(){this.called||(this.fn(),this.called=!0)}reset(){super.reset(),this.called=!1}};function Y(e){return new f(e)}var f=class extends c{from;to;targets;restoreOpaque;materials=null;finalized=!1;constructor(t){super(t.duration),this.from=t.from??1,this.to=t.to??0,this.targets=t.targets,this.restoreOpaque=t.restoreOpaque??!1}onTick(t,i,n){if(!this.materials){this.materials=A(E(t,this.targets));for(let o of this.materials)o.transparent=!0,o.needsUpdate=!0}let r=this.from+(this.to-this.from)*n;for(let o of this.materials)o.opacity=r;if(n>=1&&!this.finalized&&(this.finalized=!0,this.restoreOpaque&&this.to>=1))for(let o of this.materials)o.transparent=!1,o.needsUpdate=!0}reset(){super.reset(),this.materials=null,this.finalized=!1}};function B(e){return new y(e.duration)}var y=class{duration;done=!1;persistent=!0;ready=!1;elapsed=0;constructor(t){this.duration=t/1e3}tick(t,i){this.elapsed+=i,this.elapsed>=this.duration&&(this.ready=!0)}consume(){this.ready=!1,this.elapsed=0}reset(){this.elapsed=0,this.ready=!1}};function Z(){return new b}var b=class{duration=1/0;done=!1;persistent=!0;triggered=!1;wasPressed=!1;tick(){this.triggered=!1}check(t){t&&!this.wasPressed&&(this.triggered=!0),this.wasPressed=t}reset(){this.triggered=!1,this.wasPressed=!1}};function j(){return new v}var v=class{duration=1/0;done=!1;persistent=!0;triggered=!1;wasPressed=!1;tick(){this.triggered=!1}check(t){!t&&this.wasPressed&&(this.triggered=!0),this.wasPressed=t}reset(){this.triggered=!1,this.wasPressed=!1}};function V(...e){return new x(e)}var x=class{duration;done=!1;persistent=!1;actions;currentIndex=0;constructor(t){this.actions=t,this.duration=t.reduce((i,n)=>i+n.duration,0)}tick(t,i){if(this.done||this.actions.length===0){this.done=!0;return}let n=i;for(;n>0&&this.currentIndex<this.actions.length;){let r=this.actions[this.currentIndex];if(r.tick(t,n),r.done){let o=r.duration,s=r.elapsed??o;n=Math.max(0,s-o),this.currentIndex++}else n=0}this.currentIndex>=this.actions.length&&(this.done=!0)}reset(){this.currentIndex=0,this.done=!1;for(let t of this.actions)t.reset()}};function q(...e){return new g(e)}var g=class{duration;done=!1;persistent=!1;actions;constructor(t){this.actions=t,this.duration=Math.max(0,...t.map(i=>i.duration))}tick(t,i){if(this.done)return;let n=!0;for(let r of this.actions)r.done||r.tick(t,i),r.done||(n=!1);n&&(this.done=!0)}reset(){this.done=!1;for(let t of this.actions)t.reset()}};function F(e,t){return new O(e,t)}var O=class{duration;done=!1;persistent=!1;action;totalTimes;currentCount=0;constructor(t,i){this.action=t,this.totalTimes=i,this.duration=t.duration*i}tick(t,i){this.done||(this.action.tick(t,i),this.action.done&&(this.currentCount++,this.currentCount>=this.totalTimes?this.done=!0:this.action.reset()))}reset(){this.currentCount=0,this.done=!1,this.action.reset()}};function _(e){return new z(e)}var z=class{duration=1/0;done=!1;persistent=!1;action;constructor(t){this.action=t}tick(t,i){this.action.tick(t,i),this.action.done&&this.action.reset()}reset(){this.done=!1,this.action.reset()}};import{createTransformStore as yt}from"@zylem/behaviors/core";import{move as xt,moveX as gt,moveY as Ot,moveZ as zt,moveXY as wt,moveXZ as At,resetVelocity as Et,moveForwardXY as kt,getPosition as Mt,getVelocity as Tt,setPosition as Gt,setPositionX as Dt,setPositionY as Pt,setPositionZ as Rt,wrapAroundXY as It,wrapAround3D as Xt}from"@zylem/behaviors/core";export{G as a,D as b,P as c,R as d,I as e,X as f,Y as g,B as h,Z as i,j,V as k,q as l,F as m,_ as n,yt as o,xt as p,gt as q,Ot as r,zt as s,wt as t,At as u,Et as v,kt as w,Mt as x,Tt as y,Gt as z,Dt as A,Pt as B,Rt as C,It as D,Xt as E};
@@ -0,0 +1 @@
1
+ import{Type as e}from"@sinclair/typebox";var n=e.Tuple([e.Number(),e.Number()],{title:"Vector2",description:"A 2D position as [x, y]."}),s=e.Object({id:e.String(),type:e.String({minLength:1}),position:e.Optional(n),data:e.Optional(e.Record(e.String(),e.Any()))},{$id:"EntityBlueprint",title:"EntityBlueprint",additionalProperties:!1}),D=e.Object({id:e.String(),name:e.Optional(e.String()),entities:e.Array(s),assets:e.Optional(e.Array(e.String()))},{$id:"StageBlueprint",title:"StageBlueprint",additionalProperties:!1}),S=e.Object({value:e.Optional(e.String()),color:e.Optional(e.String()),fontSize:e.Optional(e.Number()),fontFamily:e.Optional(e.String())},{title:"TextEntityData",additionalProperties:!0}),m=e.Tuple([e.Number(),e.Number(),e.Number()],{title:"Vector3Tuple"}),g=e.Object({points:e.Array(m,{minItems:2}),color:e.Optional(e.String()),colors:e.Optional(e.Array(e.String())),linewidth:e.Optional(e.Number()),worldUnits:e.Optional(e.Boolean()),alphaToCoverage:e.Optional(e.Boolean()),opacity:e.Optional(e.Number()),transparent:e.Optional(e.Boolean()),dashed:e.Optional(e.Boolean()),dashSize:e.Optional(e.Number()),gapSize:e.Optional(e.Number()),pickThreshold:e.Optional(e.Number())},{title:"LineEntityData",additionalProperties:!0}),u=e.Object({imagePath:e.Optional(e.String()),width:e.Optional(e.Number()),height:e.Optional(e.Number())},{title:"SpriteEntityData",additionalProperties:!0}),h=e.Union([e.Object({id:e.String(),type:e.Literal("text"),position:e.Optional(n),data:e.Optional(S)}),e.Object({id:e.String(),type:e.Literal("sprite"),position:e.Optional(n),data:e.Optional(u)}),e.Object({id:e.String(),type:e.Literal("line"),position:e.Optional(n),data:e.Optional(g)}),e.Object({id:e.String(),type:e.String({minLength:1}),position:e.Optional(n),data:e.Optional(e.Record(e.String(),e.Unknown()))})],{$id:"EntityJson",title:"EntityJson"}),B=e.Object({id:e.String(),name:e.Optional(e.String()),entities:e.Array(h),assets:e.Optional(e.Array(e.String()))},{$id:"StageJson",title:"StageJson",additionalProperties:!1});import{Type as t}from"@sinclair/typebox";var y=t.Record(t.String(),t.Array(t.String()),{title:"KeyboardMapping"}),O=t.Record(t.String(),t.Array(t.String()),{title:"MouseMapping"}),a=t.Record(t.String(),t.Union([t.String(),t.Number()]),{title:"VirtualTouchStyle"}),p=t.Object({top:t.Optional(t.Union([t.String(),t.Number()])),right:t.Optional(t.Union([t.String(),t.Number()])),bottom:t.Optional(t.Union([t.String(),t.Number()])),left:t.Optional(t.Union([t.String(),t.Number()])),transform:t.Optional(t.String())},{title:"VirtualTouchPosition",additionalProperties:!1}),f=t.Object({enabled:t.Optional(t.Boolean()),className:t.Optional(t.String()),style:t.Optional(a),position:t.Optional(p),size:t.Optional(t.Number()),label:t.Optional(t.String()),svg:t.Optional(t.String())},{title:"VirtualTouchButtonConfig",additionalProperties:!1}),r=t.Object({enabled:t.Optional(t.Boolean()),className:t.Optional(t.String()),style:t.Optional(a),position:t.Optional(p),size:t.Optional(t.Number()),thumbSize:t.Optional(t.Number()),maxDistance:t.Optional(t.Number()),deadzone:t.Optional(t.Number()),directionThreshold:t.Optional(t.Number()),horizontalAxis:t.Optional(t.Union([t.Literal("Horizontal"),t.Literal("SecondaryHorizontal")])),verticalAxis:t.Optional(t.Union([t.Literal("Vertical"),t.Literal("SecondaryVertical")])),emitDirections:t.Optional(t.Boolean()),svg:t.Optional(t.Object({base:t.Optional(t.String()),thumb:t.Optional(t.String())}))},{title:"VirtualTouchJoystickConfig",additionalProperties:!1}),j=t.Union([f,t.Literal(!1)]),d=t.Record(t.String(),j,{title:"VirtualTouchButtonsConfig",description:"Keys are touch button slots: A, B, X, Y, Start, Select, L, R, LTrigger, RTrigger, Up, Down, Left, Right."}),C=t.Object({left:t.Optional(t.Union([r,t.Literal(!1)])),right:t.Optional(t.Union([r,t.Literal(!1)]))},{title:"VirtualTouchJoysticksConfig",additionalProperties:!1}),b=t.Object({enabled:t.Optional(t.Union([t.Boolean(),t.Literal("auto")])),className:t.Optional(t.String()),style:t.Optional(a),joysticks:t.Optional(t.Union([C,t.Literal(!1)])),buttons:t.Optional(t.Union([d,t.Literal(!1)]))},{title:"VirtualTouchConfig",additionalProperties:!1}),x=t.Object({mapping:t.Optional(O),pointerLock:t.Optional(t.Boolean()),sensitivity:t.Optional(t.Number()),lookMode:t.Optional(t.Union([t.Literal("delta"),t.Literal("screenCenter")])),maxLookDegrees:t.Optional(t.Number()),lookSensitivity:t.Optional(t.Number())},{title:"MouseConfig",additionalProperties:!1}),J=t.Object({key:t.Optional(y),mouse:t.Optional(x),touch:t.Optional(b),includeDefaults:t.Optional(t.Boolean())},{title:"GameInputPlayerConfig",additionalProperties:!1}),l=t.Record(t.String(),J,{$id:"GameInputConfig",title:"GameInputConfig",description:"Keys are player slots: p1, p2, p3, p4, p5, p6, p7, p8."});import{Type as i}from"@sinclair/typebox";var T=i.Union([i.String(),i.Number()],{title:"ColorJson",description:"CSS color string or numeric hex (Three.js Color-compatible)."}),L=i.Tuple([i.Number(),i.Number(),i.Number()],{title:"Vec3Components"}),E=i.Object({meshopt:i.Optional(i.Boolean()),ktx2TranscoderPath:i.Optional(i.String())},{title:"StageGLTFAssetLoaderConfig",additionalProperties:!1}),V=i.Object({gltf:i.Optional(E)},{title:"StageAssetLoaderConfig",additionalProperties:!1}),G=i.Object({inputs:i.Optional(i.Record(i.String(),i.Array(i.String()))),backgroundColor:i.Optional(T),backgroundImage:i.Optional(i.Union([i.String(),i.Null()])),gravity:i.Optional(L),variables:i.Optional(i.Record(i.String(),i.Unknown())),physicsRate:i.Optional(i.Number({exclusiveMinimum:0})),assetLoaders:i.Optional(V),defaultLighting:i.Optional(i.Boolean())},{$id:"StageConfigJson",title:"StageConfigJson",additionalProperties:!1});import{Type as o}from"@sinclair/typebox";var c=o.Union([o.String(),o.Object({width:o.Number({exclusiveMinimum:0}),height:o.Number({exclusiveMinimum:0})}),o.Literal("native")],{title:"ResolutionInput"}),N=o.Object({aspectRatio:o.Optional(o.Union([o.Number(),o.String()])),preset:o.Optional(o.String()),resolution:o.Optional(c),controls:o.Optional(o.Boolean())},{title:"GameDeviceConfigJson",additionalProperties:!1}),P=o.Object({id:o.Optional(o.String()),globals:o.Optional(o.Record(o.String(),o.Unknown())),debug:o.Optional(o.Boolean()),time:o.Optional(o.Number()),input:o.Optional(l),aspectRatio:o.Optional(o.Union([o.Number(),o.String()])),preset:o.Optional(o.String()),resolution:o.Optional(c),mobile:o.Optional(N),fullscreen:o.Optional(o.Boolean()),bodyBackground:o.Optional(o.String()),containerId:o.Optional(o.String())},{$id:"GameConfigJson",title:"GameConfigJson",additionalProperties:!1});export{n as a,s as b,D as c,S as d,m as e,g as f,u as g,h,B as i,y as j,O as k,a as l,p as m,f as n,r as o,d as p,C as q,b as r,x as s,J as t,l as u,T as v,L as w,E as x,V as y,G as z,c as A,N as B,P as C};
@@ -0,0 +1 @@
1
+ import{proxy as n}from"valtio/vanilla";var e=n({enabled:!1,paused:!1,tool:"none",selectedEntity:null,hoveredEntity:null,flags:new Set});function l(){return e.paused}function i(t){e.paused=t}function a(){return e.tool}function r(t){e.tool=t}function u(t){e.selectedEntity=t}function s(){return e.hoveredEntity}function d(t){e.hoveredEntity=t}function y(){e.hoveredEntity=null}export{e as a,l as b,i as c,a as d,r as e,u as f,s as g,d as h,y as i};
@@ -0,0 +1 @@
1
+ import{b as V,d as ve,e as G,j as Se}from"./chunk-CM5YRNBJ.js";import{a as de,b as he}from"./chunk-YHEWKN7N.js";import{a as Q,b as Ce,c as xe}from"./chunk-EVYHPR3J.js";import{c as v,d as D,e as me,f as fe,g as ye,h as f,i as be,j as L}from"./chunk-7WRQ2UAN.js";import{p as ge}from"./chunk-XRP4JJXL.js";import{StageBodyKind as _e}from"@zylem/behaviors/core";import{Color as st,Vector2 as Oe,Vector3 as Ee}from"three";function F(i){if(!i||typeof i!="object")return!1;let e=Object.getPrototypeOf(i);return e===Object.prototype||e===null}function y(i){if(i==null||typeof i=="function"||typeof i!="object")return i;if(i instanceof st||i instanceof Oe||i instanceof Ee)return i.clone();if(i instanceof Float32Array)return new Float32Array(i);if(Array.isArray(i))return i.map(e=>y(e));if(F(i)){let e={};for(let[t,o]of Object.entries(i))t!=="_builders"&&(e[t]=y(o));return e}return i}function S(i,e){let t=y(i);if(!e)return t;if(!F(t)||!F(e))return y(e);let o=t;for(let[n,s]of Object.entries(e)){if(n==="_builders"||s===void 0)continue;let r=o[n];if(n==="shader"){o[n]=y(s);continue}if(r instanceof Oe&&me(s)){o[n]=be(s,r);continue}if(r instanceof Ee&&fe(s)){o[n]=L(s,r);continue}if(F(r)&&F(s)){o[n]=S(r,s);continue}o[n]=y(s)}return o}function Me(i){return i&&i.__kind==="collision"}function ee(i){return i.cloneComponent()}function rt(i,e){let t={kind:i?_e.Static:_e.Dynamic,position:[0,0,0],gravityScale:e.gravityScale??1,canSleep:e.canSleep??!1,ccdEnabled:e.ccdEnabled??!0},o=Q(e.lockRotations);o&&(t.lockRotation=o);let n=Q(e.lockTranslations);return n&&(t.lockTranslation=n),t}function at(i,e){if(e.offset){let t=f(e.offset,v);i.offset=[t.x,t.y,t.z]}e.sensor&&(i.sensor=!0),e.collisionType&&(i.collisionGroups=Ce(e.collisionType,e.collisionFilter))}function _(i,e,t){return at(i,e),{__kind:"collision",bodyDesc:rt(e.static??!1,e),colliderDesc:i,cloneComponent:t}}function lt(i={}){let e=f(i.size,D),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}},o=y(i);return _(t,i,()=>lt(o))}function ct(i={}){let e={shape:{type:"sphere",radius:i.radius??1}},t=y(i);return _(e,i,()=>ct(t))}function ut(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>ut(n))}function pt(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>pt(n))}function dt(i={}){let e=Math.max(i.radiusTop??1,i.radiusBottom??1),o={shape:{type:"cylinder",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>dt(n))}function ht(i={}){let e=i.radius??.5,o={shape:{type:"capsule",halfHeight:(i.length??1)/2,radius:e}},n=y(i);return _(o,i,()=>ht(n))}function mt(i={}){let e=ye(i.tile,{x:10,y:10}),t=i.subdivisions??10,o=(t+1)*(t+1),n=i.heightData??new Float32Array(o),s={shape:{type:"heightfield",rows:t,cols:t,heights:n,scale:[e.x,1,e.y]}},r={...i,static:i.static??!0},a=y(r);return _(s,r,()=>mt(a))}function ft(i={}){let e=f(i.size,D),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]},sensor:!0},o={...i,static:i.static??!0,sensor:!0},n=y(o);return _(t,o,()=>ft(n))}import{Mesh as ze,ShaderMaterial as Et,Group as _t}from"three";var Ae=import.meta.env.VITE_DEBUG_FLAG==="true";import{nanoid as yt}from"nanoid";var C=class i{parent=null;children=[];options;uuid="";name="";markedForRemoval=!1;lifecycleCallbacks={setup:[],loaded:[],update:[],destroy:[],cleanup:[]};trackLifecycleRegistrations=!1;userLifecycleRegistrations=[];constructor(e=[]){let t=e.filter(o=>!(o instanceof i)).reduce((o,n)=>({...o,...n}),{});this.options=t,this.uuid=yt()}onSetup(...e){return this.lifecycleCallbacks.setup.push(...e),this.recordLifecycleRegistration("onSetup",e),this}onLoaded(...e){return this.lifecycleCallbacks.loaded.push(...e),this.recordLifecycleRegistration("onLoaded",e),this}onUpdate(...e){return this.lifecycleCallbacks.update.push(...e),this.recordLifecycleRegistration("onUpdate",e),this}onDestroy(...e){return this.lifecycleCallbacks.destroy.push(...e),this.recordLifecycleRegistration("onDestroy",e),this}onCleanup(...e){return this.lifecycleCallbacks.cleanup.push(...e),this.recordLifecycleRegistration("onCleanup",e),this}prependSetup(...e){return this.lifecycleCallbacks.setup.unshift(...e),this.recordLifecycleRegistration("prependSetup",e),this}prependUpdate(...e){return this.lifecycleCallbacks.update.unshift(...e),this.recordLifecycleRegistration("prependUpdate",e),this}setParent(e){this.parent=e}getParent(){return this.parent}add(e){this.children.push(e),e.setParent(this)}remove(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),e.setParent(null))}getChildren(){return this.children}isComposite(){return this.children.length>0}enableUserLifecycleTracking(){this.trackLifecycleRegistrations=!0}replayUserLifecycleRegistrationsTo(e,t){for(let o of this.userLifecycleRegistrations){let n=t?o.callbacks.map(s=>t(s)):[...o.callbacks];switch(o.method){case"onSetup":e.onSetup(...n);break;case"onLoaded":e.onLoaded(...n);break;case"onUpdate":e.onUpdate(...n);break;case"onDestroy":e.onDestroy(...n);break;case"onCleanup":e.onCleanup(...n);break;case"prependSetup":e.prependSetup(...n);break;case"prependUpdate":e.prependUpdate(...n);break}}}cloneChildrenInto(e){for(let t of this.children)e.add(bt(t))}nodeSetup(e){this.markedForRemoval=!1,typeof this._setup=="function"&&this._setup(e);for(let t of this.lifecycleCallbacks.setup)t(e);this.children.forEach(t=>t.nodeSetup(e))}nodeUpdate(e){if(!this.markedForRemoval){typeof this._update=="function"&&this._update(e),typeof this._tickActions=="function"&&this._tickActions(e.delta);for(let t of this.lifecycleCallbacks.update)t(e);this.children.forEach(t=>t.nodeUpdate(e))}}nodeDestroy(e){if(!this.markedForRemoval){this.children.forEach(t=>t.nodeDestroy(e));for(let t of this.lifecycleCallbacks.destroy)t(e);typeof this._destroy=="function"&&this._destroy(e),this.markedForRemoval=!0;for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}}async nodeLoaded(e){typeof this._loaded=="function"&&await this._loaded(e);for(let t of this.lifecycleCallbacks.loaded)t(e)}nodeCleanup(e){this.children.forEach(t=>t.nodeCleanup?.(e));for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}getOptions(){return this.options}setOptions(e){this.options={...this.options,...e}}recordLifecycleRegistration(e,t){!this.trackLifecycleRegistrations||t.length===0||this.userLifecycleRegistrations.push({method:e,callbacks:[...t]})}};function bt(i){let e=i?.clone;if(typeof e!="function")throw new Error(`Cannot clone child node "${i.name||i.uuid||"unknown"}": missing clone() support.`);return e.call(i)}import{createTransformStore as Mt}from"@zylem/behaviors/core";import{makeMoveable as gt}from"@zylem/behaviors/core";function Pe(i){let e=gt(i);return ge(e)}import{clearVelocityIntent as je}from"@zylem/behaviors/core";import{Color as St,Vector3 as Ot}from"three";var we=Symbol("explicitSpawnPosition");function De(i){return i.filter(e=>!(e instanceof C)).some(e=>e!=null&&typeof e=="object"&&"position"in e)}function Be(i){i[we]=!0}function Ct(i){return i._spawnPositionExplicit?!0:i.options[we]===!0}function xt(i){return i.options.hideUntilPositioned!==!1}function Re(i){return i._spawnPlacementPending===!0}function vt(i){return i._spawnPositionExplicit===!0||i._spawnPlacementReady===!0}function U(i){let e=i.group??i.mesh;if(e){if(i.physicsAttached&&i.body)try{let t=i.body.translation();e.position.set(t.x,t.y,t.z);return}catch{}if(i.wasmStageRef&&(i.runtimeHandle??-1)>=0){let t=i.wasmStageRef.getPose(i.runtimeHandle);if(t){e.position.set(t.position[0],t.position[1],t.position[2]);return}}if(i.options.position){let t=f(i.options.position,v);e.position.set(t.x,t.y,t.z)}}}function T(i,e){i.group&&(i.group.visible=e),i.mesh&&(i.mesh.visible=e)}function Hi(i){if(i._spawnInProgress=!0,i._spawnPlacementReady=!1,!xt(i)){i._spawnPlacementPending=!1;return}i._spawnPositionExplicit=Ct(i),i._spawnPlacementPending=!0,T(i,!1)}function Yi(i){i._spawnInProgress=!1}function Fe(i){i._spawnPlacementReady=!0}function te(i){if(i._spawnPlacementPending){if(U(i),i._spawnPlacementPending=!1,i.options.visible===!1){T(i,!1);return}T(i,!0)}}function Wi(i){!Re(i)||i.options.hideUntilPositioned===!0&&!vt(i)||te(i)}function Te(i){U(i),i._spawnPlacementPending=!1,T(i,!0)}function ke(i){Re(i)&&T(i,!1)}var N={position:new Ot(0,0,0),material:{color:new St("#ffffff"),shader:V},collision:{static:!1}};function eo(i,e){let t=i.filter(n=>!(n instanceof C)),o=S(e);for(let n of t)o=S(o,n);return De(i)&&Be(o),o}function At(i){return i!=null&&typeof i=="object"}function Ie(i){return{phase:i?.phase??"stay",cooldownMs:i?.cooldownMs}}function Pt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var P=class extends C{group;mesh;materials;bodyDesc=null;body=null;physicsAttached=!1;physicsWorldRef=null;colliderDesc;custom={};colliderDescs=[];compoundMeshes=[];debugInfo={};debugMaterial;collisionDelegate={collision:[],cooldowns:new Map,nextId:0};collisionType;packKey=null;bundleKey=null;instanceId=-1;isInstanced=!1;isBundled=!1;runtimeHandle=-1;runtimeAttached=!1;wasmStageRef=null;eventDelegate=new de;behaviorRefs=[];cloneFactory=null;trackAddedComponents=!1;trackedComponents=[];transformStore;_spawnPlacementPending=!1;_spawnPositionExplicit=!1;_spawnPlacementReady=!1;_spawnInProgress=!1;moveX;moveY;moveZ;moveXY;moveXZ;move;resetVelocity;moveForwardXY;getPosition;getVelocity;setPosition;setPositionX;setPositionY;setPositionZ;wrapAroundXY;wrapAround3D;rotateInDirection;rotateYEuler;rotateEuler;rotateX;rotateY;rotateZ;setRotationY;setRotationX;setRotationZ;setRotationDegrees;setRotationDegreesY;setRotationDegreesX;setRotationDegreesZ;setRotation;getRotation;constructor(){super(),this.transformStore=Mt(),Pe(this),this.wrapSpawnPlacementMutators()}wrapSpawnPlacementMutators(){let e=()=>{Fe(this),!this._spawnInProgress&&(U(this),te(this))},t=s=>(r,a,l)=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(s(r,a,l),e())},o=s=>r=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(s(r),e())};this.setPosition=t(this.setPosition.bind(this)),this.setPositionX=o(this.setPositionX.bind(this)),this.setPositionY=o(this.setPositionY.bind(this)),this.setPositionZ=o(this.setPositionZ.bind(this));let n=this.setPose.bind(this);this.setPose=s=>{let r=n(s);return r&&s.position!=null&&e(),r}}reveal(){this.options.visible=!0,Te(this)}getPose(){if(this.wasmStageRef&&this.runtimeHandle>=0){let n=this.wasmStageRef.getPose(this.runtimeHandle);if(n)return{position:{x:n.position[0],y:n.position[1],z:n.position[2]},rotation:{x:n.rotation[0],y:n.rotation[1],z:n.rotation[2],w:n.rotation[3]}}}let e=this.body;if(!e)return null;let t=e.translation(),o=e.rotation();return{position:{x:t.x,y:t.y,z:t.z},rotation:{x:o.x,y:o.y,z:o.z,w:o.w}}}setPose(e){if(this.wasmStageRef&&this.runtimeHandle>=0){let o=!0;if(e.position){let n=f(e.position);o=this.wasmStageRef.setPosition(this.runtimeHandle,n.x,n.y,n.z)&&o}if(e.rotation){let{x:n,y:s,z:r,w:a}=e.rotation;o=this.wasmStageRef.setRotation(this.runtimeHandle,n,s,r,a)&&o}return o}let t=this.body;if(!t)return!1;if(e.position){let o=f(e.position);t.setTranslation({x:o.x,y:o.y,z:o.z},!0)}return e.rotation&&t.setRotation(e.rotation,!0),!0}add(...e){for(let t of e)t instanceof ze?(this.addMeshComponent(t),this.trackComponent(t)):Me(t)?(this.addCollisionComponent(t),this.trackComponent(t)):super.add(t);return this}addMeshComponent(e){if(this.mesh)this.compoundMeshes.push(e),this.group||(this.group=new _t,this.group.add(this.mesh)),this.group.add(e);else if(this.mesh=e,this.materials||(this.materials=[]),e.material){let t=e.material;Array.isArray(t)?this.materials.push(...t):this.materials.push(t)}}addCollisionComponent(e){if(this.bodyDesc)this.colliderDescs.push(e.colliderDesc);else{this.bodyDesc=e.bodyDesc,this.colliderDesc=e.colliderDesc,this.colliderDescs.push(e.colliderDesc);let t=f(this.options?.position,v);this.bodyDesc.position=[t.x,t.y,t.z]}}trackComponent(e){if(this.trackAddedComponents){if(e instanceof ze){this.trackedComponents.push({kind:"mesh",component:Le(e)});return}this.trackedComponents.push({kind:"collision",component:ee(e)})}}_actions=[];runAction(e){return this._actions.push(e),e}action(e){return e.persistent=!0,this._actions.push(e),e}clearActions(){this._actions.length=0}_tickActions(e){if(this._actions.length===0)return;let t=this.transformStore;t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,je(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1;for(let o=this._actions.length-1;o>=0;o--){let n=this._actions[o];n.tick(this,e),n.done&&!n.persistent&&this._actions.splice(o,1)}this._actions.length===0&&(t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,je(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1)}create(){return this.name=this.options.name||"",this}clone(e){if(!this.cloneFactory)throw new Error(`Cannot clone ${this.constructor.name}: clone() is only supported for entities created by official factory helpers.`);let t=this.cloneFactory(S(this.options,e)),o=this.copyBehaviorRefsTo(t),n=r=>Dt(r,o);this.replayUserLifecycleRegistrationsTo(t,n);let s=this.getCollisionRegistrations();if(s.length>0)for(let r of s)t.onCollision(n(r.callback),r.options);for(let r of this.trackedComponents){if(r.kind==="mesh"){t.add(Le(r.component));continue}t.add(ee(r.component))}return this.cloneChildrenInto(t),t}finalizeCloneSupport(e){return this.cloneFactory=e,this.enableUserLifecycleTracking(),this.trackAddedComponents=!0,this}onCollision(...e){let t=[...this.collisionDelegate.collision??[]],o=this.collisionDelegate.nextId??0;if(e.length===1||e.length===2&&(e[1]==null||At(e[1]))){let n=e[0];if(!n)return this;let s=e[1];return t.push({id:o,callback:n,options:Ie(s)}),o+=1,this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}for(let n of e)t.push({id:o,callback:n,options:Ie()}),o+=1;return this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}use(e,t){let o={descriptor:e,options:{...e.defaultOptions,...t}};this.behaviorRefs.push(o);let n={getFSM:()=>o.fsm??null,getOptions:()=>o.options,ref:o},s=e.createHandle?.(o)??{};return{...n,...s}}getBehaviorRefs(){return this.behaviorRefs}getCollisionCallbacks(){return this.getCollisionRegistrations().map(e=>e.callback)}getCollisionRegistrations(){return(this.collisionDelegate.collision??[]).map(e=>({id:e.id,callback:e.callback,options:{...e.options}}))}copyBehaviorRefsTo(e){let t=new Map;for(let o of this.behaviorRefs){e.use(o.descriptor,y(o.options));let n=e.getBehaviorRefs().at(-1);n&&t.set(o,n)}return t}_setup(e){for(let t=this._actions.length-1;t>=0;t--){let o=this._actions[t];o.done&&!o.persistent?this._actions.splice(t,1):o.reset()}}async _loaded(e){}_update(e){this.updateMaterials(e)}_destroy(e){}_cleanup(e){this.disposeEvents();for(let t of this.compoundMeshes)t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(o=>o.dispose()):t.material?.dispose();this.compoundMeshes.length=0,this.debugMaterial?.dispose(),this.debugMaterial=void 0,this.group?.removeFromParent()}_collision(e,t,o={phase:"stay",nowMs:Pt()}){if(!this.collisionDelegate.collision?.length)return;let n=this.collisionDelegate.cooldowns??new Map;this.collisionDelegate.cooldowns=n;for(let s of this.collisionDelegate.collision){if(s.options.phase!==o.phase)continue;let r=s.options.cooldownMs;if(r!=null){let a=`${s.id}:${e.uuid}`,l=n.get(a);if(l!=null&&o.nowMs-l<r)continue;n.set(a,o.nowMs)}s.callback({entity:this,other:e,globals:t})}}updateMaterials(e){if(this.materials?.length)for(let t of this.materials)t instanceof Et&&t.uniforms&&t.uniforms.iTime&&(t.uniforms.iTime.value+=e.delta)}buildInfo(){let e={};return e.name=this.name,e.uuid=this.uuid,e}dispatch(e,t){this.eventDelegate.dispatch(e,t),he.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}disposeEvents(){this.eventDelegate.dispose()}};function wt(i){let e=new P;return e.options={...N,...i},ie(e,t=>wt(t??{}))}function Le(i){let e=i.clone(!0),t=[],o=[];i.traverse(n=>t.push(n)),e.traverse(n=>o.push(n));for(let n=0;n<t.length;n++){let s=t[n],r=o[n];s?.geometry?.clone&&(r.geometry=s.geometry.clone()),s?.material&&(r.material=Array.isArray(s.material)?s.material.map(a=>a.clone()):s.material.clone())}return e}function Dt(i,e){return e.size===0?i:((...t)=>{let o=Array.from(e.entries()).map(([n,s])=>({sourceRef:n,options:n.options,fsm:n.fsm,hasFSM:Object.prototype.hasOwnProperty.call(n,"fsm"),targetRef:s}));for(let n of o)n.sourceRef.options=n.targetRef.options,n.targetRef.fsm===void 0?delete n.sourceRef.fsm:n.sourceRef.fsm=n.targetRef.fsm;try{return i(...t)}finally{for(let n=o.length-1;n>=0;n--){let s=o[n];s.sourceRef.options=s.options,s.hasFSM?s.sourceRef.fsm=s.fsm:delete s.sourceRef.fsm}}})}function ie(i,e){return i.finalizeCloneSupport(e),i}function Ve(i){return typeof i?.load=="function"&&typeof i?.data=="function"}var Z=class{entityReference;constructor(e){this.entityReference=e}load(){this.entityReference.load&&this.entityReference.load()}data(){return this.entityReference.data?this.entityReference.data():null}};function Ge(i){let{args:e,defaultConfig:t,EntityClass:o,BuilderClass:n,entityType:s,MeshBuilderClass:r,CollisionBuilderClass:a,cloneFactory:l}=i,p=null,d,c=e.findIndex(b=>!(b instanceof C));c!==-1&&(d=e.splice(c,1).find(h=>!(h instanceof C)));let u=d?S(t,d):S(t);e.push(u);for(let b of e){if(b instanceof C)continue;let h=null,R=new o(b);try{if(Ve(R)){let I=new Z(R);I.load(),h=I.data()}}catch(I){console.error("Error creating entity with loader:",I)}p=new n(b,R,r?new r(h):null,a?new a(h):null),b.material&&p.withMaterial(b.material,s)}if(!p)throw new Error(`missing options for ${String(s)}, builder is not initialized.`);let m=p.build();return d!=null&&typeof d=="object"&&"position"in d&&(m._spawnPositionExplicit=!0),ie(m,b=>l(b))}import{Box3 as le,BufferAttribute as Vt,SkinnedMesh as Gt,MeshStandardMaterial as Ut,Group as Nt,Vector3 as M,Matrix4 as Ke}from"three";var B=class{async loadFile(e,t){switch(ve(e)){case"fbx":{let n=await G.loadFBX(e,t);return{object:n.object,animation:n.animations?.[0]}}case"gltf":case"glb":{let n=await G.loadGLTF(e,t);return{object:n.object,gltf:n.gltf}}case"obj":return{object:(await G.loadOBJ(e,t)).object};default:throw new Error(`Unsupported file type: ${e}`)}}};import{AnimationMixer as Bt,Bone as Ue,LoopOnce as Rt,LoopRepeat as Ft}from"three";function Tt(i){let e=i.lastIndexOf(".");return e>=0?i.slice(0,e):i}function Ne(i,e){if(!i?.name?.endsWith(".position"))return!1;let t=Tt(i.name),o=e.get(t);return o instanceof Ue?!(o.parent instanceof Ue):/hips\.position$/i.test(i.name)||/root\.position$/i.test(i.name)}function kt(i,e,t,o){for(let n of i.tracks){if(!Ne(n,e)||!n.values||n.values.length<3)continue;let s=n.values[0],r=o??n.values[1],a=n.values[2];for(let l=0;l<n.values.length;l+=3)n.values[l]=s,t&&(n.values[l+1]=r),n.values[l+2]=a}return i}function zt(i,e){for(let t of i.tracks)if(Ne(t,e)&&!(!t.values||t.values.length<3))return t.values[1];return null}var H=class{constructor(e){this.target=e}_mixer=null;_actions={};_animations=[];_currentAction=null;_pauseAtPercentage=0;_isPaused=!1;_queuedKey=null;_fadeDuration=.5;_currentKey="";_assetLoader=new B;async loadAnimations(e,t={}){if(!e.length)return;let o=t.stripRootMotionY??!1,n=t.referenceRootY,s=t.referenceAnimationPath,r=await Promise.all(e.map(c=>this._assetLoader.loadFile(c.path))),a=new Map;this.target.traverse(c=>{c.name&&a.set(c.name,c)});let l=[];if(r.forEach((c,u)=>{c.animation&&l.push({key:e[u].key||u.toString(),clip:c.animation,path:e[u].path})}),!l.length)return;let p=n;if(o&&p===void 0){let c=s?l.findIndex(m=>m.path===s):0,u=c>=0?[c,...l.map((m,g)=>g).filter(m=>m!==c)]:l.map((m,g)=>g);for(let m of u){let g=zt(l[m].clip,a);if(g!==null){p=g;break}}}let d=l.map(({key:c,clip:u})=>({key:c,clip:kt(u,a,o,p)}));this._animations=d.map(c=>c.clip),this._mixer=new Bt(this.target),d.forEach(({key:c,clip:u})=>{this._actions[c]=this._mixer.clipAction(u)}),this.playAnimation({key:d[0].key})}update(e){if(!this._mixer||!this._currentAction)return;this._mixer.update(e);let t=this._currentAction.getClip().duration*(this._pauseAtPercentage/100);if(!this._isPaused&&this._pauseAtPercentage>0&&this._currentAction.time>=t&&(this._currentAction.time=t,this._currentAction.paused=!0,this._isPaused=!0,this._queuedKey!==null)){let o=this._actions[this._queuedKey];o.reset().play(),this._currentAction.crossFadeTo(o,this._fadeDuration,!1),this._currentAction=o,this._currentKey=this._queuedKey,this._queuedKey=null}}playAnimation(e){if(!this._mixer)return;let{key:t,pauseAtPercentage:o=0,pauseAtEnd:n=!1,fadeToKey:s,fadeDuration:r=.5}=e;if(t===this._currentKey)return;let a=this._actions[t];if(!a)return;if(a===this._currentAction){this._currentKey=t;return}this._queuedKey=s||null,this._fadeDuration=r,this._pauseAtPercentage=n?100:o,this._isPaused=!1;let l=this._currentAction;this._pauseAtPercentage>0?(a.setLoop(Rt,1/0),a.clampWhenFinished=!0):(a.setLoop(Ft,1/0),a.clampWhenFinished=!1),a.reset().play(),l&&l.crossFadeTo(a,r,!1),this._currentAction=a,this._currentKey=t}dispose(){Object.values(this._actions).forEach(e=>{e.stop()}),this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this.target),this._mixer=null),this._actions={},this._animations=[],this._currentAction=null,this._currentKey=""}get currentAnimationKey(){return this._currentKey}get animations(){return this._animations}};import{BufferGeometry as It,Mesh as Ze,Color as Lt}from"three";import{Mesh as jt}from"three";var Y=class{_build(e,t,o){let n=new jt(t,o.at(-1));return n.position.set(0,0,0),n.castShadow=!0,n.receiveShadow=!0,n}_postBuild(){}};var W=class extends xe{},He=class extends Y{build(e){return new It}postBuild(){}},K=class{meshBuilder;collisionBuilder;materialBuilder;options;entity;constructor(e,t,o,n){this.options=e,this.entity=t,this.meshBuilder=o,this.collisionBuilder=n,this.materialBuilder=new Se;let s={meshBuilder:this.meshBuilder,collisionBuilder:this.collisionBuilder,materialBuilder:this.materialBuilder};this.options._builders=s,t&&t.options&&(t.options._builders=s)}withPosition(e){return this.options.position=e,this}withMaterial(e,t){return this.materialBuilder&&this.materialBuilder.build(e,t),this}applyMaterialToGroup(e,t){e.traverse(o=>{o instanceof Ze&&o.type==="SkinnedMesh"&&t[0]&&!o.material.map&&(o.material=t[0]),o.castShadow=!0,o.receiveShadow=!0})}build(){let e=this.entity;if(this.materialBuilder&&(e.materials=this.materialBuilder.materials),this.meshBuilder&&e.materials){let t=this.meshBuilder.build(this.options);e.mesh=this.meshBuilder._build(this.options,t,e.materials),this.meshBuilder.postBuild()}if(e.group&&e.materials&&this.applyMaterialToGroup(e.group,e.materials),this.collisionBuilder){this.collisionBuilder.withCollision(this.options?.collision||{});let[t,o]=this.collisionBuilder.build(this.options);e.bodyDesc=t,e.colliderDesc=o,e.colliderDescs.push(o);let{x:n,y:s,z:r}=f(this.options.position,v);e.bodyDesc.position=[n,s,r]}if(this.options.collisionType&&(e.collisionType=this.options.collisionType),this.options.color instanceof Lt){let t=o=>{let n=o;n&&n.color&&n.color.set&&n.color.set(this.options.color)};if(e.materials?.length)for(let o of e.materials)t(o);if(e.mesh&&e.mesh.material){let o=e.mesh.material;Array.isArray(o)?o.forEach(t):t(o)}e.group&&e.group.traverse(o=>{if(o instanceof Ze&&o.material){let n=o.material;Array.isArray(n)?n.forEach(t):t(n)}})}return e}};var Xe={...N,material:{shader:V},animations:[],models:[],collisionShape:"capsule"};function k(i){return L(i.scale,D)}var Zt=1e-4,Ht=/foot$/i,oe=new M,q=new M,Ye=new M,X=new M,We=new Ke;function Yt(i){let e=1/0,t=!1;return i.traverse(o=>{if(!o.isSkinnedMesh)return;let n=o,s=n.geometry,r=s.attributes.position,a=s.attributes.skinIndex,l=s.attributes.skinWeight,p=n.skeleton;if(!r||!a||!l||!p)return;t=!0,p.update(),n.updateMatrixWorld(!0);let d=p.boneMatrices;if(d)for(let c=0;c<r.count;c++){Ye.fromBufferAttribute(r,c).applyMatrix4(n.bindMatrix),X.set(0,0,0);for(let u=0;u<4;u++){let m=l.getComponent(c,u);if(m===0)continue;let g=a.getComponent(c,u);We.fromArray(d,g*16),X.addScaledVector(q.copy(Ye).applyMatrix4(We),m)}X.applyMatrix4(n.bindMatrixInverse).applyMatrix4(n.matrixWorld),e=Math.min(e,X.y)}}),!t||!Number.isFinite(e)?null:e}function Wt(i,e){e.updateMatrixWorld(!0);let t=e.getWorldPosition(oe).y,o=Yt(i)??1/0;if(i.traverse(n=>{!n.isBone||!Ht.test(n.name)||(n.getWorldPosition(oe),o=Math.min(o,oe.y))}),Number.isFinite(o)||i.traverse(n=>{if(!n.isSkinnedMesh)return;let s=n;if(s.computeBoundingBox(),!s.boundingBox)return;let{min:r,max:a}=s.boundingBox;for(let l of[[r.x,r.y,r.z],[r.x,r.y,a.z],[r.x,a.y,r.z],[r.x,a.y,a.z],[a.x,r.y,r.z],[a.x,r.y,a.z],[a.x,a.y,r.z],[a.x,a.y,a.z]])q.set(l[0],l[1],l[2]),q.applyMatrix4(s.matrixWorld),o=Math.min(o,q.y)}),!Number.isFinite(o)){let n=new le().setFromObject(i);if(n.isEmpty())return null;o=n.min.y}return o-t}function Kt(i,e,t){return i.stripRootMotionY!==void 0?i.stripRootMotionY:!!(e&&t.some(o=>o===e))}function j(i){let e=i.collision?.position;return e?f(e,v):null}function ne(i){return!!i.collision?.size}function Xt(i){i.hasWarnedDynamicTrimesh||(i.hasWarnedDynamicTrimesh=!0,console.warn(`Actor "${i.name||i.uuid}" requested collisionShape="trimesh" on a dynamic body; falling back to bounds.`))}function $e(i,e,t){let o=i==="model"?"bounds":i??"capsule";return o==="trimesh"&&!e?(t?.(),"bounds"):o}function qe(i,e){let t=i.x||.5,o=i.y||1,n=i.z||.5,s=Math.max(t,n)/2,r=o/2;return{shape:{type:"capsule",halfHeight:Math.max(0,r-s),radius:s},offset:[e.x,e.y,e.z],sensor:!1}}function w(i){let e=f(i.collision?.size??i.size,{x:.5,y:1,z:.5}),t=e.y||1,o=j(i);return qe({x:e.x||.5,y:t,z:e.z||.5},o??{x:0,y:t/2,z:0})}function Je(i){let e=i.collision?.size;if(!e)return null;let t=f(e,v),o=t.x/2,n=t.y/2,s=t.z/2,r=j(i);return{shape:{type:"box",halfExtents:[o,n,s]},offset:[r?.x??0,r?.y??n,r?.z??0],sensor:!1}}function Qe(i,e,t){let n=e.matrixWorld.clone().invert().multiply(i.matrixWorld);return new Ke().makeScale(t.x,t.y,t.z).multiply(n)}function se(i,e,t){i.updateMatrixWorld(!0);let o=!1,n=new le;if(i.traverse(a=>{if(!a.isMesh)return;let l=a,p=l.geometry;if(!p)return;let d=null;if(l instanceof Gt?(l.computeBoundingBox(),d=l.boundingBox?.clone()??null):(p.computeBoundingBox(),d=p.boundingBox?.clone()??null),!d)return;let c=d.applyMatrix4(Qe(l,e,t));if(!o){n.copy(c),o=!0;return}n.union(c)}),!o||n.isEmpty())return null;let s=new M,r=new M;return n.getSize(s),n.getCenter(r),{size:s,center:r}}function $t(i,e,t){i.updateMatrixWorld(!0);let o=[],n=[],s=new le,r=new M,a=!1;if(i.traverse(p=>{if(!p.isMesh)return;let d=p,c=d.geometry;if(!c)return;let u=c.getAttribute("position");if(!(u instanceof Vt))return;let m=Qe(d,e,t),g=o.length/3;for(let h=0;h<u.count;h++)r.set(u.getX(h),u.getY(h),u.getZ(h)),r.applyMatrix4(m),o.push(r.x,r.y,r.z),s.expandByPoint(r);let b=c.getIndex();if(b)for(let h=0;h<b.count;h++)n.push(g+b.getX(h));else for(let h=0;h<u.count;h++)n.push(g+h);a=!0}),!a||o.length===0||n.length===0)return null;let l=new M;return s.getCenter(l),{vertices:new Float32Array(o),indices:new Uint32Array(n),center:l}}function et(i,e,t){let o=Je(t);if(o)return o;if(!i||!e)return w(t);let n=se(i,e,k(t));if(!n)return w(t);let s=j(t);return{shape:{type:"box",halfExtents:[n.size.x/2,n.size.y/2,n.size.z/2]},offset:[s?.x??n.center.x,s?.y??n.center.y,s?.z??n.center.z],sensor:!1}}function tt(i,e,t,o,n){if(ne(n)||!i||!e)return w(n);let s=se(i,e,k(n));if(!s)return w(n);let a=j(n);if(!a){let l=t&&o?se(t,o,k(n)):null;a=l?{x:l.center.x,y:l.center.y,z:l.center.z}:{x:s.center.x,y:s.center.y,z:s.center.z}}return qe({x:s.size.x,y:s.size.y,z:s.size.z},a)}function it(i,e,t){let o=Je(t);if(o)return o;if(!i||!e)return w(t);let n=$t(i,e,k(t));if(!n)return w(t);let s=j(t);return{shape:{type:"trimesh",vertices:n.vertices,indices:n.indices},offset:s?[s.x-n.center.x,s.y-n.center.y,s.z-n.center.z]:[0,0,0],sensor:!1}}function $(i){i&&i.traverse(e=>{if(!e.isMesh)return;let t=e;t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(o=>o.dispose()):t.material?.dispose()})}var re=class extends W{objectModel=null;collisionSource=null;collisionShape="capsule";constructor(e){super(),this.objectModel=e.objectModel,this.collisionSource=e.collisionSource??e.objectModel??null,this.collisionShape=e.collisionShape??"capsule"}collider(e){let t=$e(this.collisionShape,!!e.collision?.static);return t==="bounds"?et(this.objectModel,this.objectModel,e):t==="trimesh"?it(this.objectModel,this.objectModel,e):tt(this.collisionSource,this.collisionSource,this.objectModel,this.objectModel,e)}},ae=class extends K{createEntity(e){return new z(e)}},qt=Symbol("Actor"),z=class extends P{static type=qt;_object=null;_collisionSource=null;_animationDelegate=null;_modelFileNames=[];_assetLoader=new B;_loadGeneration=0;_loadStatus="idle";controlledRotation=!1;hasWarnedDynamicTrimesh=!1;constructor(e){super(),this.options=S(Xe,e),this.prependUpdate(this.actorUpdate.bind(this)),this.controlledRotation=!0}create(){return this._loadStatus==="idle"&&(this.options.models?.length??0)>0&&this.load(),super.create()}load(){this._loadStatus==="loading"||this._loadStatus==="loaded"||(this._modelFileNames=[...this.options.models||[]],this._modelFileNames.length!==0&&(this.disposeRuntimeState(!0),this._loadStatus="loading",this.loadModelsDeferred(++this._loadGeneration)))}data(){return{animations:this._animationDelegate?.animations,objectModel:this._object,collisionSource:this._collisionSource??this._object,collisionShape:this.options.collisionShape}}needsDeferredModelCollision(){return this.requiresLoadedCollisionSource()?!this.getRuntimeCollisionSource():!1}synchronizeRuntimeCollider(){let e=this.getResolvedCollisionShape(),t;if(e==="bounds")t=et(this._object,this.group??this._object,this.options);else if(e==="trimesh")t=it(this._object,this.group??this._object,this.options);else{let o=this.getRuntimeCollisionSource();t=tt(o,o,this._object,this._object,this.options)}this.colliderDesc=t,this.colliderDescs.length>0?this.colliderDescs[0]=t:this.colliderDescs.push(t)}actorUpdate(e){this._animationDelegate?.update(e.delta)}actorDestroy(){this._loadGeneration+=1,this._loadStatus="idle",this.disposeRuntimeState(!0),this._modelFileNames=[]}_cleanup(e){super._cleanup(e),this.actorDestroy()}playAnimation(e){this._animationDelegate?.playAnimation(e)}get object(){return this._object}get collisionSource(){return this._collisionSource??this._object}getDebugInfo(){let e={type:"Actor",models:this._modelFileNames.length>0?this._modelFileNames:"none",modelLoaded:!!this._object,scale:(()=>{let t=f(this.options.scale,D);return`${t.x}, ${t.y}, ${t.z}`})(),collisionShape:this.getResolvedCollisionShape()};if(this._animationDelegate&&(e.currentAnimation=this._animationDelegate.currentAnimationKey||"none",e.animationsCount=this.options.animations?.length||0),this._object){let t=0,o=0;this._object.traverse(n=>{if(!n.isMesh)return;t++;let s=n.geometry;s?.attributes.position&&(o+=s.attributes.position.count)}),e.meshCount=t,e.vertexCount=o}return e}getResolvedCollisionShape(){return $e(this.options.collisionShape,!!this.options.collision?.static,()=>Xt(this))}requiresLoadedCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?!ne(this.options):e==="capsule"?!ne(this.options)&&this.getCollisionSourceSelection().file!==null:!1}getRuntimeCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?this._object:this._collisionSource??this._object}getCollisionSourceSelection(){let e=this.options.models?.[0]??null,t=this.options.animations?.[0]?.path??null;return t?{file:t,reuseVisibleModel:t===e}:{file:e,reuseVisibleModel:!0}}disposeRuntimeState(e){this._animationDelegate&&(this._animationDelegate.dispose(),this._animationDelegate=null);let t=this._collisionSource;$(this._object),t&&t!==this._object&&$(t),this._object=null,this._collisionSource=null,e&&this.group&&(this.group.clear(),this.group=void 0)}loadModelsDeferred(e){this.dispatch("entity:model:loading",{entityId:this.uuid,files:this._modelFileNames});let t=this.getCollisionSourceSelection(),o=this._modelFileNames.map(s=>this._assetLoader.loadFile(s,{clone:!0})),n=t.file&&!t.reuseVisibleModel?this._assetLoader.loadFile(t.file,{clone:!0}):Promise.resolve(null);Promise.all([Promise.all(o),n]).then(([s,r])=>{if(e!==this._loadGeneration){s.forEach(l=>$(l.object??null)),r?.object&&$(r.object);return}this._object=s[0]?.object??null,this._collisionSource=t.reuseVisibleModel?this._object:r?.object??this._object,this._loadStatus=this._object?"loaded":"idle";let a=0;if(this._object){this._object.traverse(u=>{u.isMesh&&a++}),this.group=new Nt,this.group.add(this._object),this.group.scale.copy(k(this.options)),ke(this),this.applyMaterialOverrides(),this._animationDelegate=new H(this._object);let l=this.options.animations||[],p=this.options.models?.[0],d=l.map(u=>u.path),c=Kt(this.options,p,d);l.length>0?this._animationDelegate.loadAnimations(l,{stripRootMotionY:c,referenceAnimationPath:p}).then(()=>{e===this._loadGeneration&&(this.alignVisualModelToGround(),this.dispatch("entity:animation:loaded",{entityId:this.uuid,animationCount:l.length}))}):this.alignVisualModelToGround()}this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!!this._object,meshCount:a})}).catch(s=>{e===this._loadGeneration&&(this._loadStatus="idle",console.error("Failed to load actor model",s),this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!1,meshCount:0,errorMessage:s instanceof Error?s.message:String(s)}))})}alignVisualModelToGround(){if(!this._object||!this.group)return;this._animationDelegate?.update(0),this._object.updateMatrixWorld(!0);let e=Wt(this._object,this.group);if(e===null||Math.abs(e)<Zt)return;let t=this.group.scale.y||1;this._object.position.y-=e/t}applyMaterialOverrides(){let e=this.options.material;!e||!e.color&&!e.path&&e.opacity===void 0||this._object&&this._object.traverse(t=>{if(!t.isMesh)return;let o=t;o.material=Array.isArray(o.material)?o.material.map(n=>this.tintMaterial(n,e)):this.tintMaterial(o.material,e),e.color&&(o.castShadow=!0,o.receiveShadow=!0)})}tintMaterial(e,t){let o="color"in e,n=!!t.color,s=t.opacity!==void 0;if(!n&&!s)return e;if(n&&!o)return new Ut({color:t.color,emissiveIntensity:.5,lightMapIntensity:.5,fog:!0,opacity:t.opacity??1,transparent:s&&t.opacity<1});let r=e.clone();if(n&&"color"in r&&r.color.copy(t.color),s&&"opacity"in r&&"transparent"in r){let a=r;a.opacity=t.opacity,a.transparent=t.opacity<1}return r.needsUpdate=!0,r}};function Jt(...i){return Ge({args:i,defaultConfig:Xe,EntityClass:z,BuilderClass:ae,CollisionBuilderClass:re,entityType:z.type,cloneFactory:e=>Jt(e??{})})}import{Color as li,Fog as ci,FogExp2 as ui,Group as pi}from"three";import{Color as Qt}from"three";import{Fn as nt,fog as ei,positionWorld as ot,positionView as ti,uniform as x,float as ii,vec3 as O,clamp as ce,mix as E,max as oi,smoothstep as ni,floor as si,fract as ue,dot as ri}from"three/tsl";var J=class{values;u={time:x(0),heightEnabled:x(0),heightLevel:x(0),heightFalloff:x(0),noiseEnabled:x(0),noiseScale:x(0),noiseStrength:x(0),noiseSpeed:x(0)};attachedScene=null;constructor(e){this.values={...e},this.syncUniforms()}setValues(e){Object.assign(this.values,e),this.syncUniforms()}tick(e){this.values.time+=e,this.u.time.value=this.values.time}scan(e){if(this.attachedScene===e)return;let t=e.fog;t&&(e.fogNode=this.buildFogNode(t),this.attachedScene=e)}unpatchAll(){this.attachedScene&&(this.attachedScene.fogNode=null,this.attachedScene=null)}syncUniforms(){this.u.time.value=this.values.time,this.u.heightEnabled.value=this.values.heightEnabled,this.u.heightLevel.value=this.values.heightLevel,this.u.heightFalloff.value=this.values.heightFalloff,this.u.noiseEnabled.value=this.values.noiseEnabled,this.u.noiseScale.value=this.values.noiseScale,this.u.noiseStrength.value=this.values.noiseStrength,this.u.noiseSpeed.value=this.values.noiseSpeed}buildFogNode(e){let t=e.isFogExp2===!0,o=x(new Qt(e.color)),n=ti.z.negate(),s=t?this.exp2Factor(x(e.density),n):ni(x(e.near),x(e.far),n),r=this.u.heightLevel.sub(ot.y),a=ce(r.mul(oi(this.u.heightFalloff,0)),0,1),l=E(s,s.mul(a),this.u.heightEnabled),p=ot.mul(this.u.noiseScale).add(O(this.u.time.mul(this.u.noiseSpeed),0,this.u.time.mul(this.u.noiseSpeed).mul(.5))),c=ai(p).sub(.5).mul(2).mul(ce(this.u.noiseStrength,0,1)),u=ce(l.add(l.mul(c)),0,1),m=E(l,u,this.u.noiseEnabled);return ei(o,m)}exp2Factor(e,t){return e.mul(e).mul(t).mul(t).negate().exp().oneMinus()}},A=nt(([i])=>{let e=ue(i.mul(O(443.8975,397.2973,491.1871))),t=e.add(ri(e,e.yzx.add(19.27)));return ue(t.x.add(t.y).mul(t.z))}),ai=nt(([i])=>{let e=si(i),t=ue(i),o=t.mul(t).mul(ii(3).sub(t.mul(2))),n=A(e.add(O(0,0,0))),s=A(e.add(O(1,0,0))),r=A(e.add(O(0,1,0))),a=A(e.add(O(1,1,0))),l=A(e.add(O(0,0,1))),p=A(e.add(O(1,0,1))),d=A(e.add(O(0,1,1))),c=A(e.add(O(1,1,1))),u=E(n,s,o.x),m=E(r,a,o.x),g=E(l,p,o.x),b=E(d,c,o.x),h=E(u,m,o.y),R=E(g,b,o.y);return E(h,R,o.z)});var di=Symbol("Fog"),hi="#9aa3ad",mi=.015,fi=10,yi=250,bi=5,gi=.2,Ci=.05,xi=.15,vi=.1,pe=class extends P{static type=di;threeFog=null;attachedScene=null;patcher;patcherEnabled;constructor(e={}){super(),this.options={...e};let t=this.resolveUniformValues(this.options);this.patcher=new J(t),this.patcherEnabled=Oi(this.options)}create(){return super.create(),this.threeFog=Si(this.options),this.group=new pi,this.group.name=this.name?`Fog:${this.name}`:"Fog",this}attachToScene(e){this.threeFog&&(this.attachedScene=e,e.fog=this.threeFog,this.patcherEnabled&&this.patcher.scan(e))}_update(e){super._update(e),!(!this.attachedScene||!this.patcherEnabled)&&(this.patcher.tick(e.delta),this.patcher.scan(this.attachedScene))}_cleanup(e){this.patcher.unpatchAll(),this.attachedScene&&this.attachedScene.fog===this.threeFog&&(this.attachedScene.fog=null),this.attachedScene=null,this.threeFog=null,super._cleanup(e)}resolveUniformValues(e){let t=e.height,o=e.noise;return{time:0,heightEnabled:t?.enabled?1:0,heightLevel:t?.level??bi,heightFalloff:t?.falloff??gi,noiseEnabled:o?1:0,noiseScale:o?.scale??Ci,noiseStrength:o?.strength??xi,noiseSpeed:o?.speed??vi}}};function Si(i){let e=new li(i.color??hi);return(i.type??"linear")==="exp2"?new ui(e,i.density??mi):new ci(e,i.start??fi,i.end??yi)}function Oi(i){let e=!!i.height?.enabled,t=!!i.noise;return e||t}function _n(i={}){return new pe(i)}export{C as a,S as b,lt as c,ct as d,ut as e,pt as f,dt as g,ht as h,mt as i,ft as j,Re as k,Hi as l,Yi as m,Wi as n,ke as o,N as p,eo as q,P as r,wt as s,ie as t,Ge as u,W as v,He as w,K as x,qt as y,z,Jt as A,di as B,pe as C,_n as D};
@@ -0,0 +1 @@
1
+ import{b as d,p as v,q as V,r as y,t as D,u as S,v as B,x as b}from"./chunk-KVSJE4XD.js";import{c as k}from"./chunk-CM5YRNBJ.js";import{c as h,d as _,h as u,i as T,j as C}from"./chunk-7WRQ2UAN.js";import{Color as $,Group as nt,Sprite as st,SpriteMaterial as rt,CanvasTexture as U,LinearFilter as E,Vector2 as ot,ClampToEdgeWrapping as H}from"three";import{MeshStandardMaterial as K,MeshBasicMaterial as tt,MeshPhongMaterial as et}from"three";function it(i){return i&&typeof i.getDebugInfo=="function"}var c=class{entity;constructor(t){this.entity=t}getPositionString(){if(this.entity.mesh){let{x:r,y:s,z:o}=this.entity.mesh.position;return`${r.toFixed(2)}, ${s.toFixed(2)}, ${o.toFixed(2)}`}let{x:t,y:e,z:n}=this.entity.options.position||{x:0,y:0,z:0};return`${t.toFixed(2)}, ${e.toFixed(2)}, ${n.toFixed(2)}`}getRotationString(){if(this.entity.mesh){let{x:s,y:o,z:a}=this.entity.mesh.rotation,p=l=>(l*180/Math.PI).toFixed(1);return`${p(s)}\xB0, ${p(o)}\xB0, ${p(a)}\xB0`}let{x:t,y:e,z:n}=this.entity.options.rotation||{x:0,y:0,z:0},r=s=>(s*180/Math.PI).toFixed(1);return`${r(t)}\xB0, ${r(e)}\xB0, ${r(n)}\xB0`}getMaterialInfo(){if(!this.entity.mesh||!this.entity.mesh.material)return{type:"none"};let t=Array.isArray(this.entity.mesh.material)?this.entity.mesh.material[0]:this.entity.mesh.material,e={type:t.type};return(t instanceof K||t instanceof tt||t instanceof et)&&(e.color=`#${t.color.getHexString()}`,e.opacity=t.opacity,e.transparent=t.transparent),"roughness"in t&&(e.roughness=t.roughness),"metalness"in t&&(e.metalness=t.metalness),e}getPhysicsInfo(){if(!this.entity.body)return null;let t={type:this.entity.body.bodyType(),mass:this.entity.body.mass(),isEnabled:this.entity.body.isEnabled(),isSleeping:this.entity.body.isSleeping()},e=this.entity.body.linvel();return t.velocity=`${e.x.toFixed(2)}, ${e.y.toFixed(2)}, ${e.z.toFixed(2)}`,t}buildDebugInfo(){let t={name:this.entity.name||this.entity.uuid,uuid:this.entity.uuid,position:this.getPositionString(),rotation:this.getRotationString(),material:this.getMaterialInfo()},e=this.getPhysicsInfo();if(e&&(t.physics=e),it(this.entity)){let n=this.entity.getDebugInfo();return{...t,...n}}return t}};var f={position:void 0,text:"",fontFamily:'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',fontSize:18,fontColor:"#FFFFFF",backgroundColor:null,padding:4,stickToViewport:!0,screenPosition:new ot(24,24),zDistance:1},O=class extends b{createEntity(t){return new g(t)}},at=Symbol("Text"),g=class i extends y{static type=at;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=d(f,t),this.options.screenPosition=T(this.options.screenPosition,f.screenPosition),this.prependSetup(this.textSetup.bind(this)),this.prependUpdate(this.textUpdate.bind(this)),this.onCleanup(this.textDestroy.bind(this))}create(){return this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._lastCanvasW=0,this._lastCanvasH=0,this.group=new nt,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new U(this._canvas),this._texture.minFilter=E,this._texture.magFilter=E;let t=new rt({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new st(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,n,r){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${n}`;let s=this._ctx.measureText(t),o=Math.ceil(s.width),a=Math.ceil(e*1.4),p=Math.max(2,o+r*2),l=Math.max(2,a+r*2),w=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:w}}drawCenteredText(t,e,n){!this._canvas||!this._ctx||(this._ctx.font=`${e}px ${n}`,this._ctx.textAlign="center",this._ctx.textBaseline="middle",this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this.options.backgroundColor&&(this._ctx.fillStyle=this.toCssColor(this.options.backgroundColor),this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height)),this._ctx.fillStyle=this.toCssColor(this.options.fontColor??"#FFFFFF"),this._ctx.fillText(t,this._canvas.width/2,this._canvas.height/2))}updateTexture(t){!this._texture||!this._canvas||(t&&(this._texture.dispose(),this._texture=new U(this._canvas),this._texture.minFilter=E,this._texture.magFilter=E,this._texture.wrapS=H,this._texture.wrapT=H),this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0))}redrawText(t){if(!this._canvas||!this._ctx)return;let e=this.options.fontSize??18,n=this.options.fontFamily??f.fontFamily,r=this.options.padding??4,{sizeChanged:s}=this.measureAndResizeCanvas(t,e,n,r);this.drawCenteredText(t,e,n),this.updateTexture(!!s),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof $?t:new $(t)).getHexString()}`}textSetup(t){this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}textUpdate(t){this._sprite&&this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}getResolution(){return{width:this._cameraRef?.screenResolution.x??1,height:this._cameraRef?.screenResolution.y??1}}getScreenPixels(t,e,n){let r=t.x>=0&&t.x<=1,s=t.y>=0&&t.y<=1;return{px:r?t.x*e:t.x,py:s?t.y*n:t.y}}computeWorldExtents(t,e){let n=1,r=1;if(t.isPerspectiveCamera){let s=t,o=Math.tan(s.fov*Math.PI/180/2)*e;n=o*s.aspect,r=o}else if(t.isOrthographicCamera){let s=t;n=(s.right-s.left)/2,r=(s.top-s.bottom)/2}return{worldHalfW:n,worldHalfH:r}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let r=t*2/e,s=this._canvas.height,o=Math.max(1e-4,s*r),a=this._canvas.width/this._canvas.height,p=o*a;this._sprite.scale.set(p,o,1)}updateWorldSpriteScale(){if(!this._canvas||!this._sprite)return;let t=this._canvas.width/Math.max(1,this._canvas.height),e=Math.max(1,this.options.fontSize??18),n=Math.max(.25,e/32),r=n*t;this._sprite.scale.set(r,n,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:n}=this.getResolution(),r=T(this.options.screenPosition,f.screenPosition),{px:s,py:o}=this.getScreenPixels(r,e,n),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:p,worldHalfH:l}=this.computeWorldExtents(t,a),w=s/e*2-1,Q=1-o/n*2,q=w*p,J=Q*l;this.group?.position.set(q,J,-a),this.updateSpriteScale(l,n)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type),text:this.options.text??"",sticky:this.options.stickToViewport}}textDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null}};function I(...i){return S({args:i,defaultConfig:{...f},EntityClass:g,BuilderClass:O,entityType:g.type,cloneFactory:t=>I(t??{})})}import{Euler as pt,Group as lt,Quaternion as ct,Vector3 as mt}from"three";import{TextureLoader as ht,SpriteMaterial as ut,Sprite as dt,SRGBColorSpace as yt}from"three";var W={...v,size:new mt(1,1,1),images:[],animations:[]},R=class extends B{collider(t){let e=C(t.collisionSize,t.size??_);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},F=class extends b{createEntity(t){return new x(t)}},ft=Symbol("Sprite"),x=class i extends y{static type=ft;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;constructor(t){super(),this.options=d(W,t),this.prependSetup(this.spriteSetup.bind(this)),this.prependUpdate(this.spriteUpdate.bind(this)),this.onCleanup(this.spriteDestroy.bind(this))}create(){return this.sprites=[],this.spriteMap.clear(),this.animations.clear(),this.currentAnimation=null,this.currentAnimationFrame="",this.currentAnimationIndex=0,this.currentAnimationTime=0,this.group=void 0,this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new ht,n=C(this.options.size,_);t.forEach((r,s)=>{let o=e.load(r.file);o.colorSpace=yt,o.anisotropy=k;let a=new ut({map:o,transparent:!0}),p=new dt(a);p.position.normalize(),p.scale.set(n.x,n.y,n.z),p.visible=s===0,this.sprites.push(p),this.spriteMap.set(r.name,s)}),this.group=new lt,this.group.add(...this.sprites)}createAnimations(t){t.forEach(e=>{let{name:n,frames:r,loop:s=!1,speed:o=1}=e,a={frames:r.map((p,l)=>({key:p,index:l,time:(typeof o=="number"?o:o[l])*(l+1),duration:typeof o=="number"?o:o[l]})),loop:s};this.animations.set(n,a)})}setSprite(t){let n=this.spriteMap.get(t)??0;this.currentSpriteIndex=n,this.sprites.forEach((r,s)=>{r.visible=this.currentSpriteIndex===s})}setAnimation(t,e){let n=this.animations.get(t);if(!n)return;let{loop:r,frames:s}=n,o=s[this.currentAnimationIndex];t===this.currentAnimation?(this.currentAnimationFrame=o.key,this.currentAnimationTime+=e,this.setSprite(this.currentAnimationFrame)):this.currentAnimation=t,this.currentAnimationTime>o.time&&this.currentAnimationIndex++,this.currentAnimationIndex>=s.length&&(r?(this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime=s[this.currentAnimationIndex].time)}getCurrentRotationQuaternion(){return this.transformStore?.dirty.rotation?this.transformStore.rotation:this.body?.rotation?.()??null}syncSpriteMaterials(){let t=this.getCurrentRotationQuaternion();this.sprites.forEach(e=>{if(e.material&&t){let r=new ct(t.x,t.y,t.z,t.w),s=new pt().setFromQuaternion(r,"XYZ");e.material.rotation=s.z}let n=C(this.options.size,_);e.scale.set(n.x,n.y,n.z)})}spriteSetup(t){this.syncSpriteMaterials()}spriteUpdate(t){this.syncSpriteMaterials()}spriteDestroy(t){this.sprites.forEach(e=>{e.removeFromParent()}),this.group?.remove(...this.sprites),this.group?.removeFromParent()}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type)}}};function P(...i){return S({args:i,defaultConfig:W,EntityClass:x,BuilderClass:F,CollisionBuilderClass:R,entityType:x.type,cloneFactory:t=>P(t??{})})}import{Color as X,Group as xt}from"three";import{Line2NodeMaterial as _t}from"three/webgpu";import{Line2 as Ct}from"three/addons/lines/webgpu/Line2.js";import{Color as N}from"three";import{LineGeometry as gt}from"three/addons/lines/LineGeometry.js";function z(i){let t=[];for(let e of i){let{x:n,y:r,z:s}=u(e,h);t.push(n,r,s)}return t}function L(i,t,e){if(!i||i.length===0)return;let n=[],r=new N(e);for(let s=0;s<t;s++){let o=i[s]??i[i.length-1]??e,a=new N(o??r);n.push(a.r,a.g,a.b)}return n}function Y(i){let t=new gt,e=z(i.points);t.setPositions(e);let n=L(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var m={...v,points:[{x:0,y:0,z:0},{x:1,y:0,z:0}],linewidth:1,worldUnits:!0,alphaToCoverage:!1,opacity:1,transparent:!1,dashed:!1,dashSize:1,gapSize:1,pickThreshold:0},vt=Symbol("Line");function M(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function j(i){return i instanceof X?i.clone():new X(i??"#ffffff")}function St(i){let t=!!i.colors?.length,e=new _t({color:j(i.color).getHex(),linewidth:i.linewidth??m.linewidth,worldUnits:i.worldUnits??m.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??m.dashSize,gapSize:i.gapSize??m.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function bt(i){return!i.point||!i.pointOnLine||i.faceIndex==null?null:{point:i.point.clone(),pointOnLine:i.pointOnLine.clone(),faceIndex:i.faceIndex,distance:i.distance}}function Et(i,t,e={}){let n=t.getLineObject();if(!n)return null;let r=e.threshold??t.options.pickThreshold??0,s=i.params.Line2??{threshold:0};s.threshold=r,i.params.Line2=s;let a=i.intersectObject(n,!1)[0];return a?bt(a):null}var Z=class i extends y{static type=vt;_line=null;_geometry=null;_material=null;constructor(t){super();let e=d(m,t);e.points=M(e.points,"ZylemLine").map(n=>u(n,h)),this.options=e}create(){return this.disposeLineResources(),this.group=new xt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(M(t,"setPoints"),this.options.points=t.map(r=>u(r,h)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(z(this.options.points));let n=L(this.options.colors,this.options.points.length,j(this.options.color));return n&&this._geometry.setColors(n),this._material.vertexColors=!!this.options.colors?.length,this.options.dashed&&this._line.computeLineDistances(),this._geometry.computeBoundingBox(),this._geometry.computeBoundingSphere(),this}getLineObject(){return this._line}pickFromRaycaster(t,e={}){return Et(t,this,e)}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??m.linewidth,worldUnits:this.options.worldUnits??m.worldUnits}}rebuildLine(){this._geometry=Y({points:this.options.points,colors:this.options.colors}),this._material=St(this.options),this._line=new Ct(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=u(this.options.position,h);this.group.position.set(t.x,t.y,t.z)}_cleanup(t){this.disposeLineResources(),super._cleanup(t)}disposeLineResources(){this._line?.removeFromParent(),this._geometry?.dispose(),this._material?.dispose(),this._line=null,this._geometry=null,this._material=null}};function G(...i){let t=V(i,m);M(t.points,"createLine");let e=new Z(t);return D(e,n=>G(n??{}))}var A={registry:new Map,register(i,t){this.registry.set(i,t)},createFromBlueprint(i){let t=this.registry.get(i.type);if(!t)throw new Error(`Unknown entity type: ${i.type}`);let e={...i.data,position:i.position?{x:i.position[0],y:i.position[1],z:0}:void 0,name:i.id};return t(e)}};A.register("text",i=>I(i));A.register("sprite",i=>P(i));A.register("line",i=>G(i));function Ce(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{c as a,at as b,g as c,I as d,ft as e,x as f,P as g,vt as h,Et as i,Z as j,G as k,A as l,Ce as m};
File without changes
@@ -1,4 +1,4 @@
1
- import{j as y}from"./chunk-MSC2BEO5.js";var r={baseFill:"rgba(12,18,24,0.72)",joystickStroke:"rgba(245,247,255,0.72)",joystickInnerStroke:"rgba(255,255,255,0.18)",joystickAccentFill:"rgba(255,255,255,0.04)",joystickTabFill:"rgba(245,247,255,0.45)",thumbFill:"rgba(22,30,38,0.92)",thumbStroke:"rgba(245,247,255,0.85)",thumbInnerFill:"rgba(255,255,255,0.08)",defaultButtonAccent:"rgba(245,247,255,0.92)"},b={baseFill:"rgba(8,14,24,0.70)",joystickStroke:"rgba(207,250,254,0.85)",joystickInnerStroke:"rgba(45,212,191,0.35)",joystickAccentFill:"rgba(20,184,166,0.08)",joystickTabFill:"rgba(207,250,254,0.55)",thumbFill:"rgba(13,148,136,0.88)",thumbStroke:"rgba(240,253,250,0.95)",thumbInnerFill:"rgba(240,253,250,0.16)",defaultButtonAccent:"#67e8f9",buttonAccents:{A:"#8b5cf6",B:"#fb7185",X:"#22d3ee",Y:"#facc15"}},m={default:r,lagoon:b};function l(e){return e?typeof e=="string"?m[e]??r:e:r}function f(e,t,o){return o||(e.buttonAccents?.[t]??e.defaultButtonAccent)}function h(e){let t=l(e);return`
1
+ import{k as y}from"./chunk-UG22Z42P.js";var r={baseFill:"rgba(12,18,24,0.72)",joystickStroke:"rgba(245,247,255,0.72)",joystickInnerStroke:"rgba(255,255,255,0.18)",joystickAccentFill:"rgba(255,255,255,0.04)",joystickTabFill:"rgba(245,247,255,0.45)",thumbFill:"rgba(22,30,38,0.92)",thumbStroke:"rgba(245,247,255,0.85)",thumbInnerFill:"rgba(255,255,255,0.08)",defaultButtonAccent:"rgba(245,247,255,0.92)"},b={baseFill:"rgba(8,14,24,0.70)",joystickStroke:"rgba(207,250,254,0.85)",joystickInnerStroke:"rgba(45,212,191,0.35)",joystickAccentFill:"rgba(20,184,166,0.08)",joystickTabFill:"rgba(207,250,254,0.55)",thumbFill:"rgba(13,148,136,0.88)",thumbStroke:"rgba(240,253,250,0.95)",thumbInnerFill:"rgba(240,253,250,0.16)",defaultButtonAccent:"#67e8f9",buttonAccents:{A:"#8b5cf6",B:"#fb7185",X:"#22d3ee",Y:"#facc15"}},m={default:r,lagoon:b};function l(e){return e?typeof e=="string"?m[e]??r:e:r}function f(e,t,o){return o||(e.buttonAccents?.[t]??e.defaultButtonAccent)}function h(e){let t=l(e);return`
2
2
  <svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
3
3
  <circle cx="70" cy="70" r="62" fill="${t.baseFill}" stroke="${t.joystickStroke}" stroke-width="4" />
4
4
  <circle cx="70" cy="70" r="42" fill="${t.joystickAccentFill}" stroke="${t.joystickInnerStroke}" stroke-width="2" />
@@ -0,0 +1 @@
1
+ import{positionWorldDirection as v,positionWorld as j,normalize as k,mix as B,smoothstep as E,clamp as F,sin as W,cos as w,atan as z,asin as C,abs as D,exp as G,pow as M,step as N,max as O,min as P,floor as V,fract as q,dot as A,length as H,vec2 as I,mod as J}from"three/tsl";function o(e,r=!1){return{colorNode:e,transparent:r}}export{o as a,v as b,j as c,k as d,B as e,E as f,F as g,W as h,w as i,z as j,C as k,D as l,G as m,M as n,N as o,O as p,P as q,V as r,q as s,A as t,H as u,I as v,J as w};
@@ -0,0 +1,9 @@
1
+ import{a as n,c as o,e as a}from"./chunk-JQKS42G4.js";var s=class r extends HTMLElement{_game=null;_state={};container;resizeObserver=null;_viewportProfile="auto";static HOST_CONFIG_MARKER=Symbol("zylem:host-config");constructor(){super(),this.attachShadow({mode:"open"});let e=document.createElement("style");e.textContent=`
2
+ :host {
3
+ display: block;
4
+ width: 100%;
5
+ height: 100%;
6
+ min-width: 0;
7
+ min-height: 0;
8
+ }
9
+ `,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.outline="none",this.container.tabIndex=0,this.shadowRoot.append(e,this.container)}focus(){this.container.focus()}connectedCallback(){typeof ResizeObserver<"u"&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(()=>{this.syncDisplayRuntime()}),this.resizeObserver.observe(this)),this.syncDisplayRuntime()}set game(e){this._game&&this._game.dispose(),this._game=e,this.attachHostContainer(e),this.syncDisplayRuntime(),e.start()}get game(){return this._game}set state(e){this._state=e,this.syncDebugState(),this.syncToolbarState()}get state(){return this._state}set viewportProfile(e){let t=e==="mobile"||e==="desktop"?e:"auto";this._viewportProfile!==t&&(this._viewportProfile=t,this.syncDisplayRuntime())}get viewportProfile(){return this._viewportProfile}static get observedAttributes(){return["viewport-profile"]}attributeChangedCallback(e,t,i){e==="viewport-profile"&&(this.viewportProfile=i??"auto")}syncDebugState(){let e=this._state.gameState?.debugFlag;e!==void 0&&(n.enabled=e)}syncToolbarState(){let{tool:e,paused:t}=this._state.toolbarState??{};e!==void 0&&a(e),t!==void 0&&o(t)}disconnectedCallback(){this.resizeObserver?.disconnect(),this.resizeObserver=null,this._game&&(this._game.dispose(),this._game=null)}attachHostContainer(e){let t=r.HOST_CONFIG_MARKER,i=e.options.find(l=>!!l?.[t]);if(i){i.container=this.container;return}e.options.push({container:this.container,[t]:!0})}syncDisplayRuntime(){if(!this._game)return;let e=this.getBoundingClientRect(),t=Math.round(e.width||this.clientWidth||0),i=Math.round(e.height||this.clientHeight||0);this._game.setDisplayRuntime({deviceProfile:this._viewportProfile,viewportSize:t>0&&i>0?{width:t,height:i}:void 0})}};customElements.define("zylem-game",s);export{s as a};
@@ -0,0 +1 @@
1
+ function r(n,e){return{[n]:{key:e}}}function V(n){return r(n,{ArrowLeft:["axes.Left"],ArrowRight:["axes.Right"],ArrowUp:["axes.Up"],ArrowDown:["axes.Down"]})}function x(n){return r(n,{ArrowLeft:["axes.SecondaryLeft"],ArrowRight:["axes.SecondaryRight"],ArrowUp:["axes.SecondaryUp"],ArrowDown:["axes.SecondaryDown"]})}function w(n){return r(n,{ArrowLeft:["directions.Left"],ArrowRight:["directions.Right"],ArrowUp:["directions.Up"],ArrowDown:["directions.Down"]})}function G(n){return r(n,{w:["directions.Up"],s:["directions.Down"],a:["directions.Left"],d:["directions.Right"]})}function A(n){return r(n,{a:["axes.Left"],d:["axes.Right"],w:["axes.Up"],s:["axes.Down"]})}function D(n){return r(n,{j:["axes.Left"],l:["axes.Right"],i:["axes.Up"],k:["axes.Down"]})}function J(n){return r(n,{j:["directions.Left"],l:["directions.Right"],i:["directions.Up"],k:["directions.Down"]})}function L(n,e){return{[n]:{mouse:{pointerLock:!0,lookMode:"delta",sensitivity:e?.sensitivity}}}}function b(n,e){return{[n]:{mouse:{pointerLock:!1,lookMode:"screenCenter",maxLookDegrees:e?.maxLookDegrees??45,lookSensitivity:e?.lookSensitivity}}}}function B(n,e){return{[n]:{mouse:{pointerLock:!1,sensitivity:e?.sensitivity}}}}function P(n,e){return{[n]:{touch:{enabled:e?.enabled??"auto",...e}}}}var h=["p1","p2","p3","p4","p5","p6","p7","p8"];function v(...n){let e={};for(let u of n)for(let o of h){let s=u[o];if(!s)continue;let t=e[o]??{},f=t.mouse||s.mouse?{...t.mouse,...s.mouse,mapping:{...t.mouse?.mapping,...s.mouse?.mapping}}:void 0,a=m(t.touch,s.touch);e[o]={key:{...t.key,...s.key},mouse:f,touch:a,includeDefaults:s.includeDefaults??t.includeDefaults}}return e}function m(n,e){if(!(!n&&!e))return n?e?{...n,...e,style:i(n.style,e.style),joysticks:T(n.joysticks,e.joysticks),buttons:k(n.buttons,e.buttons)}:d(n):d(e)}function T(n,e){if(e===void 0)return p(n);if(e===!1)return!1;let u=n||void 0;return{left:c(u?.left,e.left),right:c(u?.right,e.right)}}function c(n,e){return e===void 0?l(n):e===!1?!1:n?{...n,...e,style:i(n.style,e.style),position:i(n.position,e.position),svg:i(n.svg,e.svg)}:l(e)}function k(n,e){if(e===void 0)return y(n);if(e===!1)return!1;let u=n||void 0,o=u?C(u):{};for(let[s,t]of Object.entries(e)){let f=s,a=o[f];if(t===!1){o[f]=!1;continue}if(!a){o[f]=g(t);continue}o[f]={...a,...t,style:i(a.style,t.style),position:i(a.position,t.position)}}return o}function d(n){if(n)return{...n,style:i(void 0,n.style),joysticks:p(n.joysticks),buttons:y(n.buttons)}}function p(n){if(n!==void 0)return n===!1?!1:I(n)}function l(n){if(n!==void 0)return n===!1?!1:{...n,style:i(void 0,n.style),position:i(void 0,n.position),svg:i(void 0,n.svg)}}function y(n){if(n!==void 0)return n===!1?!1:C(n)}function g(n){return{...n,style:i(void 0,n.style),position:i(void 0,n.position)}}function I(n){return{left:l(n.left),right:l(n.right)}}function C(n){let e={};for(let[u,o]of Object.entries(n))e[u]=o===!1?!1:g(o);return e}function i(n,e){if(!(!n&&!e))return{...n??{},...e??{}}}export{V as a,x as b,w as c,G as d,A as e,D as f,J as g,L as h,b as i,B as j,P as k,v as l};
@@ -0,0 +1 @@
1
+ import{a as f,f as b}from"./chunk-JQKS42G4.js";var i=null;function g(n){return i=n,()=>{i===n&&(i=null)}}function O(n){if(!i)return console.warn("focusEntity: no active stage focus context"),!1;let t=i.resolveEntity(n);if(!t)return console.warn(`focusEntity: entity ${n} not found`),!1;let r=t.group??t.mesh??null;return r?(f.enabled||(f.enabled=!0),i.ensureDebugReady?.(),b(t),i.frameObject(r),!0):(console.warn(`focusEntity: entity ${n} has no group/mesh`),!1)}import{Box3 as d,PerspectiveCamera as p,Vector3 as u}from"three";var m=new d,a=new u,x=new u,h=new u;function l(n){m.setFromObject(n),m.getSize(a),m.getCenter(x);let t=Math.max(a.x,1e-4),r=Math.max(a.y,1e-4),o=Math.max(a.z,1e-4),e=Math.max(t,r,o);return{width:t,height:r,depth:o,center:x.clone(),maxDim:e}}function y(n,t,r=1.35){let o=t.fov*(Math.PI/180),e=n/(2*Math.tan(o/2))*r;return Math.max(e,.5)}function M(n,t,r=1.35){let o=l(n),e=y(o.maxDim,t,r);return t.position.copy(o.center).add(new u(e,e,e)),t.lookAt(o.center),t.near=Math.max(e/100,.01),t.far=Math.max(e*20,100),t.updateProjectionMatrix(),o}function v(n,t,r,o=1.5){let e=l(n),c=h.copy(r);c.lengthSq()<1e-8&&c.set(1,1,1),c.normalize();let s=e.maxDim*o;return t instanceof p&&(s=y(e.maxDim,t,o),t.near=Math.max(s/100,.01),t.far=Math.max(s*20,100),t.updateProjectionMatrix()),t.position.copy(e.center).addScaledVector(c,s),t.lookAt(e.center),e}export{M as a,v as b,g as c,O as d};
@@ -0,0 +1 @@
1
+ function u(t,r){let n;return a=>{let e=a.globals?.[t];n!==e&&(n===void 0&&e===void 0||r(e,a),n=e)}}function f(t,r){let n=new Array(t.length).fill(void 0);return a=>{let e=t.map(i=>a.globals?.[i]);if(e.some((i,l)=>n[l]!==i)){let i=n.every(o=>o===void 0),l=e.every(o=>o===void 0);i&&l||r(e,a),n=e}}}function g(t,r){let n;return a=>{let e=a.stage?.getVariable?.(t)??void 0;n!==e&&(n===void 0&&e===void 0||r(e,a),n=e)}}function C(t,r){let n=new Array(t.length).fill(void 0);return a=>{let e=l=>a.stage?.getVariable?.(l),d=t.map(e);if(d.some((l,o)=>n[o]!==l)){let l=n.every(s=>s===void 0),o=d.every(s=>s===void 0);l&&o||r(d,a),n=d}}}export{u as a,f as b,g as c,C as d};
@@ -0,0 +1 @@
1
+ import{BoundaryRicochet3DCoordinator as o,BoundaryRicochetCoordinator as r,CooldownBehavior as n,Destructible3DBehavior as i,DestructibleMesh as a,FirstPersonBehavior as D,FirstPersonEvent as m,FirstPersonFSM as c,FirstPersonShooterCoordinator as l,FirstPersonState as p,FirstPersonPresentation as u,FractureOptions as s,Jumper2DBehavior as h,Jumper2DEvent as d,Jumper2DFSM as B,Jumper2DState as C,Jumper3DBehavior as y,Jumper3DEvent as S,Jumper3DFSM as R,Jumper3DState as P,MultidirectionalSpaceShooterCoordinator as v,ParticleEmitterBehavior as E,Platformer2DBehavior as f,Platformer2DEvent as M,Platformer2DFSM as O,Platformer2DState as g,Platformer3DBehavior as T,Platformer3DEvent as I,Platformer3DFSM as F,Platformer3DState as W,Ricochet2DBehavior as H,Ricochet2DEvent as _,Ricochet2DFSM as J,Ricochet2DState as w,Ricochet3DBehavior as b,Ricochet3DEvent as A,Ricochet3DFSM as x,Ricochet3DState as V,ScreenVisibilityBehavior as k,ScreenVisibilityFSM as N,ScreenWrapBehavior as G,ScreenWrapEvent as Y,ScreenWrapFSM as U,ScreenWrapState as K,Shooter2DBehavior as L,ThrusterBehavior as Z,ThrusterEvent as z,ThrusterFSM as q,ThrusterState as j,TopDownMovementBehavior as Q,TopDownShooterCoordinator as X,WorldBoundary2DBehavior as $,WorldBoundary2DEvent as ee,WorldBoundary2DFSM as te,WorldBoundary2DState as oe,WorldBoundary3DBehavior as re,WorldBoundary3DEvent as ne,WorldBoundary3DFSM as ie,WorldBoundary3DState as ae,computeWorldBoundary2DHits as De,computeWorldBoundary3DHits as me,createFirstPersonInputComponent as ce,createFirstPersonMovementComponent as le,createFirstPersonStateComponent as pe,createJumpConfig2D as ue,createJumpConfig3D as se,createJumpInput2D as he,createJumpInput3D as de,createJumpState2D as Be,createJumpState3D as Ce,createPhysicsBodyComponent as ye,createPlatformer2DInputComponent as Se,createPlatformer2DMovementComponent as Re,createPlatformer2DStateComponent as Pe,createPlatformer3DInputComponent as ve,createPlatformer3DMovementComponent as Ee,createPlatformer3DStateComponent as fe,createShooter2DStateComponent as Me,createThrusterInputComponent as Oe,createThrusterMovementComponent as ge,createThrusterStateComponent as Te,createTopDownMovementComponent as Ie,createTopDownMovementInputComponent as Fe,createTopDownMovementStateComponent as We,createTransformComponent as He,defineBehavior as _e,fireCooldown as Je,fireShooter2DIfRequested as we,getCooldown as be,getCooldownStore as Ae,getEntityFacingAngle2D as xe,hasAnyWorldBoundary2DHit as Ve,hasAnyWorldBoundary3DHit as ke,particleEffect as Ne,particlePresets as Ge,registerCooldown as Ye,resetCooldown as Ue,resolveAim2D as Ke,tickCooldowns as Le,updateBoundaryRicochet as Ze,useBehavior as ze}from"@zylem/behaviors";import{RuntimeBoundary2DBehavior as Xe,RuntimeDynamicCircleBody2DBehavior as $e,RuntimeGoalZone2DBehavior as et,RuntimePlayerInput2DBehavior as tt,RuntimeRicochet2DBehavior as ot,RuntimeTriggerRegion2DBehavior as rt,RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY as nt,RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY as it,RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY as at,RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY as Dt,RUNTIME_RICOCHET_2D_BEHAVIOR_KEY as mt,RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY as ct,bindRuntimeDynamicCircleBody2DHandle as lt,emitRuntimeGoal as pt,emitRuntimeRicochet as ut,emitRuntimeTriggerRegionEnter as st}from"@zylem/behaviors/runtime-2d";export{o as a,r as b,n as c,i as d,a as e,D as f,m as g,c as h,l as i,p as j,u as k,s as l,h as m,d as n,B as o,C as p,y as q,S as r,R as s,P as t,v as u,E as v,f as w,M as x,O as y,g as z,T as A,I as B,F as C,W as D,H as E,_ as F,J as G,w as H,b as I,A as J,x as K,V as L,k as M,N,G as O,Y as P,U as Q,K as R,L as S,Z as T,z as U,q as V,j as W,Q as X,X as Y,$ as Z,ee as _,te as $,oe as aa,re as ba,ne as ca,ie as da,ae as ea,De as fa,me as ga,ce as ha,le as ia,pe as ja,ue as ka,se as la,he as ma,de as na,Be as oa,Ce as pa,ye as qa,Se as ra,Re as sa,Pe as ta,ve as ua,Ee as va,fe as wa,Me as xa,Oe as ya,ge as za,Te as Aa,Ie as Ba,Fe as Ca,We as Da,He as Ea,_e as Fa,Je as Ga,we as Ha,be as Ia,Ae as Ja,xe as Ka,Ve as La,ke as Ma,Ne as Na,Ge as Oa,Ye as Pa,Ue as Qa,Ke as Ra,Le as Sa,Ze as Ta,ze as Ua,Xe as Va,$e as Wa,et as Xa,tt as Ya,ot as Za,rt as _a,nt as $a,it as ab,at as bb,Dt as cb,mt as db,ct as eb,lt as fb,pt as gb,ut as hb,st as ib};
@@ -0,0 +1 @@
1
+ import{Quaternion as v}from"three";import{Quaternion as p}from"three";var h=new WeakMap,m=new p,x=new p,c=new p;function f(t){return{x:t.x,y:t.y,z:t.z}}function b(t){return{x:t.x,y:t.y,z:t.z,w:t.w}}function r(t){return{position:f(t.position),rotation:b(t.rotation)}}function u(t){return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function l(t){return{position:f(t.translation()),rotation:b(t.rotation())}}function g(t){let e=r(t);return{previous:r(e),current:e}}function w(t){let e=l(t),o=h.get(t)??g(e);return o.previous=r(e),o.current=r(e),h.set(t,o),o}function d(t,e,o){let s=u(o);return m.set(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w),x.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),c.slerpQuaternions(m,x,s),{position:{x:t.position.x+(e.position.x-t.position.x)*s,y:t.position.y+(e.position.y-t.position.y)*s,z:t.position.z+(e.position.z-t.position.z)*s},rotation:{x:c.x,y:c.y,z:c.z,w:c.w}}}function k(t,e){if(R(t))return t.getRenderPose(e);let o=h.get(t);if(!o)return l(t);let s=l(t);if(!H(s,o.current)){let n=w(t);return r(n.current)}return d(o.previous,o.current,e)}function R(t){return t!=null&&typeof t=="object"&&typeof t.getPoseHistory=="function"&&typeof t.getRenderPose=="function"}function H(t,e){return t.position.x===e.position.x&&t.position.y===e.position.y&&t.position.z===e.position.z&&t.rotation.x===e.rotation.x&&t.rotation.y===e.rotation.y&&t.rotation.z===e.rotation.z&&t.rotation.w===e.rotation.w}var P={x:0,y:0,z:0},a=new v,z=new v,S=class t{constructor(e,o,s){this.simulation=e;this.handle=o;this.clock=s;this.interpolationValidAfterStep=s.steps+2}poseScratch={position:[0,0,0],rotation:[0,0,0,1]};renderScratch={position:[0,0,0],rotation:[0,0,0,1],scale:1,custom:[0,0,0,0],isSleeping:!1};previousScratch={position:[0,0,0],rotation:[0,0,0,1],scale:1,custom:[0,0,0,0],isSleeping:!1};interpolationValidAfterStep;markPoseDiscontinuity(){this.interpolationValidAfterStep=this.clock.steps+2}isInterpolationStale(){return this.clock.steps<this.interpolationValidAfterStep}translation(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{x:e.position[0],y:e.position[1],z:e.position[2]}:{...P}}rotation(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}:{x:0,y:0,z:0,w:1}}linvel(){let e=this.simulation.getLinearVelocity(this.handle);return e?{x:e[0],y:e[1],z:e[2]}:{...P}}angvel(){let e=this.simulation.adapter.getAngularVelocity(this.handle.slot);return e?{x:e[0],y:e[1],z:e[2]}:{...P}}setTranslation(e,o=!0){this.simulation.setPosition(this.handle,e.x,e.y,e.z),this.markPoseDiscontinuity()}setRotation(e,o=!0){this.simulation.setRotation(this.handle,e.x,e.y,e.z,e.w),this.markPoseDiscontinuity()}setLinvel(e,o=!0){this.simulation.setLinearVelocity(this.handle,e.x,e.y,e.z)}setAngvel(e,o=!0){this.simulation.setAngularVelocity(this.handle,e.x,e.y,e.z)}applyImpulse(e,o=!0){this.simulation.applyImpulse(this.handle,e.x,e.y,e.z)}lockRotations(e,o=!0){e&&this.setAngvel({x:0,y:0,z:0})}lockTranslations(e,o=!0){e&&this.setLinvel({x:0,y:0,z:0})}setLinearDamping(e){}setGravityScale(e,o=!0){}bodyInfo(){return this.simulation.getBodyInfo(this.handle)}bodyType(){return this.bodyInfo()?.bodyType??0}mass(){return this.bodyInfo()?.mass??0}isSleeping(){return this.bodyInfo()?.isSleeping??!1}isEnabled(){return this.bodyInfo()?.isEnabled??!0}livePose(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{position:{x:e.position[0],y:e.position[1],z:e.position[2]},rotation:{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}}:{position:{...P},rotation:{x:0,y:0,z:0,w:1}}}static slotToPose(e){return{position:{x:e.position[0],y:e.position[1],z:e.position[2]},rotation:{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}}}getPoseHistory(){if(this.isInterpolationStale()){let i=this.livePose();return{previous:r(i),current:i}}let e=this.simulation.readRenderSlot(this.handle,this.renderScratch),o=this.simulation.readPreviousRenderSlot(this.handle,this.previousScratch),s=e?t.slotToPose(e):this.livePose();return{previous:o?t.slotToPose(o):r(s),current:s}}getRenderPose(e){let o=this.getPoseHistory();return d(o.previous,o.current,e)}isRenderSleeping(){return this.simulation.readRenderSlot(this.handle,this.renderScratch)?.isSleeping===!0}writeRenderPose(e,o,s){if(this.isInterpolationStale()){this.writeLivePose(o,s);return}let n=this.simulation.readRenderSlot(this.handle,this.renderScratch);if(!n){this.writeLivePose(o,s);return}let i=this.simulation.readPreviousRenderSlot(this.handle,this.previousScratch)??n,y=u(e);o.x=i.position[0]+(n.position[0]-i.position[0])*y,o.y=i.position[1]+(n.position[1]-i.position[1])*y,o.z=i.position[2]+(n.position[2]-i.position[2])*y,a.set(i.rotation[0],i.rotation[1],i.rotation[2],i.rotation[3]),z.set(n.rotation[0],n.rotation[1],n.rotation[2],n.rotation[3]),a.slerp(z,y),s.x=a.x,s.y=a.y,s.z=a.z,s.w=a.w}writeLivePose(e,o){let s=this.simulation.getPose(this.handle,this.poseScratch);s?(e.x=s.position[0],e.y=s.position[1],e.z=s.position[2],o.x=s.rotation[0],o.y=s.rotation[1],o.z=s.rotation[2],o.w=s.rotation[3]):(e.x=0,e.y=0,e.z=0,o.x=0,o.y=0,o.z=0,o.w=1)}};export{k as a,S as b};
@@ -0,0 +1 @@
1
+ function r(i=800,t=.05){c(i,t)}function c(i,t){let e=new(window.AudioContext||window.webkitAudioContext),n=e.createOscillator(),o=e.createGain();n.type="sawtooth",n.frequency.value=i,o.gain.setValueAtTime(.05,e.currentTime),o.gain.exponentialRampToValueAtTime(.001,e.currentTime+t),n.connect(o),o.connect(e.destination),n.start(),n.stop(e.currentTime+t)}function a(i=440,t=.1){u(i,t)}function u(i,t){let e=new(window.AudioContext||window.webkitAudioContext),n=e.createOscillator(),o=e.createGain();n.type="square",n.frequency.value=i,o.gain.setValueAtTime(.05,e.currentTime),o.gain.exponentialRampToValueAtTime(.001,e.currentTime+t),n.connect(o),o.connect(e.destination),n.start(),n.stop(e.currentTime+t)}import{Howl as x}from"howler";export{r as a,a as b,x as c};
@@ -0,0 +1,49 @@
1
+ import { SimulationBodyDefinition, SimulationColliderDefinition } from '@zylem/behaviors/core';
2
+ import { e as Vec3Input } from './vector-DN6zlPoE.js';
3
+
4
+ /** Per-axis lock input: `true` locks all axes, or pass an [x, y, z] tuple. */
5
+ type LockAxesInput = boolean | readonly [boolean, boolean, boolean];
6
+ /**
7
+ * Options for configuring entity collision behavior.
8
+ */
9
+ interface CollisionOptions {
10
+ static?: boolean;
11
+ sensor?: boolean;
12
+ canSleep?: boolean;
13
+ ccdEnabled?: boolean;
14
+ size?: Vec3Input;
15
+ position?: Vec3Input;
16
+ collisionType?: string;
17
+ collisionFilter?: string[];
18
+ /** Gravity scale applied at body spawn (no live setter FFI; default 1). */
19
+ gravityScale?: number;
20
+ /** Lock rotation axes at body spawn: `true` for all, or per-axis tuple. */
21
+ lockRotations?: LockAxesInput;
22
+ /** Lock translation axes at body spawn: `true` for all, or per-axis tuple. */
23
+ lockTranslations?: LockAxesInput;
24
+ }
25
+ /**
26
+ * Pack a collision type + filter into the runtime's interaction-groups u32
27
+ * (high 16 bits = membership mask, low 16 bits = filter mask).
28
+ */
29
+ declare function packCollisionGroups(collisionType?: string, collisionFilter?: string[]): number;
30
+ /**
31
+ * Builds plain body + collider definitions consumable by the behaviors
32
+ * `Simulation` (`simulation.spawn(...)`). No physics-engine types appear
33
+ * here — everything is data until the world uploads it to the wasm runtime.
34
+ */
35
+ declare class CollisionBuilder {
36
+ static: boolean;
37
+ sensor: boolean;
38
+ gravityScale?: number;
39
+ lockRotations?: LockAxesInput;
40
+ lockTranslations?: LockAxesInput;
41
+ build(options: Partial<CollisionOptions>): [SimulationBodyDefinition, SimulationColliderDefinition];
42
+ withCollision(collisionOptions: Partial<CollisionOptions>): this;
43
+ collider(options: CollisionOptions): SimulationColliderDefinition;
44
+ bodyDesc({ isDynamicBody }: {
45
+ isDynamicBody?: boolean | undefined;
46
+ }): SimulationBodyDefinition;
47
+ }
48
+
49
+ export { CollisionBuilder as C, type LockAxesInput as L, type CollisionOptions as a, packCollisionGroups as p };