@zylem/game-lib 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +3 -1
  2. package/dist/actions.d.ts +255 -8
  3. package/dist/actions.js +1 -772
  4. package/dist/audio.d.ts +13 -0
  5. package/dist/audio.js +1 -0
  6. package/dist/base-node-life-cycle-CnJ-7zX-.d.ts +143 -0
  7. package/dist/behavior.d.ts +3 -0
  8. package/dist/behavior.js +1 -0
  9. package/dist/chunk-4QLJUQSJ.js +1 -0
  10. package/dist/chunk-73VZQZUL.js +1 -0
  11. package/dist/chunk-A34ZG3L4.js +1 -0
  12. package/dist/chunk-CDPY4VOQ.js +1 -0
  13. package/dist/chunk-DR6XXZE7.js +19 -0
  14. package/dist/chunk-FM5TBEPO.js +1 -0
  15. package/dist/chunk-G2IIMSUH.js +1 -0
  16. package/dist/chunk-MSC2BEO5.js +1 -0
  17. package/dist/chunk-NIH5CONO.js +1 -0
  18. package/dist/chunk-ONWXGBWB.js +1 -0
  19. package/dist/chunk-QEDQDR27.js +1 -0
  20. package/dist/chunk-QXVH6POE.js +1 -0
  21. package/dist/chunk-RXDTAWI2.js +29 -0
  22. package/dist/chunk-WKHW2QO2.js +1 -0
  23. package/dist/chunk-XRP4JJXL.js +1 -0
  24. package/dist/chunk-YHEWKN7N.js +1 -0
  25. package/dist/chunk-YHKXQ2ZN.js +1 -0
  26. package/dist/core.d.ts +206 -13
  27. package/dist/core.js +24 -9160
  28. package/dist/debug.d.ts +24 -0
  29. package/dist/debug.js +1 -0
  30. package/dist/default-controls-BGc61yYl.d.ts +111 -0
  31. package/dist/entity-DNkYKfdp.d.ts +1043 -0
  32. package/dist/entity-type-map-C94h2TDW.d.ts +781 -0
  33. package/dist/entity.d.ts +265 -0
  34. package/dist/entity.js +1 -0
  35. package/dist/events.d.ts +172 -0
  36. package/dist/events.js +1 -0
  37. package/dist/game-Cuj5gy7U.d.ts +1590 -0
  38. package/dist/game-default-PZLLHYL7.js +1 -0
  39. package/dist/game-interfaces-tfpM5NBk.d.ts +90 -0
  40. package/dist/globals.d.ts +104 -0
  41. package/dist/globals.js +1 -0
  42. package/dist/graphics.d.ts +83 -0
  43. package/dist/graphics.js +1 -0
  44. package/dist/input-ui.d.ts +34 -0
  45. package/dist/input-ui.js +1 -0
  46. package/dist/input.d.ts +72 -0
  47. package/dist/input.js +1 -0
  48. package/dist/material-Wz83vTTp.d.ts +151 -0
  49. package/dist/runtime.d.ts +433 -0
  50. package/dist/runtime.js +1 -0
  51. package/dist/web-components.d.ts +67 -0
  52. package/dist/web-components.js +9 -0
  53. package/dist/world-C9zdyl5d.d.ts +103 -0
  54. package/dist/zylem-stage-runtime-Cs-UDEVU.d.ts +777 -0
  55. package/package.json +54 -41
  56. package/dist/actions.js.map +0 -1
  57. package/dist/behavior/platformer-3d.d.ts +0 -296
  58. package/dist/behavior/platformer-3d.js +0 -518
  59. package/dist/behavior/platformer-3d.js.map +0 -1
  60. package/dist/behavior/ricochet-2d.d.ts +0 -274
  61. package/dist/behavior/ricochet-2d.js +0 -394
  62. package/dist/behavior/ricochet-2d.js.map +0 -1
  63. package/dist/behavior/screen-wrap.d.ts +0 -86
  64. package/dist/behavior/screen-wrap.js +0 -195
  65. package/dist/behavior/screen-wrap.js.map +0 -1
  66. package/dist/behavior/thruster.d.ts +0 -10
  67. package/dist/behavior/thruster.js +0 -234
  68. package/dist/behavior/thruster.js.map +0 -1
  69. package/dist/behavior/world-boundary-2d.d.ts +0 -141
  70. package/dist/behavior/world-boundary-2d.js +0 -181
  71. package/dist/behavior/world-boundary-2d.js.map +0 -1
  72. package/dist/behavior-descriptor-BWNWmIjv.d.ts +0 -142
  73. package/dist/blueprints-BWGz8fII.d.ts +0 -26
  74. package/dist/camera-B5e4c78l.d.ts +0 -468
  75. package/dist/camera.d.ts +0 -6
  76. package/dist/camera.js +0 -1406
  77. package/dist/camera.js.map +0 -1
  78. package/dist/composition-DrzFrbqI.d.ts +0 -218
  79. package/dist/core-DAkskq6Y.d.ts +0 -498
  80. package/dist/core.js.map +0 -1
  81. package/dist/entities-DC9ce_vx.d.ts +0 -416
  82. package/dist/entities.d.ts +0 -9
  83. package/dist/entities.js +0 -4069
  84. package/dist/entities.js.map +0 -1
  85. package/dist/entity-BpbZqg19.d.ts +0 -1100
  86. package/dist/entity-Bq_eNEDI.d.ts +0 -28
  87. package/dist/entity-types-DAu8sGJH.d.ts +0 -26
  88. package/dist/global-change-Dc8uCKi2.d.ts +0 -25
  89. package/dist/main.d.ts +0 -654
  90. package/dist/main.js +0 -13355
  91. package/dist/main.js.map +0 -1
  92. package/dist/stage-types-BFsm3qsZ.d.ts +0 -567
  93. package/dist/stage.d.ts +0 -51
  94. package/dist/stage.js +0 -5738
  95. package/dist/stage.js.map +0 -1
  96. package/dist/thruster-DhRaJnoL.d.ts +0 -172
  97. package/dist/world-Be5m1XC1.d.ts +0 -31
