@zylem/game-lib 0.8.7 → 0.8.9

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 (63) hide show
  1. package/dist/actions.d.ts +2 -2
  2. package/dist/actions.js +1 -1
  3. package/dist/api/game-lib.api.json +794 -175
  4. package/dist/api/game-lib.api.md +63 -11
  5. package/dist/api/game-lib.d.ts +180 -5
  6. package/dist/api/game-lib.typedoc.json +157334 -208944
  7. package/dist/audio.js +1 -1
  8. package/dist/behavior.js +1 -1
  9. package/dist/bridge.d.ts +31 -6
  10. package/dist/bridge.js +1 -1
  11. package/dist/catalog.d.ts +91 -3
  12. package/dist/catalog.js +1 -1
  13. package/dist/chunk-2HSR5XDQ.js +1 -0
  14. package/dist/{chunk-7NYP4YAG.js → chunk-6FGXC4T6.js} +1 -1
  15. package/dist/chunk-6XFXPIVB.js +1 -0
  16. package/dist/{chunk-YOVE25NW.js → chunk-7JSZEEAE.js} +1 -1
  17. package/dist/chunk-AXJTUVGC.js +24 -0
  18. package/dist/chunk-BWOZF5YK.js +1 -0
  19. package/dist/chunk-EYDC2PMO.js +1 -0
  20. package/dist/chunk-G3TBBZUI.js +1 -0
  21. package/dist/chunk-J6KD2G6F.js +1 -0
  22. package/dist/chunk-KP6DLLJO.js +1 -0
  23. package/dist/chunk-VUJXR5K5.js +1 -0
  24. package/dist/chunk-WOT6VMZA.js +1 -0
  25. package/dist/{chunk-BMRFDDMR.js → chunk-X7T7QRYP.js} +1 -1
  26. package/dist/chunk-YQS7CGXE.js +1 -0
  27. package/dist/{chunk-GHJQ2HKI.js → chunk-YVWDCZNT.js} +1 -1
  28. package/dist/core.d.ts +4 -4
  29. package/dist/core.js +1 -1
  30. package/dist/{debug-state-CpnNRUFh.d.ts → debug-state-Cg3f5FB6.d.ts} +1 -1
  31. package/dist/debug.d.ts +2 -2
  32. package/dist/debug.js +1 -1
  33. package/dist/{entity-XZNGBeca.d.ts → entity-XqvuWgPm.d.ts} +54 -0
  34. package/dist/{entity-type-map-CkkFMSrL.d.ts → entity-type-map-D6BeAdvg.d.ts} +1 -1
  35. package/dist/entity.d.ts +3 -3
  36. package/dist/entity.js +1 -1
  37. package/dist/events.js +1 -1
  38. package/dist/{game-BPOr7zTB.d.ts → game-DyKbOeck.d.ts} +74 -7
  39. package/dist/game-default-6YXFFZ2Q.js +1 -0
  40. package/dist/globals.js +1 -1
  41. package/dist/graphics.js +1 -1
  42. package/dist/input-ui.js +1 -1
  43. package/dist/input.js +1 -1
  44. package/dist/public.d.ts +6 -6
  45. package/dist/public.js +1 -1
  46. package/dist/runtime.js +1 -1
  47. package/dist/schema/entity.schema.json +24 -24
  48. package/dist/schema/game-config.schema.json +10 -10
  49. package/dist/schema/stage.schema.json +29 -29
  50. package/dist/schema.js +1 -1
  51. package/dist/web-components.d.ts +4 -4
  52. package/dist/web-components.js +1 -1
  53. package/package.json +21 -19
  54. package/dist/chunk-AE3CTVHY.js +0 -1
  55. package/dist/chunk-F5LROYZL.js +0 -24
  56. package/dist/chunk-HNCTOJP7.js +0 -1
  57. package/dist/chunk-IBJLPJLE.js +0 -1
  58. package/dist/chunk-MXO4VGDB.js +0 -1
  59. package/dist/chunk-QDQ4QMAI.js +0 -1
  60. package/dist/chunk-SAQA4SXW.js +0 -1
  61. package/dist/chunk-XK63E4SX.js +0 -1
  62. package/dist/chunk-ZTYNZ2N2.js +0 -1
  63. package/dist/game-default-7HCJJF5S.js +0 -1
