@zylem/game-lib 0.9.5 → 0.9.7
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.
- package/dist/actions.d.ts +3 -3
- package/dist/api/game-lib.api.json +100288 -42733
- package/dist/api/game-lib.api.md +3842 -685
- package/dist/api/game-lib.d.ts +8934 -818
- package/dist/api/game-lib.typedoc.json +327569 -192737
- package/dist/behavior/action/fighting.d.ts +1 -0
- package/dist/behavior/action/fighting.js +1 -0
- package/dist/behavior/action/pinball.d.ts +1 -0
- package/dist/behavior/action/pinball.js +1 -0
- package/dist/behavior/action/platform.d.ts +1 -0
- package/dist/behavior/action/platform.js +1 -0
- package/dist/behavior/action/rhythm.d.ts +1 -0
- package/dist/behavior/action/rhythm.js +1 -0
- package/dist/behavior/action/shooter/first-person.d.ts +1 -0
- package/dist/behavior/action/shooter/first-person.js +1 -0
- package/dist/behavior/action/shooter/shoot-em-up.d.ts +1 -0
- package/dist/behavior/action/shooter/shoot-em-up.js +1 -0
- package/dist/behavior/action/shooter.d.ts +1 -0
- package/dist/behavior/action/shooter.js +1 -0
- package/dist/behavior/action/stealth.d.ts +1 -0
- package/dist/behavior/action/stealth.js +1 -0
- package/dist/behavior/action/survival.d.ts +1 -0
- package/dist/behavior/action/survival.js +1 -0
- package/dist/behavior/action-adventure.d.ts +1 -0
- package/dist/behavior/action-adventure.js +1 -0
- package/dist/behavior/action.d.ts +1 -0
- package/dist/behavior/action.js +1 -0
- package/dist/behavior/genre-map.d.ts +1 -0
- package/dist/behavior/genre-map.js +1 -0
- package/dist/behavior/mechanics.d.ts +1 -0
- package/dist/behavior/mechanics.js +1 -0
- package/dist/behavior/puzzle/physics.d.ts +1 -0
- package/dist/behavior/puzzle/physics.js +1 -0
- package/dist/behavior/puzzle/tile-matching.d.ts +1 -0
- package/dist/behavior/puzzle/tile-matching.js +1 -0
- package/dist/behavior/puzzle.d.ts +1 -0
- package/dist/behavior/puzzle.js +1 -0
- package/dist/behavior/role-playing/action-rpg.d.ts +1 -0
- package/dist/behavior/role-playing/action-rpg.js +1 -0
- package/dist/behavior/role-playing/monster-taming.d.ts +1 -0
- package/dist/behavior/role-playing/monster-taming.js +1 -0
- package/dist/behavior/role-playing/tactical-rpg.d.ts +1 -0
- package/dist/behavior/role-playing/tactical-rpg.js +1 -0
- package/dist/behavior/role-playing/turn-based.d.ts +1 -0
- package/dist/behavior/role-playing/turn-based.js +1 -0
- package/dist/behavior/role-playing.d.ts +1 -0
- package/dist/behavior/role-playing.js +1 -0
- package/dist/behavior/simulation/life.d.ts +1 -0
- package/dist/behavior/simulation/life.js +1 -0
- package/dist/behavior/simulation/vehicle/racing.d.ts +1 -0
- package/dist/behavior/simulation/vehicle/racing.js +1 -0
- package/dist/behavior/simulation/vehicle.d.ts +1 -0
- package/dist/behavior/simulation/vehicle.js +1 -0
- package/dist/behavior/simulation.d.ts +1 -0
- package/dist/behavior/simulation.js +1 -0
- package/dist/behavior/sports/golf.d.ts +1 -0
- package/dist/behavior/sports/golf.js +1 -0
- package/dist/behavior/sports/racing.d.ts +1 -0
- package/dist/behavior/sports/racing.js +1 -0
- package/dist/behavior/sports/racket.d.ts +1 -0
- package/dist/behavior/sports/racket.js +1 -0
- package/dist/behavior/sports/skate.d.ts +1 -0
- package/dist/behavior/sports/skate.js +1 -0
- package/dist/behavior/sports.d.ts +1 -0
- package/dist/behavior/sports.js +1 -0
- package/dist/behavior/strategy/real-time-tactics.d.ts +1 -0
- package/dist/behavior/strategy/real-time-tactics.js +1 -0
- package/dist/behavior/strategy/tower-defense.d.ts +1 -0
- package/dist/behavior/strategy/tower-defense.js +1 -0
- package/dist/behavior/strategy/turn-based-tactics.d.ts +1 -0
- package/dist/behavior/strategy/turn-based-tactics.js +1 -0
- package/dist/behavior/strategy.d.ts +1 -0
- package/dist/behavior/strategy.js +1 -0
- package/dist/behavior.d.ts +34 -0
- package/dist/bridge.d.ts +9 -2
- package/dist/bridge.js +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.js +1 -1
- package/dist/{chunk-BQRMYLYD.js → chunk-273CUPEO.js} +1 -1
- package/dist/chunk-4DAITCJS.js +1 -0
- package/dist/chunk-63T3K5EQ.js +1 -0
- package/dist/chunk-AJSIVGDX.js +1 -0
- package/dist/chunk-CVKEWWIH.js +1 -0
- package/dist/chunk-DYD7MDWO.js +1 -0
- package/dist/chunk-IHGRFR4H.js +1 -0
- package/dist/{chunk-4CZZZCFB.js → chunk-JCGW5PIR.js} +1 -1
- package/dist/{chunk-2IJLXFWY.js → chunk-JJEYLGD2.js} +4 -4
- package/dist/chunk-KL7NGD76.js +1 -0
- package/dist/chunk-M2FZ224T.js +1 -0
- package/dist/chunk-MJ7RGE47.js +1 -0
- package/dist/chunk-Q22Z4PBD.js +19 -0
- package/dist/chunk-SD7EHS4W.js +1 -0
- package/dist/chunk-UKNMIHAP.js +1 -0
- package/dist/chunk-UM5VNQPY.js +1 -0
- package/dist/chunk-Y5IU6IA5.js +1 -0
- package/dist/cinematics.d.ts +8 -5
- package/dist/core.d.ts +25 -10
- package/dist/core.js +1 -1
- package/dist/{debug-state-Cg3f5FB6.d.ts → debug-state-BgX5Q0Ff.d.ts} +2 -2
- package/dist/debug.d.ts +6 -125
- package/dist/debug.js +1 -1
- package/dist/{entity-XqvuWgPm.d.ts → entity-CY75JJSw.d.ts} +83 -4
- package/dist/{entity-type-map-CrsrKT8c.d.ts → entity-type-map-BMaPY8cd.d.ts} +53 -14
- package/dist/entity.d.ts +6 -18
- package/dist/entity.js +1 -1
- package/dist/{game-DBt7iVu4.d.ts → game-CmkhPP-9.d.ts} +8 -8
- package/dist/game-default-LAGMEHNQ.js +1 -0
- package/dist/graphics.d.ts +3 -3
- package/dist/graphics.js +1 -1
- package/dist/level-types-D10LiOcn.d.ts +91 -0
- package/dist/{material-CxxAyJYp.d.ts → material-D1IVeQc5.d.ts} +48 -2
- package/dist/placement-session-BNQoL7Jb.d.ts +82 -0
- package/dist/placement.d.ts +52 -0
- package/dist/placement.js +1 -0
- package/dist/public.d.ts +14 -10
- package/dist/public.js +1 -1
- package/dist/{stage-PBmwT5-Y.d.ts → stage-CCGJh9TD.d.ts} +189 -7
- package/dist/transform-gizmo-DappLQ9w.d.ts +123 -0
- package/dist/web-components.d.ts +10 -7
- package/dist/web-components.js +1 -1
- package/dist/{zylem-camera-CWhIGXlW.d.ts → zylem-camera-BA3VPFlS.d.ts} +9 -0
- package/package.json +147 -7
- package/dist/chunk-3CLQWJ2I.js +0 -1
- package/dist/chunk-6FGXC4T6.js +0 -19
- package/dist/chunk-GPCSX3M6.js +0 -1
- package/dist/chunk-K3NNXZIJ.js +0 -1
- package/dist/chunk-KP6DLLJO.js +0 -1
- package/dist/chunk-LI43BZQN.js +0 -1
- package/dist/chunk-NK4IXK5V.js +0 -1
- package/dist/chunk-QB3NL7VQ.js +0 -1
- package/dist/chunk-STVEILJJ.js +0 -1
- package/dist/chunk-VSFULLND.js +0 -1
- package/dist/chunk-YQS7CGXE.js +0 -1
- package/dist/game-default-BAZPDNPS.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as J,c as Q,d as ee}from"./chunk-IHGRFR4H.js";import{D,b as q,q as $,r as X}from"./chunk-AJSIVGDX.js";import{d as K,f as H,g as j}from"./chunk-Q22Z4PBD.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:!!n.collision?.sensor}}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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as v,D as E,F as l,r as m,s,w as y,y as c,z as i}from"./chunk-AJSIVGDX.js";import{Group as O,Vector3 as f}from"three";var A={...m,size:new f(1,1,1)},u=Symbol("HoverArea"),P=Symbol("DroppableArea");function n(t,e,r){let o=y(t);if(!o){r?i(t,e):c(t,e);return}if(r&&o.role!=="droppable"){i(t,{...o.handlers,...e});return}v(t,e)}var a=class extends E{static type=u;areaName="HoverArea";constructor(e){super(),this.options={...A,...e}}create(){return super.create(),this.group||(this.group=new O),this.group.name=this.name||this.areaName,this}onEnter(e){return n(this,{onEnter:e},!1),this}onLeave(e){return n(this,{onLeave:e},!1),this}onMove(e){return n(this,{onMove:e},!1),this}onClick(e){return n(this,{onClick:e},!1),this}},p=class extends a{static type=P;areaName="DroppableArea";onDrop(e){return n(this,{onDrop:e},!0),this}accepts(e){return n(this,{accepts:e},!0),this}};function b(t){return{onEnter:t.onEnter,onLeave:t.onLeave,onMove:t.onMove,onClick:t.onClick,onDrop:t.onDrop,accepts:t.accepts,placeAt:t.placeAt}}function h(...t){let e=s(t,A),r=new a(e);return c(r,b(e)),l(r,o=>h(o??{}))}function x(...t){let e=s(t,A),r=new p(e);return i(r,b(e)),l(r,o=>x(o??{}))}export{u as a,P as b,a as c,p as d,h as e,x as f};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{a as B}from"./chunk-QXVH6POE.js";import{b as p,i as u}from"./chunk-7WRQ2UAN.js";var j=`
|
|
2
|
+
uniform vec2 uvScale;
|
|
3
|
+
varying vec2 vUv;
|
|
4
|
+
|
|
5
|
+
void main() {
|
|
6
|
+
vUv = uv;
|
|
7
|
+
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
|
|
8
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
9
|
+
}
|
|
10
|
+
`;var _=`
|
|
11
|
+
uniform sampler2D tDiffuse;
|
|
12
|
+
varying vec2 vUv;
|
|
13
|
+
|
|
14
|
+
void main() {
|
|
15
|
+
vec4 texel = texture2D( tDiffuse, vUv );
|
|
16
|
+
|
|
17
|
+
gl_FragColor = texel;
|
|
18
|
+
}
|
|
19
|
+
`,S={vertex:j,fragment:_};import{AdditiveBlending as Y}from"three";import{MeshBasicNodeMaterial as k,MeshStandardNodeMaterial as q}from"three/webgpu";import{color as U,float as L,normalLocal as Q,normalView as ee,positionGeometry as te,positionViewDirection as re,vec4 as ae}from"three/tsl";function N(s,e){if(!s)return null;let t=s===!0?{}:s;return{color:t.color??e??"#ffffff",intensity:t.intensity??2.8,size:t.size??.06,falloff:t.falloff??1.6}}function D(s){return typeof s=="string"?s:`#${s.getHexString()}`}function X(){return ee.dot(re).abs().saturate()}function W(s){let e=X(),t=e.pow(L(s.falloff)),r=U(D(s.color)).mul(L(s.intensity)).mul(t),a=new k;if(a.colorNode=ae(r,t),s.size>0){let o=e.oneMinus().add(.2);a.positionNode=te.add(Q.mul(L(s.size).mul(o)))}return a.transparent=!0,a.blending=Y,a.depthWrite=!1,a.toneMapped=!1,a.needsUpdate=!0,a}function I(s,e){if(!(s instanceof q)&&!(s instanceof k))return;let r=X().oneMinus().pow(L(e.falloff)),a=s;a.emissiveNode=U(D(e.color)).mul(L(e.intensity)).mul(r.add(.2)),s.needsUpdate=!0}import{Color as C,RepeatWrapping as v,SRGBColorSpace as Te}from"three";import{MeshBasicNodeMaterial as Me,MeshStandardNodeMaterial as G}from"three/webgpu";function J(s){let e=Object.keys(s).sort().reduce((t,r)=>(t[r]=s[r],t),{});return JSON.stringify(e)}function K(s){let e=0;for(let t=0;t<s.length;t++)e=Math.imul(31,e)+s.charCodeAt(t)|0;return e.toString(36)}import{LoadingManager as ye,Cache as $}from"three";import{TextureLoader as oe,RepeatWrapping as Z}from"three";var w=16,g=class{loader;constructor(){this.loader=new oe}isSupported(e){let t=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","bmp","tga"].includes(t||"")}async load(e,t){let r=await this.loader.loadAsync(e,a=>{t?.onProgress&&a.lengthComputable&&t.onProgress(a.loaded/a.total)});return t?.repeat&&r.repeat.copy(u(t.repeat,p)),r.wrapS=t?.wrapS??Z,r.wrapT=t?.wrapT??Z,t?.colorSpace!==void 0&&(r.colorSpace=t.colorSpace),r.anisotropy=t?.anisotropy??w,r}clone(e){let t=e.clone();return t.anisotropy=e.anisotropy||w,t.needsUpdate=!0,t}};import{GLTFLoader as ie}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as de}from"three/addons/loaders/DRACOLoader.js";import{KTX2Loader as le}from"three/addons/loaders/KTX2Loader.js";import{MeshoptDecoder as ce}from"three/addons/libs/meshopt_decoder.module.js";import{Mesh as V}from"three";import{clone as se}from"three/addons/utils/SkeletonUtils.js";function m(s){let e=se(s),t=[],r=[];s.traverse(a=>t.push(a)),e.traverse(a=>r.push(a));for(let a=0;a<t.length;a++){let o=t[a],n=r[a];!(o instanceof V)||!(n instanceof V)||(o.geometry?.clone&&(n.geometry=o.geometry.clone()),o.material&&(n.material=Array.isArray(o.material)?o.material.map(i=>i.clone()):o.material.clone()))}return e}function ne(s){let e=s.indexOf("?"),t=s.indexOf("#"),r=[e,t].filter(a=>a>=0).reduce((a,o)=>Math.min(a,o),s.length);return s.slice(0,r)}function c(s){let e=ne(s),t=e.lastIndexOf("/"),r=t>=0?e.slice(t+1):e,a=r.lastIndexOf(".");return a<0||a===r.length-1?null:r.slice(a+1).toLowerCase()}var pe=["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"],he="https://www.gstatic.com/draco/v1/decoders/",y=class{loader;dracoLoader;ktx2Loader=null;meshoptEnabled=!1;configuredRenderer=null;ktx2TranscoderPath=null;constructor(){this.dracoLoader=new de,this.dracoLoader.setDecoderPath(he),this.loader=new ie,this.loader.setDRACOLoader(this.dracoLoader),this.setMeshoptEnabled(!0)}isSupported(e){let t=c(e);return["gltf","glb"].includes(t||"")}async configureRuntime({meshopt:e=!0,ktx2TranscoderPath:t,renderer:r=null}={}){this.setMeshoptEnabled(e!==!1);let a=this.normalizeTranscoderPath(t);if(!a){this.clearKTX2Loader();return}if(!r)throw new Error("GLTFLoaderAdapter.configureRuntime requires a renderer when ktx2TranscoderPath is provided.");(!this.ktx2Loader||this.ktx2TranscoderPath!==a)&&(this.clearKTX2Loader(),this.ktx2Loader=new le,this.ktx2Loader.setTranscoderPath(a),this.loader.setKTX2Loader(this.ktx2Loader),this.ktx2TranscoderPath=a,this.configuredRenderer=null),!(!this.ktx2Loader||this.configuredRenderer===r)&&(this.ktx2Loader.detectSupport(r),this.configuredRenderer=r)}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=await this.loader.parseAsync(a,e);return this.applyTextureAnisotropy(o.scene),{object:o.scene,animations:o.animations,gltf:o}}catch(r){return console.error(`Async fetch GLTF load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{this.applyTextureAnisotropy(o.scene),r({object:o.scene,animations:o.animations,gltf:o})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:m(e.object),animations:e.animations?.map(t=>t.clone()),gltf:e.gltf}}applyTextureAnisotropy(e){e.traverse(t=>{let r=t.material;if(!r)return;let a=Array.isArray(r)?r:[r];for(let o of a)for(let n of pe){let i=o[n];if(i&&i.isTexture){let d=i;d.anisotropy=w,d.needsUpdate=!0}}})}setMeshoptEnabled(e){if(e){if(this.meshoptEnabled)return;this.loader.setMeshoptDecoder(ce),this.meshoptEnabled=!0;return}this.meshoptEnabled&&(this.loader.setMeshoptDecoder(void 0),this.meshoptEnabled=!1)}clearKTX2Loader(){this.ktx2Loader&&(this.ktx2Loader.dispose(),this.ktx2Loader=null),this.loader.setKTX2Loader(void 0),this.configuredRenderer=null,this.ktx2TranscoderPath=null}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}};import{FBXLoader as ue}from"three/addons/loaders/FBXLoader.js";var T=class{loader;constructor(){this.loader=new ue}isSupported(e){return c(e)==="fbx"}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=this.loader.parse(a,e);return{object:o,animations:o.animations||[]}}catch(r){return console.error(`Async fetch FBX load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:o.animations||[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:m(e.object),animations:e.animations?.map(t=>t.clone())}}};import{OBJLoader as me}from"three/addons/loaders/OBJLoader.js";import{MTLLoader as fe}from"three/addons/loaders/MTLLoader.js";var M=class{loader;mtlLoader;constructor(){this.loader=new me,this.mtlLoader=new fe}isSupported(e){return c(e)==="obj"}async load(e,t){return t?.mtlPath&&await this.loadMTL(t.mtlPath),new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}async loadMTL(e){return new Promise((t,r)=>{this.mtlLoader.load(e,a=>{a.preload(),this.loader.setMaterials(a),t()},void 0,a=>r(a))})}clone(e){return{object:m(e.object),animations:[]}}};import{AudioLoader as Le}from"three";var x=class{loader;constructor(){this.loader=new Le}isSupported(e){let t=c(e);return["mp3","ogg","wav","flac","aac","m4a"].includes(t||"")}async load(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>r(o),o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}};import{FileLoader as ge}from"three";var f=class{loader;constructor(){this.loader=new ge}isSupported(e){return!0}async load(e,t){let r=t?.responseType??"text";return this.loader.setResponseType(r),new Promise((a,o)=>{this.loader.load(e,n=>a(n),n=>{t?.onProgress&&n.lengthComputable&&t.onProgress(n.loaded/n.total)},n=>o(n))})}},b=class{fileLoader;constructor(){this.fileLoader=new f}isSupported(e){return c(e)==="json"}async load(e,t){return await this.fileLoader.load(e,{...t,responseType:"json"})}};var P=class s{static instance=null;textureCache=new Map;modelCache=new Map;audioCache=new Map;fileCache=new Map;jsonCache=new Map;pendingGLTFRuntimePath=null;pendingGLTFRuntimePromise=null;pendingGLTFRuntimeResolve=null;textureLoader;gltfLoader;fbxLoader;objLoader;audioLoader;fileLoader;jsonLoader;loadingManager;events;stats={texturesLoaded:0,modelsLoaded:0,audioLoaded:0,filesLoaded:0,cacheHits:0,cacheMisses:0};constructor(){this.textureLoader=new g,this.gltfLoader=new y,this.fbxLoader=new T,this.objLoader=new M,this.audioLoader=new x,this.fileLoader=new f,this.jsonLoader=new b,this.loadingManager=new ye,this.loadingManager.onProgress=(e,t,r)=>{this.events.emit("batch:progress",{loaded:t,total:r})},this.events=B(),$.enabled=!0}static getInstance(){return s.instance||(s.instance=new s),s.instance}static resetInstance(){s.instance&&(s.instance.clearCache(),s.instance=null)}async loadTexture(e,t){return this.loadWithCache(e,"texture",this.textureCache,()=>this.textureLoader.load(e,t),t,r=>{if(!t?.clone)return r;let a=this.textureLoader.clone(r);return t.repeat&&a.repeat.copy(u(t.repeat,p)),t.wrapS!==void 0&&(a.wrapS=t.wrapS),t.wrapT!==void 0&&(a.wrapT=t.wrapT),a})}async loadGLTF(e,t){return await this.waitForPreparedGLTFRuntime(),this.loadWithCache(e,"gltf",this.modelCache,()=>this.gltfLoader.load(e,t),t,r=>t?.clone?this.gltfLoader.clone(r):r)}prepareGLTFRuntime(e){let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&(this.pendingGLTFRuntimePath===t&&this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePath=t,this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePromise=new Promise(r=>{this.pendingGLTFRuntimeResolve=r}))))}async configureGLTFRuntime(e){await this.gltfLoader.configureRuntime(e);let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&e?.renderer&&this.resolvePreparedGLTFRuntime(t)}async loadFBX(e,t){return this.loadWithCache(e,"fbx",this.modelCache,()=>this.fbxLoader.load(e,t),t,r=>t?.clone?this.fbxLoader.clone(r):r)}async loadOBJ(e,t){let r=t?.mtlPath?`${e}:${t.mtlPath}`:e;return this.loadWithCache(r,"obj",this.modelCache,()=>this.objLoader.load(e,t),t,a=>t?.clone?this.objLoader.clone(a):a)}async loadModel(e,t){let r=c(e);switch(r){case"gltf":case"glb":return this.loadGLTF(e,t);case"fbx":return this.loadFBX(e,t);case"obj":return this.loadOBJ(e,t);default:throw new Error(`Unsupported model format: ${r}`)}}async loadAudio(e,t){return this.loadWithCache(e,"audio",this.audioCache,()=>this.audioLoader.load(e,t),t)}async loadFile(e,t){let r=t?.responseType?`${e}:${t.responseType}`:e;return this.loadWithCache(r,"file",this.fileCache,()=>this.fileLoader.load(e,t),t)}async loadJSON(e,t){return this.loadWithCache(e,"json",this.jsonCache,()=>this.jsonLoader.load(e,t),t)}async loadBatch(e){let t=new Map,r=e.map(async a=>{try{let o;switch(a.type){case"texture":o=await this.loadTexture(a.url,a.options);break;case"gltf":o=await this.loadGLTF(a.url,a.options);break;case"fbx":o=await this.loadFBX(a.url,a.options);break;case"obj":o=await this.loadOBJ(a.url,a.options);break;case"audio":o=await this.loadAudio(a.url,a.options);break;case"file":o=await this.loadFile(a.url,a.options);break;case"json":o=await this.loadJSON(a.url,a.options);break;default:throw new Error(`Unknown asset type: ${a.type}`)}t.set(a.url,o)}catch(o){throw this.events.emit("asset:error",{url:a.url,type:a.type,error:o}),o}});return await Promise.all(r),this.events.emit("batch:complete",{urls:e.map(a=>a.url)}),t}async preload(e){await this.loadBatch(e)}isCached(e){return this.textureCache.has(e)||this.modelCache.has(e)||this.audioCache.has(e)||this.fileCache.has(e)||this.jsonCache.has(e)}clearCache(e){e?(this.textureCache.delete(e),this.modelCache.delete(e),this.audioCache.delete(e),this.fileCache.delete(e),this.jsonCache.delete(e)):(this.textureCache.clear(),this.modelCache.clear(),this.audioCache.clear(),this.fileCache.clear(),this.jsonCache.clear(),$.clear(),this.pendingGLTFRuntimePath=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimeResolve=null)}getStats(){return{...this.stats}}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}async loadWithCache(e,t,r,a,o,n){o?.forceReload&&r.delete(e);let i=r.get(e);if(i){this.stats.cacheHits++,this.events.emit("asset:loaded",{url:e,type:t,fromCache:!0});let l=await i.promise;return n?n(l):l}this.stats.cacheMisses++,this.events.emit("asset:loading",{url:e,type:t});let d=a(),h={promise:d,loadedAt:Date.now()};r.set(e,h);try{let l=await d;return h.result=l,this.updateStats(t),this.events.emit("asset:loaded",{url:e,type:t,fromCache:!1}),n?n(l):l}catch(l){throw r.delete(e),this.events.emit("asset:error",{url:e,type:t,error:l}),l}}updateStats(e){switch(e){case"texture":this.stats.texturesLoaded++;break;case"gltf":case"fbx":case"obj":this.stats.modelsLoaded++;break;case"audio":this.stats.audioLoaded++;break;case"file":case"json":this.stats.filesLoaded++;break}}async waitForPreparedGLTFRuntime(){this.pendingGLTFRuntimePromise&&await this.pendingGLTFRuntimePromise}resolvePreparedGLTFRuntime(e){this.pendingGLTFRuntimePath&&this.pendingGLTFRuntimePath!==e||(this.pendingGLTFRuntimeResolve?.(),this.pendingGLTFRuntimeResolve=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimePath=null)}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}},R=P.getInstance();import{uniform as $t,uv as zt,time as Ht,vec3 as _t,vec4 as Yt,float as qt,Fn as Qt}from"three/tsl";function xe(s){return"colorNode"in s}function H(s){return"fragment"in s&&"vertex"in s}function be(s){return!!s&&H(s)&&s.vertex===S.vertex&&s.fragment===S.fragment}var z=class s{static sharedMaterialMap=new Map;static clearSharedMaterialCache(){s.sharedMaterialMap.clear()}materials=[];useTSL;constructor(e=!0){this.useTSL=e}trackSharedMaterial(e,t){let r=K(J(e)),a=s.sharedMaterialMap.get(r);if(a){let o=a.geometryMap.get(t);o?a.geometryMap.set(t,o+1):a.geometryMap.set(t,1)}else s.sharedMaterialMap.set(r,{geometryMap:new Map([[t,1]]),material:this.materials[0]})}build(e,t){let{path:r,normalMap:a,repeat:o,color:n,shader:i,opacity:d}=e,h=N(e.glow,n),l=be(i),O=!!i&&!l,A=!!r&&(!i||l),F=h!==null&&!A&&!O&&!r;if(A?this.setTexture(r??null,o,!0,d,n):O&&i?xe(i)?this.setTSLShader(i,d):H(i)&&(console.warn("MaterialBuilder: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(n??new C("#ffffff"),!0,d)):r&&this.setTexture(r,o,!0,d,n),n&&!A&&!O&&!F&&this.withColor(n,!0,d),this.materials.length===0&&(F&&h?this.materials.push(W(h)):this.setColor(new C("#ffffff"),!0,d)),h&&!F&&this.materials.length>0){let E=this.materials[this.materials.length-1];E&&I(E,h)}a&&this.materials.length>0&&this.setNormalMap(a,o),this.trackSharedMaterial(e,t)}withColor(e,t=!1,r){return this.setColor(e,t,r),this}withShader(e,t){return this.setShader(e,t),this}withTSLShader(e,t){return this.setTSLShader(e,t),this}applyOpacity(e,t,r=!1){t!==void 0&&(e.opacity=t),e.transparent=r||t!==void 0&&t<1,e.needsUpdate=!0}setTexture(e=null,t=p,r=!0,a,o){if(!e)return;let n=new G;o&&(n.color=o),this.applyOpacity(n,a),this.materials.push(n),R.loadTexture(e,{clone:!0,repeat:u(t,p),colorSpace:Te}).then(i=>{i.wrapS=v,i.wrapT=v,n.map=i,n.needsUpdate=!0})}setNormalMap(e,t=p){let r=this.materials[this.materials.length-1];r&&R.loadTexture(e,{clone:!0,repeat:u(t,p)}).then(a=>{a.wrapS=v,a.wrapT=v,r instanceof G&&(r.normalMap=a,r.needsUpdate=!0)})}setColor(e,t=!0,r){let a=new G;a.color=e,this.applyOpacity(a,r),this.materials.push(a)}setShader(e,t){console.warn("MaterialBuilder.setShader: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(new C("#ffffff"),!0,t)}setTSLShader(e,t){this.materials.push(we(e,t))}};function we(s,e){let t=new Me;return t.colorNode=s.colorNode,s.positionNode&&(t.positionNode=s.positionNode),s.normalNode&&(t.normalNode=s.normalNode),s.blending!==void 0&&(t.blending=s.blending),s.side!==void 0&&(t.side=s.side),s.depthTest!==void 0&&(t.depthTest=s.depthTest),e!==void 0&&(t.opacity=e),t.transparent=!!s.transparent||e!==void 0&&e<1,t.needsUpdate=!0,t}export{J as a,K as b,j as c,S as d,w as e,c as f,R as g,W as h,I as i,xe as j,H as k,z as l,we as m,$t as n,zt as o,Ht as p,_t as q,Yt as r,qt as s,Qt as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as c,o as b}from"./chunk-2HSR5XDQ.js";import{B as y,E as g,L as x,O as z,j as s,m as p,p as d,s as h,v as u,y as m}from"./chunk-DYD7MDWO.js";import{g as f}from"./chunk-IHGRFR4H.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{a as Pi,b as g,c as Ee,d as Ei,f as Bt,m as _t,o as ne}from"./chunk-KL7NGD76.js";import{a as Te,b as Ni}from"./chunk-WBQ5TNRZ.js";import{a as Xi}from"./chunk-BH53MBAZ.js";import{l as wi}from"./chunk-UG22Z42P.js";import{a as Ji,b as er,d as tr}from"./chunk-Y5IU6IA5.js";import{b as Si,c as Yi,f as $i}from"./chunk-47HAZZWF.js";import{a as Mi,c as Tt,d as zt,e as Di,f as q,g as ki}from"./chunk-273CUPEO.js";import{A as Pe,b as Dt,d as h,e as gi,i as z,k as W,o as kt,q as yi,s as vi,t as bi,u as B,y as Ci,z as Rt}from"./chunk-UM5VNQPY.js";import{c as K,j as ke}from"./chunk-2HSR5XDQ.js";import{a as ze,b as ji,c as Be,d as Wi,e as qi,f as Ki,g as Qi,m as X}from"./chunk-D2PATZCC.js";import{b as Re,d as Ui}from"./chunk-M2FZ224T.js";import{g as Zi}from"./chunk-IHGRFR4H.js";import{B as Gi,C as At,D as Hi,E as Ot,a as se,k as Bi,l as _i,m as Li,n as Ai,o as Y,p as Oi,q as oe,t as Vi,u as Ii,v as De,w as L,x as Fi}from"./chunk-AJSIVGDX.js";import{a as Lt,b as Ti,g as Q,j as Me,k as zi}from"./chunk-Q22Z4PBD.js";import{a as xi,b as _}from"./chunk-AIQ6IVT5.js";import{g as $}from"./chunk-UUOPT2N4.js";import{c as xe,d as Mt,j as x}from"./chunk-4QLJUQSJ.js";import{c as D,i as Ri,j as f}from"./chunk-7WRQ2UAN.js";import{Vector2 as or,RenderTarget as Nn,HalfFloatType as Un}from"three";import{WebGPURenderer as jn,RenderPipeline as Wn}from"three/webgpu";import{pass as qn,renderOutput as ar,screenCoordinate as Kn,vec2 as Vt,vec4 as ur,fract as lr,sin as cr,dot as dr,texture as Qn,uniform as Yn}from"three/tsl";import{setConsoleFunction as Hn,getConsoleFunction as Zn}from"three";var ir="THREE.Abstract function.",rr=!1,nr=!1;function sr(){if(rr)return;rr=!0;let s=Zn();Hn((e,t,...i)=>{if(e==="warn"&&t===ir){nr||(nr=!0,console.warn(`${ir} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(s){s(e,t,...i);return}let r=i[0],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 hr={x:0,y:0,width:1,height:1},$n=1/20;async function ka(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var _e=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 or(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(sr(),this.renderer=new jn({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 Wn(this.renderer),r=qn(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 o=ar(n),a=this._transition;if(a)try{o=ur(a.resolved.shader({fromNode:a.fromNode,toNode:o,progress:a.progressUniform})),a.composed=!0}catch(l){console.error("RendererManager: stage transition shader failed, skipping.",l)}i.outputNode=o.add(ts()),this.postProcessing=i}rebindPostProcessingCamera(e){!this.postProcessing||!this._postSceneRef||this.setupPostProcessing(this._postSceneRef,e)}get transitionActive(){return this._transition!==null}beginSnapshotTransition(e,t,i){this.finishTransition();let r=new or;this.renderer.getDrawingBufferSize(r);let n=new Nn(Math.max(1,r.x),Math.max(1,r.y),{type:Un}),o=this.renderer.getRenderTarget();try{this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(n),this.renderer.render(t,i)}catch(a){console.error("RendererManager: failed to capture transition snapshot.",a)}finally{this.renderer.setRenderTarget(o)}this._transition={resolved:e,progressUniform:Yn(0),fromNode:ar(Qn(n.texture)),elapsed:0,snapshotTarget:n,composed:!1}}beginInStageTransition(e,t,i){this._initialized&&(this.beginSnapshotTransition(e,t,i),this.setupPostProcessing(t,i))}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+=Math.min(e,$n);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,o=this.screenResolution.y,a=Math.floor(r.x*n),l=Math.floor(r.y*o),c=Math.floor(r.width*n),d=Math.floor(r.height*o);this.renderer.setViewport(a,l,c,d),this.renderer.setScissor(a,l,c,d),this.renderer.setScissorTest(!0),i&&this.postProcessing?this.postProcessing.render():this.renderer.render(e,t.camera)}renderCameraToTarget(e,t){let i=t.renderTarget;if(!i)return;let r=Xn(e,i.texture),n=this.renderer.getRenderTarget();this.renderer.setRenderTarget(i),this.renderer.setScissorTest(!1),this.renderer.clear(),this.renderer.render(e,t.camera),this.renderer.setRenderTarget(n);for(let o of r)o.visible=!0}renderCameras(e,t){if(!e||t.length===0)return;this.renderer.setScissorTest(!1),this.renderer.clear();let i=t.length===1&&es(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 Xn(s,e){let t=[];return s.traverse(i=>{let r=i;!r.isMesh||!r.visible||!(Array.isArray(r.material)?r.material:[r.material]).some(o=>Jn(o,e))||(r.visible=!1,t.push(r))}),t}function Jn(s,e){return s?s.map===e:!1}function es(s){return s.x===0&&s.y===0&&s.width===1&&s.height===1}function ts(){let s=Kn.xy,e=lr(cr(dr(s,Vt(12.9898,78.233))).mul(43758.5453)),t=lr(cr(dr(s.add(Vt(13,7)),Vt(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return ur(i,i,i,0)}function ae(s){return s?.category??"none"}function le(s){let e=ae(s);return e==="environment"||e==="pack"}function F(s){return s.isInstanced===!0||s.isBundled===!0}import{BundleGroup as is}from"three/webgpu";var Le=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 o=this.getOrCreateBundle(r);return n.matrixAutoUpdate=!0,n.userData.zylemEntityUuid=e.uuid,n.parent&&n.parent.remove(n),o.add(n),o.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 is,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as pr,Matrix4 as ce,Vector3 as mr,Quaternion as rs}from"three";var de=class s{packs=new Map;entityToPack=new Map;scene=null;static DEFAULT_CAPACITY=128;static GROWTH_FACTOR=2;setScene(e){this.scene=e}static generatePackKey(e){let t={geo:`${e.geometryType}:${Lt(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Ti(Lt(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 s.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 o;return n.freeIndices.length>0?o=n.freeIndices.pop():(o=n.entities.length,o>=n.capacity&&this.growPack(n),n.entities.push(null)),n.entities[o]=e,n.entityMap.set(e.uuid,o),this.entityToPack.set(e.uuid,r),n.instancedMesh.count=Math.max(n.instancedMesh.count,o+1),n.activeIndices.push(o),n.dirtyIndices.add(o),o}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 a=i.activeIndices.pop();n<i.activeIndices.length&&(i.activeIndices[n]=a)}i.dirtyIndices.delete(r);let o=new ce;o.makeScale(0,0,0),i.instancedMesh.setMatrixAt(r,o),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 ce,i=new mr,r=new rs,n=new mr(1,1,1);for(let o of this.packs.values()){if(o.activeIndices.length===0)continue;let a=!1;for(let l of o.activeIndices){let c=o.entities[l];if(!c)continue;if(Bi(c)){t.makeScale(0,0,0),o.instancedMesh.setMatrixAt(l,t),a=!0;continue}let d=o.dirtyIndices.has(l),u=!!c.body;if(!(!d&&!u)){if(!d&&u){let p=c.body;if(typeof p.isRenderSleeping=="function"&&p.isRenderSleeping())continue}this.updateInstanceMatrix(o,l,t,i,r,n,e),a=!0}}o.dirtyIndices.clear(),a&&(o.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,n,o,a){let l=e.entities[t];if(l){if(l.body){let c=l.body;if(typeof c.writeRenderPose=="function")c.writeRenderPose(a,r,n);else{let d=Te(l.body,a);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,o)}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=s.DEFAULT_CAPACITY,n=new pr(t,i,r);n.count=0,n.frustumCulled=!1;let o=new ce().makeScale(0,0,0);for(let l=0;l<r;l++)n.setMatrixAt(l,o);n.instanceMatrix.needsUpdate=!0;let a={key:e,instancedMesh:n,geometry:t,material:i,entityMap:new Map,entities:[],freeIndices:[],activeIndices:[],dirtyIndices:new Set,capacity:r};return this.packs.set(e,a),this.scene&&this.scene.add(n),a}growPack(e){let t=e.capacity*s.GROWTH_FACTOR,i=new pr(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new ce;for(let o=0;o<e.capacity;o++)e.instancedMesh.getMatrixAt(o,r),i.setMatrixAt(o,r);let n=new ce().makeScale(0,0,0);for(let o=e.capacity;o<t;o++)i.setMatrixAt(o,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 Ae=class{bundles=new Le;instances=new de;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=ae(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=de.generateEntityPackKey(e);if(t==="pack"){let o=this.instances.register(e,i,r,n);return o<0?!1:(e.packKey=n,e.instanceId=o,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()}};import{BoxGeometry as Nt,BufferGeometry as Mr,DoubleSide as Dr,EdgesGeometry as ms,Float32BufferAttribute as kr,Group as Fe,Line as fs,LineBasicMaterial as Rr,LineSegments as gs,Mesh as J,MeshBasicMaterial as Cr,MeshStandardMaterial as Ge,OctahedronGeometry as ys,Raycaster as vs,SphereGeometry as Sr}from"three";function ue(s,e){return s.x*e.x+s.y*e.y+s.z*e.z}function G(s,e){return{x:s.y*e.z-s.z*e.y,y:s.z*e.x-s.x*e.z,z:s.x*e.y-s.y*e.x}}function ns(s,e){return{x:s.x-e.x,y:s.y-e.y,z:s.z-e.z}}function ss(s,e){return{x:s.x*e,y:s.y*e,z:s.z*e}}function fr(s){return Math.hypot(s.x,s.y,s.z)}function os(s){let e=fr(s);return e<1e-5?null:ss(s,1/e)}function as(s,e){return Math.abs(s.x-e.x)<=1e-5&&Math.abs(s.y-e.y)<=1e-5&&Math.abs(s.z-e.z)<=1e-5}function ls(s,e,t){let i=s.normal,r=e.normal,n=t.normal,o=ue(i,G(r,n));if(Math.abs(o)<1e-8)return null;let a=G(r,n),l=G(n,i),c=G(i,r);return{x:(s.distance*a.x+e.distance*l.x+t.distance*c.x)/o,y:(s.distance*a.y+e.distance*l.y+t.distance*c.y)/o,z:(s.distance*a.z+e.distance*l.z+t.distance*c.z)/o}}function cs(s,e){for(let t of e)if(ue(t.normal,s)-t.distance>1e-5)return!1;return!0}function ds(s,e,t){let i=s[e[0]],r=G(t,{x:1,y:0,z:0});fr(r)<1e-8&&(r=G(t,{x:0,y:1,z:0}));let n=os(r);if(!n)return[...e];let o=G(t,n),a=e.map(l=>{let c=ns(s[l],i);return{index:l,angle:Math.atan2(ue(c,o),ue(c,n))}});return a.sort((l,c)=>l.angle-c.angle),a.map(l=>l.index)}function H(s){if(s.length<4)return null;let e=[];for(let i=0;i<s.length;i+=1)for(let r=i+1;r<s.length;r+=1)for(let n=r+1;n<s.length;n+=1){let o=ls(s[i],s[r],s[n]);!o||!cs(o,s)||e.some(a=>as(a,o))||e.push(o)}if(e.length<4)return null;let t=[];for(let i=0;i<s.length;i+=1){let r=s[i],n=[];for(let a=0;a<e.length;a+=1)Math.abs(ue(r.normal,e[a])-r.distance)<=1e-5&&n.push(a);if(n.length<3)continue;let o=ds(e,n,r.normal);o.length<3||t.push({planeIndex:i,indices:o})}return t.length<4?null:{vertices:e,faces:t}}import{Vector3 as It}from"three";var us=0;function hs(s,e){if(e)return{position:s.origin.clone().add(s.direction.clone().multiplyScalar(e.distance)),normal:new It(e.normal[0],e.normal[1],e.normal[2])};if(Math.abs(s.direction.y)<1e-6)return null;let t=(us-s.origin.y)/s.direction.y;return t<0?null:{position:s.origin.clone().add(s.direction.clone().multiplyScalar(t)),normal:new It(0,1,0)}}function ps(s,e){if(e.lengthSq()<1e-8)return 0;let t=e.clone().normalize();return(Math.abs(t.x)*s.x+Math.abs(t.y)*s.y+Math.abs(t.z)*s.z)/2}function Ft(s,e,t){let i=ps(e,t);return i<=0?s.clone():s.clone().add(t.clone().normalize().multiplyScalar(i))}function Z(s,e,t,i){let r=hs(s,e);if(!r)return null;let{normal:n}=r,o=t.enabled?q(r.position,t.translate):r.position,a=new It(o.x,o.y,o.z);return{position:i?Ft(a,i,n):a,normal:n}}function gr(s){let e=[];for(let t of s){let i=H(t.planes);if(!i)continue;let r=new Float32Array(i.vertices.length*3);i.vertices.forEach((n,o)=>{r[o*3]=n.x,r[o*3+1]=n.y,r[o*3+2]=n.z}),e.push(r)}return e}function yr(s){return s===g.top?"top":s===g.side?"side":null}function vr(s){let e=Math.abs(s.x),t=Math.abs(s.y),i=Math.abs(s.z);return t>=e&&t>=i?"top":e>=i?"side":"front"}function he(s){return s==="top"?"y":s==="side"?"x":"z"}function Gt(s,e,t){let i=s.origin[e],r=s.direction[e];if(Math.abs(r)<1e-8)return null;let n=(t-i)/r;return n<0?null:{x:s.origin.x+s.direction.x*n,y:s.origin.y+s.direction.y*n,z:s.origin.z+s.direction.z*n}}function A(s,e){return Math.round(s/e)*e}function Oe(s,e,t,i){let r=Math.max(i,1e-4),n=(u,p)=>{let m=A(Math.min(u,p),r),v=A(Math.max(u,p),r);return v-m<r*.5&&(v=m+r),[m,v]};if(s==="top"){let[u,p]=n(e.x,t.x),[m,v]=n(e.z,t.z),S=A(e.y,r);return{min:{x:u,y:S,z:m},max:{x:p,y:S+r,z:v}}}if(s==="front"){let[u,p]=n(e.x,t.x),[m,v]=n(e.y,t.y),S=A(e.z,r);return{min:{x:u,y:m,z:S},max:{x:p,y:v,z:S+r}}}let[o,a]=n(e.y,t.y),[l,c]=n(e.z,t.z),d=A(e.x,r);return{min:{x:d,y:o,z:l},max:{x:d+r,y:a,z:c}}}function br(s,e,t){if(s==="top"){let a=t.x-e.x,l=t.z-e.z,c=Math.hypot(a,l);if(c<1e-6)return null;let d={x:-l/c,y:0,z:a/c};return{normal:d,distance:d.x*e.x+d.z*e.z}}if(s==="front"){let a=t.x-e.x,l=t.y-e.y,c=Math.hypot(a,l);if(c<1e-6)return null;let d={x:-l/c,y:a/c,z:0};return{normal:d,distance:d.x*e.x+d.y*e.y}}let i=t.y-e.y,r=t.z-e.z,n=Math.hypot(i,r);if(n<1e-6)return null;let o={x:0,y:-r/n,z:i/n};return{normal:o,distance:o.y*e.y+o.z*e.z}}function Ve(s,e){return e<=0?{x:s.x,y:s.y,z:s.z}:{x:A(s.x,e),y:A(s.y,e),z:A(s.z,e)}}var Tr=13157044,bs=14998992,wr=250,Cs=[{color:16724787,axis:"x"},{color:3394662,axis:"y"},{color:3377407,axis:"z"}],zr=null;function al(){return zr}function Ht(s){zr=s}function xr(s){return{origin:{x:s.origin.x,y:s.origin.y,z:s.origin.z},direction:{x:s.direction.x,y:s.direction.y,z:s.direction.z}}}function Ut(s,e){let t=s.size;return{x:t?.x??e.x,y:t?.y??e.y,z:t?.z??e.z}}function Ss(s,e){return s.solids.some(t=>t.id===e)?"solid":s.doodads.some(t=>t.id===e)?"doodad":s.entities.some(t=>t.id===e)?"entity":null}function ws(s){Array.isArray(s)?s.forEach(e=>e.dispose()):s.dispose()}function Zt(s){s.traverse(e=>{let t=e;t.geometry?.dispose(),t.material&&ws(t.material)})}function xs(s){let e=s.clone(!0);return e.traverse(t=>{let i=t;if(i.geometry&&(i.geometry=i.geometry.clone()),!i.material)return;let n=(Array.isArray(i.material)?i.material:[i.material]).map(o=>o.clone());i.material=Array.isArray(i.material)?n:n[0]}),e}function Ps(s,e){let t=K(s);if(t)try{let r=t.create({position:{x:0,y:0,z:0},props:e});if(r&&typeof r.then!="function"){let n=r.group??r.mesh;if(n)return xs(n)}}catch{}let i=Ut(e,{x:1,y:1,z:1});return new J(new Nt(i.x,i.y,i.z),new Ge({color:13157044}))}function Pr(s,e){let t=e.position??{x:0,y:0,z:0};s.position.set(t.x,t.y,t.z),e.quaternion?s.quaternion.set(e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w):e.rotation&&s.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e.scale&&s.scale.set(e.scale.x,e.scale.y,e.scale.z)}function Es(s){return new Ge({color:s?bs:Tr,side:Dr})}function Ie(s){let e=new Fe;for(let t of Cs){let i={x:s.x,y:s.y,z:s.z},r={x:s.x,y:s.y,z:s.z};i[t.axis]-=wr,r[t.axis]+=wr;let n=new Mr;n.setAttribute("position",new kr([i.x,i.y,i.z,r.x,r.y,r.z],3));let o=new fs(n,new Rr({color:t.color,depthTest:!1}));o.frustumCulled=!1,o.renderOrder=20,e.add(o)}return e}function Er(s){let e=s.vertices.reduce((i,r)=>({x:i.x+r.x,y:i.y+r.y,z:i.z+r.z}),{x:0,y:0,z:0}),t=s.vertices.length;return{x:e.x/t,y:e.y/t,z:e.z/t}}function Ms(s){let e=[],t=[];for(let r of s.faces){let n=e.length/3;for(let o of r.indices){let a=s.vertices[o];e.push(a.x,a.y,a.z)}for(let o=1;o<r.indices.length-1;o+=1)t.push(n,n+o,n+o+1)}let i=new Mr;return i.setAttribute("position",new kr(e,3)),i.setIndex(t),i.computeVertexNormals(),i}var He=class{constructor(e){this.host=e;this.root.name="level-preview"}root=new Fe;raycaster=new vs;mounted=!1;generation=0;mode="edit";payload=null;drag=null;clipAnchor=null;ghost=null;hoverGuides=null;bodyHandle=null;zoneIds=[];get isActive(){return this.payload!==null}get isEditing(){return this.payload!==null&&this.mode==="edit"}tick(){!this.payload||this.mounted||!this.host.getScene()||this.rebuild()}sync(e){this.mode="edit",this.payload=e,Ht(e.document),this.rebuild()}play(e){this.mode="play",this.payload={document:e,hiddenLayers:[],selectedIds:this.payload?.selectedIds??[],activeLayer:this.payload?.activeLayer??"solid",placement:null},Ht(e),this.rebuild()}close(){this.generation+=1,this.payload=null,this.drag=null,this.clipAnchor=null,Ht(null),this.teardownOwned(),this.unmount()}dispose(){this.close()}pointerDown(e){if(!this.payload)return!1;let t=z();if(t==="select")return this.host.publishSelect(this.pickId(e)),!0;if(t==="delete"){let i=this.pickId(e);return i&&this.host.publishGesture({kind:"delete",id:i}),!0}return t==="add"?(this.placeArmed(e),!0):t==="brush"||t==="clip"||t==="vertex"?(this.beginSolidGesture(t,e),!0):t==="translate"?this.beginTranslate(e):!1}pointerMove(e){if(!this.drag||this.drag.kind!=="brush")return;let t=this.viewPoint(this.drag.view,e);t&&this.showBrushGhost(Oe(this.drag.view,this.drag.start,t,this.gridStep()))}pointerHover(e){if(!this.payload||this.drag)return;let t=z();if(t!=="brush"&&t!=="clip"&&t!=="vertex"){this.clearHoverGuides();return}if(t==="clip"&&this.clipAnchor){this.clearHoverGuides();return}if(t==="vertex"&&this.selectedSolidCenter()){this.clearHoverGuides();return}let i=this.viewPoint(this.currentDrawView(),e);if(!i){this.clearHoverGuides();return}this.showHoverGuides(i)}pointerUp(e){let t=this.drag;if(this.drag=null,this.clearGhost(),!t)return;if(t.kind==="brush"){let o=this.viewPoint(t.view,e)??t.start,a=Oe(t.view,t.start,o,this.gridStep());this.host.publishGesture({kind:"brush",min:a.min,max:a.max});return}if(t.kind==="vertex"){let o=this.viewPoint(t.view,e,t.plane);if(!o)return;this.host.publishGesture({kind:"vertex",brushId:t.brushId,vertexIndex:t.vertexIndex,position:Ve(o,this.gridStep())});return}let i=this.translatePoint(t,e);if(!i)return;let r=Ve(i,this.gridStep()),n={x:r.x-t.start.x,y:r.y-t.start.y,z:r.z-t.start.z};t.view==="top"&&(n.y=0),t.view==="side"&&(n.x=0),t.view==="front"&&(n.z=0),!(n.x===0&&n.y===0&&n.z===0)&&this.host.publishGesture({kind:"translate",id:t.id,layer:t.layer,delta:n})}rebuild(){let e=++this.generation;this.teardownOwned();let t=this.payload;if(!t||!this.ensureRoot()||(this.buildVisuals(),this.mode!=="play"))return;let i=gr(t.document.solids);this.bodyHandle=i.length>0?this.host.spawnHulls(i):null,this.spawnZones(t.document,e).catch(r=>{console.error("Level triggers failed to spawn",r)})}buildVisuals(){let e=this.payload;if(!e)return;let t=new Set(this.mode==="play"?[]:e.hiddenLayers),i=new Set(e.selectedIds);if(this.mode==="edit"&&!t.has("solid"))for(let n of e.document.solids){let o=H(n.planes);if(!o)continue;let a=i.has(n.id),l=new J(Ms(o),Es(a));l.userData.levelId=n.id,this.root.add(l),a&&this.root.add(Ie(Er(o))),i.has(n.id)&&z()==="vertex"&&this.addVertexHandles(n.id,o)}if(!t.has("doodad"))for(let n of e.document.doodads){let o=Ps(n.typeId,n.props);Pr(o,n.pose),o.userData.levelId=n.id,this.root.add(o)}if(!t.has("entity"))for(let n of e.document.entities){let o=n.typeId==="zone"?this.triggerOutline(n.props):new J(new ys(.3),new Ge({color:14904020}));Pr(o,n.pose),o.userData.levelId=n.id,this.root.add(o)}}addVertexHandles(e,t){let i=Math.max(this.gridStep()*.28,.08);t.vertices.forEach((r,n)=>{let o=new J(new Sr(i,8,6),new Cr({color:16772744,depthTest:!1}));o.position.set(r.x,r.y,r.z),o.userData.levelId=e,o.userData.vertexIndex=n,o.renderOrder=10,this.root.add(o)})}triggerOutline(e){let t=Ut(e,{x:2,y:2,z:2});return new gs(new ms(new Nt(t.x,t.y,t.z)),new Rr({color:4054167}))}async spawnZones(e,t){for(let i of e.entities){if(i.typeId!=="zone")continue;if(t!==this.generation)return;let r=await this.host.spawnZone({name:i.name,position:i.pose.position??{x:0,y:0,z:0},size:Ut(i.props,{x:2,y:2,z:2})});if(t!==this.generation){r&&this.host.detach(r);return}r&&this.zoneIds.push(r)}}beginSolidGesture(e,t){let i=this.currentDrawView(),r=this.viewPoint(i,t);if(!r)return;if(e==="brush"){this.clearHoverGuides(),this.drag={kind:"brush",view:i,start:r},this.showBrushGhost(Oe(i,r,r,this.gridStep()));return}if(e==="clip"){if(!this.clipAnchor){this.clipAnchor=r,this.showClipMarker(r);return}let o=br(i,this.clipAnchor,r);this.clipAnchor=null,this.clearGhost();let a=this.selectedSolidId();o&&a&&this.host.publishGesture({kind:"clip",brushId:a,plane:o});return}let n=this.pick(t);if(n&&typeof n.vertexIndex=="number"){let o=this.vertexAt(n.id,n.vertexIndex);this.drag={kind:"vertex",brushId:n.id,vertexIndex:n.vertexIndex,view:i,plane:o?.[he(i)]??0};return}this.host.publishSelect(n?.id??null)}vertexAt(e,t){let i=this.payload?.document.solids.find(r=>r.id===e);return i?H(i.planes)?.vertices[t]??null:null}beginTranslate(e){let t=this.payload,i=t?.selectedIds[0];if(!t||!i)return!1;let r=Ss(t.document,i);if(!r)return!1;let n=this.currentDrawView(),o=this.translatePoint({kind:"translate",id:i,layer:r,view:n,start:{x:0,y:0,z:0}},e);return o&&(this.drag={kind:"translate",id:i,layer:r,view:n,start:Ve(o,this.gridStep())}),!0}placeArmed(e){let t=this.payload?.placement;if(!t)return;let i=Z(e,this.host.physicsHit(e),{enabled:!0,translate:this.gridStep()});if(!i)return;let r={position:{x:i.position.x,y:i.position.y,z:i.position.z}};if(t.kind==="doodad"){this.host.publishGesture({kind:"doodad",typeId:t.typeId,pose:r,...t.props?{props:t.props}:{}});return}if(t.kind==="spawn"){this.host.publishGesture({kind:"spawn",pose:r});return}this.host.publishGesture({kind:"trigger",pose:r,size:t.size})}currentDrawView(){return yr(this.host.cameraId())??vr(this.host.viewDirection())}viewPoint(e,t,i=0){return Gt(xr(t),he(e),i)}translatePoint(e,t){let i=this.anchorOf(e.id);return Gt(xr(t),he(e.view),i[he(e.view)])}anchorOf(e){let t=this.payload?.document,i=t?.solids.find(o=>o.id===e);if(i){let o=H(i.planes);if(o&&o.vertices.length>0){let a=o.vertices.reduce((c,d)=>({x:c.x+d.x,y:c.y+d.y,z:c.z+d.z}),{x:0,y:0,z:0}),l=o.vertices.length;return{x:a.x/l,y:a.y/l,z:a.z/l}}}let r=t?.doodads.find(o=>o.id===e);return r?.pose.position?r.pose.position:t?.entities.find(o=>o.id===e)?.pose.position??{x:0,y:0,z:0}}selectedSolidId(){let e=this.payload;return e?e.selectedIds.find(t=>e.document.solids.some(i=>i.id===t))??null:null}pickId(e){return this.pick(e)?.id??null}pick(e){if(!this.mounted)return null;this.raycaster.set(e.origin,e.direction);let t=this.raycaster.intersectObjects(this.root.children,!0);for(let i of t){let r=i.object;for(;r;){let n=r.userData.vertexIndex,o=r.userData.levelId;if(typeof o=="string")return typeof n=="number"?{id:o,vertexIndex:n}:{id:o};r=r.parent}}return null}showBrushGhost(e){this.clearGhost();let t={x:e.max.x-e.min.x,y:e.max.y-e.min.y,z:e.max.z-e.min.z},i={x:(e.min.x+e.max.x)/2,y:(e.min.y+e.max.y)/2,z:(e.min.z+e.max.z)/2},r=new J(new Nt(t.x,t.y,t.z),new Ge({color:Tr,transparent:!0,opacity:.35,depthWrite:!1,side:Dr}));r.position.set(i.x,i.y,i.z);let n=new Fe;n.add(r),n.add(Ie(i)),this.ghost=n,this.root.add(n)}showClipMarker(e){this.clearGhost();let t=new J(new Sr(Math.max(this.gridStep()*.2,.06),8,6),new Cr({color:16772744,depthTest:!1}));t.position.set(e.x,e.y,e.z);let i=new Fe;i.add(t),i.add(Ie(e)),this.ghost=i,this.root.add(i)}showHoverGuides(e){if(this.clearHoverGuides(),!this.ensureRoot())return;let t=Ie(e);this.hoverGuides=t,this.root.add(t)}clearHoverGuides(){this.hoverGuides&&(this.root.remove(this.hoverGuides),Zt(this.hoverGuides),this.hoverGuides=null)}selectedSolidCenter(){let e=this.selectedSolidId();if(!e)return null;let t=this.payload?.document.solids.find(r=>r.id===e);if(!t)return null;let i=H(t.planes);return i?Er(i):null}clearGhost(){this.ghost&&(this.root.remove(this.ghost),Zt(this.ghost),this.ghost=null)}gridStep(){let e=B().translate;return e>0?e:1}ensureRoot(){let e=this.host.getScene();return e?(this.mounted||(e.add(this.root),this.mounted=!0),!0):!1}teardownOwned(){for(let e of this.zoneIds)this.host.detach(e);this.zoneIds=[],this.bodyHandle!==null&&(this.host.despawnHulls(this.bodyHandle),this.bodyHandle=null),this.clearGhost(),this.clearHoverGuides();for(let e of[...this.root.children])this.root.remove(e),Zt(e)}unmount(){this.mounted&&(this.host.getScene()?.remove(this.root),this.mounted=!1)}};var Ze=!1,k={},Br=0,_r=0,pe=null;function Lr(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function jt(){return Ze?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(Ze=!0),Ze)}function cl(s){Ze=s,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=s)}function Wt(s){jt()&&(pe=s,_r=Lr())}function qt(){if(!jt()||pe===null)return;let s=Lr()-_r;k[pe]=(k[pe]??0)+s,pe=null}function Ar(){if(!jt()||(Br++,Br%60!==0))return;let s=Object.values(k).reduce((t,i)=>t+(i??0),0),e=Object.keys(k).sort((t,i)=>(k[i]??0)-(k[t]??0)).map(t=>{let i=k[t]??0,r=s>0?(i/s*100).toFixed(1):"0.0";return`${t}=${i.toFixed(2)}ms (${r}%)`});console.info(`[ZylemStage profile] avg over 60 frames (${s.toFixed(2)}ms/frame): ${e.join(", ")}`);for(let t of Object.keys(k))k[t]=0}function R(s,e){Wt(s);try{return e()}finally{qt()}}var y={FirstPerson:"first-person",ThirdPerson:"third-person",SecondPerson:"second-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};function Kt(s){switch(s){case y.Isometric:case y.TopDown:case y.Flat2D:case y.Fixed2D:return"orthographic";default:return"perspective"}}import{Vector3 as Ds,Quaternion as ks,MathUtils as Qt}from"three";function Ne(){return{position:new Ds(0,0,10),rotation:new ks,fov:75,zoom:1,near:.1,far:1e3}}function N(s){return{position:s.position.clone(),rotation:s.rotation.clone(),fov:s.fov,zoom:s.zoom,near:s.near,far:s.far,lookAt:s.lookAt?.clone()}}function Or(s,e){let t=N(s);return e.position&&t.position.add(e.position),e.rotation&&t.rotation.multiply(e.rotation),e.fov!=null&&t.fov!=null&&(t.fov+=e.fov),e.zoom!=null&&t.zoom!=null&&(t.zoom+=e.zoom),t}function Vr(s,e,t,i){let r=1-Math.pow(1-Qt.clamp(t,0,1),i*60),n=N(s);return n.position.lerp(e.position,r),n.rotation.slerp(e.rotation,r),e.fov!=null&&n.fov!=null&&(n.fov=Qt.lerp(n.fov,e.fov,r)),e.zoom!=null&&n.zoom!=null&&(n.zoom=Qt.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 Ue=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=Ne();_finalPose=Ne();_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):Ne(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=N(t);for(let r=this.actions.length-1;r>=0;r--){let n=this.actions[r],o=n.update(e);t=Or(t,o),n.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=Vr(this._finalPose,t,this.damping,e.dt):(this._finalPose=N(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?N(this._desiredPose):null,finalPose:this._finalPose?N(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 O,Quaternion as je}from"three";var Rs={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},ee=class{id="third-person";projection="perspective";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Rs,...r},this.initialPosition=t?f(t,D):void 0,this.initialLookAt=i?f(i,D):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 je,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new O(0,0,0)}:{position:new O(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new je,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new O(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new O(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new je,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([u,p])=>this.getTrailedPosition(u,p.position,e.time)),r=new O;for(let u of i)r.add(u);r.divideScalar(i.length);let n=0;for(let u of i){let p=r.distanceTo(u);p>n&&(n=p)}let o=Math.max(n*this.opts.paddingFactor,this.opts.minDistance),a=new O(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=a.length(),c=l>0?a.clone().normalize():new O(0,.5,1).normalize(),d=r.clone().add(c.multiplyScalar(o));if(l>0){let u=this.opts.height/l;d.y=r.y+o*u}return{position:d,rotation:new je,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 o=i-r-.05;for(;n.length>1&&n[0].time<o;)n.shift();n.length>this.opts.trailBufferSize&&n.splice(0,n.length-this.opts.trailBufferSize);let a=i-r;if(n[0].time>=a)return n[0].pos.clone();for(let l=1;l<n.length;l++){let c=n[l-1],d=n[l];if(c.time<=a&&a<=d.time){let u=d.time-c.time,p=u>1e-6?(a-c.time)/u:0;return new O().lerpVectors(c.pos,d.pos,p)}}return n[n.length-1].pos.clone()}};import{Vector3 as Ir,Quaternion as Ts}from"three";var Fr={position:{x:0,y:0,z:10},zoom:10},te=class{id="fixed-2d";projection="orthographic";defaults={damping:1};opts;constructor(e){this.opts={...Fr,...e,position:f(e?.position,Fr.position)}}getBasePose(e){return{position:new Ir(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new Ts,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new Ir(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as Yt,Quaternion as $t,Euler as Zr,MathUtils as P}from"three";var zs={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},me=class{id="first-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new $t;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...zs,...r},this.initialPosition=t?f(t,D):void 0,this.initialLookAt=i?f(i,D):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=P.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=P.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 Yt(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new Yt(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=P.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=P.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new $t().setFromEuler(new Zr(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=Gr.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let n=Math.atan2(-r.x,-r.z),o=Math.asin(P.clamp(r.y,-1,1)),a=Bs.setFromEuler(Hr.set(o,n,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(a,P.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 P.lerp(this._currentFov,this._targetFov,P.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=Gr.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(P.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=Hr.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=P.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},Gr=new Yt,Bs=new $t,Hr=new Zr;import{Quaternion as _s,Vector3 as Xt}from"three";var Ls={distance:10,zoom:10,targetKey:"primary"},Nr=new Xt(1,1,1).normalize(),fe=class{id="isometric";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Ls,...r},this.initialPosition=t?f(t):void 0,this.initialLookAt=i?f(i):void 0}getBasePose(e){let t=e.targets[this.opts.targetKey];if(!t)return this.staticPose();let i=t.position.clone(),r=i.clone().addScaledVector(Nr,this.opts.distance);return this.pose(r,i)}staticPose(){return this.initialPosition?this.pose(this.initialPosition.clone(),this.initialLookAt?.clone()??new Xt(0,0,0)):this.pose(Nr.clone().multiplyScalar(this.opts.distance),new Xt(0,0,0))}pose(e,t){return{position:e,rotation:new _s,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as As,Vector3 as We}from"three";var Os={height:10,zoom:10,targetKey:"primary"},ge=class{id="top-down";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Os,...r},this.initialPosition=t?f(t):void 0,this.initialLookAt=i?f(i):void 0}getBasePose(e){let t=e.targets[this.opts.targetKey];if(!t)return this.staticPose();let i=t.position.clone();return this.pose(new We(i.x,i.y+this.opts.height,i.z),i)}staticPose(){if(this.initialPosition){let e=this.initialLookAt?.clone()??new We(this.initialPosition.x,this.initialPosition.y-this.opts.height,this.initialPosition.z);return this.pose(this.initialPosition.clone(),e)}return this.pose(new We(0,this.opts.height,0),new We(0,0,0))}pose(e,t){return{position:e,rotation:new As,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as Ur,Vector3 as qe}from"three";var Vs={anchorKey:"anchor",subjectKey:"primary",eyeHeight:1.7,fov:75},Jt=new qe,ye=class{id="second-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Vs,...r},this.initialPosition=t?f(t):void 0,this.initialLookAt=i?f(i):void 0}getBasePose(e){let t=e.targets[this.opts.anchorKey];if(!t)return this.staticPose();let i=new qe(t.position.x,t.position.y+this.opts.eyeHeight,t.position.z),r=e.targets[this.opts.subjectKey],n=r?r.position.clone():i.clone().add(this.anchorForward(t.rotation));return{position:i,rotation:new Ur,fov:this.opts.fov,near:.1,far:1e3,lookAt:n}}staticPose(){let e=this.initialPosition?.clone()??new qe(0,this.opts.eyeHeight,0),t=this.initialLookAt?.clone()??e.clone().add(new qe(0,0,-1));return{position:e,rotation:new Ur,fov:this.opts.fov,near:.1,far:1e3,lookAt:t}}anchorForward(e){return Jt.set(0,0,-1),e&&Jt.applyQuaternion(e),Jt.clone()}};function U(s,e){switch(s){case"third-person":return new ee(e);case"first-person":return new me(e);case"second-person":return new ye(e);case"isometric":return new fe(e);case"top-down":return new ge(e);case"flat-2d":return new te(e);case"fixed-2d":return new te(e);default:return new ee(e)}}import{Vector2 as js,Vector3 as w,OrthographicCamera as ti,PerspectiveCamera as Ye}from"three";import{PerspectiveCamera as ei,Vector3 as Fs,OrthographicCamera as ve,RenderTarget as Gs,LinearFilter as jr}from"three";import{Vector3 as Ke}from"three";import{OrbitControls as Is}from"three/addons/controls/OrbitControls.js";var Qe=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new Ke;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;_rotationLocked=!1;_screenSpacePanning=!1;_seededLookAt=null;_fullPolarRange=!1;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}setDebugViewCamera(e){this._isDebugViewCamera=e}setDefaultOrbitTarget(e){this._defaultOrbitTarget=e,e&&!this.orbitTarget&&this.debugStateSnapshot.enabled&&this._followSelection&&(this.orbitTarget=e)}seedOrbitPose(e,t){this._seededLookAt=t.clone(),this.camera.position.copy(e),this.camera.lookAt(t),this.orbitControls&&(this.orbitControls.target.copy(t),this.orbitControls.update(),this._rotationLocked&&this.applyRotationLock()),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()}setRotationLocked(e){this._rotationLocked=e,e?this.applyRotationLock():this.releaseRotationLock()}setFullPolarRange(e){this._fullPolarRange=e,!(!this.orbitControls||this._rotationLocked)&&(this.orbitControls.maxPolarAngle=this.polarLimit())}setScreenSpacePanning(e){this._screenSpacePanning=e,this.orbitControls&&(this.orbitControls.screenSpacePanning=e)}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 Ke().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=Si(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),this._rotationLocked&&this.applyRotationLock()):!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),this._rotationLocked&&this.applyRotationLock()):!e.enabled&&t?(this.saveDebugCameraState(),this.orbitTarget=null,this._userOrbitEnabled||this.disableOrbitControls(),this.reattachCameraToRig(),this.restoreCameraState()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected)}enableOrbitControls(){if(this.orbitControls)return;let e=this.camera.position.clone(),t=this.camera.quaternion.clone();this.orbitControls=new Is(this.camera,this.domElement),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.05,this.orbitControls.screenSpacePanning=this._screenSpacePanning,this.orbitControls.minDistance=1,this.orbitControls.maxDistance=500,this.orbitControls.maxPolarAngle=this.polarLimit(),this.orbitControls.enabled=this._interactionEnabled,this.orbitControls.target.copy(this._seededLookAt??new Ke),this.camera.position.copy(e),this.camera.quaternion.copy(t),this._rotationLocked?this.applyRotationLock():this.orbitControls.update()}applyRotationLock(){let e=this.orbitControls;if(!e)return;e.update();let t=e.getPolarAngle(),i=e.getAzimuthalAngle();e.minPolarAngle=t,e.maxPolarAngle=t,e.minAzimuthAngle=i,e.maxAzimuthAngle=i,e.enableRotate=!1,e.update()}polarLimit(){return this._fullPolarRange?Math.PI-.001:Math.PI/2}releaseRotationLock(){let e=this.orbitControls;e&&(e.minPolarAngle=0,e.maxPolarAngle=this.polarLimit(),e.minAzimuthAngle=-1/0,e.maxAzimuthAngle=1/0,e.enableRotate=!0,e.update())}rebindCamera(e){this.camera=e,this.orbitControls&&(this.orbitControls.object=e,this._rotationLocked&&this.applyRotationLock())}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 Ke;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 T=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...hr};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 Fs(0,0,0));let n=U(e);this.pipeline=new Ue(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 Qe(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 _e(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()}armEditorOrbit(e,t=!1){this._skipDebugOrbit=!0,this.orbitController?.setScreenSpacePanning(t),this.orbitController?.setRotationLocked(e),this.enableOrbitalControls(),this.setOrbitInteractionEnabled(!0)}allowFullOrbit(){this.orbitController?.setFullPolarRange(!0)}disarmEditorOrbit(){this.setOrbitInteractionEnabled(!1)}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 ei&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof ve){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 Gs(e,t,{minFilter:jr,magFilter:jr}),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)}replaceOrbitPose(e,t){if(this.orbitController){this.orbitController.seedOrbitPose(e,t);return}this.camera.position.copy(e),this.camera.lookAt(t)}applyOrthographicFrame(e,t,i){let r=this.camera;if(!(r instanceof ve))return;this.frustumSize=e;let n=this.screenResolution.x/Math.max(this.screenResolution.y,1);r.zoom=1,r.left=e*n/-2,r.right=e*n/2,r.top=e/2,r.bottom=e/-2,r.near=t,r.far=i,r.updateProjectionMatrix()}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===y.Flat2D||this._perspective===y.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){let t=e.lookAt.x-e.position.x,i=e.lookAt.y-e.position.y,r=e.lookAt.z-e.position.z,n=Math.hypot(t,i,r);n>1e-8&&Math.abs(i)/n>.999?this.camera.up.set(0,0,-1):this.camera.up.set(0,1,0),this.camera.lookAt(e.lookAt)}else this.camera.quaternion.copy(e.rotation);if(this.camera instanceof ei&&(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 ve){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()}}applyPerspective(e,t){this._perspective=e,this.pipeline.setPerspective(t),this.ensureProjection(t.projection??Kt(e))}ensureProjection(e){if((this.camera instanceof ve?"orthographic":"perspective")===e)return;let i=this.screenResolution.x/Math.max(this.screenResolution.y,1),r=e==="orthographic"?this.createOrthographicCamera(i):this.createPerspectiveCamera(i);if(r.position.copy(this.camera.position),r.quaternion.copy(this.camera.quaternion),r.up.copy(this.camera.up),r.layers.mask=this.camera.layers.mask,r.name=this.camera.name,"near"in this.camera&&"near"in r){let o=this.camera,a=r;a.near=o.near,a.far=o.far,a.zoom=o.zoom,a.updateProjectionMatrix()}let n=this.camera.parent;n&&(n.add(r),n.remove(this.camera)),this.camera=r,this.orbitController?.rebindCamera(r),this._rendererManager?.rebindPostProcessingCamera(r)}createCameraForPerspective(e){return Kt(this._perspective)==="orthographic"?this.createOrthographicCamera(e):this.createPerspectiveCamera(e)}createPerspectiveCamera(e){return new ei(75,e,.1,1e3)}createOrthographicCamera(e){return new ve(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3)}};import{OrthographicCamera as Hs,PerspectiveCamera as Zs,Vector3 as Wr}from"three";var Ns=4;function qr(s,e){if(s instanceof Zs){let t=Math.max(s.zoom,1e-6),i=2*Math.tan(s.fov*Math.PI/360)*Math.max(e,.01)/t,r=s.aspect>0?s.aspect:1;return{width:i*r,height:i}}if(s instanceof Hs){let t=Math.max(s.zoom,1e-6);return{width:(s.right-s.left)/t,height:(s.top-s.bottom)/t}}return{width:1,height:1}}function Kr(s,e){let t=(s.top-s.bottom)/2/Math.max(s.zoom,1e-6);return 2*Math.atan(t/Math.max(e,.01))*(180/Math.PI)}function Us(s){return Math.max(s.max.x-s.min.x,s.max.y-s.min.y,s.max.z-s.min.z)}function Qr(s,e){let t=Ns*Math.max(e.width,e.height);return s.filter(i=>{if(i.isEmpty())return!1;let r=Us(i);return Number.isFinite(r)&&r<=t})}function Yr(s,e,t,i,r,n){let o=r.width/2,a=r.height/2,l=new Wr;for(let d of i){let u=[d.min.x,d.max.x],p=[d.min.y,d.max.y],m=[d.min.z,d.max.z];for(let v of u)for(let S of p)for(let we of m)l.set(v,S,we).sub(s),o=Math.max(o,Math.abs(l.dot(e))),a=Math.max(a,Math.abs(l.dot(t)))}let c=Math.max(n,1e-6);return Math.max(a*2,o*2/c)}function $r(s,e,t,i){if(t.length===0)return i;let r=1/0,n=-1/0,o=new Wr;for(let l of t){let c=[l.min.x,l.max.x],d=[l.min.y,l.max.y],u=[l.min.z,l.max.z];for(let p of c)for(let m of d)for(let v of u){o.set(p,m,v).sub(s);let S=o.dot(e);r=Math.min(r,S),n=Math.max(n,S)}}if(!Number.isFinite(r)||!Number.isFinite(n))return i;let a=Math.max((n-r)*.05,1);return{near:r-a,far:Math.max(n+a,r-a+1)}}var Xr=1e4,Jr=[{id:g.side,perspective:y.Fixed2D,lockRotation:!0,screenSpacePan:!0,position:(s,e)=>new w(s.x+e,s.y,s.z),up:()=>new w(0,1,0)},{id:g.top,perspective:y.TopDown,lockRotation:!0,screenSpacePan:!0,position:(s,e)=>new w(s.x,s.y+e,s.z),up:()=>new w(0,0,-1)},{id:g.isometric,perspective:y.Isometric,lockRotation:!0,screenSpacePan:!0,near:-Xr,far:Xr,position:(s,e)=>s.clone().add(new w(1,1,1).normalize().multiplyScalar(e)),up:()=>new w(0,1,0)},{id:g.free,perspective:y.ThirdPerson,lockRotation:!1,screenSpacePan:!1,fullPolarRange:!0,position:(s,e,t)=>t.distanceTo(s)>.5?t.clone():s.clone().add(new w(0,e*.5,e)),up:s=>s.clone()}];function ii(s){let e=new w;s.getWorldDirection(e);let i=new w().sub(s.position).dot(e),r=i>1?i:12;return{lookAt:s.position.clone().add(e.multiplyScalar(r)),distance:r}}var $e=class{cameras=new Map;_activeCameras=[];_editorCameras=new Map;_lockedEditorIds=new Set;_screenSpacePanIds=new Set;_framedEditorViews=new Set;_entityBounds=null;_rememberedGameCamera=null;_editorViewLocked=!1;_suspendedOrbits=new Set;_editorCamerasPromise=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;_unregisterEditorHost=null;get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}isEditorViewActive(){return this._editorViewLocked}activeEditorCameraId(){let e=this.primaryCamera;if(!e||!this._editorViewLocked)return null;for(let[t,i]of this._editorCameras)if(i===e)return t;return null}hasEditorCameras(){return this._editorCameras.size>0}setEditorEntityBounds(e){this._entityBounds=e}syncFreeCameraToGame(){let e=()=>{this.copyFreeFromGame()&&this.activateCameraById(g.free)};if(this.hasEditorCameras()){e();return}this.ensureEditorCameras().then(e)}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,o]of this.cameras.entries())if(o===e){t=n;break}if(!t)return!1;let i=this.cameras.get(t);if(!i)return!1;this.cameras.delete(t);let r=this._activeCameras.indexOf(i);return r!==-1&&this._activeCameras.splice(r,1),this._rememberedGameCamera===i&&(this._rememberedGameCamera=null),this._suspendedOrbits.delete(i),!0}setActiveCamera(e){let t=this.resolveCamera(e);return t?this._editorViewLocked&&!this.isEditorCamera(t)?(this._rememberedGameCamera=t,!0):(this.isEditorCamera(t)||(this._rememberedGameCamera=t,this.restoreOrbitFor(t)),this.commitActive(t)):(console.warn(`CameraManager: Camera not found: ${e}`),!1)}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;for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._unregisterEditorHost=Ei(this),Ee()&&await this.ensureEditorCameras()}ensureEditorCameras(){return this._editorCameras.size>0?Promise.resolve():this._editorCamerasPromise?this._editorCamerasPromise:(this._editorCamerasPromise=this.createEditorCameras().finally(()=>{this._editorCamerasPromise=null}),this._editorCamerasPromise)}destroyEditorCameras(){let e=this.primaryCamera!==null&&this.isEditorCamera(this.primaryCamera);if(this._editorViewLocked=!1,e){let t=this.gameCameraToRestore();t&&(this.restoreOrbitFor(t),this.commitActive(t))}for(let t of this._editorCameras.values())this.removeCamera(t),t.destroy();this._editorCameras.clear(),this._lockedEditorIds.clear(),this._screenSpacePanIds.clear(),this._framedEditorViews.clear()}activateCameraById(e){if(e===Pi){let r=this.gameCameraToRestore();return r?this.showGameCamera(r):!1}let t=this._editorCameras.get(e);if(t)return this.showEditorCamera(e,t);let i=this.getCamera(e);return!i||this.isEditorCamera(i)?!1:(this._rememberedGameCamera=i,this.showGameCamera(i))}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 js(window.innerWidth,window.innerHeight),t=new T(y.ThirdPerson,e);return this.addCamera(t,"default"),t}return this._activeCameras[0]}dispose(){this._unregisterEditorHost?.(),this._unregisterEditorHost=null,this._editorViewLocked=!1;for(let e of this.cameras.values())e.destroy();this.cameras.clear(),this._activeCameras=[],this._editorCameras.clear(),this._lockedEditorIds.clear(),this._screenSpacePanIds.clear(),this._framedEditorViews.clear(),this._entityBounds=null,this._rememberedGameCamera=null,this._suspendedOrbits.clear(),this._rendererManager=null,this._sceneRef=null}async createEditorCameras(){if(this._editorCameras.size>0||!this._sceneRef||!this._rendererManager)return;let e=this.primaryCamera??this.ensureDefaultCamera();e.sceneRef||(e.setRendererManager(this._rendererManager),await e.setup(this._sceneRef,this._rendererManager));let t=ii(e.camera),i=this._rendererManager.screenResolution.clone(),r=Math.max(t.distance,4);this.isEditorCamera(e)||(this._rememberedGameCamera=e);for(let n of Jr){let o=new T(n.perspective,i,r);o._skipDebugOrbit=!0;let a=n.position(t.lookAt,t.distance,e.camera.position),l=n.up(e.camera.up);o.camera.up.copy(l),o.camera.position.copy(a),o.camera.lookAt(t.lookAt),(o.camera instanceof ti||o.camera instanceof Ye)&&(o.camera.near=n.near??.1,o.camera.far=n.far??2e3,o.camera.updateProjectionMatrix()),this.addCamera(o,n.id),this._editorCameras.set(n.id,o),n.lockRotation&&this._lockedEditorIds.add(n.id),n.screenSpacePan&&this._screenSpacePanIds.add(n.id),o.setRendererManager(this._rendererManager),await o.setup(this._sceneRef,this._rendererManager),n.fullPolarRange&&o.allowFullOrbit(),o.seedDebugOrbitPose(a,t.lookAt)}}showEditorCamera(e,t){if(!this._editorViewLocked){let i=this.primaryCamera;i&&!this.isEditorCamera(i)&&(this._rememberedGameCamera=i)}return this.isOrthographicEditorView(e)&&!this._framedEditorViews.has(e)&&this.frameOrthographicView(e,t)&&this._framedEditorViews.add(e),this._editorViewLocked=!0,this.suspendOtherOrbits(t),this.syncEditorOrbit(e),this.commitActive(t)}showGameCamera(e){return this._editorViewLocked=!1,this.syncEditorOrbit(null),this.restoreOrbitFor(e),this.commitActive(e)}syncEditorOrbit(e){for(let[t,i]of this._editorCameras)t===e?(t===g.free&&i.allowFullOrbit(),i.armEditorOrbit(this._lockedEditorIds.has(t),this._screenSpacePanIds.has(t))):i.disarmEditorOrbit()}isOrthographicEditorView(e){return e===g.side||e===g.top||e===g.isometric}copyFreeFromGame(){let e=this._editorCameras.get(g.free),t=this.gameCameraToRestore();if(!e||!t)return!1;let i=t.camera;i.updateMatrixWorld(!0);let r=ii(i);return e.camera.up.copy(i.up),(i instanceof Ye||i instanceof ti)&&this.copyGameplayProjection(i,e,r.distance),e.allowFullOrbit(),e.replaceOrbitPose(i.position,r.lookAt),!0}copyGameplayProjection(e,t,i){let r=t.camera;r instanceof Ye&&(e instanceof Ye?(r.fov=e.fov,r.zoom=e.zoom,r.near=e.near,r.far=e.far):e instanceof ti&&(r.fov=Kr(e,i),r.zoom=1),r.updateProjectionMatrix())}frameOrthographicView(e,t){let i=Jr.find(Gn=>Gn.id===e),r=this.gameCameraToRestore();if(!i||!r)return!1;let n=r.camera;n.updateMatrixWorld(!0);let o=ii(n),a=qr(n,o.distance),l=Qr(this._entityBounds?.()??[],a),c=Math.max(o.distance,4),d=i.position(o.lookAt,c,n.position);t.camera.up.copy(i.up(n.up)),t.camera.position.copy(d),t.camera.lookAt(o.lookAt),t.camera.updateMatrixWorld(!0);let u=new w().setFromMatrixColumn(t.camera.matrixWorld,0),p=new w().setFromMatrixColumn(t.camera.matrixWorld,1),m=new w;t.camera.getWorldDirection(m);let v=t.screenResolution.x/Math.max(t.screenResolution.y,1),S=Yr(o.lookAt,u,p,l,a,v),we=$r(t.camera.position,m,l,{near:i.near??.1,far:i.far??2e3});return t.applyOrthographicFrame(S,we.near,we.far),t.replaceOrbitPose(d,o.lookAt),!0}suspendOtherOrbits(e){for(let t of this.cameras.values())t===e||this.isEditorCamera(t)||t.isOrbitActive&&(t.setOrbitInteractionEnabled(!1),this._suspendedOrbits.add(t))}restoreOrbitFor(e){this._suspendedOrbits.has(e)&&(e.setOrbitInteractionEnabled(!0),this._suspendedOrbits.delete(e))}gameCameraToRestore(){if(this._rememberedGameCamera&&this.cameraIsRegistered(this._rememberedGameCamera))return this._rememberedGameCamera;for(let e of this.cameras.values())if(!this.isEditorCamera(e))return e;return null}cameraIsRegistered(e){for(let t of this.cameras.values())if(t===e)return!0;return!1}isEditorCamera(e){for(let t of this._editorCameras.values())if(t===e)return!0;return!1}commitActive(e){let t=this.primaryCamera,i=this._activeCameras.filter(r=>r!==this._activeCameras[0]&&r.viewport.width<1);return this._activeCameras=[e,...i],t!==e&&this._rendererManager?.rebindPostProcessingCamera(e.camera),!0}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;for(let t of this.cameras.values())if(t===e)return t;return null}};var E=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.applyPerspective(e,U(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function Fc(s){let e=Ri(s.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;(s.perspective==="fixed-2d"||s.perspective==="isometric"||s.perspective==="top-down")&&(t=s.zoom||10);let i=new T(s.perspective||"third-person",e,t);s.name&&(i.name=s.name);let r=f(s.position,D),n=f(s.target,D);i.move(r),i.camera.lookAt(n);let o=s.perspective||"third-person";if(o==="fixed-2d"||o==="flat-2d"?i.applyPerspective(o,U(o,{zoom:t})):o==="isometric"||o==="top-down"?i.applyPerspective(o,U(o,{zoom:t,initialPosition:r.clone(),initialLookAt:n.clone()})):i.applyPerspective(o,U(o,{initialPosition:r.clone(),initialLookAt:n.clone()})),s.viewport&&(i.viewport={...s.viewport}),s.useOrbitalControls&&(i._useOrbitalControls=!0),s.skipDebugOrbit&&(i._skipDebugOrbit=!0),s.damping!=null&&(i.pipeline.damping=s.damping),s.behaviors)for(let[a,l]of Object.entries(s.behaviors))i.pipeline.addBehavior(a,l);if(s.renderToTexture){let{width:a=512,height:l=512}=s.renderToTexture;i.createRenderTarget(a,l)}return new E(i)}import{Vector3 as Ws}from"three";function V(s){return!!s&&typeof s=="object"&&typeof s.create=="function"}function be(s){return!!s&&typeof s.then=="function"}function ri(s){return!!s&&typeof s=="object"&&s instanceof E}function en(s){return!s||typeof s!="object"||V(s)||ri(s)||be(s)||typeof s.then=="function"?!1:s.constructor===Object||s.constructor?.name==="Object"}function tn(s){return s?!!(V(s)||typeof s=="function"||be(s)):!1}var qs="/three/basis/";function Je(s){return{...s,ktx2TranscoderPath:s?.ktx2TranscoderPath??qs}}var Xe=class{constructor(e,t,i,r,n,o,a=60,l={},c=!0,d=[]){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=n;this.variables=o;this.physicsRate=a;this.assetLoaders=l;this.defaultLighting=c;this.postProcessingEffects=d}};function Ks(){return new Xe({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},ze,null,null,new Ws(0,0,0),{},60,{},!0)}function rn(s=[]){let e=Ks(),t={},i=[],r=[],n=[];for(let l of s)ri(l)?n.push(l):V(l)?i.push(l):tn(l)&&!V(l)?r.push(l):en(l)&&(t={...t,...l});let o=new Xe(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),a=n.length>0?n[0]:void 0;return{config:o,entities:i,asyncEntities:r,camera:a,cameras:n}}function qc(s){return{...s}}var Qs=Symbol("vessel"),Ce=class extends se{static type=Qs;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=Ys();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function Ys(...s){let e=new Ce;return s.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Vn,Vector3 as In}from"three";import{createSimulation as $s}from"@zylem/behaviors/core";function ni(s){return typeof s?.handlePostCollision=="function"&&typeof s?.handleIntersectionEvent=="function"}function Xs(s,e){return s<e?`${s}|${e}`:`${e}|${s}`}var et=class s{type="World";simulation;collisionMap=new Map;collisionBehaviorMap=new Map;_removalMap=new Map;activeCollisionPairs=new Map;livePairs=new Map;handleIdToUuid=new Map;currentCollisionTimeMs=0;zeroGravity;fixedTimestep;interpolationAlpha=0;stepClock={steps:0};static async create(e,t=60){let i={x:e?.x??0,y:e?.y??0,z:e?.z??0},r=await $s({gravity:[i.x,i.y,i.z],fixedTimestep:1/t,initialCapacity:4096});return new s(r,t,i.x===0&&i.y===0&&i.z===0)}constructor(e,t=60,i=!1){this.simulation=e,this.fixedTimestep=1/t,this.zeroGravity=i,this.simulation?.setEventsEnabled?.(!1)}addEntity(e){let t={...e.bodyDesc??{}},i=e.colliderDescs?.length?e.colliderDescs:e.colliderDesc?[e.colliderDesc]:[];this.zeroGravity&&(t.lockTranslation=t.lockTranslation??[!0,!0,!0],t.lockRotation=t.lockRotation??[!0,!0,!0]),(e.controlledRotation||e instanceof Re)&&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 Ni(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=Xs(i,r),o=this.livePairs.get(n);o||(o={uuidA:i<r?i:r,uuidB:i<r?r:i,contactCount:0,intersectionCount:0},this.livePairs.set(n,o));let a=t.type==="collisionStarted"?1:-1;t.sensor?o.intersectionCount=Math.max(0,o.intersectionCount+a):o.contactCount=Math.max(0,o.contactCount+a),o.contactCount===0&&o.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(!ni(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 o=this.collisionMap.get(n.uuidA),a=this.collisionMap.get(n.uuidB);this.activeCollisionPairs.has(r)||this.dispatchCollisionPhase(n,"enter",t),(this.entityHasCollisionPhaseListener(o,"stay")||this.entityHasCollisionPhaseListener(a,"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),o=this.collisionMap.get(e.uuidB);n&&o&&n._collision(o,Mt.globals,r);let a=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);a&&l&&l._collision(a,Mt.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&ni(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let n=this.collisionMap.get(e.uuidA),o=this.collisionMap.get(e.uuidB);n&&o&&ni(o)&&(o.handleIntersectionEvent({entity:o,other:n,delta:t}),this.collisionBehaviorMap.set(o.uuid,o))}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 Js,Color as nn,AmbientLight as eo,DirectionalLight as to,Vector3 as tt,GridHelper as io,Texture as ro,SRGBColorSpace as no}from"three";var it=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new Js,o=i.backgroundColor instanceof nn?i.backgroundColor:new nn(i.backgroundColor);r.background=o,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&Q.loadTexture(i.backgroundImage,{colorSpace:no}).then(a=>{r.background=a}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),h.enabled&&this.debugScene()}setupBackgroundShader(e,t){if(!Me(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:x()})}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 ro&&(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 eo(16777215,1);e.add(t);let i=new to(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 tt(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(F(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=so(e);i&&i.attachToScene(this.scene);let r=e.options.position??new tt(0,0,0);if(e.physicsAttached&&e.body)try{let n=e.body.translation();r=new tt(n.x,n.y,n.z)}catch{r=e.options.position??new tt(0,0,0)}this.add(t,r),oe(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new io(1e3,100);this.scene.add(i)}};function so(s){return s.constructor.type===Ui?s:null}var rt=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 oo}from"three";var sn=new oo;function on(s){let e=s._childrenMap,t=s._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval||i.isInstanced||i.isBundled||i.skipRenderPoseSync)continue;let r=i.body,n=i.group??i.mesh,o=n?Te(r,t?.interpolationAlpha??0):null;n&&o&&n.position.set(o.position.x,o.position.y,o.position.z),!i.controlledRotation&&n&&o&&(sn.set(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w),n.setRotationFromQuaternion(sn))}}import{nanoid as pa}from"nanoid";import{Box3 as gt,BufferAttribute as Rn,BufferGeometry as $o,LineBasicMaterial as Xo,LineSegments as Jo,Raycaster as ea,Vector2 as ta,Vector3 as yt}from"three";import{subscribe as ia}from"valtio/vanilla";import{nanoid as Tn}from"nanoid";import{getZylemBridge as zn}from"@zylem/bridge";import{StageBodyKind as ra}from"@zylem/behaviors/core";import{Box3 as ao,BoxGeometry as an,Color as lo,EdgesGeometry as ln,Group as co,LineBasicMaterial as uo,LineSegments as ho,Mesh as po,MeshBasicMaterial as mo,Vector3 as cn}from"three";var nt=class{scene;container;fillMesh;edgeLines;currentColor=new lo(65280);bbox=new ao;size=new cn;center=new cn;constructor(e){this.scene=e;let t=new an(1,1,1);this.fillMesh=new po(t,new mo({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new ln(t);this.edgeLines=new ho(i,new uo({color:this.currentColor,linewidth:1})),this.container=new co,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}this.bbox.setFromObject(e),this.updateFromBounds(this.bbox)}updateFromBounds(e){if(!e||e.isEmpty()){this.hide();return}if(e!==this.bbox&&this.bbox.copy(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 an(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 ln(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 fo,BoxGeometry as go,Group as yo,Mesh as vo,MeshBasicMaterial as bo,Vector3 as dn}from"three";var Co={x:0,y:0,z:0},So=7128319,wo=.35;function xo(){return new bo({color:So,transparent:!0,opacity:wo,depthWrite:!1})}function Po(s){let e=s.size;return new dn(e?.x??1,e?.y??1,e?.z??1)}function Eo(s,e){try{let t=s.create({position:Co,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 "${s.id}" factory failed, falling back to a box`,t),null}}function Mo(s,e){s.traverse(t=>{let i=t;i.isMesh&&(i.material=e,i.castShadow=!1,i.receiveShadow=!1)})}var st=class{scene;container;builtFor=null;builtProps=null;material=null;extent=null;bounds=new fo;constructor(e){this.scene=e,this.container=new yo,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=K(e),n={...r?.defaultProps??{},...t??{}},a=(r?Eo(r,n):null)??new vo(new go(...Po(n).toArray()));a.position.set(0,0,0),this.material=xo(),Mo(a,this.material),this.container.add(a),this.bounds.setFromObject(a),this.extent=this.bounds.isEmpty()?null:this.bounds.getSize(new dn)}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{Box3 as To,Quaternion as ct,Vector3 as M}from"three";import{nanoid as zo}from"nanoid";import{Vector3 as ie}from"three";var oi=.95,Do=16,Se=new ie,ko=new ie,un=new ie,si=new ie;function hn(s){return s?s.isPerspectiveCamera===!0||s.isOrthographicCamera===!0:!1}function ot(s,e,t=oi){return Se.copy(s).project(e),Math.abs(Se.x)<=t&&Math.abs(Se.y)<=t&&Se.z>=-1&&Se.z<=1}function pn(s){let e=0,t=1;for(let i=0;i<Do;i+=1){let r=(e+t)/2;s(r)?e=r:t=r}return e}function mn(s,e,t,i=oi){if(!hn(t))return e.clone();let r=t;if(ot(e,r,i)||!ot(s,r,i))return e.clone();let n=pn(o=>ot(ko.copy(s).lerp(e,o),r,i));return s.clone().lerp(e,n)}function fn(s,e,t,i,r=oi){if(!hn(i)||t.x<=1&&t.y<=1&&t.z<=1||s.isEmpty())return t.clone();let n=i;un.copy(e);let o=new ie(1,1,1),a=c=>(o.set(1+(t.x-1)*c,1+(t.y-1)*c,1+(t.z-1)*c),Ro(s,un,o,n,r));if(a(1))return t.clone();let l=pn(a);return new ie(1+(t.x-1)*l,1+(t.y-1)*l,1+(t.z-1)*l)}function Ro(s,e,t,i,r){for(let n=0;n<8;n+=1)if(si.set(n&1?s.max.x:s.min.x,n&2?s.max.y:s.min.y,n&4?s.max.z:s.min.z),si.sub(e).multiply(t).add(e),!ot(si,i,r))return!1;return!0}var Bo={translate:"Move",rotate:"Rotate",scale:"Scale"};function ai(s){let e=typeof s?.getPose=="function"?s.getPose():null,t=s?.group??s?.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 s?.getScale=="function"?s.getScale():{x:1,y:1,z:1};return{position:new M(i.x,i.y,i.z),quaternion:new ct(r.x,r.y,r.z,r.w),scale:new M(n.x,n.y,n.z)}}function gn(s){let e=zt(s.quaternion);return{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:e,quaternion:{x:s.quaternion.x,y:s.quaternion.y,z:s.quaternion.z,w:s.quaternion.w},scale:{x:s.scale.x,y:s.scale.y,z:s.scale.z}}}function _o(s,e){return s.position.distanceToSquared(e.position)>1e-5*1e-5||Math.abs(s.quaternion.dot(e.quaternion))<1-1e-5||s.scale.distanceToSquared(e.scale)>1e-5*1e-5}function at(s,e){(e.position||e.quaternion)&&s.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&&s.setScale?.(e.scale.x,e.scale.y,e.scale.z)}function Lo(s){let e=s?.group??s?.mesh;if(!e?.isObject3D)return null;let t=new To().setFromObject(e);return t.isEmpty()?null:t}var li=.02,ci=50;function Ao(s){return new M(di(s.x,li,ci),di(s.y,li,ci),di(s.z,li,ci))}function di(s,e,t){return Math.min(Math.max(s,e),t)}var ui=new ct,Oo=new M,lt=class{gizmo=new $i;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=h.paused,h.paused=!0):!e&&this.pausedBeforeEntry!==null&&(h.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 h.selectedEntityIds){let o=this.context.resolveEntity(n);o&&r.push({uuid:n,entity:o,start:ai(o),startBounds:this.mode==="scale"?Lo(o):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 o=B(),a=o.enabled&&!t;switch(n.kind){case"translate":this.applyTranslate(i,n.offset,a?o.translate:0,r);break;case"rotate":this.applyRotate(i,n.axis,n.angle,a?o.rotate:0);break;case"scale":this.applyScale(i,n.factor,a?o.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=ai(i.entity);_o(i.start,r)&&(e.mode==="scale"&&Bt(i.entity),t.push({uuid:i.uuid,before:gn(i.start),after:gn(r)}))}t.length&&ne({opId:zo(10),kind:"transform",label:this.describeOperation(e),entries:t})}cancelDrag(){this.session=null,this.gizmo.endDrag()}dispose(){this.cancelDrag(),this.pausedBeforeEntry!==null&&(h.paused=this.pausedBeforeEntry,this.pausedBeforeEntry=null),this.gizmo.dispose()}applyTranslate(e,t,i,r){let n=Oo.copy(e.pivotStart).add(t),o=mn(e.pivotStart,n,r),a=i>0?q(o,i):o,l=new M(a.x-e.pivotStart.x,a.y-e.pivotStart.y,a.z-e.pivotStart.z);for(let c of e.entries)at(c.entity,{position:c.start.position.clone().add(l)})}applyRotate(e,t,i,r){let n=e.axis;for(let o of e.entries){ui.setFromAxisAngle(t,i);let a=ui.clone().multiply(o.start.quaternion),l=a;if(r>0&&(n==="x"||n==="y"||n==="z")){let d=zt(a);d[n]=Di(d[n],r);let u=Tt(d);l=new ct(u.x,u.y,u.z,u.w)}let c=o.start.position.clone().sub(e.pivotStart).applyQuaternion(ui).add(e.pivotStart);at(o.entity,{position:c,quaternion:l})}}applyScale(e,t,i,r){for(let n of e.entries){let o=n.startBounds?fn(n.startBounds,n.start.position,t,r):t,a=Ao(o),l=new M(n.start.scale.x*a.x,n.start.scale.y*a.y,n.start.scale.z*a.z),c=i>0?ki(l,i):l;at(n.entity,{scale:new M(c.x,c.y,c.z)})}}describeOperation(e){let t=Bo[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=h.selectedEntityIds;if(!e.length)return null;let t=new M,i=0;for(let r of e){let n=this.context.resolveEntity(r);n&&(t.add(ai(n).position),i++)}return i?t.divideScalar(i):null}};function yn(s,e,t){for(let i of s.entries){let r=e==="undo"?i.before:i.after;if(!r)continue;let n=t(i.uuid);if(!n)continue;let o=r.quaternion??(r.rotation?Tt(r.rotation):void 0);at(n,{position:r.position?new M(r.position.x,r.position.y,r.position.z):void 0,quaternion:o?new ct(o.x,o.y,o.z,o.w):void 0,scale:r.scale?new M(r.scale.x,r.scale.y,r.scale.z):void 0}),r.scale&&Bt(n)}}var Vo=200;function vn(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function Io(s){return vn(s)&&(Me(s)||zi(s))}var dt=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 o of e.swatches){let{result:a,entry:l}=this.applyPair(n,o,t);i.push(a),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(!vn(t.props))return{result:{...r,ok:!1,reason:"invalid-props"}};let o=i.get(e)??{previousRefs:new Map,appliedRefs:new Map},a=t.kind==="shader"?this.applyShader(n,t,o):this.applyBehavior(n,t,o);return a.ok?(i.set(e,o),{result:{...r,ok:!0,replaced:a.replaced},entry:{uuid:e,swatch:t,...a.replacedSpec?{replaced:a.replacedSpec}:{}}}):{result:{...r,ok:!1,reason:a.reason}}}applyShader(e,t,i){let r=ke("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(a){return console.warn(`[zylem] swatch shader "${t.source}" threw`,a),{ok:!1,reason:"invalid-props"}}if(!Io(n))return{ok:!1,reason:"invalid-props"};let o=e.setMaterial({shader:n},{disposePrevious:!1});return o?(i.previousMaterials?hi(o,i.previousMaterials):i.previousMaterials=o,{ok:!0,replaced:!1}):{ok:!1,reason:"no-material"}}applyBehavior(e,t,i){let r=ke("behavior",t.source);if(!r)return{ok:!1,reason:"unknown-source"};let{descriptor:n}=r,o=n.key,a=!1,l,c=e.getBehaviorRef(n);c&&(e.removeBehavior(c),this.stage.detachBehaviorLink(e,c),i.appliedRefs.get(o)===c||(a=!0,l={source:t.source,props:{...c.options}},i.previousRefs.has(o)||i.previousRefs.set(o,c)));let d;try{e.use(n,t.props),d=e.getBehaviorRefs().at(-1)}catch(u){console.warn(`[zylem] swatch behavior "${t.source}" failed to attach`,u)}return!d||d.descriptor.key!==o?(c&&(e.restoreBehaviorRef(c),this.stage.attachBehaviorLink(e,c),i.previousRefs.get(o)===c&&i.previousRefs.delete(o)),{ok:!1,reason:"invalid-props"}):(this.stage.attachBehaviorLink(e,d),i.appliedRefs.set(o,d),{ok:!0,replaced:a,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=ke("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 o=i.getBehaviorRefs().at(-1);o&&this.stage.attachBehaviorLink(i,o)}continue}i.setMaterial({})}}}remember(e,t){for(this.snapshots.has(e)&&this.forget(e),this.snapshots.set(e,t);this.snapshots.size>Vo;){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()??[];hi(r.previousMaterials??[],n),hi(r.redoMaterials??[],n)}}};function hi(s,e){for(let t of s)e.includes(t)||t.dispose()}import{Box3 as Zo,Frustum as No,Vector2 as ht}from"three";import{Frustum as Fo,Vector2 as bn,Vector3 as Go}from"three";var Cn=Array.from({length:8},()=>new Go),b=new bn,C=new bn;function Sn(s,e,t,i=new Fo){b.set(Math.min(e.x,t.x),Math.min(e.y,t.y)),C.set(Math.max(e.x,t.x),Math.max(e.y,t.y));let r=1e-5;C.x-b.x<r&&(C.x=b.x+r),C.y-b.y<r&&(C.y=b.y+r),I(0,b.x,b.y,-1,s),I(1,C.x,b.y,-1,s),I(2,C.x,C.y,-1,s),I(3,b.x,C.y,-1,s),I(4,b.x,b.y,1,s),I(5,C.x,b.y,1,s),I(6,C.x,C.y,1,s),I(7,b.x,C.y,1,s);let[n,o,a,l,c,d,u,p]=Cn,m=i.planes;return re(m[0],n,c,p),re(m[1],o,u,d),re(m[2],l,p,u),re(m[3],n,d,c),re(m[4],n,l,a),re(m[5],c,u,p),i}function I(s,e,t,i,r){Cn[s].set(e,t,i).unproject(r)}function re(s,e,t,i){s.setFromCoplanarPoints(e,t,i)}function wn(s,e){return e.isEmpty()||!Number.isFinite(e.min.x)||!Number.isFinite(e.max.x)?!1:s.intersectsBox(e)}function xn(s,e,t){switch(t){case"add":{let i=new Set(s),r=[...s];for(let n of e)i.has(n)||(i.add(n),r.push(n));return r}case"subtract":{let i=new Set(e);return s.filter(r=>!i.has(r))}default:return[...new Set(e)]}}function Pn(s){return s.altKey?"subtract":s.shiftKey?"add":"replace"}var Ho="[data-zylem-overlay-root]";function En(s){let e=s.parentElement;return e?e.querySelector(Ho)??e:null}var ut=class{element=null;host=null;show(e,t){let i=this.ensureElement(e);i.style.left=`${t.left}px`,i.style.top=`${t.top}px`,i.style.width=`${t.width}px`,i.style.height=`${t.height}px`,i.style.display="block"}hide(){this.element&&(this.element.style.display="none")}dispose(){this.element?.remove(),this.element=null,this.host=null}ensureElement(e){if(this.element&&this.host===e)return this.element;this.element?.remove();let t=document.createElement("div");t.dataset.zylemMarquee="true";let i=t.style;return i.position="absolute",i.pointerEvents="none",i.boxSizing="border-box",i.border="1px solid rgba(34, 255, 34, 0.9)",i.background="rgba(34, 255, 34, 0.12)",i.display="none",i.zIndex="20",e.appendChild(t),this.element=t,this.host=e,t}};var Uo=4,jo=new Zo,Mn=new No,pt=class{context;overlay=new ut;armed=!1;dragging=!1;mode="replace";baseSelection=[];startNdc=new ht;currentNdc=new ht;startClient=new ht;currentClient=new ht;host=null;constructor(e){this.context=e}get isArmed(){return this.armed}get isDragging(){return this.dragging}pointerDown(e,t,i){this.armed=!0,this.dragging=!1,this.mode=Pn(t),this.baseSelection=[...h.selectedEntityIds],this.startNdc.copy(e),this.currentNdc.copy(e),this.startClient.set(t.clientX,t.clientY),this.currentClient.copy(this.startClient),this.host=En(i)}pointerMove(e,t){if(!this.armed)return!1;this.currentNdc.copy(e),this.currentClient.set(t.clientX,t.clientY);let i=!1;if(!this.dragging){if(this.currentClient.distanceTo(this.startClient)<Uo)return!1;this.dragging=!0,i=!0}return this.drawOverlay(),i}pointerUp(e){if(!this.armed)return"idle";let t=this.dragging;return this.currentNdc.copy(e),this.reset(),t?(this.commit(),"marquee"):"click"}cancel(){this.reset()}dispose(){this.reset(),this.overlay.dispose()}reset(){this.armed=!1,this.dragging=!1,this.overlay.hide()}drawOverlay(){if(!this.host)return;let e=this.host.getBoundingClientRect(),t=Math.min(this.startClient.x,this.currentClient.x)-e.left,i=Math.min(this.startClient.y,this.currentClient.y)-e.top;this.overlay.show(this.host,{left:t,top:i,width:Math.abs(this.currentClient.x-this.startClient.x),height:Math.abs(this.currentClient.y-this.startClient.y)})}commit(){let e=this.context.getCamera();if(!e)return;Sn(e,this.startNdc,this.currentNdc,Mn);let t=[];this.context.forEachEntity((i,r)=>{let n=$(r,jo);n&&wn(Mn,n)&&t.push(i)}),yi(xn(this.baseSelection,t,this.mode))}};import{BoxGeometry as Wo,EdgesGeometry as qo,Group as Ko,LineBasicMaterial as Qo,LineSegments as Yo,Vector3 as kn}from"three";var mt=new kn,Dn=new kn,ft=class{scene;container=new Ko;edges;material;pool=[];constructor(e,t=16765503){this.scene=e;let i=new Wo(1,1,1);this.edges=new qo(i),i.dispose(),this.material=new Qo({color:t,depthTest:!1,transparent:!0,opacity:.9}),this.container.name="SelectionHighlight",this.container.renderOrder=999,this.scene.add(this.container)}setColor(e){this.material.color.set(e)}update(e){let t=0;for(let i of e){if(i.isEmpty()||!Number.isFinite(i.min.x)||!Number.isFinite(i.max.x))continue;i.getSize(mt),i.getCenter(Dn);let r=this.acquire(t);t+=1,r.position.copy(Dn),r.scale.set(Math.max(mt.x,1e-6),Math.max(mt.y,1e-6),Math.max(mt.z,1e-6)),r.visible=!0}for(let i=t;i<this.pool.length;i+=1)this.pool[i].visible=!1}hide(){for(let e of this.pool)e.visible=!1}dispose(){this.scene.remove(this.container),this.edges.dispose(),this.material.dispose(),this.pool.length=0}acquire(e){let t=this.pool[e];if(t)return t;let i=new Yo(this.edges,this.material);return i.frustumCulled=!1,this.container.add(i),this.pool.push(i),i}};var Bn=2293538,na=16724787,pi=new gt,_n=new yt,vt=class{stage;options;mouseNdc=new ta(-2,-2);raycaster=new ea;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;placementGhost=null;debugLines=null;debugStateUnsubscribe=null;focusContextUnregister=null;entityResolverUnregister=null;lastDebugEnabled=null;warnedMissingAddFactory=!1;transformTool;swatchApplier;marquee;selectionHighlight=null;selectionBoundsPool=[];hoverBounds=new gt;grid=new Yi;levelSession;levelPointer=!1;lastTool=null;capturedPointer=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.transformTool=new lt({getScene:()=>this.stage.scene?.scene??null,getCamera:()=>this.getDebugViewCamera()?.camera??null,resolveEntity:i=>this.resolveEntity(i)}),this.swatchApplier=new dt({resolveEntity:i=>this.resolveEntity(i),attachBehaviorLink:(i,r)=>this.stage.entityDelegate.attachBehaviorLink(i,r),detachBehaviorLink:(i,r)=>this.stage.entityDelegate.detachBehaviorLink(i,r)}),this.marquee=new pt({getCamera:()=>this.getDebugViewCamera()?.camera??null,forEachEntity:i=>this.forEachSelectableEntity(i)}),this.levelSession=new He(this.levelSessionHost()),this.syncWithDebugState(),this.debugStateUnsubscribe=ia(h,()=>{this.syncWithDebugState()}),this.entityResolverUnregister=gi(i=>this.resolveEntity(i)),this.focusContextUnregister=Mi({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{let r=this.stage.cameraManagerRef,n=()=>{r&&!r.isEditorViewActive()&&r.hasEditorCameras()&&r.activateCameraById(g.free),this.getDebugViewCamera()?.frameObject(i)};if(r&&Ee()&&!r.hasEditorCameras()){r.ensureEditorCameras().then(n);return}n()},ensureDebugReady:()=>{h.enabled||(h.enabled=!0),this.lastDebugEnabled=!0,this.activate()}}),this.stage.cameraManagerRef?.setEditorEntityBounds(()=>this.editorEntityBoxes())}setAddEntityFactory(e){this.options.addEntityFactory=e,this.warnedMissingAddFactory=!1}syncLevel(e){this.levelSession.sync(e),this.syncGrid()}playLevel(e){this.levelSession.play(e),this.syncGrid()}closeLevel(){this.levelSession.close(),this.syncGrid()}levelSessionHost(){return{getScene:()=>this.stage.scene?.scene??null,cameraId:()=>this.stage.cameraManagerRef?.activeEditorCameraId()??null,viewDirection:()=>{let e=this.getDebugViewCamera()?.camera;if(!e)return{x:0,y:-1,z:0};e.updateMatrixWorld(!0);let t=new yt;return e.getWorldDirection(t),{x:t.x,y:t.y,z:t.z}},physicsHit:e=>{let t=this.stage.world?.raycast(e.origin,e.direction,this.options.maxRayDistance);return t?{distance:t.distance,normal:t.normal}:null},spawnZone:async e=>{let t=Zi({name:e.name,position:e.position,size:e.size,editorOwned:!0});return await this.stage.spawnEntity(t),t.uuid??null},detach:e=>{this.stage.entityDelegate.detachEntity(e)},spawnHulls:e=>{let t=this.stage.world?.simulation;return!t||e.length===0?null:t.spawn({body:{kind:ra.Static,position:[0,0,0],rotation:[0,0,0,1],canSleep:!0,ccdEnabled:!1},colliders:e.map(i=>({shape:{type:"convexHull",vertices:i},friction:.5,restitution:0,sensor:!1}))})},despawnHulls:e=>{if(e)try{this.stage.world?.simulation.despawn(e)}catch{}},publishGesture:e=>{Ln("level:gesture",{gesture:e})},publishSelect:e=>{Ln("level:select",{id:e})},publishNotice:e=>{_t("info",e)}}}getDebugViewCamera(){return this.stage.cameraManagerRef?.primaryCamera??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)}forEachSelectableEntity(e){let t=new Set,i=(r,n)=>{t.has(n)||(t.add(n),e(n,r))};this.stage.entityDelegate.childrenMap.forEach(i),this.stage.entityDelegate.debugMap.forEach(i)}populateDebugMap(){this.stage.entityDelegate.childrenMap.forEach((e,t)=>{this.stage.entityDelegate.debugMap.set(t,e)})}syncWithDebugState(){this.syncToolMode(),this.syncGrid();let e=h.enabled;e!==this.lastDebugEnabled&&(this.lastDebugEnabled=e,e?this.activate():this.deactivate())}syncToolMode(){let e=h.tool;if(e===this.lastTool)return;this.lastTool=e,this.marquee.isArmed&&(this.marquee.cancel(),this.endPointerCapture()),e!=="none"&&(this.ensureInteraction(),this.populateDebugMap()),this.parkToolVisuals(e);let t=Dt(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(B().translate),this.grid.setVisible(h.gridVisible||this.levelSession.isEditing))}activate(){this.domListenersAttached||(this.domListenersAttached=this.attachDomListeners()),this.populateDebugMap(),this.rebindPostProcessing(this.getDebugViewCamera()),document.pointerLockElement&&document.exitPointerLock()}deactivate(){this.disposeDebugVisuals(),this.transformTool.cancelDrag(),this.grid.setVisible(!1),this.rebindPostProcessing(this.getDebugViewCamera())}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 Jo(new $o,new Xo({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 nt(e),this.placementGhost??=new st(e),this.selectionHighlight??=new ft(e))}updateSelectionHighlight(){let e=this.selectionHighlight;if(!e)return;let t=h.selectedEntityIds;if(t.length===0){e.hide();return}let i=[];for(let r of t){let n=this.resolveEntity(r),o=this.selectionBoundsPool[i.length]??=new gt,a=$(n,o);a&&i.push(a)}e.update(i)}parkToolVisuals(e){e!=="add"&&this.placementGhost?.hide(),e!=="select"&&e!=="delete"&&!h.pickMode&&this.debugCursor?.hide(),e==="none"&&!h.enabled&&this.selectionHighlight?.hide()}disposeToolVisuals(){this.debugCursor?.dispose(),this.debugCursor=null,this.placementGhost?.dispose(),this.placementGhost=null,this.selectionHighlight?.dispose(),this.selectionHighlight=null}update(){let e=this.getDebugViewCamera();if(!this.stage.scene||!this.stage.world||!e)return;let{world:t}=this.stage,i=z();if(this.ensureInteraction(),this.ensureToolVisuals(),this.levelSession.tick(),this.syncGrid(),h.enabled?(this.initDebugVisuals(),this.updateColliderWireframes(t)):this.disposeDebugVisuals(),this.updatePlacementGhost(i,t),this.updateSelectionHighlight(),Dt(i)){this.debugCursor?.hide(),this.transformTool.update(),this.transformTool.isDragging||this.transformTool.hover(this.currentRay());return}if(this.transformTool.update(),!(i==="select"||i==="delete"||h.pickMode)){this.debugCursor?.hide();return}let n=this.currentRay(),o=t.raycast(n.origin,n.direction,this.options.maxRayDistance);o?Rt(o.uuid??null):Pe();let a=Ci();if(!a){this.debugCursor?.hide();return}let l=$(this.resolveEntity(a),this.hoverBounds);if(!l){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(Bn);break;case"delete":this.debugCursor?.setColor(na);break;default:this.debugCursor?.setColor(h.pickMode?Bn:16777215);break}this.debugCursor?.updateFromBounds(l)}pickAtNdc(e,t,i={}){let r=i.updateHover??h.pickMode;this.mouseNdc.set(e,t);let n=this.stage.world;if(!n||!this.getDebugViewCamera())return r&&Pe(),null;let o=this.currentRay(),l=n.raycast(o.origin,o.direction,this.options.maxRayDistance)?.uuid??null;if(!l)return r&&Pe(),null;r&&Rt(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 Rn(new Float32Array(t.vertices),3)),this.debugLines.geometry.setAttribute("color",new Rn(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||!W()||(this.domListenersAttached=this.attachDomListeners())}updatePlacementGhost(e,t){let i=this.placementGhost;if(!i)return;let r=h.addTypeId;if(e!=="add"||!r){i.hide();return}i.setType(r,h.addTypeProps??null);let n=this.currentRay(),o=t.raycast(n.origin,n.direction,this.options.maxRayDistance)??null,a=Z(n,o,B(),i.measure());if(!a){i.hide();return}i.showAt(a.position)}editorEntityBoxes(){let e=[];return this.stage.entityDelegate.childrenMap.forEach(t=>{let i=$(t,new gt);i&&e.push(i.clone())}),e}dispose(){this.stage.cameraManagerRef?.setEditorEntityBounds(null),this.focusContextUnregister?.(),this.focusContextUnregister=null,this.entityResolverUnregister?.(),this.entityResolverUnregister=null,this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.endPointerCapture(),this.levelSession.dispose(),this.marquee.dispose(),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":yn(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,t={shiftKey:!1,altKey:!1}){let i=z();if(i!=="select"&&i!=="delete"&&i!=="add")return;let n=this.stage.world?.raycast(e.origin,e.direction,this.options.maxRayDistance)??null;switch(i){case"select":{let o=n?.uuid??null,a=o&&this.resolveEntity(o)?o:null;t.altKey?a&&vi([a]):t.shiftKey?a&&bi(a):a?kt(a):kt(null);break}case"delete":{let o=n?.uuid??null;if(!o)break;this.stage.entityDelegate.detachEntity(o)&&ne({opId:Tn(10),kind:"delete",label:"Delete entity",entries:[{uuid:o}]});break}case"add":this.placeEntity(e,n);break}}placeEntity(e,t){let i=Z(e,t,B());if(!i)return;let{position:r,normal:n}=i,o=h.addTypeId?K(h.addTypeId):null;if(!o&&!this.options.addEntityFactory){this.warnMissingAddSource();return}let a=o?o.create({position:{x:r.x,y:r.y,z:r.z},normal:{x:n.x,y:n.y,z:n.z},props:{...o.defaultProps??{},...h.addTypeProps??{}}}):this.options.addEntityFactory({position:r,normal:n});a&&Promise.resolve(a).then(async l=>{l&&(await this.stage.entityDelegate.spawnEntity(l),this.restOnSurface(l,r,n),ne({opId:Tn(10),kind:"create",label:`Add ${o?.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"||(pi.setFromObject(r),pi.isEmpty()))return;pi.getSize(_n);let n=Ft(t,_n,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),_t("warn",e)}attachDomListeners(){let e=this.stage.rendererManager?.getDomElement();if(!e)return!1;let t=a=>{let l=e.getBoundingClientRect(),c=(a.clientX-l.left)/l.width*2-1,d=-((a.clientY-l.top)/l.height*2-1);this.mouseNdc.set(c,d)},i=a=>{if(t(a),this.levelPointer){a.preventDefault(),a.stopImmediatePropagation(),this.levelSession.pointerMove(this.currentRay());return}if(this.levelSession.pointerHover(this.currentRay()),this.marquee.isArmed){this.marquee.pointerMove(this.mouseNdc,a);return}this.transformTool.isDragging&&this.transformTool.pointerMove(this.currentRay(),a.altKey)},r=a=>{if(a.button!==0)return;t(a);let l=this.currentRay();if(this.levelSession.pointerDown(l)){a.preventDefault(),a.stopImmediatePropagation(),this.levelPointer=!0,this.beginPointerCapture(e,a.pointerId);return}if(this.transformTool.pointerDown(l)){this.beginPointerCapture(e,a.pointerId);return}if(z()==="select"){this.marquee.pointerDown(this.mouseNdc,a,e),this.beginPointerCapture(e,a.pointerId);return}this.handleAction(l,a)},n=a=>{if(this.levelPointer){a.preventDefault(),a.stopImmediatePropagation(),this.levelSession.pointerUp(this.currentRay()),this.levelPointer=!1,this.endPointerCapture();return}if(this.marquee.isArmed){let l=this.marquee.pointerUp(this.mouseNdc);this.endPointerCapture(),l==="click"&&this.handleAction(this.currentRay(),a);return}this.transformTool.isDragging&&(this.transformTool.pointerUp(),this.endPointerCapture())},o=a=>{if(this.levelPointer){this.levelPointer=!1,this.levelSession.pointerUp(this.currentRay()),this.endPointerCapture();return}if(this.marquee.isArmed){this.marquee.cancel(),this.endPointerCapture();return}n(a)};return e.addEventListener("pointermove",i,!0),e.addEventListener("pointerdown",r,!0),e.addEventListener("pointerup",n,!0),e.addEventListener("pointercancel",o,!0),this.domDisposeFns.push(()=>e.removeEventListener("pointermove",i,!0),()=>e.removeEventListener("pointerdown",r,!0),()=>e.removeEventListener("pointerup",n,!0),()=>e.removeEventListener("pointercancel",o,!0)),!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}}};function Ln(s,e){zn().channel.send.bind(zn().channel)(s,e)}import{Vector2 as sa}from"three";var bt=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new sa(e,t);return new T(y.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new $e;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 o=n.cameraRef;i.addCamera(o,o.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 Ct=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"?xe.emit("stage:loading:start",t):e.type==="progress"?xe.emit("stage:loading:progress",t):e.type==="complete"&&xe.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 St=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)},_.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){le(e.options)||(this.scene?.addEntityGroup(e),oe(e),Y(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),oe(i),Y(i),le(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(_.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as An}from"@zylem/behaviors/core";var oa=200,wt=class s{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 Ce){e.create();for(let i of e.getChildren())i instanceof se&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:x(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();Li(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof se&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:x(),camera:this.camera}),this.tryRegisterRenderStrategy(t),F(t)||this.scene.addEntityGroup(t),Y(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),Ai(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),F(e)||this.scene.addEntityGroup(e),Y(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(ae(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!==An.Static&&(e.bodyDesc.kind=An.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof Re){if(e.needsDeferredModelCollision())return;e.synchronizeRuntimeCollider()}this.world.addEntity(e)}}addEntityToStage(e){this.childrenMap.set(e.uuid,e),h.enabled&&this.debugMap.set(e.uuid,e);for(let t of this.entityAddedHandlers)try{t(e)}catch(i){console.error("onEntityAdded handler failed",i)}De(e,!0)}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),F(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),De(r,!1),this.detachedMap.set(e,{entity:r,position:n?.position??null,rotation:n?.rotation??null}),this.evictOldestDetached(),_.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),F(i)||this.scene.addEntityGroup(i),_i(i),Oi(i),this.addEntityToStage(i),this.entityModelDelegate.observe(i),!0}isDetached(e){return this.detachedMap.has(e)}evictOldestDetached(){for(;this.detachedMap.size>oa;){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:x()})}catch{}X(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 Hi?{...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(V(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();V(i)?this.handleEntityImmediatelyOrQueue(i):be(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}be(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 o=await n;o&&await this.spawnEntity(o)}catch(o){console.error("Failed to resolve pending stage entity",o)}t++,this.loadingDelegate.emitProgress("Loaded async entity",t,r),t%5===0&&await this.yieldToEventLoop()}t%5!==0&&await this.yieldToEventLoop()}registerSystem(e){if(!this.world||!this.scene)return;let t;typeof e=="function"?t=e({world:this.world,scene:this.scene,getBehaviorLinks:i=>this.behaviorEntityIndex.get(i)??s.EMPTY_BEHAVIOR_LINKS,createEntity:Ot,getGlobals:x}):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=>{De(t,!1);try{t.nodeDestroy({me:t,globals:x()})}catch{}X(t),e.push(t.uuid)}),this.detachedMap.forEach(({entity:t})=>{try{t.nodeDestroy?.({me:t,globals:x()})}catch{}X(t)}),this.detachedMap.clear(),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[];for(let t of 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 o=this.behaviorSystemByKey.get(i);if(!o&&!this.registeredSystemKeys.has(i)){let a=t.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:l=>this.behaviorEntityIndex.get(l)??s.EMPTY_BEHAVIOR_LINKS,createEntity:Ot,getGlobals:x});o=a,this.behaviorSystems.push(a),this.behaviorSystemByKey.set(i,a),this.registeredSystemKeys.add(i)}return o?.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(o=>o.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)}}};import{Box3 as On,Raycaster as aa,Vector2 as la,Vector3 as xt}from"three";var ca=5e3,da=new xt(0,1,0),Pt=class{host;unsubscribe;known=new Set;targets=new Map;bounds=new On;raycaster=new aa;mouseNdc=new la;session=null;view=null;closing=!1;disposed=!1;hovered=null;hoveredId=null;lastAim=null;rayOverride=null;canvas=null;listening=!1;keys=!1;constructor(e){this.host=e,this.unsubscribe=[Ii((t,i)=>{if(!this.disposed){if(!i){this.known.delete(t.uuid),this.targets.delete(t.uuid),this.hoveredId===t.uuid&&this.leaveHovered(),this.syncListeners();return}this.known.add(t.uuid),this.syncTarget(t)}}),Vi(t=>{this.disposed||!this.known.has(t.uuid)||this.syncTarget(t)})]}get isPlacing(){return this.session!=null&&!this.closing}get previewOpacity(){return this.view?.opacity??0}get previewPosition(){return this.view?.container.visible?this.view.container.position.clone():null}setRay(e){this.rayOverride=e}registerTarget(e){this.disposed||(this.known.add(e.uuid),this.syncTarget(e))}unregisterTarget(e){this.known.delete(e),this.targets.delete(e),this.hoveredId===e&&this.leaveHovered(),this.syncListeners()}arm(e){this.disposed||(this.closing=!1,this.session=e,this.mountView(),this.syncListeners())}setPayload(e){this.session&&(this.session.payload=e)}setRepresentative(e){this.session&&(this.session.representative=e,this.mountView())}cancel(){this.disposed||!this.session&&!this.view&&!this.closing||(this.beginClose(),this.host.onSessionEnded?.())}update(e){if(this.disposed)return;if(this.syncListeners(),this.suspended()){this.view?.hide();return}!this.view&&this.session&&!this.closing&&this.mountView();let t=this.currentRay();if(t){let i=this.resolveAim(t);this.applyHover(i),this.present(i),this.lastAim=i}this.view?.advance(e,{valid:this.lastAim?.valid??!1,position:mi(this.lastAim?.position)}),this.closing&&this.view?.fadeCompleted&&(this.view.dispose(),this.view=null,this.closing=!1,this.syncListeners())}pointerDown(e){if(this.disposed||this.suspended())return!1;if(e===2)return!this.session&&!this.closing&&!this.view?!1:(this.cancel(),!0);if(e!==0||this.closing)return!1;if(this.session){let t=this.currentRay();return t?this.tryCommit(this.resolveAim(t)):!1}return this.clickHovered()}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.unsubscribe)e();this.unsubscribe.length=0,this.detachListeners(),this.view?.dispose(),this.view=null,this.session=null,this.closing=!1,this.targets.clear(),this.known.clear(),this.hovered=null,this.hoveredId=null}}suspended(){return W()}mountView(){let e=this.host.getScene();!e||!this.session||(this.view?.dispose(),this.view=new tr(e,this.session.representative))}syncTarget(e){Fi(e)?this.targets.set(e.uuid,e):(this.targets.delete(e.uuid),this.hoveredId===e.uuid&&this.leaveHovered()),this.syncListeners()}resolveAim(e){let t=this.nearestArea(e),i=this.surfacePoint(e),r=t?L(t.entity):null,n=r?.role==="droppable",o=!1;if(this.session&&n&&t){let d=r?.handlers.accepts;o=d?d(this.session.payload,t.entity)===!0:!0}let a=null;if(n&&t){if(a=((r?.handlers.placeAt??this.session?.placeAt??"area")==="hit"?t.point:t.center).clone(),this.session?.snap!=null){let u=q(a,this.session.snap);a.set(u.x,u.y,u.z)}}else i&&(a=i.position.clone());let l=i?.normal.clone()??da.clone(),c=!1;return this.session&&a&&(c=this.hasDroppable()?n&&o:!0),{area:t?.entity??null,position:a,normal:l,valid:c}}nearestArea(e){let t=null;for(let i of this.targets.values()){if(!L(i))continue;let r=At(i,this.bounds);if(!r)continue;let n=Gi(e,r);n&&(t&&n.distance>=t.distance||(t={entity:i,distance:n.distance,point:n.point,center:r.getCenter(new xt)}))}return t}hasDroppable(){for(let e of this.targets.values())if(L(e)?.role==="droppable")return!0;return!1}surfacePoint(e){let t=this.host.raycast(e.origin,e.direction,ca),i=this.session?.snap!=null?{enabled:!0,translate:this.session.snap}:{enabled:!1,translate:0};return Z(e,t,i,this.view?.measure()??null)}present(e){if(!this.view||this.closing||!this.session)return;if(!e.position){this.view.hide();return}let t=this.session.representative.options,i=e.valid?t.valid:t.invalid;this.view.setLook(i,t.fadeIn??er,t.opacity??Ji),this.view.showAt(e.position)}applyHover(e){let t=e.area?.uuid??null;t!==this.hoveredId&&(this.hovered&&this.fire(this.hovered,"onLeave",this.lastAim??e),this.hovered=e.area,this.hoveredId=t,e.area&&this.fire(e.area,"onEnter",e)),e.area&&this.fire(e.area,"onMove",e)}leaveHovered(){let e=this.hovered,t=this.lastAim;this.hovered=null,this.hoveredId=null,e&&t&&this.fire(e,"onLeave",t)}fire(e,t,i){let r=L(e)?.handlers[t];if(r)try{r(this.areaContext(e,i))}catch(n){console.error("[zylem] pointer area callback failed",n)}}areaContext(e,t){return{area:e,position:mi(t.position??ua(e)),normal:{x:t.normal.x,y:t.normal.y,z:t.normal.z},valid:this.session?t.valid:!0,payload:this.session?.payload}}tryCommit(e){if(!this.session||!e.valid||!e.position)return!1;let t=this.pointContext(e),i=this.session.spawnOnClick;if(i){let n;try{n=i(t)}catch(o){return console.error("[zylem] spawnOnClick failed",o),!1}if(!ha(n))return!1;try{this.host.addSpawn(n)}catch(o){return console.error("[zylem] placement spawn failed",o),!1}return this.notifyDrop(e.area,t),this.finishCommit(),!0}return(e.area?L(e.area)?.role:null)!=="droppable"?!1:(this.notifyDrop(e.area,t),this.finishCommit(),!0)}pointContext(e){return{position:mi(e.position),normal:{x:e.normal.x,y:e.normal.y,z:e.normal.z},area:e.area,valid:e.valid,payload:this.session?.payload}}notifyDrop(e,t){if(!e)return;let i=L(e);if(!(i?.role!=="droppable"||!i.handlers.onDrop))try{i.handlers.onDrop(t)}catch(r){console.error("[zylem] droppable onDrop failed",r)}}finishCommit(){this.session?.repeat!==!0&&(this.beginClose(),this.host.onSessionEnded?.())}beginClose(){if(this.closing&&!this.session)return;let e=this.session?.representative.options.fadeOut??this.view?.fadeOutDuration??.1;if(this.closing=!0,this.session=null,!this.view||e<=0){this.view?.dispose(),this.view=null,this.closing=!1,this.syncListeners();return}this.view.fadeTo(0,e),this.syncListeners()}clickHovered(){let e=this.currentRay();if(!e)return!1;let t=this.resolveAim(e);if(!t.area)return!1;let i=L(t.area)?.handlers.onClick;if(!i)return!1;try{i(this.areaContext(t.area,t))}catch(r){return console.error("[zylem] pointer area callback failed",r),!1}return!0}currentRay(){if(this.rayOverride)return{origin:this.rayOverride.origin,direction:this.rayOverride.direction.clone().normalize()};let e=this.host.getCamera();return e?(this.raycaster.setFromCamera(this.mouseNdc,e),{origin:this.raycaster.ray.origin.clone(),direction:this.raycaster.ray.direction.clone().normalize()}):null}syncListeners(){if(this.disposed)return;let e=this.suspended(),t=!e&&(this.session!=null||this.closing);t&&!this.keys&&typeof window<"u"?(window.addEventListener("keydown",this.onKeyDown),this.keys=!0):(!t||e)&&this.keys&&typeof window<"u"&&(window.removeEventListener("keydown",this.onKeyDown),this.keys=!1);let i=this.host.getCanvas(),r=!e&&i!=null&&(this.targets.size>0||this.session!=null||this.view!=null||this.closing);r&&i&&(!this.listening||this.canvas!==i)?(this.detachPointer(),this.canvas=i,i.addEventListener("pointermove",this.onPointerMove,!0),i.addEventListener("pointerdown",this.onPointerDown,!0),this.listening=!0):!r&&this.listening&&this.detachPointer()}detachListeners(){this.detachPointer(),this.keys&&typeof window<"u"&&(window.removeEventListener("keydown",this.onKeyDown),this.keys=!1)}detachPointer(){if(!this.listening||!this.canvas){this.listening=!1,this.canvas=null;return}this.canvas.removeEventListener("pointermove",this.onPointerMove,!0),this.canvas.removeEventListener("pointerdown",this.onPointerDown,!0),this.listening=!1,this.canvas=null}onPointerMove=e=>{this.trackPointer(e)};onPointerDown=e=>{this.trackPointer(e),this.pointerDown(e.button)&&(e.preventDefault(),e.stopImmediatePropagation())};onKeyDown=e=>{e.key==="Escape"&&(!this.session&&!this.closing||this.cancel())};trackPointer(e){let t=this.canvas;if(!t)return;let i=t.getBoundingClientRect();if(i.width<=0||i.height<=0)return;let r=(e.clientX-i.left)/i.width*2-1,n=-((e.clientY-i.top)/i.height*2-1);this.mouseNdc.set(r,n)}};function ua(s){let e=At(s,new On);return e?e.getCenter(new xt):new xt}function mi(s){return s?{x:s.x,y:s.y,z:s.z}:{x:0,y:0,z:0}}function ha(s){return s==null||s===!1?!1:typeof s=="object"||typeof s=="function"}var ma="Stage",Et=class extends rt{type=ma;state={...ji};gravity;world;scene;renderStrategy=null;debugDelegate=null;pointerDelegate;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=pa(),this.cameraDelegate=new bt(this),this.loadingDelegate=new Ct,this.entityModelDelegate=new St,this.entityDelegate=new wt(this.loadingDelegate,this.entityModelDelegate),this.pointerDelegate=new Pt(fa(this));let t=rn(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 In(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Vn?e:new Vn(e);Wi(i),qi(t),Ki(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 it(e,r,this.state);let n=this.gravity??new In(0,0,0);if(this.world=await et.create(n,this.state.physicsRate),this.scene.setup(),this.cameraManagerRef&&this.rendererManager){await this.scene.setupCameraManager(this.scene.scene,this.cameraManagerRef,this.rendererManager);let a=this.cameraManagerRef.primaryCamera;a&&(this.rendererManager.setPostProcessingEffects(this.state.postProcessingEffects??[]),this.rendererManager.setupPostProcessing(this.scene.scene,a.camera)),this.rendererManager.startRenderLoop(()=>{this.cameraManagerRef?.render(this.scene.scene)})}else await this.scene.setupCamera(this.scene.scene,r);let o=this.resolveRenderer(r);await Q.configureGLTFRuntime({renderer:o,...Je(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,a=>this.entityDelegate.handleLateModelReady(a)),this.renderStrategy=new Ae,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 vt(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;R("behaviorSystems",()=>{for(let n of this.entityDelegate.behaviorSystems)n.update(void 0,t)}),R("entityLoop",()=>{for(let n of this.entityDelegate.childrenMap.values()){let o=this.childUpdateParams;o.delta=e.delta,o.inputs=e.inputs,o.globals=e.globals,o.camera=e.camera,o.stage=e.stage,o.game=e.game,o.me=n,n.nodeUpdate(o);let a=n;a.transformStore&&Xi(a,a.transformStore),n.markedForRemoval&&this.entityDelegate.removeEntityByUuid(n.uuid)}}),R("worldUpdate",()=>{i.update(e)}),R("behaviorPostUpdate",()=>{for(let n of this.entityDelegate.behaviorSystems)n.postUpdate?.(void 0,t)}),R("syncRenderPoses",()=>{on({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),R("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),R("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),R("scene",()=>{r.update({delta:t})}),this.pointerDelegate.update(t),Ar()}outOfLoop(){this.debugUpdate()}debugUpdate(){W()&&(Wt("debugUpdate"),this.debugDelegate?.update(),qt())}_destroy(e){this.pointerDelegate.dispose(),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,Qi(),X(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)}};function fa(s){return{getScene:()=>s.scene?.scene??null,raycast:(e,t,i)=>{let r=s.world?.raycast(e,t,i);return r?{distance:r.distance,normal:r.normal}:null},addSpawn:e=>{if(s.wrapperRef){s.wrapperRef.add(e);return}s.enqueue(e)},getCanvas:()=>s.rendererManager?.getDomElement()??null,getCamera:()=>(s.cameraManagerRef?.primaryCamera??s.cameraRef)?.camera??null,onSessionEnded:()=>{s.wrapperRef?.abandonPlacement()}}}import{proxy as ga}from"valtio/vanilla";import{Vector3 as ya}from"three";var va={backgroundColor:ze,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new ya(0,0,0),variables:{}},j=ga({...va});function Fn(s){let e=ba(),t={};return typeof s[0]=="object"&&(t=s.shift()??{}),[{...e,...t},...s]}function ba(){return{backgroundColor:j.backgroundColor,backgroundImage:j.backgroundImage??null,inputs:j.inputs?{...j.inputs}:void 0,gravity:j.gravity,variables:j.variables?{...j.variables}:void 0}}var fi=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new xi;inputConfig=null;pendingPlacement=null;placementGeneration=0;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];Q.prepareGLTFRuntime(Je(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=wi(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){this.wrappedStage?.pointerDelegate.dispose(),Be.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new Et(r),this.wrappedStage.wrapperRef=this,this.pendingPlacement&&this.wrappedStage.pointerDelegate.arm(this.pendingPlacement),this.pendingLoadingCallbacks.forEach(c=>{this.wrappedStage.onLoading(c)}),this.pendingLoadingCallbacks=[];let n=t instanceof E?t.cameraRef:t;await this.wrappedStage.load(e,n,i);let o=null,a=!1,l=()=>{if(a=!1,!o?.length){o=null;return}let c=o;o=null,Be.entities=[...Be.entities,...c]};this.wrappedStage.onEntityAdded(c=>{if(le(c.options))return;let d=this.wrappedStage.buildEntityState(c);o||(o=[]),o.push(d),a||(a=!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)}armPlacement(e){let t=++this.placementGeneration;return this.pendingPlacement=e,this.wrappedStage?.pointerDelegate.arm(e),{cancel:()=>{this.placementGeneration===t&&this.cancelPlacement()},setPayload:i=>{this.placementGeneration!==t||!this.pendingPlacement||(this.pendingPlacement.payload=i,this.wrappedStage?.pointerDelegate.setPayload(i))},setRepresentative:i=>{this.placementGeneration!==t||!this.pendingPlacement||(this.pendingPlacement.representative=i,this.wrappedStage?.pointerDelegate.setRepresentative(i))}}}cancelPlacement(){return this.abandonPlacement(),this.wrappedStage?.pointerDelegate.cancel(),this}abandonPlacement(){this.placementGeneration++,this.pendingPlacement=null}addCamera(e,t){let i=e instanceof E?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof E?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof E?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),_.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function Kh(...s){let e=Fn(s);return new fi([...e])}export{ka as a,_e as b,ae as c,le as d,F as e,Le as f,Ae as g,al as h,cl as i,y as j,N as k,Ue as l,ee as m,te as n,me as o,fe as p,ge as q,ye as r,U as s,$e as t,E as u,Fc as v,qc as w,Ys as x,fi as y,Kh as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{proxy as c}from"valtio/vanilla";var a=["translate","rotate","scale"];function b(e){return a.includes(e)}var y={enabled:!0,translate:.25,rotate:Math.PI/12,scale:.1},t=c({enabled:!1,paused:!1,tool:"none",selectedEntityId:null,selectedEntityIds:[],hoveredEntityId:null,snap:{...y},gridVisible:!1,addTypeId:null,addTypeProps:null,pickMode:!1,flags:new Set}),l=null;function S(e){return l=e,()=>{l===e&&(l=null)}}function d(e){return!e||!l?null:l(e)}function s(e,n){if(e==null)return null;if(typeof e=="string")return e;let o=e.uuid;if(typeof o=="string")return console.warn(`${n}: received a live entity. Pass the UUID instead \u2014 storing entities in debugState makes valtio deep-proxy the scene graph.`),o;throw new TypeError(`${n} expects an entity UUID string or null, received ${typeof e}.`)}function v(){return t.paused}function T(e){t.paused=e}function m(){return t.tool}function h(e){t.tool=e}function D(){return t.enabled||t.tool!=="none"||t.pickMode}function k(e){t.pickMode=e,!e&&t.tool!=="select"&&t.tool!=="delete"&&x()}function P(){return t.pickMode}function R(){return t.selectedEntityId}function p(e){let n=s(e,"setSelectedEntityId");t.selectedEntityId!==n&&(t.selectedEntityId=n,t.selectedEntityIds=n?[n]:[])}function M(){return[...t.selectedEntityIds]}function u(e){let n=e.map((i,r)=>s(i,`setSelectedEntityIds[${r}]`)).filter(i=>i!==null);n.length===t.selectedEntityIds.length&&n.every((i,r)=>t.selectedEntityIds[r]===i)||(t.selectedEntityIds=n,t.selectedEntityId=n[0]??null)}function g(e){let n=t.selectedEntityIds,o=e.filter((i,r)=>!n.includes(i)&&e.indexOf(i)===r);o.length!==0&&u([...n,...o])}function f(e){let n=new Set(e);u(t.selectedEntityIds.filter(o=>!n.has(o)))}function w(e){let n=s(e,"toggleSelectedEntityId");n&&(t.selectedEntityIds.includes(n)?f([n]):g([n]))}function G(){return{...t.snap}}function O(e){Object.assign(t.snap,e)}function H(e){t.gridVisible=e}function A(e,n){t.addTypeId=e,t.addTypeProps=e?n??null:null}function U(){return t.hoveredEntityId}function E(e){let n=s(e,"setHoveredEntityId");t.hoveredEntityId!==n&&(t.hoveredEntityId=n)}function x(){E(null)}function F(){return d(t.selectedEntityId)}function N(){return d(t.hoveredEntityId)}function V(e){p(s(e,"setSelectedEntity"))}export{a,b,y as c,t as d,S as e,d as f,v as g,T as h,m as i,h as j,D as k,k as l,P as m,R as n,p as o,M as p,u as q,g as r,f as s,w as t,G as u,O as v,H as w,A as x,U as y,E as z,x as A,F as B,N as C,V as D};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as p}from"./chunk-7WRQ2UAN.js";import{Box3 as v,BoxGeometry as b,Color as E,Group as M,Mesh as x,MeshBasicMaterial as R,Vector3 as f}from"three";var j=.45,B=.12,g=.1;function N(r,e){return{source:r,options:e??{}}}var y=class{container;fadeOutDuration;materials=[];offset;onFrame;extent=null;display=0;from=0;to=0;elapsed=0;duration=0;targetOpacity=Number.NaN;colorKey="\0";tint=null;constructor(e,i){let n=i.options;this.fadeOutDuration=n.fadeOut??g,this.onFrame=n.onFrame;let t=p(n.offset,{x:0,y:0,z:0});this.offset=new f(t.x,t.y,t.z),this.container=new M,this.container.name="EntityRepresentative",this.container.visible=!1,e.add(this.container);let o=w(i);this.materials=o.materials,this.extent=o.extent,this.container.add(o.object),this.applyVisual()}get opacity(){return this.display}get fadeCompleted(){return this.duration<=0||this.elapsed>=this.duration-1e-8}measure(){return this.extent?this.extent.clone():null}setLook(e,i,n){let t=e?.opacity??n,o=e?.color==null?"":String(e.color);t===this.targetOpacity&&o===this.colorKey||(this.colorKey=o,this.tint=O(e?.color),this.fadeTo(t,i))}fadeTo(e,i){this.targetOpacity=e,this.from=this.display,this.to=e,this.elapsed=0,this.duration=Math.max(0,i),this.duration<=0&&(this.display=this.to,this.applyVisual())}showAt(e){this.container.position.copy(e),this.offset.lengthSq()>0&&this.container.position.add(this.offset),this.container.visible=!0}hide(){this.container.visible=!1}advance(e,i){if(this.duration<=0)this.display=this.to;else{this.elapsed+=Math.max(0,e);let t=Math.min(1,this.elapsed/this.duration);this.display=this.from+(this.to-this.from)*t}let n=this.display;this.onFrame?.({delta:e,opacity:n,setOpacity:t=>{n=t},valid:i.valid,position:i.position}),this.display=n,this.applyVisual()}dispose(){this.container.removeFromParent(),d(this.container),this.materials.length=0}applyVisual(){for(let e of this.materials){e.opacity=this.display,e.transparent=!0,e.depthWrite=!1;let i=e.userData.representativeBaseColor;e.color&&(this.tint?e.color.copy(this.tint):i&&e.color.copy(i))}}};function O(r){if(r==null)return null;try{return new E(r)}catch{return null}}function w(r){let e=T(r.source),i=typeof r.source=="function",n=V(e),t=e?A(e):null;i&&e&&S(e,t),t||(t=new x(new b(n.x,n.y,n.z),u(new R({color:16777215})))),t.position.set(0,0,0);let o=[];t.traverse(c=>{let l=c.material;if(!l)return;let h=Array.isArray(l)?l:[l];for(let m of h)o.push(m)});let a=new v().setFromObject(t),s=a.isEmpty()?n:a.getSize(new f);return{object:t,materials:o,extent:s}}function T(r){try{let e=typeof r=="function"?r():r;if(!e||typeof e.then=="function")return null;if(!e.group&&!e.mesh&&typeof e.create=="function"){let i=e.create();if(i&&typeof i.then=="function")return null}return e}catch(e){return console.warn("[zylem] entity representative: the source failed, using a box",e),null}}function V(r){let e=p(r?.options?.size,{x:1,y:1,z:1});return new f(e.x>0?e.x:1,e.y>0?e.y:1,e.z>0?e.z:1)}function A(r){let e=r.group??r.mesh;if(!e)return null;let i=e.clone(!0),n=[],t=[];e.traverse(o=>n.push(o)),i.traverse(o=>t.push(o));for(let o=0;o<n.length;o++){let a=n[o],s=t[o];a.geometry&&(s.geometry=a.geometry.clone()),a.material&&(s.material=Array.isArray(a.material)?a.material.map(c=>u(c)):u(a.material)),s.castShadow=!1,s.receiveShadow=!1}return i}function u(r){let e=r.clone();return e.transparent=!0,e.depthWrite=!1,e.color?.clone&&(e.userData.representativeBaseColor=e.color.clone()),e}function S(r,e){let i=new Set;e?.traverse(t=>{let o=t;o.geometry&&i.add(o.geometry);let a=o.material;if(a)for(let s of Array.isArray(a)?a:[a])i.add(s)});let n=r.group??r.mesh;n&&d(n,i)}function d(r,e){r.traverse(i=>{let n=i;n.geometry&&!e?.has(n.geometry)&&n.geometry.dispose();let t=n.material;if(t)for(let o of Array.isArray(t)?t:[t])e?.has(o)||o.dispose()})}export{j as a,B as b,N as c,y as d};
|
package/dist/cinematics.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { k as CutsceneEasing, V as Vec3Def, h as CutsceneScene, n as CameraShot, g as CutsceneDefinition, s as DollyPath, i as CutsceneCamera, o as CameraTrack, x as SceneTransition, y as SceneTransitionType, v as EventItem, w as AudioItem } from './cutscene-definition-C479fkei.js';
|
|
2
2
|
export { A as AudioItemSchema, q as AudioTrack, l as CameraKeyframe, c as CameraKeyframeSchema, m as CameraPoseDef, d as CameraShotSchema, j as CutsceneCameraKind, b as CutsceneCameraSchema, C as CutsceneDefinitionSchema, u as CutsceneEvent, e as CutsceneEventSchema, a as CutsceneSceneSchema, r as CutsceneTrack, f as CutsceneTrackSchema, D as DollyPathSchema, E as EventItemSchema, p as EventTrack, S as SceneTransitionSchema, t as ShotBlend } from './cutscene-definition-C479fkei.js';
|
|
3
|
-
import { f as CameraBehavior, d as CameraContext, C as CameraPose, l as ZylemCamera } from './zylem-camera-
|
|
3
|
+
import { f as CameraBehavior, d as CameraContext, C as CameraPose, l as ZylemCamera } from './zylem-camera-BA3VPFlS.js';
|
|
4
4
|
import { Z as ZylemTransitionShader } from './stage-transition-CmGpV4tc.js';
|
|
5
|
-
import { Z as ZylemStage, q as Stage } from './stage-
|
|
5
|
+
import { Z as ZylemStage, q as Stage } from './stage-CCGJh9TD.js';
|
|
6
6
|
import { g as SongDefinition } from './song-definition-rEKksP0B.js';
|
|
7
7
|
import { CutsceneStatusPayload, CutsceneViewPayload, CutsceneLoadPayload, CameraPosePayload } from '@zylem/bridge';
|
|
8
8
|
import '@sinclair/typebox';
|
|
@@ -13,10 +13,10 @@ import '@zylem/behaviors/core';
|
|
|
13
13
|
import 'three/webgpu';
|
|
14
14
|
import './base-node-idopiSw5.js';
|
|
15
15
|
import './base-node-life-cycle-BK9xebT9.js';
|
|
16
|
-
import './entity-type-map-
|
|
17
|
-
import './entity-
|
|
16
|
+
import './entity-type-map-BMaPY8cd.js';
|
|
17
|
+
import './entity-CY75JJSw.js';
|
|
18
18
|
import './vector-D3eDzvcA.js';
|
|
19
|
-
import './material-
|
|
19
|
+
import './material-D1IVeQc5.js';
|
|
20
20
|
import './collision-builder-BckxkdmA.js';
|
|
21
21
|
import './events.js';
|
|
22
22
|
import 'mitt';
|
|
@@ -24,6 +24,9 @@ import './selection-bounds-BKmSo9aG.js';
|
|
|
24
24
|
import '@zylem/behaviors/particle-emitter';
|
|
25
25
|
import 'three/addons/lines/webgpu/Line2.js';
|
|
26
26
|
import './game-interfaces-vF5sRi1n.js';
|
|
27
|
+
import './placement-session-BNQoL7Jb.js';
|
|
28
|
+
import './level-types-D10LiOcn.js';
|
|
29
|
+
import './transform-gizmo-DappLQ9w.js';
|
|
27
30
|
|
|
28
31
|
/**
|
|
29
32
|
* Pure evaluation of a cutscene at a point in time: which scene and shot are
|