@@ -0,0 +1 @@
1
+ import{a as G,m as ve,n as Ue}from"./chunk-A34ZG3L4.js";import{a as u,d as ye,f as Te,g as _e,h as Ae,i as ke}from"./chunk-CDPY4VOQ.js";import{a as k,m as Fe,n as be,u as H,w as Ze}from"./chunk-ONWXGBWB.js";import{e as R,f as Ie}from"./chunk-DR6XXZE7.js";import{a as Oe,b as A}from"./chunk-YHEWKN7N.js";import{a as U,b as Ve,c as j,d as We,e as Ne,f as He,g as Ge,m as Q}from"./chunk-WKHW2QO2.js";import{c as N,d as fe,j as S}from"./chunk-4QLJUQSJ.js";import{c as v,i as ze,j as g}from"./chunk-G2IIMSUH.js";import{a as je}from"./chunk-FM5TBEPO.js";import{k as Be}from"./chunk-MSC2BEO5.js";import{Vector2 as Ot}from"three";import{WebGPURenderer as zt,RenderPipeline as Ft}from"three/webgpu";import{pass as It,renderOutput as Zt,screenCoordinate as Vt,vec2 as Ce,vec4 as Wt,fract as $e,sin as Xe,dot as Je}from"three/tsl";import{setConsoleFunction as kt,getConsoleFunction as Bt}from"three";var Qe="THREE.Abstract function.",Ke=!1,qe=!1;function Ye(){if(Ke)return;Ke=!0;let a=Bt();kt((e,t,...i)=>{if(e==="warn"&&t===Qe){qe||(qe=!0,console.warn(`${Qe} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(a){a(e,t,...i);return}let r=i[0],s=e==="log"?console.log:e==="error"?console.error:console.warn;r&&r.isStackTrace&&typeof r.getError=="function"?s(r.getError(t)):s(t,...i)})}var et={x:0,y:0,width:1,height:1};async function Xi(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var K=class{renderer;postProcessing=null;renderScale=1;screenResolution;rendererType;_initialized=!1;_sceneRef=null;_lastAnimationTimestamp=null;constructor(e,t="webgpu"){this.screenResolution=e||new Ot(window.innerWidth,window.innerHeight),this.rendererType="webgpu"}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(Ye(),this.renderer=new zt({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();let i=new Ft(this.renderer),r=It(e,t);this.renderScale!==1&&r.setResolutionScale(this.renderScale),i.outputColorTransform=!1,i.outputNode=Zt(r).add(Ht()),this.postProcessing=i}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,e(i)})}stopRenderLoop(){this._lastAnimationTimestamp=null;try{this.renderer.setAnimationLoop(null)}catch{}}renderCamera(e,t,i=!1){let r=t.viewport,s=this.screenResolution.x,n=this.screenResolution.y,l=Math.floor(r.x*s),o=Math.floor(r.y*n),c=Math.floor(r.width*s),d=Math.floor(r.height*n);this.renderer.setViewport(l,o,c,d),this.renderer.setScissor(l,o,c,d),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&&Nt(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.disposePostProcessing();try{this.renderer.dispose()}catch{}this._sceneRef=null,this._initialized=!1}};function Nt(a){return a.x===0&&a.y===0&&a.width===1&&a.height===1}function Ht(){let a=Vt.xy,e=$e(Xe(Je(a,Ce(12.9898,78.233))).mul(43758.5453)),t=$e(Xe(Je(a.add(Ce(13,7)),Ce(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return Wt(i,i,i,0)}var p={FirstPerson:"first-person",ThirdPerson:"third-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};import{Vector3 as Gt,Quaternion as Ut,MathUtils as Se}from"three";function q(){return{position:new Gt(0,0,10),rotation:new Ut,fov:75,zoom:1,near:.1,far:1e3}}function D(a){return{position:a.position.clone(),rotation:a.rotation.clone(),fov:a.fov,zoom:a.zoom,near:a.near,far:a.far,lookAt:a.lookAt?.clone()}}function tt(a,e){let t=D(a);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 it(a,e,t,i){let r=1-Math.pow(1-Se.clamp(t,0,1),i*60),s=D(a);return s.position.lerp(e.position,r),s.rotation.slerp(e.rotation,r),e.fov!=null&&s.fov!=null&&(s.fov=Se.lerp(s.fov,e.fov,r)),e.zoom!=null&&s.zoom!=null&&(s.zoom=Se.lerp(s.zoom,e.zoom,r)),e.near!=null&&(s.near=e.near),e.far!=null&&(s.far=e.far),e.lookAt?s.lookAt?s.lookAt.lerp(e.lookAt,r):s.lookAt=e.lookAt.clone():s.lookAt=void 0,s}var Y=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=q();_finalPose=q();_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):q(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=D(t);for(let r=this.actions.length-1;r>=0;r--){let s=this.actions[r],n=s.update(e);t=tt(t,n),s.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=it(this._finalPose,t,this.damping,e.dt):(this._finalPose=D(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?D(this._desiredPose):null,finalPose:this._finalPose?D(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 P,Quaternion as $}from"three";var jt={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},E=class{id="third-person";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...jt,...r},this.initialPosition=t?g(t,v):void 0,this.initialLookAt=i?g(i,v):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 $,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new P(0,0,0)}:{position:new P(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new $,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new P(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new P(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new $,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([m,h])=>this.getTrailedPosition(m,h.position,e.time)),r=new P;for(let m of i)r.add(m);r.divideScalar(i.length);let s=0;for(let m of i){let h=r.distanceTo(m);h>s&&(s=h)}let n=Math.max(s*this.opts.paddingFactor,this.opts.minDistance),l=new P(this.opts.shoulderOffset,this.opts.height,this.opts.distance),o=l.length(),c=o>0?l.clone().normalize():new P(0,.5,1).normalize(),d=r.clone().add(c.multiplyScalar(n));if(o>0){let m=this.opts.height/o;d.y=r.y+n*m}return{position:d,rotation:new $,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 s=this._trailBuffers.get(e);s||(s=[],this._trailBuffers.set(e,s)),s.push({time:i,pos:t.clone()});let n=i-r-.05;for(;s.length>1&&s[0].time<n;)s.shift();s.length>this.opts.trailBufferSize&&s.splice(0,s.length-this.opts.trailBufferSize);let l=i-r;if(s[0].time>=l)return s[0].pos.clone();for(let o=1;o<s.length;o++){let c=s[o-1],d=s[o];if(c.time<=l&&l<=d.time){let m=d.time-c.time,h=m>1e-6?(l-c.time)/m:0;return new P().lerpVectors(c.pos,d.pos,h)}}return s[s.length-1].pos.clone()}};import{Vector3 as rt,Quaternion as Qt}from"three";var at={position:{x:0,y:0,z:10},zoom:10},M=class{id="fixed-2d";defaults={damping:1};opts;constructor(e){this.opts={...at,...e,position:g(e?.position,at.position)}}getBasePose(e){return{position:new rt(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new Qt,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new rt(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as Pe,Quaternion as we,Euler as ot,MathUtils as y}from"three";var Kt={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},B=class{id="first-person";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new we;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Kt,...r},this.initialPosition=t?g(t,v):void 0,this.initialLookAt=i?g(i,v):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=y.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=y.clamp(t,-this.opts.pitchLimit,this.opts.pitchLimit)}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 Pe(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new Pe(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=y.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=y.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new we().setFromEuler(new ot(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=st.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let s=Math.atan2(-r.x,-r.z),n=Math.asin(y.clamp(r.y,-1,1)),l=qt.setFromEuler(nt.set(n,s,0,"YXZ")),o=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(l,y.clamp(o,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 y.lerp(this._currentFov,this._targetFov,y.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=st.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(y.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=nt.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=y.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},st=new Pe,qt=new we,nt=new ot;function L(a,e){switch(a){case"third-person":return new E(e);case"first-person":return new B(e);case"isometric":return new E({distance:10,height:10,...e});case"flat-2d":return new M(e);case"fixed-2d":return new M(e);default:return new E(e)}}import{Vector2 as Jt}from"three";import{PerspectiveCamera as O,Vector3 as $t,OrthographicCamera as J,RenderTarget as Xt,LinearFilter as ct}from"three";import{Vector3 as lt}from"three";import{OrbitControls as Yt}from"three/addons/controls/OrbitControls.js";var X=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new lt;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;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}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}applyDebugState(e){let t=this.debugStateSnapshot.enabled;this.debugStateSnapshot={enabled:e.enabled,selected:[...e.selected]},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 Yt(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=null,this.orbitControls&&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=null}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 lt;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;rendererType;sceneRef=null;name="";viewport={...et};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;_rendererManager=null;_elapsedTime=0;constructor(e,t,i=10,r="webgpu"){this._perspective=e,this.screenResolution=t,this.frustumSize=i,this.rendererType=r;let s=t.x/t.y;this.camera=this.createCameraForPerspective(s),this.camera.position.set(0,0,10),this.camera.lookAt(new $t(0,0,0));let n=L(e);this.pipeline=new Y(n)}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 X(this.camera,this._rendererManager.renderer.domElement,null),this.orbitController.setScene(e),this._useOrbitalControls&&this.orbitController.enableUserOrbitControls())}async setupLegacy(e){this._rendererManager||(this._rendererManager=new K(this.screenResolution,this.rendererType),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 O&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof J){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 Xt(e,t,{minFilter:ct,magFilter:ct}),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}setDebugDelegate(e){this._skipDebugOrbit||this.orbitController?.setDebugDelegate(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],s=i===0?"primary":`target_${i}`;r.group&&(t[s]={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 O&&(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 J){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 O(75,e,.1,1e3);case p.FirstPerson:return new O(75,e,.1,1e3);case p.Isometric:return new J(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);case p.Flat2D:case p.Fixed2D:return new J(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);default:return new O(75,e,.1,1e3)}}};var ee=class{cameras=new Map;_activeCameras=[];_debugCamera=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 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[s,n]of this.cameras.entries())if(n===e){t=s;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);for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._debugCamera&&(this._debugCamera.setRendererManager(t),await this._debugCamera.setup(e,t))}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 Jt(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?.destroy(),this.cameras.clear(),this._activeCameras=[],this._debugCamera=null,this._rendererManager=null,this._sceneRef=null}createDebugCamera(e){this._debugCamera=new C(p.ThirdPerson,e),this._debugCamera.name="__debug__",this._debugCamera.enableOrbitalControls()}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;for(let t of this.cameras.values())if(t===e)return t;return null}};var b=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 ia(a){let e=ze(a.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;a.perspective==="fixed-2d"&&(t=a.zoom||10);let i=new C(a.perspective||"third-person",e,t,a.rendererType||"webgpu");a.name&&(i.name=a.name);let r=g(a.position,v),s=g(a.target,v);i.move(r),i.camera.lookAt(s);let n=a.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:s.clone()})),a.viewport&&(i.viewport={...a.viewport}),a.useOrbitalControls&&(i._useOrbitalControls=!0),a.skipDebugOrbit&&(i._skipDebugOrbit=!0),a.damping!=null&&(i.pipeline.damping=a.damping),a.behaviors)for(let[l,o]of Object.entries(a.behaviors))i.pipeline.addBehavior(l,o);if(a.renderToTexture){let{width:l=512,height:o=512}=a.renderToTexture;i.createRenderTarget(l,o)}return new b(i)}import{Vector3 as ei}from"three";function w(a){return!!a&&typeof a=="object"&&typeof a.create=="function"}function z(a){return!!a&&typeof a.then=="function"}function De(a){return!!a&&typeof a=="object"&&a instanceof b}function dt(a){return!a||typeof a!="object"||w(a)||De(a)||z(a)||typeof a.then=="function"?!1:a.constructor===Object||a.constructor?.name==="Object"}function ut(a){return a?!!(w(a)||typeof a=="function"||z(a)):!1}var ti="/three/basis/";function ie(a){return{...a,ktx2TranscoderPath:a?.ktx2TranscoderPath??ti}}var te=class{constructor(e,t,i,r,s,n,l=60,o={},c=void 0,d=void 0,m=!0,h=void 0){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=s;this.variables=n;this.physicsRate=l;this.assetLoaders=o;this.runtimeAdapter=c;this.runtimeDebugBinding=d;this.defaultLighting=m;this.wasmRuntime=h}};function ii(){return new te({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},U,null,null,new ei(0,0,0),{},60,{},void 0,void 0,!0,void 0)}function mt(a=[]){let e=ii(),t={},i=[],r=[],s=[];for(let o of a)De(o)?s.push(o):w(o)?i.push(o):ut(o)&&!w(o)?r.push(o):dt(o)&&(t={...t,...o});let n=new te(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.runtimeAdapter??e.runtimeAdapter,t.runtimeDebugBinding??e.runtimeDebugBinding,t.defaultLighting??e.defaultLighting,t.wasmRuntime??e.wasmRuntime),l=s.length>0?s[0]:void 0;return{config:n,entities:i,asyncEntities:r,camera:l,cameras:s}}function da(a){return{...a}}var ri=Symbol("vessel"),F=class extends k{static type=ri;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=ai();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function ai(...a){let e=new F;return a.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as _t,Vector3 as pe}from"three";import St from"@dimforge/rapier3d-compat";import{Quaternion as Ee}from"three";var T=new WeakMap,ht=new Ee,pt=new Ee,I=new Ee;function gt(a){return{x:a.x,y:a.y,z:a.z}}function ft(a){return{x:a.x,y:a.y,z:a.z,w:a.w}}function _(a){return{position:gt(a.position),rotation:ft(a.rotation)}}function si(a){return Number.isFinite(a)?Math.max(0,Math.min(1,a)):0}function Z(a){return{position:gt(a.translation()),rotation:ft(a.rotation())}}function xe(a){let e=_(a);return{previous:_(e),current:e}}function yt(a){let e=xe(Z(a));return T.set(a,e),e}function V(a){let e=Z(a),t=T.get(a)??xe(e);return t.previous=_(e),t.current=_(e),T.set(a,t),t}function bt(a){return V(a)}function vt(a){let e=Z(a),t=T.get(a)??xe(e);return t.current=_(e),T.set(a,t),t}function ni(a,e,t){let i=si(t);return ht.set(a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w),pt.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),I.slerpQuaternions(ht,pt,i),{position:{x:a.position.x+(e.position.x-a.position.x)*i,y:a.position.y+(e.position.y-a.position.y)*i,z:a.position.z+(e.position.z-a.position.z)*i},rotation:{x:I.x,y:I.y,z:I.z,w:I.w}}}function Ct(a,e){if(oi(a))return a.getRenderPose(e);let t=T.get(a);if(!t)return Z(a);let i=Z(a);if(!li(i,t.current)){let r=V(a);return _(r.current)}return ni(t.previous,t.current,e)}function oi(a){return a!=null&&typeof a=="object"&&typeof a.getPoseHistory=="function"&&typeof a.getRenderPose=="function"}function li(a,e){return a.position.x===e.position.x&&a.position.y===e.position.y&&a.position.z===e.position.z&&a.rotation.x===e.rotation.x&&a.rotation.y===e.rotation.y&&a.rotation.z===e.rotation.z&&a.rotation.w===e.rotation.w}function Re(a){return typeof a?.handlePostCollision=="function"&&typeof a?.handleIntersectionEvent=="function"}function ci(a,e){return a<e?`${a}|${e}`:`${e}|${a}`}function di(a){let e=new Map;for(let t of a){if(t.uuidA===t.uuidB)continue;let i=ci(t.uuidA,t.uuidB),r=t.uuidA<t.uuidB?t.uuidA:t.uuidB,s=t.uuidA<t.uuidB?t.uuidB:t.uuidA,n=e.get(i);if(n){t.contactType==="contact"?n.hasContact=!0:n.hasIntersection=!0;continue}e.set(i,{uuidA:r,uuidB:s,hasContact:t.contactType==="contact",hasIntersection:t.contactType==="intersection"})}return e}var W=class a{type="World";world;collisionMap=new Map;collisionBehaviorMap=new Map;_removalMap=new Map;activeCollisionPairs=new Map;currentCollisionTimeMs=0;fixedTimestep;accumulator=0;static MAX_STEPS_PER_FRAME=5;interpolationAlpha=0;trackedDirectBodies=new WeakSet;static async loadPhysics(e){return await St.init(),new St.World(e)}constructor(e,t=60){this.world=e,this.fixedTimestep=1/t,e&&(this.world.integrationParameters.dt=this.fixedTimestep)}addEntity(e){this.addEntityDirect(e)}setForRemoval(e){e.physicsAttached&&this._removalMap.set(e.uuid,e)}destroyEntity(e){this.destroyEntityDirect(e)}setup(){}update(e){this.updateDirect(e)}addEntityDirect(e){let t=this.world.createRigidBody(e.bodyDesc);e.body=t,e.physicsAttached=!0,e.body.userData={uuid:e.uuid,ref:e},yt(t),this.patchDirectBodyPoseTracking(t),this.world.gravity.x===0&&this.world.gravity.y===0&&this.world.gravity.z===0&&(e.body.lockTranslations(!0,!0),e.body.lockRotations(!0,!0));let i=this.world.createCollider(e.colliderDesc,e.body);if(e.collider=i,e.colliders=[i],e.colliderDescs?.length>1)for(let r=1;r<e.colliderDescs.length;r++){let s=this.world.createCollider(e.colliderDescs[r],e.body);e.colliders.push(s)}(e.controlledRotation||e instanceof H)&&e.body.lockRotations(!0,!0),e.useCharacterController&&(e.characterController=this.world.createCharacterController(.01),e.characterController.setMaxSlopeClimbAngle(45*Math.PI/180),e.characterController.setMinSlopeSlideAngle(30*Math.PI/180),e.characterController.enableSnapToGround(.01),e.characterController.setSlideEnabled(!0),e.characterController.setApplyImpulsesToDynamicBodies(!0),e.characterController.setCharacterMass(1)),this.collisionMap.set(e.uuid,e)}destroyEntityDirect(e){if(e.characterController){try{e.characterController.free()}catch{}e.characterController=null}if(e.colliders?.length)for(let t of e.colliders)try{this.world.removeCollider(t,!0)}catch{}else if(e.collider)try{this.world.removeCollider(e.collider,!0)}catch{}if(e.body){try{this.world.removeRigidBody(e.body)}catch{}this.removeEntityFromTracking(e.uuid)}this.clearEntityPhysicsState(e)}updateDirect(e){let{delta:t}=e;if(!this.world)return;this.currentCollisionTimeMs+=t*1e3,this.processPendingRemovals(),this.accumulator+=t;let i=this.fixedTimestep*a.MAX_STEPS_PER_FRAME;for(this.accumulator=Math.min(this.accumulator,i);this.accumulator>=this.fixedTimestep;)this.captureDirectBodyPreviousPoses(),this.world.step(),this.captureDirectBodyCurrentPoses(),this.accumulator-=this.fixedTimestep;this.processCollisionPairs(this.collectCollisionPairsFromWorld(),t,this.currentCollisionTimeMs),this.interpolationAlpha=this.accumulator/this.fixedTimestep}captureDirectBodyPreviousPoses(){for(let[,e]of this.collisionMap){let t=e.body;t&&bt(t)}}captureDirectBodyCurrentPoses(){for(let[,e]of this.collisionMap){let t=e.body;t&&vt(t)}}patchDirectBodyPoseTracking(e){if(this.trackedDirectBodies.has(e))return;let t=e,i=e.setTranslation.bind(e),r=e.setRotation.bind(e);t.setTranslation=(s,n)=>{i(s,n),V(e)},t.setRotation=(s,n)=>{r(s,n),V(e)},this.trackedDirectBodies.add(e)}updatePostCollisionBehaviors(e){let t=this.collisionBehaviorMap;for(let[i,r]of t){let s=r;if(!Re(s))continue;s.handlePostCollision({entity:s,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)}collectCollisionPairsFromWorld(){let e=[];if(!this.world)return e;for(let[,t]of this.collisionMap){let i=t,r=i.body;if(!r)continue;let s=r.collider(0);s&&(this.world.contactsWith(s,n=>{let o=n.parent()?.userData?.uuid;o&&e.push({uuidA:i.uuid,uuidB:o,contactType:"contact"})}),this.world.intersectionsWith(s,n=>{let o=n.parent()?.userData?.uuid;o&&e.push({uuidA:i.uuid,uuidB:o,contactType:"intersection"})}))}return e}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,i=this.currentCollisionTimeMs){let r=di(e);for(let[s,n]of r){let l=this.collisionMap.get(n.uuidA),o=this.collisionMap.get(n.uuidB);this.activeCollisionPairs.has(s)||this.dispatchCollisionPhase(n,"enter",i),(this.entityHasCollisionPhaseListener(l,"stay")||this.entityHasCollisionPhaseListener(o,"stay"))&&this.dispatchCollisionPhase(n,"stay",i),n.hasIntersection&&this.dispatchIntersectionDelegates(n,t)}this.updatePostCollisionBehaviors(t),this.activeCollisionPairs=r}dispatchCollisionPhase(e,t,i){let r={phase:t,nowMs:i},s=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);s&&n&&s._collision(n,fe.globals,r);let l=this.collisionMap.get(e.uuidA),o=this.collisionMap.get(e.uuidB);l&&o&&o._collision(l,fe.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&Re(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let s=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);s&&n&&Re(n)&&(n.handleIntersectionEvent({entity:n,other:s,delta:t}),this.collisionBehaviorMap.set(n.uuid,n))}destroy(){try{for(let[,e]of this.collisionMap)try{this.destroyEntityDirect(e)}catch{}try{this.world?.free()}catch{}this.world=void 0,this.collisionMap.clear(),this.collisionBehaviorMap.clear(),this._removalMap.clear(),this.activeCollisionPairs.clear()}catch{}}clearEntityPhysicsState(e){e.physicsAttached=!1,e.body=null,e.collider=void 0,e.colliders=[],e.characterController=null}};import{Scene as ui,Color as Pt,AmbientLight as mi,DirectionalLight as hi,Vector3 as re,GridHelper as pi,BoxGeometry as gi,Mesh as fi,BackSide as yi,Texture as bi,SRGBColorSpace as vi}from"three";import{MeshBasicNodeMaterial as Ci}from"three/webgpu";var ae=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;skyboxMaterial=null;skyboxMesh=null;constructor(e,t,i){let r=new ui,n=i.backgroundColor instanceof Pt?i.backgroundColor:new Pt(i.backgroundColor);r.background=n,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader,t):i.backgroundImage&&R.loadTexture(i.backgroundImage,{colorSpace:vi}).then(l=>{r.background=l}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),u.enabled&&this.debugScene()}setupBackgroundShader(e,t,i){if(!Ie(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;let r=new Ci;r.colorNode=t.colorNode,t.transparent&&(r.transparent=!0),r.side=yi,r.depthWrite=!1,r.depthTest=!1,this.skyboxMaterial=r;let s=i?.camera?.far??1e3,n=Math.max(10,s*.9),l=new gi(1,1,1),o=new fi(l,this.skyboxMaterial);o.scale.setScalar(n),o.frustumCulled=!1,o.renderOrder=-1e3,this.skyboxMesh=o,e.add(o)}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.skyboxMaterial&&this.skyboxMaterial.dispose(),this.skyboxMesh&&(this.skyboxMesh.geometry.dispose(),this.skyboxMesh=null),this.scene&&(this.scene.background instanceof bi&&(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 mi(16777215,1);e.add(t);let i=new hi(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 re(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){let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Si(e);i&&i.attachToScene(this.scene);let r=e.options.position??new re(0,0,0);if(e.physicsAttached&&e.body)try{let s=e.body.translation();r=new re(s.x,s.y,s.z)}catch{r=e.options.position??new re(0,0,0)}this.add(t,r)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new pi(1e3,100);this.scene.add(i)}updateSkybox(e){if(!this.skyboxMesh)return;let t=this.cameraManager?.primaryCamera?.camera??this.zylemCamera?.camera;t&&t.getWorldPosition(this.skyboxMesh.position)}};function Si(a){return a.constructor.type===Ze?a:null}var se=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 Pi}from"three";var wt=new Pi;function Dt(a){let e=a._childrenMap,t=a._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval)continue;let r=i.body,s=i.group??i.mesh,n=s?Ct(r,t?.interpolationAlpha??0):null;s&&n&&s.position.set(n.position.x,n.position.y,n.position.z),!i.controlledRotation&&s&&n&&(wt.set(n.rotation.x,n.rotation.y,n.rotation.z,n.rotation.w),s.setRotationFromQuaternion(wt))}}import{nanoid as Ii}from"nanoid";import{Ray as _i}from"@dimforge/rapier3d-compat";import{BufferAttribute as le,BufferGeometry as Mt,LineBasicMaterial as Lt,LineSegments as Tt,Raycaster as Ai,Vector2 as ki}from"three";import{subscribe as Bi}from"valtio/vanilla";import{subscribe as wi}from"valtio/vanilla";var ne=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),wi(u,t)}resolveTarget(e){let t=this.stage.entityDelegate.debugMap.get(e)||this.stage.world?.collisionMap.get(e)||null;return t?.group??t?.mesh??null??null}snapshot(){return{enabled:u.enabled,selected:u.selectedEntity?[u.selectedEntity.uuid]:[]}}};import{Box3 as Di,BoxGeometry as Et,Color as Ei,EdgesGeometry as xt,Group as xi,LineBasicMaterial as Ri,LineSegments as Mi,Mesh as Li,MeshBasicMaterial as Ti,Vector3 as Rt}from"three";var oe=class{scene;container;fillMesh;edgeLines;currentColor=new Ei(65280);bbox=new Di;size=new Rt;center=new Rt;constructor(e){this.scene=e;let t=new Et(1,1,1);this.fillMesh=new Li(t,new Ti({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new xt(t);this.edgeLines=new Mi(i,new Ri({color:this.currentColor,linewidth:1})),this.container=new xi,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 Et(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 xt(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 Oi=2293538,zi=16724787,ce=class{stage;options;mouseNdc=new ki(-2,-2);raycaster=new Ai;isMouseDown=!1;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;debugLines=null;runtimeDebugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.syncWithDebugState(),this.debugStateUnsubscribe=Bi(u,()=>{this.syncWithDebugState()})}syncWithDebugState(){u.enabled?this.activate():this.deactivate()}activate(){this.domListenersAttached||(this.attachDomListeners(),this.domListenersAttached=!0),this.stage.cameraRef&&!this.cameraDebugDelegate&&(this.cameraDebugDelegate=new ne(this.stage),this.stage.cameraRef.setDebugDelegate(this.cameraDebugDelegate))}deactivate(){this.disposeDebugVisuals(),this.stage.cameraRef&&this.stage.cameraRef.setDebugDelegate(null),this.cameraDebugDelegate=null}initDebugVisuals(){this.debugLines||!this.stage.scene||(this.debugLines=new Tt(new Mt,new Lt({vertexColors:!0})),this.stage.scene.scene.add(this.debugLines),this.debugLines.visible=!0,this.runtimeDebugLines=new Tt(new Mt,new Lt({vertexColors:!0})),this.runtimeDebugLines.visible=!0,this.stage.scene.scene.add(this.runtimeDebugLines),this.debugCursor=new oe(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.runtimeDebugLines&&this.stage.scene&&(this.stage.scene.scene.remove(this.runtimeDebugLines),this.runtimeDebugLines.geometry.dispose(),this.runtimeDebugLines.material.dispose(),this.runtimeDebugLines=null),this.debugCursor?.dispose(),this.debugCursor=null}update(){if(!u.enabled){this.debugLines&&this.disposeDebugVisuals();return}if(!this.stage.scene||!this.stage.world||!this.stage.cameraRef)return;this.debugLines||this.initDebugVisuals();let{world:e,cameraRef:t}=this.stage,i=e.world!=null;if(this.debugLines&&i){let{vertices:h,colors:f}=e.world.debugRender();this.debugLines.geometry.setAttribute("position",new le(h,3)),this.debugLines.geometry.setAttribute("color",new le(f,4))}if(this.runtimeDebugLines){let f=this.stage.runtimeAdapter?.getDebugRender?.()??null;f&&f.vertices.length>0?(this.runtimeDebugLines.geometry.setAttribute("position",new le(new Float32Array(f.vertices),3)),this.runtimeDebugLines.geometry.setAttribute("color",new le(new Float32Array(f.colors),4)),this.runtimeDebugLines.geometry.attributes.position.needsUpdate=!0,this.runtimeDebugLines.geometry.attributes.color.needsUpdate=!0,this.runtimeDebugLines.visible=!0):this.runtimeDebugLines.visible=!1}let r=ye(),s=r==="select"||r==="delete",n=null,l=null,o=null;if(i){this.raycaster.setFromCamera(this.mouseNdc,t.camera),l=this.raycaster.ray.origin.clone(),o=this.raycaster.ray.direction.clone().normalize();let h=new _i({x:l.x,y:l.y,z:l.z},{x:o.x,y:o.y,z:o.z});n=e.world.castRay(h,this.options.maxRayDistance,!0)}if(n&&s){let f=n.collider?._parent?.userData?.uuid;if(f){let Le=this.stage.entityDelegate.debugMap.get(f);Le&&Ae(Le)}else ke();this.isMouseDown&&l&&o&&this.handleActionOnHit(f??null,l,o,n.toi)}this.isMouseDown=!1;let c=_e();if(!c){this.debugCursor?.hide();return}let d=this.stage.entityDelegate.debugMap.get(`${c}`),m=d?.group??d?.mesh??null;if(!m){this.debugCursor?.hide();return}switch(r){case"select":this.debugCursor?.setColor(Oi);break;case"delete":this.debugCursor?.setColor(zi);break;default:this.debugCursor?.setColor(16777215);break}this.debugCursor?.updateFromObject(m)}dispose(){this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.deactivate(),this.domDisposeFns.forEach(e=>e()),this.domDisposeFns=[],this.domListenersAttached=!1}handleActionOnHit(e,t,i,r){switch(ye()){case"select":{if(e){let n=this.stage.entityDelegate.debugMap.get(e);n&&Te(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)),l=this.options.addEntityFactory({position:n});l&&Promise.resolve(l).then(o=>{o&&this.stage.entityDelegate.spawnEntity(o)}).catch(()=>{});break}default:break}}attachDomListeners(){let e=this.stage.cameraRef?.renderer.domElement??this.stage.scene?.zylemCamera.renderer.domElement;if(!e)return;let t=r=>{let s=e.getBoundingClientRect(),n=(r.clientX-s.left)/s.width*2-1,l=-((r.clientY-s.top)/s.height*2-1);this.mouseNdc.set(n,l)},i=()=>{this.isMouseDown=!0};e.addEventListener("mousemove",t),e.addEventListener("mousedown",i),this.domDisposeFns.push(()=>e.removeEventListener("mousemove",t)),this.domDisposeFns.push(()=>e.removeEventListener("mousedown",i))}};import{Vector2 as Fi}from"three";var de=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Fi(e,t);return new C(p.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new ee;if(e)return i.addCamera(e,e.name||"main"),i;let r=t.filter(s=>s!==void 0);if(r.length>0){for(let s of r){let n=s.cameraRef;i.addCamera(n,n.name||void 0)}for(let s=1;s<r.length;s++)i.addActiveCamera(r[s].cameraRef)}else{let s=this.createDefaultCamera();i.addCamera(s,"default")}return i}};var ue=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"?N.emit("stage:loading:start",t):e.type==="progress"?N.emit("stage:loading:progress",t):e.type==="complete"&&N.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 me=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){this.scene?.addEntityGroup(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),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}};var he=class a{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;instanceManager=null;camera=null;runtimeAdapter=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.instanceManager=e.instanceManager,this.camera=e.camera,this.runtimeAdapter=e.runtimeAdapter??null,this.wasmStage=e.wasmStage??null}async spawnEntity(e){if(!this.scene||!this.world)return;if(e instanceof F){e.create();for(let s of e.getChildren())s instanceof k&&await this.spawnEntity(s);e.nodeSetup({me:e,globals:S(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create(),i=this.runtimeAdapter?.ownsEntity(t)??!1,r=i&&(this.runtimeAdapter?.rendersEntity(t)??!1);this.wasmStage&&(t.wasmStageRef=this.wasmStage),this.registerBehaviorLinks(t),i||this.maybeAttachEntityPhysics(t);for(let s of e.getChildren())s instanceof k&&await this.spawnEntity(s);e.nodeSetup({me:e,globals:S(),camera:this.camera}),i&&this.runtimeAdapter?.registerEntity(t),r||this.scene.addEntityGroup(t),i||this.tryRegisterInstance(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t)}handleLateModelReady(e){if(!(!this.world||!this.scene||!this.childrenMap.has(e.uuid))){if(this.runtimeAdapter?.ownsEntity(e)){this.runtimeAdapter.registerEntity(e),this.runtimeAdapter.rendersEntity(e)||this.scene.addEntityGroup(e);return}this.maybeAttachEntityPhysics(e),this.tryRegisterInstance(e)}}tryRegisterInstance(e){if(!this.instanceManager||e.isInstanced||e.options?.batched!==!0||!e.mesh?.geometry||!e.materials?.length)return;let i=e.mesh.geometry,r=e.materials[0],s=G.generateEntityBatchKey(e),n=this.instanceManager.register(e,i,r,s);n>=0&&(e.batchKey=s,e.instanceId=n,e.isInstanced=!0,e.mesh&&(e.mesh.visible=!1))}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof H){if(e.needsDeferredModelCollision())return;e.synchronizeRuntimeCollider()}this.world.addEntity(e)}}addEntityToStage(e){this.childrenMap.set(e.uuid,e),u.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.isInstanced&&this.instanceManager&&this.instanceManager.unregister(r),this.runtimeAdapter?.unregisterEntity(r),this.runtimeAdapter?.ownsEntity(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 Fe?{...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(w(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();w(i)?this.handleEntityImmediatelyOrQueue(i):z(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}z(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)}*entityLoadGenerator(){let e=this.children.length+this.pendingEntities.length+this.pendingPromises.length,t=0;for(let i of this.children)this.spawnEntity(i),t++,yield{current:t,total:e,name:i.name||"unknown"};if(this.pendingEntities.length&&(this.enqueue(...this.pendingEntities),t+=this.pendingEntities.length,this.pendingEntities=[],yield{current:t,total:e,name:"pending entities"}),this.pendingPromises.length){for(let i of this.pendingPromises)i.then(r=>{this.spawnEntity(r)}).catch(r=>console.error("Failed to resolve pending stage entity",r));t+=this.pendingPromises.length,this.pendingPromises=[],yield{current:t,total:e,name:"async entities"}}}yieldToEventLoop(){return new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>e(),t.port2.postMessage(void 0)})}async runEntityLoadGenerator(){let e=this.entityLoadGenerator(),t=0,i=5;for(let r of e)this.loadingDelegate.emitProgress(`Loaded ${r.name}`,r.current,r.total),++t%i===0&&await this.yieldToEventLoop();t%i!==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)??a.EMPTY_BEHAVIOR_LINKS,createEntity:be,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{}Q(e)}),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[],this._isLoaded=!1,this.scene=null,this.world=null,this.instanceManager=null,this.camera=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 s=r.descriptor.key,n={entity:e,ref:r};i.push(n);let l=this.behaviorEntityIndex.get(s);l||(l=new Set,this.behaviorEntityIndex.set(s,l)),l.add(n);let o=this.behaviorSystemByKey.get(s);if(!o&&!this.registeredSystemKeys.has(s)){let c=r.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:d=>this.behaviorEntityIndex.get(d)??a.EMPTY_BEHAVIOR_LINKS,createEntity:be,getGlobals:S});o=c,this.behaviorSystems.push(c),this.behaviorSystemByKey.set(s,c),this.registeredSystemKeys.add(s)}o?.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 s=this.behaviorEntityIndex.get(r);s&&(this.behaviorSystemByKey.get(r)?.detach?.(i),s.delete(i),s.size===0&&this.behaviorEntityIndex.delete(r))}this.behaviorLinksByUuid.delete(e.uuid)}}};var Zi="Stage",ge=class extends se{type=Zi;state={...Ve};gravity;world;scene;instanceManager=null;wasmStage=null;debugDelegate=null;uuid;wrapperRef=null;camera;cameras=[];cameraRef=null;cameraManagerRef=null;rendererManager=null;runtimeAdapter=null;cameraDelegate;loadingDelegate;entityModelDelegate;childUpdateParams={};entityDelegate;constructor(e=[]){super(),this.world=null,this.scene=null,this.uuid=Ii(),this.cameraDelegate=new de(this),this.loadingDelegate=new ue,this.entityModelDelegate=new me,this.entityDelegate=new he(this.loadingDelegate,this.entityModelDelegate);let t=mt(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,runtimeAdapter:t.config.runtimeAdapter,runtimeDebugBinding:t.config.runtimeDebugBinding,defaultLighting:t.config.defaultLighting,wasmRuntime:t.config.wasmRuntime,entities:[]},this.gravity=t.config.gravity??new pe(0,0,0),this.runtimeAdapter=t.config.runtimeAdapter??null,this.runtimeAdapter&&!this.state.runtimeDebugBinding&&(this.state.runtimeDebugBinding=Ue())}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof _t?e:new _t(e);We(i),Ne(t),He(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 ae(e,r,this.state);let s=this.gravity??new pe(0,0,0),n=await W.loadPhysics(s);if(this.world=new W(n,this.state.physicsRate),this.state.wasmRuntime&&(this.wasmStage=await this.loadWasmStage(this.state.wasmRuntime)),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.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 l=this.resolveRenderer(r);await R.configureGLTFRuntime({renderer:l,...ie(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,o=>this.entityDelegate.handleLateModelReady(o)),this.instanceManager=new G,this.instanceManager.setScene(this.scene.scene),this.entityDelegate.attach({scene:this.scene,world:this.world,instanceManager:this.instanceManager,camera:r,runtimeAdapter:this.runtimeAdapter,wasmStage:this.wasmStage}),this.loadingDelegate.emitStart(),await this.entityDelegate.runEntityLoadGenerator(),this.entityDelegate.isLoaded=!0,this.runtimeAdapter&&await this.runtimeAdapter.init(this.runtimeContext()),this.loadingDelegate.emitComplete()}hasSetup=!1;_setup(e){if(!this.hasSetup){if(!this.scene||!this.world){this.logMissingEntities();return}this.debugDelegate=new ce(this),this.hasSetup=!0}}_update(e){let{delta:t}=e;if(!this.scene||!this.world){this.logMissingEntities();return}this.world.update(e);for(let i of this.entityDelegate.behaviorSystems)i.update(void 0,t);for(let i of this.entityDelegate.childrenMap.values()){let r=this.childUpdateParams;r.delta=e.delta,r.inputs=e.inputs,r.globals=e.globals,r.camera=e.camera,r.stage=e.stage,r.game=e.game,r.me=i,i.nodeUpdate(r);let s=i;s.transformStore&&je(s,s.transformStore),i.markedForRemoval&&this.entityDelegate.removeEntityByUuid(i.uuid)}Dt({_childrenMap:this.entityDelegate.childrenMap,_world:this.world}),this.wasmStage&&this.wasmStage.step(t),this.runtimeAdapter&&this.runtimeAdapter.step({...this.runtimeContext(),delta:t,inputs:e.inputs}),this.instanceManager?.update(),this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t),this.scene.update({delta:t}),this.scene.updateSkybox(t)}outOfLoop(){this.debugUpdate()}debugUpdate(){u.enabled&&this.debugDelegate?.update()}_destroy(e){this.runtimeAdapter?.destroy(this.scene&&this.world?this.runtimeContext():null),this.runtimeAdapter=null,this.wasmStage&&(this.wasmStage.dispose(),this.wasmStage=null),this.entityDelegate.destroyAll(),this.world?.destroy(),this.scene?.destroy(),this.debugDelegate?.dispose(),this.debugDelegate=null,this.entityModelDelegate.dispose(),this.instanceManager?.dispose(),this.instanceManager=null,this.rendererManager&&this.rendererManager.stopRenderLoop(),this.world=null,this.scene=null,this.cameraRef=null,this.cameraManagerRef=null,Ge(),Q(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")}runtimeContext(){return{scene:this.scene,world:this.world,camera:this.cameraRef,debug:this.state.runtimeDebugBinding}}async loadWasmStage(e){let t=typeof e.source=="function"?await e.source():e.source,i=e.options??{},r=i.initialCapacity??256,s=this.gravity instanceof pe?this.gravity:new pe(this.gravity?.x??0,this.gravity?.y??0,this.gravity?.z??0),n=i.gravity??[s.x,s.y,s.z];if(t instanceof ArrayBuffer)return ve(t,{initialCapacity:r,gravity:n});let l=await fetch(t);if(!l.ok)throw new Error(`Failed to fetch wasm-stage runtime: ${l.status} ${l.statusText}`);let o=await l.arrayBuffer();return ve(o,{initialCapacity:r,gravity:n})}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 Vi}from"valtio/vanilla";import{Vector3 as Wi}from"three";var Ni={backgroundColor:U,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new Wi(0,0,0),variables:{}},x=Vi({...Ni});function At(a){let e=Hi(),t={};return typeof a[0]=="object"&&(t=a.shift()??{}),[{...e,...t},...a]}function Hi(){return{backgroundColor:x.backgroundColor,backgroundImage:x.backgroundImage??null,inputs:x.inputs?{...x.inputs}:void 0,gravity:x.gravity,variables:x.variables?{...x.variables}:void 0}}var Me=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Oe;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];R.prepareGLTFRuntime(ie(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=Be(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){j.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new ge(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(n=>{this.wrappedStage.onLoading(n)}),this.pendingLoadingCallbacks=[];let s=t instanceof b?t.cameraRef:t;await this.wrappedStage.load(e,s,i),this.wrappedStage.onEntityAdded(n=>{let l=this.wrappedStage.buildEntityState(n);j.entities=[...j.entities,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 b?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof b?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof b?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 on(...a){let e=At(a);return new Me([...e])}export{Xi as a,K as b,p as c,D as d,Y as e,E as f,M as g,B as h,L as i,ee as j,b as k,ia as l,da as m,ai as n,Me as o,on as p};
@@ -0,0 +1 @@
1
+ function n(t){return{all:t=t||new Map,on:function(e,f){var i=t.get(e);i?i.push(f):t.set(e,[f])},off:function(e,f){var i=t.get(e);i&&(f?i.splice(i.indexOf(f)>>>0,1):t.set(e,[]))},emit:function(e,f){var i=t.get(e);i&&i.slice().map(function(c){c(f)}),(i=t.get("*"))&&i.slice().map(function(c){c(e,f)})}}}export{n as a};
@@ -0,0 +1,29 @@
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`
2
+ <svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
3
+ <circle cx="70" cy="70" r="62" fill="${t.baseFill}" stroke="${t.joystickStroke}" stroke-width="4" />
4
+ <circle cx="70" cy="70" r="42" fill="${t.joystickAccentFill}" stroke="${t.joystickInnerStroke}" stroke-width="2" />
5
+ <path d="M70 24 L78 40 L62 40 Z" fill="${t.joystickTabFill}" />
6
+ <path d="M116 70 L100 78 L100 62 Z" fill="${t.joystickTabFill}" />
7
+ <path d="M70 116 L62 100 L78 100 Z" fill="${t.joystickTabFill}" />
8
+ <path d="M24 70 L40 62 L40 78 Z" fill="${t.joystickTabFill}" />
9
+ </svg>
10
+ `}function a(e){let t=l(e);return`
11
+ <svg viewBox="0 0 64 64" width="100%" height="100%" aria-hidden="true">
12
+ <circle cx="32" cy="32" r="28" fill="${t.thumbFill}" stroke="${t.thumbStroke}" stroke-width="3.5" />
13
+ <circle cx="32" cy="32" r="15" fill="${t.thumbInnerFill}" stroke="${t.thumbStroke}" stroke-width="1.5" />
14
+ </svg>
15
+ `}function g(e,t={}){let o=l(t.theme),n=t.accent??o.defaultButtonAccent,i=B(e),u=i.length>2?24:34;return`
16
+ <svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true">
17
+ <circle cx="50" cy="50" r="45" fill="${o.baseFill}" stroke="${n}" stroke-width="4.5" />
18
+ <circle cx="50" cy="50" r="33" fill="${n}" opacity="0.18" />
19
+ <text
20
+ x="50"
21
+ y="60"
22
+ text-anchor="middle"
23
+ font-family="ui-sans-serif, system-ui, sans-serif"
24
+ font-size="${u}"
25
+ font-weight="700"
26
+ fill="${n}"
27
+ >${i}</text>
28
+ </svg>
29
+ `}function B(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var S=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"];function C(e="p1",t={}){let o=l(t.theme),n=V(o,t),i=t.override?A(n,t.override):n;return y(e,i)}function V(e,t){return{enabled:t.enabled??"auto",joysticks:j(e,t.joysticks??"left"),buttons:x(e,t)}}function j(e,t){if(t==="none")return!1;let o={svg:{base:h(e),thumb:a(e)}},n={};return t==="left"||t==="both"?n.left={...o}:n.left=!1,t==="right"||t==="both"?n.right={...o}:n.right=!1,n}function x(e,t){let o=t.buttons??["A","B"],n=new Set(o),i=t.buttonAccents,u=t.buttonLabels,c={};for(let s of S){if(!n.has(s)){c[s]=!1;continue}let T=u?.[s]??s,p=f(e,s,i?.[s]),d={label:T,svg:g(T,{accent:p,theme:e})};c[s]=d}return c}function A(e,t){let o={...e,...t};(e.style||t.style)&&(o.style={...e.style,...t.style});let n=F(e.joysticks,t.joysticks);n!==void 0?o.joysticks=n:delete o.joysticks;let i=v(e.buttons,t.buttons);return i!==void 0?o.buttons=i:delete o.buttons,o}function F(e,t){if(t===void 0)return e;if(t===!1)return!1;if(!e)return t;let o={},n=k(e.left,t.left);n!==void 0&&(o.left=n);let i=k(e.right,t.right);return i!==void 0&&(o.right=i),o}function k(e,t){if(t===void 0)return e;if(t===!1)return!1;if(!e)return t;let o={...e,...t};return(e.style||t.style)&&(o.style={...e.style,...t.style}),(e.position||t.position)&&(o.position={...e.position,...t.position}),(e.svg||t.svg)&&(o.svg={...e.svg,...t.svg}),o}function v(e,t){if(t===void 0)return e;if(t===!1)return!1;if(!e)return t;let o={...e};for(let[n,i]of Object.entries(t)){if(i===void 0)continue;let u=o[n];if(i===!1||!u){o[n]=i;continue}let c={...u,...i};(u.style||i.style)&&(c.style={...u.style,...i.style}),(u.position||i.position)&&(c.position={...u.position,...i.position}),o[n]=c}return o}export{m as a,l as b,f as c,h as d,a as e,g as f,C as g};
@@ -0,0 +1 @@
1
+ import{a as i,b as p}from"./chunk-4QLJUQSJ.js";import{c as s,d as c}from"./chunk-G2IIMSUH.js";import{Color as m,Vector3 as y}from"three";import{proxy as v,subscribe as S}from"valtio/vanilla";import{Color as k}from"three";import{Vector3 as b}from"@dimforge/rapier3d-compat";var d=new k("#0333EC");var E=new b(s.x,s.y,s.z),I=new b(c.x,c.y,c.z);var P={backgroundColor:d,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:[]},u=v({backgroundColor:new m(m.NAMES.cornflowerblue),backgroundImage:null,inputs:{p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},variables:{},gravity:new y(0,0,0),entities:[]}),Z=e=>{u.backgroundColor=e},A=e=>{u.backgroundImage=e};var O=e=>{u.variables={...e}},G=()=>{u.variables={}};var l=new Map;function g(e){let t=l.get(e);return t||(t=v({}),l.set(e,t)),t}function M(e,t,o){let n=g(e);p(n,t,o)}function z(e,t,o){let n=g(e),a=i(n,t);return a===void 0?(p(n,t,o),o):a}function N(e,t){let o=l.get(e);if(o)return i(o,t)}function _(e,t,o){let n=g(e),a=i(n,t);return S(n,()=>{let r=i(n,t);r!==a&&(a=r,o(r))})}function D(e,t,o){let n=g(e),a=t.map(r=>i(n,r));return S(n,()=>{let r=t.map(f=>i(n,f));r.some((f,x)=>f!==a[x])&&(a=r,o(r))})}function K(e){l.delete(e)}export{d as a,P as b,u as c,Z as d,A as e,O as f,G as g,M as h,z as i,N as j,_ as k,D as l,K as m};
@@ -0,0 +1 @@
1
+ import{Euler as d,Vector3 as E,MathUtils as m,Quaternion as c}from"three";import{createTransformStore as v}from"@zylem/behaviors/core";function s(o){!o.group||!o.transformStore||o.group.setRotationFromQuaternion(new c(o.transformStore.rotation.x,o.transformStore.rotation.y,o.transformStore.rotation.z,o.transformStore.rotation.w))}function p(o,r){if(!o.body)return;let t=Math.atan2(-r.x,r.z);l(o,t)}function l(o,r){S(o,new E(0,-r,0))}function S(o,r){if(!o.transformStore)return;let t=new c().setFromEuler(new d(r.x,r.y,r.z));o.transformStore.rotation.w=t.w,o.transformStore.rotation.x=t.x,o.transformStore.rotation.y=t.y,o.transformStore.rotation.z=t.z,o.transformStore.dirty.rotation=!0,s(o)}function z(o,r){if(!o.transformStore)return;let t=r/2,n=Math.cos(t),a=Math.sin(t),e=o.transformStore.rotation,i=e.w*n-e.y*a,u=e.x*n+e.z*a,f=e.y*n+e.w*a,b=e.z*n-e.x*a;o.transformStore.rotation.w=i,o.transformStore.rotation.x=u,o.transformStore.rotation.y=f,o.transformStore.rotation.z=b,o.transformStore.dirty.rotation=!0,s(o)}function h(o,r){if(!o.transformStore)return;let t=r/2,n=Math.cos(t),a=Math.sin(t),e=o.transformStore.rotation,i=e.w*n-e.x*a,u=e.x*n+e.w*a,f=e.y*n+e.z*a,b=e.z*n-e.y*a;o.transformStore.rotation.w=i,o.transformStore.rotation.x=u,o.transformStore.rotation.y=f,o.transformStore.rotation.z=b,o.transformStore.dirty.rotation=!0,s(o)}function D(o,r){if(!o.transformStore)return;let t=r/2,n=Math.cos(t),a=Math.sin(t),e=o.transformStore.rotation,i=e.w*n-e.z*a,u=e.x*n-e.y*a,f=e.y*n+e.x*a,b=e.z*n+e.w*a;o.transformStore.rotation.w=i,o.transformStore.rotation.x=u,o.transformStore.rotation.y=f,o.transformStore.rotation.z=b,o.transformStore.dirty.rotation=!0,o._rotation2DAngle=(o._rotation2DAngle??0)+r,s(o)}function R(o,r){if(!o.transformStore)return;let t=r/2,n=Math.cos(t),a=Math.sin(t);o.transformStore.rotation.w=n,o.transformStore.rotation.x=0,o.transformStore.rotation.y=a,o.transformStore.rotation.z=0,o.transformStore.dirty.rotation=!0,s(o)}function Y(o,r){o.body&&R(o,m.degToRad(r))}function x(o,r){if(!o.transformStore)return;let t=r/2,n=Math.cos(t),a=Math.sin(t);o.transformStore.rotation.w=n,o.transformStore.rotation.x=a,o.transformStore.rotation.y=0,o.transformStore.rotation.z=0,o.transformStore.dirty.rotation=!0,s(o)}function M(o,r){o.body&&x(o,m.degToRad(r))}function w(o,r){if(!o.transformStore)return;let t=r/2,n=Math.cos(t),a=Math.sin(t);o.transformStore.rotation.w=n,o.transformStore.rotation.x=0,o.transformStore.rotation.y=0,o.transformStore.rotation.z=a,o.transformStore.dirty.rotation=!0,o._rotation2DAngle=r,s(o)}function A(o,r){o.body&&w(o,m.degToRad(r))}function g(o,r,t,n){if(!o.transformStore)return;let a=new c().setFromEuler(new d(r,t,n));o.transformStore.rotation.w=a.w,o.transformStore.rotation.x=a.x,o.transformStore.rotation.y=a.y,o.transformStore.rotation.z=a.z,o.transformStore.dirty.rotation=!0,o._rotation2DAngle=n,s(o)}function T(o,r,t,n){o.body&&g(o,m.degToRad(r),m.degToRad(t),m.degToRad(n))}function X(o){return o.body?o.body.rotation():null}function V(o){let r=o;return r.transformStore||(r.transformStore=v()),r.rotateInDirection=t=>p(o,t),r.rotateYEuler=t=>l(o,t),r.rotateEuler=t=>S(o,t),r.rotateX=t=>h(o,t),r.rotateY=t=>z(o,t),r.rotateZ=t=>D(o,t),r.setRotationY=t=>R(o,t),r.setRotationX=t=>x(o,t),r.setRotationZ=t=>w(o,t),r.setRotationDegreesY=t=>Y(o,t),r.setRotationDegreesX=t=>M(o,t),r.setRotationDegreesZ=t=>A(o,t),r.setRotationDegrees=(t,n,a)=>T(o,t,n,a),r.setRotation=(t,n,a)=>g(o,t,n,a),r.getRotation=()=>X(o),r}export{p as a,l as b,S as c,z as d,h as e,D as f,R as g,Y as h,x as i,M as j,w as k,A as l,g as m,T as n,X as o,V as p};
@@ -0,0 +1 @@
1
+ import{a as n}from"./chunk-QXVH6POE.js";var i=class{emitter;unsubscribes=[];constructor(){this.emitter=n()}dispatch(e,t){this.emitter.emit(e,t)}listen(e,t){this.emitter.on(e,t);let s=()=>this.emitter.off(e,t);return this.unsubscribes.push(s),s}listenAll(e){this.emitter.on("*",e);let t=()=>this.emitter.off("*",e);return this.unsubscribes.push(t),t}dispose(){this.unsubscribes.forEach(e=>e()),this.unsubscribes=[],this.emitter.all.clear()}};var a=n();export{i as a,a as b};
@@ -0,0 +1 @@
1
+ function s(r){let n=Object.keys(r).sort().reduce((t,e)=>(t[e]=r[e],t),{});return JSON.stringify(n)}function i(r){let n=0;for(let t=0;t<r.length;t++)n=Math.imul(31,n)+r.charCodeAt(t)|0;return n.toString(36)}export{s as a,i as b};
package/dist/core.d.ts CHANGED
@@ -1,16 +1,209 @@
1
- export { V as Vect3, c as createGame, v as vessel } from './core-DAkskq6Y.js';
2
- export { Z as ZylemGameConfig } from './stage-types-BFsm3qsZ.js';
3
- export { g as globalChange, a as globalChanges, v as variableChange, b as variableChanges } from './global-change-Dc8uCKi2.js';
4
- import './entity-BpbZqg19.js';
5
- import 'three';
1
+ import { S as Stage, a as StageStateInterface, C as CameraWrapper } from './game-Cuj5gy7U.js';
2
+ export { A as AspectRatio, r as AspectRatioValue, l as CameraOptions, D as DeviceProfile, q as FirstPersonOptions, m as FirstPersonPerspective, p as Fixed2DOptions, F as Fixed2DPerspective, G as Game, d as GameConfigLike, e as GameDeviceConfig, b as GameLoadingEvent, P as PerspectiveOptions, R as ResolutionInput, f as ResolveGameConfigRuntime, w as RetroPreset, x as RetroPresetKey, y as RetroResolution, i as StageConfigLike, j as StageOptions, o as ThirdPersonOptions, T as ThirdPersonPerspective, k as createCamera, c as createGame, n as createPerspective, h as createStage, g as gameConfig, t as getDisplayAspect, u as getPresetResolution, v as parseResolution, s as stageConfig } from './game-Cuj5gy7U.js';
3
+ export { G as GameInputConfig, b as GameInputPlayerConfig, K as KeyboardMapping, M as MouseConfig, c as MouseMapping, d as VirtualTouchButtonConfig, a as VirtualTouchButtonSlot, e as VirtualTouchButtonsConfig, V as VirtualTouchConfig, f as VirtualTouchJoystickConfig, g as VirtualTouchJoysticksConfig, h as VirtualTouchPosition, i as VirtualTouchStyle, Z as ZylemGameConfig } from './game-interfaces-tfpM5NBk.js';
4
+ import { Vector2 } from 'three';
5
+ import { G as GameEntity, M as BaseNode, Z as NodeInterface } from './entity-DNkYKfdp.js';
6
+ import * as _sinclair_typebox from '@sinclair/typebox';
7
+ import { Static } from '@sinclair/typebox';
8
+ import { C as CameraBehavior } from './zylem-stage-runtime-Cs-UDEVU.js';
9
+ export { l as CameraAction, j as CameraContext, f as CameraManager, k as CameraPerspective, n as CameraPipeline, m as CameraPipelineState, g as CameraPose, P as PerspectiveType, d as Perspectives, h as PoseDelta, e as RendererType, T as TransformLike, V as Viewport, Z as ZylemRenderer, i as isWebGPUSupported } from './zylem-stage-runtime-Cs-UDEVU.js';
10
+ import { a as Vec3Input, c as Vec3 } from './material-Wz83vTTp.js';
11
+ export { f as VEC2_ONE, g as VEC2_ZERO, h as VEC3_ONE, i as VEC3_ZERO, d as Vec2, e as Vec2Components, b as Vec2Input, V as Vec3Components, n as normalizeVec2, j as normalizeVec3, t as toRapierVector3, k as toThreeVector2, l as toThreeVector3 } from './material-Wz83vTTp.js';
12
+ import { S as StageEntity } from './world-C9zdyl5d.js';
13
+ import { S as SetupContext, L as LoadedContext, f as UpdateContext, D as DestroyContext, C as CleanupContext } from './base-node-life-cycle-CnJ-7zX-.js';
14
+ export { g as LoadingEvent } from './base-node-life-cycle-CnJ-7zX-.js';
6
15
  import '@dimforge/rapier3d-compat';
7
- import 'bitecs';
16
+ import '@zylem/behaviors/core';
17
+ import './entity-type-map-C94h2TDW.js';
18
+ import '@zylem/behaviors/particle-emitter';
19
+ import './events.js';
8
20
  import 'mitt';
9
- import './behavior-descriptor-BWNWmIjv.js';
10
- import './camera-B5e4c78l.js';
11
- import './entity-Bq_eNEDI.js';
21
+ import './default-controls-BGc61yYl.js';
12
22
  import 'three/webgpu';
13
- import 'three/examples/jsm/postprocessing/EffectComposer.js';
14
- import './world-Be5m1XC1.js';
15
- import './entity-types-DAu8sGJH.js';
16
- import './entities-DC9ce_vx.js';
23
+
24
+ interface EntitySpawner {
25
+ spawn: (stage: Stage, x: number, y: number) => Promise<GameEntity<any>>;
26
+ spawnRelative: (source: any, stage: Stage, offset?: Vector2) => Promise<any | void>;
27
+ }
28
+ declare function entitySpawner(factory: (x: number, y: number) => Promise<any> | GameEntity<any>): EntitySpawner;
29
+
30
+ declare const StageSchema: _sinclair_typebox.TObject<{
31
+ id: _sinclair_typebox.TString;
32
+ name: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
33
+ entities: _sinclair_typebox.TArray<_sinclair_typebox.TObject<{
34
+ id: _sinclair_typebox.TString;
35
+ type: _sinclair_typebox.TString;
36
+ position: _sinclair_typebox.TOptional<_sinclair_typebox.TTuple<[_sinclair_typebox.TNumber, _sinclair_typebox.TNumber]>>;
37
+ data: _sinclair_typebox.TOptional<_sinclair_typebox.TRecord<_sinclair_typebox.TString, _sinclair_typebox.TAny>>;
38
+ }>>;
39
+ assets: _sinclair_typebox.TOptional<_sinclair_typebox.TArray<_sinclair_typebox.TString>>;
40
+ }>;
41
+ type StageBlueprint = Static<typeof StageSchema>;
42
+
43
+ declare const stageState: {
44
+ previous: StageBlueprint | null;
45
+ current: StageBlueprint | null;
46
+ next: StageBlueprint | null;
47
+ isLoading: boolean;
48
+ };
49
+ declare const StageManager: {
50
+ staticRegistry: Map<string, {
51
+ name?: string | undefined;
52
+ assets?: string[] | undefined;
53
+ id: string;
54
+ entities: {
55
+ position?: [number, number] | undefined;
56
+ data?: {
57
+ [x: string]: any;
58
+ } | undefined;
59
+ id: string;
60
+ type: string;
61
+ }[];
62
+ }>;
63
+ registerStaticStage(id: string, blueprint: StageBlueprint): void;
64
+ loadStageData(stageId: string): Promise<StageBlueprint>;
65
+ transitionForward(nextStageId: string, loadStaticStage?: (id: string) => Promise<StageBlueprint>): Promise<void>;
66
+ /**
67
+ * Manually set the next stage to pre-load it.
68
+ */
69
+ preloadNext(stageId: string, loadStaticStage?: (id: string) => Promise<StageBlueprint>): Promise<void>;
70
+ };
71
+
72
+ /**
73
+ * Event name for stage state changes.
74
+ * Dispatched when the stage state proxy is updated.
75
+ */
76
+ declare const STAGE_STATE_CHANGE = "STAGE_STATE_CHANGE";
77
+ /**
78
+ * Event detail payload for STAGE_STATE_CHANGE events.
79
+ */
80
+ interface StageStateChangeEvent {
81
+ entities: StageStateInterface['entities'];
82
+ variables: StageStateInterface['variables'];
83
+ }
84
+ /**
85
+ * Initialize the stage state dispatcher.
86
+ * Subscribes to stageState changes and dispatches STAGE_STATE_CHANGE events to the window.
87
+ *
88
+ * @returns Unsubscribe function to stop dispatching events.
89
+ *
90
+ * @example
91
+ * // Start dispatching stage state changes
92
+ * const unsubscribe = initStageStateDispatcher();
93
+ *
94
+ * // Later, stop dispatching
95
+ * unsubscribe();
96
+ */
97
+ declare function initStageStateDispatcher(): () => void;
98
+ /**
99
+ * Manually dispatch the current stage state.
100
+ * Useful for initial sync when a listener is added.
101
+ */
102
+ declare function dispatchStageState(): void;
103
+
104
+ /**
105
+ * Options for the followTarget behavior.
106
+ */
107
+ interface FollowTargetOptions {
108
+ /** Key in CameraContext.targets to follow. Default 'primary'. */
109
+ targetKey?: string;
110
+ /** Position offset from the target. Default (0, 0, 0). */
111
+ offset?: Vec3Input;
112
+ /**
113
+ * Interpolation factor in 0..1, applied per 60Hz frame.
114
+ * 1 = instant snap, lower = smoother follow. The per-frame rate is scaled
115
+ * by dt so tracking speed is identical across refresh rates (60/120/144Hz).
116
+ * Default 0.1.
117
+ */
118
+ lerpFactor?: number;
119
+ }
120
+ /**
121
+ * A simple follow behavior that moves the camera pose toward a target's position + offset.
122
+ *
123
+ * This behavior modifies only the position (and lookAt) of the incoming pose,
124
+ * leaving rotation/fov/zoom to the perspective or other behaviors.
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * camera.addBehavior('follow', createFollowTarget({ targetKey: 'player', offset: new Vector3(0, 3, 8) }));
129
+ * ```
130
+ */
131
+ declare function createFollowTarget(options?: FollowTargetOptions): CameraBehavior;
132
+
133
+ /**
134
+ * Options for setCameraFeed.
135
+ */
136
+ interface CameraFeedOptions {
137
+ /** Render target width in pixels. Only used when the camera does not
138
+ * already have a render target. @default 512 */
139
+ width?: number;
140
+ /** Render target height in pixels. Only used when the camera does not
141
+ * already have a render target. @default 512 */
142
+ height?: number;
143
+ }
144
+ /**
145
+ * Display a camera's live feed on an entity's mesh surface.
146
+ *
147
+ * This is the primary user-facing function for "jumbotron", security-camera,
148
+ * or broadcast-style effects. It ensures the camera has an offscreen render
149
+ * target and replaces the entity's mesh material with one that shows the
150
+ * camera's rendered output.
151
+ *
152
+ * @param entity The entity whose mesh will display the camera feed.
153
+ * @param camera The camera whose view will be rendered to the texture.
154
+ * @param options Optional dimensions for the render target.
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * const feedCam = createCamera({
159
+ * perspective: Perspectives.ThirdPerson,
160
+ * position: new Vector3(0, 30, 60),
161
+ * target: new Vector3(0, 0, 0),
162
+ * renderToTexture: { width: 1024, height: 576 },
163
+ * });
164
+ *
165
+ * const screen = createBox({ size: { x: 16, y: 9, z: 0.2 } });
166
+ * screen.onSetup(({ me }) => {
167
+ * setCameraFeed(me, feedCam);
168
+ * });
169
+ * ```
170
+ */
171
+ declare function setCameraFeed(entity: StageEntity, camera: CameraWrapper, options?: CameraFeedOptions): void;
172
+
173
+ /**
174
+ * A Vessel is an empty container entity that holds child entities.
175
+ * It has no geometry, physics, or rendering of its own, but propagates
176
+ * lifecycle events to its children and provides a logical grouping mechanism.
177
+ *
178
+ * Child entities added to a Vessel will be individually spawned into the
179
+ * stage's physics world and render scene when the Vessel is spawned.
180
+ */
181
+ declare class Vessel extends BaseNode<{}, Vessel> {
182
+ static type: symbol;
183
+ protected _setup(_params: SetupContext<this>): void;
184
+ protected _loaded(_params: LoadedContext<this>): Promise<void>;
185
+ protected _update(_params: UpdateContext<this>): void;
186
+ protected _destroy(_params: DestroyContext<this>): void;
187
+ protected _cleanup(_params: CleanupContext<this>): void;
188
+ create(): this;
189
+ clone(): this;
190
+ /**
191
+ * Add one or more child entities to this vessel.
192
+ * Overrides parent to support multiple arguments.
193
+ * @returns this for chaining
194
+ */
195
+ add(...nodes: NodeInterface[]): this;
196
+ }
197
+ /**
198
+ * Create a vessel containing the given child entities.
199
+ * @param args Child BaseNode entities to add
200
+ * @returns A new Vessel with the children added
201
+ */
202
+ declare function vessel(...args: Array<BaseNode>): Vessel;
203
+
204
+ /**
205
+ * @deprecated Use Vec3 from ../vector instead.
206
+ */
207
+ type Vect3 = Vec3;
208
+
209
+ export { CameraBehavior, type CameraFeedOptions, CameraWrapper, type FollowTargetOptions, STAGE_STATE_CHANGE, SetupContext, type StageBlueprint, StageEntity, StageManager, type StageStateChangeEvent, UpdateContext, Vec3, Vec3Input, type Vect3, createFollowTarget, dispatchStageState, entitySpawner, initStageStateDispatcher, setCameraFeed, stageState, vessel };