@zylem/game-lib 0.9.9 → 0.9.11
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/README.md +4 -0
- package/dist/actions.d.ts +2 -2
- package/dist/api/game-lib.api.json +1150 -187
- package/dist/api/game-lib.api.md +65 -9
- package/dist/api/game-lib.d.ts +100 -11
- package/dist/api/game-lib.typedoc.json +63710 -72679
- package/dist/bake-IARN2D5W.js +1 -0
- package/dist/bridge.d.ts +3 -1
- package/dist/bridge.js +1 -1
- package/dist/catalog.js +1 -1
- package/dist/chunk-2I76JHSN.js +1 -0
- package/dist/{chunk-CI7A5N6G.js → chunk-3XIJCDII.js} +1 -1
- package/dist/{chunk-BJYXY2FB.js → chunk-DLIQ7RKB.js} +1 -1
- package/dist/{chunk-YW2GTHCV.js → chunk-HOLQZSW3.js} +1 -1
- package/dist/{chunk-3LXDHDJB.js → chunk-KGAXGWKQ.js} +1 -1
- package/dist/chunk-LUFSPEPZ.js +1 -0
- package/dist/{chunk-5NQGXW75.js → chunk-M47F6LKE.js} +1 -1
- package/dist/chunk-NA5SAMP2.js +1 -0
- package/dist/{chunk-YFXNZ2RS.js → chunk-O5N7VFYK.js} +1 -1
- package/dist/chunk-RPLJRBU3.js +1 -0
- package/dist/{chunk-JUA5KNND.js → chunk-RRYBT6NL.js} +2 -2
- package/dist/chunk-TLUGF3AS.js +1 -0
- package/dist/{chunk-273CUPEO.js → chunk-TRKPYAVB.js} +1 -1
- package/dist/{chunk-UNCP6V7I.js → chunk-VLGJAGMX.js} +1 -1
- package/dist/chunk-W6XV7CCC.js +1 -0
- package/dist/{chunk-JCGW5PIR.js → chunk-WM3NVEDX.js} +1 -1
- package/dist/{chunk-YWH5HQDT.js → chunk-X4TZ645S.js} +1 -1
- package/dist/{chunk-ICJ2E2OV.js → chunk-Y2NS4OJH.js} +1 -1
- package/dist/chunk-YETBTF6G.js +1 -0
- package/dist/cinematics.d.ts +5 -4
- package/dist/core.d.ts +8 -7
- package/dist/core.js +1 -1
- package/dist/{debug-state-JRneI6c2.d.ts → debug-state-CKrWEXUz.d.ts} +7 -1
- package/dist/debug.d.ts +2 -2
- package/dist/debug.js +1 -1
- package/dist/{entity-CY75JJSw.d.ts → entity-B8VygThO.d.ts} +7 -0
- package/dist/{entity-type-map-BMaPY8cd.d.ts → entity-type-map-CnxOtV01.d.ts} +1 -1
- package/dist/entity.d.ts +4 -4
- package/dist/entity.js +1 -1
- package/dist/{game-uQd7k6-m.d.ts → game-BqKsvmSH.d.ts} +2 -2
- package/dist/game-default-ENWXZSPB.js +1 -0
- package/dist/graphics.js +1 -1
- package/dist/nav-mesh-P7OR5WYX.js +1 -0
- package/dist/navigation-session-2rs6rHOw.d.ts +54 -0
- package/dist/navigation-worker.js +2 -0
- package/dist/navigation.d.ts +27 -0
- package/dist/navigation.js +1 -0
- package/dist/{placement-session-BNQoL7Jb.d.ts → placement-session-DfvCaGxX.d.ts} +1 -1
- package/dist/placement.d.ts +3 -3
- package/dist/placement.js +1 -1
- package/dist/public.d.ts +9 -6
- package/dist/public.js +1 -1
- package/dist/{stage-Dez16Gxm.d.ts → stage-DT8QQbGk.d.ts} +11 -14
- package/dist/web-components.d.ts +8 -7
- package/dist/web-components.js +1 -1
- package/package.json +12 -4
- package/dist/chunk-26EJFYDX.js +0 -1
- package/dist/chunk-UM5VNQPY.js +0 -1
- package/dist/chunk-VUTKEMIE.js +0 -1
- package/dist/game-default-FRKFJOJX.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as q,j as Xe}from"./chunk-2HSR5XDQ.js";import{a as Tr,b as m,c as Ue,d as kr,f as Lr,g as mi,n as fi,p as be}from"./chunk-W6XV7CCC.js";import{a as Qe,b as Yr}from"./chunk-WBQ5TNRZ.js";import{a as Ye,b as Jr,c as $e,d as en,e as tn,f as rn,g as nn,m as le}from"./chunk-D2PATZCC.js";import{a as an}from"./chunk-BH53MBAZ.js";import{l as Mr}from"./chunk-UG22Z42P.js";import{a as ln,b as cn,d as un}from"./chunk-Y5IU6IA5.js";import{b as Er,c as sn,e as Je,f as on}from"./chunk-SIRFF4DY.js";import{a as Rr,c as ve,d as pi,e as Br,f as ne,g as zr}from"./chunk-TRKPYAVB.js";import{a as K,b as Xr,c as Qr}from"./chunk-YETBTF6G.js";import{A as hi,B as Ne,b as L,d as h,e as wr,i as O,k as re,p as di,r as Sr,t as Cr,u as xr,v as C,z as Pr}from"./chunk-LUFSPEPZ.js";import{b as Ce,d as $r}from"./chunk-DLIQ7RKB.js";import{g as Kr}from"./chunk-VLGJAGMX.js";import{c as Ze,d as ui,j as x}from"./chunk-4QLJUQSJ.js";import{B as Wr,C as yi,D as qr,E as vi,a as we,k as Ir,l as Fr,m as Gr,n as Hr,o as oe,p as jr,q as Se,t as Zr,u as Nr,v as Ke,w as V,x as Ur}from"./chunk-3XIJCDII.js";import{a as gi,b as Vr,f as se,i as qe,j as Ar}from"./chunk-HOLQZSW3.js";import{c as S,d as Or,h as We,i as _r,j as g}from"./chunk-7WRQ2UAN.js";import{a as Dr,b as _}from"./chunk-AIQ6IVT5.js";import{g as ae}from"./chunk-UUOPT2N4.js";import{Vector2 as fn,RenderTarget as Go,HalfFloatType as Ho}from"three";import{WebGPURenderer as jo,RenderPipeline as Zo}from"three/webgpu";import{pass as No,renderOutput as gn,screenCoordinate as Uo,vec2 as bi,vec4 as wn,fract as yn,sin as vn,dot as bn,texture as Wo,uniform as qo}from"three/tsl";import{setConsoleFunction as Io,getConsoleFunction as Fo}from"three";var dn="THREE.Abstract function.",hn=!1,pn=!1;function mn(){if(hn)return;hn=!0;let n=Fo();Io((e,t,...i)=>{if(e==="warn"&&t===dn){pn||(pn=!0,console.warn(`${dn} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(n){n(e,t,...i);return}let r=i[0],s=e==="log"?console.log:e==="error"?console.error:console.warn;r&&r.isStackTrace&&typeof r.getError=="function"?s(r.getError(t)):s(t,...i)})}var Sn={x:0,y:0,width:1,height:1},Ko=1/20;async function cd(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var et=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 fn(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(mn(),this.renderer=new jo({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 Zo(this.renderer),r=No(e,t);this.renderScale!==1&&r.setResolutionScale(this.renderScale);let s=r;for(let l of this._postEffects)try{s=l(s,{scenePass:r,scene:e,camera:t})}catch(c){console.error("RendererManager: post-processing effect failed, skipping.",c)}i.outputColorTransform=!1;let o=gn(s),a=this._transition;if(a)try{o=wn(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($o()),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 fn;this.renderer.getDrawingBufferSize(r);let s=new Go(Math.max(1,r.x),Math.max(1,r.y),{type:Ho}),o=this.renderer.getRenderTarget();try{this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(s),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:qo(0),fromNode:gn(Wo(s.texture)),elapsed:0,snapshotTarget:s,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,Ko);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,s=this.screenResolution.x,o=this.screenResolution.y,a=Math.floor(r.x*s),l=Math.floor(r.y*o),c=Math.floor(r.width*s),u=Math.floor(r.height*o);this.renderer.setViewport(a,l,c,u),this.renderer.setScissor(a,l,c,u),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=Xo(e,i.texture),s=this.renderer.getRenderTarget();this.renderer.setRenderTarget(i),this.renderer.setScissorTest(!1),this.renderer.clear(),this.renderer.render(e,t.camera),this.renderer.setRenderTarget(s);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&&Yo(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 Xo(n,e){let t=[];return n.traverse(i=>{let r=i;!r.isMesh||!r.visible||!(Array.isArray(r.material)?r.material:[r.material]).some(o=>Qo(o,e))||(r.visible=!1,t.push(r))}),t}function Qo(n,e){return n?n.map===e:!1}function Yo(n){return n.x===0&&n.y===0&&n.width===1&&n.height===1}function $o(){let n=Uo.xy,e=yn(vn(bn(n,bi(12.9898,78.233))).mul(43758.5453)),t=yn(vn(bn(n.add(bi(13,7)),bi(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return wn(i,i,i,0)}function xe(n){return n?.category??"none"}function Pe(n){let e=xe(n);return e==="environment"||e==="pack"}function X(n){return n.isInstanced===!0||n.isBundled===!0}import{BundleGroup as Jo}from"three/webgpu";var tt=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 s=e.mesh??e.group;if(!s)return!1;let o=this.getOrCreateBundle(r);return s.matrixAutoUpdate=!0,s.userData.zylemEntityUuid=e.uuid,s.parent&&s.parent.remove(s),o.add(s),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 Jo,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as Cn,Matrix4 as Ee,Vector3 as xn,Quaternion as ea}from"three";var Me=class n{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}:${gi(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Vr(gi(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},s=t.material||{};return n.generatePackKey({geometryType:i,dimensions:{x:r.x,y:r.y,z:r.z},materialPath:s.path||null,shaderType:s.shader?"custom":"standard",colorHex:s.color?.getHex?.()||t.color?.getHex?.()||16777215})}register(e,t,i,r){let s=this.packs.get(r);s||(s=this.createPack(r,t,i));let o;return s.freeIndices.length>0?o=s.freeIndices.pop():(o=s.entities.length,o>=s.capacity&&this.growPack(s),s.entities.push(null)),s.entities[o]=e,s.entityMap.set(e.uuid,o),this.entityToPack.set(e.uuid,r),s.instancedMesh.count=Math.max(s.instancedMesh.count,o+1),s.activeIndices.push(o),s.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 s=i.activeIndices.indexOf(r);if(s!==-1){let a=i.activeIndices.pop();s<i.activeIndices.length&&(i.activeIndices[s]=a)}i.dirtyIndices.delete(r);let o=new Ee;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 Ee,i=new xn,r=new ea,s=new xn(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(Ir(c)){t.makeScale(0,0,0),o.instancedMesh.setMatrixAt(l,t),a=!0;continue}let u=o.dirtyIndices.has(l),d=!!c.body;if(!(!u&&!d)){if(!u&&d){let p=c.body;if(typeof p.isRenderSleeping=="function"&&p.isRenderSleeping())continue}this.updateInstanceMatrix(o,l,t,i,r,s,e),a=!0}}o.dirtyIndices.clear(),a&&(o.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,s,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,s);else{let u=Qe(l.body,a);r.set(u.position.x,u.position.y,u.position.z),s.set(u.rotation.x,u.rotation.y,u.rotation.z,u.rotation.w)}i.compose(r,s,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 s=r.entityMap.size;e+=s,t.push({key:i,count:s,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=n.DEFAULT_CAPACITY,s=new Cn(t,i,r);s.count=0,s.frustumCulled=!1;let o=new Ee().makeScale(0,0,0);for(let l=0;l<r;l++)s.setMatrixAt(l,o);s.instanceMatrix.needsUpdate=!0;let a={key:e,instancedMesh:s,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(s),a}growPack(e){let t=e.capacity*n.GROWTH_FACTOR,i=new Cn(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new Ee;for(let o=0;o<e.capacity;o++)e.instancedMesh.getMatrixAt(o,r),i.setMatrixAt(o,r);let s=new Ee().makeScale(0,0,0);for(let o=e.capacity;o<t;o++)i.setMatrixAt(o,s);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 it=class{bundles=new tt;instances=new Me;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=xe(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],s=Me.generateEntityPackKey(e);if(t==="pack"){let o=this.instances.register(e,i,r,s);return o<0?!1:(e.packKey=s,e.instanceId=o,e.isInstanced=!0,e.mesh&&(e.mesh.visible=!1),!0)}return t==="environment"&&this.bundles.register(e,i,r,s)?(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{Box3 as Vl,Box3Helper as Al,BoxGeometry as Ps,Color as Il,DoubleSide as Fl,EdgesGeometry as Gl,Group as Cs,LineBasicMaterial as Hl,LineSegments as jl,Mesh as Ct,MeshStandardMaterial as qi,OctahedronGeometry as Zl,Vector3 as Nl}from"three";import{DEFAULT_DRAW_SHAPE as Ul,brushCenter as Wl,brushTopology as ql,clipBrush as Kl,deleteBrushElements as Xl,frameForPlane as Ql,primitiveBrushes as Yl,sectorSizeOf as $l}from"@zylem/bridge";import{Vector3 as wi}from"three";var ta=0;function ia(n,e){if(e)return{position:n.origin.clone().add(n.direction.clone().multiplyScalar(e.distance)),normal:new wi(e.normal[0],e.normal[1],e.normal[2])};if(Math.abs(n.direction.y)<1e-6)return null;let t=(ta-n.origin.y)/n.direction.y;return t<0?null:{position:n.origin.clone().add(n.direction.clone().multiplyScalar(t)),normal:new wi(0,1,0)}}function ra(n,e){if(e.lengthSq()<1e-8)return 0;let t=e.clone().normalize();return(Math.abs(t.x)*n.x+Math.abs(t.y)*n.y+Math.abs(t.z)*n.z)/2}function Si(n,e,t){let i=ra(e,t);return i<=0?n.clone():n.clone().add(t.clone().normalize().multiplyScalar(i))}function Q(n,e,t,i){let r=ia(n,e);if(!r)return null;let{normal:s}=r,o=t.enabled?ne(r.position,t.translate):r.position,a=new wi(o.x,o.y,o.z);return{position:i?Si(a,i,s):a,normal:s}}import{Vector3 as rt}from"three";import{frameForPlane as En,pointInFrame as na}from"@zylem/bridge";var sa=.05,Ci=.001,oa=1e-9;function Y(n,e){return n.x*e.x+n.y*e.y+n.z*e.z}function aa(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function xi(n){return Math.hypot(n.x,n.y,n.z)}function A(n){return Math.abs(n)<oa?0:n}function ue(n){return{x:A(n.x),y:A(n.y),z:A(n.z)}}function Mn(n){return n===m.top||n===m.bottom?"top":n===m.side||n===m.left?"side":null}function la(n){let e=Math.abs(n.x),t=Math.abs(n.y),i=Math.abs(n.z);return t>=e-Ci&&t>=i-Ci?"top":e>=i-Ci?"side":"front"}function Dn(n){return n==="top"?"y":n==="side"?"x":"z"}function k(n,e,t,i={}){let r=xi(e)*xi(n.direction);if(r<1e-12)return null;let s=Y(e,n.direction);if(Math.abs(s)<Math.max(i.minIncidence??sa,1e-9)*r)return null;let o=(t-Y(e,n.origin))/s;return o<0&&!i.behind?null:{x:n.origin.x+n.direction.x*o,y:n.origin.y+n.direction.y*o,z:n.origin.z+n.direction.z*o}}function ca(n,e){let t=Dn(n),i={x:0,y:0,z:0};return i[t]=e[t]>0?-1:1,En(i,0)}function ua(){return En({x:0,y:1,z:0},0)}function Pi(n,e){let t=Mn(n);return t?ca(t,e):ua()}function De(n){return{normal:{...n.normal},distance:Y(n.normal,n.origin)}}function Tn(n,e,t){let i=Dn(Mn(n)??la(e)),r={x:0,y:0,z:0};return r[i]=1,{normal:r,distance:t[i]}}function P(n,e){return e>0?A(Math.round(n/e)*e):n}function I(n,e){return{x:P(n.x,e),y:P(n.y,e),z:P(n.z,e)}}function Ei(n,e,t){let i=I(n,t),r=xi(e.normal);if(r<1e-12)return i;let s=(Y(e.normal,i)-e.distance)/(r*r);return ue({x:i.x-e.normal.x*s,y:i.y-e.normal.y*s,z:i.z-e.normal.z*s})}function Mi(n,e,t){let i=na(n,I(e,t));return{u:A(i.u),v:A(i.v)}}function Pn(n,e,t){let i=new rt(n.direction.x,n.direction.y,n.direction.z),r=new rt(t.x,t.y,t.z);return i.lengthSq()<1e-24||r.lengthSq()<1e-24?null:sn({origin:new rt(n.origin.x,n.origin.y,n.origin.z),direction:i.normalize()},new rt(e.x,e.y,e.z),r.normalize())}var ce=class{constructor(e,t,i,r){this.anchor=e;this.axis=t;this.view=r;this.startValue=Pn(i,e,t),this.startValue===null&&(this.startHit=this.screenHit(i),this.sign=Y(t,r.direction)<=0?1:-1)}startValue;startHit=null;sign=1;get onScreen(){return this.startValue===null}measure(e){if(this.startValue!==null){let i=Pn(e,this.anchor,this.axis);return i===null?null:i-this.startValue}if(!this.startHit)return null;let t=this.screenHit(e);return t?Y(aa(t,this.startHit),this.view.up)*this.sign:null}screenHit(e){return k(e,this.view.direction,Y(this.view.direction,this.anchor),{behind:!0})}};var Bn=1e-6;function Di(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function zn(n,e){return{x:n.y*e.z-n.z*e.y,y:n.z*e.x-n.x*e.z,z:n.x*e.y-n.y*e.x}}function Ln(n,e){let t=Math.hypot(e.x,e.y,e.z);if(t<1e-9)return null;let i=ue({x:e.x/t,y:e.y/t,z:e.z/t});return{normal:i,distance:A(i.x*n.x+i.y*n.y+i.z*n.z)}}function da(n,e){return Math.hypot(n.x-e.x,n.y-e.y,n.z-e.z)<Bn}function kn(n,e,t){let i=Di(e,n),r=Math.hypot(i.x,i.y,i.z),s=Math.hypot(t.x,t.y,t.z);if(r<Bn||s<1e-9)return null;let o=zn(i,t);return Math.hypot(o.x,o.y,o.z)<1e-6*r*s?null:Ln(n,o)}function Rn(n,e,t){let i=Di(e,n),r=Di(t,n),s=zn(i,r),o=Math.hypot(i.x,i.y,i.z)*Math.hypot(r.x,r.y,r.z);return o<1e-12||Math.hypot(s.x,s.y,s.z)<1e-6*o?null:Ln(n,s)}var nt=class{points=[];get active(){return this.points.length>0}get placed(){return this.points}click(e,t,i){let[r,s]=this.points;if(!r)return this.points=[{...e}],null;if(this.points.some(a=>da(a,e)))return null;if(!s){if(i)return this.points.push({...e}),null;let a=kn(r,e,t);return a&&(this.points=[]),a}let o=Rn(r,s,e);return o&&(this.points=[]),o}preview(e,t){let[i,r]=this.points;return i?r?Rn(i,r,e):kn(i,e,t):null}cancel(){this.points=[]}};import{framePoint as On,orderFootprint as ha}from"@zylem/bridge";var _n=1e-6;function Vn(n){return{origin:{...n.origin},u:{...n.u},v:{...n.v},normal:{...n.normal}}}var st=class{current="idle";frame=null;step=0;start={u:0,v:0};end={u:0,v:0};height=0;lift=null;get phase(){return this.current}get activeFrame(){return this.current==="idle"?null:this.frame}get anchor(){return this.current==="idle"||!this.frame?null:On(this.frame,this.start.u,this.start.v)}begin(e,t,i){this.frame=Vn(e),this.step=i,this.start=Mi(e,t,i),this.end={...this.start},this.height=0,this.lift=null,this.current="footprint"}drag(e){if(this.current!=="footprint"||!this.frame)return;let t=De(this.frame),i=k(e,t.normal,t.distance);i&&(this.end=Mi(this.frame,i,this.step))}release(e,t){if(this.current!=="footprint"||!this.frame)return!1;let i=this.footprint();if(i.u1-i.u0<_n||i.v1-i.v0<_n)return this.cancel(),!1;let r=On(this.frame,(i.u0+i.u1)/2,(i.v0+i.v1)/2);return this.lift=new ce(r,this.frame.normal,e,t),this.height=this.initialHeight(),this.current="height",!0}raise(e){if(this.current!=="height"||!this.lift)return;let t=this.lift.measure(e);t!==null&&(this.height=P(this.initialHeight()+t,this.step))}commit(e){let t=this.state();return this.cancel(),t?.height?{kind:"primitive",frame:Vn(t.frame),footprint:t.footprint,height:t.height,shape:{...e}}:null}cancel(){this.current="idle",this.frame=null,this.lift=null,this.height=0}state(){return this.current==="idle"||!this.frame?null:{frame:this.frame,footprint:this.footprint(),height:this.current==="height"?this.height:null}}footprint(){return ha({u0:this.start.u,v0:this.start.v,u1:this.end.u,v1:this.end.v})}initialHeight(){return this.step>0?this.step:1}};import{extrudeFace as ka,moveElementsBy as Ra,moveFaces as Ba,shearFaces as za}from"@zylem/bridge";import{Raycaster as pa,Vector2 as ma,Vector3 as Gn}from"three";var fa=8,ga=10,ya=400,va=6,ba=1.5,wa=.001,ot=new Gn;function Sa(n,e){n.updateMatrixWorld();let t=n.isPerspectiveCamera===!0,i=t?n.near??.1:-1/0,r=s=>-ot.set(s.x,s.y,s.z).applyMatrix4(n.matrixWorldInverse).z;return{perspective:t,nearDepth:i,depthOf:r,project(s){let o=r(s);return t&&o<i?null:(ot.set(s.x,s.y,s.z).project(n),{x:(ot.x+1)/2*e.width,y:(1-ot.y)/2*e.height,depth:o})}}}function An(n,e){let t=Math.max(1,n.nearDepth*4),i={x:e.origin.x+e.direction.x*t,y:e.origin.y+e.direction.y*t,z:e.origin.z+e.direction.z*t},r=n.project(i);return r?{x:r.x,y:r.y}:null}function Ca(n,e){let t=n.userData.trianglePlanes;return!t||typeof e!="number"?null:t[e]??null}function xa(n,e,t){let i=t.x-e.x,r=t.y-e.y,s=i*i+r*r,o=s<1e-12?0:Math.min(1,Math.max(0,((n.x-e.x)*i+(n.y-e.y)*r)/s));return{distance:Math.hypot(e.x+i*o-n.x,e.y+r*o-n.y),t:o}}function Hn(n){return[...n].sort((e,t)=>Math.abs(e.distance-t.distance)>ba?e.distance-t.distance:e.depth-t.depth)}function Pa(n,e,t,i=ga){let r=[];for(let s of e)s.topology.vertices.forEach((o,a)=>{let l=t.project(o);if(!l)return;let c=Math.hypot(l.x-n.x,l.y-n.y);c>i||r.push({item:{brushId:s.id,index:a},distance:c,depth:l.depth,point:o})});return Hn(r)}function jn(n,e,t){return{x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t,z:n.z+(e.z-n.z)*t}}function Ea(n,e,t){if(!t.perspective)return[n,e];let i=t.nearDepth*1.001,r=t.depthOf(n),s=t.depthOf(e);if(r<i&&s<i)return null;if(r>=i&&s>=i)return[n,e];let o=jn(n,e,(i-r)/(s-r));return r<i?[o,e]:[n,o]}function Ma(n,e,t,i){if(!i)return n;let r=(1-n)*t+n*e;return Math.abs(r)<1e-12?n:n*e/r}function Da(n,e,t,i=fa){let r=[];for(let s of e){let{vertices:o,edges:a}=s.topology;a.forEach((l,c)=>{let u=Ea(o[l.vertices[0]],o[l.vertices[1]],t);if(!u)return;let d=t.project(u[0]),p=t.project(u[1]);if(!d||!p)return;let{distance:v,t:W}=xa(n,d,p);if(v>i)return;let T=jn(u[0],u[1],Ma(W,d.depth,p.depth,t.perspective));r.push({item:{brushId:s.id,index:c},distance:v,depth:t.depthOf(T),point:T})})}return Hn(r)}function Zn(n,e,t=ya,i=va){if(!n)return!1;let r=e.time-n.time;return r>=0&&r<=t?Math.hypot(e.x-n.x,e.y-n.y)<=i:!1}function Nn(n,e){return n.brushId===e.brushId&&n.kind===e.kind&&n.planes.length===e.planes.length&&n.planes.every((t,i)=>t===e.planes[i])}function F(n){return{brushId:n.brushId,kind:n.kind,planes:[...n.planes]}}function In(n){return{origin:{x:n.origin.x,y:n.origin.y,z:n.origin.z},direction:{x:n.direction.x,y:n.direction.y,z:n.direction.z}}}function Ta(n){for(let e=n;e;e=e.parent)if(!e.visible)return!1;return!0}function Fn(n){for(let e=n;e;e=e.parent){let t=e.userData.levelId;if(typeof t=="string")return t}return null}var at=class{constructor(e,t,i){this.solids=e;this.objects=t;this.view=i}raycaster=new pa;projector(){let e=this.view.camera(),t=this.view.viewport();return e&&t?Sa(e,t):null}screenOf(e){let t=this.projector();return t?An(t,In(e)):null}object(e){this.raycaster.set(e.origin,e.direction);let t=[...this.visibleMeshes(),...this.objects.values()];for(let i of this.raycaster.intersectObjects(t,!0)){if(!Ta(i.object))continue;let r=Fn(i.object);if(r)return r}return null}face(e){this.raycaster.set(e.origin,e.direction);let t=this.raycaster.intersectObjects(this.visibleMeshes(),!1)[0];if(!t)return null;let i=Fn(t.object),r=i?this.solids.get(i):void 0,s=Ca(t.object.geometry,t.faceIndex),o=s===null?void 0:r?.planes[s];return!i||s===null||!o?null:{ref:{brushId:i,kind:"face",planes:[s]},plane:o,point:{x:t.point.x,y:t.point.y,z:t.point.z}}}element(e,t){if(t==="face"){let o=this.face(e),a=o?this.solids.get(o.ref.brushId)?.topology:void 0;if(!o||!a)return null;let l=a.faces.find(c=>c.planeIndex===o.ref.planes[0]);return{ref:o.ref,point:o.point,corners:l?l.indices.map(c=>a.vertices[c]):[]}}let i=this.projector(),r=i?An(i,In(e)):null;if(!i||!r)return null;let s=[];for(let[o,a]of this.solids)a.mesh.visible&&s.push({id:o,topology:a.topology});if(t==="vertex"){for(let o of Pa(r,s,i)){let a=this.solids.get(o.item.brushId)?.topology.vertexPlanes[o.item.index];if(!(!a||!this.inSight(o.point)))return{ref:{brushId:o.item.brushId,kind:"vertex",planes:[...a]},point:o.point,corners:[o.point]}}return null}for(let o of Da(r,s,i)){let a=this.solids.get(o.item.brushId)?.topology,l=a?.edges[o.item.index];if(!(!a||!l||!this.inSight(o.point)))return{ref:{brushId:o.item.brushId,kind:"edge",planes:[...l.planes]},point:o.point,corners:[a.vertices[l.vertices[0]],a.vertices[l.vertices[1]]]}}return null}inSight(e){let t=this.view.camera();if(!t)return!0;let i=new Gn(e.x,e.y,e.z),r=i.clone().project(t);this.raycaster.setFromCamera(new ma(r.x,r.y),t);let{origin:s,direction:o}=this.raycaster.ray,a=i.sub(s).dot(o),l=this.raycaster.intersectObjects(this.visibleMeshes(),!1)[0];return!l||l.distance>=a-wa*Math.max(1,Math.abs(a))}visibleMeshes(){let e=[];for(let t of this.solids.values())t.mesh.visible&&e.push(t.mesh);return e}};var Wn=Object.freeze({x:0,y:0,z:0});function Ti(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function La(n,e){return{x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}}function Un(n,e){return n.x*e.x+n.y*e.y+n.z*e.z}function qn(n,e){let t=Un(e,e);if(t<1e-24)return n;let i=Un(n,e)/t;return ue({x:n.x-e.x*i,y:n.y-e.y*i,z:n.z-e.z*i})}function ki(n){return Math.hypot(n.x,n.y,n.z)<1e-9}function Kn(n,e){return n.x===e.x&&n.y===e.y&&n.z===e.z}function Xn(n){return Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.z)}function Te(n){let e=new Map;for(let t of n){let i=e.get(t.brushId);i?i.push(t):e.set(t.brushId,[t])}return e}function lt(n){try{return n()??void 0}catch{return}}var ct=class{constructor(e,t,i,r,s){this.faces=e;this.solids=t;this.measure=i;this.step=r;this.extrude=s,this.groups=Te(e)}distance=0;extrude;shown=null;groups;update(e,t){let i=this.measure.measure(e);if(i===null||!Number.isFinite(i))return;let r=P(i,this.step),s=t.altKey===!0;if(r===this.distance&&s===this.extrude)return;let o=r===0?null:this.build(r,s);o!==void 0&&(this.distance=r,this.extrude=s,this.shown=o)}preview(){return this.shown}finish(){return this.distance===0?null:{kind:this.extrude?"face-extrude":"face-move",faces:this.faces.map(F),distance:this.distance}}build(e,t){if(t){let r=[];for(let s of this.faces){let o=this.solids.get(s.brushId),a=o&<(()=>ka(o,s.planes[0]??-1,e));if(!a)return;r.push(a)}return{solids:new Map,added:r}}let i=new Map;for(let[r,s]of this.groups){let o=this.solids.get(r),a=o&<(()=>Ba(o,s.map(l=>l.planes[0]??-1),e));if(!a)return;i.set(r,a)}return{solids:i,added:[]}}},ut=class{constructor(e,t,i,r,s,o){this.elements=e;this.solids=t;this.plane=i;this.grabbed=r;this.snapTo=s;this.step=o;this.groups=Te(e)}delta=Wn;shown=null;groups;update(e){let t=k(e,this.plane.normal,this.plane.distance);if(!t)return;let i=this.snapped(Ti(t,this.grabbed));if(!Xn(i)||Kn(i,this.delta))return;let r=ki(i)?null:this.build(i);r!==void 0&&(this.delta=i,this.shown=r)}preview(){return this.shown}finish(){return ki(this.delta)?null:{kind:"element-move",elements:this.elements.map(F),delta:{...this.delta}}}snapped(e){let t=this.snapTo?Ti(I(La(this.snapTo,e),this.step),this.snapTo):I(e,this.step);return qn(t,this.plane.normal)}build(e){let t=new Map;for(let[i,r]of this.groups){let s=this.solids.get(i),o=s&<(()=>Ra(s,r.map(a=>({key:{kind:a.kind,planes:a.planes},delta:e}))));if(!o)return;t.set(i,o.planes)}return{solids:t,added:[]}}},dt=class{constructor(e,t,i,r,s){this.faces=e;this.solids=t;this.plane=i;this.grabbed=r;this.step=s;this.groups=Te(e)}delta=Wn;shown=null;groups;update(e){let t=k(e,this.plane.normal,this.plane.distance);if(!t)return;let i=ue(I(Ti(t,this.grabbed),this.step));if(!Xn(i)||Kn(i,this.delta))return;let r=this.slides(i)?this.build(i):null;r!==void 0&&(this.delta=i,this.shown=r)}preview(){return this.shown}finish(){return this.slides(this.delta)?{kind:"shear",faces:this.faces.map(F),delta:{...this.delta}}:null}slides(e){return!ki(qn(e,this.plane.normal))}build(e){let t=new Map;for(let[i,r]of this.groups){let s=this.solids.get(i),o=s&<(()=>za(s,r.map(a=>a.planes[0]??-1),e));if(!o)return;t.set(i,o.planes)}return{solids:t,added:[]}}};import{Euler as Oa,Quaternion as Bi,Vector3 as ke}from"three";import{brushCenter as _a,elementPositions as Va,moveElements as Aa,rotateBrush as Ia,scaleBrush as Fa,translateBrush as Ga}from"@zylem/bridge";var Ha=.001;function Qn(n){let e=n.reduce((t,i)=>({x:t.x+i.x,y:t.y+i.y,z:t.z+i.z}),{x:0,y:0,z:0});return{x:e.x/n.length,y:e.y/n.length,z:e.z/n.length}}function pt(n,e){return n.doodads.find(t=>t.id===e)?.pose??n.entities.find(t=>t.id===e)?.pose??null}function ja(n){let e=n.position??{x:0,y:0,z:0},t=n.rotation??{x:0,y:0,z:0},i=n.quaternion??new Bi().setFromEuler(new Oa(t.x,t.y,t.z));return{position:{...e},quaternion:{x:i.x,y:i.y,z:i.z,w:i.w},scale:{...n.scale??{x:1,y:1,z:1}}}}function Yn(n,e,t,i){let r={pivot:i,solids:new Map,poses:new Map,elements:[]};if((n.elementMode??"object")==="object")for(let s of n.selectedIds){let o=e.get(s);if(o){r.solids.set(s,o.planes);continue}let a=t.has(s)?pt(n.document,s):null;if(!a)continue;let l=n.document.entities.find(c=>c.id===s);r.poses.set(s,{pose:ja(a),scales:!l||l.typeId==="zone"})}else for(let s of n.elements??[]){let o=e.get(s.brushId);o&&(r.solids.set(s.brushId,o.planes),r.elements.push(s))}return r.solids.size>0||r.poses.size>0?r:null}function $n(n,e,t){let i=[];if((n.elementMode??"object")==="object")for(let r of n.selectedIds){let s=e.get(r),o=s?_a(s.planes):null;o?i.push(o):t.has(r)&&i.push(pt(n.document,r)?.position??{x:0,y:0,z:0})}else for(let r of n.elements??[]){let s=e.get(r.brushId),o=s?Va(s.planes,{kind:r.kind,planes:r.planes}):null;o&&o.length>0&&i.push(Qn(o))}return i.length>0?Qn(i):null}function Za(n){switch(n.kind){case"translate":return n.delta.x===0&&n.delta.y===0&&n.delta.z===0;case"rotate":return n.angle===0;case"scale":return n.factor.x===1&&n.factor.y===1&&n.factor.z===1}}function Na(n,e){switch(e.kind){case"translate":return Ga(n,e.delta);case"rotate":return Ia(n,e.axis,e.angle,e.pivot);case"scale":return Fa(n,e.factor,e.pivot)}}function Ua(n,e,t){let i=new ke(n.position.x,n.position.y,n.position.z),r=new Bi(n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w),s={...n.scale};switch(e.kind){case"translate":i.add(new ke(e.delta.x,e.delta.y,e.delta.z));break;case"rotate":{let o=new ke(e.pivot.x,e.pivot.y,e.pivot.z),a=new Bi().setFromAxisAngle(new ke(e.axis.x,e.axis.y,e.axis.z).normalize(),e.angle);i.sub(o).applyQuaternion(a).add(o),r.premultiply(a);break}case"scale":{let{factor:o,pivot:a}=e;i.set(a.x+(i.x-a.x)*o.x,a.y+(i.y-a.y)*o.y,a.z+(i.z-a.z)*o.z),t&&(s.x*=o.x,s.y*=o.y,s.z*=o.z);break}}return{position:{x:i.x,y:i.y,z:i.z},quaternion:{x:r.x,y:r.y,z:r.z,w:r.w},scale:s}}function Wa(n,e){let t=new Map;if(e.kind==="translate"&&n.elements.length>0){for(let[r,s]of Te(n.elements)){let o=n.solids.get(r),a=o?Aa(o,s.map(l=>({kind:l.kind,planes:l.planes})),e.delta):null;if(!a)return null;t.set(r,a.planes)}return{solids:t,poses:new Map}}for(let[r,s]of n.solids){let o=Na(s,e);if(!o)return null;t.set(r,o)}let i=new Map;for(let[r,s]of n.poses)i.set(r,Ua(s.pose,e,s.scales));return{solids:t,poses:i}}function Ri(n,e){return n===1||!(e>0)?Math.max(n,Ha):Math.max(P(n,e),e)}var ht=class{gizmo=new Je;drag=null;get root(){return this.gizmo.root}get visible(){return this.gizmo.visible}get isDragging(){return this.drag!==null}place(e,t){if(!this.drag){if(!e||!t){this.gizmo.hide();return}this.gizmo.setMode(e),this.gizmo.show(new ke(t.x,t.y,t.z)),this.gizmo.root.updateMatrixWorld(!0)}}update(e){this.gizmo.update(e),this.gizmo.root.updateMatrixWorld(!0)}hover(e){if(this.drag)return!0;let t=e?this.gizmo.pick(e):null;return this.gizmo.setHighlight(t),t!==null}begin(e,t,i){if(this.drag||!this.gizmo.visible)return!1;let r=this.gizmo.pick(e);return!r||!this.gizmo.beginDrag(r,e,t)?!1:(this.drag={target:i,transform:null,preview:null},!0)}move(e,t,i){let r=this.drag;if(!r)return null;let s=this.gizmo.updateDrag(e,t),o=s?this.snapped(s,r.target.pivot,i):null;if(!o)return r.preview;let a=null;try{a=Wa(r.target,o)}catch{a=null}return a&&(r.transform=o,r.preview=a),r.preview}end(){let e=this.drag;this.cancel();let t=e?.transform;if(!e||!t||Za(t))return null;let{target:i}=e;if(t.kind==="translate"&&i.elements.length>0)return{kind:"element-move",elements:i.elements.map(F),delta:{...t.delta}};let r=[...i.solids.keys(),...i.poses.keys()];return r.length>0?{kind:"transform",ids:r,transform:t}:null}cancel(){this.drag=null,this.gizmo.endDrag()}dispose(){this.cancel(),this.gizmo.dispose()}snapped(e,t,i){let r=C(),s=r.enabled&&!i;switch(e.kind){case"translate":{let o={x:e.offset.x,y:e.offset.y,z:e.offset.z};return{kind:"translate",delta:I(o,s?r.translate:0)}}case"rotate":{let o=P(e.angle,s?r.rotate:0);return Number.isFinite(o)?{kind:"rotate",axis:{x:e.axis.x,y:e.axis.y,z:e.axis.z},angle:o,pivot:{...t}}:null}case"scale":{let o=s?r.scale:0,a={x:Ri(e.factor.x,o),y:Ri(e.factor.y,o),z:Ri(e.factor.z,o)};return Number.isFinite(a.x+a.y+a.z)?{kind:"scale",factor:a,pivot:{...t}}:null}}}};import{BufferGeometry as qa,DoubleSide as ts,Float32BufferAttribute as Ka,Group as $,Line as is,LineBasicMaterial as zi,LineSegments as Li,Mesh as rs,MeshBasicMaterial as Xa,MeshStandardMaterial as Qa,Points as ns,PointsMaterial as ss}from"three";import{compileBrush as Ya,elementPositions as $a,framePoint as mt,primitiveBrushes as Ja}from"@zylem/bridge";var ft=6737151,Re=16756768,os=13157044,Jn=3752010,Be=15,el=4,tl=7,es=250,il=[{color:16724787,axis:"x"},{color:3394662,axis:"y"},{color:3377407,axis:"z"}];function as(n){let e=typeof window>"u"?1:window.devicePixelRatio||1;return n*e}function rl(n){if(!Array.isArray(n)){n.dispose();return}for(let e of n)e.dispose()}function Oi(n){n.traverse(e=>{let t=e;t.geometry?.dispose(),t.material&&rl(t.material)})}var G=class{constructor(e){this.parent=e}current=null;set(e){this.current!==e&&(this.current&&(this.parent.remove(this.current),Oi(this.current)),this.current=e,e&&this.parent.add(e))}clear(){this.set(null)}};function H(n){let e=new qa;return e.setAttribute("position",new Ka(n,3)),e}function gt(n){return n.flatMap(e=>[e.x,e.y,e.z])}function _i(n,e){return new zi({color:n,depthTest:!e,transparent:e})}function nl(n,e){let t=new is(H(gt([...n,n[0]])),_i(e,!0));return t.renderOrder=Be+1,t}function Vi(n,e,t){if(n.length<3)return null;let i=H(gt(n)),r=[];for(let a=1;a<n.length-1;a+=1)r.push(0,a,a+1);i.setIndex(r);let s=new rs(i,new Xa({color:e,transparent:!0,opacity:t,side:ts,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-4}));s.renderOrder=Be;let o=new $;return o.add(s,nl(n,e)),o}function ze(n,e){let t=new Li(H(n.flatMap(([i,r])=>[i.x,i.y,i.z,r.x,r.y,r.z])),_i(e,!0));return t.renderOrder=Be+1,t.frustumCulled=!1,t}function Ai(n,e,t=tl){let i=new ns(H(gt(n)),new ss({color:e,size:as(t),sizeAttenuation:!1,depthTest:!1,transparent:!0}));return i.renderOrder=Be+2,i.frustumCulled=!1,i}function Ii(n){return n.edges.map(e=>[n.vertices[e.vertices[0]],n.vertices[e.vertices[1]]])}function ls(n,e){let t=[],i=[];for(let o of n){for(let[a,l]of Ii(o))t.push(a.x,a.y,a.z,l.x,l.y,l.z);e&&i.push(...gt(o.vertices))}if(t.length===0)return null;let r=new $;r.name="level-element-wire";let s=new Li(H(t),_i(Jn,!1));if(s.frustumCulled=!1,r.add(s),i.length>0){let o=new ns(H(i),new ss({color:Jn,size:as(el),sizeAttenuation:!1}));o.frustumCulled=!1,r.add(o)}return r}function sl(n){let e=[];for(let t of n.faces)t.indices.forEach((i,r)=>{let s=n.vertices[i],o=n.vertices[t.indices[(r+1)%t.indices.length]];e.push(s.x,s.y,s.z,o.x,o.y,o.z)});return e}function Fi(n,e=os,t=.35){let i=new $;for(let r of n){let s=Ya(r);if(!s)continue;let o=new rs(K(s),new Qa({color:e,transparent:!0,opacity:t,depthWrite:!1,side:ts}));o.renderOrder=Be-1;let a=new Li(H(sl(s)),new zi({color:e,transparent:!0,opacity:.9}));i.add(o,a)}return i.children.length>0?i:null}function ol(n,e,t=os){let i=[mt(n,e.u0,e.v0),mt(n,e.u1,e.v0),mt(n,e.u1,e.v1),mt(n,e.u0,e.v1)];return Vi(i,t,.25)}function cs(n,e){let t=new $,i=ol(n.frame,n.footprint);if(i&&t.add(i),n.height){let r=Ja(e.shape,n.frame,n.footprint,n.height,e),s=r?Fi(r):null;s&&t.add(s)}return t}function yt(n){let e=new $;for(let t of il){let i={x:n.x,y:n.y,z:n.z},r={x:n.x,y:n.y,z:n.z};i[t.axis]-=es,r[t.axis]+=es;let s=new is(H([i.x,i.y,i.z,r.x,r.y,r.z]),new zi({color:t.color,depthTest:!1}));s.frustumCulled=!1,s.renderOrder=20,e.add(s)}return e}function us(n){let[e]=n;if(!e)return null;let t=new $;t.add(Ai(n,Re));let i=[];for(let r=1;r<n.length;r+=1)i.push([n[r-1],n[r]]);return i.length>0&&t.add(ze(i,Re)),t.add(yt(e)),t}function ds(n,e,t,i){return n==="face"?Vi(e,t,i):n==="edge"&&e.length===2?ze([[e[0],e[1]]],t):n==="vertex"&&e.length>0?Ai(e,t):null}function hs(n,e){let t=new $,i=[],r=[];for(let s of n){let o=e(s.brushId),a=o?$a(o,{kind:s.kind,planes:s.planes}):null;if(a)if(s.kind==="face"){let l=Vi(a,Re,.35);l&&t.add(l)}else s.kind==="edge"&&a.length===2?i.push([a[0],a[1]]):s.kind==="vertex"&&a[0]&&r.push(a[0])}return i.length>0&&t.add(ze(i,Re)),r.length>0&&t.add(Ai(r,Re)),t.children.length>0?t:null}import{compileBrush as al,sectorKey as ll,sectorOf as cl}from"@zylem/bridge";import{compileBrush as nh}from"@zylem/bridge";function ps(n){let e=new Float32Array(n.vertices.length*3);return n.vertices.forEach((t,i)=>{e[i*3]=t.x,e[i*3+1]=t.y,e[i*3+2]=t.z}),e}function ms(n,e){let t=new Map;for(let i of n){let r=al(i.planes),s=r?cl(i.planes,e):null;if(!r||!s)continue;let o=ll(s),a=t.get(o);a?a.push(r):t.set(o,[r])}return[...t].map(([i,r])=>({key:i,geometry:Xr(r),hulls:r.map(ps)}))}import{BufferGeometry as ul,CanvasTexture as dl,Float32BufferAttribute as hl,Group as pl,LineBasicMaterial as ml,LineSegments as fl,SRGBColorSpace as gl,Sprite as yl,SpriteMaterial as vl}from"three";import{sectorBounds as ys,sectorKey as bt,sectorOf as Hi,sectorSizeOf as ji,sectorTint as bl}from"@zylem/bridge";var wl="level-sector-overlay",Sl=7113983,Cl=.55,de=.01,vt=1,fs=128,xl=256,Pl=.9,El=.35,Ml=.25,gs=.04;function vs(n,e){let t=e.hiddenSectors;if(!t||t.length===0)return!1;let i=Hi(n,ji(e.document));return i!==null&&t.includes(bt(i))}function Zi(n,e){if(!e.showSectorTint)return null;let t=Hi(n,ji(e.document));return t?bl(t):null}function Dl(n,e){let t=new Map;for(let i of n.document.solids){let r=Hi(i.planes,e);r&&t.set(bt(r),r)}return t}function Tl(n){let e={minX:0,maxX:0,minZ:0,maxZ:0},t=!0;for(let i of n){if(t){e.minX=e.maxX=i.x,e.minZ=e.maxZ=i.z,t=!1;continue}e.minX=Math.min(e.minX,i.x),e.maxX=Math.max(e.maxX,i.x),e.minZ=Math.min(e.minZ,i.z),e.maxZ=Math.max(e.maxZ,i.z)}return{minX:e.minX-vt,maxX:e.maxX+vt,minZ:e.minZ-vt,maxZ:e.maxZ+vt}}function kl(n,e){let t=[],i=n.minX*e,r=(n.maxX+1)*e,s=n.minZ*e,o=(n.maxZ+1)*e;for(let a=n.minX;a<=n.maxX+1;a+=1)t.push(a*e,de,s,a*e,de,o);for(let a=n.minZ;a<=n.maxZ+1;a+=1)t.push(i,de,a*e,r,de,a*e);return t}function Rl(n,e){let t=[];for(let i of n){let{min:r,max:s}=ys(i,e),o=de;t.push(r.x,o,r.z,s.x,o,r.z),t.push(s.x,o,r.z,s.x,o,s.z),t.push(s.x,o,s.z,r.x,o,s.z),t.push(r.x,o,s.z,r.x,o,r.z)}return t}function Bl(n){let e=new ul;e.setAttribute("position",new hl(n,3));let t=new fl(e,new ml({color:Sl,transparent:!0,opacity:Cl,depthWrite:!1}));return t.frustumCulled=!1,t}var Gi=new Map;function zl(n){if(Gi.has(n))return Gi.get(n)??null;let e=typeof document>"u"?null:document.createElement("canvas"),t=e?.getContext("2d")??null,i=null;return e&&t&&(e.width=256,e.height=64,t.font="600 40px system-ui, sans-serif",t.textAlign="left",t.textBaseline="middle",t.fillStyle="#c5d2ff",t.fillText(n,8,32),i=new dl(e),i.colorSpace=gl),Gi.set(n,i),i}function Ll(n,e,t){let i=bt(n),r=zl(i);if(!r)return null;let s=new yl(new vl({map:r,transparent:!0,opacity:t?El:Pl,depthTest:!1,depthWrite:!1})),o=e*Ml,{min:a}=ys(n,e);return s.name=`sector-label:${i}`,s.scale.set(o,o/4,1),s.position.set(a.x+e*gs+o/2,de,a.z+e*gs+o/8),s.renderOrder=5,s}function*Ol(n){for(let e=n.minX;e<=n.maxX;e+=1)for(let t=n.minZ;t<=n.maxZ;t+=1)yield{x:e,z:t}}function bs(n){let e=ji(n.document),t=Dl(n,e),i=Tl(t.values()),r=i.maxX-i.minX+1,s=i.maxZ-i.minZ+1,o=r>fs||s>fs,a=new pl;a.name=wl,a.add(Bl(o?Rl(t.values(),e):kl(i,e)));let l=new Set(n.hiddenSectors??[]),c=r*s>xl?t.values():Ol(i);for(let u of c){let d=Ll(u,e,l.has(bt(u)));d&&a.add(d)}return a}import{Group as _l,Mesh as ws}from"three";import{compileBrush as Ss}from"@zylem/bridge";var wt=class{constructor(e,t){this.scene=t;this.slot=new G(e)}current=null;posed=new Set;slot;get value(){return this.current}show(e){this.current=e?{solids:e.solids??new Map,added:e.added??[],poses:e.poses??new Map,split:e.split??new Map}:null,this.apply()}apply(){let e=this.current;for(let[s,o]of this.scene.solids){let a=e!==null&&(e.solids.has(s)||e.split.has(s));o.mesh.visible=!a,o.guides&&(o.guides.visible=!a)}let t=this.scene.selection();if(t&&(t.visible=!e||e.solids.size===0&&e.added.length===0),this.pose(e?.poses??null),!e){this.slot.clear();return}let i=new _l;for(let[s,o]of e.solids){let a=Ss(o),l=this.scene.solids.get(s)?.planes??o;a&&i.add(new ws(K(a),this.scene.material(s,l)))}for(let s of e.split.values())s.forEach((o,a)=>{let l=Ss(o);l&&i.add(new ws(K(l),this.scene.half(a)))});let r=e.added.length>0?Fi(e.added):null;r&&i.add(r),this.slot.set(i)}forget(){this.current=null,this.posed.clear(),this.slot.clear()}pose(e){for(let t of this.posed){let i=this.scene.objects.get(t);i&&!e?.has(t)&&this.scene.restore(t,i)}if(this.posed.clear(),!!e)for(let[t,i]of e){let r=this.scene.objects.get(t);r&&(r.position.set(i.position.x,i.position.y,i.position.z),r.quaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w),r.scale.set(i.scale.x,i.scale.y,i.scale.z),this.posed.add(t))}}};var Jl=13157044,ec=14998992,tc=["#5aa9ff","#ff9a5a"],ic=4,Es=null;function _h(){return Es}function Ni(n){Es=n}function J(n){return{origin:{x:n.origin.x,y:n.origin.y,z:n.origin.z},direction:{x:n.direction.x,y:n.direction.y,z:n.direction.z}}}function Wi(n,e){let t=n.size;return{x:t?.x??e.x,y:t?.y??e.y,z:t?.z??e.z}}function xs(n){let e=Math.hypot(n.x,n.y,n.z)||1;return{x:n.x/e,y:n.y/e,z:n.z/e}}function rc(n){let e=n.clone(!0);return e.traverse(t=>{let i=t;if(i.geometry&&(i.geometry=i.geometry.clone()),!i.material)return;let s=(Array.isArray(i.material)?i.material:[i.material]).map(o=>o.clone());i.material=Array.isArray(i.material)?s:s[0]}),e}function nc(n,e){let t=q(n);if(t)try{let r=t.create({position:{x:0,y:0,z:0},props:e});if(r&&typeof r.then!="function"){let s=r.group??r.mesh;if(s)return rc(s)}}catch{}let i=Wi(e,{x:1,y:1,z:1});return new Ct(new Ps(i.x,i.y,i.z),new qi({color:13157044}))}function Ui(n,e){let t=e.position??{x:0,y:0,z:0};n.position.set(t.x,t.y,t.z),e.quaternion?n.quaternion.set(e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w):e.rotation?n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z):n.quaternion.identity();let i=e.scale??{x:1,y:1,z:1};n.scale.set(i.x,i.y,i.z)}function St(n,e=null){let t=new qi({color:e??(n?ec:Jl),side:Fl,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});return e&&n&&t.color.lerp(new Il(16777215),.35),t}function he(n,e,t,i){return{id:n,...e?{elements:e}:{},...t?{additive:!0}:{},...i?{ungroup:!0}:{}}}function sc(n){return`${n.brushId}:${n.kind}:${n.planes.join(",")}`}var xt=class{constructor(e){this.host=e;this.root.name="level-preview",this.tools.name="level-tools",this.tools.add(this.gizmo.root),this.picker=new at(this.solids,this.objects,{camera:()=>e.camera(),viewport:()=>e.viewport()}),this.preview=new wt(this.tools,{solids:this.solids,objects:this.objects,selection:()=>this.selectionView,material:(t,i)=>St(this.isObjectSelected(t),this.sectorTint(i)),half:t=>St(!1,tc[t%2]),restore:(t,i)=>{let r=this.payload?pt(this.payload.document,t):null;r&&Ui(i,r)}})}root=new Cs;tools=new Cs;hoverSlot=new G(this.tools);ghostSlot=new G(this.tools);guideSlot=new G(this.tools);mounted=!1;generation=0;mode="edit";payload=null;solids=new Map;objects=new Map;selectionView=null;picker;preview;drawTool=new st;clipTool=new nt;clipCursor=null;gizmo=new ht;gizmoPivot=null;held=null;lastClick=null;hoverRay=null;hoverKey=null;bodyHandles=[];zoneIds=[];get isActive(){return this.payload!==null}get isEditing(){return this.payload!==null&&this.mode==="edit"}get hasGesture(){return this.drawTool.phase!=="idle"||this.clipTool.active||this.gizmo.isDragging||this.held!==null&&this.held.kind!=="press"}get drawPlane(){let e=this.drawTool.activeFrame,t=this.drawTool.anchor;return e&&t?{frame:e,focus:t}:null}tick(){if(this.payload){if(!this.mounted){if(!this.host.getScene())return;this.rebuild()}this.syncGizmo()}}sync(e){let t=this.elementMode();this.mode="edit",this.payload=e,Ni(e.document),(this.held?.kind==="drag"||this.held?.kind==="gizmo")&&this.elementMode()!==t&&this.cancelHeld(),this.rebuild()}play(e){this.cancelGesture(),this.mode="play",this.payload={document:e,hiddenLayers:[],selectedIds:this.payload?.selectedIds??[],activeLayer:this.payload?.activeLayer??"solid",placement:null},Ni(e),this.rebuild()}close(){this.generation+=1,this.cancelGesture(),this.payload=null,Ni(null),this.teardownOwned(),this.clearTools(),this.unmount()}dispose(){this.close(),this.gizmo.dispose()}cancelGesture(){this.cancelHeld(),this.drawTool.cancel(),this.clipTool.cancel(),this.clipCursor=null,this.ghostSlot.clear(),this.guideSlot.clear(),this.setHover(null),this.preview.show(null)}pointerDown(e,t={}){if(!this.isEditing)return!1;if(this.cancelHeld(),this.preview.value&&!this.clipTool.active&&this.preview.show(null),this.drawTool.phase==="height")return this.commitDraw(),this.held={kind:"press"},!0;switch(O()){case"select":return this.pressSelect(e,t);case"shear":return this.pressShear(e,t);case"brush":return this.pressDraw(e);case"clip":return this.pressClip(e,t);case"translate":case"rotate":case"scale":return this.pressTransform(e,t);case"delete":return this.pressDelete(e),!0;case"add":return this.placeArmed(e),this.held={kind:"press"},!0;default:return!1}}pointerMove(e,t={}){let i=this.held;if(!(!i||!this.isEditing)){if(i.kind==="draw"){this.drawTool.drag(J(e)),this.showDraw();return}if(i.kind==="drag"){if(!i.drag||!i.moved&&!this.leftPress(i.from,e))return;i.moved=!0,i.drag.update(J(e),t);let r=i.drag.preview();this.preview.show(r?{solids:r.solids,added:r.added}:null);return}if(i.kind==="gizmo"){let r=this.host.camera();if(!r)return;let s=this.gizmo.move(e,r,t.altKey===!0);this.preview.show(s?{solids:s.solids,poses:s.poses}:null)}}}pointerHover(e){if(!this.isEditing){this.setHover(null);return}if(this.held)return;if(this.hoverRay={origin:e.origin.clone(),direction:e.direction.clone()},this.drawTool.phase==="height"){this.drawTool.raise(J(e)),this.showDraw();return}let t=O();if(t==="brush"||t==="clip"){this.setHover(null);let i=this.surfacePoint(e);t==="clip"&&this.clipTool.active?(this.guideSlot.clear(),this.showClip(i)):this.guideSlot.set(i?yt(i):null);return}if(this.guideSlot.clear(),L(t)&&this.gizmo.hover(e)){this.setHover(null);return}if(t==="select"||t==="delete"||L(t)){this.hoverIn(e,this.elementMode());return}if(t==="shear"){this.hoverIn(e,"face");return}this.setHover(null)}pointerUp(e){let t=this.held;if(this.held=null,!!t){if(t.kind==="draw"){if(this.drawTool.phase!=="footprint")return;let i=J(e);this.drawTool.drag(i),this.drawTool.release(i,this.viewBasis()),this.showDraw();return}if(t.kind==="drag"){let i=t.moved?t.drag?.finish()??null:null;if(i){this.host.publishGesture(i);return}this.preview.show(null),this.host.publishSelect(t.click);return}if(t.kind==="gizmo"){let i=this.gizmo.end();i?this.host.publishGesture(i):this.preview.show(null)}}}elementMode(){return this.payload?.elementMode??"object"}pressSelect(e,t){let i=t.shiftKey===!0;this.held={kind:"press"};let r=this.elementMode();if(r==="object"){let o=this.picker.object(e),a=o?this.registerClick(e,t):!1;return this.host.publishSelect(he(o,void 0,i,a)),!0}let s=this.picker.element(e,r);return s?(this.pressElement(e,s,r,t),!0):(this.host.publishSelect(he(null,void 0,i,!1)),!0)}pressElement(e,t,i,r){let s=this.registerClick(e,r),o=he(t.ref.brushId,[t.ref],r.shiftKey===!0,s),a=i==="face"?this.faceDrag(e,t,r):this.elementDrag(t);this.hold(e,a,o)}pressShear(e,t){let i=t.shiftKey===!0,r=this.picker.face(e);if(!r)return this.host.publishSelect(he(null,void 0,i,!1)),this.held={kind:"press"},!0;let s=this.registerClick(e,t),o=this.dragSet(r.ref),a=new dt(o,this.startPlanes(o),r.plane,r.point,this.snapStep()),l=this.elementMode()==="face"?[r.ref]:void 0;return this.hold(e,a,he(r.ref.brushId,l,i,s)),!0}pressDelete(e){this.held={kind:"press"};let t=this.elementMode();if(t==="object"){let o=this.picker.object(e);o&&this.host.publishGesture({kind:"delete",id:o});return}let i=this.picker.element(e,t);if(!i)return;let r=this.solids.get(i.ref.brushId);if(!(r?Xl(r.planes,[{kind:i.ref.kind,planes:i.ref.planes}]):null)){this.host.publishNotice("That would not leave a solid.");return}this.host.publishGesture({kind:"element-delete",elements:[F(i.ref)]})}pressDraw(e){let t=this.drawStart(e);return t?(this.drawTool.begin(t.frame,t.point,this.snapStep()),this.held={kind:"draw"},this.guideSlot.clear(),this.showDraw(),!0):(this.held={kind:"press"},!0)}pressClip(e,t){this.held={kind:"press"};let i=this.clipTargets();if(i.length===0)return this.host.publishNotice("Select the solids to clip first."),!0;let r=this.surfacePoint(e);if(!r)return!0;this.guideSlot.clear();let s=this.clipTool.click(r,this.host.viewDirection(),t.shiftKey===!0);return s?(this.clipCursor=null,this.ghostSlot.clear(),this.host.publishGesture({kind:"clip",brushIds:i,plane:s}),!0):(this.showClip(r),!0)}pressTransform(e,t){let i=this.host.camera(),r=this.payload,s=i&&r&&this.gizmoPivot?Yn(r,this.solids,this.objects,this.gizmoPivot):null;if(i&&s&&this.gizmo.begin(e,i,s))return this.held={kind:"gizmo"},this.setHover(null),!0;let o=this.elementMode();if(o==="object"){let l=this.picker.object(e);if(!l)return!1;let c=this.registerClick(e,t);return this.host.publishSelect(he(l,void 0,t.shiftKey===!0,c)),this.held={kind:"press"},!0}let a=this.picker.element(e,o);return a?(this.pressElement(e,a,o,t),!0):!1}hold(e,t,i){this.held={kind:"drag",drag:t,click:i,from:this.picker.screenOf(e),moved:!1},this.setHover(null)}registerClick(e,t){let i=this.picker.screenOf(e),r={time:t.timeStamp??performance.now(),x:i?.x??0,y:i?.y??0},s=Zn(this.lastClick,r);return this.lastClick=s?null:r,s}leftPress(e,t){if(!e)return!0;let i=this.picker.screenOf(t);return!i||Math.hypot(i.x-e.x,i.y-e.y)>=ic}dragSet(e){let t=this.payload?.elements??[];return t.some(i=>Nn(i,e))?t.filter(i=>i.kind===e.kind&&this.solids.has(i.brushId)):[e]}startPlanes(e){let t=new Map;for(let i of e){let r=this.solids.get(i.brushId);r&&t.set(i.brushId,r.planes)}return t}faceDrag(e,t,i){let r=this.solids.get(t.ref.brushId)?.planes[t.ref.planes[0]??-1];if(!r)return null;let s=new ce(t.point,xs(r.normal),J(e),this.viewBasis()),o=this.dragSet(t.ref);return new ct(o,this.startPlanes(o),s,this.snapStep(),i.altKey===!0)}elementDrag(e){let t=this.dragSet(e.ref),i=Tn(this.host.cameraId(),this.host.viewDirection(),e.point),r=t.length===1&&e.ref.kind==="vertex"?e.corners[0]??null:null;return new ut(t,this.startPlanes(t),i,e.point,r,this.snapStep())}drawStart(e){let t=this.picker.face(e);if(t)return{frame:Ql(t.plane.normal,t.plane.distance),point:t.point};let i=Pi(this.host.cameraId(),this.host.viewDirection()),r=De(i),s=k(J(e),r.normal,r.distance);return s?{frame:i,point:s}:null}surfacePoint(e){let t=this.snapStep(),i=this.picker.face(e);if(i)return Ei(i.point,i.plane,t);let r=De(Pi(this.host.cameraId(),this.host.viewDirection())),s=k(J(e),r.normal,r.distance);return s?Ei(s,r,t):null}drawShape(){return{...this.payload?.drawShape??Ul}}commitDraw(){let e=this.drawTool.commit(this.drawShape()),t=e?.shape;if(e&&t&&Yl(t.shape,e.frame,e.footprint,e.height,t)){this.host.publishGesture(e);return}this.ghostSlot.clear()}showDraw(){let e=this.drawTool.state();this.ghostSlot.set(e?cs(e,this.drawShape()):null)}clipTargets(){let e=this.payload;if(!e)return[];let t=new Set(e.document.solids.map(r=>r.id)),i=new Set;for(let r of e.selectedIds)t.has(r)&&i.add(r);for(let r of e.elements??[])t.has(r.brushId)&&i.add(r.brushId);return[...i]}showClip(e){this.clipCursor=e;let t=this.clipTool.placed;this.ghostSlot.set(us(e?[...t,e]:t));let i=e&&t.length>0?this.clipTool.preview(e,this.host.viewDirection()):null,r=new Map;if(i)for(let s of this.clipTargets()){let o=this.solids.get(s),a=o?Kl(o.planes,i):[];a.length>1&&r.set(s,a)}this.preview.show(r.size>0?{split:r}:null)}hoverIn(e,t){if(t==="object"){let r=this.picker.object(e);this.setHover(r?`object:${r}`:null,()=>r?this.objectOutline(r):null);return}let i=this.picker.element(e,t);this.setHover(i?sc(i.ref):null,()=>i?ds(i.ref.kind,i.corners,ft,.2):null)}setHover(e,t){e!==this.hoverKey&&(this.hoverKey=e,this.hoverSlot.set(e&&t?t():null))}objectOutline(e){let t=this.solids.get(e);if(t)return ze(Ii(t.topology),ft);let i=this.objects.get(e);if(!i)return null;let r=new Vl().setFromObject(i);return r.isEmpty()?null:new Al(r,ft)}isObjectSelected(e){return this.elementMode()==="object"&&(this.payload?.selectedIds.includes(e)??!1)}sectorTint(e){return this.payload?Zi(e,this.payload):null}syncGizmo(){let e=O();if(this.gizmo.place(this.isEditing&&L(e)?e:null,this.gizmoPivot),!this.gizmo.visible)return;let t=this.host.camera();t&&this.gizmo.update(t)}viewBasis(){let e=this.host.viewDirection(),t=this.host.camera();if(t){t.updateMatrixWorld();let s=new Nl().setFromMatrixColumn(t.matrixWorld,1).normalize();return{direction:e,up:{x:s.x,y:s.y,z:s.z}}}let i={x:-e.x*e.y,y:1-e.y*e.y,z:-e.z*e.y},r=Math.hypot(i.x,i.y,i.z)>1e-6?xs(i):{x:0,y:0,z:-1};return{direction:e,up:r}}rebuild(){let e=++this.generation;this.teardownOwned();let t=this.payload;!t||!this.ensureRoot()||(this.buildVisuals(),this.root.updateMatrixWorld(!0),this.gizmoPivot=this.isEditing?$n(t,this.solids,this.objects):null,this.refreshTools(),this.mode==="play"&&(this.spawnSectors(t.document),this.spawnZones(t.document,e).catch(i=>{console.error("Level triggers failed to spawn",i)})))}refreshTools(){if(!this.isEditing){this.clearTools();return}!this.held&&!this.gizmo.isDragging?this.preview.forget():this.preview.apply(),this.ghostSlot.clear(),this.setHover(null),this.drawTool.phase!=="idle"?this.showDraw():this.clipTool.active?this.showClip(this.clipCursor):this.hoverRay&&!this.held&&this.pointerHover(this.hoverRay),this.syncGizmo()}spawnSectors(e){for(let t of ms(e.solids,$l(e))){let i=new Ct(t.geometry,St(!1));if(i.name=`level-sector:${t.key}`,this.root.add(i),t.hulls.length===0)continue;let r=this.host.spawnHulls(t.hulls);r!==null&&this.bodyHandles.push(r)}}buildVisuals(){let e=this.payload;if(!e)return;let t=this.mode==="edit",i=new Set(t?e.hiddenLayers:[]),r=t?this.elementMode():"object";if(t&&!i.has("solid"))for(let s of e.document.solids){if(vs(s.planes,e))continue;let o=ql(s.planes);if(!o)continue;let a=this.isObjectSelected(s.id),l=new Ct(K(o),St(a,Zi(s.planes,e)));l.userData.levelId=s.id,this.root.add(l);let c=a?Wl(s.planes):null,u=c?yt(c):null;u&&this.root.add(u),this.solids.set(s.id,{planes:s.planes,topology:o,mesh:l,guides:u})}if(t){let s=bs(e);s&&this.root.add(s)}if(t&&r!=="object"){let s=[...this.solids.values()].map(a=>a.topology),o=ls(s,r==="vertex");o&&this.root.add(o),this.selectionView=hs(e.elements??[],a=>this.solids.get(a)?.planes),this.selectionView&&this.root.add(this.selectionView)}if(!i.has("doodad"))for(let s of e.document.doodads){let o=nc(s.typeId,s.props);Ui(o,s.pose),o.userData.levelId=s.id,this.root.add(o),this.objects.set(s.id,o)}if(!i.has("entity"))for(let s of e.document.entities){let o=s.typeId==="zone"?this.triggerOutline(s.props):new Ct(new Zl(.3),new qi({color:14904020}));Ui(o,s.pose),o.userData.levelId=s.id,this.root.add(o),this.objects.set(s.id,o)}}triggerOutline(e){let t=Wi(e,{x:2,y:2,z:2});return new jl(new Gl(new Ps(t.x,t.y,t.z)),new Hl({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:Wi(i.props,{x:2,y:2,z:2})});if(t!==this.generation){r&&this.host.detach(r);return}r&&this.zoneIds.push(r)}}placeArmed(e){let t=this.payload?.placement;if(!t)return;let i=Q(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})}cancelHeld(){let e=this.held;this.held=null,this.gizmo.isDragging&&this.gizmo.cancel(),(e?.kind==="drag"||e?.kind==="gizmo")&&this.preview.show(null),e?.kind==="draw"&&(this.drawTool.cancel(),this.ghostSlot.clear())}gridStep(){let e=C().translate;return e>0?e:1}snapStep(){let e=C();return e.enabled&&e.translate>0?e.translate:0}ensureRoot(){let e=this.host.getScene();return e?(this.tools.parent!==this.root&&this.root.add(this.tools),this.mounted||(e.add(this.root),this.mounted=!0),!0):!1}clearTools(){this.setHover(null),this.ghostSlot.clear(),this.guideSlot.clear(),this.preview.forget(),this.gizmo.place(null,null)}teardownOwned(){for(let e of this.zoneIds)this.host.detach(e);this.zoneIds=[];for(let e of this.bodyHandles)this.host.despawnHulls(e);this.bodyHandles=[],this.solids.clear(),this.objects.clear(),this.selectionView=null;for(let e of[...this.root.children])e!==this.tools&&(this.root.remove(e),Oi(e))}unmount(){this.mounted&&(this.host.getScene()?.remove(this.root),this.mounted=!1)}};var Pt=!1,R={},Ms=0,Ds=0,Le=null;function Ts(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ki(){return Pt?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(Pt=!0),Pt)}function Ah(n){Pt=n,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=n)}function Xi(n){Ki()&&(Le=n,Ds=Ts())}function Qi(){if(!Ki()||Le===null)return;let n=Ts()-Ds;R[Le]=(R[Le]??0)+n,Le=null}function ks(){if(!Ki()||(Ms++,Ms%60!==0))return;let n=Object.values(R).reduce((t,i)=>t+(i??0),0),e=Object.keys(R).sort((t,i)=>(R[i]??0)-(R[t]??0)).map(t=>{let i=R[t]??0,r=n>0?(i/n*100).toFixed(1):"0.0";return`${t}=${i.toFixed(2)}ms (${r}%)`});console.info(`[ZylemStage profile] avg over 60 frames (${n.toFixed(2)}ms/frame): ${e.join(", ")}`);for(let t of Object.keys(R))R[t]=0}function B(n,e){Xi(n);try{return e()}finally{Qi()}}var f={FirstPerson:"first-person",ThirdPerson:"third-person",SecondPerson:"second-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};function Yi(n){switch(n){case f.Isometric:case f.TopDown:case f.Flat2D:case f.Fixed2D:return"orthographic";default:return"perspective"}}import{Vector3 as oc,Quaternion as ac,MathUtils as $i}from"three";function Et(){return{position:new oc(0,0,10),rotation:new ac,fov:75,zoom:1,near:.1,far:1e3}}function ee(n){return{position:n.position.clone(),rotation:n.rotation.clone(),fov:n.fov,zoom:n.zoom,near:n.near,far:n.far,lookAt:n.lookAt?.clone()}}function Rs(n,e){let t=ee(n);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 Bs(n,e,t,i){let r=1-Math.pow(1-$i.clamp(t,0,1),i*60),s=ee(n);return s.position.lerp(e.position,r),s.rotation.slerp(e.rotation,r),e.fov!=null&&s.fov!=null&&(s.fov=$i.lerp(s.fov,e.fov,r)),e.zoom!=null&&s.zoom!=null&&(s.zoom=$i.lerp(s.zoom,e.zoom,r)),e.near!=null&&(s.near=e.near),e.far!=null&&(s.far=e.far),e.lookAt?s.lookAt?s.lookAt.lerp(e.lookAt,r):s.lookAt=e.lookAt.clone():s.lookAt=void 0,s}var Mt=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=Et();_finalPose=Et();_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):Et(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=ee(t);for(let r=this.actions.length-1;r>=0;r--){let s=this.actions[r],o=s.update(e);t=Rs(t,o),s.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=Bs(this._finalPose,t,this.damping,e.dt):(this._finalPose=ee(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?ee(this._desiredPose):null,finalPose:this._finalPose?ee(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 j,Quaternion as Dt}from"three";var lc={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},pe=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={...lc,...r},this.initialPosition=t?g(t,S):void 0,this.initialLookAt=i?g(i,S):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 Dt,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new j(0,0,0)}:{position:new j(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new Dt,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new j(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new j(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new Dt,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([d,p])=>this.getTrailedPosition(d,p.position,e.time)),r=new j;for(let d of i)r.add(d);r.divideScalar(i.length);let s=0;for(let d of i){let p=r.distanceTo(d);p>s&&(s=p)}let o=Math.max(s*this.opts.paddingFactor,this.opts.minDistance),a=new j(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=a.length(),c=l>0?a.clone().normalize():new j(0,.5,1).normalize(),u=r.clone().add(c.multiplyScalar(o));if(l>0){let d=this.opts.height/l;u.y=r.y+o*d}return{position:u,rotation:new Dt,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}getTrailedPosition(e,t,i){let r=this.opts.trailDelay;if(r<=0)return t;let s=this._trailBuffers.get(e);s||(s=[],this._trailBuffers.set(e,s)),s.push({time:i,pos:t.clone()});let o=i-r-.05;for(;s.length>1&&s[0].time<o;)s.shift();s.length>this.opts.trailBufferSize&&s.splice(0,s.length-this.opts.trailBufferSize);let a=i-r;if(s[0].time>=a)return s[0].pos.clone();for(let l=1;l<s.length;l++){let c=s[l-1],u=s[l];if(c.time<=a&&a<=u.time){let d=u.time-c.time,p=d>1e-6?(a-c.time)/d:0;return new j().lerpVectors(c.pos,u.pos,p)}}return s[s.length-1].pos.clone()}};import{Vector3 as zs,Quaternion as cc}from"three";var Ls={position:{x:0,y:0,z:10},zoom:10},me=class{id="fixed-2d";projection="orthographic";defaults={damping:1};opts;constructor(e){this.opts={...Ls,...e,position:g(e?.position,Ls.position)}}getBasePose(e){return{position:new zs(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new cc,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new zs(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as Ji,Quaternion as er,Euler as Vs,MathUtils as E}from"three";var uc={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},Oe=class{id="first-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new er;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...uc,...r},this.initialPosition=t?g(t,S):void 0,this.initialLookAt=i?g(i,S):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=E.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=E.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 Ji(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new Ji(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=E.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=E.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new er().setFromEuler(new Vs(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=Os.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let s=Math.atan2(-r.x,-r.z),o=Math.asin(E.clamp(r.y,-1,1)),a=dc.setFromEuler(_s.set(o,s,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(a,E.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 E.lerp(this._currentFov,this._targetFov,E.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=Os.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(E.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=_s.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=E.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},Os=new Ji,dc=new er,_s=new Vs;import{Quaternion as hc,Vector3 as tr}from"three";var pc={distance:10,zoom:10,targetKey:"primary"},As=new tr(1,1,1).normalize(),_e=class{id="isometric";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...pc,...r},this.initialPosition=t?g(t):void 0,this.initialLookAt=i?g(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(As,this.opts.distance);return this.pose(r,i)}staticPose(){return this.initialPosition?this.pose(this.initialPosition.clone(),this.initialLookAt?.clone()??new tr(0,0,0)):this.pose(As.clone().multiplyScalar(this.opts.distance),new tr(0,0,0))}pose(e,t){return{position:e,rotation:new hc,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as mc,Vector3 as Tt}from"three";var fc={height:10,zoom:10,targetKey:"primary"},Ve=class{id="top-down";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...fc,...r},this.initialPosition=t?g(t):void 0,this.initialLookAt=i?g(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 Tt(i.x,i.y+this.opts.height,i.z),i)}staticPose(){if(this.initialPosition){let e=this.initialLookAt?.clone()??new Tt(this.initialPosition.x,this.initialPosition.y-this.opts.height,this.initialPosition.z);return this.pose(this.initialPosition.clone(),e)}return this.pose(new Tt(0,this.opts.height,0),new Tt(0,0,0))}pose(e,t){return{position:e,rotation:new mc,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as Is,Vector3 as kt}from"three";var gc={anchorKey:"anchor",subjectKey:"primary",eyeHeight:1.7,fov:75},ir=new kt,Ae=class{id="second-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...gc,...r},this.initialPosition=t?g(t):void 0,this.initialLookAt=i?g(i):void 0}getBasePose(e){let t=e.targets[this.opts.anchorKey];if(!t)return this.staticPose();let i=new kt(t.position.x,t.position.y+this.opts.eyeHeight,t.position.z),r=e.targets[this.opts.subjectKey],s=r?r.position.clone():i.clone().add(this.anchorForward(t.rotation));return{position:i,rotation:new Is,fov:this.opts.fov,near:.1,far:1e3,lookAt:s}}staticPose(){let e=this.initialPosition?.clone()??new kt(0,this.opts.eyeHeight,0),t=this.initialLookAt?.clone()??e.clone().add(new kt(0,0,-1));return{position:e,rotation:new Is,fov:this.opts.fov,near:.1,far:1e3,lookAt:t}}anchorForward(e){return ir.set(0,0,-1),e&&ir.applyQuaternion(e),ir.clone()}};function te(n,e){switch(n){case"third-person":return new pe(e);case"first-person":return new Oe(e);case"second-person":return new Ae(e);case"isometric":return new _e(e);case"top-down":return new Ve(e);case"flat-2d":return new me(e);case"fixed-2d":return new me(e);default:return new pe(e)}}import{Vector2 as Pc,Vector3 as y,OrthographicCamera as nr,PerspectiveCamera as zt}from"three";import{PerspectiveCamera as rr,Vector3 as vc,OrthographicCamera as Ie,RenderTarget as bc,LinearFilter as Fs}from"three";import{Vector3 as Rt}from"three";import{OrbitControls as yc}from"three/addons/controls/OrbitControls.js";var Bt=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new Rt;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 Rt().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=Er(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 yc(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 Rt),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.maxPolarAngle=Math.max(e.maxPolarAngle,Math.PI),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 Rt;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 z=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...Sn};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 vc(0,0,0));let s=te(e);this.pipeline=new Mt(s)}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 Bt(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 et(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 rr&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof Ie){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 bc(e,t,{minFilter:Fs,magFilter:Fs}),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 Ie))return;this.frustumSize=e;let s=this.screenResolution.x/Math.max(this.screenResolution.y,1);r.zoom=1,r.left=e*s/-2,r.right=e*s/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===f.Flat2D||this._perspective===f.Fixed2D)&&(this.frustumSize=e.z),this.camera.position.set(e.x,e.y,e.z)}rotate(e,t,i){this.camera.rotateX(e),this.camera.rotateY(t),this.camera.rotateZ(i)}getDomElement(){if(this._rendererManager)return this._rendererManager.getDomElement();throw new Error("ZylemCamera: No renderer manager available. Call setup() first.")}getRendererManager(){return this._rendererManager}setRendererManager(e){this._rendererManager=e}get renderer(){return this._rendererManager?.renderer}get composer(){return this._rendererManager?.postProcessing}setPixelRatio(e){this._rendererManager?.setPixelRatio(e)}buildContext(e){let t={};for(let i=0;i<this.targets.length;i++){let r=this.targets[i],s=i===0?"primary":`target_${i}`;r.group&&(t[s]={position:r.group.position,rotation:r.group.quaternion})}return{dt:e,time:this._elapsedTime,viewport:{width:this.screenResolution.x,height:this.screenResolution.y,aspect:this.screenResolution.x/this.screenResolution.y},targets:t}}commitPose(e){if(this.camera.position.copy(e.position),e.lookAt){let t=e.lookAt.x-e.position.x,i=e.lookAt.y-e.position.y,r=e.lookAt.z-e.position.z,s=Math.hypot(t,i,r);s>1e-8&&Math.abs(i)/s>.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 rr&&(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 Ie){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??Yi(e))}ensureProjection(e){if((this.camera instanceof Ie?"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 s=this.camera.parent;s&&(s.add(r),s.remove(this.camera)),this.camera=r,this.orbitController?.rebindCamera(r),this._rendererManager?.rebindPostProcessingCamera(r)}createCameraForPerspective(e){return Yi(this._perspective)==="orthographic"?this.createOrthographicCamera(e):this.createPerspectiveCamera(e)}createPerspectiveCamera(e){return new rr(75,e,.1,1e3)}createOrthographicCamera(e){return new Ie(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3)}};import{OrthographicCamera as wc,PerspectiveCamera as Sc,Vector3 as Gs}from"three";var Cc=4;function Hs(n,e){if(n instanceof Sc){let t=Math.max(n.zoom,1e-6),i=2*Math.tan(n.fov*Math.PI/360)*Math.max(e,.01)/t,r=n.aspect>0?n.aspect:1;return{width:i*r,height:i}}if(n instanceof wc){let t=Math.max(n.zoom,1e-6);return{width:(n.right-n.left)/t,height:(n.top-n.bottom)/t}}return{width:1,height:1}}function js(n,e){let t=(n.top-n.bottom)/2/Math.max(n.zoom,1e-6);return 2*Math.atan(t/Math.max(e,.01))*(180/Math.PI)}function xc(n){return Math.max(n.max.x-n.min.x,n.max.y-n.min.y,n.max.z-n.min.z)}function Zs(n,e){let t=Cc*Math.max(e.width,e.height);return n.filter(i=>{if(i.isEmpty())return!1;let r=xc(i);return Number.isFinite(r)&&r<=t})}function Ns(n,e,t,i,r,s){let o=r.width/2,a=r.height/2,l=new Gs;for(let u of i){let d=[u.min.x,u.max.x],p=[u.min.y,u.max.y],v=[u.min.z,u.max.z];for(let W of d)for(let T of p)for(let je of v)l.set(W,T,je).sub(n),o=Math.max(o,Math.abs(l.dot(e))),a=Math.max(a,Math.abs(l.dot(t)))}let c=Math.max(s,1e-6);return Math.max(a*2,o*2/c)}function Us(n,e,t,i){if(t.length===0)return i;let r=1/0,s=-1/0,o=new Gs;for(let l of t){let c=[l.min.x,l.max.x],u=[l.min.y,l.max.y],d=[l.min.z,l.max.z];for(let p of c)for(let v of u)for(let W of d){o.set(p,v,W).sub(n);let T=o.dot(e);r=Math.min(r,T),s=Math.max(s,T)}}if(!Number.isFinite(r)||!Number.isFinite(s))return i;let a=Math.max((s-r)*.05,1);return{near:r-a,far:Math.max(s+a,r-a+1)}}var Ws=1e4;function Z(n,e,t,i,r=!1){let s=t.clone().normalize();return{id:n,perspective:e,lockRotation:!0,screenSpacePan:!0,orthographic:!0,...r?{near:-Ws,far:Ws}:{},position:(o,a)=>o.clone().addScaledVector(s,a),up:()=>i.clone()}}var fe=new y(0,1,0),Ec=new y(0,0,-1),Mc=new y(0,0,1),sr=[Z(m.left,f.Fixed2D,new y(-1,0,0),fe),Z(m.side,f.Fixed2D,new y(1,0,0),fe),Z(m.top,f.TopDown,new y(0,1,0),Ec),Z(m.bottom,f.TopDown,new y(0,-1,0),Mc),Z(m.isoLeftTop,f.Isometric,new y(-1,1,1),fe,!0),Z(m.isometric,f.Isometric,new y(1,1,1),fe,!0),Z(m.isoLeftBottom,f.Isometric,new y(-1,-1,1),fe,!0),Z(m.isoRightBottom,f.Isometric,new y(1,-1,1),fe,!0),{id:m.perspective,perspective:f.ThirdPerson,lockRotation:!0,screenSpacePan:!0,orthographic:!1,position:(n,e,t)=>t.distanceTo(n)>.5?t.clone():n.clone().add(new y(0,e*.5,e)),up:n=>n.clone()},{id:m.free,perspective:f.ThirdPerson,lockRotation:!1,screenSpacePan:!1,orthographic:!1,fullPolarRange:!0,position:(n,e,t)=>t.distanceTo(n)>.5?t.clone():n.clone().add(new y(0,e*.5,e)),up:n=>n.clone()}];function or(n){let e=new y;n.getWorldDirection(e);let i=new y().sub(n.position).dot(e),r=i>1?i:12;return{lookAt:n.position.clone().add(e.multiplyScalar(r)),distance:r}}var Lt=class{cameras=new Map;_activeCameras=[];_editorCameras=new Map;_lockedEditorIds=new Set;_screenSpacePanIds=new Set;_framedEditorViews=new Set;_freePoseCaptured=!1;_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(m.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[s,o]of this.cameras.entries())if(o===e){t=s;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=kr(this),Ue()&&await this.ensureEditorCameras()}ensureEditorCameras(){return this._editorCamerasPromise?this._editorCamerasPromise:this._editorCameras.size>0?Promise.resolve():(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(),this._freePoseCaptured=!1}activateCameraById(e){if(e===Tr){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 Pc(window.innerWidth,window.innerHeight),t=new z(f.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._freePoseCaptured=!1,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=or(e.camera),i=this._rendererManager.screenResolution.clone(),r=Math.max(t.distance,4);this.isEditorCamera(e)||(this._rememberedGameCamera=e);for(let s of sr){let o=new z(s.perspective,i,r);o._skipDebugOrbit=!0;let a=s.position(t.lookAt,t.distance,e.camera.position),l=s.up(e.camera.up);o.camera.up.copy(l),o.camera.position.copy(a),o.camera.lookAt(t.lookAt),(o.camera instanceof nr||o.camera instanceof zt)&&(o.camera.near=s.near??.1,o.camera.far=s.far??2e3,o.camera.updateProjectionMatrix()),this.addCamera(o,s.id),this._editorCameras.set(s.id,o),s.lockRotation&&this._lockedEditorIds.add(s.id),s.screenSpacePan&&this._screenSpacePanIds.add(s.id),o.setRendererManager(this._rendererManager),await o.setup(this._sceneRef,this._rendererManager),s.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),e===m.free&&!this._freePoseCaptured&&this.copyFreeFromGame()&&(this._freePoseCaptured=!0),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===m.free&&i.allowFullOrbit(),i.armEditorOrbit(this._lockedEditorIds.has(t),this._screenSpacePanIds.has(t))):i.disarmEditorOrbit()}isOrthographicEditorView(e){return sr.some(t=>t.id===e&&t.orthographic)}copyFreeFromGame(){let e=this._editorCameras.get(m.free),t=this.gameCameraToRestore();if(!e||!t)return!1;let i=t.camera;i.updateMatrixWorld(!0);let r=or(i);return e.camera.up.copy(i.up),(i instanceof zt||i instanceof nr)&&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 zt&&(e instanceof zt?(r.fov=e.fov,r.zoom=e.zoom,r.near=e.near,r.far=e.far):e instanceof nr&&(r.fov=js(e,i),r.zoom=1),r.updateProjectionMatrix())}frameOrthographicView(e,t){let i=sr.find(Ao=>Ao.id===e),r=this.gameCameraToRestore();if(!i||!r)return!1;let s=r.camera;s.updateMatrixWorld(!0);let o=or(s),a=Hs(s,o.distance),l=Zs(this._entityBounds?.()??[],a),c=Math.max(o.distance,4),u=i.position(o.lookAt,c,s.position);t.camera.up.copy(i.up(s.up)),t.camera.position.copy(u),t.camera.lookAt(o.lookAt),t.camera.updateMatrixWorld(!0);let d=new y().setFromMatrixColumn(t.camera.matrixWorld,0),p=new y().setFromMatrixColumn(t.camera.matrixWorld,1),v=new y;t.camera.getWorldDirection(v);let W=t.screenResolution.x/Math.max(t.screenResolution.y,1),T=Ns(o.lookAt,d,p,l,a,W),je=Us(t.camera.position,v,l,{near:i.near??.1,far:i.far??2e3});return t.applyOrthographicFrame(T,je.near,je.far),t.replaceOrbitPose(u,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 M=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,te(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function pm(n){let e=_r(n.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;(n.perspective==="fixed-2d"||n.perspective==="isometric"||n.perspective==="top-down")&&(t=n.zoom||10);let i=new z(n.perspective||"third-person",e,t);n.name&&(i.name=n.name);let r=g(n.position,S),s=g(n.target,S);i.move(r),i.camera.lookAt(s);let o=n.perspective||"third-person";if(o==="fixed-2d"||o==="flat-2d"?i.applyPerspective(o,te(o,{zoom:t})):o==="isometric"||o==="top-down"?i.applyPerspective(o,te(o,{zoom:t,initialPosition:r.clone(),initialLookAt:s.clone()})):i.applyPerspective(o,te(o,{initialPosition:r.clone(),initialLookAt:s.clone()})),n.viewport&&(i.viewport={...n.viewport}),n.useOrbitalControls&&(i._useOrbitalControls=!0),n.skipDebugOrbit&&(i._skipDebugOrbit=!0),n.damping!=null&&(i.pipeline.damping=n.damping),n.behaviors)for(let[a,l]of Object.entries(n.behaviors))i.pipeline.addBehavior(a,l);if(n.renderToTexture){let{width:a=512,height:l=512}=n.renderToTexture;i.createRenderTarget(a,l)}return new M(i)}import{Vector3 as Dc}from"three";function N(n){return!!n&&typeof n=="object"&&typeof n.create=="function"}function Fe(n){return!!n&&typeof n.then=="function"}function ar(n){return!!n&&typeof n=="object"&&n instanceof M}function qs(n){return!n||typeof n!="object"||N(n)||ar(n)||Fe(n)||typeof n.then=="function"?!1:n.constructor===Object||n.constructor?.name==="Object"}function Ks(n){return n?!!(N(n)||typeof n=="function"||Fe(n)):!1}var Tc="/three/basis/";function _t(n){return{...n,ktx2TranscoderPath:n?.ktx2TranscoderPath??Tc}}var Ot=class{constructor(e,t,i,r,s,o,a=60,l={},c=!0,u=[]){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=s;this.variables=o;this.physicsRate=a;this.assetLoaders=l;this.defaultLighting=c;this.postProcessingEffects=u}};function kc(){return new Ot({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},Ye,null,null,new Dc(0,0,0),{},60,{},!0)}function Xs(n=[]){let e=kc(),t={},i=[],r=[],s=[];for(let l of n)ar(l)?s.push(l):N(l)?i.push(l):Ks(l)&&!N(l)?r.push(l):qs(l)&&(t={...t,...l});let o=new Ot(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=s.length>0?s[0]:void 0;return{config:o,entities:i,asyncEntities:r,camera:a,cameras:s}}function Sm(n){return{...n}}var Rc=Symbol("vessel"),Ge=class extends we{static type=Rc;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=Bc();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function Bc(...n){let e=new Ge;return n.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{getZylemBridge as li}from"@zylem/bridge";import{Color as Oo,Vector3 as _o}from"three";import{createSimulation as zc}from"@zylem/behaviors/core";function lr(n){return typeof n?.handlePostCollision=="function"&&typeof n?.handleIntersectionEvent=="function"}function Lc(n,e){return n<e?`${n}|${e}`:`${e}|${n}`}var Vt=class n{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 zc({gravity:[i.x,i.y,i.z],fixedTimestep:1/t,initialCapacity:4096});return new n(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 Ce)&&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 Yr(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 s=Lc(i,r),o=this.livePairs.get(s);o||(o={uuidA:i<r?i:r,uuidB:i<r?r:i,contactCount:0,intersectionCount:0},this.livePairs.set(s,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(s)}}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 s=r;if(!lr(s))continue;s.handlePostCollision({entity:s,delta:e})||this.collisionBehaviorMap.delete(i)}}processPendingRemovals(){if(this._removalMap.size!==0){for(let[,e]of this._removalMap)this.destroyEntity(e);this._removalMap.clear()}}removeEntityFromTracking(e){this.collisionMap.delete(e),this._removalMap.delete(e),this.pruneActiveCollisionPairs(e)}pruneActiveCollisionPairs(e){for(let[t,i]of this.activeCollisionPairs)(i.uuidA===e||i.uuidB===e)&&this.activeCollisionPairs.delete(t);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,s]of i){let o=this.collisionMap.get(s.uuidA),a=this.collisionMap.get(s.uuidB);this.activeCollisionPairs.has(r)||this.dispatchCollisionPhase(s,"enter",t),(this.entityHasCollisionPhaseListener(o,"stay")||this.entityHasCollisionPhaseListener(a,"stay"))&&this.dispatchCollisionPhase(s,"stay",t),s.hasIntersection&&this.dispatchIntersectionDelegates(s,e)}this.updatePostCollisionBehaviors(e),this.activeCollisionPairs=i}dispatchCollisionPhase(e,t,i){let r={phase:t,nowMs:i},s=this.collisionMap.get(e.uuidA),o=this.collisionMap.get(e.uuidB);s&&o&&s._collision(o,ui.globals,r);let a=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);a&&l&&l._collision(a,ui.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&lr(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let s=this.collisionMap.get(e.uuidA),o=this.collisionMap.get(e.uuidB);s&&o&&lr(o)&&(o.handleIntersectionEvent({entity:o,other:s,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 Oc,Color as Qs,AmbientLight as _c,DirectionalLight as Vc,Vector3 as At,GridHelper as Ac,Texture as Ic,SRGBColorSpace as Fc}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 Oc,o=i.backgroundColor instanceof Qs?i.backgroundColor:new Qs(i.backgroundColor);r.background=o,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&se.loadTexture(i.backgroundImage,{colorSpace:Fc}).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(!qe(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 Ic&&(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 _c(16777215,1);e.add(t);let i=new Vc(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 At(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(X(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Gc(e);i&&i.attachToScene(this.scene);let r=e.options.position??new At(0,0,0);if(e.physicsAttached&&e.body)try{let s=e.body.translation();r=new At(s.x,s.y,s.z)}catch{r=e.options.position??new At(0,0,0)}this.add(t,r),Se(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new Ac(1e3,100);this.scene.add(i)}};function Gc(n){return n.constructor.type===$r?n:null}var Ft=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 Hc}from"three";var Ys=new Hc;function $s(n){let e=n._childrenMap,t=n._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval||i.isInstanced||i.isBundled||i.skipRenderPoseSync)continue;let r=i.body,s=i.group??i.mesh,o=s?Qe(r,t?.interpolationAlpha??0):null;s&&o&&s.position.set(o.position.x,o.position.y,o.position.z),!i.controlledRotation&&s&&o&&(Ys.set(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w),s.setRotationFromQuaternion(Ys))}}import{nanoid as Ku}from"nanoid";import{Box3 as $t,BufferAttribute as Co,BufferGeometry as Bu,LineBasicMaterial as zu,LineSegments as Lu,Raycaster as Ou,Vector2 as _u,Vector3 as Jt}from"three";import{subscribe as Vu}from"valtio/vanilla";import{nanoid as xo}from"nanoid";import{getZylemBridge as Po}from"@zylem/bridge";import{StageBodyKind as Au}from"@zylem/behaviors/core";import{Box3 as jc,BoxGeometry as Js,Color as Zc,EdgesGeometry as eo,Group as Nc,LineBasicMaterial as Uc,LineSegments as Wc,Mesh as qc,MeshBasicMaterial as Kc,Vector3 as to}from"three";var Gt=class{scene;container;fillMesh;edgeLines;currentColor=new Zc(65280);bbox=new jc;size=new to;center=new to;constructor(e){this.scene=e;let t=new Js(1,1,1);this.fillMesh=new qc(t,new Kc({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new eo(t);this.edgeLines=new Wc(i,new Uc({color:this.currentColor,linewidth:1})),this.container=new Nc,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 Js(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 eo(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 Xc,BoxGeometry as Qc,Group as Yc,Mesh as $c,MeshBasicMaterial as Jc,Vector3 as io}from"three";var eu={x:0,y:0,z:0},tu=7128319,iu=.35;function ru(){return new Jc({color:tu,transparent:!0,opacity:iu,depthWrite:!1})}function nu(n){let e=n.size;return new io(e?.x??1,e?.y??1,e?.z??1)}function su(n,e){try{let t=n.create({position:eu,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 "${n.id}" factory failed, falling back to a box`,t),null}}function ou(n,e){n.traverse(t=>{let i=t;i.isMesh&&(i.material=e,i.castShadow=!1,i.receiveShadow=!1)})}var Ht=class{scene;container;builtFor=null;builtProps=null;material=null;extent=null;bounds=new Xc;constructor(e){this.scene=e,this.container=new Yc,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=q(e),s={...r?.defaultProps??{},...t??{}},a=(r?su(r,s):null)??new $c(new Qc(...nu(s).toArray()));a.position.set(0,0,0),this.material=ru(),ou(a,this.material),this.container.add(a),this.bounds.setFromObject(a),this.extent=this.bounds.isEmpty()?null:this.bounds.getSize(new io)}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 uu,Quaternion as Ut,Vector3 as D}from"three";import{nanoid as du}from"nanoid";import{Vector3 as ge}from"three";var ur=.95,au=16,He=new ge,lu=new ge,ro=new ge,cr=new ge;function no(n){return n?n.isPerspectiveCamera===!0||n.isOrthographicCamera===!0:!1}function jt(n,e,t=ur){return He.copy(n).project(e),Math.abs(He.x)<=t&&Math.abs(He.y)<=t&&He.z>=-1&&He.z<=1}function so(n){let e=0,t=1;for(let i=0;i<au;i+=1){let r=(e+t)/2;n(r)?e=r:t=r}return e}function oo(n,e,t,i=ur){if(!no(t))return e.clone();let r=t;if(jt(e,r,i)||!jt(n,r,i))return e.clone();let s=so(o=>jt(lu.copy(n).lerp(e,o),r,i));return n.clone().lerp(e,s)}function ao(n,e,t,i,r=ur){if(!no(i)||t.x<=1&&t.y<=1&&t.z<=1||n.isEmpty())return t.clone();let s=i;ro.copy(e);let o=new ge(1,1,1),a=c=>(o.set(1+(t.x-1)*c,1+(t.y-1)*c,1+(t.z-1)*c),cu(n,ro,o,s,r));if(a(1))return t.clone();let l=so(a);return new ge(1+(t.x-1)*l,1+(t.y-1)*l,1+(t.z-1)*l)}function cu(n,e,t,i,r){for(let s=0;s<8;s+=1)if(cr.set(s&1?n.max.x:n.min.x,s&2?n.max.y:n.min.y,s&4?n.max.z:n.min.z),cr.sub(e).multiply(t).add(e),!jt(cr,i,r))return!1;return!0}var hu={translate:"Move",rotate:"Rotate",scale:"Scale"};function dr(n){let e=typeof n?.getPose=="function"?n.getPose():null,t=n?.group??n?.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},s=typeof n?.getScale=="function"?n.getScale():{x:1,y:1,z:1};return{position:new D(i.x,i.y,i.z),quaternion:new Ut(r.x,r.y,r.z,r.w),scale:new D(s.x,s.y,s.z)}}function lo(n){let e=pi(n.quaternion);return{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:e,quaternion:{x:n.quaternion.x,y:n.quaternion.y,z:n.quaternion.z,w:n.quaternion.w},scale:{x:n.scale.x,y:n.scale.y,z:n.scale.z}}}function pu(n,e){return n.position.distanceToSquared(e.position)>1e-5*1e-5||Math.abs(n.quaternion.dot(e.quaternion))<1-1e-5||n.scale.distanceToSquared(e.scale)>1e-5*1e-5}function Zt(n,e){(e.position||e.quaternion)&&n.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&&n.setScale?.(e.scale.x,e.scale.y,e.scale.z)}function mu(n){let e=n?.group??n?.mesh;if(!e?.isObject3D)return null;let t=new uu().setFromObject(e);return t.isEmpty()?null:t}var hr=.02,pr=50;function fu(n){return new D(mr(n.x,hr,pr),mr(n.y,hr,pr),mr(n.z,hr,pr))}function mr(n,e,t){return Math.min(Math.max(n,e),t)}var fr=new Ut,gu=new D,Nt=class{gizmo=new Je;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 s of h.selectedEntityIds){let o=this.context.resolveEntity(s);o&&r.push({uuid:s,entity:o,start:dr(o),startBounds:this.mode==="scale"?mu(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 s=this.gizmo.updateDrag(e,r);if(!s)return;let o=C(),a=o.enabled&&!t;switch(s.kind){case"translate":this.applyTranslate(i,s.offset,a?o.translate:0,r);break;case"rotate":this.applyRotate(i,s.axis,s.angle,a?o.rotate:0);break;case"scale":this.applyScale(i,s.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=dr(i.entity);pu(i.start,r)&&(e.mode==="scale"&&mi(i.entity),t.push({uuid:i.uuid,before:lo(i.start),after:lo(r)}))}t.length&&be({opId:du(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 s=gu.copy(e.pivotStart).add(t),o=oo(e.pivotStart,s,r),a=i>0?ne(o,i):o,l=new D(a.x-e.pivotStart.x,a.y-e.pivotStart.y,a.z-e.pivotStart.z);for(let c of e.entries)Zt(c.entity,{position:c.start.position.clone().add(l)})}applyRotate(e,t,i,r){let s=e.axis;for(let o of e.entries){fr.setFromAxisAngle(t,i);let a=fr.clone().multiply(o.start.quaternion),l=a;if(r>0&&(s==="x"||s==="y"||s==="z")){let u=pi(a);u[s]=Br(u[s],r);let d=ve(u);l=new Ut(d.x,d.y,d.z,d.w)}let c=o.start.position.clone().sub(e.pivotStart).applyQuaternion(fr).add(e.pivotStart);Zt(o.entity,{position:c,quaternion:l})}}applyScale(e,t,i,r){for(let s of e.entries){let o=s.startBounds?ao(s.startBounds,s.start.position,t,r):t,a=fu(o),l=new D(s.start.scale.x*a.x,s.start.scale.y*a.y,s.start.scale.z*a.z),c=i>0?zr(l,i):l;Zt(s.entity,{scale:new D(c.x,c.y,c.z)})}}describeOperation(e){let t=hu[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 D,i=0;for(let r of e){let s=this.context.resolveEntity(r);s&&(t.add(dr(s).position),i++)}return i?t.divideScalar(i):null}};function co(n,e,t){for(let i of n.entries){let r=e==="undo"?i.before:i.after;if(!r)continue;let s=t(i.uuid);if(!s)continue;let o=r.quaternion??(r.rotation?ve(r.rotation):void 0);Zt(s,{position:r.position?new D(r.position.x,r.position.y,r.position.z):void 0,quaternion:o?new Ut(o.x,o.y,o.z,o.w):void 0,scale:r.scale?new D(r.scale.x,r.scale.y,r.scale.z):void 0}),r.scale&&mi(s)}}var yu=200;function uo(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function vu(n){return uo(n)&&(qe(n)||Ar(n))}var Wt=class{stage;snapshots=new Map;constructor(e){this.stage=e}applySwatches(e){let t=new Map,i=[],r=[];for(let s of e.uuids)for(let o of e.swatches){let{result:a,entry:l}=this.applyPair(s,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 s of e.entries)s.swatch&&this.applyPair(s.uuid,s.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},s=this.stage.resolveEntity(e);if(!s)return{result:{...r,ok:!1,reason:"entity-not-found"}};if(!uo(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(s,t,o):this.applyBehavior(s,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=Xe("shader",t.source);if(!r)return{ok:!1,reason:"unknown-source"};if(!e.hasMaterial())return{ok:!1,reason:"no-material"};let s;try{s=r.create(t.props)}catch(a){return console.warn(`[zylem] swatch shader "${t.source}" threw`,a),{ok:!1,reason:"invalid-props"}}if(!vu(s))return{ok:!1,reason:"invalid-props"};let o=e.setMaterial({shader:s},{disposePrevious:!1});return o?(i.previousMaterials?gr(o,i.previousMaterials):i.previousMaterials=o,{ok:!0,replaced:!1}):{ok:!1,reason:"no-material"}}applyBehavior(e,t,i){let r=Xe("behavior",t.source);if(!r)return{ok:!1,reason:"unknown-source"};let{descriptor:s}=r,o=s.key,a=!1,l,c=e.getBehaviorRef(s);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 u;try{e.use(s,t.props),u=e.getBehaviorRefs().at(-1)}catch(d){console.warn(`[zylem] swatch behavior "${t.source}" failed to attach`,d)}return!u||u.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,u),i.appliedRefs.set(o,u),{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 s=r.replaceMaterials(i.previousMaterials,{disposePrevious:!1});s&&(i.redoMaterials=s)}for(let s of i.appliedRefs.values())r.removeBehavior(s)&&this.stage.detachBehaviorLink(r,s);for(let s of i.previousRefs.values())r.restoreBehaviorRef(s),this.stage.attachBehaviorLink(r,s)}}}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 s of i.previousRefs.values())r.removeBehavior(s)&&this.stage.detachBehaviorLink(r,s);for(let s of i.appliedRefs.values())r.restoreBehaviorRef(s),this.stage.attachBehaviorLink(r,s)}}}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=Xe("behavior",t.swatch.source);if(!r)continue;let s=i.removeBehavior(r.descriptor);if(s&&this.stage.detachBehaviorLink(i,s),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>yu;){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 s=this.stage.resolveEntity(i)?.getMaterials()??[];gr(r.previousMaterials??[],s),gr(r.redoMaterials??[],s)}}};function gr(n,e){for(let t of n)e.includes(t)||t.dispose()}import{Box3 as Cu,Frustum as xu,Vector2 as Kt}from"three";import{Frustum as bu,Vector2 as ho,Vector3 as wu}from"three";var po=Array.from({length:8},()=>new wu),b=new ho,w=new ho;function mo(n,e,t,i=new bu){b.set(Math.min(e.x,t.x),Math.min(e.y,t.y)),w.set(Math.max(e.x,t.x),Math.max(e.y,t.y));let r=1e-5;w.x-b.x<r&&(w.x=b.x+r),w.y-b.y<r&&(w.y=b.y+r),U(0,b.x,b.y,-1,n),U(1,w.x,b.y,-1,n),U(2,w.x,w.y,-1,n),U(3,b.x,w.y,-1,n),U(4,b.x,b.y,1,n),U(5,w.x,b.y,1,n),U(6,w.x,w.y,1,n),U(7,b.x,w.y,1,n);let[s,o,a,l,c,u,d,p]=po,v=i.planes;return ye(v[0],s,c,p),ye(v[1],o,d,u),ye(v[2],l,p,d),ye(v[3],s,u,c),ye(v[4],s,l,a),ye(v[5],c,d,p),i}function U(n,e,t,i,r){po[n].set(e,t,i).unproject(r)}function ye(n,e,t,i){n.setFromCoplanarPoints(e,t,i)}function fo(n,e){return e.isEmpty()||!Number.isFinite(e.min.x)||!Number.isFinite(e.max.x)?!1:n.intersectsBox(e)}function go(n,e,t){switch(t){case"add":{let i=new Set(n),r=[...n];for(let s of e)i.has(s)||(i.add(s),r.push(s));return r}case"subtract":{let i=new Set(e);return n.filter(r=>!i.has(r))}default:return[...new Set(e)]}}function yo(n){return n.altKey?"subtract":n.shiftKey?"add":"replace"}var Su="[data-zylem-overlay-root]";function vo(n){let e=n.parentElement;return e?e.querySelector(Su)??e:null}var qt=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 Pu=4,Eu=new Cu,bo=new xu,Xt=class{context;overlay=new qt;armed=!1;dragging=!1;mode="replace";baseSelection=[];startNdc=new Kt;currentNdc=new Kt;startClient=new Kt;currentClient=new Kt;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=yo(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=vo(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)<Pu)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;mo(e,this.startNdc,this.currentNdc,bo);let t=[];this.context.forEachEntity((i,r)=>{let s=ae(r,Eu);s&&fo(bo,s)&&t.push(i)}),Sr(go(this.baseSelection,t,this.mode))}};import{BoxGeometry as Mu,EdgesGeometry as Du,Group as Tu,LineBasicMaterial as ku,LineSegments as Ru,Vector3 as So}from"three";var Qt=new So,wo=new So,Yt=class{scene;container=new Tu;edges;material;pool=[];constructor(e,t=16765503){this.scene=e;let i=new Mu(1,1,1);this.edges=new Du(i),i.dispose(),this.material=new ku({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(Qt),i.getCenter(wo);let r=this.acquire(t);t+=1,r.position.copy(wo),r.scale.set(Math.max(Qt.x,1e-6),Math.max(Qt.y,1e-6),Math.max(Qt.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 Ru(this.edges,this.material);return i.frustumCulled=!1,this.container.add(i),this.pool.push(i),i}};var Eo=2293538,Iu=16724787,yr=new $t,Mo=new Jt,ei=class{stage;options;mouseNdc=new _u(-2,-2);raycaster=new Ou;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 $t;grid=new on;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 Nt({getScene:()=>this.stage.scene?.scene??null,getCamera:()=>this.getDebugViewCamera()?.camera??null,resolveEntity:i=>this.resolveEntity(i)}),this.swatchApplier=new Wt({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 Xt({getCamera:()=>this.getDebugViewCamera()?.camera??null,forEachEntity:i=>this.forEachSelectableEntity(i)}),this.levelSession=new xt(this.levelSessionHost()),this.syncWithDebugState(),this.debugStateUnsubscribe=Vu(h,()=>{this.syncWithDebugState()}),this.entityResolverUnregister=wr(i=>this.resolveEntity(i)),this.focusContextUnregister=Rr({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{let r=this.stage.cameraManagerRef,s=()=>{r&&!r.isEditorViewActive()&&r.hasEditorCameras()&&r.activateCameraById(m.free),this.getDebugViewCamera()?.frameObject(i)};if(r&&Ue()&&!r.hasEditorCameras()){r.ensureEditorCameras().then(s);return}s()},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.stage.navigation.sync(e.document),this.syncTransformTool(),this.syncGrid()}playLevel(e){this.levelSession.play(e),this.stage.navigation.setTool({tool:"none"}),this.stage.navigation.sync(e),this.syncTransformTool(),this.syncGrid()}closeLevel(){this.levelSession.close(),this.stage.navigation.clear(),this.syncTransformTool(),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 Jt;return e.getWorldDirection(t),{x:t.x,y:t.y,z:t.z}},camera:()=>this.getDebugViewCamera()?.camera??null,viewport:()=>{let e=this.stage.rendererManager?.getDomElement().getBoundingClientRect();return e&&e.width>0&&e.height>0?{width:e.width,height:e.height}:null},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=Kr({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:Au.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=>{Po().channel.send("level:gesture",{gesture:e})},publishSelect:e=>{Po().channel.send("level:select",e)},publishNotice:e=>{fi("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,s)=>{t.has(s)||(t.add(s),e(s,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()),this.levelSession.cancelGesture(),e!=="none"&&(this.ensureInteraction(),this.populateDebugMap()),this.parkToolVisuals(e);let t=L(e);this.getDebugViewCamera()?.setOrbitFollowEnabled(!t),this.syncTransformTool()}syncTransformTool(){let e=h.tool,t=L(e)&&!this.levelSession.isEditing;this.transformTool.setMode(t?e:null)}syncGrid(){let e=this.stage.scene?.scene;if(!e)return;this.grid.addTo(e),this.grid.setIncrement(C().translate);let t=this.levelSession.drawPlane;this.grid.setPlane(t?.frame??null,t?.focus),this.grid.setVisible(h.gridVisible)}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 Lu(new Bu,new zu({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 Gt(e),this.placementGhost??=new Ht(e),this.selectionHighlight??=new Yt(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 s=this.resolveEntity(r),o=this.selectionBoundsPool[i.length]??=new $t,a=ae(s,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=O();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(),L(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 s=this.currentRay(),o=t.raycast(s.origin,s.direction,this.options.maxRayDistance);o?hi(o.uuid??null):Ne();let a=Pr();if(!a){this.debugCursor?.hide();return}let l=ae(this.resolveEntity(a),this.hoverBounds);if(!l){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(Eo);break;case"delete":this.debugCursor?.setColor(Iu);break;default:this.debugCursor?.setColor(h.pickMode?Eo:16777215);break}this.debugCursor?.updateFromBounds(l)}pickAtNdc(e,t,i={}){let r=i.updateHover??h.pickMode;this.mouseNdc.set(e,t);let s=this.stage.world;if(!s||!this.getDebugViewCamera())return r&&Ne(),null;let o=this.currentRay(),l=s.raycast(o.origin,o.direction,this.options.maxRayDistance)?.uuid??null;if(!l)return r&&Ne(),null;r&&hi(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 Co(new Float32Array(t.vertices),3)),this.debugLines.geometry.setAttribute("color",new Co(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||!re()||(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 s=this.currentRay(),o=t.raycast(s.origin,s.direction,this.options.maxRayDistance)??null,a=Q(s,o,C(),i.measure());if(!a){i.hide();return}i.showAt(a.position)}editorEntityBoxes(){let e=[];return this.stage.entityDelegate.childrenMap.forEach(t=>{let i=ae(t,new $t);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":co(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 Jt,direction:new Jt(0,0,-1)}}handleAction(e,t={shiftKey:!1,altKey:!1}){let i=O();if(i!=="select"&&i!=="delete"&&i!=="add")return;let s=this.stage.world?.raycast(e.origin,e.direction,this.options.maxRayDistance)??null;switch(i){case"select":{let o=s?.uuid??null,a=o&&this.resolveEntity(o)?o:null;t.altKey?a&&Cr([a]):t.shiftKey?a&&xr(a):a?di(a):di(null);break}case"delete":{let o=s?.uuid??null;if(!o)break;this.stage.entityDelegate.detachEntity(o)&&be({opId:xo(10),kind:"delete",label:"Delete entity",entries:[{uuid:o}]});break}case"add":this.placeEntity(e,s);break}}placeEntity(e,t){let i=Q(e,t,C());if(!i)return;let{position:r,normal:s}=i,o=h.addTypeId,a={...o?q(o)?.defaultProps??{}:{},...h.addTypeProps??{}},l=o?q(o):null;if(!l&&!this.options.addEntityFactory){this.warnMissingAddSource();return}let c=l?l.create({position:{x:r.x,y:r.y,z:r.z},normal:{x:s.x,y:s.y,z:s.z},props:{...l.defaultProps??{},...h.addTypeProps??{}}}):this.options.addEntityFactory({position:r,normal:s});c&&Promise.resolve(c).then(async u=>{u&&(await this.stage.entityDelegate.spawnEntity(u),this.restOnSurface(u,r,s),be({opId:xo(10),kind:"create",label:`Add ${l?.label??"entity"}`,entries:[{uuid:u.uuid,...o?{typeId:o}:{},...Object.keys(a).length>0?{props:a}:{}}]}))}).catch(u=>{console.error("Add tool: failed to spawn entity",u)})}restOnSurface(e,t,i){let r=e?.group??e?.mesh;if(!r||typeof e.setPose!="function"||(yr.setFromObject(r),yr.isEmpty()))return;yr.getSize(Mo);let s=Si(t,Mo,i);s.equals(t)||e.setPose({position:{x:s.x,y:s.y,z:s.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),fi("warn",e)}attachDomListeners(){let e=this.stage.rendererManager?.getDomElement();if(!e)return!1;let t=l=>{let c=e.getBoundingClientRect(),u=(l.clientX-c.left)/c.width*2-1,d=-((l.clientY-c.top)/c.height*2-1);this.mouseNdc.set(u,d)},i=l=>{if(t(l),this.levelPointer){l.preventDefault(),l.stopImmediatePropagation(),this.levelSession.pointerMove(this.currentRay(),l);return}if(this.levelSession.pointerHover(this.currentRay()),this.marquee.isArmed){this.marquee.pointerMove(this.mouseNdc,l);return}this.transformTool.isDragging&&this.transformTool.pointerMove(this.currentRay(),l.altKey)},r=l=>{if(l.button!==0)return;t(l);let c=this.currentRay();if(this.stage.navigation.pointerDown(c)){l.preventDefault(),l.stopImmediatePropagation();return}if(this.levelSession.pointerDown(c,l)){l.preventDefault(),l.stopImmediatePropagation(),this.levelPointer=!0,this.beginPointerCapture(e,l.pointerId);return}if(this.transformTool.pointerDown(c)){this.beginPointerCapture(e,l.pointerId);return}if(O()==="select"){this.marquee.pointerDown(this.mouseNdc,l,e),this.beginPointerCapture(e,l.pointerId);return}this.handleAction(c,l)},s=l=>{if(this.levelPointer){l.preventDefault(),l.stopImmediatePropagation(),this.levelSession.pointerUp(this.currentRay()),this.levelPointer=!1,this.endPointerCapture();return}if(this.marquee.isArmed){let c=this.marquee.pointerUp(this.mouseNdc);this.endPointerCapture(),c==="click"&&this.handleAction(this.currentRay(),l);return}this.transformTool.isDragging&&(this.transformTool.pointerUp(),this.endPointerCapture())},o=l=>{if(this.levelPointer){this.levelPointer=!1,this.levelSession.pointerUp(this.currentRay()),this.endPointerCapture();return}if(this.marquee.isArmed){this.marquee.cancel(),this.endPointerCapture();return}s(l)},a=l=>{l.key!=="Escape"||!this.levelSession.hasGesture||(l.preventDefault(),l.stopImmediatePropagation(),this.levelSession.cancelGesture())};return e.addEventListener("pointermove",i,!0),e.addEventListener("pointerdown",r,!0),e.addEventListener("pointerup",s,!0),e.addEventListener("pointercancel",o,!0),window.addEventListener("keydown",a,!0),this.domDisposeFns.push(()=>e.removeEventListener("pointermove",i,!0),()=>e.removeEventListener("pointerdown",r,!0),()=>e.removeEventListener("pointerup",s,!0),()=>e.removeEventListener("pointercancel",o,!0),()=>window.removeEventListener("keydown",a,!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}}};import{Vector2 as Fu}from"three";var ti=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Fu(e,t);return new z(f.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new Lt;if(e)return i.addCamera(e,e.name||"main"),i;let r=t.filter(s=>s!==void 0);if(r.length>0){for(let s of r){let o=s.cameraRef;i.addCamera(o,o.name||void 0)}for(let s=1;s<r.length;s++)i.addActiveCamera(r[s].cameraRef)}else{let s=this.createDefaultCamera();i.addCamera(s,"default")}return i}};var ii=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"?Ze.emit("stage:loading:start",t):e.type==="progress"?Ze.emit("stage:loading:progress",t):e.type==="complete"&&Ze.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 ri=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){Pe(e.options)||(this.scene?.addEntityGroup(e),Se(e),oe(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),Se(i),oe(i),Pe(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 zo}from"@zylem/behaviors/core";var ni=new WeakSet;function Do(n,e={}){let t=ko(n);t?(Ro(n,t),n._rotation2DAngle=We(n.options.rotation,S).z,Bo(n,t)||ni.add(n)):ni.delete(n),e.skipScale||Gu(n)}function To(n){let e=ko(n);e&&(n.physicsAttached||Ro(n,e),ni.has(n)&&Bo(n,e)&&ni.delete(n))}function ko(n){let e=n.options.rotation;return e?ve(We(e,S)):null}function Ro(n,e){n.bodyDesc&&(n.bodyDesc.rotation=[e.x,e.y,e.z,e.w])}function Bo(n,e){let t=n.group??n.mesh;return t?(t.quaternion.set(e.x,e.y,e.z,e.w),!0):!1}function Gu(n){let e=n.options.scale;if(!e)return;let t=We(e,Or);n.setScale(t.x,t.y,t.z),Lr(n)}var Hu=200,si=class n{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 Ge){e.create();for(let i of e.getChildren())i instanceof we&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:x(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();Gr(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.applySpawnTransform(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof we&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:x(),camera:this.camera}),this.tryRegisterRenderStrategy(t),X(t)||this.scene.addEntityGroup(t),oe(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),Hr(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),To(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),X(e)||this.scene.addEntityGroup(e),oe(e))}applySpawnTransform(e){Do(e,{skipScale:e instanceof Ce})}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(xe(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!==zo.Static&&(e.bodyDesc.kind=zo.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof Ce){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)}Ke(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 s=typeof r.getPose=="function"?r.getPose():null;return this.unregisterBehaviorLinks(r),this.entityModelDelegate.unobserve(e),X(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),Ke(r,!1),this.detachedMap.set(e,{entity:r,position:s?.position??null,rotation:s?.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:s}=t;return i.bodyDesc&&(r&&(i.bodyDesc.position=[r.x,r.y,r.z]),s&&(i.bodyDesc.rotation=[s.x,s.y,s.z,s.w])),this.registerBehaviorLinks(i),this.maybeAttachEntityPhysics(i),this.tryRegisterRenderStrategy(i),X(i)||this.scene.addEntityGroup(i),Fr(i),jr(i),this.addEntityToStage(i),this.entityModelDelegate.observe(i),!0}isDetached(e){return this.detachedMap.has(e)}evictOldestDetached(){for(;this.detachedMap.size>Hu;){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{}le(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 qr?{...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(N(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();N(i)?this.handleEntityImmediatelyOrQueue(i):Fe(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}Fe(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 s=[...this.pendingEntities];this.pendingEntities=[],this.enqueue(...s)}let i=[...this.pendingPromises];this.pendingPromises=[];let r=this.children.length+i.length;for(let s of this.children)await this.spawnEntity(s),t++,this.loadingDelegate.emitProgress(`Loaded ${s.name||"unknown"}`,t,r),t%5===0&&await this.yieldToEventLoop();for(let s of i){try{let o=await s;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)??n.EMPTY_BEHAVIOR_LINKS,createEntity:vi,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=>{Ke(t,!1);try{t.nodeDestroy({me:t,globals:x()})}catch{}le(t),e.push(t.uuid)}),this.detachedMap.forEach(({entity:t})=>{try{t.nodeDestroy?.({me:t,globals:x()})}catch{}le(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},s=this.behaviorEntityIndex.get(i);s||(s=new Set,this.behaviorEntityIndex.set(i,s)),s.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)??n.EMPTY_BEHAVIOR_LINKS,createEntity:vi,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[s]=i.splice(r,1);return s&&this.unlinkBehaviorLink(s),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 Lo,Raycaster as ju,Vector2 as Zu,Vector3 as oi}from"three";var Nu=5e3,Uu=new oi(0,1,0),ai=class{host;unsubscribe;known=new Set;targets=new Map;bounds=new Lo;raycaster=new ju;mouseNdc=new Zu;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=[Nr((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)}}),Zr(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:vr(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 re()}mountView(){let e=this.host.getScene();!e||!this.session||(this.view?.dispose(),this.view=new un(e,this.session.representative))}syncTarget(e){Ur(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?V(t.entity):null,s=r?.role==="droppable",o=!1;if(this.session&&s&&t){let u=r?.handlers.accepts;o=u?u(this.session.payload,t.entity)===!0:!0}let a=null;if(s&&t){if(a=((r?.handlers.placeAt??this.session?.placeAt??"area")==="hit"?t.point:t.center).clone(),this.session?.snap!=null){let d=ne(a,this.session.snap);a.set(d.x,d.y,d.z)}}else i&&(a=i.position.clone());let l=i?.normal.clone()??Uu.clone(),c=!1;return this.session&&a&&(c=this.hasDroppable()?s&&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(!V(i))continue;let r=yi(i,this.bounds);if(!r)continue;let s=Wr(e,r);s&&(t&&s.distance>=t.distance||(t={entity:i,distance:s.distance,point:s.point,center:r.getCenter(new oi)}))}return t}hasDroppable(){for(let e of this.targets.values())if(V(e)?.role==="droppable")return!0;return!1}surfacePoint(e){let t=this.host.raycast(e.origin,e.direction,Nu),i=this.session?.snap!=null?{enabled:!0,translate:this.session.snap}:{enabled:!1,translate:0};return Q(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??cn,t.opacity??ln),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=V(e)?.handlers[t];if(r)try{r(this.areaContext(e,i))}catch(s){console.error("[zylem] pointer area callback failed",s)}}areaContext(e,t){return{area:e,position:vr(t.position??Wu(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 s;try{s=i(t)}catch(o){return console.error("[zylem] spawnOnClick failed",o),!1}if(!qu(s))return!1;try{this.host.addSpawn(s)}catch(o){return console.error("[zylem] placement spawn failed",o),!1}return this.notifyDrop(e.area,t),this.finishCommit(),!0}return(e.area?V(e.area)?.role:null)!=="droppable"?!1:(this.notifyDrop(e.area,t),this.finishCommit(),!0)}pointContext(e){return{position:vr(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=V(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=V(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,s=-((e.clientY-i.top)/i.height*2-1);this.mouseNdc.set(r,s)}};function Wu(n){let e=yi(n,new Lo);return e?e.getCenter(new oi):new oi}function vr(n){return n?{x:n.x,y:n.y,z:n.z}:{x:0,y:0,z:0}}function qu(n){return n==null||n===!1?!1:typeof n=="object"||typeof n=="function"}var Xu="Stage",ci=class extends Ft{type=Xu;navigation;state={...Jr};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=Ku();let t=this;this.navigation=new Qr({get stageId(){return t.uuid},scene:()=>this.scene?.scene??null,status:r=>li().channel.send("navigation:status",r),baked:(r,s)=>li().channel.send("navigation:baked",{stageId:this.uuid,requestId:r,asset:s}),path:(r,s)=>li().channel.send("navigation:path",{stageId:this.uuid,requestId:s,result:r}),edit:r=>li().channel.send("navigation:edit",{stageId:this.uuid,edit:r})}),this.cameraDelegate=new ti(this),this.loadingDelegate=new ii,this.entityModelDelegate=new ri,this.entityDelegate=new si(this.loadingDelegate,this.entityModelDelegate),this.pointerDelegate=new ai(Qu(this));let i=Xs(e);this.camera=i.camera,this.cameras=i.cameras,this.entityDelegate.children=i.entities,i.asyncEntities.length&&this.entityDelegate.enqueue(...i.asyncEntities),this.state={...this.state,inputs:i.config.inputs,backgroundColor:i.config.backgroundColor,backgroundImage:i.config.backgroundImage,backgroundShader:i.config.backgroundShader,gravity:i.config.gravity,variables:i.config.variables,physicsRate:i.config.physicsRate,assetLoaders:i.config.assetLoaders,defaultLighting:i.config.defaultLighting,postProcessingEffects:i.config.postProcessingEffects,entities:[]},this.gravity=i.config.gravity??new _o(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Oo?e:new Oo(e);en(i),tn(t),rn(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 s=this.gravity??new _o(0,0,0);if(this.world=await Vt.create(s,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 se.configureGLTFRuntime({renderer:o,..._t(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,a=>this.entityDelegate.handleLateModelReady(a)),this.renderStrategy=new it,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 ei(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;B("behaviorSystems",()=>{for(let s of this.entityDelegate.behaviorSystems)s.update(void 0,t)}),B("entityLoop",()=>{for(let s 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=s,s.nodeUpdate(o);let a=s;a.transformStore&&an(a,a.transformStore),s.markedForRemoval&&this.entityDelegate.removeEntityByUuid(s.uuid)}}),B("worldUpdate",()=>{i.update(e)}),B("behaviorPostUpdate",()=>{for(let s of this.entityDelegate.behaviorSystems)s.postUpdate?.(void 0,t)}),B("syncRenderPoses",()=>{$s({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),B("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),B("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),B("scene",()=>{r.update({delta:t})}),this.pointerDelegate.update(t),ks()}outOfLoop(){this.debugUpdate()}debugUpdate(){re()&&(Xi("debugUpdate"),this.debugDelegate?.update(),Qi())}_destroy(e){this.pointerDelegate.dispose(),this.navigation.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,nn(),le(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 Qu(n){return{getScene:()=>n.scene?.scene??null,raycast:(e,t,i)=>{let r=n.world?.raycast(e,t,i);return r?{distance:r.distance,normal:r.normal}:null},addSpawn:e=>{if(n.wrapperRef){n.wrapperRef.add(e);return}n.enqueue(e)},getCanvas:()=>n.rendererManager?.getDomElement()??null,getCamera:()=>(n.cameraManagerRef?.primaryCamera??n.cameraRef)?.camera??null,onSessionEnded:()=>{n.wrapperRef?.abandonPlacement()}}}import{proxy as Yu}from"valtio/vanilla";import{Vector3 as $u}from"three";var Ju={backgroundColor:Ye,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new $u(0,0,0),variables:{}},ie=Yu({...Ju});function Vo(n){let e=ed(),t={};return typeof n[0]=="object"&&(t=n.shift()??{}),[{...e,...t},...n]}function ed(){return{backgroundColor:ie.backgroundColor,backgroundImage:ie.backgroundImage??null,inputs:ie.inputs?{...ie.inputs}:void 0,gravity:ie.gravity,variables:ie.variables?{...ie.variables}:void 0}}var br=class{wrappedStage;get navigation(){return this.wrappedStage?.navigation??null}options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Dr;inputConfig=null;pendingPlacement=null;placementGeneration=0;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];se.prepareGLTFRuntime(_t(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=Mr(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){this.wrappedStage?.pointerDelegate.dispose(),$e.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new ci(r),this.wrappedStage.wrapperRef=this,this.pendingPlacement&&this.wrappedStage.pointerDelegate.arm(this.pendingPlacement),this.pendingLoadingCallbacks.forEach(c=>{this.wrappedStage.onLoading(c)}),this.pendingLoadingCallbacks=[];let s=t instanceof M?t.cameraRef:t;await this.wrappedStage.load(e,s,i);let o=null,a=!1,l=()=>{if(a=!1,!o?.length){o=null;return}let c=o;o=null,$e.entities=[...$e.entities,...c]};this.wrappedStage.onEntityAdded(c=>{if(Pe(c.options))return;let u=this.wrappedStage.buildEntityState(c);o||(o=[]),o.push(u),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 M?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof M?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof M?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 Ry(...n){let e=Vo(n);return new br([...e])}export{cd as a,et as b,xe as c,Pe as d,X as e,tt as f,it as g,_h as h,Ah as i,f as j,ee as k,Mt as l,pe as m,me as n,Oe as o,_e as p,Ve as q,Ae as r,te as s,Lt as t,M as u,pm as v,Sm as w,Bc as x,br as y,Ry as z};
|
|
@@ -1 +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-
|
|
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-3XIJCDII.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 @@
|
|
|
1
|
+
import{createLevelNavigation as n,DEFAULT_NAVIGATION_SETTINGS as v,navigationSourceHash as N}from"@zylem/bridge";export{n as a,v as b,N as c};
|