@@ -0,0 +1 @@
1
+ import{b as St,c as Ht,f as Wt}from"./chunk-BCFFS3FP.js";import{c as te,j as re}from"./chunk-2HSR5XDQ.js";import{a as je,f as Tt,h as I}from"./chunk-G3TBBZUI.js";import{a as Et,c as He,d as We,e as Mt,f as ee,g as xt}from"./chunk-CBUQBP2U.js";import{b as Ze,d as u,e as vt,i as Ge,k as X,o as Ue,r as k,v as Ct,w as Ne,x as J}from"./chunk-EVMLNMGU.js";import{a as ae,b as Ft}from"./chunk-WBQ5TNRZ.js";import{b as ne,d as It}from"./chunk-YQS7CGXE.js";import{a as V,k as kt,l as Lt,m as Ot,n as Bt,o as O,p as At,q as Z,t as zt,u as qe}from"./chunk-KP6DLLJO.js";import{a as Ke,b as Rt,g as L,h as ie,i as _t}from"./chunk-6FGXC4T6.js";import{a as Pt,b as E}from"./chunk-AIQ6IVT5.js";import{a as se,b as Vt,c as oe,d as Zt,e as Gt,f as Ut,g as Nt,m as B}from"./chunk-D2PATZCC.js";import{c as $,d as Ve,j as g}from"./chunk-4QLJUQSJ.js";import{c as C,i as Dt,j as m}from"./chunk-7WRQ2UAN.js";import{a as jt}from"./chunk-BH53MBAZ.js";import{l as wt}from"./chunk-UG22Z42P.js";import{Vector2 as $t,RenderTarget as ji,HalfFloatType as Ki}from"three";import{WebGPURenderer as qi,RenderPipeline as Qi}from"three/webgpu";import{pass as Yi,renderOutput as Xt,screenCoordinate as $i,vec2 as Qe,vec4 as ii,fract as Jt,sin as ei,dot as ti,texture as Xi,uniform as Ji}from"three/tsl";import{setConsoleFunction as Hi,getConsoleFunction as Wi}from"three";var Kt="THREE.Abstract function.",qt=!1,Qt=!1;function Yt(){if(qt)return;qt=!0;let a=Wi();Hi((e,t,...i)=>{if(e==="warn"&&t===Kt){Qt||(Qt=!0,console.warn(`${Kt} (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],n=e==="log"?console.log:e==="error"?console.error:console.warn;r&&r.isStackTrace&&typeof r.getError=="function"?n(r.getError(t)):n(t,...i)})}var ri={x:0,y:0,width:1,height:1};async function zn(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var le=class{renderer;postProcessing=null;renderScale=1;screenResolution;_initialized=!1;_sceneRef=null;_lastAnimationTimestamp=null;_postEffects=[];_postSceneRef=null;_postCameraRef=null;_transition=null;constructor(e){this.screenResolution=e||new $t(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(Yt(),this.renderer=new qi({antialias:!0,alpha:!0}),await this.renderer.init(),this.renderer.setSize(this.screenResolution.x,this.screenResolution.y),this.renderer.shadowMap.enabled=!0,this._initialized=!0)}setScene(e){this._sceneRef=e}setupPostProcessing(e,t){this.disposePostProcessing(),this._postSceneRef=e,this._postCameraRef=t;let i=new Qi(this.renderer),r=Yi(e,t);this.renderScale!==1&&r.setResolutionScale(this.renderScale);let n=r;for(let l of this._postEffects)try{n=l(n,{scenePass:r,scene:e,camera:t})}catch(c){console.error("RendererManager: post-processing effect failed, skipping.",c)}i.outputColorTransform=!1;let s=Xt(n),o=this._transition;if(o)try{s=ii(o.resolved.shader({fromNode:o.fromNode,toNode:s,progress:o.progressUniform})),o.composed=!0}catch(l){console.error("RendererManager: stage transition shader failed, skipping.",l)}i.outputNode=s.add(tr()),this.postProcessing=i}get transitionActive(){return this._transition!==null}beginSnapshotTransition(e,t,i){this.finishTransition();let r=new $t;this.renderer.getDrawingBufferSize(r);let n=new ji(Math.max(1,r.x),Math.max(1,r.y),{type:Ki}),s=this.renderer.getRenderTarget();try{this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(n),this.renderer.render(t,i)}catch(o){console.error("RendererManager: failed to capture transition snapshot.",o)}finally{this.renderer.setRenderTarget(s)}this._transition={resolved:e,progressUniform:Ji(0),fromNode:Xt(Xi(n.texture)),elapsed:0,snapshotTarget:n,composed:!1}}finishTransition(){let e=this._transition;if(e){this._transition=null,e.progressUniform.value=1,this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef);try{e.resolved.onComplete?.()}catch(t){console.error("RendererManager: transition onComplete failed.",t)}this.releaseTransitionResources(e)}}cancelTransition(){let e=this._transition;if(e){this._transition=null;try{e.resolved.onComplete?.()}catch{}this.releaseTransitionResources(e)}}releaseTransitionResources(e){try{e.snapshotTarget?.dispose()}catch{}}advanceTransition(e){let t=this._transition;if(!t||!t.composed)return;t.elapsed+=e;let i=Math.min(t.elapsed/t.resolved.duration,1);t.progressUniform.value=t.resolved.easing(i),i>=1&&this.finishTransition()}setPostProcessingEffects(e){this._postEffects=[...e],this.postProcessing&&this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef)}setRenderScale(e){this.renderScale=Math.max(1,Number.isFinite(e)?e:1)}disposePostProcessing(){try{this.postProcessing?.dispose?.()}catch{}this.postProcessing=null}startRenderLoop(e){this._lastAnimationTimestamp=null,this.renderer.setAnimationLoop(t=>{let i=this._lastAnimationTimestamp===null?0:Math.max(0,(t-this._lastAnimationTimestamp)/1e3);this._lastAnimationTimestamp=t,this.advanceTransition(i),e(i)})}stopRenderLoop(){this._lastAnimationTimestamp=null;try{this.renderer.setAnimationLoop(null)}catch{}}renderCamera(e,t,i=!1){let r=t.viewport,n=this.screenResolution.x,s=this.screenResolution.y,o=Math.floor(r.x*n),l=Math.floor(r.y*s),c=Math.floor(r.width*n),d=Math.floor(r.height*s);this.renderer.setViewport(o,l,c,d),this.renderer.setScissor(o,l,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&&er(t[0].viewport);for(let r of t)this.renderCamera(e,r,i);this.renderer.setScissorTest(!1)}render(e,t){this.postProcessing?this.postProcessing.render():this.renderer.render(e,t)}resize(e,t){this.screenResolution.set(e,t),this.renderer.setSize(e,t,!1)}setPixelRatio(e){let t=Math.max(1,Number.isFinite(e)?e:1);this.renderer.setPixelRatio(t)}getDomElement(){return this.renderer.domElement}dispose(){this.stopRenderLoop(),this.cancelTransition(),this.disposePostProcessing();try{this.renderer.dispose()}catch{}this._sceneRef=null,this._postSceneRef=null,this._postCameraRef=null,this._postEffects=[],this._initialized=!1}};function er(a){return a.x===0&&a.y===0&&a.width===1&&a.height===1}function tr(){let a=$i.xy,e=Jt(ei(ti(a,Qe(12.9898,78.233))).mul(43758.5453)),t=Jt(ei(ti(a.add(Qe(13,7)),Qe(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return ii(i,i,i,0)}function G(a){return a?.category??"none"}function U(a){let e=G(a);return e==="environment"||e==="pack"}function T(a){return a.isInstanced===!0||a.isBundled===!0}import{BundleGroup as ir}from"three/webgpu";var ce=class{bundles=new Map;entityToBundle=new Map;scene=null;setScene(e){this.scene=e}register(e,t,i,r){if(e.isBundled)return!0;let n=e.mesh??e.group;if(!n)return!1;let s=this.getOrCreateBundle(r);return n.matrixAutoUpdate=!0,n.userData.zylemEntityUuid=e.uuid,n.parent&&n.parent.remove(n),s.add(n),s.needsUpdate=!0,e.isBundled=!0,e.bundleKey=r,this.entityToBundle.set(e.uuid,r),!0}unregister(e){let t=this.entityToBundle.get(e.uuid);if(!t)return;let i=this.bundles.get(t),r=e.mesh??e.group;i&&r&&(i.remove(r),i.needsUpdate=!0),e.isBundled=!1,e.bundleKey=null,this.entityToBundle.delete(e.uuid)}getStats(){return{bundleCount:this.bundles.size,entityCount:this.entityToBundle.size}}dispose(){for(let e of this.bundles.values())this.scene&&this.scene.remove(e);this.bundles.clear(),this.entityToBundle.clear()}getOrCreateBundle(e){let t=this.bundles.get(e);return t||(t=new ir,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as ni,Matrix4 as N,Vector3 as ai,Quaternion as rr}from"three";var H=class a{packs=new Map;entityToPack=new Map;scene=null;static DEFAULT_CAPACITY=128;static GROWTH_FACTOR=2;setScene(e){this.scene=e}static generatePackKey(e){let t={geo:`${e.geometryType}:${Ke(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Rt(Ke(t))}static generateEntityPackKey(e){let t=e.options;if(t.runtime?.packKeyOverride)return t.runtime.packKeyOverride;let i=e.constructor?.type?.description||"unknown",r=t.size||{x:1,y:1,z:1},n=t.material||{};return a.generatePackKey({geometryType:i,dimensions:{x:r.x,y:r.y,z:r.z},materialPath:n.path||null,shaderType:n.shader?"custom":"standard",colorHex:n.color?.getHex?.()||t.color?.getHex?.()||16777215})}register(e,t,i,r){let n=this.packs.get(r);n||(n=this.createPack(r,t,i));let s;return n.freeIndices.length>0?s=n.freeIndices.pop():(s=n.entities.length,s>=n.capacity&&this.growPack(n),n.entities.push(null)),n.entities[s]=e,n.entityMap.set(e.uuid,s),this.entityToPack.set(e.uuid,r),n.instancedMesh.count=Math.max(n.instancedMesh.count,s+1),n.activeIndices.push(s),n.dirtyIndices.add(s),s}unregister(e){let t=this.entityToPack.get(e.uuid);if(!t)return;let i=this.packs.get(t);if(!i)return;let r=i.entityMap.get(e.uuid);if(r===void 0)return;i.entities[r]=null,i.entityMap.delete(e.uuid),this.entityToPack.delete(e.uuid),i.freeIndices.push(r);let n=i.activeIndices.indexOf(r);if(n!==-1){let o=i.activeIndices.pop();n<i.activeIndices.length&&(i.activeIndices[n]=o)}i.dirtyIndices.delete(r);let s=new N;s.makeScale(0,0,0),i.instancedMesh.setMatrixAt(r,s),i.instancedMesh.instanceMatrix.needsUpdate=!0}markDirty(e){let t=this.entityToPack.get(e.uuid);if(!t)return;let i=this.packs.get(t);if(!i)return;let r=i.entityMap.get(e.uuid);r!==void 0&&i.dirtyIndices.add(r)}update(e=0){let t=new N,i=new ai,r=new rr,n=new ai(1,1,1);for(let s of this.packs.values()){if(s.activeIndices.length===0)continue;let o=!1;for(let l of s.activeIndices){let c=s.entities[l];if(!c)continue;if(kt(c)){t.makeScale(0,0,0),s.instancedMesh.setMatrixAt(l,t),o=!0;continue}let d=s.dirtyIndices.has(l),p=!!c.body;if(!(!d&&!p)){if(!d&&p){let v=c.body;if(typeof v.isRenderSleeping=="function"&&v.isRenderSleeping())continue}this.updateInstanceMatrix(s,l,t,i,r,n,e),o=!0}}s.dirtyIndices.clear(),o&&(s.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,n,s,o){let l=e.entities[t];if(l){if(l.body){let c=l.body;if(typeof c.writeRenderPose=="function")c.writeRenderPose(o,r,n);else{let d=ae(l.body,o);r.set(d.position.x,d.position.y,d.position.z),n.set(d.rotation.x,d.rotation.y,d.rotation.z,d.rotation.w)}i.compose(r,n,s)}else l.mesh?(l.mesh.updateMatrix(),i.copy(l.mesh.matrix)):l.group&&(l.group.updateMatrix(),i.copy(l.group.matrix));e.instancedMesh.setMatrixAt(t,i)}}getPackInfo(e){let t=this.entityToPack.get(e.uuid);if(!t)return null;let i=this.packs.get(t);if(!i)return null;let r=i.entityMap.get(e.uuid);return r===void 0?null:{packKey:t,instanceId:r}}getStats(){let e=0,t=[];for(let[i,r]of this.packs){let n=r.entityMap.size;e+=n,t.push({key:i,count:n,capacity:r.capacity})}return{packCount:this.packs.size,totalInstances:e,packs:t}}dispose(){for(let e of this.packs.values())this.scene&&this.scene.remove(e.instancedMesh),e.instancedMesh.dispose(),e.geometry.dispose();this.packs.clear(),this.entityToPack.clear()}createPack(e,t,i){let r=a.DEFAULT_CAPACITY,n=new ni(t,i,r);n.count=0,n.frustumCulled=!1;let s=new N().makeScale(0,0,0);for(let l=0;l<r;l++)n.setMatrixAt(l,s);n.instanceMatrix.needsUpdate=!0;let o={key:e,instancedMesh:n,geometry:t,material:i,entityMap:new Map,entities:[],freeIndices:[],activeIndices:[],dirtyIndices:new Set,capacity:r};return this.packs.set(e,o),this.scene&&this.scene.add(n),o}growPack(e){let t=e.capacity*a.GROWTH_FACTOR,i=new ni(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new N;for(let s=0;s<e.capacity;s++)e.instancedMesh.getMatrixAt(s,r),i.setMatrixAt(s,r);let n=new N().makeScale(0,0,0);for(let s=e.capacity;s<t;s++)i.setMatrixAt(s,n);i.instanceMatrix.needsUpdate=!0,this.scene&&(this.scene.remove(e.instancedMesh),this.scene.add(i)),e.instancedMesh.dispose(),e.instancedMesh=i,e.capacity=t}};var de=class{bundles=new ce;instances=new H;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=G(e.options);if(t==="none")return!1;if(e.isInstanced||e.isBundled)return!0;if(!e.mesh?.geometry||!e.materials?.length)return!1;let i=e.mesh.geometry,r=e.materials[0],n=H.generateEntityPackKey(e);if(t==="pack"){let s=this.instances.register(e,i,r,n);return s<0?!1:(e.packKey=n,e.instanceId=s,e.isInstanced=!0,e.mesh&&(e.mesh.visible=!1),!0)}return t==="environment"&&this.bundles.register(e,i,r,n)?(e.mesh&&(e.mesh.visible=!0),!0):!1}unregister(e){e.isInstanced&&(this.instances.unregister(e),e.isInstanced=!1,e.instanceId=-1,e.packKey=null),e.isBundled&&this.bundles.unregister(e)}update(e=0){this.instances.update(e)}dispose(){this.bundles.dispose(),this.instances.dispose()}};var ue=!1,S={},si=0,oi=0,W=null;function li(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ye(){return ue?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(ue=!0),ue)}function Jn(a){ue=a,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=a)}function $e(a){Ye()&&(W=a,oi=li())}function Xe(){if(!Ye()||W===null)return;let a=li()-oi;S[W]=(S[W]??0)+a,W=null}function ci(){if(!Ye()||(si++,si%60!==0))return;let a=Object.values(S).reduce((t,i)=>t+(i??0),0),e=Object.keys(S).sort((t,i)=>(S[i]??0)-(S[t]??0)).map(t=>{let i=S[t]??0,r=a>0?(i/a*100).toFixed(1):"0.0";return`${t}=${i.toFixed(2)}ms (${r}%)`});console.info(`[ZylemStage profile] avg over 60 frames (${a.toFixed(2)}ms/frame): ${e.join(", ")}`);for(let t of Object.keys(S))S[t]=0}function w(a,e){$e(a);try{return e()}finally{Xe()}}var h={FirstPerson:"first-person",ThirdPerson:"third-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};import{Vector3 as nr,Quaternion as ar,MathUtils as Je}from"three";function pe(){return{position:new nr(0,0,10),rotation:new ar,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 di(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 ui(a,e,t,i){let r=1-Math.pow(1-Je.clamp(t,0,1),i*60),n=D(a);return n.position.lerp(e.position,r),n.rotation.slerp(e.rotation,r),e.fov!=null&&n.fov!=null&&(n.fov=Je.lerp(n.fov,e.fov,r)),e.zoom!=null&&n.zoom!=null&&(n.zoom=Je.lerp(n.zoom,e.zoom,r)),e.near!=null&&(n.near=e.near),e.far!=null&&(n.far=e.far),e.lookAt?n.lookAt?n.lookAt.lerp(e.lookAt,r):n.lookAt=e.lookAt.clone():n.lookAt=void 0,n}var he=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=pe();_finalPose=pe();_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):pe(),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 n=this.actions[r],s=n.update(e);t=di(t,s),n.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=ui(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 M,Quaternion as me}from"three";var sr={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},R=class{id="third-person";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...sr,...r},this.initialPosition=t?m(t,C):void 0,this.initialLookAt=i?m(i,C):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 me,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new M(0,0,0)}:{position:new M(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new me,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new M(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new M(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new me,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([p,v])=>this.getTrailedPosition(p,v.position,e.time)),r=new M;for(let p of i)r.add(p);r.divideScalar(i.length);let n=0;for(let p of i){let v=r.distanceTo(p);v>n&&(n=v)}let s=Math.max(n*this.opts.paddingFactor,this.opts.minDistance),o=new M(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=o.length(),c=l>0?o.clone().normalize():new M(0,.5,1).normalize(),d=r.clone().add(c.multiplyScalar(s));if(l>0){let p=this.opts.height/l;d.y=r.y+s*p}return{position:d,rotation:new me,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 n=this._trailBuffers.get(e);n||(n=[],this._trailBuffers.set(e,n)),n.push({time:i,pos:t.clone()});let s=i-r-.05;for(;n.length>1&&n[0].time<s;)n.shift();n.length>this.opts.trailBufferSize&&n.splice(0,n.length-this.opts.trailBufferSize);let o=i-r;if(n[0].time>=o)return n[0].pos.clone();for(let l=1;l<n.length;l++){let c=n[l-1],d=n[l];if(c.time<=o&&o<=d.time){let p=d.time-c.time,v=p>1e-6?(o-c.time)/p:0;return new M().lerpVectors(c.pos,d.pos,v)}}return n[n.length-1].pos.clone()}};import{Vector3 as pi,Quaternion as or}from"three";var hi={position:{x:0,y:0,z:10},zoom:10},A=class{id="fixed-2d";defaults={damping:1};opts;constructor(e){this.opts={...hi,...e,position:m(e?.position,hi.position)}}getBasePose(e){return{position:new pi(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new or,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new pi(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as et,Quaternion as tt,Euler as fi,MathUtils as f}from"three";var lr={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},j=class{id="first-person";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new tt;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...lr,...r},this.initialPosition=t?m(t,C):void 0,this.initialLookAt=i?m(i,C):void 0,this._currentFov=this.opts.defaultFov,this._targetFov=this.opts.defaultFov,this._lookAtLerpSpeed=this.opts.lookAtLerpSpeed,this.initialPosition&&this.initialLookAt&&this.deriveYawPitchFromLookAt(this.initialPosition,this.initialLookAt)}look(e,t){this._yaw+=e,this._pitch=f.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=f.clamp(t,-this.opts.pitchLimit,this.opts.pitchLimit)}setEyeHeight(e){this.opts.eyeHeight=e}get yaw(){return this._yaw}get pitch(){return this._pitch}zoom(e){this._targetFov=e}resetZoom(){this._targetFov=this.opts.defaultFov}get currentFov(){return this._currentFov}lookAt(e,t){this._lookAtTarget=e,t!=null&&(this._lookAtLerpSpeed=t)}clearLookAt(){this._lookAtTarget&&this.deriveYawPitchFromQuaternion(this._currentRotation),this._lookAtTarget=null}getBasePose(e){let t=this.computePosition(e),i=this.computeRotation(t,e.dt);return this._currentFov=this.lerpFov(e.dt),{position:t,rotation:i,fov:this._currentFov,near:.1,far:1e3}}computePosition(e){let t=e.targets[this.opts.targetKey];if(t){let i=t.position.y+this.opts.eyeHeight,r=this.smoothVertical(i,e.dt);return new et(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new et(0,this.opts.eyeHeight,0)}smoothVertical(e,t){if(this.opts.verticalSmoothing>=1)return this._smoothedY=e,e;if(this._smoothedY==null)return this._smoothedY=e,e;let i=f.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=f.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new tt().setFromEuler(new fi(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=mi.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let n=Math.atan2(-r.x,-r.z),s=Math.asin(f.clamp(r.y,-1,1)),o=cr.setFromEuler(gi.set(s,n,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(o,f.clamp(l,0,1)),this._currentRotation.clone()}}return this._currentRotation.copy(i),i}lerpFov(e){if(Math.abs(this._currentFov-this._targetFov)<.01)return this._targetFov;let t=1-Math.pow(1-Math.min(this.opts.fovLerpSpeed*e,1),1);return f.lerp(this._currentFov,this._targetFov,f.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=mi.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(f.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=gi.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=f.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},mi=new et,cr=new tt,gi=new fi;function z(a,e){switch(a){case"third-person":return new R(e);case"first-person":return new j(e);case"isometric":return new R({distance:10,height:10,...e});case"flat-2d":return new A(e);case"fixed-2d":return new A(e);default:return new R(e)}}import{Vector2 as hr,Object3D as mr,Vector3 as ye}from"three";import{PerspectiveCamera as K,Vector3 as ur,OrthographicCamera as fe,RenderTarget as pr,LinearFilter as yi}from"three";import{Vector3 as it}from"three";import{OrbitControls as dr}from"three/addons/controls/OrbitControls.js";var ge=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new it;debugDelegate=null;debugUnsubscribe=null;debugStateSnapshot={enabled:!1,selected:[]};savedCameraPosition=null;savedCameraQuaternion=null;savedCameraZoom=null;savedCameraLocalPosition=null;savedDebugCameraPosition=null;savedDebugCameraQuaternion=null;savedDebugCameraZoom=null;savedDebugOrbitTarget=null;_userOrbitEnabled=!1;_isDebugViewCamera=!1;_defaultOrbitTarget=null;_debugPoseSeeded=!1;_interactionEnabled=!0;_followSelection=!0;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}setDebugViewCamera(e){this._isDebugViewCamera=e}setDefaultOrbitTarget(e){this._defaultOrbitTarget=e,e&&!this.orbitTarget&&this.debugStateSnapshot.enabled&&this._followSelection&&(this.orbitTarget=e)}seedOrbitPose(e,t){this.camera.position.copy(e),this.camera.lookAt(t),this.orbitControls&&(this.orbitControls.target.copy(t),this.orbitControls.update()),this._debugPoseSeeded=!0}get isDebugViewCamera(){return this._isDebugViewCamera}get isDebugOrbitPoseSeeded(){return this._debugPoseSeeded}get isActive(){return this.debugStateSnapshot.enabled}get isOrbitActive(){return this.debugStateSnapshot.enabled||this._userOrbitEnabled}update(){this._followSelection&&this.orbitControls&&this.orbitTarget&&(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)),this.orbitControls?.update()}enableUserOrbitControls(){this._userOrbitEnabled=!0,this.orbitControls||this.enableOrbitControls()}disableUserOrbitControls(){this._userOrbitEnabled=!1,this.debugStateSnapshot.enabled||this.disableOrbitControls()}setDebugDelegate(e){if(this.debugDelegate===e)return;if(this.detachDebugDelegate(),this.debugDelegate=e,!e){this.applyDebugState({enabled:!1,selected:[]});return}let t=e.subscribe(i=>{this.applyDebugState(i)});this.debugUnsubscribe=()=>{t?.()}}dispose(){this.disableOrbitControls(),this.detachDebugDelegate()}get debugState(){return this.debugStateSnapshot}frameTarget(e){!this.orbitControls&&(this.debugStateSnapshot.enabled||this._userOrbitEnabled)&&this.enableOrbitControls(),this.orbitControls||this.enableOrbitControls(),this.orbitTarget=e;let t=new it().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=St(e,this.camera,t);this.orbitControls.target.copy(i.center),this.orbitControls.update()}applyDebugState(e){let t=this.debugStateSnapshot.enabled;if(this.debugStateSnapshot={enabled:e.enabled,selected:[...e.selected]},this._isDebugViewCamera){e.enabled&&!t?(this.enableOrbitControls(),this._debugPoseSeeded&&this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this._userOrbitEnabled||this.disableOrbitControls()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected);return}e.enabled&&!t?(this.saveCameraState(),this.detachCameraFromRig(),this.enableOrbitControls(),this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this.orbitTarget=null,this._userOrbitEnabled||this.disableOrbitControls(),this.reattachCameraToRig(),this.restoreCameraState()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected)}enableOrbitControls(){this.orbitControls||(this.orbitControls=new dr(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.enabled=this._interactionEnabled,this.orbitControls.target.set(0,0,0))}setInteractionEnabled(e){this._interactionEnabled=e,this.orbitControls&&(this.orbitControls.enabled=e)}setFollowSelectionEnabled(e){if(this._followSelection!==e){if(this._followSelection=e,!e){this.orbitTarget=null;return}this.updateOrbitTargetFromSelection(this.debugStateSnapshot.selected)}}get isFollowingSelection(){return this._followSelection}disableOrbitControls(){this.orbitControls&&(this.orbitControls.dispose(),this.orbitControls=null)}updateOrbitTargetFromSelection(e){if(this._followSelection){if(!this.debugDelegate||e.length===0){this.orbitTarget=this._defaultOrbitTarget,this.orbitControls&&(this.orbitTarget?(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)):this.orbitControls.target.set(0,0,0));return}for(let t=e.length-1;t>=0;t-=1){let i=e[t],r=this.debugDelegate.resolveTarget(i);if(r){this.orbitTarget=r,this.orbitControls&&(r.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos));return}}this.orbitTarget=this._defaultOrbitTarget,this.orbitControls&&(this.orbitTarget?(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)):this.orbitControls.target.set(0,0,0))}}detachDebugDelegate(){if(this.debugUnsubscribe)try{this.debugUnsubscribe()}catch{}this.debugUnsubscribe=null,this.debugDelegate=null}saveCameraState(){this.savedCameraPosition=this.camera.position.clone(),this.savedCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedCameraZoom=this.camera.zoom)}restoreCameraState(){this.savedCameraPosition&&(this.camera.position.copy(this.savedCameraPosition),this.savedCameraPosition=null),this.savedCameraQuaternion&&(this.camera.quaternion.copy(this.savedCameraQuaternion),this.savedCameraQuaternion=null),this.savedCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedCameraZoom,this.camera.updateProjectionMatrix?.(),this.savedCameraZoom=null)}saveDebugCameraState(){this.savedDebugCameraPosition=this.camera.position.clone(),this.savedDebugCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedDebugCameraZoom=this.camera.zoom),this.orbitControls&&(this.savedDebugOrbitTarget=this.orbitControls.target.clone())}restoreDebugCameraState(){this.savedDebugCameraPosition&&this.camera.position.copy(this.savedDebugCameraPosition),this.savedDebugCameraQuaternion&&this.camera.quaternion.copy(this.savedDebugCameraQuaternion),this.savedDebugCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedDebugCameraZoom,this.camera.updateProjectionMatrix?.()),this.savedDebugOrbitTarget&&this.orbitControls&&this.orbitControls.target.copy(this.savedDebugOrbitTarget)}detachCameraFromRig(){if(!this.cameraRig||this.camera.parent!==this.cameraRig)return;this.savedCameraLocalPosition=this.camera.position.clone();let e=new it;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 P=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...ri};targets=[];pipeline;renderTarget=null;get target(){return this.targets.length>0?this.targets[0]:null}set target(e){e?this.targets.length===0?this.targets.push(e):this.targets[0]=e:this.targets=[]}orbitController=null;_useOrbitalControls=!1;_skipDebugOrbit=!1;isDebugViewCamera=!1;_rendererManager=null;_elapsedTime=0;constructor(e,t,i=10){this._perspective=e,this.screenResolution=t,this.frustumSize=i;let r=t.x/t.y;this.camera=this.createCameraForPerspective(r),this.camera.position.set(0,0,10),this.camera.lookAt(new ur(0,0,0));let n=z(e);this.pipeline=new he(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 ge(this.camera,this._rendererManager.renderer.domElement,null),this.orbitController.setScene(e),this.isDebugViewCamera&&this.orbitController.setDebugViewCamera(!0),this._useOrbitalControls&&this.orbitController.enableUserOrbitControls())}async setupLegacy(e){this._rendererManager||(this._rendererManager=new le(this.screenResolution),await this._rendererManager.initRenderer(),this._rendererManager.setupPostProcessing(e,this.camera),this._rendererManager.startRenderLoop(()=>{this._rendererManager&&this.sceneRef&&(this.isOrbitActive&&this.updateOrbitControls(),this._rendererManager.render(this.sceneRef,this.camera))})),await this.setup(e,this._rendererManager)}update(e){if(this.isDebugModeActive()||this._useOrbitalControls)return;this._elapsedTime+=e;let t=this.buildContext(e),i=this.pipeline.run(t);this.commitPose(i)}isDebugModeActive(){return this.orbitController?.isActive??!1}get isOrbitActive(){return this.orbitController?.isOrbitActive??!1}updateOrbitControls(){this.orbitController?.update()}enableOrbitalControls(){this._useOrbitalControls=!0,this.orbitController?.enableUserOrbitControls()}disableOrbitalControls(){this._useOrbitalControls=!1,this.orbitController?.disableUserOrbitControls()}get useOrbitalControls(){return this._useOrbitalControls}addTarget(e){this.targets.includes(e)||this.targets.push(e)}removeTarget(e){let t=this.targets.indexOf(e);t!==-1&&this.targets.splice(t,1)}clearTargets(){this.targets=[]}setViewport(e,t,i,r){this.viewport={x:e,y:t,width:i,height:r}}resize(e,t){if(this.screenResolution.set(e,t),this.camera instanceof K&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof fe){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 pr(e,t,{minFilter:yi,magFilter:yi}),this.renderTarget}getRenderTexture(){return this.renderTarget?.texture??null}destroy(){try{this.orbitController?.dispose()}catch{}try{this.renderTarget?.dispose()}catch{}this.renderTarget=null,this.sceneRef=null,this.targets=[],this._rendererManager=null}setDefaultOrbitTarget(e){this.orbitController?.setDefaultOrbitTarget(e)}seedDebugOrbitPose(e,t){this.isDebugViewCamera&&this.isDebugOrbitPoseSeeded()||this.orbitController?.seedOrbitPose(e,t)}isDebugOrbitPoseSeeded(){return this.orbitController?.isDebugOrbitPoseSeeded??!1}setDebugDelegate(e){this._skipDebugOrbit||this.orbitController?.setDebugDelegate(e)}frameObject(e){this.orbitController?.frameTarget(e)}setOrbitInteractionEnabled(e){this.orbitController?.setInteractionEnabled(e)}setOrbitFollowEnabled(e){this.orbitController?.setFollowSelectionEnabled(e)}move(e){(this._perspective===h.Flat2D||this._perspective===h.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],n=i===0?"primary":`target_${i}`;r.group&&(t[n]={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 K&&(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 fe){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 h.ThirdPerson:return new K(75,e,.1,1e3);case h.FirstPerson:return new K(75,e,.1,1e3);case h.Isometric:return new fe(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);case h.Flat2D:case h.Fixed2D:return new fe(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);default:return new K(75,e,.1,1e3)}}};var be=class{cameras=new Map;_activeCameras=[];_debugCamera=null;_preDebugPrimary=null;_debugOrbitTargetAnchor=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;constructor(){}get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}get debugCamera(){return this._debugCamera}get preDebugPrimary(){return this._preDebugPrimary}get allCameras(){return Array.from(this.cameras.values())}addCamera(e,t){let i=t||e.name||`camera_${this._autoNameCounter++}`;return e.name=i,this.cameras.set(i,e),this._activeCameras.length===0&&this._activeCameras.push(e),i}removeCamera(e){let t;if(typeof e=="string")t=e;else for(let[n,s]of this.cameras.entries())if(s===e){t=n;break}if(!t)return!1;let i=this.cameras.get(t);if(!i)return!1;if(i===this._debugCamera)return console.warn("CameraManager: Cannot remove the debug camera"),!1;this.cameras.delete(t);let r=this._activeCameras.indexOf(i);return r!==-1&&this._activeCameras.splice(r,1),!0}setActiveCamera(e){let t=this.resolveCamera(e);if(!t)return console.warn(`CameraManager: Camera not found: ${e}`),!1;let i=this._activeCameras.filter(r=>r!==this._activeCameras[0]&&r.viewport.width<1);return this._activeCameras=[t,...i],!0}addActiveCamera(e){let t=this.resolveCamera(e);return t?(this._activeCameras.includes(t)||this._activeCameras.push(t),!0):!1}deactivateCamera(e){let t=this.resolveCamera(e);if(!t)return!1;let i=this._activeCameras.indexOf(t);return i!==-1?(this._activeCameras.splice(i,1),!0):!1}getCamera(e){return this.cameras.get(e)??null}async setup(e,t){this._sceneRef=e,this._rendererManager=t,this.createDebugCamera(t.screenResolution),this._debugOrbitTargetAnchor=new mr,this._debugOrbitTargetAnchor.name="__debug_orbit_target__",e.add(this._debugOrbitTargetAnchor);for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._debugCamera&&this._debugOrbitTargetAnchor&&this._debugCamera.setDefaultOrbitTarget(this._debugOrbitTargetAnchor)}activateDebugCamera(){if(!this._debugCamera)return!1;let e=this.primaryCamera;if(e===this._debugCamera)return!0;this._preDebugPrimary=e;let t=this.setActiveCamera(this._debugCamera);return t&&this.seedDebugCameraPose(e),t}deactivateDebugCamera(){if(!this._debugCamera)return!1;let e=this._preDebugPrimary;if(this._preDebugPrimary=null,e&&e!==this._debugCamera)return this.setActiveCamera(e);for(let t of this.cameras.values())if(t!==this._debugCamera)return this.setActiveCamera(t);return!1}update(e){for(let t of this._activeCameras)t.update(e)}render(e){if(!this._rendererManager||this._activeCameras.length===0)return;this.updateOrbitingCamerasForRender();let t=[],i=[];for(let r of this._activeCameras)r.renderTarget?t.push(r):i.push(r);for(let r of t)this._rendererManager.renderCameraToTarget(e,r);i.length>0&&this._rendererManager.renderCameras(e,i)}updateOrbitingCamerasForRender(){for(let e of this._activeCameras)e.isOrbitActive&&e.updateOrbitControls()}ensureDefaultCamera(){if(this.cameras.size===0||this._activeCameras.length===0){let e=this._rendererManager?.screenResolution||new hr(window.innerWidth,window.innerHeight),t=new P(h.ThirdPerson,e);return this.addCamera(t,"default"),t}return this._activeCameras[0]}dispose(){for(let e of this.cameras.values())e.destroy();this._debugCamera&&!this.cameras.has("__debug__")&&this._debugCamera.destroy(),this.cameras.clear(),this._activeCameras=[],this._debugCamera=null,this._preDebugPrimary=null,this._debugOrbitTargetAnchor&&this._sceneRef&&this._sceneRef.remove(this._debugOrbitTargetAnchor),this._debugOrbitTargetAnchor=null,this._rendererManager=null,this._sceneRef=null}createDebugCamera(e){this._debugCamera=new P(h.ThirdPerson,e),this._debugCamera.name="__debug__",this._debugCamera.isDebugViewCamera=!0,this._debugCamera.enableOrbitalControls(),this.cameras.set("__debug__",this._debugCamera)}seedDebugCameraPose(e){if(!this._debugCamera||this._debugCamera.isDebugOrbitPoseSeeded())return;let t=new ye(0,0,0),i=new ye(0,6,12);if(e&&e!==this._debugCamera){let r=e.camera.position,n=new ye().subVectors(r,t);n.lengthSq()>1&&i.copy(n.normalize().multiplyScalar(12).add(new ye(0,4,0)))}this._debugCamera.seedDebugOrbitPose(i,t)}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;if(e===this._debugCamera)return this._debugCamera;for(let t of this.cameras.values())if(t===e)return t;return null}};var y=class{cameraRef;constructor(e){this.cameraRef=e}addTarget(e){this.cameraRef.addTarget(e)}removeTarget(e){this.cameraRef.removeTarget(e)}clearTargets(){this.cameraRef.clearTargets()}enableOrbitalControls(){this.cameraRef.enableOrbitalControls()}disableOrbitalControls(){this.cameraRef.disableOrbitalControls()}setViewport(e,t,i,r){this.cameraRef.setViewport(e,t,i,r)}addBehavior(e,t){this.cameraRef.pipeline.addBehavior(e,t)}removeBehavior(e){return this.cameraRef.pipeline.removeBehavior(e)}addAction(e){this.cameraRef.pipeline.addAction(e)}setPerspective(e,t){this.cameraRef.pipeline.setPerspective(z(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function ns(a){let e=Dt(a.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;a.perspective==="fixed-2d"&&(t=a.zoom||10);let i=new P(a.perspective||"third-person",e,t);a.name&&(i.name=a.name);let r=m(a.position,C),n=m(a.target,C);i.move(r),i.camera.lookAt(n);let s=a.perspective||"third-person";if(s==="fixed-2d"||s==="flat-2d"?i.pipeline.setPerspective(z(s,{zoom:t})):i.pipeline.setPerspective(z(s,{initialPosition:r.clone(),initialLookAt:n.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[o,l]of Object.entries(a.behaviors))i.pipeline.addBehavior(o,l);if(a.renderToTexture){let{width:o=512,height:l=512}=a.renderToTexture;i.createRenderTarget(o,l)}return new y(i)}import{Vector3 as gr}from"three";function x(a){return!!a&&typeof a=="object"&&typeof a.create=="function"}function q(a){return!!a&&typeof a.then=="function"}function rt(a){return!!a&&typeof a=="object"&&a instanceof y}function bi(a){return!a||typeof a!="object"||x(a)||rt(a)||q(a)||typeof a.then=="function"?!1:a.constructor===Object||a.constructor?.name==="Object"}function vi(a){return a?!!(x(a)||typeof a=="function"||q(a)):!1}var fr="/three/basis/";function Ce(a){return{...a,ktx2TranscoderPath:a?.ktx2TranscoderPath??fr}}var ve=class{constructor(e,t,i,r,n,s,o=60,l={},c=!0,d=[]){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=n;this.variables=s;this.physicsRate=o;this.assetLoaders=l;this.defaultLighting=c;this.postProcessingEffects=d}};function yr(){return new ve({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},se,null,null,new gr(0,0,0),{},60,{},!0)}function Ci(a=[]){let e=yr(),t={},i=[],r=[],n=[];for(let l of a)rt(l)?n.push(l):x(l)?i.push(l):vi(l)&&!x(l)?r.push(l):bi(l)&&(t={...t,...l});let s=new ve(t.inputs??e.inputs,t.backgroundColor??e.backgroundColor,t.backgroundImage??e.backgroundImage,t.backgroundShader??e.backgroundShader,t.gravity??e.gravity,t.variables??e.variables,t.physicsRate??e.physicsRate,t.assetLoaders??e.assetLoaders,t.defaultLighting??e.defaultLighting,t.postProcessingEffects??e.postProcessingEffects),o=n.length>0?n[0]:void 0;return{config:s,entities:i,asyncEntities:r,camera:o,cameras:n}}function ps(a){return{...a}}var br=Symbol("vessel"),Q=class extends V{static type=br;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=vr();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function vr(...a){let e=new Q;return a.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Gi,Vector3 as Ui}from"three";import{createSimulation as Cr}from"@zylem/behaviors/core";function nt(a){return typeof a?.handlePostCollision=="function"&&typeof a?.handleIntersectionEvent=="function"}function Sr(a,e){return a<e?`${a}|${e}`:`${e}|${a}`}var Se=class a{type="World";simulation;collisionMap=new Map;collisionBehaviorMap=new Map;_removalMap=new Map;activeCollisionPairs=new Map;livePairs=new Map;handleIdToUuid=new Map;currentCollisionTimeMs=0;zeroGravity;fixedTimestep;interpolationAlpha=0;stepClock={steps:0};static async create(e,t=60){let i={x:e?.x??0,y:e?.y??0,z:e?.z??0},r=await Cr({gravity:[i.x,i.y,i.z],fixedTimestep:1/t,initialCapacity:4096});return new a(r,t,i.x===0&&i.y===0&&i.z===0)}constructor(e,t=60,i=!1){this.simulation=e,this.fixedTimestep=1/t,this.zeroGravity=i,this.simulation?.setEventsEnabled?.(!1)}addEntity(e){let t={...e.bodyDesc??{}},i=e.colliderDescs?.length?e.colliderDescs:e.colliderDesc?[e.colliderDesc]:[];this.zeroGravity&&(t.lockTranslation=t.lockTranslation??[!0,!0,!0],t.lockRotation=t.lockRotation??[!0,!0,!0]),(e.controlledRotation||e instanceof ne)&&e.bodyDesc?.lockRotation===void 0&&(t.lockRotation=[!0,!0,!0]);let r=this.simulation.spawn({body:t,colliders:i});if(!r){console.warn(`ZylemWorld: failed to spawn entity ${e.uuid} into simulation`);return}e.body=new Ft(this.simulation,r,this.stepClock),e.physicsAttached=!0,e.physicsWorldRef=this,e.simulationHandle=r,e.runtimeHandle=r.slot,e.runtimeAttached=!0,e.wasmStageRef=this.simulation.adapter,this.handleIdToUuid.set(r.id,e.uuid),this.collisionMap.set(e.uuid,e)}setForRemoval(e){e.physicsAttached&&this._removalMap.set(e.uuid,e)}destroyEntity(e){if(!(e.physicsWorldRef===this)){this.removeEntityFromTracking(e.uuid);return}let i=e.simulationHandle;if(i){try{this.simulation.despawn(i)}catch{}this.handleIdToUuid.delete(i.id)}this.removeEntityFromTracking(e.uuid),this.clearEntityPhysicsState(e)}setup(){}update(e){let{delta:t}=e;this.currentCollisionTimeMs+=t*1e3,this.processPendingRemovals();let i=this.hasCollisionPhaseListeners();i&&!this.simulation.areEventsEnabled&&this.simulation.setEventsEnabled?.(!0);let r=this.simulation.update(t);this.stepClock.steps+=r.stepsTaken,this.interpolationAlpha=r.alpha,i&&(this.applyCollisionEvents(r.events),this.processCollisionPairs(t,this.currentCollisionTimeMs))}hasCollisionPhaseListeners(){for(let e of this.collisionMap.values())if(e?.collisionDelegate?.collision?.length)return!0;return!1}applyCollisionEvents(e){for(let t of e){if(t.type!=="collisionStarted"&&t.type!=="collisionStopped")continue;let i=t.a?this.handleIdToUuid.get(t.a.id):void 0,r=t.b?this.handleIdToUuid.get(t.b.id):void 0;if(!i||!r||i===r)continue;let n=Sr(i,r),s=this.livePairs.get(n);s||(s={uuidA:i<r?i:r,uuidB:i<r?r:i,contactCount:0,intersectionCount:0},this.livePairs.set(n,s));let o=t.type==="collisionStarted"?1:-1;t.sensor?s.intersectionCount=Math.max(0,s.intersectionCount+o):s.contactCount=Math.max(0,s.contactCount+o),s.contactCount===0&&s.intersectionCount===0&&this.livePairs.delete(n)}}snapshotLivePairs(){let e=new Map;for(let[t,i]of this.livePairs)e.set(t,{uuidA:i.uuidA,uuidB:i.uuidB,hasContact:i.contactCount>0,hasIntersection:i.intersectionCount>0});return e}updatePostCollisionBehaviors(e){let t=this.collisionBehaviorMap;for(let[i,r]of t){let n=r;if(!nt(n))continue;n.handlePostCollision({entity:n,delta:e})||this.collisionBehaviorMap.delete(i)}}processPendingRemovals(){if(this._removalMap.size!==0){for(let[,e]of this._removalMap)this.destroyEntity(e);this._removalMap.clear()}}removeEntityFromTracking(e){this.collisionMap.delete(e),this._removalMap.delete(e),this.pruneActiveCollisionPairs(e)}pruneActiveCollisionPairs(e){for(let[t,i]of this.activeCollisionPairs)(i.uuidA===e||i.uuidB===e)&&this.activeCollisionPairs.delete(t);for(let[t,i]of this.livePairs)(i.uuidA===e||i.uuidB===e)&&this.livePairs.delete(t)}entityHasCollisionPhaseListener(e,t){let i=e?.collisionDelegate.collision;if(!i?.length)return!1;for(let r of i)if(r.options.phase===t)return!0;return!1}processCollisionPairs(e,t=this.currentCollisionTimeMs){let i=this.snapshotLivePairs();for(let[r,n]of i){let s=this.collisionMap.get(n.uuidA),o=this.collisionMap.get(n.uuidB);this.activeCollisionPairs.has(r)||this.dispatchCollisionPhase(n,"enter",t),(this.entityHasCollisionPhaseListener(s,"stay")||this.entityHasCollisionPhaseListener(o,"stay"))&&this.dispatchCollisionPhase(n,"stay",t),n.hasIntersection&&this.dispatchIntersectionDelegates(n,e)}this.updatePostCollisionBehaviors(e),this.activeCollisionPairs=i}dispatchCollisionPhase(e,t,i){let r={phase:t,nowMs:i},n=this.collisionMap.get(e.uuidA),s=this.collisionMap.get(e.uuidB);n&&s&&n._collision(s,Ve.globals,r);let o=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);o&&l&&l._collision(o,Ve.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&nt(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let n=this.collisionMap.get(e.uuidA),s=this.collisionMap.get(e.uuidB);n&&s&&nt(s)&&(s.handleIntersectionEvent({entity:s,other:n,delta:t}),this.collisionBehaviorMap.set(s.uuid,s))}raycast(e,t,i){let r=this.simulation.castRay([e.x,e.y,e.z],[t.x,t.y,t.z],i,!0);return r?{uuid:r.entity?this.handleIdToUuid.get(r.entity.id)??null:null,distance:r.distance,normal:r.normal}:null}destroy(){try{for(let[,e]of this.collisionMap)try{this.clearEntityPhysicsState(e)}catch{}try{this.simulation.dispose()}catch{}this.collisionMap.clear(),this.collisionBehaviorMap.clear(),this._removalMap.clear(),this.activeCollisionPairs.clear(),this.livePairs.clear(),this.handleIdToUuid.clear()}catch{}}clearEntityPhysicsState(e){e.physicsAttached=!1,e.body=null,e.runtimeHandle=-1,e.runtimeAttached=!1,e.wasmStageRef=null,e.simulationHandle=void 0,e.physicsWorldRef===this&&(e.physicsWorldRef=null)}};import{Scene as wr,Color as Si,AmbientLight as Pr,DirectionalLight as Er,Vector3 as we,GridHelper as Mr,Texture as xr,SRGBColorSpace as Tr}from"three";var Pe=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new wr,s=i.backgroundColor instanceof Si?i.backgroundColor:new Si(i.backgroundColor);r.background=s,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&L.loadTexture(i.backgroundImage,{colorSpace:Tr}).then(o=>{r.background=o}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),u.enabled&&this.debugScene()}setupBackgroundShader(e,t){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,e.backgroundNode=t.colorNode}setup(){this._setup&&this._setup({me:this,camera:this.zylemCamera,globals:g()})}destroy(){this.cameraManager?(this.cameraManager.dispose(),this.cameraManager=null):this.zylemCamera&&this.zylemCamera.destroy&&this.zylemCamera.destroy(),this.scene&&(this.scene.backgroundNode=null,this.scene.background instanceof xr&&(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 Pr(16777215,1);e.add(t);let i=new Er(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 we(0,0,0)){e.position.set(t.x,t.y,t.z),this.scene.add(e)}addEntity(e){let t=e.group??e.mesh;!t||this.isAttachedOutsideScene(t)||this.add(t,e.options.position)}addEntityGroup(e){if(T(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Dr(e);i&&i.attachToScene(this.scene);let r=e.options.position??new we(0,0,0);if(e.physicsAttached&&e.body)try{let n=e.body.translation();r=new we(n.x,n.y,n.z)}catch{r=e.options.position??new we(0,0,0)}this.add(t,r),Z(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new Mr(1e3,100);this.scene.add(i)}};function Dr(a){return a.constructor.type===It?a:null}var Ee=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 Rr}from"three";var wi=new Rr;function Pi(a){let e=a._childrenMap,t=a._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval||i.isInstanced||i.isBundled||i.skipRenderPoseSync)continue;let r=i.body,n=i.group??i.mesh,s=n?ae(r,t?.interpolationAlpha??0):null;n&&s&&n.position.set(s.position.x,s.position.y,s.position.z),!i.controlledRotation&&n&&s&&(wi.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w),n.setRotationFromQuaternion(wi))}}import{nanoid as wn}from"nanoid";import{Box3 as pn,BufferAttribute as zi,BufferGeometry as hn,LineBasicMaterial as mn,LineSegments as gn,Raycaster as fn,Vector2 as yn,Vector3 as yt}from"three";import{subscribe as bn}from"valtio/vanilla";import{nanoid as Fi}from"nanoid";import{subscribe as _r}from"valtio/vanilla";var Me=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),_r(u,t)}resolveTarget(e){let t=this.stage.entityDelegate.debugMap.get(e)||this.stage.entityDelegate.childrenMap.get(e)||this.stage.world?.collisionMap.get(e)||null;return t?.group??t?.mesh??null??null}snapshot(){return{enabled:u.enabled,selected:u.selectedEntityId?[u.selectedEntityId]:[]}}};import{Box3 as kr,BoxGeometry as Ei,Color as Lr,EdgesGeometry as Mi,Group as Or,LineBasicMaterial as Br,LineSegments as Ar,Mesh as zr,MeshBasicMaterial as Fr,Vector3 as xi}from"three";var xe=class{scene;container;fillMesh;edgeLines;currentColor=new Lr(65280);bbox=new kr;size=new xi;center=new xi;constructor(e){this.scene=e;let t=new Ei(1,1,1);this.fillMesh=new zr(t,new Fr({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new Mi(t);this.edgeLines=new Ar(i,new Br({color:this.currentColor,linewidth:1})),this.container=new Or,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 Ei(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 Mi(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()}};import{Box3 as Ir,BoxGeometry as Vr,Group as Zr,Mesh as Gr,MeshBasicMaterial as Ur,Vector3 as Ti}from"three";var Nr={x:0,y:0,z:0},Hr=7128319,Wr=.35;function jr(){return new Ur({color:Hr,transparent:!0,opacity:Wr,depthWrite:!1})}function Kr(a){let e=a.size;return new Ti(e?.x??1,e?.y??1,e?.z??1)}function qr(a,e){try{let t=a.create({position:Nr,props:e});if(!t||typeof t.then=="function")return null;let i=t,r=i.group??i.mesh??null;return r?r.clone():null}catch(t){return console.warn(`[zylem] placement ghost: the "${a.id}" factory failed, falling back to a box`,t),null}}function Qr(a,e){a.traverse(t=>{let i=t;i.isMesh&&(i.material=e,i.castShadow=!1,i.receiveShadow=!1)})}var Te=class{scene;container;builtFor=null;builtProps=null;material=null;extent=null;bounds=new Ir;constructor(e){this.scene=e,this.container=new Zr,this.container.name="PlacementGhost",this.container.visible=!1,this.scene.add(this.container)}setType(e,t){let i=t??null;if(e===this.builtFor&&i===this.builtProps)return;if(this.builtFor=e,this.builtProps=i,this.clearSilhouette(),!e){this.hide();return}let r=te(e),n={...r?.defaultProps??{},...t??{}},o=(r?qr(r,n):null)??new Gr(new Vr(...Kr(n).toArray()));o.position.set(0,0,0),this.material=jr(),Qr(o,this.material),this.container.add(o),this.bounds.setFromObject(o),this.extent=this.bounds.isEmpty()?null:this.bounds.getSize(new Ti)}measure(){return this.extent}showAt(e){if(this.container.children.length===0){this.hide();return}this.container.position.copy(e),this.container.visible=!0}hide(){this.container.visible=!1}dispose(){this.clearSilhouette(),this.scene.remove(this.container),this.builtFor=null,this.builtProps=null}clearSilhouette(){for(let e of[...this.container.children])this.container.remove(e),e.traverse(t=>{let i=t;i.isMesh&&i.geometry?.dispose()});this.material?.dispose(),this.material=null,this.extent=null}};import{Vector3 as at}from"three";var Yr=0;function $r(a,e){if(e)return{position:a.origin.clone().add(a.direction.clone().multiplyScalar(e.distance)),normal:new at(e.normal[0],e.normal[1],e.normal[2])};if(Math.abs(a.direction.y)<1e-6)return null;let t=(Yr-a.origin.y)/a.direction.y;return t<0?null:{position:a.origin.clone().add(a.direction.clone().multiplyScalar(t)),normal:new at(0,1,0)}}function Xr(a,e){if(e.lengthSq()<1e-8)return 0;let t=e.clone().normalize();return(Math.abs(t.x)*a.x+Math.abs(t.y)*a.y+Math.abs(t.z)*a.z)/2}function st(a,e,t){let i=Xr(e,t);return i<=0?a.clone():a.clone().add(t.clone().normalize().multiplyScalar(i))}function ot(a,e,t,i){let r=$r(a,e);if(!r)return null;let{normal:n}=r,s=t.enabled?ee(r.position,t.translate):r.position,o=new at(s.x,s.y,s.z);return{position:i?st(o,i,n):o,normal:n}}import{Box3 as rn,Quaternion as ke,Vector3 as b}from"three";import{nanoid as nn}from"nanoid";import{Vector3 as F}from"three";var ct=.95,Jr=16,Y=new F,en=new F,Di=new F,lt=new F;function Ri(a){return a?a.isPerspectiveCamera===!0||a.isOrthographicCamera===!0:!1}function De(a,e,t=ct){return Y.copy(a).project(e),Math.abs(Y.x)<=t&&Math.abs(Y.y)<=t&&Y.z>=-1&&Y.z<=1}function _i(a){let e=0,t=1;for(let i=0;i<Jr;i+=1){let r=(e+t)/2;a(r)?e=r:t=r}return e}function ki(a,e,t,i=ct){if(!Ri(t))return e.clone();let r=t;if(De(e,r,i)||!De(a,r,i))return e.clone();let n=_i(s=>De(en.copy(a).lerp(e,s),r,i));return a.clone().lerp(e,n)}function Li(a,e,t,i,r=ct){if(!Ri(i)||t.x<=1&&t.y<=1&&t.z<=1||a.isEmpty())return t.clone();let n=i;Di.copy(e);let s=new F(1,1,1),o=c=>(s.set(1+(t.x-1)*c,1+(t.y-1)*c,1+(t.z-1)*c),tn(a,Di,s,n,r));if(o(1))return t.clone();let l=_i(o);return new F(1+(t.x-1)*l,1+(t.y-1)*l,1+(t.z-1)*l)}function tn(a,e,t,i,r){for(let n=0;n<8;n+=1)if(lt.set(n&1?a.max.x:a.min.x,n&2?a.max.y:a.min.y,n&4?a.max.z:a.min.z),lt.sub(e).multiply(t).add(e),!De(lt,i,r))return!1;return!0}var an={translate:"Move",rotate:"Rotate",scale:"Scale"};function dt(a){let e=typeof a?.getPose=="function"?a.getPose():null,t=a?.group??a?.mesh,i=e?.position??(t?{x:t.position.x,y:t.position.y,z:t.position.z}:null)??{x:0,y:0,z:0},r=e?.rotation??{x:0,y:0,z:0,w:1},n=typeof a?.getScale=="function"?a.getScale():{x:1,y:1,z:1};return{position:new b(i.x,i.y,i.z),quaternion:new ke(r.x,r.y,r.z,r.w),scale:new b(n.x,n.y,n.z)}}function Oi(a){let e=We(a.quaternion);return{position:{x:a.position.x,y:a.position.y,z:a.position.z},rotation:e,quaternion:{x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w},scale:{x:a.scale.x,y:a.scale.y,z:a.scale.z}}}function sn(a,e){return a.position.distanceToSquared(e.position)>1e-5*1e-5||Math.abs(a.quaternion.dot(e.quaternion))<1-1e-5||a.scale.distanceToSquared(e.scale)>1e-5*1e-5}function Re(a,e){(e.position||e.quaternion)&&a.setPose?.({position:e.position?{x:e.position.x,y:e.position.y,z:e.position.z}:void 0,rotation:e.quaternion?{x:e.quaternion.x,y:e.quaternion.y,z:e.quaternion.z,w:e.quaternion.w}:void 0}),e.scale&&a.setScale?.(e.scale.x,e.scale.y,e.scale.z)}function on(a){let e=a?.group??a?.mesh;if(!e?.isObject3D)return null;let t=new rn().setFromObject(e);return t.isEmpty()?null:t}var ut=.02,pt=50;function ln(a){return new b(ht(a.x,ut,pt),ht(a.y,ut,pt),ht(a.z,ut,pt))}function ht(a,e,t){return Math.min(Math.max(a,e),t)}var mt=new ke,cn=new b,_e=class{gizmo=new Wt;context;mode=null;session=null;pausedBeforeEntry=null;constructor(e){this.context=e}setMode(e){if(this.mode!==e){if(e&&this.pausedBeforeEntry===null?(this.pausedBeforeEntry=u.paused,u.paused=!0):!e&&this.pausedBeforeEntry!==null&&(u.paused=this.pausedBeforeEntry,this.pausedBeforeEntry=null),this.mode=e,this.cancelDrag(),!e){this.gizmo.hide();return}this.gizmo.setMode(e)}}getMode(){return this.mode}get isDragging(){return this.session!==null}update(){let e=this.context.getScene();if(e&&this.gizmo.addTo(e),!this.mode){this.gizmo.hide();return}if(!this.session){let i=this.selectionPivot();if(!i){this.gizmo.hide();return}this.gizmo.show(i)}let t=this.context.getCamera();t&&this.gizmo.update(t)}hover(e){if(!this.mode||this.session)return null;let t=this.gizmo.pick(e);return this.gizmo.setHighlight(t),t}pointerDown(e){if(!this.mode)return!1;let t=this.context.getCamera();if(!t)return!1;let i=this.gizmo.pick(e);if(!i||!this.gizmo.beginDrag(i,e,t))return!1;let r=[];for(let n of u.selectedEntityIds){let s=this.context.resolveEntity(n);s&&r.push({uuid:n,entity:s,start:dt(s),startBounds:this.mode==="scale"?on(s):null})}return r.length?(this.session={mode:this.mode,axis:i,entries:r,pivotStart:this.gizmo.pivot.clone(),changed:!1},!0):(this.gizmo.endDrag(),!1)}pointerMove(e,t){let i=this.session;if(!i)return;let r=this.context.getCamera();if(!r)return;let n=this.gizmo.updateDrag(e,r);if(!n)return;let s=k(),o=s.enabled&&!t;switch(n.kind){case"translate":this.applyTranslate(i,n.offset,o?s.translate:0,r);break;case"rotate":this.applyRotate(i,n.axis,n.angle,o?s.rotate:0);break;case"scale":this.applyScale(i,n.factor,o?s.scale:0,r);break}i.changed=!0}pointerUp(){let e=this.session;if(this.session=null,this.gizmo.endDrag(),!e)return;let t=[];for(let i of e.entries){let r=dt(i.entity);sn(i.start,r)&&(e.mode==="scale"&&je(i.entity),t.push({uuid:i.uuid,before:Oi(i.start),after:Oi(r)}))}t.length&&I({opId:nn(10),kind:"transform",label:this.describeOperation(e),entries:t})}cancelDrag(){this.session=null,this.gizmo.endDrag()}dispose(){this.cancelDrag(),this.pausedBeforeEntry!==null&&(u.paused=this.pausedBeforeEntry,this.pausedBeforeEntry=null),this.gizmo.dispose()}applyTranslate(e,t,i,r){let n=cn.copy(e.pivotStart).add(t),s=ki(e.pivotStart,n,r),o=i>0?ee(s,i):s,l=new b(o.x-e.pivotStart.x,o.y-e.pivotStart.y,o.z-e.pivotStart.z);for(let c of e.entries)Re(c.entity,{position:c.start.position.clone().add(l)})}applyRotate(e,t,i,r){let n=e.axis;for(let s of e.entries){mt.setFromAxisAngle(t,i);let o=mt.clone().multiply(s.start.quaternion),l=o;if(r>0&&(n==="x"||n==="y"||n==="z")){let d=We(o);d[n]=Mt(d[n],r);let p=He(d);l=new ke(p.x,p.y,p.z,p.w)}let c=s.start.position.clone().sub(e.pivotStart).applyQuaternion(mt).add(e.pivotStart);Re(s.entity,{position:c,quaternion:l})}}applyScale(e,t,i,r){for(let n of e.entries){let s=n.startBounds?Li(n.startBounds,n.start.position,t,r):t,o=ln(s),l=new b(n.start.scale.x*o.x,n.start.scale.y*o.y,n.start.scale.z*o.z),c=i>0?xt(l,i):l;Re(n.entity,{scale:new b(c.x,c.y,c.z)})}}describeOperation(e){let t=an[e.mode];if(e.entries.length>1)return`${t} ${e.entries.length} entities`;let i=e.entries[0]?.entity,r=i?.name||String(i?.constructor?.type??"").replace("Symbol(","").replace(")","")||"Entity";return`${t} ${r}`}selectionPivot(){let e=u.selectedEntityIds;if(!e.length)return null;let t=new b,i=0;for(let r of e){let n=this.context.resolveEntity(r);n&&(t.add(dt(n).position),i++)}return i?t.divideScalar(i):null}};function Bi(a,e,t){for(let i of a.entries){let r=e==="undo"?i.before:i.after;if(!r)continue;let n=t(i.uuid);if(!n)continue;let s=r.quaternion??(r.rotation?He(r.rotation):void 0);Re(n,{position:r.position?new b(r.position.x,r.position.y,r.position.z):void 0,quaternion:s?new ke(s.x,s.y,s.z,s.w):void 0,scale:r.scale?new b(r.scale.x,r.scale.y,r.scale.z):void 0}),r.scale&&je(n)}}var dn=200;function Ai(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function un(a){return Ai(a)&&(ie(a)||_t(a))}var Le=class{stage;snapshots=new Map;constructor(e){this.stage=e}applySwatches(e){let t=new Map,i=[],r=[];for(let n of e.uuids)for(let s of e.swatches){let{result:o,entry:l}=this.applyPair(n,s,t);i.push(o),l&&r.push(l)}return t.size>0&&this.remember(e.opId,t),{results:i,entries:r}}applySceneOperation(e,t){if(e.kind!=="swatch")return;let i=this.snapshots.get(e.opId);if(i){t==="undo"?this.undoFromSnapshot(i):this.redoFromSnapshot(i);return}if(t==="redo"){let r=new Map;for(let n of e.entries)n.swatch&&this.applyPair(n.uuid,n.swatch,r);r.size>0&&this.remember(e.opId,r);return}this.undoWithoutSnapshot(e)}hasSnapshot(e){return this.snapshots.has(e)}dispose(){for(let[e]of this.snapshots)this.forget(e)}applyPair(e,t,i){let r={uuid:e,kind:t.kind,source:t.source},n=this.stage.resolveEntity(e);if(!n)return{result:{...r,ok:!1,reason:"entity-not-found"}};if(!Ai(t.props))return{result:{...r,ok:!1,reason:"invalid-props"}};let s=i.get(e)??{previousRefs:new Map,appliedRefs:new Map},o=t.kind==="shader"?this.applyShader(n,t,s):this.applyBehavior(n,t,s);return o.ok?(i.set(e,s),{result:{...r,ok:!0,replaced:o.replaced},entry:{uuid:e,swatch:t,...o.replacedSpec?{replaced:o.replacedSpec}:{}}}):{result:{...r,ok:!1,reason:o.reason}}}applyShader(e,t,i){let r=re("shader",t.source);if(!r)return{ok:!1,reason:"unknown-source"};if(!e.hasMaterial())return{ok:!1,reason:"no-material"};let n;try{n=r.create(t.props)}catch(o){return console.warn(`[zylem] swatch shader "${t.source}" threw`,o),{ok:!1,reason:"invalid-props"}}if(!un(n))return{ok:!1,reason:"invalid-props"};let s=e.setMaterial({shader:n},{disposePrevious:!1});return s?(i.previousMaterials?gt(s,i.previousMaterials):i.previousMaterials=s,{ok:!0,replaced:!1}):{ok:!1,reason:"no-material"}}applyBehavior(e,t,i){let r=re("behavior",t.source);if(!r)return{ok:!1,reason:"unknown-source"};let{descriptor:n}=r,s=n.key,o=!1,l,c=e.getBehaviorRef(n);c&&(e.removeBehavior(c),this.stage.detachBehaviorLink(e,c),i.appliedRefs.get(s)===c||(o=!0,l={source:t.source,props:{...c.options}},i.previousRefs.has(s)||i.previousRefs.set(s,c)));let d;try{e.use(n,t.props),d=e.getBehaviorRefs().at(-1)}catch(p){console.warn(`[zylem] swatch behavior "${t.source}" failed to attach`,p)}return!d||d.descriptor.key!==s?(c&&(e.restoreBehaviorRef(c),this.stage.attachBehaviorLink(e,c),i.previousRefs.get(s)===c&&i.previousRefs.delete(s)),{ok:!1,reason:"invalid-props"}):(this.stage.attachBehaviorLink(e,d),i.appliedRefs.set(s,d),{ok:!0,replaced:o,replacedSpec:l})}undoFromSnapshot(e){for(let[t,i]of[...e].reverse()){let r=this.stage.resolveEntity(t);if(r){if(i.previousMaterials){let n=r.replaceMaterials(i.previousMaterials,{disposePrevious:!1});n&&(i.redoMaterials=n)}for(let n of i.appliedRefs.values())r.removeBehavior(n)&&this.stage.detachBehaviorLink(r,n);for(let n of i.previousRefs.values())r.restoreBehaviorRef(n),this.stage.attachBehaviorLink(r,n)}}}redoFromSnapshot(e){for(let[t,i]of e){let r=this.stage.resolveEntity(t);if(r){i.redoMaterials&&r.replaceMaterials(i.redoMaterials,{disposePrevious:!1});for(let n of i.previousRefs.values())r.removeBehavior(n)&&this.stage.detachBehaviorLink(r,n);for(let n of i.appliedRefs.values())r.restoreBehaviorRef(n),this.stage.attachBehaviorLink(r,n)}}}undoWithoutSnapshot(e){for(let t of[...e.entries].reverse()){let i=this.stage.resolveEntity(t.uuid);if(!(!i||!t.swatch)){if(t.swatch.kind==="behavior"){let r=re("behavior",t.swatch.source);if(!r)continue;let n=i.removeBehavior(r.descriptor);if(n&&this.stage.detachBehaviorLink(i,n),t.replaced){i.use(r.descriptor,t.replaced.props);let s=i.getBehaviorRefs().at(-1);s&&this.stage.attachBehaviorLink(i,s)}continue}i.setMaterial({})}}}remember(e,t){for(this.snapshots.has(e)&&this.forget(e),this.snapshots.set(e,t);this.snapshots.size>dn;){let i=this.snapshots.keys().next().value;if(i===void 0)break;this.forget(i)}}forget(e){let t=this.snapshots.get(e);if(this.snapshots.delete(e),!!t)for(let[i,r]of t){let n=this.stage.resolveEntity(i)?.getMaterials()??[];gt(r.previousMaterials??[],n),gt(r.redoMaterials??[],n)}}};function gt(a,e){for(let t of a)e.includes(t)||t.dispose()}var Ii=2293538,vn=16724787,ft=new pn,Vi=new yt,Oe=class{stage;options;mouseNdc=new yn(-2,-2);raycaster=new fn;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;placementGhost=null;debugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;focusContextUnregister=null;entityResolverUnregister=null;lastDebugEnabled=null;warnedMissingAddFactory=!1;transformTool;swatchApplier;grid=new Ht;lastTool=null;capturedPointer=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.transformTool=new _e({getScene:()=>this.stage.scene?.scene??null,getCamera:()=>this.getDebugViewCamera()?.camera??null,resolveEntity:i=>this.resolveEntity(i)}),this.swatchApplier=new Le({resolveEntity:i=>this.resolveEntity(i),attachBehaviorLink:(i,r)=>this.stage.entityDelegate.attachBehaviorLink(i,r),detachBehaviorLink:(i,r)=>this.stage.entityDelegate.detachBehaviorLink(i,r)}),this.syncWithDebugState(),this.debugStateUnsubscribe=bn(u,()=>{this.syncWithDebugState()}),this.entityResolverUnregister=vt(i=>this.resolveEntity(i)),this.focusContextUnregister=Et({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{this.ensureCameraDebugDelegate(),this.getDebugViewCamera()?.frameObject(i)},ensureDebugReady:()=>{u.enabled||(u.enabled=!0),this.lastDebugEnabled=!0,this.activate()}})}setAddEntityFactory(e){this.options.addEntityFactory=e,this.warnedMissingAddFactory=!1}getDebugViewCamera(){return this.stage.cameraManagerRef?.primaryCamera??this.stage.cameraManagerRef?.debugCamera??this.stage.cameraRef??null}resolveEntity(e){let t=this.stage.entityDelegate.debugMap.get(e);if(t)return t;let i=this.stage.entityDelegate.childrenMap.get(e);return i||(this.stage.world?.collisionMap.get(e)??null)}populateDebugMap(){this.stage.entityDelegate.childrenMap.forEach((e,t)=>{this.stage.entityDelegate.debugMap.set(t,e)})}ensureCameraDebugDelegate(){let e=this.stage.cameraManagerRef?.debugCamera??null;e&&(this.cameraDebugDelegate||(this.cameraDebugDelegate=new Me(this.stage)),e.setDebugDelegate(this.cameraDebugDelegate))}syncWithDebugState(){this.syncToolMode(),this.syncGrid();let e=u.enabled;e!==this.lastDebugEnabled&&(this.lastDebugEnabled=e,e?this.activate():this.deactivate())}syncToolMode(){let e=u.tool;if(e===this.lastTool)return;this.lastTool=e,e!=="none"&&(this.ensureInteraction(),this.populateDebugMap()),this.parkToolVisuals(e);let t=Ze(e);this.getDebugViewCamera()?.setOrbitFollowEnabled(!t),this.transformTool.setMode(t?e:null)}syncGrid(){let e=this.stage.scene?.scene;e&&(this.grid.addTo(e),this.grid.setIncrement(k().translate),this.grid.setVisible(u.gridVisible))}activate(){this.domListenersAttached||(this.domListenersAttached=this.attachDomListeners()),this.populateDebugMap(),this.stage.cameraManagerRef?.activateDebugCamera();let e=this.stage.cameraManagerRef?.debugCamera??null;this.rebindPostProcessing(e),this.ensureCameraDebugDelegate(),document.pointerLockElement&&document.exitPointerLock()}deactivate(){this.disposeDebugVisuals(),this.transformTool.cancelDrag(),this.grid.setVisible(!1);let e=this.stage.cameraManagerRef?.debugCamera;e&&e.setDebugDelegate(null),this.stage.cameraRef&&this.stage.cameraRef!==e&&this.stage.cameraRef.setDebugDelegate(null),this.cameraDebugDelegate=null,this.stage.cameraManagerRef?.deactivateDebugCamera();let t=this.stage.cameraManagerRef?.primaryCamera??this.stage.cameraRef??null;this.rebindPostProcessing(t)}rebindPostProcessing(e){let t=this.stage.scene?.scene,i=this.stage.rendererManager;t&&i&&e&&i.setupPostProcessing(t,e.camera)}initDebugVisuals(){this.debugLines||!this.stage.scene||(this.debugLines=new gn(new hn,new mn({vertexColors:!0})),this.stage.scene.scene.add(this.debugLines),this.debugLines.visible=!0)}disposeDebugVisuals(){this.debugLines&&this.stage.scene&&(this.stage.scene.scene.remove(this.debugLines),this.debugLines.geometry.dispose(),this.debugLines.material.dispose(),this.debugLines=null)}ensureToolVisuals(){let e=this.stage.scene?.scene;e&&(this.debugCursor??=new xe(e),this.placementGhost??=new Te(e))}parkToolVisuals(e){e!=="add"&&this.placementGhost?.hide(),e!=="select"&&e!=="delete"&&!u.pickMode&&this.debugCursor?.hide()}disposeToolVisuals(){this.debugCursor?.dispose(),this.debugCursor=null,this.placementGhost?.dispose(),this.placementGhost=null}update(){let e=this.getDebugViewCamera();if(!this.stage.scene||!this.stage.world||!e)return;let{world:t}=this.stage,i=Ge();if(this.ensureInteraction(),this.ensureToolVisuals(),u.enabled?(this.initDebugVisuals(),this.updateColliderWireframes(t)):this.disposeDebugVisuals(),this.updatePlacementGhost(i,t),Ze(i)){this.debugCursor?.hide(),this.transformTool.update(),this.transformTool.isDragging||this.transformTool.hover(this.currentRay());return}if(this.transformTool.update(),!(i==="select"||i==="delete"||u.pickMode)){this.debugCursor?.hide();return}let n=this.currentRay(),s=t.raycast(n.origin,n.direction,this.options.maxRayDistance);s?Ne(s.uuid??null):J();let o=Ct();if(!o){this.debugCursor?.hide();return}let l=this.resolveEntity(o),c=l?.group??l?.mesh??null;if(!c){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(Ii);break;case"delete":this.debugCursor?.setColor(vn);break;default:this.debugCursor?.setColor(u.pickMode?Ii:16777215);break}this.debugCursor?.updateFromObject(c)}pickAtNdc(e,t,i={}){let r=i.updateHover??u.pickMode;this.mouseNdc.set(e,t);let n=this.stage.world;if(!n||!this.getDebugViewCamera())return r&&J(),null;let s=this.currentRay(),l=n.raycast(s.origin,s.direction,this.options.maxRayDistance)?.uuid??null;if(!l)return r&&J(),null;r&&Ne(l);let c=this.resolveEntity(l);return{uuid:l,name:c?.name??""}}applySwatches(e){return this.swatchApplier.applySwatches(e)}updateColliderWireframes(e){if(!this.debugLines)return;let t=e.simulation.getDebugRender();t&&t.vertices.length>0?(this.debugLines.geometry.setAttribute("position",new zi(new Float32Array(t.vertices),3)),this.debugLines.geometry.setAttribute("color",new zi(new Float32Array(t.colors),4)),this.debugLines.geometry.attributes.position.needsUpdate=!0,this.debugLines.geometry.attributes.color.needsUpdate=!0,this.debugLines.visible=!0):this.debugLines.visible=!1}ensureInteraction(){this.domListenersAttached||!X()||(this.domListenersAttached=this.attachDomListeners())}updatePlacementGhost(e,t){let i=this.placementGhost;if(!i)return;let r=u.addTypeId;if(e!=="add"||!r){i.hide();return}i.setType(r,u.addTypeProps??null);let n=this.currentRay(),s=t.raycast(n.origin,n.direction,this.options.maxRayDistance)??null,o=ot(n,s,k(),i.measure());if(!o){i.hide();return}i.showAt(o.position)}dispose(){this.focusContextUnregister?.(),this.focusContextUnregister=null,this.entityResolverUnregister?.(),this.entityResolverUnregister=null,this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.endPointerCapture(),this.transformTool.dispose(),this.swatchApplier.dispose(),this.grid.dispose(),this.deactivate(),this.disposeToolVisuals(),this.domDisposeFns.forEach(e=>e()),this.domDisposeFns=[],this.domListenersAttached=!1}applySceneOperation(e,t){let i=t==="undo";switch(e.kind){case"transform":Bi(e,t,r=>this.resolveEntity(r));break;case"create":for(let r of e.entries)i?this.stage.entityDelegate.detachEntity(r.uuid):this.stage.entityDelegate.restoreEntity(r.uuid);break;case"delete":for(let r of e.entries)i?this.stage.entityDelegate.restoreEntity(r.uuid):this.stage.entityDelegate.detachEntity(r.uuid);break;case"swatch":this.swatchApplier.applySceneOperation(e,t);break}}currentRay(){let e=this.getDebugViewCamera();return e?(this.raycaster.setFromCamera(this.mouseNdc,e.camera),{origin:this.raycaster.ray.origin.clone(),direction:this.raycaster.ray.direction.clone().normalize()}):{origin:new yt,direction:new yt(0,0,-1)}}handleAction(e){let t=Ge();if(t!=="select"&&t!=="delete"&&t!=="add")return;let r=this.stage.world?.raycast(e.origin,e.direction,this.options.maxRayDistance)??null;switch(t){case"select":{let n=r?.uuid??null;n&&this.resolveEntity(n)?Ue(n):Ue(null);break}case"delete":{let n=r?.uuid??null;if(!n)break;this.stage.entityDelegate.detachEntity(n)&&I({opId:Fi(10),kind:"delete",label:"Delete entity",entries:[{uuid:n}]});break}case"add":this.placeEntity(e,r);break}}placeEntity(e,t){let i=ot(e,t,k());if(!i)return;let{position:r,normal:n}=i,s=u.addTypeId?te(u.addTypeId):null;if(!s&&!this.options.addEntityFactory){this.warnMissingAddSource();return}let o=s?s.create({position:{x:r.x,y:r.y,z:r.z},normal:{x:n.x,y:n.y,z:n.z},props:{...s.defaultProps??{},...u.addTypeProps??{}}}):this.options.addEntityFactory({position:r,normal:n});o&&Promise.resolve(o).then(async l=>{l&&(await this.stage.entityDelegate.spawnEntity(l),this.restOnSurface(l,r,n),I({opId:Fi(10),kind:"create",label:`Add ${s?.label??"entity"}`,entries:[{uuid:l.uuid}]}))}).catch(l=>{console.error("Add tool: failed to spawn entity",l)})}restOnSurface(e,t,i){let r=e?.group??e?.mesh;if(!r||typeof e.setPose!="function"||(ft.setFromObject(r),ft.isEmpty()))return;ft.getSize(Vi);let n=st(t,Vi,i);n.equals(t)||e.setPose({position:{x:n.x,y:n.y,z:n.z}})}warnMissingAddSource(){if(this.warnedMissingAddFactory)return;this.warnedMissingAddFactory=!0;let e="Add tool: no entity type is armed and no `addEntityFactory` is configured, so there is nothing to spawn.";console.warn(e),Tt("warn",e)}attachDomListeners(){let e=this.stage.rendererManager?.getDomElement();if(!e)return!1;let t=s=>{let o=e.getBoundingClientRect(),l=(s.clientX-o.left)/o.width*2-1,c=-((s.clientY-o.top)/o.height*2-1);this.mouseNdc.set(l,c)},i=s=>{t(s),this.transformTool.isDragging&&this.transformTool.pointerMove(this.currentRay(),s.altKey)},r=s=>{if(s.button!==0)return;t(s);let o=this.currentRay();if(this.transformTool.pointerDown(o)){this.beginPointerCapture(e,s.pointerId);return}this.handleAction(o)},n=()=>{this.transformTool.isDragging&&(this.transformTool.pointerUp(),this.endPointerCapture())};return e.addEventListener("pointermove",i),e.addEventListener("pointerdown",r),e.addEventListener("pointerup",n),e.addEventListener("pointercancel",n),this.domDisposeFns.push(()=>e.removeEventListener("pointermove",i),()=>e.removeEventListener("pointerdown",r),()=>e.removeEventListener("pointerup",n),()=>e.removeEventListener("pointercancel",n)),!0}beginPointerCapture(e,t){this.getDebugViewCamera()?.setOrbitInteractionEnabled(!1);try{e.setPointerCapture(t),this.capturedPointer={element:e,pointerId:t}}catch{this.capturedPointer=null}}endPointerCapture(){if(this.getDebugViewCamera()?.setOrbitInteractionEnabled(!0),!!this.capturedPointer){try{this.capturedPointer.element.releasePointerCapture(this.capturedPointer.pointerId)}catch{}this.capturedPointer=null}}};import{Vector2 as Cn}from"three";var Be=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Cn(e,t);return new P(h.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new be;if(e)return i.addCamera(e,e.name||"main"),i;let r=t.filter(n=>n!==void 0);if(r.length>0){for(let n of r){let s=n.cameraRef;i.addCamera(s,s.name||void 0)}for(let n=1;n<r.length;n++)i.addActiveCamera(r[n].cameraRef)}else{let n=this.createDefaultCamera();i.addCamera(n,"default")}return i}};var Ae=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"?$.emit("stage:loading:start",t):e.type==="progress"?$.emit("stage:loading:progress",t):e.type==="complete"&&$.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 ze=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)},E.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){U(e.options)||(this.scene?.addEntityGroup(e),Z(e),O(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),Z(i),O(i),U(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(E.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as Zi}from"@zylem/behaviors/core";var Sn=200,Fe=class a{static EMPTY_BEHAVIOR_LINKS=[];children=[];childrenMap=new Map;debugMap=new Map;detachedMap=new Map;pendingEntities=[];pendingPromises=[];_isLoaded=!1;entityAddedHandlers=[];behaviorSystems=[];behaviorSystemByKey=new Map;registeredSystemKeys=new Set;behaviorEntityIndex=new Map;behaviorLinksByUuid=new Map;scene=null;world=null;renderStrategy=null;camera=null;wasmStage=null;loadingDelegate;entityModelDelegate;constructor(e,t){this.loadingDelegate=e,this.entityModelDelegate=t}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}attach(e){this.scene=e.scene,this.world=e.world,this.renderStrategy=e.renderStrategy,this.camera=e.camera,this.wasmStage=e.world.simulation.adapter}async spawnEntity(e){if(!this.scene||!this.world)return;if(e instanceof Q){e.create();for(let i of e.getChildren())i instanceof V&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:g(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();Ot(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof V&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:g(),camera:this.camera}),this.tryRegisterRenderStrategy(t),T(t)||this.scene.addEntityGroup(t),O(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),Bt(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),T(e)||this.scene.addEntityGroup(e),O(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(G(e.options)!=="environment")return;let t=e.options.collision??{};t.static!==!0&&(console.warn(`category 'environment' forces static collision for entity '${e.name||e.uuid}'`),e.options.collision={...t,static:!0}),e.bodyDesc&&e.bodyDesc.kind!==Zi.Static&&(e.bodyDesc.kind=Zi.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof ne){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){return this.detachEntity(e)}detachEntity(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);if(!r)return!1;let n=typeof r.getPose=="function"?r.getPose():null;return this.unregisterBehaviorLinks(r),this.entityModelDelegate.unobserve(e),T(r)&&this.renderStrategy?.unregister(r),this.world.destroyEntity(r),r.group?this.scene.scene.remove(r.group):r.mesh&&this.scene.scene.remove(r.mesh),this.childrenMap.delete(e),this.debugMap.delete(e),this.detachedMap.set(e,{entity:r,position:n?.position??null,rotation:n?.rotation??null}),this.evictOldestDetached(),E.emit("entity:destroyed",{entityId:e}),!0}restoreEntity(e){if(!this.scene||!this.world)return!1;let t=this.detachedMap.get(e);if(!t)return!1;this.detachedMap.delete(e);let{entity:i,position:r,rotation:n}=t;return i.bodyDesc&&(r&&(i.bodyDesc.position=[r.x,r.y,r.z]),n&&(i.bodyDesc.rotation=[n.x,n.y,n.z,n.w])),this.registerBehaviorLinks(i),this.maybeAttachEntityPhysics(i),this.tryRegisterRenderStrategy(i),T(i)||this.scene.addEntityGroup(i),Lt(i),At(i),this.addEntityToStage(i),this.entityModelDelegate.observe(i),!0}isDetached(e){return this.detachedMap.has(e)}evictOldestDetached(){for(;this.detachedMap.size>Sn;){let e=this.detachedMap.keys().next();if(e.done)return;let t=this.detachedMap.get(e.value);if(this.detachedMap.delete(e.value),!!t){try{t.entity.nodeDestroy?.({me:t.entity,globals:g()})}catch{}B(t.entity)}}}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 zt?{...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(x(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();x(i)?this.handleEntityImmediatelyOrQueue(i):q(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}q(t)&&this.handlePromiseWithSpawnOnResolve(t)}}handleEntityImmediatelyOrQueue(e){this._isLoaded?this.spawnEntity(e):this.children.push(e)}handlePromiseWithSpawnOnResolve(e){this._isLoaded?e.then(t=>this.spawnEntity(t)).catch(t=>console.error("Failed to build async entity",t)):this.pendingPromises.push(e)}yieldToEventLoop(){return new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>e(),t.port2.postMessage(void 0)})}async runEntityLoadGenerator(){let t=0;if(this.pendingEntities.length){let n=[...this.pendingEntities];this.pendingEntities=[],this.enqueue(...n)}let i=[...this.pendingPromises];this.pendingPromises=[];let r=this.children.length+i.length;for(let n of this.children)await this.spawnEntity(n),t++,this.loadingDelegate.emitProgress(`Loaded ${n.name||"unknown"}`,t,r),t%5===0&&await this.yieldToEventLoop();for(let n of i){try{let s=await n;s&&await this.spawnEntity(s)}catch(s){console.error("Failed to resolve pending stage entity",s)}t++,this.loadingDelegate.emitProgress("Loaded async entity",t,r),t%5===0&&await this.yieldToEventLoop()}t%5!==0&&await this.yieldToEventLoop()}registerSystem(e){if(!this.world||!this.scene)return;let t;typeof e=="function"?t=e({world:this.world,scene:this.scene,getBehaviorLinks:i=>this.behaviorEntityIndex.get(i)??a.EMPTY_BEHAVIOR_LINKS,createEntity:qe,getGlobals:g}):t=e,this.behaviorSystems.push(t)}destroyAll(){for(let t of this.behaviorSystems)t.destroy?.();this.behaviorSystems.length=0,this.behaviorSystemByKey.clear(),this.registeredSystemKeys.clear(),this.behaviorEntityIndex.clear(),this.behaviorLinksByUuid.clear();let e=[];this.childrenMap.forEach(t=>{try{t.nodeDestroy({me:t,globals:g()})}catch{}B(t),e.push(t.uuid)}),this.detachedMap.forEach(({entity:t})=>{try{t.nodeDestroy?.({me:t,globals:g()})}catch{}B(t)}),this.detachedMap.clear(),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[];for(let t of e)E.emit("entity:destroyed",{entityId:t});this._isLoaded=!1,this.scene=null,this.world=null,this.renderStrategy=null,this.camera=null,this.wasmStage=null}registerBehaviorLinks(e){if(!this.world||!this.scene||typeof e?.getBehaviorRefs!="function")return;let t=e.getBehaviorRefs();if(!Array.isArray(t)||t.length===0)return;let i=[];for(let r of t)i.push(this.linkBehaviorRef(e,r));this.behaviorLinksByUuid.set(e.uuid,i)}linkBehaviorRef(e,t){let i=t.descriptor.key,r={entity:e,ref:t},n=this.behaviorEntityIndex.get(i);n||(n=new Set,this.behaviorEntityIndex.set(i,n)),n.add(r);let s=this.behaviorSystemByKey.get(i);if(!s&&!this.registeredSystemKeys.has(i)){let o=t.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:l=>this.behaviorEntityIndex.get(l)??a.EMPTY_BEHAVIOR_LINKS,createEntity:qe,getGlobals:g});s=o,this.behaviorSystems.push(o),this.behaviorSystemByKey.set(i,o),this.registeredSystemKeys.add(i)}return s?.attach?.(r),r}unlinkBehaviorLink(e){let t=e.ref?.descriptor?.key;if(!t)return;this.behaviorSystemByKey.get(t)?.detach?.(e);let i=this.behaviorEntityIndex.get(t);i&&(i.delete(e),i.size===0&&this.behaviorEntityIndex.delete(t))}syncBehaviorLinks(e){this.unregisterBehaviorLinks(e),this.registerBehaviorLinks(e)}attachBehaviorLink(e,t){if(!this.world||!this.scene||!e?.uuid)return!1;let i=this.behaviorLinksByUuid.get(e.uuid)??[];return i.some(r=>r.ref===t)?!1:(i.push(this.linkBehaviorRef(e,t)),this.behaviorLinksByUuid.set(e.uuid,i),!0)}detachBehaviorLink(e,t){let i=this.behaviorLinksByUuid.get(e?.uuid);if(!i)return!1;let r=i.findIndex(s=>s.ref===t);if(r===-1)return!1;let[n]=i.splice(r,1);return n&&this.unlinkBehaviorLink(n),i.length===0&&this.behaviorLinksByUuid.delete(e.uuid),!0}unregisterBehaviorLinks(e){let t=this.behaviorLinksByUuid.get(e?.uuid);if(t){for(let i of t)this.unlinkBehaviorLink(i);this.behaviorLinksByUuid.delete(e.uuid)}}};var Pn="Stage",Ie=class extends Ee{type=Pn;state={...Vt};gravity;world;scene;renderStrategy=null;debugDelegate=null;uuid;wrapperRef=null;camera;cameras=[];cameraRef=null;cameraManagerRef=null;rendererManager=null;cameraDelegate;loadingDelegate;entityModelDelegate;childUpdateParams={};entityDelegate;constructor(e=[]){super(),this.world=null,this.scene=null,this.uuid=wn(),this.cameraDelegate=new Be(this),this.loadingDelegate=new Ae,this.entityModelDelegate=new ze,this.entityDelegate=new Fe(this.loadingDelegate,this.entityModelDelegate);let t=Ci(e);this.camera=t.camera,this.cameras=t.cameras,this.entityDelegate.children=t.entities,t.asyncEntities.length&&this.entityDelegate.enqueue(...t.asyncEntities),this.state={...this.state,inputs:t.config.inputs,backgroundColor:t.config.backgroundColor,backgroundImage:t.config.backgroundImage,backgroundShader:t.config.backgroundShader,gravity:t.config.gravity,variables:t.config.variables,physicsRate:t.config.physicsRate,assetLoaders:t.config.assetLoaders,defaultLighting:t.config.defaultLighting,postProcessingEffects:t.config.postProcessingEffects,entities:[]},this.gravity=t.config.gravity??new Ui(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Gi?e:new Gi(e);Zt(i),Gt(t),Ut(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 Pe(e,r,this.state);let n=this.gravity??new Ui(0,0,0);if(this.world=await Se.create(n,this.state.physicsRate),this.scene.setup(),this.cameraManagerRef&&this.rendererManager){await this.scene.setupCameraManager(this.scene.scene,this.cameraManagerRef,this.rendererManager);let o=this.cameraManagerRef.primaryCamera;o&&(this.rendererManager.setPostProcessingEffects(this.state.postProcessingEffects??[]),this.rendererManager.setupPostProcessing(this.scene.scene,o.camera)),this.rendererManager.startRenderLoop(()=>{this.cameraManagerRef?.render(this.scene.scene)})}else await this.scene.setupCamera(this.scene.scene,r);let s=this.resolveRenderer(r);await L.configureGLTFRuntime({renderer:s,...Ce(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,o=>this.entityDelegate.handleLateModelReady(o)),this.renderStrategy=new de,this.renderStrategy.setScene(this.scene.scene),this.entityDelegate.attach({scene:this.scene,world:this.world,renderStrategy:this.renderStrategy,camera:r}),this.loadingDelegate.emitStart(),await this.entityDelegate.runEntityLoadGenerator(),this.entityDelegate.isLoaded=!0,this.loadingDelegate.emitComplete()}hasSetup=!1;_setup(e){if(!this.hasSetup){if(!this.scene||!this.world){this.logMissingEntities();return}this.debugDelegate=new Oe(this),this.hasSetup=!0}}_update(e){let{delta:t}=e;if(!this.scene||!this.world){this.logMissingEntities();return}let i=this.world,r=this.scene;w("behaviorSystems",()=>{for(let n of this.entityDelegate.behaviorSystems)n.update(void 0,t)}),w("entityLoop",()=>{for(let n of this.entityDelegate.childrenMap.values()){let s=this.childUpdateParams;s.delta=e.delta,s.inputs=e.inputs,s.globals=e.globals,s.camera=e.camera,s.stage=e.stage,s.game=e.game,s.me=n,n.nodeUpdate(s);let o=n;o.transformStore&&jt(o,o.transformStore),n.markedForRemoval&&this.entityDelegate.removeEntityByUuid(n.uuid)}}),w("worldUpdate",()=>{i.update(e)}),w("behaviorPostUpdate",()=>{for(let n of this.entityDelegate.behaviorSystems)n.postUpdate?.(void 0,t)}),w("syncRenderPoses",()=>{Pi({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),w("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),w("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),w("scene",()=>{r.update({delta:t})}),ci()}outOfLoop(){this.debugUpdate()}debugUpdate(){X()&&($e("debugUpdate"),this.debugDelegate?.update(),Xe())}_destroy(e){this.entityDelegate.destroyAll(),this.world?.destroy(),this.scene?.destroy(),this.debugDelegate?.dispose(),this.debugDelegate=null,this.entityModelDelegate.dispose(),this.renderStrategy?.dispose(),this.renderStrategy=null,this.rendererManager&&this.rendererManager.stopRenderLoop(),this.world=null,this.scene=null,this.cameraRef=null,this.cameraManagerRef=null,Nt(),B(this)}async spawnEntity(e){return this.entityDelegate.spawnEntity(e)}buildEntityState(e){return this.entityDelegate.buildEntityState(e)}onEntityAdded(e,t){return this.entityDelegate.onEntityAdded(e,t)}onLoading(e){return this.loadingDelegate.onLoading(e)}registerSystem(e){return this.entityDelegate.registerSystem(e),this}removeEntityByUuid(e){return this.entityDelegate.removeEntityByUuid(e)}getEntityByName(e){return this.entityDelegate.getEntityByName(e)}enqueue(...e){this.entityDelegate.enqueue(...e)}logMissingEntities(){console.warn("Zylem world or scene is null")}addCamera(e,t){return this.cameraManagerRef?this.cameraManagerRef.addCamera(e,t):(console.warn("ZylemStage: CameraManager not available. Ensure stage is loaded with a RendererManager."),null)}removeCamera(e){return this.cameraManagerRef?.removeCamera(e)??!1}setActiveCamera(e){return this.cameraManagerRef?.setActiveCamera(e)??!1}getCamera(e){return this.cameraManagerRef?.getCamera(e)??null}resize(e,t){this.scene&&this.scene.updateRenderer(e,t)}};import{proxy as En}from"valtio/vanilla";import{Vector3 as Mn}from"three";var xn={backgroundColor:se,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new Mn(0,0,0),variables:{}},_=En({...xn});function Ni(a){let e=Tn(),t={};return typeof a[0]=="object"&&(t=a.shift()??{}),[{...e,...t},...a]}function Tn(){return{backgroundColor:_.backgroundColor,backgroundImage:_.backgroundImage??null,inputs:_.inputs?{..._.inputs}:void 0,gravity:_.gravity,variables:_.variables?{..._.variables}:void 0}}var bt=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Pt;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];L.prepareGLTFRuntime(Ce(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=wt(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){oe.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new Ie(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(c=>{this.wrappedStage.onLoading(c)}),this.pendingLoadingCallbacks=[];let n=t instanceof y?t.cameraRef:t;await this.wrappedStage.load(e,n,i);let s=null,o=!1,l=()=>{if(o=!1,!s?.length){s=null;return}let c=s;s=null,oe.entities=[...oe.entities,...c]};this.wrappedStage.onEntityAdded(c=>{if(U(c.options))return;let d=this.wrappedStage.buildEntityState(c);s||(s=[]),s.push(d),o||(o=!0,queueMicrotask(l))},{replayExisting:!0}),this.applyLifecycleCallbacks()}applyLifecycleCallbacks(){this.wrappedStage&&(this.setupCallbacks.length>0&&(this.wrappedStage.setup=e=>{let t={...e,stage:this};this.setupCallbacks.forEach(i=>i(t))}),this.updateCallbacks.length>0&&(this.wrappedStage.update=e=>{let t={...e,stage:this};this.updateCallbacks.forEach(i=>i(t))}),this.destroyCallbacks.length>0&&(this.wrappedStage.destroy=e=>{let t={...e,stage:this};this.destroyCallbacks.forEach(i=>i(t))}))}async addEntities(e){this._pendingEntities.push(...e),this.wrappedStage&&this.wrappedStage.enqueue(...e)}add(...e){this.addToBlueprints(...e),this.addToStage(...e)}addToBlueprints(...e){this.wrappedStage||this.options.push(...e)}addToStage(...e){this.wrappedStage&&this.wrappedStage.enqueue(...e)}start(e){!this.wrappedStage||this.wrappedStage.hasSetup||this.wrappedStage.nodeSetup(e)}onUpdate(...e){return this.updateCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.update=t=>{let i={...t,stage:this};this.updateCallbacks.forEach(r=>r(i))}),this}onSetup(...e){return this.setupCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.setup=t=>{let i={...t,stage:this};this.setupCallbacks.forEach(r=>r(i))}),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.destroy=t=>{let i={...t,stage:this};this.destroyCallbacks.forEach(r=>r(i))}),this}onLoading(e){return this.wrappedStage?this.wrappedStage.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e)})}getEntityByName(e,t){return this.wrappedStage?.getEntityByName(e)}addCamera(e,t){let i=e instanceof y?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof y?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof y?this.wrappedStage?.setActiveCamera(e.cameraRef)??!1:this.wrappedStage?.setActiveCamera(e)??!1}getCamera(e){return this.wrappedStage?.getCamera(e)??null}dispatch(e,t){this.eventDelegate.dispatch(e,t),E.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function Hl(...a){let e=Ni(a);return new bt([...e])}export{zn as a,le as b,G as c,U as d,T as e,ce as f,de as g,Jn as h,h as i,D as j,he as k,R as l,A as m,j as n,z as o,be as p,y as q,ns as r,ps as s,vr as t,bt as u,Hl as v};
@@ -0,0 +1 @@
1
+ import{b as c,o as b}from"./chunk-2HSR5XDQ.js";import{B as y,E as g,H as f,K as x,N as z,j as s,m as p,p as d,s as h,v as u,y as m}from"./chunk-X7T7QRYP.js";import{a as w}from"./chunk-VUJXR5K5.js";import{Vector3 as S}from"three";var C='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">';function t(r){return`${C}${r}</svg>`}var i={box:t('<path d="M12 2.5 21 7v10l-9 4.5L3 17V7z"/><path d="M3 7l9 4.5L21 7"/><path d="M12 11.5v10"/>'),sphere:t('<circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="9" ry="3.5"/>'),cone:t('<path d="M12 3 20 18H4z"/><ellipse cx="12" cy="18" rx="8" ry="3"/>'),pyramid:t('<path d="M12 3 21 19H3z"/><path d="M12 3v16"/><path d="M3 19l9-5 9 5"/>'),cylinder:t('<ellipse cx="12" cy="6" rx="7" ry="3"/><path d="M5 6v12"/><path d="M19 6v12"/><ellipse cx="12" cy="18" rx="7" ry="3"/>'),pill:t('<rect x="7" y="3" width="10" height="18" rx="5"/><path d="M7 12h10"/>'),disk:t('<ellipse cx="12" cy="12" rx="9" ry="4"/><ellipse cx="12" cy="12" rx="3" ry="1.3"/>'),plane:t('<path d="M2 17 12 11l10 6-10 5z"/><path d="M12 11V4"/>'),zone:t('<rect x="3.5" y="3.5" width="17" height="17" rx="2" stroke-dasharray="3 2.5"/>'),rect:t('<rect x="3.5" y="6" width="17" height="12" rx="1.5"/>'),light:t('<circle cx="12" cy="9" r="4.5"/><path d="M12 2v1.5"/><path d="M12 14.5V22"/><path d="M4.9 4.9 6 6"/><path d="M19.1 4.9 18 6"/><path d="M2 9h1.5"/><path d="M20.5 9H22"/>')};function n(r,e,v,k,M,P){return{id:r,label:e,description:v,icon:k,group:"Shapes",tags:P,defaultProps:{size:{x:1,y:1,z:1}},create:M}}function o(r){let e=r.size;return new S(e?.x??1,e?.y??1,e?.z??1)}var T=[n("box","Box","Cuboid mesh with a matching box collider.",i.box,({position:r,props:e})=>s({position:r,size:o(e),...e}),["cube","block","platform","wall"]),n("sphere","Sphere","Ball mesh with a sphere collider.",i.sphere,({position:r,props:e})=>p({position:r,size:o(e),...e}),["ball","orb","round"]),n("cone","Cone","Cone mesh with a cone collider.",i.cone,({position:r,props:e})=>d({position:r,size:o(e),...e}),["spike","point"]),n("pyramid","Pyramid","Four-sided pyramid mesh and collider.",i.pyramid,({position:r,props:e})=>h({position:r,size:o(e),...e}),["tetra","spike"]),n("cylinder","Cylinder","Cylinder mesh with a matching collider.",i.cylinder,({position:r,props:e})=>u({position:r,size:o(e),...e}),["tube","pillar","column"]),n("pill","Pill","Capsule mesh with a capsule collider.",i.pill,({position:r,props:e})=>m({position:r,size:o(e),...e}),["capsule","character"]),n("disk","Disk","Flat cylinder, useful for pucks and platforms.",i.disk,({position:r,props:e})=>y({position:r,size:o(e),...e}),["puck","coin","circle"]),{id:"plane",label:"Plane",description:"Static ground plane with a tiled surface.",icon:i.plane,group:"Scene",tags:["ground","floor","terrain"],defaultProps:{size:{x:10,y:1,z:10}},create:({position:r,props:e})=>g({position:r,size:o(e),...e})},{id:"zone",label:"Zone",description:"Invisible sensor volume that reports overlaps.",icon:i.zone,group:"Scene",tags:["trigger","sensor","area"],defaultProps:{size:{x:2,y:2,z:2}},create:({position:r,props:e})=>f({position:r,size:o(e),...e})},{id:"rect",label:"Rect",description:"Flat rectangle for 2D scenes and UI panels.",icon:i.rect,group:"Scene",tags:["quad","panel","2d"],defaultProps:{size:{x:1,y:1,z:1}},create:({position:r,props:e})=>x({position:r,size:o(e),...e})},{id:"light",label:"Point Light",description:"Point light placed at the click position.",icon:i.light,group:"Scene",tags:["lamp","illumination"],defaultProps:{intensity:1},create:({position:r,props:e})=>z({type:"point",position:r,...e})}],a=null;function Y(){return a||(a=c(T),a)}var l=null;function j(){return l||(l=b("behavior",w),l)}export{T as a,Y as b,j as c};
@@ -0,0 +1 @@
1
+ import{b as w,c as E,d as x}from"./chunk-CBUQBP2U.js";import{d as s,h,j as y,l as b,o as f,q as g,s as m,t as S,u as v}from"./chunk-EVMLNMGU.js";import{subscribe as A}from"valtio/vanilla";import{announceBridgeReady as q,getZylemBridge as c}from"@zylem/bridge";function d(t,e){return[t[0]*e.x,t[1]*e.y,t[2]*e.z]}function P(t,e){let i=new Float32Array(t.length);for(let n=0;n<t.length;n+=3)i[n]=t[n]*e.x,i[n+1]=t[n+1]*e.y,i[n+2]=t[n+2]*e.z;return i}function z(t,e){let{shape:i}=t,n=t.offset?d(t.offset,e):t.offset,o;switch(i.type){case"box":o={type:"box",halfExtents:d(i.halfExtents,e)};break;case"sphere":o={type:"sphere",radius:i.radius*Math.max(e.x,e.y,e.z)};break;case"capsule":case"cylinder":case"cone":o={type:i.type,halfHeight:i.halfHeight*e.y,radius:i.radius*Math.max(e.x,e.z)};break;case"convexHull":o={type:"convexHull",vertices:P(i.vertices,e)};break;case"trimesh":o={type:"trimesh",vertices:P(i.vertices,e),indices:i.indices};break;case"heightfield":o={...i,scale:d(i.scale,e)};break;default:o=i;break}return{...t,shape:o,offset:n}}function V(t){if(!t.colliderBaseline){let e=t.colliderDescs.length?t.colliderDescs:t.colliderDesc?[t.colliderDesc]:[];t.colliderBaseline=e.map(i=>({...i}))}return t.colliderBaseline}function D(t){if(!t.colliderScaleDirty)return!1;t.colliderScaleDirty=!1;let e=V(t);if(!e.length)return!1;let i=t.getScale(),n=e.map(r=>z(r,i));t.colliderDescs=n,t.colliderDesc=n[0];let o=t.physicsWorldRef;if(!o)return!0;let a=t.getPose();return o.destroyEntity(t),a&&t.bodyDesc&&(t.bodyDesc.position=[a.position.x,a.position.y,a.position.z],t.bodyDesc.rotation=[a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w]),o.addEntity(t),!0}function C(t){return(t?.group??t?.mesh)?.scale}function G(t){let i=(typeof t?.getScale=="function"?t.getScale():void 0)??t?.scale??C(t)??{};return{x:i.x??1,y:i.y??1,z:i.z??1}}function F(t){let e=typeof t?.getPose=="function"?t.getPose():null;if(!e?.rotation)return;let{x:i,y:n,z:o,w:a}=e.rotation;return{x:i,y:n,z:o,w:a}}function u(t){let e=typeof t?.getPose=="function"?t.getPose():null,i=e?.position??{x:0,y:0,z:0},n=e?.rotation??{x:0,y:0,z:0,w:1};return{position:{x:i.x,y:i.y,z:i.z},rotation:x(n),quaternion:{x:n.x,y:n.y,z:n.z,w:n.w},scale:G(t)}}function T(t,e){if(typeof t?.setScale=="function"){t.setScale(e.x,e.y,e.z);return}C(t)?.set?.(e.x,e.y,e.z)}function U(t){!t||typeof t.getScale!="function"||D(t)}function I(t,e){if(!t)return!1;let i=e.quaternion??(e.rotation?E(e.rotation):void 0),n=!1;return(e.position||i)&&typeof t.setPose=="function"&&(n=t.setPose({position:e.position,rotation:i})),e.scale&&(T(t,e.scale),n=!0),n}function K(t){let e=t?.constructor?.type;return e?String(e).replace("Symbol(","").replace(")",""):"Unknown"}function R(t){let e=t;if(!e?.uuid)return;let i=c().channel;if(!i.hasSubscribers("entity:upsert"))return;let n=u(t);i.queue("entity:upsert",[{uuid:e.uuid,name:e.name||"Unnamed",type:K(t),position:n.position,rotation:n.rotation,scale:n.scale,quaternion:n.quaternion}])}function Z(t,e){c().channel.send("game:notice",{level:t,message:e})}function N(t,e,i){let n=[...new Set(t.swatches.map(r=>r.source))],o=[...new Set(e.map(r=>r.uuid))],a=o.length===1?i(o[0])||"entity":`${o.length} entities`;return`Apply ${n.join(", ")} to ${a}`}var k=class{channel;unsubscribes=[];host=null;editorKnown={};applyingSceneOperation=!1;constructor(){this.channel=c().channel}connect(e,i){this.disconnect(),this.host=e,this.unsubscribes.push(this.channel.on("debug:set",({enabled:n})=>{this.editorKnown.debug=n,s.enabled=n}),this.channel.on("tool:set",({tool:n})=>{y(n)}),this.channel.on("playback:set",({paused:n})=>{this.editorKnown.paused=n,h(n)}),this.channel.on("entity:select",({uuid:n})=>{this.editorKnown.selectedUuid=n,f(n)}),this.channel.on("entity:focus",({uuid:n})=>{w(n)}),this.channel.on("entity:transform",({uuid:n,position:o,rotation:a,quaternion:r,scale:p})=>{let l=this.host?.resolveEntity(n);if(!l)return;let B=u(l);if(I(l,{position:o,rotation:a,quaternion:r,scale:p}),p&&U(l),R(l),this.applyingSceneOperation)return;let O=u(l);this.channel.send("scene:operation",{opId:`tx-${n}-${Date.now().toString(36)}`,kind:"transform",label:`Set ${l.name||"entity"} transform`,entries:[{uuid:n,before:B,after:O}]})}),this.channel.on("entity:create",({typeId:n,props:o,pose:a})=>{this.host?.createEntity?.(n,o,a)}),this.channel.on("scene:operation:apply",({op:n,direction:o})=>{this.applyingSceneOperation=!0;try{this.host?.applySceneOperation?.(n,o)}finally{this.applyingSceneOperation=!1}}),this.channel.on("add:type:set",({typeId:n,props:o})=>{v(n,o??null)}),this.channel.on("snap:set",n=>{m(n)}),this.channel.on("grid:set",({visible:n})=>{S(n)}),this.channel.on("stage:variable:set",({key:n,value:o})=>{this.host?.setStageVariable?.(n,o)}),this.channel.on("pick:mode:set",({enabled:n})=>{b(n)}),this.channel.on("entity:pick",({requestId:n,ndc:o})=>{let a=this.host?.pickEntity?.(o)??null;this.channel.send("entity:pick:result",{requestId:n,hit:a})}),this.channel.on("entity:apply-swatch",n=>{this.handleApplySwatch(n)}),A(s,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),q(i)}disconnect(){for(let e of this.unsubscribes)e();this.unsubscribes=[],this.host=null,this.editorKnown={}}handleApplySwatch(e){let i=e.opId??`swatch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,n=this.host?.applySwatches?this.host.applySwatches({...e,opId:i}):{results:e.uuids.flatMap(a=>e.swatches.map(r=>({uuid:a,kind:r.kind,source:r.source,ok:!1,reason:"entity-not-found"}))),entries:[]},o=[...new Set(n.entries.map(a=>a.uuid))];e.select&&o.length>0&&g(o),n.entries.length>0&&!this.applyingSceneOperation&&this.channel.send("scene:operation",{opId:i,kind:"swatch",label:N(e,n.entries,a=>this.host?.resolveEntity(a)?.name),entries:n.entries}),this.channel.send("entity:swatch-applied",{opId:i,results:n.results})}publishDebugStateChanges(){let e={};s.paused!==this.editorKnown.paused&&(this.editorKnown.paused=s.paused,e.paused=s.paused),s.enabled!==this.editorKnown.debug&&(this.editorKnown.debug=s.enabled,e.debug=s.enabled),(e.paused!==void 0||e.debug!==void 0)&&this.publishStatus(e),(s.selectedEntityId!==this.editorKnown.selectedUuid||s.hoveredEntityId!==this.editorKnown.hoveredUuid)&&(this.editorKnown.selectedUuid=s.selectedEntityId,this.editorKnown.hoveredUuid=s.hoveredEntityId,this.channel.queue("entity:selection",{selectedUuid:s.selectedEntityId,hoveredUuid:s.hoveredEntityId,selectedUuids:[...s.selectedEntityIds]}))}wantsEntityUpdates(){return this.channel.hasSubscribers("entity:upsert")||this.channel.hasSubscribers("stage:snapshot")}wantsThumbnails(){return this.channel.hasSubscribers("entity:thumbnail")}onEditorAttached(e){return this.channel.onSubscriberAdded(i=>{if(i!=="entity:upsert"&&i!=="entity:thumbnail")return;let n=i==="entity:upsert"?"entity:thumbnail":"entity:upsert";this.channel.subscriberCount(n)>0||e()})}publishConfig(e){this.channel.send("game:config",e)}publishLoading(e){this.channel.send("game:loading",e)}publishStatus(e){this.channel.queue("game:status",e)}publishVariable(e){this.channel.send("game:variable",e)}publishNotice(e,i){this.channel.send("game:notice",{level:e,message:i})}publishStageSnapshot(e){this.channel.send("stage:snapshot",e)}queueEntityUpsert(e){e.length&&this.channel.queue("entity:upsert",e)}queueEntityRemoved(e){e.length&&this.channel.queue("entity:removed",{uuids:e})}queueThumbnails(e){e.length&&this.channel.queue("entity:thumbnail",e)}publishCatalog(e){this.channel.send("catalog:snapshot",{entities:e})}publishSceneOperation(e){this.channel.send("scene:operation",e)}wantsSceneOperations(){return this.channel.hasSubscribers("scene:operation")}};function J(t){c().channel.send("scene:operation",t)}export{D as a,G as b,F as c,u as d,K as e,Z as f,k as g,J as h};
@@ -0,0 +1 @@
1
+ import{getZylemBridge as p,announceBridgeReady as d,applySwatchesToSelection as i,BRIDGE_READY_EVENT as o}from"@zylem/bridge";export{p as a,d as b,i as c,o as d};
@@ -0,0 +1 @@
1
+ import{d as H,j as E}from"./chunk-6FGXC4T6.js";import{a as G,b as V}from"./chunk-AIQ6IVT5.js";import{a as M,b as Z,c as j}from"./chunk-EVYHPR3J.js";import{c as m,d as S,e as z,f as F,g as L,h as c,i as U,j as N}from"./chunk-7WRQ2UAN.js";import{p as X}from"./chunk-XRP4JJXL.js";import{StageBodyKind as W}from"@zylem/behaviors/core";import{Color as be,Vector2 as Y,Vector3 as K}from"three";function g(i){if(!i||typeof i!="object")return!1;let e=Object.getPrototypeOf(i);return e===Object.prototype||e===null}function l(i){if(i==null||typeof i=="function"||typeof i!="object")return i;if(i instanceof be||i instanceof Y||i instanceof K)return i.clone();if(i instanceof Float32Array)return new Float32Array(i);if(Array.isArray(i))return i.map(e=>l(e));if(g(i)){let e={};for(let[t,o]of Object.entries(i))t!=="_builders"&&(e[t]=l(o));return e}return i}function d(i,e){let t=l(i);if(!e)return t;if(!g(t)||!g(e))return l(e);let o=t;for(let[n,s]of Object.entries(e)){if(n==="_builders"||s===void 0)continue;let r=o[n];if(n==="shader"){o[n]=l(s);continue}if(r instanceof Y&&z(s)){o[n]=U(s,r);continue}if(r instanceof K&&F(s)){o[n]=N(s,r);continue}if(g(r)&&g(s)){o[n]=d(r,s);continue}o[n]=l(s)}return o}function $(i){return i&&i.__kind==="collision"}function k(i){return i.cloneComponent()}function Ce(i,e){let t={kind:i?W.Static:W.Dynamic,position:[0,0,0],gravityScale:e.gravityScale??1,canSleep:e.canSleep??!1,ccdEnabled:e.ccdEnabled??!0},o=M(e.lockRotations);o&&(t.lockRotation=o);let n=M(e.lockTranslations);return n&&(t.lockTranslation=n),t}function ge(i,e){if(e.offset){let t=c(e.offset,m);i.offset=[t.x,t.y,t.z]}e.sensor&&(i.sensor=!0),e.collisionType&&(i.collisionGroups=Z(e.collisionType,e.collisionFilter))}function h(i,e,t){return ge(i,e),{__kind:"collision",bodyDesc:Ce(e.static??!1,e),colliderDesc:i,cloneComponent:t}}function ve(i={}){let e=c(i.size,S),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}},o=l(i);return h(t,i,()=>ve(o))}function xe(i={}){let e={shape:{type:"sphere",radius:i.radius??1}},t=l(i);return h(e,i,()=>xe(t))}function Ee(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>Ee(n))}function Oe(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>Oe(n))}function Pe(i={}){let e=Math.max(i.radiusTop??1,i.radiusBottom??1),o={shape:{type:"cylinder",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>Pe(n))}function Re(i={}){let e=i.radius??.5,o={shape:{type:"capsule",halfHeight:(i.length??1)/2,radius:e}},n=l(i);return h(o,i,()=>Re(n))}function Be(i={}){let e=L(i.tile,{x:10,y:10}),t=i.subdivisions??10,o=(t+1)*(t+1),n=i.heightData??new Float32Array(o),s={shape:{type:"heightfield",rows:t,cols:t,heights:n,scale:[e.x,1,e.y]}},r={...i,static:i.static??!0},a=l(r);return h(s,r,()=>Be(a))}function we(i={}){let e=c(i.size,S),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]},sensor:!0},o={...i,static:i.static??!0,sensor:!0},n=l(o);return h(t,o,()=>we(n))}import{Mesh as ae,ShaderMaterial as Ve,Group as ze}from"three";var Q=import.meta.env.VITE_DEBUG_FLAG==="true";import{nanoid as Se}from"nanoid";var p=class i{parent=null;children=[];options;uuid="";name="";markedForRemoval=!1;lifecycleCallbacks={setup:[],loaded:[],update:[],destroy:[],cleanup:[]};trackLifecycleRegistrations=!1;userLifecycleRegistrations=[];constructor(e=[]){let t=e.filter(o=>!(o instanceof i)).reduce((o,n)=>({...o,...n}),{});this.options=t,this.uuid=Se()}onSetup(...e){return this.lifecycleCallbacks.setup.push(...e),this.recordLifecycleRegistration("onSetup",e),this}onLoaded(...e){return this.lifecycleCallbacks.loaded.push(...e),this.recordLifecycleRegistration("onLoaded",e),this}onUpdate(...e){return this.lifecycleCallbacks.update.push(...e),this.recordLifecycleRegistration("onUpdate",e),this}onDestroy(...e){return this.lifecycleCallbacks.destroy.push(...e),this.recordLifecycleRegistration("onDestroy",e),this}onCleanup(...e){return this.lifecycleCallbacks.cleanup.push(...e),this.recordLifecycleRegistration("onCleanup",e),this}prependSetup(...e){return this.lifecycleCallbacks.setup.unshift(...e),this.recordLifecycleRegistration("prependSetup",e),this}prependUpdate(...e){return this.lifecycleCallbacks.update.unshift(...e),this.recordLifecycleRegistration("prependUpdate",e),this}setParent(e){this.parent=e}getParent(){return this.parent}add(e){this.children.push(e),e.setParent(this)}remove(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),e.setParent(null))}getChildren(){return this.children}isComposite(){return this.children.length>0}enableUserLifecycleTracking(){this.trackLifecycleRegistrations=!0}replayUserLifecycleRegistrationsTo(e,t){for(let o of this.userLifecycleRegistrations){let n=t?o.callbacks.map(s=>t(s)):[...o.callbacks];switch(o.method){case"onSetup":e.onSetup(...n);break;case"onLoaded":e.onLoaded(...n);break;case"onUpdate":e.onUpdate(...n);break;case"onDestroy":e.onDestroy(...n);break;case"onCleanup":e.onCleanup(...n);break;case"prependSetup":e.prependSetup(...n);break;case"prependUpdate":e.prependUpdate(...n);break}}}cloneChildrenInto(e){for(let t of this.children)e.add(Me(t))}nodeSetup(e){this.markedForRemoval=!1,typeof this._setup=="function"&&this._setup(e);for(let t of this.lifecycleCallbacks.setup)t(e);this.children.forEach(t=>t.nodeSetup(e))}nodeUpdate(e){if(!this.markedForRemoval){typeof this._update=="function"&&this._update(e),typeof this._tickActions=="function"&&this._tickActions(e.delta);for(let t of this.lifecycleCallbacks.update)t(e);this.children.forEach(t=>t.nodeUpdate(e))}}nodeDestroy(e){if(!this.markedForRemoval){this.children.forEach(t=>t.nodeDestroy(e));for(let t of this.lifecycleCallbacks.destroy)t(e);typeof this._destroy=="function"&&this._destroy(e),this.markedForRemoval=!0;for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}}async nodeLoaded(e){typeof this._loaded=="function"&&await this._loaded(e);for(let t of this.lifecycleCallbacks.loaded)t(e)}nodeCleanup(e){this.children.forEach(t=>t.nodeCleanup?.(e));for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}getOptions(){return this.options}setOptions(e){this.options={...this.options,...e}}recordLifecycleRegistration(e,t){!this.trackLifecycleRegistrations||t.length===0||this.userLifecycleRegistrations.push({method:e,callbacks:[...t]})}};function Me(i){let e=i?.clone;if(typeof e!="function")throw new Error(`Cannot clone child node "${i.name||i.uuid||"unknown"}": missing clone() support.`);return e.call(i)}import{createTransformStore as Fe}from"@zylem/behaviors/core";import{makeMoveable as ke}from"@zylem/behaviors/core";function q(i){let e=ke(i);return X(e)}import{clearVelocityIntent as le}from"@zylem/behaviors/core";import{Color as Ie,Vector3 as Ge}from"three";import{Quaternion as De}from"three";var J=Symbol("explicitSpawnPosition"),O=new De;function ee(i){return i.filter(e=>!(e instanceof p)).some(e=>e!=null&&typeof e=="object"&&"position"in e)}function te(i){i[J]=!0}function Te(i){return i._spawnPositionExplicit?!0:i.options[J]===!0}function _e(i){return i.options.hideUntilPositioned!==!1}function ie(i){return i._spawnPlacementPending===!0}function Ae(i){return i._spawnPositionExplicit===!0||i._spawnPlacementReady===!0}function P(i){let e=i.group??i.mesh;if(e){if(i.physicsAttached&&i.body)try{let t=i.body.translation();e.position.set(t.x,t.y,t.z);return}catch{}if(i.wasmStageRef&&(i.runtimeHandle??-1)>=0){let t=i.wasmStageRef.getPose(i.runtimeHandle);if(t){e.position.set(t.position[0],t.position[1],t.position[2]);return}}if(i.options.position){let t=c(i.options.position,m);e.position.set(t.x,t.y,t.z)}}}function oe(i){let e=i.group??i.mesh;if(!(!e||i.controlledRotation)){if(i.physicsAttached&&i.body)try{let t=i.body.rotation();O.set(t.x,t.y,t.z,t.w),e.setRotationFromQuaternion(O);return}catch{}if(i.wasmStageRef&&(i.runtimeHandle??-1)>=0){let t=i.wasmStageRef.getPose(i.runtimeHandle);t&&(O.set(t.rotation[0],t.rotation[1],t.rotation[2],t.rotation[3]),e.setRotationFromQuaternion(O))}}}function v(i,e){i.group&&(i.group.visible=e),i.mesh&&(i.mesh.visible=e)}function yt(i){if(i._spawnInProgress=!0,i._spawnPlacementReady=!1,!_e(i)){i._spawnPlacementPending=!1;return}i._spawnPositionExplicit=Te(i),i._spawnPlacementPending=!0,v(i,!1)}function bt(i){i._spawnInProgress=!1}function ne(i){i._spawnPlacementReady=!0}function D(i){if(i._spawnPlacementPending){if(P(i),i._spawnPlacementPending=!1,i.options.visible===!1){v(i,!1);return}v(i,!0)}}function Ct(i){!ie(i)||i.options.hideUntilPositioned===!0&&!Ae(i)||D(i)}function se(i){P(i),i._spawnPlacementPending=!1,v(i,!0)}function gt(i){ie(i)&&v(i,!1)}var re={position:new Ge(0,0,0),material:{color:new Ie("#ffffff"),shader:H},collision:{static:!1}};function Bt(i,e){let t=i.filter(n=>!(n instanceof p)),o=d(e);for(let n of t)o=d(o,n);return ee(i)&&te(o),o}function Le(i){return i!=null&&typeof i=="object"}function ce(i){return{phase:i?.phase??"stay",cooldownMs:i?.cooldownMs}}function Ue(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var T=class extends p{group;mesh;materials;bodyDesc=null;body=null;physicsAttached=!1;physicsWorldRef=null;colliderDesc;custom={};colliderBaseline=null;colliderScaleDirty=!1;colliderDescs=[];compoundMeshes=[];debugInfo={};debugMaterial;collisionDelegate={collision:[],cooldowns:new Map,nextId:0};collisionType;packKey=null;bundleKey=null;instanceId=-1;isInstanced=!1;isBundled=!1;runtimeHandle=-1;runtimeAttached=!1;wasmStageRef=null;eventDelegate=new G;behaviorRefs=[];cloneFactory=null;trackAddedComponents=!1;trackedComponents=[];transformStore;_scale={x:1,y:1,z:1};_spawnPlacementPending=!1;_spawnPositionExplicit=!1;_spawnPlacementReady=!1;_spawnInProgress=!1;moveX;moveY;moveZ;moveXY;moveXZ;move;resetVelocity;moveForwardXY;getPosition;getVelocity;setPosition;setPositionX;setPositionY;setPositionZ;wrapAroundXY;wrapAround3D;rotateInDirection;rotateYEuler;rotateEuler;rotateX;rotateY;rotateZ;setRotationY;setRotationX;setRotationZ;setRotationDegrees;setRotationDegreesY;setRotationDegreesX;setRotationDegreesZ;setRotation;getRotation;constructor(){super(),this.transformStore=Fe(),q(this),this.wrapSpawnPlacementMutators()}wrapSpawnPlacementMutators(){let e=()=>{ne(this),!this._spawnInProgress&&(P(this),D(this))},t=r=>(a,f,y)=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(r(a,f,y),e())},o=r=>a=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(r(a),e())};this.setPosition=t(this.setPosition.bind(this)),this.setPositionX=o(this.setPositionX.bind(this)),this.setPositionY=o(this.setPositionY.bind(this)),this.setPositionZ=o(this.setPositionZ.bind(this));let n=()=>{this._spawnInProgress||oe(this)},s=this.setPose.bind(this);this.setPose=r=>{let a=s(r);return a&&(r.position!=null&&e(),r.rotation!=null&&n(),a)}}reveal(){this.options.visible=!0,se(this)}getPose(){if(this.wasmStageRef&&this.runtimeHandle>=0){let n=this.wasmStageRef.getPose(this.runtimeHandle);if(n)return{position:{x:n.position[0],y:n.position[1],z:n.position[2]},rotation:{x:n.rotation[0],y:n.rotation[1],z:n.rotation[2],w:n.rotation[3]}}}let e=this.body;if(!e)return null;let t=e.translation(),o=e.rotation();return{position:{x:t.x,y:t.y,z:t.z},rotation:{x:o.x,y:o.y,z:o.z,w:o.w}}}setPose(e){if(this.wasmStageRef&&this.runtimeHandle>=0){let o=!0;if(e.position){let n=c(e.position);o=this.wasmStageRef.setPosition(this.runtimeHandle,n.x,n.y,n.z)&&o}if(e.rotation){let{x:n,y:s,z:r,w:a}=e.rotation;o=this.wasmStageRef.setRotation(this.runtimeHandle,n,s,r,a)&&o}return o&&this.body?.markPoseDiscontinuity(),o}let t=this.body;if(!t)return!1;if(e.position){let o=c(e.position);t.setTranslation({x:o.x,y:o.y,z:o.z},!0)}return e.rotation&&t.setRotation(e.rotation,!0),!0}getScale(){return{...this._scale}}setScale(e,t,o){this._scale={x:e,y:t,z:o},(this.group??this.mesh)?.scale.set(e,t,o),this.colliderScaleDirty=!0}add(...e){for(let t of e)t instanceof ae?(this.addMeshComponent(t),this.trackComponent(t)):$(t)?(this.addCollisionComponent(t),this.trackComponent(t)):super.add(t);return this}addMeshComponent(e){if(this.mesh)this.compoundMeshes.push(e),this.group||(this.group=new ze,this.group.add(this.mesh)),this.group.add(e);else if(this.mesh=e,this.materials||(this.materials=[]),e.material){let t=e.material;Array.isArray(t)?this.materials.push(...t):this.materials.push(t)}}addCollisionComponent(e){if(this.bodyDesc)this.colliderDescs.push(e.colliderDesc);else{this.bodyDesc=e.bodyDesc,this.colliderDesc=e.colliderDesc,this.colliderDescs.push(e.colliderDesc);let t=c(this.options?.position,m);this.bodyDesc.position=[t.x,t.y,t.z]}}trackComponent(e){if(this.trackAddedComponents){if(e instanceof ae){this.trackedComponents.push({kind:"mesh",component:pe(e)});return}this.trackedComponents.push({kind:"collision",component:k(e)})}}_actions=[];runAction(e){return this._actions.push(e),e}action(e){return e.persistent=!0,this._actions.push(e),e}clearActions(){this._actions.length=0}_tickActions(e){if(this._actions.length===0)return;let t=this.transformStore;t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,le(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1;for(let o=this._actions.length-1;o>=0;o--){let n=this._actions[o];n.tick(this,e),n.done&&!n.persistent&&this._actions.splice(o,1)}this._actions.length===0&&(t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,le(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1)}create(){return this.name=this.options.name||"",this}clone(e){if(!this.cloneFactory)throw new Error(`Cannot clone ${this.constructor.name}: clone() is only supported for entities created by official factory helpers.`);let t=this.cloneFactory(d(this.options,e)),o=this.copyBehaviorRefsTo(t),n=r=>He(r,o);this.replayUserLifecycleRegistrationsTo(t,n);let s=this.getCollisionRegistrations();if(s.length>0)for(let r of s)t.onCollision(n(r.callback),r.options);for(let r of this.trackedComponents){if(r.kind==="mesh"){t.add(pe(r.component));continue}t.add(k(r.component))}return this.cloneChildrenInto(t),t}finalizeCloneSupport(e){return this.cloneFactory=e,this.enableUserLifecycleTracking(),this.trackAddedComponents=!0,this}onCollision(...e){let t=[...this.collisionDelegate.collision??[]],o=this.collisionDelegate.nextId??0;if(e.length===1||e.length===2&&(e[1]==null||Le(e[1]))){let n=e[0];if(!n)return this;let s=e[1];return t.push({id:o,callback:n,options:ce(s)}),o+=1,this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}for(let n of e)t.push({id:o,callback:n,options:ce()}),o+=1;return this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}use(e,t){let o={descriptor:e,options:{...e.defaultOptions,...t}};this.behaviorRefs.push(o);let n={getFSM:()=>o.fsm??null,getOptions:()=>o.options,ref:o},s=e.createHandle?.(o)??{};return{...n,...s}}getBehaviorRefs(){return this.behaviorRefs}getBehaviorRef(e){return this.behaviorRefs.find(t=>t.descriptor.key===e.key)??null}hasBehavior(e){return this.getBehaviorRef(e)!==null}removeBehavior(e){let t="descriptor"in e?this.behaviorRefs.indexOf(e):this.behaviorRefs.findIndex(n=>n.descriptor.key===e.key);if(t===-1)return null;let[o]=this.behaviorRefs.splice(t,1);return o??null}restoreBehaviorRef(e){this.behaviorRefs.includes(e)||this.behaviorRefs.push(e)}getCollisionCallbacks(){return this.getCollisionRegistrations().map(e=>e.callback)}getCollisionRegistrations(){return(this.collisionDelegate.collision??[]).map(e=>({id:e.id,callback:e.callback,options:{...e.options}}))}copyBehaviorRefsTo(e){let t=new Map;for(let o of this.behaviorRefs){e.use(o.descriptor,l(o.options));let n=e.getBehaviorRefs().at(-1);n&&t.set(o,n)}return t}_setup(e){for(let t=this._actions.length-1;t>=0;t--){let o=this._actions[t];o.done&&!o.persistent?this._actions.splice(t,1):o.reset()}}async _loaded(e){}_update(e){this.updateMaterials(e)}_destroy(e){}_cleanup(e){this.disposeEvents();for(let t of this.compoundMeshes)t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(o=>o.dispose()):t.material?.dispose();this.compoundMeshes.length=0,this.debugMaterial?.dispose(),this.debugMaterial=void 0,this.group?.removeFromParent()}_collision(e,t,o={phase:"stay",nowMs:Ue()}){if(!this.collisionDelegate.collision?.length)return;let n=this.collisionDelegate.cooldowns??new Map;this.collisionDelegate.cooldowns=n;for(let s of this.collisionDelegate.collision){if(s.options.phase!==o.phase)continue;let r=s.options.cooldownMs;if(r!=null){let a=`${s.id}:${e.uuid}`,f=n.get(a);if(f!=null&&o.nowMs-f<r)continue;n.set(a,o.nowMs)}s.callback({entity:this,other:e,globals:t})}}hasMaterial(){return this.mesh!==void 0||this.compoundMeshes.length>0}getMaterials(){return this.materials?[...this.materials]:[]}setMaterial(e,t={}){if(!this.hasMaterial())return null;let o=new E,n=this.constructor.type??Symbol.for("zylem:entity");return o.build(e,n),this.replaceMaterials(o.materials,t)}replaceMaterials(e,t={}){if(!this.hasMaterial()||e.length===0)return null;let{disposePrevious:o=!0}=t,n=this.materials?[...this.materials]:[],s=r=>{Array.isArray(r.material)?r.material=r.material.map((a,f)=>e[f%e.length]):r.material=e[0]};this.mesh&&s(this.mesh);for(let r of this.compoundMeshes)s(r);if(this.materials=[...e],o)for(let r of n)e.includes(r)||r.dispose();return n}updateMaterials(e){if(this.materials?.length)for(let t of this.materials)t instanceof Ve&&t.uniforms&&t.uniforms.iTime&&(t.uniforms.iTime.value+=e.delta)}buildInfo(){let e={};return e.name=this.name,e.uuid=this.uuid,e}dispatch(e,t){this.eventDelegate.dispatch(e,t),V.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}disposeEvents(){this.eventDelegate.dispose()}};function Ne(i){let e=new T;return e.options={...re,...i},_(e,t=>Ne(t??{}))}function pe(i){let e=i.clone(!0),t=[],o=[];i.traverse(n=>t.push(n)),e.traverse(n=>o.push(n));for(let n=0;n<t.length;n++){let s=t[n],r=o[n];s?.geometry?.clone&&(r.geometry=s.geometry.clone()),s?.material&&(r.material=Array.isArray(s.material)?s.material.map(a=>a.clone()):s.material.clone())}return e}function He(i,e){return e.size===0?i:((...t)=>{let o=Array.from(e.entries()).map(([n,s])=>({sourceRef:n,options:n.options,fsm:n.fsm,hasFSM:Object.prototype.hasOwnProperty.call(n,"fsm"),targetRef:s}));for(let n of o)n.sourceRef.options=n.targetRef.options,n.targetRef.fsm===void 0?delete n.sourceRef.fsm:n.sourceRef.fsm=n.targetRef.fsm;try{return i(...t)}finally{for(let n=o.length-1;n>=0;n--){let s=o[n];s.sourceRef.options=s.options,s.hasFSM?s.sourceRef.fsm=s.fsm:delete s.sourceRef.fsm}}})}function _(i,e){return i.finalizeCloneSupport(e),i}function ue(i){return typeof i?.load=="function"&&typeof i?.data=="function"}var R=class{entityReference;constructor(e){this.entityReference=e}load(){this.entityReference.load&&this.entityReference.load()}data(){return this.entityReference.data?this.entityReference.data():null}};function ei(i){let{args:e,defaultConfig:t,EntityClass:o,BuilderClass:n,entityType:s,MeshBuilderClass:r,CollisionBuilderClass:a,cloneFactory:f}=i,y=null,b,A=e.findIndex(u=>!(u instanceof p));A!==-1&&(b=e.splice(A,1).find(C=>!(C instanceof p)));let ye=b?d(t,b):d(t);e.push(ye);for(let u of e){if(u instanceof p)continue;let C=null,w=new o(u);try{if(ue(w)){let x=new R(w);x.load(),C=x.data()}}catch(x){console.error("Error creating entity with loader:",x)}y=new n(u,w,r?new r(C):null,a?new a(C):null),u.material&&y.withMaterial(u.material,s)}if(!y)throw new Error(`missing options for ${String(s)}, builder is not initialized.`);let I=y.build();return b!=null&&typeof b=="object"&&"position"in b&&(I._spawnPositionExplicit=!0),_(I,u=>f(u))}import{BufferGeometry as Ze,Mesh as de,Color as je}from"three";import{Mesh as Xe}from"three";var B=class{_build(e,t,o){let n=new Xe(t,o.at(-1));return n.position.set(0,0,0),n.castShadow=!0,n.receiveShadow=!0,n}_postBuild(){}};var fe=class extends j{},me=class extends B{build(e){return new Ze}postBuild(){}},he=class{meshBuilder;collisionBuilder;materialBuilder;options;entity;constructor(e,t,o,n){this.options=e,this.entity=t,this.meshBuilder=o,this.collisionBuilder=n,this.materialBuilder=new E;let s={meshBuilder:this.meshBuilder,collisionBuilder:this.collisionBuilder,materialBuilder:this.materialBuilder};this.options._builders=s,t&&t.options&&(t.options._builders=s)}withPosition(e){return this.options.position=e,this}withMaterial(e,t){return this.materialBuilder&&this.materialBuilder.build(e,t),this}applyMaterialToGroup(e,t){e.traverse(o=>{o instanceof de&&o.type==="SkinnedMesh"&&t[0]&&!o.material.map&&(o.material=t[0]),o.castShadow=!0,o.receiveShadow=!0})}build(){let e=this.entity;if(this.materialBuilder&&(e.materials=this.materialBuilder.materials),this.meshBuilder&&e.materials){let t=this.meshBuilder.build(this.options);e.mesh=this.meshBuilder._build(this.options,t,e.materials),this.meshBuilder.postBuild()}if(e.group&&e.materials&&this.applyMaterialToGroup(e.group,e.materials),this.collisionBuilder){this.collisionBuilder.withCollision(this.options?.collision||{});let[t,o]=this.collisionBuilder.build(this.options);e.bodyDesc=t,e.colliderDesc=o,e.colliderDescs.push(o);let{x:n,y:s,z:r}=c(this.options.position,m);e.bodyDesc.position=[n,s,r]}if(this.options.collisionType&&(e.collisionType=this.options.collisionType),this.options.color instanceof je){let t=o=>{let n=o;n&&n.color&&n.color.set&&n.color.set(this.options.color)};if(e.materials?.length)for(let o of e.materials)t(o);if(e.mesh&&e.mesh.material){let o=e.mesh.material;Array.isArray(o)?o.forEach(t):t(o)}e.group&&e.group.traverse(o=>{if(o instanceof de&&o.material){let n=o.material;Array.isArray(n)?n.forEach(t):t(n)}})}return e}};export{p as a,d as b,ve as c,xe as d,Ee as e,Oe as f,Pe as g,Re as h,Be as i,we as j,ie as k,P as l,yt as m,bt as n,Ct as o,se as p,gt as q,re as r,Bt as s,T as t,Ne as u,_ as v,fe as w,me as x,he as y,ei as z};
@@ -0,0 +1 @@
1
+ import{a as e}from"./chunk-WOT6VMZA.js";var o={};e(o,{BoundaryRicochet3DCoordinator:()=>t,BoundaryRicochetCoordinator:()=>r,CooldownBehavior:()=>n,Destructible3DBehavior:()=>i,DestructibleMesh:()=>a,FirstPersonBehavior:()=>c,FirstPersonEvent:()=>p,FirstPersonFSM:()=>l,FirstPersonPresentation:()=>m,FirstPersonShooterCoordinator:()=>D,FirstPersonState:()=>s,FractureOptions:()=>u,Jumper2DBehavior:()=>h,Jumper2DEvent:()=>d,Jumper2DFSM:()=>S,Jumper2DState:()=>C,Jumper3DBehavior:()=>P,Jumper3DEvent:()=>y,Jumper3DFSM:()=>B,Jumper3DState:()=>v,MultidirectionalSpaceShooterCoordinator:()=>f,ParticleEmitterBehavior:()=>M,Platformer2DBehavior:()=>F,Platformer2DEvent:()=>E,Platformer2DFSM:()=>R,Platformer2DState:()=>W,Platformer3DBehavior:()=>g,Platformer3DEvent:()=>T,Platformer3DFSM:()=>O,Platformer3DState:()=>J,Ricochet2DBehavior:()=>w,Ricochet2DEvent:()=>I,Ricochet2DFSM:()=>b,Ricochet2DState:()=>H,Ricochet3DBehavior:()=>x,Ricochet3DEvent:()=>k,Ricochet3DFSM:()=>A,Ricochet3DState:()=>V,ScreenVisibilityBehavior:()=>q,ScreenVisibilityFSM:()=>z,ScreenWrapBehavior:()=>L,ScreenWrapEvent:()=>j,ScreenWrapFSM:()=>G,ScreenWrapState:()=>U,Shooter2DBehavior:()=>K,ThrusterBehavior:()=>N,ThrusterEvent:()=>Q,ThrusterFSM:()=>X,ThrusterState:()=>Y,TopDownMovementBehavior:()=>Z,TopDownShooterCoordinator:()=>_,WorldBoundary2DBehavior:()=>$,WorldBoundary2DEvent:()=>ee,WorldBoundary2DFSM:()=>oe,WorldBoundary2DState:()=>te,WorldBoundary3DBehavior:()=>re,WorldBoundary3DEvent:()=>ne,WorldBoundary3DFSM:()=>ie,WorldBoundary3DState:()=>ae,computeWorldBoundary2DHits:()=>ce,computeWorldBoundary3DHits:()=>pe,createFirstPersonInputComponent:()=>le,createFirstPersonMovementComponent:()=>De,createFirstPersonStateComponent:()=>se,createJumpConfig2D:()=>me,createJumpConfig3D:()=>ue,createJumpInput2D:()=>he,createJumpInput3D:()=>de,createJumpState2D:()=>Se,createJumpState3D:()=>Ce,createPhysicsBodyComponent:()=>Pe,createPlatformer2DInputComponent:()=>ye,createPlatformer2DMovementComponent:()=>Be,createPlatformer2DStateComponent:()=>ve,createPlatformer3DInputComponent:()=>fe,createPlatformer3DMovementComponent:()=>Me,createPlatformer3DStateComponent:()=>Fe,createShooter2DStateComponent:()=>Ee,createThrusterInputComponent:()=>Re,createThrusterMovementComponent:()=>We,createThrusterStateComponent:()=>ge,createTopDownMovementComponent:()=>Te,createTopDownMovementInputComponent:()=>Oe,createTopDownMovementStateComponent:()=>Je,createTransformComponent:()=>we,defineBehavior:()=>Ie,fireCooldown:()=>be,fireShooter2DIfRequested:()=>He,getCooldown:()=>xe,getCooldownStore:()=>ke,getEntityFacingAngle2D:()=>Ae,hasAnyWorldBoundary2DHit:()=>Ve,hasAnyWorldBoundary3DHit:()=>qe,particleEffect:()=>ze,particlePresets:()=>Le,registerCooldown:()=>je,resetCooldown:()=>Ge,resolveAim2D:()=>Ue,tickCooldowns:()=>Ke,updateBoundaryRicochet:()=>Ne,useBehavior:()=>Qe});import{BoundaryRicochet3DCoordinator as t,BoundaryRicochetCoordinator as r,CooldownBehavior as n,Destructible3DBehavior as i,DestructibleMesh as a,FirstPersonBehavior as c,FirstPersonEvent as p,FirstPersonFSM as l,FirstPersonShooterCoordinator as D,FirstPersonState as s,FirstPersonPresentation as m,FractureOptions as u,Jumper2DBehavior as h,Jumper2DEvent as d,Jumper2DFSM as S,Jumper2DState as C,Jumper3DBehavior as P,Jumper3DEvent as y,Jumper3DFSM as B,Jumper3DState as v,MultidirectionalSpaceShooterCoordinator as f,ParticleEmitterBehavior as M,Platformer2DBehavior as F,Platformer2DEvent as E,Platformer2DFSM as R,Platformer2DState as W,Platformer3DBehavior as g,Platformer3DEvent as T,Platformer3DFSM as O,Platformer3DState as J,Ricochet2DBehavior as w,Ricochet2DEvent as I,Ricochet2DFSM as b,Ricochet2DState as H,Ricochet3DBehavior as x,Ricochet3DEvent as k,Ricochet3DFSM as A,Ricochet3DState as V,ScreenVisibilityBehavior as q,ScreenVisibilityFSM as z,ScreenWrapBehavior as L,ScreenWrapEvent as j,ScreenWrapFSM as G,ScreenWrapState as U,Shooter2DBehavior as K,ThrusterBehavior as N,ThrusterEvent as Q,ThrusterFSM as X,ThrusterState as Y,TopDownMovementBehavior as Z,TopDownShooterCoordinator as _,WorldBoundary2DBehavior as $,WorldBoundary2DEvent as ee,WorldBoundary2DFSM as oe,WorldBoundary2DState as te,WorldBoundary3DBehavior as re,WorldBoundary3DEvent as ne,WorldBoundary3DFSM as ie,WorldBoundary3DState as ae,computeWorldBoundary2DHits as ce,computeWorldBoundary3DHits as pe,createFirstPersonInputComponent as le,createFirstPersonMovementComponent as De,createFirstPersonStateComponent as se,createJumpConfig2D as me,createJumpConfig3D as ue,createJumpInput2D as he,createJumpInput3D as de,createJumpState2D as Se,createJumpState3D as Ce,createPhysicsBodyComponent as Pe,createPlatformer2DInputComponent as ye,createPlatformer2DMovementComponent as Be,createPlatformer2DStateComponent as ve,createPlatformer3DInputComponent as fe,createPlatformer3DMovementComponent as Me,createPlatformer3DStateComponent as Fe,createShooter2DStateComponent as Ee,createThrusterInputComponent as Re,createThrusterMovementComponent as We,createThrusterStateComponent as ge,createTopDownMovementComponent as Te,createTopDownMovementInputComponent as Oe,createTopDownMovementStateComponent as Je,createTransformComponent as we,defineBehavior as Ie,fireCooldown as be,fireShooter2DIfRequested as He,getCooldown as xe,getCooldownStore as ke,getEntityFacingAngle2D as Ae,hasAnyWorldBoundary2DHit as Ve,hasAnyWorldBoundary3DHit as qe,particleEffect as ze,particlePresets as Le,registerCooldown as je,resetCooldown as Ge,resolveAim2D as Ue,tickCooldowns as Ke,updateBoundaryRicochet as Ne,useBehavior as Qe}from"@zylem/behaviors";export{o as a,t as b,r as c,n as d,i as e,a as f,c as g,p as h,l as i,D as j,s as k,m as l,u as m,h as n,d as o,S as p,C as q,P as r,y as s,B as t,v as u,f as v,M as w,F as x,E as y,R as z,W as A,g as B,T as C,O as D,J as E,w as F,I as G,b as H,H as I,x as J,k as K,A as L,V as M,q as N,z as O,L as P,j as Q,G as R,U as S,K as T,N as U,Q as V,X as W,Y as X,Z as Y,_ as Z,$ as _,ee as $,oe as aa,te as ba,re as ca,ne as da,ie as ea,ae as fa,ce as ga,pe as ha,le as ia,De as ja,se as ka,me as la,ue as ma,he as na,de as oa,Se as pa,Ce as qa,Pe as ra,ye as sa,Be as ta,ve as ua,fe as va,Me as wa,Fe as xa,Ee as ya,Re as za,We as Aa,ge as Ba,Te as Ca,Oe as Da,Je as Ea,we as Fa,Ie as Ga,be as Ha,He as Ia,xe as Ja,ke as Ka,Ae as La,Ve as Ma,qe as Na,ze as Oa,Le as Pa,je as Qa,Ge as Ra,Ue as Sa,Ke as Ta,Ne as Ua,Qe as Va};
@@ -0,0 +1 @@
1
+ var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
@@ -1 +1 @@
1
- import{b as R,c as gt,d as ft,e as bt,f as xt,g as Ot,h as wt,j as St,r as p,s as f,t as c,v as b,w as N,x as $,y as D,z as T}from"./chunk-SAQA4SXW.js";import{j as vt}from"./chunk-7NYP4YAG.js";import{d as V}from"./chunk-4QLJUQSJ.js";import{b as j,c as dt,d as yt,h as q,i as E}from"./chunk-7WRQ2UAN.js";import{BoxGeometry as qt,CapsuleGeometry as Jt,ConeGeometry as Ct,CylinderGeometry as Kt,Mesh as z,MeshStandardMaterial as Qt,SphereGeometry as te}from"three";function B(e,t=Symbol("mesh")){if(e.material||e.color){let i=new vt;if(i.build({...e.material,color:e.color??e.material?.color},t),i.materials.length>0)return i.materials}return[new Qt]}function L(e,t){if(t.position){let i=q(t.position,dt);e.position.set(i.x,i.y,i.z)}return e.castShadow=!0,e.receiveShadow=!0,e}function Mt(e={}){let t=q(e.size,yt),i=new qt(t.x,t.y,t.z),o=B(e);return L(new z(i,o.at(-1)),e)}function Pt(e={}){let t=new te(e.radius??1),i=B(e);return L(new z(t,i.at(-1)),e)}function Zt(e={}){let t=new Ct(e.radius??1,e.height??2,e.radialSegments??32),i=B(e);return L(new z(t,i.at(-1)),e)}function Et(e={}){let t=new Ct(e.radius??1,e.height??2,4),i=B(e);return L(new z(t,i.at(-1)),e)}function _t(e={}){let t=new Kt(e.radiusTop??1,e.radiusBottom??1,e.height??2,e.radialSegments??32),i=B(e);return L(new z(t,i.at(-1)),e)}function Rt(e={}){let t=new Jt(e.radius??.5,e.length??1,e.capSegments??10,e.radialSegments??20),i=B(e);return L(new z(t,i.at(-1)),e)}import{Vector3 as se}from"three";import{MeshStandardMaterial as ee,MeshBasicMaterial as ie,MeshPhongMaterial as oe}from"three";function ne(e){return e&&typeof e.getDebugInfo=="function"}var u=class{entity;constructor(t){this.entity=t}getPositionString(){if(this.entity.mesh){let{x:n,y:s,z:l}=this.entity.mesh.position;return`${n.toFixed(2)}, ${s.toFixed(2)}, ${l.toFixed(2)}`}let{x:t,y:i,z:o}=this.entity.options.position||{x:0,y:0,z:0};return`${t.toFixed(2)}, ${i.toFixed(2)}, ${o.toFixed(2)}`}getRotationString(){if(this.entity.mesh){let{x:s,y:l,z:r}=this.entity.mesh.rotation,a=m=>(m*180/Math.PI).toFixed(1);return`${a(s)}\xB0, ${a(l)}\xB0, ${a(r)}\xB0`}let{x:t,y:i,z:o}=this.entity.options.rotation||{x:0,y:0,z:0},n=s=>(s*180/Math.PI).toFixed(1);return`${n(t)}\xB0, ${n(i)}\xB0, ${n(o)}\xB0`}getMaterialInfo(){if(!this.entity.mesh||!this.entity.mesh.material)return{type:"none"};let t=Array.isArray(this.entity.mesh.material)?this.entity.mesh.material[0]:this.entity.mesh.material,i={type:t.type};return(t instanceof ee||t instanceof ie||t instanceof oe)&&(i.color=`#${t.color.getHexString()}`,i.opacity=t.opacity,i.transparent=t.transparent),"roughness"in t&&(i.roughness=t.roughness),"metalness"in t&&(i.metalness=t.metalness),i}getPhysicsInfo(){if(!this.entity.body)return null;let t={type:this.entity.body.bodyType(),mass:this.entity.body.mass(),isEnabled:this.entity.body.isEnabled(),isSleeping:this.entity.body.isSleeping()},i=this.entity.body.linvel();return t.velocity=`${i.x.toFixed(2)}, ${i.y.toFixed(2)}, ${i.z.toFixed(2)}`,t}buildDebugInfo(){let t={name:this.entity.name||this.entity.uuid,uuid:this.entity.uuid,position:this.getPositionString(),rotation:this.getRotationString(),material:this.getMaterialInfo()},i=this.getPhysicsInfo();if(i&&(t.physics=i),ne(this.entity)){let o=this.entity.getDebugInfo();return{...t,...o}}return t}};var Dt={...p,size:new se(1,1,1)},re=Symbol("Box"),J=class e extends c{static type=re;constructor(t){super(),this.options={...Dt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),{x:o,y:n,z:s}=this.options.size??{x:1,y:1,z:1};return{...i,type:String(e.type),size:`${o}, ${n}, ${s}`}}};function ae(...e){let t=f(e,Dt),i=new J(t);return i.add(Mt({size:t.size,material:t.material,color:t.color}),gt({size:t.size,static:t.collision?.static,sensor:t.collision?.sensor,canSleep:t.collision?.canSleep,ccdEnabled:t.collision?.ccdEnabled,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ae(o??{}))}var Tt={...p,radius:1},le=Symbol("Sphere"),K=class e extends c{static type=le;constructor(t){super(),this.options={...Tt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radius??1;return{...i,type:String(e.type),radius:o.toFixed(2)}}};function ce(...e){let t=f(e,Tt),i=new K(t);return i.add(Pt({radius:t.radius,material:t.material,color:t.color}),ft({radius:t.radius,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ce(o??{}))}var zt={...p,radius:1,height:2,radialSegments:32},he=Symbol("Cone"),Q=class e extends c{static type=he;constructor(t){super(),this.options={...zt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...i,type:String(e.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function me(...e){let t=f(e,zt),i=new Q(t);return i.add(Zt({radius:t.radius,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),bt({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>me(o??{}))}var Bt={...p,radius:1,height:2},pe=Symbol("Pyramid"),tt=class e extends c{static type=pe;constructor(t){super(),this.options={...Bt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...i,type:String(e.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function ue(...e){let t=f(e,Bt),i=new tt(t);return i.add(Et({radius:t.radius,height:t.height,material:t.material,color:t.color}),xt({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ue(o??{}))}var Lt={...p,radiusTop:1,radiusBottom:1,height:2,radialSegments:32},de=Symbol("Cylinder"),et=class e extends c{static type=de;constructor(t){super(),this.options={...Lt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radiusTop??1,n=this.options.radiusBottom??1,s=this.options.height??2;return{...i,type:String(e.type),radiusTop:o.toFixed(2),radiusBottom:n.toFixed(2),height:s.toFixed(2)}}};function ye(...e){let t=f(e,Lt),i=new et(t);return i.add(_t({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),Ot({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ye(o??{}))}var It={...p,radius:.5,length:1,capSegments:10,radialSegments:20},ge=Symbol("Pill"),it=class e extends c{static type=ge;constructor(t){super(),this.options={...It,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radius??.5,n=this.options.length??1;return{...i,type:String(e.type),radius:o.toFixed(2),length:n.toFixed(2)}}};function fe(...e){let t=f(e,It),i=new it(t);return i.add(Rt({radius:t.radius,length:t.length,capSegments:t.capSegments,radialSegments:t.radialSegments,material:t.material,color:t.color}),wt({radius:t.radius,length:t.length,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>fe(o??{}))}import{Group as be,RingGeometry as xe}from"three";var kt={...p,innerRadius:0,outerRadius:1,thetaSegments:32},ot=class extends N{collider(t){let i=t.outerRadius??1;return{shape:{type:"cylinder",halfHeight:.1/2,radius:i}}}},nt=class extends ${build(t){let i=t.innerRadius??0,o=t.outerRadius??1,n=t.thetaSegments??32,s=new xe(i,o,n);return s.rotateX(-Math.PI/2),s}},st=class extends D{createEntity(t){return new F(t)}build(){let t=super.build();return t.mesh&&!t.group&&(t.group=new be,t.group.add(t.mesh)),t}},Oe=Symbol("Disk"),F=class e extends c{static type=Oe;constructor(t){super(),this.options={...kt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.innerRadius??0,n=this.options.outerRadius??1;return{...i,type:String(e.type),innerRadius:o.toFixed(2),outerRadius:n.toFixed(2)}}};function we(...e){return T({args:e,defaultConfig:kt,EntityClass:F,BuilderClass:st,MeshBuilderClass:nt,CollisionBuilderClass:ot,entityType:F.type,cloneFactory:t=>we(t??{})})}import{PlaneGeometry as ve,Vector2 as Ft,Vector3 as Gt}from"three";import{BufferGeometry as Se,Float32BufferAttribute as rt}from"three";var X=class e extends Se{constructor(t=1,i=1,o=1,n=1){super(),this.type="XZPlaneGeometry",this.parameters={width:t,height:i,widthSegments:o,heightSegments:n};let s=t/2,l=i/2,r=Math.floor(o),a=Math.floor(n),m=r+1,C=a+1,M=t/r,x=i/a,O=[],w=[],d=[],P=[];for(let y=0;y<C;y++){let h=y*x-l;for(let S=0;S<m;S++){let Z=S*M-s;w.push(Z,0,h),d.push(0,1,0),P.push(S/r),P.push(1-y/a)}}for(let y=0;y<a;y++)for(let h=0;h<r;h++){let S=h+m*y,Z=h+m*(y+1),g=h+1+m*(y+1),v=h+1+m*y;O.push(S,Z,v),O.push(Z,g,v)}this.setIndex(O),this.setAttribute("position",new rt(w,3)),this.setAttribute("normal",new rt(d,3)),this.setAttribute("uv",new rt(P,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}};var Y=4,Ht={...p,tile:new Ft(10,10),repeat:new Ft(1,1),collision:{static:!0},subdivisions:Y,randomizeHeight:!1,heightScale:1};function At(e){let t=e.subdivisions??Y,i=e.heightMap2D,o=e.heightMap,n=e.subdivisionsX??t,s=e.subdivisionsZ??t;return i&&i.length>0&&i[0]?.length>0?(s=i.length-1,n=i[0].length-1):o&&o.length>0&&(n=o.length-1),{subdivisionsX:n,subdivisionsZ:s}}var at=class extends N{collider(t){let i=E(t.tile,j),{subdivisionsX:o,subdivisionsZ:n}=At(t),s=new Gt(i.x,1,i.y),l=t._builders?.meshBuilder?.heightData??new Float32Array((o+1)*(n+1));return{shape:{type:"heightfield",rows:o,cols:n,heights:l,scale:[s.x,1,s.z]}}}},lt=class extends ${heightData=new Float32Array;columnsRows=new Map;subdivisionsX=Y;subdivisionsZ=Y;build(t){let i=E(t.tile,j),{subdivisionsX:o,subdivisionsZ:n}=At(t);this.subdivisionsX=o,this.subdivisionsZ=n;let s=new Gt(i.x,1,i.y),l=t.heightScale??1,r=new X(s.x,s.z,o,n),a=new ve(s.x,s.z,o,n),m=o>0?s.x/o:1,C=n>0?s.z/n:1,M=r.attributes.position.array,x=a.attributes.position.array,O=new Map,w=t.heightMap2D,d=t.heightMap,P=t.randomizeHeight??!1,y=(h,S)=>h<0?0:h>S?S:h;for(let h=0;h<x.length;h+=3){let S=x[h],Z=x[h+1],g=y(Math.round((S+s.x/2)/m),o),v=y(Math.round((s.z/2-Z)/C),n),_=0;if(w){let ut=w[v];ut&&(_=ut[g]??0)}else d&&d.length>0?_=d[g]??0:P&&(_=Math.random()*4);let k=_*l;x[h+2]=k,M[h+1]=k,O.get(v)||O.set(v,new Map),O.get(v).set(g,k)}return this.columnsRows=O,r}postBuild(){let t=[];for(let i=0;i<=this.subdivisionsX;++i)for(let o=0;o<=this.subdivisionsZ;++o){let n=this.columnsRows.get(o);t.push(n?.get(i)??0)}this.heightData=new Float32Array(t)}},ct=class extends D{createEntity(t){return new G(t)}},Ce=Symbol("Plane"),G=class extends c{static type=Ce;constructor(t){super(),this.options=R(Ht,t)}};function Me(...e){return T({args:e,defaultConfig:Ht,EntityClass:G,BuilderClass:ct,MeshBuilderClass:lt,CollisionBuilderClass:at,entityType:G.type,cloneFactory:t=>Me(t??{})})}import{Vector3 as Pe}from"three";var Vt={...p,size:new Pe(1,1,1),collision:{static:!0}},Ze=Symbol("Zone"),ht=class extends c{static type=Ze;_enteredZone=new Map;_exitedZone=new Map;_zoneEntities=new Map;constructor(t){super(),this.options=R(Vt,t)}handlePostCollision({delta:t}){return this._enteredZone.forEach((i,o)=>{this.exited(t,o)}),this._enteredZone.size>0}handleIntersectionEvent({other:t,delta:i}){this._enteredZone.get(t.uuid)?this.held(i,t):(this.entered(t),this._zoneEntities.set(t.uuid,t))}onEnter(t){return this.options.onEnter=t,this}onHeld(t){return this.options.onHeld=t,this}onExit(t){return this.options.onExit=t,this}entered(t){this._enteredZone.set(t.uuid,1),this.options.onEnter&&this.options.onEnter({self:this,visitor:t,globals:V.globals})}exited(t,i){let o=this._exitedZone.get(i);if(o&&o>1+t){this._exitedZone.delete(i),this._enteredZone.delete(i);let n=this._zoneEntities.get(i);this.options.onExit&&this.options.onExit({self:this,visitor:n,globals:V.globals});return}this._exitedZone.set(i,1+t)}held(t,i){let o=this._enteredZone.get(i.uuid)??0;this._enteredZone.set(i.uuid,o+t),this._exitedZone.set(i.uuid,1),this.options.onHeld&&this.options.onHeld({delta:t,self:this,visitor:i,globals:V.globals,heldTime:o})}};function Ee(...e){let t=f(e,Vt),i=new ht(t);return i.add(St({size:t.size,static:t.collision?.static??!0,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>Ee(o??{}))}import{Color as Nt,Group as _e,Sprite as Re,SpriteMaterial as De,CanvasTexture as $t,LinearFilter as W,Vector2 as U,ClampToEdgeWrapping as Xt,ShaderMaterial as Yt,Mesh as Te,PlaneGeometry as ze,Vector3 as Wt}from"three";var I={position:void 0,width:120,height:48,fillColor:"#FFFFFF",strokeColor:null,strokeWidth:0,radius:0,padding:0,stickToViewport:!0,screenPosition:new U(24,24),zDistance:1,anchor:new U(0,0)},mt=class extends D{createEntity(t){return new H(t)}},Be=Symbol("Rect"),H=class e extends c{static type=Be;_sprite=null;_mesh=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=R(I,t),this.options.screenPosition=E(this.options.screenPosition,I.screenPosition),this.options.anchor=E(this.options.anchor,I.anchor),this.group=new _e,this.createSprite(),this.prependSetup(this.rectSetup.bind(this)),this.prependUpdate(this.rectUpdate.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new $t(this._canvas),this._texture.minFilter=W,this._texture.magFilter=W;let t=new De({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new Re(t),this.group?.add(this._sprite),this.redrawRect()}redrawRect(){if(!this._canvas||!this._ctx)return;let t=Math.max(2,Math.floor(this.options.width??120)),i=Math.max(2,Math.floor(this.options.height??48)),o=this.options.padding??0,n=this.options.strokeWidth??0,s=t+o*2+n,l=i+o*2+n,r=Math.max(2,s),a=Math.max(2,l),m=r!==this._lastCanvasW||a!==this._lastCanvasH;this._canvas.width=r,this._canvas.height=a,this._lastCanvasW=r,this._lastCanvasH=a,this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height);let C=Math.max(0,this.options.radius??0),M=Math.floor(o+n/2),x=Math.floor(o+n/2),O=Math.floor(t),w=Math.floor(i);if(this._ctx.beginPath(),C>0?this.roundedRectPath(this._ctx,M,x,O,w,C):this._ctx.rect(M,x,O,w),this.options.fillColor&&(this._ctx.fillStyle=this.toCssColor(this.options.fillColor),this._ctx.fill()),this.options.strokeColor&&n>0&&(this._ctx.lineWidth=n,this._ctx.strokeStyle=this.toCssColor(this.options.strokeColor),this._ctx.stroke()),this._texture){if(m&&(this._texture.dispose(),this._texture=new $t(this._canvas),this._texture.minFilter=W,this._texture.magFilter=W,this._texture.wrapS=Xt,this._texture.wrapT=Xt,this._sprite&&this._sprite.material instanceof Yt)){let d=this._sprite.material;d.uniforms?.tDiffuse&&(d.uniforms.tDiffuse.value=this._texture),d.uniforms?.iResolution&&d.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)}this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0)}}getWidth(){return this.options.width??0}getHeight(){return this.options.height??0}roundedRectPath(t,i,o,n,s,l){let r=Math.min(l,Math.floor(Math.min(n,s)/2));t.moveTo(i+r,o),t.lineTo(i+n-r,o),t.quadraticCurveTo(i+n,o,i+n,o+r),t.lineTo(i+n,o+s-r),t.quadraticCurveTo(i+n,o+s,i+n-r,o+s),t.lineTo(i+r,o+s),t.quadraticCurveTo(i,o+s,i,o+s-r),t.lineTo(i,o+r),t.quadraticCurveTo(i,o,i+r,o)}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof Nt?t:new Nt(t)).getHexString()}`}getResolution(){try{let t=this._cameraRef?.renderer?.domElement;if(t)return{width:t.clientWidth||1,height:t.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}rectSetup(t){if(this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&this._cameraRef.camera.add(this.group),this.materials?.length&&this._sprite){let i=this.materials[0];i instanceof Yt&&(i.transparent=!0,i.depthTest=!1,i.depthWrite=!1,this._texture&&(i.uniforms?.tDiffuse&&(i.uniforms.tDiffuse.value=this._texture),i.uniforms?.iResolution&&this._canvas&&i.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)),this._mesh=new Te(new ze(1,1),i),this.group?.add(this._mesh),this._sprite.visible=!1)}}rectUpdate(t){if(this._sprite){if(this._cameraRef&&this.options.bounds){let i=this.computeScreenBoundsFromOptions(this.options.bounds);if(i){let{x:o,y:n,width:s,height:l}=i,r=Math.max(2,Math.floor(s)),a=Math.max(2,Math.floor(l)),m=r!==(this.options.width??0)||a!==(this.options.height??0);this.options.screenPosition=new U(Math.floor(o),Math.floor(n)),this.options.width=r,this.options.height=a,this.options.anchor=new U(0,0),m&&this.redrawRect()}}this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:i,height:o}=this.getResolution(),n=E(this.options.screenPosition,I.screenPosition),s=n.x,l=n.y,r=Math.max(.001,this.options.zDistance??1),a=1,m=1;if(t.isPerspectiveCamera){let g=t,v=Math.tan(g.fov*Math.PI/180/2)*r;a=v*g.aspect,m=v}else if(t.isOrthographicCamera){let g=t;a=(g.right-g.left)/2,m=(g.top-g.bottom)/2}let C=s/i*2-1,M=1-l/o*2,x=C*a,O=M*m,w=1,d=1;if(this._canvas){let v=m*2/o,_=this._canvas.height;d=Math.max(1e-4,_*v);let k=this._canvas.width/this._canvas.height;w=d*k,this._sprite.scale.set(w,d,1),this._mesh&&this._mesh.scale.set(w,d,1)}let P=E(this.options.anchor,I.anchor),y=Math.min(100,Math.max(0,P.x))/100,h=Math.min(100,Math.max(0,P.y))/100,S=(.5-y)*w,Z=(h-.5)*d;this.group?.position.set(x+S,O+Z,-r)}worldToScreen(t){if(!this._cameraRef)return{x:0,y:0};let i=this._cameraRef.camera,{width:o,height:n}=this.getResolution(),s=t.clone().project(i),l=(s.x+1)/2*o,r=(1-s.y)/2*n;return{x:l,y:r}}computeScreenBoundsFromOptions(t){if(!this._cameraRef)return null;if(t.screen)return{...t.screen};if(t.world){let{left:i,right:o,top:n,bottom:s,z:l=0}=t.world,r=this.worldToScreen(new Wt(i,n,l)),a=this.worldToScreen(new Wt(o,s,l)),m=Math.min(r.x,a.x),C=Math.min(r.y,a.y),M=Math.abs(a.x-r.x),x=Math.abs(a.y-r.y);return{x:m,y:C,width:M,height:x}}return null}updateRect(t){this.options={...this.options,...t},this.redrawRect(),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new u(this).buildDebugInfo(),type:String(e.type),width:this.options.width??0,height:this.options.height??0,sticky:this.options.stickToViewport}}};function Le(...e){return T({args:e,defaultConfig:{...I},EntityClass:H,BuilderClass:mt,entityType:H.type,cloneFactory:t=>Le(t??{})})}import{AmbientLight as Ie,DirectionalLight as ke,Group as Fe,HemisphereLight as Ge,Object3D as He,PointLight as Ae,SpotLight as Ve}from"three";var Ne=Symbol("Light"),$e={x:0,y:0,z:0},A=16777215,Xe={mapSize:2048,near:.1,far:500,bias:0,radius:1,left:-100,right:100,top:100,bottom:-100},Ye={mapSize:1024,near:.1,far:500,bias:0,radius:1},pt=class extends c{static type=Ne;light=null;lightTarget=null;constructor(t){super(),this.options={...t}}create(){super.create();let t=new Fe,{light:i,target:o}=We(this.options);return t.add(i),o&&t.add(o),this.group=t,this.light=i,this.lightTarget=o,this}_cleanup(t){this.light?.shadow?.map?.dispose?.(),this.light=null,this.lightTarget=null,super._cleanup(t)}};function We(e){switch(e.type){case"ambient":return{light:Ue(e),target:null};case"hemisphere":return{light:je(e),target:null};case"directional":return qe(e);case"point":return{light:Je(e),target:null};case"spot":return Ke(e)}}function Ue(e){let t=new Ie(e.color??A,e.intensity??1);return e.name&&(t.name=e.name),t}function je(e){let t=e.skyColor??e.color??A,i=e.groundColor??0,o=new Ge(t,i,e.intensity??1);return e.name&&(o.name=e.name),o}function qe(e){let t=new ke(e.color??A,e.intensity??1);e.name&&(t.name=e.name),Qe(t,e.castShadow??!1,e.shadow);let i=Ut(e.position,e.target);return i&&(t.target=i),{light:t,target:i}}function Je(e){let t=new Ae(e.color??A,e.intensity??1,e.distance,e.decay);return e.name&&(t.name=e.name),jt(t,e.castShadow??!1,e.shadow),t}function Ke(e){let t=new Ve(e.color??A,e.intensity??1,e.distance,e.angle,e.penumbra,e.decay);e.name&&(t.name=e.name),jt(t,e.castShadow??!1,e.shadow);let i=Ut(e.position,e.target);return i&&(t.target=i),{light:t,target:i}}function Ut(e,t){if(!t)return null;let i=e??$e,o=new He;return o.position.set(t.x-i.x,t.y-i.y,t.z-i.z),o}function Qe(e,t,i){if(!t){e.castShadow=!1;return}e.castShadow=!0;let o={...Xe,...i??{}};e.shadow.mapSize.set(o.mapSize,o.mapSize),e.shadow.camera.near=o.near,e.shadow.camera.far=o.far,e.shadow.camera.left=o.left,e.shadow.camera.right=o.right,e.shadow.camera.top=o.top,e.shadow.camera.bottom=o.bottom,e.shadow.bias=o.bias,e.shadow.radius=o.radius,e.shadow.camera.updateProjectionMatrix()}function jt(e,t,i){if(!t){e.castShadow=!1;return}e.castShadow=!0;let o={...Ye,...i??{}};e.shadow.mapSize.set(o.mapSize,o.mapSize),e.shadow.camera.near=o.near,e.shadow.camera.far=o.far,e.shadow.bias=o.bias,e.shadow.radius=o.radius,e.shadow.camera.updateProjectionMatrix()}function No(e){return new pt(e)}export{u as a,Mt as b,Pt as c,Zt as d,Et as e,_t as f,Rt as g,re as h,J as i,ae as j,le as k,K as l,ce as m,he as n,Q as o,me as p,pe as q,tt as r,ue as s,de as t,et as u,ye as v,ge as w,it as x,fe as y,Oe as z,F as A,we as B,Ce as C,G as D,Me as E,Ze as F,ht as G,Ee as H,Be as I,H as J,Le as K,Ne as L,pt as M,No as N};
1
+ import{b as R,c as ft,d as bt,e as xt,f as Ot,g as wt,h as St,j as vt,r as p,s as f,t as c,v as b,w as N,x as $,y as D,z as T}from"./chunk-KP6DLLJO.js";import{j as gt}from"./chunk-6FGXC4T6.js";import{d as V}from"./chunk-4QLJUQSJ.js";import{b as j,c as dt,d as yt,h as q,i as E}from"./chunk-7WRQ2UAN.js";import{BoxGeometry as qt,CapsuleGeometry as Jt,ConeGeometry as Ct,CylinderGeometry as Kt,Mesh as z,MeshStandardMaterial as Qt,SphereGeometry as te}from"three";function B(e,t=Symbol("mesh")){if(e.material||e.color){let i=new gt;if(i.build({...e.material,color:e.color??e.material?.color},t),i.materials.length>0)return i.materials}return[new Qt]}function L(e,t){if(t.position){let i=q(t.position,dt);e.position.set(i.x,i.y,i.z)}return e.castShadow=!0,e.receiveShadow=!0,e}function Mt(e={}){let t=q(e.size,yt),i=new qt(t.x,t.y,t.z),o=B(e);return L(new z(i,o.at(-1)),e)}function Pt(e={}){let t=new te(e.radius??1),i=B(e);return L(new z(t,i.at(-1)),e)}function Zt(e={}){let t=new Ct(e.radius??1,e.height??2,e.radialSegments??32),i=B(e);return L(new z(t,i.at(-1)),e)}function Et(e={}){let t=new Ct(e.radius??1,e.height??2,4),i=B(e);return L(new z(t,i.at(-1)),e)}function _t(e={}){let t=new Kt(e.radiusTop??1,e.radiusBottom??1,e.height??2,e.radialSegments??32),i=B(e);return L(new z(t,i.at(-1)),e)}function Rt(e={}){let t=new Jt(e.radius??.5,e.length??1,e.capSegments??10,e.radialSegments??20),i=B(e);return L(new z(t,i.at(-1)),e)}import{Vector3 as se}from"three";import{MeshStandardMaterial as ee,MeshBasicMaterial as ie,MeshPhongMaterial as oe}from"three";function ne(e){return e&&typeof e.getDebugInfo=="function"}var u=class{entity;constructor(t){this.entity=t}getPositionString(){if(this.entity.mesh){let{x:n,y:s,z:l}=this.entity.mesh.position;return`${n.toFixed(2)}, ${s.toFixed(2)}, ${l.toFixed(2)}`}let{x:t,y:i,z:o}=this.entity.options.position||{x:0,y:0,z:0};return`${t.toFixed(2)}, ${i.toFixed(2)}, ${o.toFixed(2)}`}getRotationString(){if(this.entity.mesh){let{x:s,y:l,z:r}=this.entity.mesh.rotation,a=m=>(m*180/Math.PI).toFixed(1);return`${a(s)}\xB0, ${a(l)}\xB0, ${a(r)}\xB0`}let{x:t,y:i,z:o}=this.entity.options.rotation||{x:0,y:0,z:0},n=s=>(s*180/Math.PI).toFixed(1);return`${n(t)}\xB0, ${n(i)}\xB0, ${n(o)}\xB0`}getMaterialInfo(){if(!this.entity.mesh||!this.entity.mesh.material)return{type:"none"};let t=Array.isArray(this.entity.mesh.material)?this.entity.mesh.material[0]:this.entity.mesh.material,i={type:t.type};return(t instanceof ee||t instanceof ie||t instanceof oe)&&(i.color=`#${t.color.getHexString()}`,i.opacity=t.opacity,i.transparent=t.transparent),"roughness"in t&&(i.roughness=t.roughness),"metalness"in t&&(i.metalness=t.metalness),i}getPhysicsInfo(){if(!this.entity.body)return null;let t={type:this.entity.body.bodyType(),mass:this.entity.body.mass(),isEnabled:this.entity.body.isEnabled(),isSleeping:this.entity.body.isSleeping()},i=this.entity.body.linvel();return t.velocity=`${i.x.toFixed(2)}, ${i.y.toFixed(2)}, ${i.z.toFixed(2)}`,t}buildDebugInfo(){let t={name:this.entity.name||this.entity.uuid,uuid:this.entity.uuid,position:this.getPositionString(),rotation:this.getRotationString(),material:this.getMaterialInfo()},i=this.getPhysicsInfo();if(i&&(t.physics=i),ne(this.entity)){let o=this.entity.getDebugInfo();return{...t,...o}}return t}};var Dt={...p,size:new se(1,1,1)},re=Symbol("Box"),J=class e extends c{static type=re;constructor(t){super(),this.options={...Dt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),{x:o,y:n,z:s}=this.options.size??{x:1,y:1,z:1};return{...i,type:String(e.type),size:`${o}, ${n}, ${s}`}}};function ae(...e){let t=f(e,Dt),i=new J(t);return i.add(Mt({size:t.size,material:t.material,color:t.color}),ft({size:t.size,static:t.collision?.static,sensor:t.collision?.sensor,canSleep:t.collision?.canSleep,ccdEnabled:t.collision?.ccdEnabled,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ae(o??{}))}var Tt={...p,radius:1},le=Symbol("Sphere"),K=class e extends c{static type=le;constructor(t){super(),this.options={...Tt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radius??1;return{...i,type:String(e.type),radius:o.toFixed(2)}}};function ce(...e){let t=f(e,Tt),i=new K(t);return i.add(Pt({radius:t.radius,material:t.material,color:t.color}),bt({radius:t.radius,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ce(o??{}))}var zt={...p,radius:1,height:2,radialSegments:32},he=Symbol("Cone"),Q=class e extends c{static type=he;constructor(t){super(),this.options={...zt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...i,type:String(e.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function me(...e){let t=f(e,zt),i=new Q(t);return i.add(Zt({radius:t.radius,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),xt({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>me(o??{}))}var Bt={...p,radius:1,height:2},pe=Symbol("Pyramid"),tt=class e extends c{static type=pe;constructor(t){super(),this.options={...Bt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...i,type:String(e.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function ue(...e){let t=f(e,Bt),i=new tt(t);return i.add(Et({radius:t.radius,height:t.height,material:t.material,color:t.color}),Ot({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ue(o??{}))}var Lt={...p,radiusTop:1,radiusBottom:1,height:2,radialSegments:32},de=Symbol("Cylinder"),et=class e extends c{static type=de;constructor(t){super(),this.options={...Lt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radiusTop??1,n=this.options.radiusBottom??1,s=this.options.height??2;return{...i,type:String(e.type),radiusTop:o.toFixed(2),radiusBottom:n.toFixed(2),height:s.toFixed(2)}}};function ye(...e){let t=f(e,Lt),i=new et(t);return i.add(_t({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),wt({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ye(o??{}))}var It={...p,radius:.5,length:1,capSegments:10,radialSegments:20},ge=Symbol("Pill"),it=class e extends c{static type=ge;constructor(t){super(),this.options={...It,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.radius??.5,n=this.options.length??1;return{...i,type:String(e.type),radius:o.toFixed(2),length:n.toFixed(2)}}};function fe(...e){let t=f(e,It),i=new it(t);return i.add(Rt({radius:t.radius,length:t.length,capSegments:t.capSegments,radialSegments:t.radialSegments,material:t.material,color:t.color}),St({radius:t.radius,length:t.length,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>fe(o??{}))}import{Group as be,RingGeometry as xe}from"three";var kt={...p,innerRadius:0,outerRadius:1,thetaSegments:32},ot=class extends N{collider(t){let i=t.outerRadius??1;return{shape:{type:"cylinder",halfHeight:.1/2,radius:i}}}},nt=class extends ${build(t){let i=t.innerRadius??0,o=t.outerRadius??1,n=t.thetaSegments??32,s=new xe(i,o,n);return s.rotateX(-Math.PI/2),s}},st=class extends D{createEntity(t){return new F(t)}build(){let t=super.build();return t.mesh&&!t.group&&(t.group=new be,t.group.add(t.mesh)),t}},Oe=Symbol("Disk"),F=class e extends c{static type=Oe;constructor(t){super(),this.options={...kt,...t}}buildInfo(){let i=new u(this).buildDebugInfo(),o=this.options.innerRadius??0,n=this.options.outerRadius??1;return{...i,type:String(e.type),innerRadius:o.toFixed(2),outerRadius:n.toFixed(2)}}};function we(...e){return T({args:e,defaultConfig:kt,EntityClass:F,BuilderClass:st,MeshBuilderClass:nt,CollisionBuilderClass:ot,entityType:F.type,cloneFactory:t=>we(t??{})})}import{PlaneGeometry as ve,Vector2 as Ft,Vector3 as Gt}from"three";import{BufferGeometry as Se,Float32BufferAttribute as rt}from"three";var X=class e extends Se{constructor(t=1,i=1,o=1,n=1){super(),this.type="XZPlaneGeometry",this.parameters={width:t,height:i,widthSegments:o,heightSegments:n};let s=t/2,l=i/2,r=Math.floor(o),a=Math.floor(n),m=r+1,C=a+1,M=t/r,x=i/a,O=[],w=[],d=[],P=[];for(let y=0;y<C;y++){let h=y*x-l;for(let S=0;S<m;S++){let Z=S*M-s;w.push(Z,0,h),d.push(0,1,0),P.push(S/r),P.push(1-y/a)}}for(let y=0;y<a;y++)for(let h=0;h<r;h++){let S=h+m*y,Z=h+m*(y+1),g=h+1+m*(y+1),v=h+1+m*y;O.push(S,Z,v),O.push(Z,g,v)}this.setIndex(O),this.setAttribute("position",new rt(w,3)),this.setAttribute("normal",new rt(d,3)),this.setAttribute("uv",new rt(P,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}};var Y=4,Ht={...p,tile:new Ft(10,10),repeat:new Ft(1,1),collision:{static:!0},subdivisions:Y,randomizeHeight:!1,heightScale:1};function At(e){let t=e.subdivisions??Y,i=e.heightMap2D,o=e.heightMap,n=e.subdivisionsX??t,s=e.subdivisionsZ??t;return i&&i.length>0&&i[0]?.length>0?(s=i.length-1,n=i[0].length-1):o&&o.length>0&&(n=o.length-1),{subdivisionsX:n,subdivisionsZ:s}}var at=class extends N{collider(t){let i=E(t.tile,j),{subdivisionsX:o,subdivisionsZ:n}=At(t),s=new Gt(i.x,1,i.y),l=t._builders?.meshBuilder?.heightData??new Float32Array((o+1)*(n+1));return{shape:{type:"heightfield",rows:o,cols:n,heights:l,scale:[s.x,1,s.z]}}}},lt=class extends ${heightData=new Float32Array;columnsRows=new Map;subdivisionsX=Y;subdivisionsZ=Y;build(t){let i=E(t.tile,j),{subdivisionsX:o,subdivisionsZ:n}=At(t);this.subdivisionsX=o,this.subdivisionsZ=n;let s=new Gt(i.x,1,i.y),l=t.heightScale??1,r=new X(s.x,s.z,o,n),a=new ve(s.x,s.z,o,n),m=o>0?s.x/o:1,C=n>0?s.z/n:1,M=r.attributes.position.array,x=a.attributes.position.array,O=new Map,w=t.heightMap2D,d=t.heightMap,P=t.randomizeHeight??!1,y=(h,S)=>h<0?0:h>S?S:h;for(let h=0;h<x.length;h+=3){let S=x[h],Z=x[h+1],g=y(Math.round((S+s.x/2)/m),o),v=y(Math.round((s.z/2-Z)/C),n),_=0;if(w){let ut=w[v];ut&&(_=ut[g]??0)}else d&&d.length>0?_=d[g]??0:P&&(_=Math.random()*4);let k=_*l;x[h+2]=k,M[h+1]=k,O.get(v)||O.set(v,new Map),O.get(v).set(g,k)}return this.columnsRows=O,r}postBuild(){let t=[];for(let i=0;i<=this.subdivisionsX;++i)for(let o=0;o<=this.subdivisionsZ;++o){let n=this.columnsRows.get(o);t.push(n?.get(i)??0)}this.heightData=new Float32Array(t)}},ct=class extends D{createEntity(t){return new G(t)}},Ce=Symbol("Plane"),G=class extends c{static type=Ce;constructor(t){super(),this.options=R(Ht,t)}};function Me(...e){return T({args:e,defaultConfig:Ht,EntityClass:G,BuilderClass:ct,MeshBuilderClass:lt,CollisionBuilderClass:at,entityType:G.type,cloneFactory:t=>Me(t??{})})}import{Vector3 as Pe}from"three";var Vt={...p,size:new Pe(1,1,1),collision:{static:!0}},Ze=Symbol("Zone"),ht=class extends c{static type=Ze;_enteredZone=new Map;_exitedZone=new Map;_zoneEntities=new Map;constructor(t){super(),this.options=R(Vt,t)}handlePostCollision({delta:t}){return this._enteredZone.forEach((i,o)=>{this.exited(t,o)}),this._enteredZone.size>0}handleIntersectionEvent({other:t,delta:i}){this._enteredZone.get(t.uuid)?this.held(i,t):(this.entered(t),this._zoneEntities.set(t.uuid,t))}onEnter(t){return this.options.onEnter=t,this}onHeld(t){return this.options.onHeld=t,this}onExit(t){return this.options.onExit=t,this}entered(t){this._enteredZone.set(t.uuid,1),this.options.onEnter&&this.options.onEnter({self:this,visitor:t,globals:V.globals})}exited(t,i){let o=this._exitedZone.get(i);if(o&&o>1+t){this._exitedZone.delete(i),this._enteredZone.delete(i);let n=this._zoneEntities.get(i);this.options.onExit&&this.options.onExit({self:this,visitor:n,globals:V.globals});return}this._exitedZone.set(i,1+t)}held(t,i){let o=this._enteredZone.get(i.uuid)??0;this._enteredZone.set(i.uuid,o+t),this._exitedZone.set(i.uuid,1),this.options.onHeld&&this.options.onHeld({delta:t,self:this,visitor:i,globals:V.globals,heldTime:o})}};function Ee(...e){let t=f(e,Vt),i=new ht(t);return i.add(vt({size:t.size,static:t.collision?.static??!0,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>Ee(o??{}))}import{Color as Nt,Group as _e,Sprite as Re,SpriteMaterial as De,CanvasTexture as $t,LinearFilter as W,Vector2 as U,ClampToEdgeWrapping as Xt,ShaderMaterial as Yt,Mesh as Te,PlaneGeometry as ze,Vector3 as Wt}from"three";var I={position:void 0,width:120,height:48,fillColor:"#FFFFFF",strokeColor:null,strokeWidth:0,radius:0,padding:0,stickToViewport:!0,screenPosition:new U(24,24),zDistance:1,anchor:new U(0,0)},mt=class extends D{createEntity(t){return new H(t)}},Be=Symbol("Rect"),H=class e extends c{static type=Be;_sprite=null;_mesh=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=R(I,t),this.options.screenPosition=E(this.options.screenPosition,I.screenPosition),this.options.anchor=E(this.options.anchor,I.anchor),this.group=new _e,this.createSprite(),this.prependSetup(this.rectSetup.bind(this)),this.prependUpdate(this.rectUpdate.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new $t(this._canvas),this._texture.minFilter=W,this._texture.magFilter=W;let t=new De({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new Re(t),this.group?.add(this._sprite),this.redrawRect()}redrawRect(){if(!this._canvas||!this._ctx)return;let t=Math.max(2,Math.floor(this.options.width??120)),i=Math.max(2,Math.floor(this.options.height??48)),o=this.options.padding??0,n=this.options.strokeWidth??0,s=t+o*2+n,l=i+o*2+n,r=Math.max(2,s),a=Math.max(2,l),m=r!==this._lastCanvasW||a!==this._lastCanvasH;this._canvas.width=r,this._canvas.height=a,this._lastCanvasW=r,this._lastCanvasH=a,this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height);let C=Math.max(0,this.options.radius??0),M=Math.floor(o+n/2),x=Math.floor(o+n/2),O=Math.floor(t),w=Math.floor(i);if(this._ctx.beginPath(),C>0?this.roundedRectPath(this._ctx,M,x,O,w,C):this._ctx.rect(M,x,O,w),this.options.fillColor&&(this._ctx.fillStyle=this.toCssColor(this.options.fillColor),this._ctx.fill()),this.options.strokeColor&&n>0&&(this._ctx.lineWidth=n,this._ctx.strokeStyle=this.toCssColor(this.options.strokeColor),this._ctx.stroke()),this._texture){if(m&&(this._texture.dispose(),this._texture=new $t(this._canvas),this._texture.minFilter=W,this._texture.magFilter=W,this._texture.wrapS=Xt,this._texture.wrapT=Xt,this._sprite&&this._sprite.material instanceof Yt)){let d=this._sprite.material;d.uniforms?.tDiffuse&&(d.uniforms.tDiffuse.value=this._texture),d.uniforms?.iResolution&&d.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)}this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0)}}getWidth(){return this.options.width??0}getHeight(){return this.options.height??0}roundedRectPath(t,i,o,n,s,l){let r=Math.min(l,Math.floor(Math.min(n,s)/2));t.moveTo(i+r,o),t.lineTo(i+n-r,o),t.quadraticCurveTo(i+n,o,i+n,o+r),t.lineTo(i+n,o+s-r),t.quadraticCurveTo(i+n,o+s,i+n-r,o+s),t.lineTo(i+r,o+s),t.quadraticCurveTo(i,o+s,i,o+s-r),t.lineTo(i,o+r),t.quadraticCurveTo(i,o,i+r,o)}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof Nt?t:new Nt(t)).getHexString()}`}getResolution(){try{let t=this._cameraRef?.renderer?.domElement;if(t)return{width:t.clientWidth||1,height:t.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}rectSetup(t){if(this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&this._cameraRef.camera.add(this.group),this.materials?.length&&this._sprite){let i=this.materials[0];i instanceof Yt&&(i.transparent=!0,i.depthTest=!1,i.depthWrite=!1,this._texture&&(i.uniforms?.tDiffuse&&(i.uniforms.tDiffuse.value=this._texture),i.uniforms?.iResolution&&this._canvas&&i.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)),this._mesh=new Te(new ze(1,1),i),this.group?.add(this._mesh),this._sprite.visible=!1)}}rectUpdate(t){if(this._sprite){if(this._cameraRef&&this.options.bounds){let i=this.computeScreenBoundsFromOptions(this.options.bounds);if(i){let{x:o,y:n,width:s,height:l}=i,r=Math.max(2,Math.floor(s)),a=Math.max(2,Math.floor(l)),m=r!==(this.options.width??0)||a!==(this.options.height??0);this.options.screenPosition=new U(Math.floor(o),Math.floor(n)),this.options.width=r,this.options.height=a,this.options.anchor=new U(0,0),m&&this.redrawRect()}}this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:i,height:o}=this.getResolution(),n=E(this.options.screenPosition,I.screenPosition),s=n.x,l=n.y,r=Math.max(.001,this.options.zDistance??1),a=1,m=1;if(t.isPerspectiveCamera){let g=t,v=Math.tan(g.fov*Math.PI/180/2)*r;a=v*g.aspect,m=v}else if(t.isOrthographicCamera){let g=t;a=(g.right-g.left)/2,m=(g.top-g.bottom)/2}let C=s/i*2-1,M=1-l/o*2,x=C*a,O=M*m,w=1,d=1;if(this._canvas){let v=m*2/o,_=this._canvas.height;d=Math.max(1e-4,_*v);let k=this._canvas.width/this._canvas.height;w=d*k,this._sprite.scale.set(w,d,1),this._mesh&&this._mesh.scale.set(w,d,1)}let P=E(this.options.anchor,I.anchor),y=Math.min(100,Math.max(0,P.x))/100,h=Math.min(100,Math.max(0,P.y))/100,S=(.5-y)*w,Z=(h-.5)*d;this.group?.position.set(x+S,O+Z,-r)}worldToScreen(t){if(!this._cameraRef)return{x:0,y:0};let i=this._cameraRef.camera,{width:o,height:n}=this.getResolution(),s=t.clone().project(i),l=(s.x+1)/2*o,r=(1-s.y)/2*n;return{x:l,y:r}}computeScreenBoundsFromOptions(t){if(!this._cameraRef)return null;if(t.screen)return{...t.screen};if(t.world){let{left:i,right:o,top:n,bottom:s,z:l=0}=t.world,r=this.worldToScreen(new Wt(i,n,l)),a=this.worldToScreen(new Wt(o,s,l)),m=Math.min(r.x,a.x),C=Math.min(r.y,a.y),M=Math.abs(a.x-r.x),x=Math.abs(a.y-r.y);return{x:m,y:C,width:M,height:x}}return null}updateRect(t){this.options={...this.options,...t},this.redrawRect(),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new u(this).buildDebugInfo(),type:String(e.type),width:this.options.width??0,height:this.options.height??0,sticky:this.options.stickToViewport}}};function Le(...e){return T({args:e,defaultConfig:{...I},EntityClass:H,BuilderClass:mt,entityType:H.type,cloneFactory:t=>Le(t??{})})}import{AmbientLight as Ie,DirectionalLight as ke,Group as Fe,HemisphereLight as Ge,Object3D as He,PointLight as Ae,SpotLight as Ve}from"three";var Ne=Symbol("Light"),$e={x:0,y:0,z:0},A=16777215,Xe={mapSize:2048,near:.1,far:500,bias:0,radius:1,left:-100,right:100,top:100,bottom:-100},Ye={mapSize:1024,near:.1,far:500,bias:0,radius:1},pt=class extends c{static type=Ne;light=null;lightTarget=null;constructor(t){super(),this.options={...t}}create(){super.create();let t=new Fe,{light:i,target:o}=We(this.options);return t.add(i),o&&t.add(o),this.group=t,this.light=i,this.lightTarget=o,this}_cleanup(t){this.light?.shadow?.map?.dispose?.(),this.light=null,this.lightTarget=null,super._cleanup(t)}};function We(e){switch(e.type){case"ambient":return{light:Ue(e),target:null};case"hemisphere":return{light:je(e),target:null};case"directional":return qe(e);case"point":return{light:Je(e),target:null};case"spot":return Ke(e)}}function Ue(e){let t=new Ie(e.color??A,e.intensity??1);return e.name&&(t.name=e.name),t}function je(e){let t=e.skyColor??e.color??A,i=e.groundColor??0,o=new Ge(t,i,e.intensity??1);return e.name&&(o.name=e.name),o}function qe(e){let t=new ke(e.color??A,e.intensity??1);e.name&&(t.name=e.name),Qe(t,e.castShadow??!1,e.shadow);let i=Ut(e.position,e.target);return i&&(t.target=i),{light:t,target:i}}function Je(e){let t=new Ae(e.color??A,e.intensity??1,e.distance,e.decay);return e.name&&(t.name=e.name),jt(t,e.castShadow??!1,e.shadow),t}function Ke(e){let t=new Ve(e.color??A,e.intensity??1,e.distance,e.angle,e.penumbra,e.decay);e.name&&(t.name=e.name),jt(t,e.castShadow??!1,e.shadow);let i=Ut(e.position,e.target);return i&&(t.target=i),{light:t,target:i}}function Ut(e,t){if(!t)return null;let i=e??$e,o=new He;return o.position.set(t.x-i.x,t.y-i.y,t.z-i.z),o}function Qe(e,t,i){if(!t){e.castShadow=!1;return}e.castShadow=!0;let o={...Xe,...i??{}};e.shadow.mapSize.set(o.mapSize,o.mapSize),e.shadow.camera.near=o.near,e.shadow.camera.far=o.far,e.shadow.camera.left=o.left,e.shadow.camera.right=o.right,e.shadow.camera.top=o.top,e.shadow.camera.bottom=o.bottom,e.shadow.bias=o.bias,e.shadow.radius=o.radius,e.shadow.camera.updateProjectionMatrix()}function jt(e,t,i){if(!t){e.castShadow=!1;return}e.castShadow=!0;let o={...Ye,...i??{}};e.shadow.mapSize.set(o.mapSize,o.mapSize),e.shadow.camera.near=o.near,e.shadow.camera.far=o.far,e.shadow.bias=o.bias,e.shadow.radius=o.radius,e.shadow.camera.updateProjectionMatrix()}function No(e){return new pt(e)}export{u as a,Mt as b,Pt as c,Zt as d,Et as e,_t as f,Rt as g,re as h,J as i,ae as j,le as k,K as l,ce as m,he as n,Q as o,me as p,pe as q,tt as r,ue as s,de as t,et as u,ye as v,ge as w,it as x,fe as y,Oe as z,F as A,we as B,Ce as C,G as D,Me as E,Ze as F,ht as G,Ee as H,Be as I,H as J,Le as K,Ne as L,pt as M,No as N};
@@ -0,0 +1 @@
1
+ import{b as q,q as $,r as X,t as D,w as J,y as Q,z as ee}from"./chunk-KP6DLLJO.js";import{d as K,f as H,g as j}from"./chunk-6FGXC4T6.js";import{c as B,d as P,h as M,j as Y}from"./chunk-7WRQ2UAN.js";import{Box3 as I,BufferAttribute as Ae,SkinnedMesh as Me,MeshStandardMaterial as Fe,Group as Oe,Vector3 as x,Matrix4 as se}from"three";var S=class{async loadFile(e,t){switch(H(e)){case"fbx":{let i=await j.loadFBX(e,t);return{object:i.object,animation:i.animations?.[0]}}case"gltf":case"glb":{let i=await j.loadGLTF(e,t);return{object:i.object,gltf:i.gltf}}case"obj":return{object:(await j.loadOBJ(e,t)).object};default:throw new Error(`Unsupported file type: ${e}`)}}};import{AnimationMixer as ge,Bone as te,LoopOnce as be,LoopRepeat as xe}from"three";function _e(n){let e=n.lastIndexOf(".");return e>=0?n.slice(0,e):n}function ie(n,e){if(!n?.name?.endsWith(".position"))return!1;let t=_e(n.name),o=e.get(t);return o instanceof te?!(o.parent instanceof te):/hips\.position$/i.test(n.name)||/root\.position$/i.test(n.name)}function ve(n,e,t,o){for(let i of n.tracks){if(!ie(i,e)||!i.values||i.values.length<3)continue;let s=i.values[0],r=o??i.values[1],a=i.values[2];for(let l=0;l<i.values.length;l+=3)i.values[l]=s,t&&(i.values[l+1]=r),i.values[l+2]=a}return n}function Se(n,e){for(let t of n.tracks)if(ie(t,e)&&!(!t.values||t.values.length<3))return t.values[1];return null}var E=class{constructor(e){this.target=e}_mixer=null;_actions={};_animations=[];_currentAction=null;_pauseAtPercentage=0;_isPaused=!1;_queuedKey=null;_fadeDuration=.5;_currentKey="";_assetLoader=new S;async loadAnimations(e,t={}){if(!e.length)return;let o=t.stripRootMotionY??!1,i=t.referenceRootY,s=t.referenceAnimationPath,r=await Promise.all(e.map(c=>this._assetLoader.loadFile(c.path))),a=new Map;this.target.traverse(c=>{c.name&&a.set(c.name,c)});let l=[];if(r.forEach((c,u)=>{c.animation&&l.push({key:e[u].key||u.toString(),clip:c.animation,path:e[u].path})}),!l.length)return;let h=i;if(o&&h===void 0){let c=s?l.findIndex(p=>p.path===s):0,u=c>=0?[c,...l.map((p,f)=>f).filter(p=>p!==c)]:l.map((p,f)=>f);for(let p of u){let f=Se(l[p].clip,a);if(f!==null){h=f;break}}}let d=l.map(({key:c,clip:u})=>({key:c,clip:ve(u,a,o,h)}));this._animations=d.map(c=>c.clip),this._mixer=new ge(this.target),d.forEach(({key:c,clip:u})=>{this._actions[c]=this._mixer.clipAction(u)}),this.playAnimation({key:d[0].key})}update(e){if(!this._mixer||!this._currentAction)return;this._mixer.update(e);let t=this._currentAction.getClip().duration*(this._pauseAtPercentage/100);if(!this._isPaused&&this._pauseAtPercentage>0&&this._currentAction.time>=t&&(this._currentAction.time=t,this._currentAction.paused=!0,this._isPaused=!0,this._queuedKey!==null)){let o=this._actions[this._queuedKey];o.reset().play(),this._currentAction.crossFadeTo(o,this._fadeDuration,!1),this._currentAction=o,this._currentKey=this._queuedKey,this._queuedKey=null}}playAnimation(e){if(!this._mixer)return;let{key:t,pauseAtPercentage:o=0,pauseAtEnd:i=!1,fadeToKey:s,fadeDuration:r=.5}=e;if(t===this._currentKey)return;let a=this._actions[t];if(!a)return;if(a===this._currentAction){this._currentKey=t;return}this._queuedKey=s||null,this._fadeDuration=r,this._pauseAtPercentage=i?100:o,this._isPaused=!1;let l=this._currentAction;this._pauseAtPercentage>0?(a.setLoop(be,1/0),a.clampWhenFinished=!0):(a.setLoop(xe,1/0),a.clampWhenFinished=!1),a.reset().play(),l&&l.crossFadeTo(a,r,!1),this._currentAction=a,this._currentKey=t}dispose(){Object.values(this._actions).forEach(e=>{e.stop()}),this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this.target),this._mixer=null),this._actions={},this._animations=[],this._currentAction=null,this._currentKey=""}get currentAnimationKey(){return this._currentKey}get animations(){return this._animations}};var re={...X,material:{shader:K},animations:[],models:[],collisionShape:"capsule"};function F(n){return Y(n.scale,P)}var Ce=1e-4,je=/foot$/i,Z=new x,w=new x,ne=new x,T=new x,oe=new se;function De(n){let e=1/0,t=!1;return n.traverse(o=>{if(!o.isSkinnedMesh)return;let i=o,s=i.geometry,r=s.attributes.position,a=s.attributes.skinIndex,l=s.attributes.skinWeight,h=i.skeleton;if(!r||!a||!l||!h)return;t=!0,h.update(),i.updateMatrixWorld(!0);let d=h.boneMatrices;if(d)for(let c=0;c<r.count;c++){ne.fromBufferAttribute(r,c).applyMatrix4(i.bindMatrix),T.set(0,0,0);for(let u=0;u<4;u++){let p=l.getComponent(c,u);if(p===0)continue;let f=a.getComponent(c,u);oe.fromArray(d,f*16),T.addScaledVector(w.copy(ne).applyMatrix4(oe),p)}T.applyMatrix4(i.bindMatrixInverse).applyMatrix4(i.matrixWorld),e=Math.min(e,T.y)}}),!t||!Number.isFinite(e)?null:e}function Ee(n,e){e.updateMatrixWorld(!0);let t=e.getWorldPosition(Z).y,o=De(n)??1/0;if(n.traverse(i=>{!i.isBone||!je.test(i.name)||(i.getWorldPosition(Z),o=Math.min(o,Z.y))}),Number.isFinite(o)||n.traverse(i=>{if(!i.isSkinnedMesh)return;let s=i;if(s.computeBoundingBox(),!s.boundingBox)return;let{min:r,max:a}=s.boundingBox;for(let l of[[r.x,r.y,r.z],[r.x,r.y,a.z],[r.x,a.y,r.z],[r.x,a.y,a.z],[a.x,r.y,r.z],[a.x,r.y,a.z],[a.x,a.y,r.z],[a.x,a.y,a.z]])w.set(l[0],l[1],l[2]),w.applyMatrix4(s.matrixWorld),o=Math.min(o,w.y)}),!Number.isFinite(o)){let i=new I().setFromObject(n);if(i.isEmpty())return null;o=i.min.y}return o-t}function Te(n,e,t){return n.stripRootMotionY!==void 0?n.stripRootMotionY:!!(e&&t.some(o=>o===e))}function C(n){let e=n.collision?.position;return e?M(e,B):null}function R(n){return!!n.collision?.size}function ze(n){n.hasWarnedDynamicTrimesh||(n.hasWarnedDynamicTrimesh=!0,console.warn(`Actor "${n.name||n.uuid}" requested collisionShape="trimesh" on a dynamic body; falling back to bounds.`))}function ae(n,e,t){let o=n==="model"?"bounds":n??"capsule";return o==="trimesh"&&!e?(t?.(),"bounds"):o}function le(n,e){let t=n.x||.5,o=n.y||1,i=n.z||.5,s=Math.max(t,i)/2,r=o/2;return{shape:{type:"capsule",halfHeight:Math.max(0,r-s),radius:s},offset:[e.x,e.y,e.z],sensor:!1}}function v(n){let e=M(n.collision?.size??n.size,{x:.5,y:1,z:.5}),t=e.y||1,o=C(n);return le({x:e.x||.5,y:t,z:e.z||.5},o??{x:0,y:t/2,z:0})}function ce(n){let e=n.collision?.size;if(!e)return null;let t=M(e,B),o=t.x/2,i=t.y/2,s=t.z/2,r=C(n);return{shape:{type:"box",halfExtents:[o,i,s]},offset:[r?.x??0,r?.y??i,r?.z??0],sensor:!1}}function ue(n,e,t){let i=e.matrixWorld.clone().invert().multiply(n.matrixWorld);return new se().makeScale(t.x,t.y,t.z).multiply(i)}function V(n,e,t){n.updateMatrixWorld(!0);let o=!1,i=new I;if(n.traverse(a=>{if(!a.isMesh)return;let l=a,h=l.geometry;if(!h)return;let d=null;if(l instanceof Me?(l.computeBoundingBox(),d=l.boundingBox?.clone()??null):(h.computeBoundingBox(),d=h.boundingBox?.clone()??null),!d)return;let c=d.applyMatrix4(ue(l,e,t));if(!o){i.copy(c),o=!0;return}i.union(c)}),!o||i.isEmpty())return null;let s=new x,r=new x;return i.getSize(s),i.getCenter(r),{size:s,center:r}}function we(n,e,t){n.updateMatrixWorld(!0);let o=[],i=[],s=new I,r=new x,a=!1;if(n.traverse(h=>{if(!h.isMesh)return;let d=h,c=d.geometry;if(!c)return;let u=c.getAttribute("position");if(!(u instanceof Ae))return;let p=ue(d,e,t),f=o.length/3;for(let m=0;m<u.count;m++)r.set(u.getX(m),u.getY(m),u.getZ(m)),r.applyMatrix4(p),o.push(r.x,r.y,r.z),s.expandByPoint(r);let A=c.getIndex();if(A)for(let m=0;m<A.count;m++)i.push(f+A.getX(m));else for(let m=0;m<u.count;m++)i.push(f+m);a=!0}),!a||o.length===0||i.length===0)return null;let l=new x;return s.getCenter(l),{vertices:new Float32Array(o),indices:new Uint32Array(i),center:l}}function he(n,e,t){let o=ce(t);if(o)return o;if(!n||!e)return v(t);let i=V(n,e,F(t));if(!i)return v(t);let s=C(t);return{shape:{type:"box",halfExtents:[i.size.x/2,i.size.y/2,i.size.z/2]},offset:[s?.x??i.center.x,s?.y??i.center.y,s?.z??i.center.z],sensor:!1}}function de(n,e,t,o,i){if(R(i)||!n||!e)return v(i);let s=V(n,e,F(i));if(!s)return v(i);let a=C(i);if(!a){let l=t&&o?V(t,o,F(i)):null;a=l?{x:l.center.x,y:l.center.y,z:l.center.z}:{x:s.center.x,y:s.center.y,z:s.center.z}}return le({x:s.size.x,y:s.size.y,z:s.size.z},a)}function pe(n,e,t){let o=ce(t);if(o)return o;if(!n||!e)return v(t);let i=we(n,e,F(t));if(!i)return v(t);let s=C(t);return{shape:{type:"trimesh",vertices:i.vertices,indices:i.indices},offset:s?[s.x-i.center.x,s.y-i.center.y,s.z-i.center.z]:[0,0,0],sensor:!1}}function z(n){n&&n.traverse(e=>{if(!e.isMesh)return;let t=e;t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(o=>o.dispose()):t.material?.dispose()})}var k=class extends J{objectModel=null;collisionSource=null;collisionShape="capsule";constructor(e){super(),this.objectModel=e.objectModel,this.collisionSource=e.collisionSource??e.objectModel??null,this.collisionShape=e.collisionShape??"capsule"}collider(e){let t=ae(this.collisionShape,!!e.collision?.static);return t==="bounds"?he(this.objectModel,this.objectModel,e):t==="trimesh"?pe(this.objectModel,this.objectModel,e):de(this.collisionSource,this.collisionSource,this.objectModel,this.objectModel,e)}},U=class extends Q{createEntity(e){return new O(e)}},Le=Symbol("Actor"),O=class extends D{static type=Le;_object=null;_collisionSource=null;_animationDelegate=null;_modelFileNames=[];_assetLoader=new S;_loadGeneration=0;_loadStatus="idle";controlledRotation=!1;hasWarnedDynamicTrimesh=!1;constructor(e){super(),this.options=q(re,e),this.prependUpdate(this.actorUpdate.bind(this)),this.controlledRotation=!0}create(){return this._loadStatus==="idle"&&(this.options.models?.length??0)>0&&this.load(),super.create()}load(){this._loadStatus==="loading"||this._loadStatus==="loaded"||(this._modelFileNames=[...this.options.models||[]],this._modelFileNames.length!==0&&(this.disposeRuntimeState(!0),this._loadStatus="loading",this.loadModelsDeferred(++this._loadGeneration)))}data(){return{animations:this._animationDelegate?.animations,objectModel:this._object,collisionSource:this._collisionSource??this._object,collisionShape:this.options.collisionShape}}needsDeferredModelCollision(){return this.requiresLoadedCollisionSource()?!this.getRuntimeCollisionSource():!1}synchronizeRuntimeCollider(){let e=this.getResolvedCollisionShape(),t;if(e==="bounds")t=he(this._object,this.group??this._object,this.options);else if(e==="trimesh")t=pe(this._object,this.group??this._object,this.options);else{let o=this.getRuntimeCollisionSource();t=de(o,o,this._object,this._object,this.options)}this.colliderDesc=t,this.colliderDescs.length>0?this.colliderDescs[0]=t:this.colliderDescs.push(t)}actorUpdate(e){this._animationDelegate?.update(e.delta)}actorDestroy(){this._loadGeneration+=1,this._loadStatus="idle",this.disposeRuntimeState(!0),this._modelFileNames=[]}_cleanup(e){super._cleanup(e),this.actorDestroy()}playAnimation(e){this._animationDelegate?.playAnimation(e)}get object(){return this._object}get collisionSource(){return this._collisionSource??this._object}getDebugInfo(){let e={type:"Actor",models:this._modelFileNames.length>0?this._modelFileNames:"none",modelLoaded:!!this._object,scale:(()=>{let t=M(this.options.scale,P);return`${t.x}, ${t.y}, ${t.z}`})(),collisionShape:this.getResolvedCollisionShape()};if(this._animationDelegate&&(e.currentAnimation=this._animationDelegate.currentAnimationKey||"none",e.animationsCount=this.options.animations?.length||0),this._object){let t=0,o=0;this._object.traverse(i=>{if(!i.isMesh)return;t++;let s=i.geometry;s?.attributes.position&&(o+=s.attributes.position.count)}),e.meshCount=t,e.vertexCount=o}return e}getResolvedCollisionShape(){return ae(this.options.collisionShape,!!this.options.collision?.static,()=>ze(this))}requiresLoadedCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?!R(this.options):e==="capsule"?!R(this.options)&&this.getCollisionSourceSelection().file!==null:!1}getRuntimeCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?this._object:this._collisionSource??this._object}getCollisionSourceSelection(){let e=this.options.models?.[0]??null,t=this.options.animations?.[0]?.path??null;return t?{file:t,reuseVisibleModel:t===e}:{file:e,reuseVisibleModel:!0}}disposeRuntimeState(e){this._animationDelegate&&(this._animationDelegate.dispose(),this._animationDelegate=null);let t=this._collisionSource;z(this._object),t&&t!==this._object&&z(t),this._object=null,this._collisionSource=null,e&&this.group&&(this.group.clear(),this.group=void 0)}loadModelsDeferred(e){this.dispatch("entity:model:loading",{entityId:this.uuid,files:this._modelFileNames});let t=this.getCollisionSourceSelection(),o=this._modelFileNames.map(s=>this._assetLoader.loadFile(s,{clone:!0})),i=t.file&&!t.reuseVisibleModel?this._assetLoader.loadFile(t.file,{clone:!0}):Promise.resolve(null);Promise.all([Promise.all(o),i]).then(([s,r])=>{if(e!==this._loadGeneration){s.forEach(l=>z(l.object??null)),r?.object&&z(r.object);return}this._object=s[0]?.object??null,this._collisionSource=t.reuseVisibleModel?this._object:r?.object??this._object,this._loadStatus=this._object?"loaded":"idle";let a=0;if(this._object){this._object.traverse(u=>{u.isMesh&&a++}),this.group=new Oe,this.group.add(this._object),this.group.scale.copy(F(this.options)),$(this),this.applyMaterialOverrides(),this._animationDelegate=new E(this._object);let l=this.options.animations||[],h=this.options.models?.[0],d=l.map(u=>u.path),c=Te(this.options,h,d);l.length>0?this._animationDelegate.loadAnimations(l,{stripRootMotionY:c,referenceAnimationPath:h}).then(()=>{e===this._loadGeneration&&(this.alignVisualModelToGround(),this.dispatch("entity:animation:loaded",{entityId:this.uuid,animationCount:l.length}))}):this.alignVisualModelToGround()}this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!!this._object,meshCount:a})}).catch(s=>{e===this._loadGeneration&&(this._loadStatus="idle",console.error("Failed to load actor model",s),this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!1,meshCount:0,errorMessage:s instanceof Error?s.message:String(s)}))})}alignVisualModelToGround(){if(!this._object||!this.group)return;this._animationDelegate?.update(0),this._object.updateMatrixWorld(!0);let e=Ee(this._object,this.group);if(e===null||Math.abs(e)<Ce)return;let t=this.group.scale.y||1;this._object.position.y-=e/t}applyMaterialOverrides(){let e=this.options.material;!e||!e.color&&!e.path&&e.opacity===void 0||this._object&&this._object.traverse(t=>{if(!t.isMesh)return;let o=t;o.material=Array.isArray(o.material)?o.material.map(i=>this.tintMaterial(i,e)):this.tintMaterial(o.material,e),e.color&&(o.castShadow=!0,o.receiveShadow=!0)})}tintMaterial(e,t){let o="color"in e,i=!!t.color,s=t.opacity!==void 0;if(!i&&!s)return e;if(i&&!o)return new Fe({color:t.color,emissiveIntensity:.5,lightMapIntensity:.5,fog:!0,opacity:t.opacity??1,transparent:s&&t.opacity<1});let r=e.clone();if(i&&"color"in r&&r.color.copy(t.color),s&&"opacity"in r&&"transparent"in r){let a=r;a.opacity=t.opacity,a.transparent=t.opacity<1}return r.needsUpdate=!0,r}};function Be(...n){return ee({args:n,defaultConfig:re,EntityClass:O,BuilderClass:U,CollisionBuilderClass:k,entityType:O.type,cloneFactory:e=>Be(e??{})})}import{Color as We,Fog as Ye,FogExp2 as Ke,Group as He}from"three";import{Color as Pe}from"three";import{Fn as fe,fog as Ze,positionWorld as me,positionView as Re,uniform as y,float as Ve,vec3 as g,clamp as N,mix as b,max as ke,smoothstep as Ue,floor as Ie,fract as G,dot as Ne}from"three/tsl";var L=class{values;u={time:y(0),heightEnabled:y(0),heightLevel:y(0),heightFalloff:y(0),noiseEnabled:y(0),noiseScale:y(0),noiseStrength:y(0),noiseSpeed:y(0)};attachedScene=null;constructor(e){this.values={...e},this.syncUniforms()}setValues(e){Object.assign(this.values,e),this.syncUniforms()}tick(e){this.values.time+=e,this.u.time.value=this.values.time}scan(e){if(this.attachedScene===e)return;let t=e.fog;t&&(e.fogNode=this.buildFogNode(t),this.attachedScene=e)}unpatchAll(){this.attachedScene&&(this.attachedScene.fogNode=null,this.attachedScene=null)}syncUniforms(){this.u.time.value=this.values.time,this.u.heightEnabled.value=this.values.heightEnabled,this.u.heightLevel.value=this.values.heightLevel,this.u.heightFalloff.value=this.values.heightFalloff,this.u.noiseEnabled.value=this.values.noiseEnabled,this.u.noiseScale.value=this.values.noiseScale,this.u.noiseStrength.value=this.values.noiseStrength,this.u.noiseSpeed.value=this.values.noiseSpeed}buildFogNode(e){let t=e.isFogExp2===!0,o=y(new Pe(e.color)),i=Re.z.negate(),s=t?this.exp2Factor(y(e.density),i):Ue(y(e.near),y(e.far),i),r=this.u.heightLevel.sub(me.y),a=N(r.mul(ke(this.u.heightFalloff,0)),0,1),l=b(s,s.mul(a),this.u.heightEnabled),h=me.mul(this.u.noiseScale).add(g(this.u.time.mul(this.u.noiseSpeed),0,this.u.time.mul(this.u.noiseSpeed).mul(.5))),c=Ge(h).sub(.5).mul(2).mul(N(this.u.noiseStrength,0,1)),u=N(l.add(l.mul(c)),0,1),p=b(l,u,this.u.noiseEnabled);return Ze(o,p)}exp2Factor(e,t){return e.mul(e).mul(t).mul(t).negate().exp().oneMinus()}},_=fe(([n])=>{let e=G(n.mul(g(443.8975,397.2973,491.1871))),t=e.add(Ne(e,e.yzx.add(19.27)));return G(t.x.add(t.y).mul(t.z))}),Ge=fe(([n])=>{let e=Ie(n),t=G(n),o=t.mul(t).mul(Ve(3).sub(t.mul(2))),i=_(e.add(g(0,0,0))),s=_(e.add(g(1,0,0))),r=_(e.add(g(0,1,0))),a=_(e.add(g(1,1,0))),l=_(e.add(g(0,0,1))),h=_(e.add(g(1,0,1))),d=_(e.add(g(0,1,1))),c=_(e.add(g(1,1,1))),u=b(i,s,o.x),p=b(r,a,o.x),f=b(l,h,o.x),A=b(d,c,o.x),m=b(u,p,o.y),ye=b(f,A,o.y);return b(m,ye,o.z)});var qe=Symbol("Fog"),$e="#9aa3ad",Xe=.015,Je=10,Qe=250,et=5,tt=.2,it=.05,nt=.15,ot=.1,W=class extends D{static type=qe;threeFog=null;attachedScene=null;patcher;patcherEnabled;constructor(e={}){super(),this.options={...e};let t=this.resolveUniformValues(this.options);this.patcher=new L(t),this.patcherEnabled=rt(this.options)}create(){return super.create(),this.threeFog=st(this.options),this.group=new He,this.group.name=this.name?`Fog:${this.name}`:"Fog",this}attachToScene(e){this.threeFog&&(this.attachedScene=e,e.fog=this.threeFog,this.patcherEnabled&&this.patcher.scan(e))}_update(e){super._update(e),!(!this.attachedScene||!this.patcherEnabled)&&(this.patcher.tick(e.delta),this.patcher.scan(this.attachedScene))}_cleanup(e){this.patcher.unpatchAll(),this.attachedScene&&this.attachedScene.fog===this.threeFog&&(this.attachedScene.fog=null),this.attachedScene=null,this.threeFog=null,super._cleanup(e)}resolveUniformValues(e){let t=e.height,o=e.noise;return{time:0,heightEnabled:t?.enabled?1:0,heightLevel:t?.level??et,heightFalloff:t?.falloff??tt,noiseEnabled:o?1:0,noiseScale:o?.scale??it,noiseStrength:o?.strength??nt,noiseSpeed:o?.speed??ot}}};function st(n){let e=new We(n.color??$e);return(n.type??"linear")==="exp2"?new Ke(e,n.density??Xe):new Ye(e,n.start??Je,n.end??Qe)}function rt(n){let e=!!n.height?.enabled,t=!!n.noise;return e||t}function Nt(n={}){return new W(n)}export{Le as a,O as b,Be as c,qe as d,W as e,Nt as f};
@@ -1 +1 @@
1
- import{a as T,b as u,r as w,t as f,v as d}from"./chunk-SAQA4SXW.js";import{j as v}from"./chunk-4QLJUQSJ.js";import{a as _,g as E,i as O,j as b}from"./chunk-7WRQ2UAN.js";import{Group as k,Quaternion as G,Vector3 as N}from"three";import{ParticleEmitterBehavior as x}from"@zylem/behaviors/particle-emitter";var V={...w,effect:{create(){throw new Error("createParticleSystem(...) requires an effect or preset definition.")}},preset:void 0,autoplay:!0,localOffset:void 0,followPosition:!0,followRotation:!0,autoDestroy:!1},I=Symbol("ParticleSystem");function W(n){return{effect:n.preset??n.effect,autoplay:n.autoplay,localOffset:n.localOffset,followPosition:n.followPosition,followRotation:n.followRotation,autoDestroy:n.autoDestroy}}var P=class n extends f{static type=I;particleHandle=null;constructor(o,e=!0){super(),this.options=u(V,o),this.group=new k;let t=this.options.position;t&&this.group.position.copy(b(t)),this.__zylemParticleSystemEntity=!0,this.bindStandaloneTransforms(),e&&(this.particleHandle=this.use(x,W(this.options)))}bindStandaloneTransforms(){let o=()=>{this.options.position=new N(this.group?.position.x??0,this.group?.position.y??0,this.group?.position.z??0)},e=()=>{this.group&&(this._rotation2DAngle=this.group.rotation.z)};this.setPosition=(t,i,r)=>{this.group?.position.set(t,i,r),o()},this.setPositionX=t=>{this.group&&(this.group.position.x=t,o())},this.setPositionY=t=>{this.group&&(this.group.position.y=t,o())},this.setPositionZ=t=>{this.group&&(this.group.position.z=t,o())},this.getPosition=()=>this.group?{x:this.group.position.x,y:this.group.position.y,z:this.group.position.z}:null,this.setRotation=(t,i,r)=>{this.group?.rotation.set(t,i,r),e()},this.setRotationX=t=>{this.group&&(this.group.rotation.x=t,e())},this.setRotationY=t=>{this.group&&(this.group.rotation.y=t,e())},this.setRotationZ=t=>{this.group&&(this.group.rotation.z=t,e())},this.setRotationDegrees=(t,i,r)=>{this.group?.rotation.set(t*Math.PI/180,i*Math.PI/180,r*Math.PI/180),e()},this.setRotationDegreesX=t=>{this.group&&(this.group.rotation.x=t*Math.PI/180,e())},this.setRotationDegreesY=t=>{this.group&&(this.group.rotation.y=t*Math.PI/180,e())},this.setRotationDegreesZ=t=>{this.group&&(this.group.rotation.z=t*Math.PI/180,e())},this.rotateX=t=>{this.group?.rotateX(t),e()},this.rotateY=t=>{this.group?.rotateY(t),e()},this.rotateZ=t=>{this.group?.rotateZ(t),e()},this.getRotation=()=>{if(!this.group)return null;let t=new G;return this.group.getWorldQuaternion(t),t}}resolveParticleHandle(){if(this.particleHandle)return this.particleHandle;let o=this.getBehaviorRefs().find(i=>i.descriptor.key===x.key);if(!o)return null;let e={getFSM:()=>o.fsm??null,getOptions:()=>o.options,ref:o},t=x.createHandle?.(o)??{};return this.particleHandle={...e,...t},this.particleHandle}play(){this.resolveParticleHandle()?.play()}stop(){this.resolveParticleHandle()?.stop()}pause(){this.resolveParticleHandle()?.pause()}restart(){this.resolveParticleHandle()?.restart()}burst(){this.resolveParticleHandle()?.burst()}isPlaying(){return this.resolveParticleHandle()?.isPlaying()??!1}getSystem(){return this.resolveParticleHandle()?.getSystem()}buildInfo(){return{...super.buildInfo(),type:String(n.type)}}};function Z(n,o=!0){let e=new P(n,o);return d(e,t=>Z(t,!1))}function X(n){return Z(n,!0)}import{Group as U,Sprite as Q,SpriteMaterial as $,CanvasTexture as q,LinearFilter as R,Color as H,ClampToEdgeWrapping as M}from"three";import{getCooldown as z}from"@zylem/behaviors/cooldown";var K={"top-left":{fx:0,fy:0},"top-center":{fx:.5,fy:0},"top-right":{fx:1,fy:0},"center-left":{fx:0,fy:.5},center:{fx:.5,fy:.5},"center-right":{fx:1,fy:.5},"bottom-left":{fx:0,fy:1},"bottom-center":{fx:.5,fy:1},"bottom-right":{fx:1,fy:1}},D=192,j={xs:8,sm:16,md:32,lg:48,xl:64},C={position:void 0,cooldown:"",iconSize:"md",fillColor:"#333333",showTimer:!0,stickToViewport:!0,screenAnchor:"top-left",screenPosition:{x:0,y:0},zDistance:1,overlayColor:"rgba(0, 0, 0, 0.65)"},J=Symbol("CooldownIcon"),S=class extends f{static type=J;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_iconTexture=null;_iconImage=null;_lastRenderedProgress=-1;constructor(o){super(),this.options=u(C,o),this.options.screenPosition=O(this.options.screenPosition,C.screenPosition),this.group=new U,this.createSprite(),this.prependSetup(this.iconSetup.bind(this)),this.prependUpdate(this.iconUpdate.bind(this)),this.onCleanup(this.iconDestroy.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._canvas.width=256,this._canvas.height=256,this._ctx=this._canvas.getContext("2d"),this._texture=new q(this._canvas),this._texture.minFilter=R,this._texture.magFilter=R,this._texture.wrapS=M,this._texture.wrapT=M;let e=new $({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1});if(this._sprite=new Q(e),this.group?.add(this._sprite),this.options.icon){let t=new Image;t.crossOrigin="anonymous",t.onload=()=>{this._iconImage=t,this.redraw(this._lastRenderedProgress>=0?this._lastRenderedProgress:1)},t.src=this.options.icon}this.redraw(1)}redraw(o){if(!this._canvas||!this._ctx)return;let e=this._ctx,t=this._canvas.width,i=this._canvas.height,r=t/2,s=i/2,l=Math.min(r,s);if(e.clearRect(0,0,t,i),this._iconImage?e.drawImage(this._iconImage,0,0,t,i):(e.fillStyle=this.toCssColor(this.options.fillColor??"#333333"),e.fillRect(0,0,t,i)),o<1){let p=(1-o)*Math.PI*2,c=-Math.PI/2,h=c+p;if(e.save(),e.fillStyle=this.options.overlayColor??"rgba(0, 0, 0, 0.65)",e.beginPath(),e.moveTo(r,s),e.arc(r,s,l+1,c,h,!1),e.closePath(),e.fill(),e.restore(),this.options.showTimer){let a=z(this.options.cooldown);if(a){let m=Math.max(0,a.duration-a.elapsed),g=m>=10?Math.ceil(m).toString():m.toFixed(1),y=Math.floor(t*.3);e.font=`bold ${y}px sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillStyle="#FFFFFF",e.strokeStyle="#000000",e.lineWidth=2,e.strokeText(g,r,s),e.fillText(g,r,s)}}}this._texture&&(this._texture.needsUpdate=!0),this._lastRenderedProgress=o}toCssColor(o){return typeof o=="string"?o:`#${(o instanceof H?o:new H(o)).getHexString()}`}getResolution(){try{let o=this._cameraRef?.renderer?.domElement;if(o)return{width:o.clientWidth||1,height:o.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}iconSetup(o){this._sprite||this.createSprite(),this._cameraRef=o.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}iconUpdate(o){let t=z(this.options.cooldown)?.progress??1;(Math.abs(t-this._lastRenderedProgress)>.02||t===1&&this._lastRenderedProgress!==1)&&this.redraw(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}resolveScreenPosition(o,e){let t=this.options.screenAnchor??"top-left",i=E(this.options.screenPosition,_),r=i.x,s=i.y,{fx:l,fy:p}=K[t],c=l*o,h=p*e,a=e/D;return{px:c+r*a,py:h+s*a}}resolveIconSize(o){let e=this.options.iconSize??"md",t,i;typeof e=="string"?t=i=j[e]:typeof e=="number"?t=i=e:(t=e.width,i=e.height);let r=o/D;return{widthPx:t*r,heightPx:i*r}}computeWorldExtents(o,e){let t=1,i=1;if(o.isPerspectiveCamera){let r=o,s=Math.tan(r.fov*Math.PI/180/2)*e;t=s*r.aspect,i=s}else if(o.isOrthographicCamera){let r=o;t=(r.right-r.left)/2,i=(r.top-r.bottom)/2}return{worldHalfW:t,worldHalfH:i}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let o=this._cameraRef.camera,{width:e,height:t}=this.getResolution(),{px:i,py:r}=this.resolveScreenPosition(e,t),s=Math.max(.001,this.options.zDistance??1),{worldHalfW:l,worldHalfH:p}=this.computeWorldExtents(o,s),c=i/e*2-1,h=1-r/t*2,a=c*l,m=h*p;{let y=p*2/t,{widthPx:F,heightPx:L}=this.resolveIconSize(t),A=Math.max(1e-4,F*y),B=Math.max(1e-4,L*y);this._sprite.scale.set(A,B,1)}this.group?.position.set(a,m,-s)}iconDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._iconTexture?.dispose(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null,this._iconTexture=null,this._iconImage=null}};function Y(...n){let o=n.filter(t=>!(t instanceof T)),e={...C};for(let t of o)e={...e,...t};return d(new S(e),t=>Y(t??{}))}function tt(n,o,e){e({me:n,globals:o})}function et(n,o){let e=o??v();tt(n,e,n.nodeDestroy.bind(n))}export{I as a,P as b,X as c,Y as d,et as e};
1
+ import{a as T,b as u,r as w,t as f,v as d}from"./chunk-KP6DLLJO.js";import{j as v}from"./chunk-4QLJUQSJ.js";import{a as _,g as E,i as O,j as b}from"./chunk-7WRQ2UAN.js";import{Group as k,Quaternion as G,Vector3 as N}from"three";import{ParticleEmitterBehavior as x}from"@zylem/behaviors/particle-emitter";var V={...w,effect:{create(){throw new Error("createParticleSystem(...) requires an effect or preset definition.")}},preset:void 0,autoplay:!0,localOffset:void 0,followPosition:!0,followRotation:!0,autoDestroy:!1},I=Symbol("ParticleSystem");function W(n){return{effect:n.preset??n.effect,autoplay:n.autoplay,localOffset:n.localOffset,followPosition:n.followPosition,followRotation:n.followRotation,autoDestroy:n.autoDestroy}}var P=class n extends f{static type=I;particleHandle=null;constructor(o,e=!0){super(),this.options=u(V,o),this.group=new k;let t=this.options.position;t&&this.group.position.copy(b(t)),this.__zylemParticleSystemEntity=!0,this.bindStandaloneTransforms(),e&&(this.particleHandle=this.use(x,W(this.options)))}bindStandaloneTransforms(){let o=()=>{this.options.position=new N(this.group?.position.x??0,this.group?.position.y??0,this.group?.position.z??0)},e=()=>{this.group&&(this._rotation2DAngle=this.group.rotation.z)};this.setPosition=(t,i,r)=>{this.group?.position.set(t,i,r),o()},this.setPositionX=t=>{this.group&&(this.group.position.x=t,o())},this.setPositionY=t=>{this.group&&(this.group.position.y=t,o())},this.setPositionZ=t=>{this.group&&(this.group.position.z=t,o())},this.getPosition=()=>this.group?{x:this.group.position.x,y:this.group.position.y,z:this.group.position.z}:null,this.setRotation=(t,i,r)=>{this.group?.rotation.set(t,i,r),e()},this.setRotationX=t=>{this.group&&(this.group.rotation.x=t,e())},this.setRotationY=t=>{this.group&&(this.group.rotation.y=t,e())},this.setRotationZ=t=>{this.group&&(this.group.rotation.z=t,e())},this.setRotationDegrees=(t,i,r)=>{this.group?.rotation.set(t*Math.PI/180,i*Math.PI/180,r*Math.PI/180),e()},this.setRotationDegreesX=t=>{this.group&&(this.group.rotation.x=t*Math.PI/180,e())},this.setRotationDegreesY=t=>{this.group&&(this.group.rotation.y=t*Math.PI/180,e())},this.setRotationDegreesZ=t=>{this.group&&(this.group.rotation.z=t*Math.PI/180,e())},this.rotateX=t=>{this.group?.rotateX(t),e()},this.rotateY=t=>{this.group?.rotateY(t),e()},this.rotateZ=t=>{this.group?.rotateZ(t),e()},this.getRotation=()=>{if(!this.group)return null;let t=new G;return this.group.getWorldQuaternion(t),t}}resolveParticleHandle(){if(this.particleHandle)return this.particleHandle;let o=this.getBehaviorRefs().find(i=>i.descriptor.key===x.key);if(!o)return null;let e={getFSM:()=>o.fsm??null,getOptions:()=>o.options,ref:o},t=x.createHandle?.(o)??{};return this.particleHandle={...e,...t},this.particleHandle}play(){this.resolveParticleHandle()?.play()}stop(){this.resolveParticleHandle()?.stop()}pause(){this.resolveParticleHandle()?.pause()}restart(){this.resolveParticleHandle()?.restart()}burst(){this.resolveParticleHandle()?.burst()}isPlaying(){return this.resolveParticleHandle()?.isPlaying()??!1}getSystem(){return this.resolveParticleHandle()?.getSystem()}buildInfo(){return{...super.buildInfo(),type:String(n.type)}}};function Z(n,o=!0){let e=new P(n,o);return d(e,t=>Z(t,!1))}function X(n){return Z(n,!0)}import{Group as U,Sprite as Q,SpriteMaterial as $,CanvasTexture as q,LinearFilter as R,Color as H,ClampToEdgeWrapping as M}from"three";import{getCooldown as z}from"@zylem/behaviors/cooldown";var K={"top-left":{fx:0,fy:0},"top-center":{fx:.5,fy:0},"top-right":{fx:1,fy:0},"center-left":{fx:0,fy:.5},center:{fx:.5,fy:.5},"center-right":{fx:1,fy:.5},"bottom-left":{fx:0,fy:1},"bottom-center":{fx:.5,fy:1},"bottom-right":{fx:1,fy:1}},D=192,j={xs:8,sm:16,md:32,lg:48,xl:64},C={position:void 0,cooldown:"",iconSize:"md",fillColor:"#333333",showTimer:!0,stickToViewport:!0,screenAnchor:"top-left",screenPosition:{x:0,y:0},zDistance:1,overlayColor:"rgba(0, 0, 0, 0.65)"},J=Symbol("CooldownIcon"),S=class extends f{static type=J;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_iconTexture=null;_iconImage=null;_lastRenderedProgress=-1;constructor(o){super(),this.options=u(C,o),this.options.screenPosition=O(this.options.screenPosition,C.screenPosition),this.group=new U,this.createSprite(),this.prependSetup(this.iconSetup.bind(this)),this.prependUpdate(this.iconUpdate.bind(this)),this.onCleanup(this.iconDestroy.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._canvas.width=256,this._canvas.height=256,this._ctx=this._canvas.getContext("2d"),this._texture=new q(this._canvas),this._texture.minFilter=R,this._texture.magFilter=R,this._texture.wrapS=M,this._texture.wrapT=M;let e=new $({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1});if(this._sprite=new Q(e),this.group?.add(this._sprite),this.options.icon){let t=new Image;t.crossOrigin="anonymous",t.onload=()=>{this._iconImage=t,this.redraw(this._lastRenderedProgress>=0?this._lastRenderedProgress:1)},t.src=this.options.icon}this.redraw(1)}redraw(o){if(!this._canvas||!this._ctx)return;let e=this._ctx,t=this._canvas.width,i=this._canvas.height,r=t/2,s=i/2,l=Math.min(r,s);if(e.clearRect(0,0,t,i),this._iconImage?e.drawImage(this._iconImage,0,0,t,i):(e.fillStyle=this.toCssColor(this.options.fillColor??"#333333"),e.fillRect(0,0,t,i)),o<1){let p=(1-o)*Math.PI*2,c=-Math.PI/2,h=c+p;if(e.save(),e.fillStyle=this.options.overlayColor??"rgba(0, 0, 0, 0.65)",e.beginPath(),e.moveTo(r,s),e.arc(r,s,l+1,c,h,!1),e.closePath(),e.fill(),e.restore(),this.options.showTimer){let a=z(this.options.cooldown);if(a){let m=Math.max(0,a.duration-a.elapsed),g=m>=10?Math.ceil(m).toString():m.toFixed(1),y=Math.floor(t*.3);e.font=`bold ${y}px sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillStyle="#FFFFFF",e.strokeStyle="#000000",e.lineWidth=2,e.strokeText(g,r,s),e.fillText(g,r,s)}}}this._texture&&(this._texture.needsUpdate=!0),this._lastRenderedProgress=o}toCssColor(o){return typeof o=="string"?o:`#${(o instanceof H?o:new H(o)).getHexString()}`}getResolution(){try{let o=this._cameraRef?.renderer?.domElement;if(o)return{width:o.clientWidth||1,height:o.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}iconSetup(o){this._sprite||this.createSprite(),this._cameraRef=o.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}iconUpdate(o){let t=z(this.options.cooldown)?.progress??1;(Math.abs(t-this._lastRenderedProgress)>.02||t===1&&this._lastRenderedProgress!==1)&&this.redraw(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}resolveScreenPosition(o,e){let t=this.options.screenAnchor??"top-left",i=E(this.options.screenPosition,_),r=i.x,s=i.y,{fx:l,fy:p}=K[t],c=l*o,h=p*e,a=e/D;return{px:c+r*a,py:h+s*a}}resolveIconSize(o){let e=this.options.iconSize??"md",t,i;typeof e=="string"?t=i=j[e]:typeof e=="number"?t=i=e:(t=e.width,i=e.height);let r=o/D;return{widthPx:t*r,heightPx:i*r}}computeWorldExtents(o,e){let t=1,i=1;if(o.isPerspectiveCamera){let r=o,s=Math.tan(r.fov*Math.PI/180/2)*e;t=s*r.aspect,i=s}else if(o.isOrthographicCamera){let r=o;t=(r.right-r.left)/2,i=(r.top-r.bottom)/2}return{worldHalfW:t,worldHalfH:i}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let o=this._cameraRef.camera,{width:e,height:t}=this.getResolution(),{px:i,py:r}=this.resolveScreenPosition(e,t),s=Math.max(.001,this.options.zDistance??1),{worldHalfW:l,worldHalfH:p}=this.computeWorldExtents(o,s),c=i/e*2-1,h=1-r/t*2,a=c*l,m=h*p;{let y=p*2/t,{widthPx:F,heightPx:L}=this.resolveIconSize(t),A=Math.max(1e-4,F*y),B=Math.max(1e-4,L*y);this._sprite.scale.set(A,B,1)}this.group?.position.set(a,m,-s)}iconDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._iconTexture?.dispose(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null,this._iconTexture=null,this._iconImage=null}};function Y(...n){let o=n.filter(t=>!(t instanceof T)),e={...C};for(let t of o)e={...e,...t};return d(new S(e),t=>Y(t??{}))}function tt(n,o,e){e({me:n,globals:o})}function et(n,o){let e=o??v();tt(n,e,n.nodeDestroy.bind(n))}export{I as a,P as b,X as c,Y as d,et as e};