@zylem/game-lib 0.9.8 → 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import{a as Er,b as m,c as Ze,d as Mr,f as di,m as hi,o as ve}from"./chunk-26EJFYDX.js";import{a as qe,b as Nr}from"./chunk-WBQ5TNRZ.js";import{a as Jr}from"./chunk-BH53MBAZ.js";import{l as xr}from"./chunk-UG22Z42P.js";import{a as en,b as tn,d as rn}from"./chunk-Y5IU6IA5.js";import{b as Cr,c as Yr,e as Ye,f as $r}from"./chunk-SIRFF4DY.js";import{a as Dr,c as ci,d as ui,e as Tr,f as ne,g as kr}from"./chunk-273CUPEO.js";import{A as je,b as L,d as h,e as yr,i as O,k as re,o as ai,q as vr,s as br,t as wr,u as S,y as Sr,z as li}from"./chunk-UM5VNQPY.js";import{c as K,j as We}from"./chunk-2HSR5XDQ.js";import{a as Xe,b as Wr,c as Qe,d as Kr,e as qr,f as Xr,g as Qr,m as le}from"./chunk-D2PATZCC.js";import{b as Ke,d as Ur}from"./chunk-BJYXY2FB.js";import{g as Zr}from"./chunk-UNCP6V7I.js";import{B as Hr,C as mi,D as jr,E as fi,a as be,k as Lr,l as Or,m as _r,n as Vr,o as oe,p as Ar,q as we,t as Ir,u as Fr,v as Ue,w as V,x as Gr}from"./chunk-CI7A5N6G.js";import{a as pi,b as Rr,f as se,i as Ne,j as zr}from"./chunk-YW2GTHCV.js";import{a as Pr,b as _}from"./chunk-AIQ6IVT5.js";import{g as ae}from"./chunk-UUOPT2N4.js";import{c as He,d as oi,j as C}from"./chunk-4QLJUQSJ.js";import{c as T,i as Br,j as g}from"./chunk-7WRQ2UAN.js";import{Vector2 as ln,RenderTarget as Ro,HalfFloatType as zo}from"three";import{WebGPURenderer as Lo,RenderPipeline as Oo}from"three/webgpu";import{pass as _o,renderOutput as cn,screenCoordinate as Vo,vec2 as gi,vec4 as pn,fract as un,sin as dn,dot as hn,texture as Ao,uniform as Io}from"three/tsl";import{setConsoleFunction as ko,getConsoleFunction as Bo}from"three";var nn="THREE.Abstract function.",sn=!1,on=!1;function an(){if(sn)return;sn=!0;let n=Bo();ko((e,t,...i)=>{if(e==="warn"&&t===nn){on||(on=!0,console.warn(`${nn} (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 mn={x:0,y:0,width:1,height:1},Fo=1/20;async function td(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var $e=class{renderer;postProcessing=null;renderScale=1;screenResolution;_initialized=!1;_sceneRef=null;_lastAnimationTimestamp=null;_postEffects=[];_postSceneRef=null;_postCameraRef=null;_transition=null;constructor(e){this.screenResolution=e||new ln(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(an(),this.renderer=new Lo({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 Oo(this.renderer),r=_o(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=cn(s),a=this._transition;if(a)try{o=pn(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(Zo()),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 ln;this.renderer.getDrawingBufferSize(r);let s=new Ro(Math.max(1,r.x),Math.max(1,r.y),{type:zo}),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:Io(0),fromNode:cn(Ao(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,Fo);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=Go(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&&jo(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 Go(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=>Ho(o,e))||(r.visible=!1,t.push(r))}),t}function Ho(n,e){return n?n.map===e:!1}function jo(n){return n.x===0&&n.y===0&&n.width===1&&n.height===1}function Zo(){let n=Vo.xy,e=un(dn(hn(n,gi(12.9898,78.233))).mul(43758.5453)),t=un(dn(hn(n.add(gi(13,7)),gi(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return pn(i,i,i,0)}function Se(n){return n?.category??"none"}function Ce(n){let e=Se(n);return e==="environment"||e==="pack"}function q(n){return n.isInstanced===!0||n.isBundled===!0}import{BundleGroup as No}from"three/webgpu";var Je=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 No,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as fn,Matrix4 as xe,Vector3 as gn,Quaternion as Uo}from"three";var Pe=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}:${pi(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Rr(pi(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 xe;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 xe,i=new gn,r=new Uo,s=new gn(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(Lr(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 fn(t,i,r);s.count=0,s.frustumCulled=!1;let o=new xe().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 fn(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new xe;for(let o=0;o<e.capacity;o++)e.instancedMesh.getMatrixAt(o,r),i.setMatrixAt(o,r);let s=new xe().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 et=class{bundles=new Je;instances=new Pe;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=Se(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=Pe.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 kl,Box3Helper as Bl,BoxGeometry as ws,Color as Rl,DoubleSide as zl,EdgesGeometry as Ll,Group as vs,LineBasicMaterial as Ol,LineSegments as _l,Mesh as wt,MeshStandardMaterial as Ni,OctahedronGeometry as Vl,Vector3 as Al}from"three";import{DEFAULT_DRAW_SHAPE as Il,brushCenter as Fl,brushTopology as Gl,clipBrush as Hl,deleteBrushElements as jl,frameForPlane as Zl,primitiveBrushes as Nl,sectorSizeOf as Ul}from"@zylem/bridge";import{Vector3 as yi}from"three";var Wo=0;function Ko(n,e){if(e)return{position:n.origin.clone().add(n.direction.clone().multiplyScalar(e.distance)),normal:new yi(e.normal[0],e.normal[1],e.normal[2])};if(Math.abs(n.direction.y)<1e-6)return null;let t=(Wo-n.origin.y)/n.direction.y;return t<0?null:{position:n.origin.clone().add(n.direction.clone().multiplyScalar(t)),normal:new yi(0,1,0)}}function qo(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 vi(n,e,t){let i=qo(e,t);return i<=0?n.clone():n.clone().add(t.clone().normalize().multiplyScalar(i))}function X(n,e,t,i){let r=Ko(n,e);if(!r)return null;let{normal:s}=r,o=t.enabled?ne(r.position,t.translate):r.position,a=new yi(o.x,o.y,o.z);return{position:i?vi(a,i,s):a,normal:s}}import{Vector3 as tt}from"three";import{frameForPlane as vn,pointInFrame as Xo}from"@zylem/bridge";var Qo=.05,bi=.001,Yo=1e-9;function Q(n,e){return n.x*e.x+n.y*e.y+n.z*e.z}function $o(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function wi(n){return Math.hypot(n.x,n.y,n.z)}function A(n){return Math.abs(n)<Yo?0:n}function ue(n){return{x:A(n.x),y:A(n.y),z:A(n.z)}}function bn(n){return n===m.top||n===m.bottom?"top":n===m.side||n===m.left?"side":null}function Jo(n){let e=Math.abs(n.x),t=Math.abs(n.y),i=Math.abs(n.z);return t>=e-bi&&t>=i-bi?"top":e>=i-bi?"side":"front"}function wn(n){return n==="top"?"y":n==="side"?"x":"z"}function k(n,e,t,i={}){let r=wi(e)*wi(n.direction);if(r<1e-12)return null;let s=Q(e,n.direction);if(Math.abs(s)<Math.max(i.minIncidence??Qo,1e-9)*r)return null;let o=(t-Q(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 ea(n,e){let t=wn(n),i={x:0,y:0,z:0};return i[t]=e[t]>0?-1:1,vn(i,0)}function ta(){return vn({x:0,y:1,z:0},0)}function Si(n,e){let t=bn(n);return t?ea(t,e):ta()}function Ee(n){return{normal:{...n.normal},distance:Q(n.normal,n.origin)}}function Sn(n,e,t){let i=wn(bn(n)??Jo(e)),r={x:0,y:0,z:0};return r[i]=1,{normal:r,distance:t[i]}}function x(n,e){return e>0?A(Math.round(n/e)*e):n}function I(n,e){return{x:x(n.x,e),y:x(n.y,e),z:x(n.z,e)}}function Ci(n,e,t){let i=I(n,t),r=wi(e.normal);if(r<1e-12)return i;let s=(Q(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 xi(n,e,t){let i=Xo(n,I(e,t));return{u:A(i.u),v:A(i.v)}}function yn(n,e,t){let i=new tt(n.direction.x,n.direction.y,n.direction.z),r=new tt(t.x,t.y,t.z);return i.lengthSq()<1e-24||r.lengthSq()<1e-24?null:Yr({origin:new tt(n.origin.x,n.origin.y,n.origin.z),direction:i.normalize()},new tt(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=yn(i,e,t),this.startValue===null&&(this.startHit=this.screenHit(i),this.sign=Q(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=yn(e,this.anchor,this.axis);return i===null?null:i-this.startValue}if(!this.startHit)return null;let t=this.screenHit(e);return t?Q($o(t,this.startHit),this.view.up)*this.sign:null}screenHit(e){return k(e,this.view.direction,Q(this.view.direction,this.anchor),{behind:!0})}};var Pn=1e-6;function Pi(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function En(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 Mn(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 ia(n,e){return Math.hypot(n.x-e.x,n.y-e.y,n.z-e.z)<Pn}function Cn(n,e,t){let i=Pi(e,n),r=Math.hypot(i.x,i.y,i.z),s=Math.hypot(t.x,t.y,t.z);if(r<Pn||s<1e-9)return null;let o=En(i,t);return Math.hypot(o.x,o.y,o.z)<1e-6*r*s?null:Mn(n,o)}function xn(n,e,t){let i=Pi(e,n),r=Pi(t,n),s=En(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:Mn(n,s)}var it=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=>ia(a,e)))return null;if(!s){if(i)return this.points.push({...e}),null;let a=Cn(r,e,t);return a&&(this.points=[]),a}let o=xn(r,s,e);return o&&(this.points=[]),o}preview(e,t){let[i,r]=this.points;return i?r?xn(i,r,e):Cn(i,e,t):null}cancel(){this.points=[]}};import{framePoint as Dn,orderFootprint as ra}from"@zylem/bridge";var Tn=1e-6;function kn(n){return{origin:{...n.origin},u:{...n.u},v:{...n.v},normal:{...n.normal}}}var rt=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:Dn(this.frame,this.start.u,this.start.v)}begin(e,t,i){this.frame=kn(e),this.step=i,this.start=xi(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=Ee(this.frame),i=k(e,t.normal,t.distance);i&&(this.end=xi(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<Tn||i.v1-i.v0<Tn)return this.cancel(),!1;let r=Dn(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=x(this.initialHeight()+t,this.step))}commit(e){let t=this.state();return this.cancel(),t?.height?{kind:"primitive",frame:kn(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 ra({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 wa,moveElementsBy as Sa,moveFaces as Ca,shearFaces as xa}from"@zylem/bridge";import{Raycaster as na,Vector2 as sa,Vector3 as Ln}from"three";var oa=8,aa=10,la=400,ca=6,ua=1.5,da=.001,nt=new Ln;function ha(n,e){n.updateMatrixWorld();let t=n.isPerspectiveCamera===!0,i=t?n.near??.1:-1/0,r=s=>-nt.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:(nt.set(s.x,s.y,s.z).project(n),{x:(nt.x+1)/2*e.width,y:(1-nt.y)/2*e.height,depth:o})}}}function Bn(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 pa(n,e){let t=n.userData.trianglePlanes;return!t||typeof e!="number"?null:t[e]??null}function ma(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 On(n){return[...n].sort((e,t)=>Math.abs(e.distance-t.distance)>ua?e.distance-t.distance:e.depth-t.depth)}function fa(n,e,t,i=aa){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 On(r)}function _n(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 ga(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=_n(n,e,(i-r)/(s-r));return r<i?[o,e]:[n,o]}function ya(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 va(n,e,t,i=oa){let r=[];for(let s of e){let{vertices:o,edges:a}=s.topology;a.forEach((l,c)=>{let u=ga(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}=ma(n,d,p);if(v>i)return;let D=_n(u[0],u[1],ya(W,d.depth,p.depth,t.perspective));r.push({item:{brushId:s.id,index:c},distance:v,depth:t.depthOf(D),point:D})})}return On(r)}function Vn(n,e,t=la,i=ca){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 An(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 Rn(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 ba(n){for(let e=n;e;e=e.parent)if(!e.visible)return!1;return!0}function zn(n){for(let e=n;e;e=e.parent){let t=e.userData.levelId;if(typeof t=="string")return t}return null}var st=class{constructor(e,t,i){this.solids=e;this.objects=t;this.view=i}raycaster=new na;projector(){let e=this.view.camera(),t=this.view.viewport();return e&&t?ha(e,t):null}screenOf(e){let t=this.projector();return t?Bn(t,Rn(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(!ba(i.object))continue;let r=zn(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=zn(t.object),r=i?this.solids.get(i):void 0,s=pa(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?Bn(i,Rn(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 fa(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 va(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 Ln(e.x,e.y,e.z),r=i.clone().project(t);this.raycaster.setFromCamera(new sa(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-da*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 Fn=Object.freeze({x:0,y:0,z:0});function Ei(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function Pa(n,e){return{x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}}function In(n,e){return n.x*e.x+n.y*e.y+n.z*e.z}function Gn(n,e){let t=In(e,e);if(t<1e-24)return n;let i=In(n,e)/t;return ue({x:n.x-e.x*i,y:n.y-e.y*i,z:n.z-e.z*i})}function Mi(n){return Math.hypot(n.x,n.y,n.z)<1e-9}function Hn(n,e){return n.x===e.x&&n.y===e.y&&n.z===e.z}function jn(n){return Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.z)}function Me(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 ot(n){try{return n()??void 0}catch{return}}var at=class{constructor(e,t,i,r,s){this.faces=e;this.solids=t;this.measure=i;this.step=r;this.extrude=s,this.groups=Me(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=x(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&&ot(()=>wa(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&&ot(()=>Ca(o,s.map(l=>l.planes[0]??-1),e));if(!a)return;i.set(r,a)}return{solids:i,added:[]}}},lt=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=Me(e)}delta=Fn;shown=null;groups;update(e){let t=k(e,this.plane.normal,this.plane.distance);if(!t)return;let i=this.snapped(Ei(t,this.grabbed));if(!jn(i)||Hn(i,this.delta))return;let r=Mi(i)?null:this.build(i);r!==void 0&&(this.delta=i,this.shown=r)}preview(){return this.shown}finish(){return Mi(this.delta)?null:{kind:"element-move",elements:this.elements.map(F),delta:{...this.delta}}}snapped(e){let t=this.snapTo?Ei(I(Pa(this.snapTo,e),this.step),this.snapTo):I(e,this.step);return Gn(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&&ot(()=>Sa(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:[]}}},ct=class{constructor(e,t,i,r,s){this.faces=e;this.solids=t;this.plane=i;this.grabbed=r;this.step=s;this.groups=Me(e)}delta=Fn;shown=null;groups;update(e){let t=k(e,this.plane.normal,this.plane.distance);if(!t)return;let i=ue(I(Ei(t,this.grabbed),this.step));if(!jn(i)||Hn(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!Mi(Gn(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&&ot(()=>xa(s,r.map(a=>a.planes[0]??-1),e));if(!o)return;t.set(i,o.planes)}return{solids:t,added:[]}}};import{BufferGeometry as Ea,Float32BufferAttribute as Ma}from"three";function Zn(n,e,t,i){for(let r of n.faces){let s=e.length/3;for(let o of r.indices){let a=n.vertices[o];e.push(a.x,a.y,a.z)}for(let o=1;o<r.indices.length-1;o+=1)t.push(s,s+o,s+o+1),i?.push(r.planeIndex)}}function Nn(n,e){let t=new Ea;return t.setAttribute("position",new Ma(n,3)),t.setIndex(e),t.computeVertexNormals(),t}function Y(n){let e=[],t=[],i=[];Zn(n,e,t,i);let r=Nn(e,t);return r.userData.trianglePlanes=i,r}function Un(n){let e=[],t=[];for(let i of n)Zn(i,e,t);return Nn(e,t)}import{Euler as Da,Quaternion as Ti,Vector3 as De}from"three";import{brushCenter as Ta,elementPositions as ka,moveElements as Ba,rotateBrush as Ra,scaleBrush as za,translateBrush as La}from"@zylem/bridge";var Oa=.001;function Wn(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 dt(n,e){return n.doodads.find(t=>t.id===e)?.pose??n.entities.find(t=>t.id===e)?.pose??null}function _a(n){let e=n.position??{x:0,y:0,z:0},t=n.rotation??{x:0,y:0,z:0},i=n.quaternion??new Ti().setFromEuler(new Da(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 Kn(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)?dt(n.document,s):null;if(!a)continue;let l=n.document.entities.find(c=>c.id===s);r.poses.set(s,{pose:_a(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 qn(n,e,t){let i=[];if((n.elementMode??"object")==="object")for(let r of n.selectedIds){let s=e.get(r),o=s?Ta(s.planes):null;o?i.push(o):t.has(r)&&i.push(dt(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?ka(s.planes,{kind:r.kind,planes:r.planes}):null;o&&o.length>0&&i.push(Wn(o))}return i.length>0?Wn(i):null}function Va(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 Aa(n,e){switch(e.kind){case"translate":return La(n,e.delta);case"rotate":return Ra(n,e.axis,e.angle,e.pivot);case"scale":return za(n,e.factor,e.pivot)}}function Ia(n,e,t){let i=new De(n.position.x,n.position.y,n.position.z),r=new Ti(n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w),s={...n.scale};switch(e.kind){case"translate":i.add(new De(e.delta.x,e.delta.y,e.delta.z));break;case"rotate":{let o=new De(e.pivot.x,e.pivot.y,e.pivot.z),a=new Ti().setFromAxisAngle(new De(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 Fa(n,e){let t=new Map;if(e.kind==="translate"&&n.elements.length>0){for(let[r,s]of Me(n.elements)){let o=n.solids.get(r),a=o?Ba(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=Aa(s,e);if(!o)return null;t.set(r,o)}let i=new Map;for(let[r,s]of n.poses)i.set(r,Ia(s.pose,e,s.scales));return{solids:t,poses:i}}function Di(n,e){return n===1||!(e>0)?Math.max(n,Oa):Math.max(x(n,e),e)}var ut=class{gizmo=new Ye;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 De(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=Fa(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||Va(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=S(),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=x(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:Di(e.factor.x,o),y:Di(e.factor.y,o),z:Di(e.factor.z,o)};return Number.isFinite(a.x+a.y+a.z)?{kind:"scale",factor:a,pivot:{...t}}:null}}}};import{BufferGeometry as Ga,DoubleSide as Yn,Float32BufferAttribute as Ha,Group as $,Line as $n,LineBasicMaterial as ki,LineSegments as Bi,Mesh as Jn,MeshBasicMaterial as ja,MeshStandardMaterial as Za,Points as es,PointsMaterial as ts}from"three";import{compileBrush as Na,elementPositions as Ua,framePoint as ht,primitiveBrushes as Wa}from"@zylem/bridge";var pt=6737151,Te=16756768,is=13157044,Xn=3752010,ke=15,Ka=4,qa=7,Qn=250,Xa=[{color:16724787,axis:"x"},{color:3394662,axis:"y"},{color:3377407,axis:"z"}];function rs(n){let e=typeof window>"u"?1:window.devicePixelRatio||1;return n*e}function Qa(n){if(!Array.isArray(n)){n.dispose();return}for(let e of n)e.dispose()}function Ri(n){n.traverse(e=>{let t=e;t.geometry?.dispose(),t.material&&Qa(t.material)})}var G=class{constructor(e){this.parent=e}current=null;set(e){this.current!==e&&(this.current&&(this.parent.remove(this.current),Ri(this.current)),this.current=e,e&&this.parent.add(e))}clear(){this.set(null)}};function H(n){let e=new Ga;return e.setAttribute("position",new Ha(n,3)),e}function mt(n){return n.flatMap(e=>[e.x,e.y,e.z])}function zi(n,e){return new ki({color:n,depthTest:!e,transparent:e})}function Ya(n,e){let t=new $n(H(mt([...n,n[0]])),zi(e,!0));return t.renderOrder=ke+1,t}function Li(n,e,t){if(n.length<3)return null;let i=H(mt(n)),r=[];for(let a=1;a<n.length-1;a+=1)r.push(0,a,a+1);i.setIndex(r);let s=new Jn(i,new ja({color:e,transparent:!0,opacity:t,side:Yn,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-4}));s.renderOrder=ke;let o=new $;return o.add(s,Ya(n,e)),o}function Be(n,e){let t=new Bi(H(n.flatMap(([i,r])=>[i.x,i.y,i.z,r.x,r.y,r.z])),zi(e,!0));return t.renderOrder=ke+1,t.frustumCulled=!1,t}function Oi(n,e,t=qa){let i=new es(H(mt(n)),new ts({color:e,size:rs(t),sizeAttenuation:!1,depthTest:!1,transparent:!0}));return i.renderOrder=ke+2,i.frustumCulled=!1,i}function _i(n){return n.edges.map(e=>[n.vertices[e.vertices[0]],n.vertices[e.vertices[1]]])}function ns(n,e){let t=[],i=[];for(let o of n){for(let[a,l]of _i(o))t.push(a.x,a.y,a.z,l.x,l.y,l.z);e&&i.push(...mt(o.vertices))}if(t.length===0)return null;let r=new $;r.name="level-element-wire";let s=new Bi(H(t),zi(Xn,!1));if(s.frustumCulled=!1,r.add(s),i.length>0){let o=new es(H(i),new ts({color:Xn,size:rs(Ka),sizeAttenuation:!1}));o.frustumCulled=!1,r.add(o)}return r}function $a(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 Vi(n,e=is,t=.35){let i=new $;for(let r of n){let s=Na(r);if(!s)continue;let o=new Jn(Y(s),new Za({color:e,transparent:!0,opacity:t,depthWrite:!1,side:Yn}));o.renderOrder=ke-1;let a=new Bi(H($a(s)),new ki({color:e,transparent:!0,opacity:.9}));i.add(o,a)}return i.children.length>0?i:null}function Ja(n,e,t=is){let i=[ht(n,e.u0,e.v0),ht(n,e.u1,e.v0),ht(n,e.u1,e.v1),ht(n,e.u0,e.v1)];return Li(i,t,.25)}function ss(n,e){let t=new $,i=Ja(n.frame,n.footprint);if(i&&t.add(i),n.height){let r=Wa(e.shape,n.frame,n.footprint,n.height,e),s=r?Vi(r):null;s&&t.add(s)}return t}function ft(n){let e=new $;for(let t of Xa){let i={x:n.x,y:n.y,z:n.z},r={x:n.x,y:n.y,z:n.z};i[t.axis]-=Qn,r[t.axis]+=Qn;let s=new $n(H([i.x,i.y,i.z,r.x,r.y,r.z]),new ki({color:t.color,depthTest:!1}));s.frustumCulled=!1,s.renderOrder=20,e.add(s)}return e}function os(n){let[e]=n;if(!e)return null;let t=new $;t.add(Oi(n,Te));let i=[];for(let r=1;r<n.length;r+=1)i.push([n[r-1],n[r]]);return i.length>0&&t.add(Be(i,Te)),t.add(ft(e)),t}function as(n,e,t,i){return n==="face"?Li(e,t,i):n==="edge"&&e.length===2?Be([[e[0],e[1]]],t):n==="vertex"&&e.length>0?Oi(e,t):null}function ls(n,e){let t=new $,i=[],r=[];for(let s of n){let o=e(s.brushId),a=o?Ua(o,{kind:s.kind,planes:s.planes}):null;if(a)if(s.kind==="face"){let l=Li(a,Te,.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(Be(i,Te)),r.length>0&&t.add(Oi(r,Te)),t.children.length>0?t:null}import{compileBrush as el,sectorKey as tl,sectorOf as il}from"@zylem/bridge";import{compileBrush as $d}from"@zylem/bridge";function cs(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 us(n,e){let t=new Map;for(let i of n){let r=el(i.planes),s=r?il(i.planes,e):null;if(!r||!s)continue;let o=tl(s),a=t.get(o);a?a.push(r):t.set(o,[r])}return[...t].map(([i,r])=>({key:i,geometry:Un(r),hulls:r.map(cs)}))}import{BufferGeometry as rl,CanvasTexture as nl,Float32BufferAttribute as sl,Group as ol,LineBasicMaterial as al,LineSegments as ll,SRGBColorSpace as cl,Sprite as ul,SpriteMaterial as dl}from"three";import{sectorBounds as ps,sectorKey as yt,sectorOf as Ii,sectorSizeOf as Fi,sectorTint as hl}from"@zylem/bridge";var pl="level-sector-overlay",ml=7113983,fl=.55,de=.01,gt=1,ds=128,gl=256,yl=.9,vl=.35,bl=.25,hs=.04;function ms(n,e){let t=e.hiddenSectors;if(!t||t.length===0)return!1;let i=Ii(n,Fi(e.document));return i!==null&&t.includes(yt(i))}function Gi(n,e){if(!e.showSectorTint)return null;let t=Ii(n,Fi(e.document));return t?hl(t):null}function wl(n,e){let t=new Map;for(let i of n.document.solids){let r=Ii(i.planes,e);r&&t.set(yt(r),r)}return t}function Sl(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-gt,maxX:e.maxX+gt,minZ:e.minZ-gt,maxZ:e.maxZ+gt}}function Cl(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 xl(n,e){let t=[];for(let i of n){let{min:r,max:s}=ps(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 Pl(n){let e=new rl;e.setAttribute("position",new sl(n,3));let t=new ll(e,new al({color:ml,transparent:!0,opacity:fl,depthWrite:!1}));return t.frustumCulled=!1,t}var Ai=new Map;function El(n){if(Ai.has(n))return Ai.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 nl(e),i.colorSpace=cl),Ai.set(n,i),i}function Ml(n,e,t){let i=yt(n),r=El(i);if(!r)return null;let s=new ul(new dl({map:r,transparent:!0,opacity:t?vl:yl,depthTest:!1,depthWrite:!1})),o=e*bl,{min:a}=ps(n,e);return s.name=`sector-label:${i}`,s.scale.set(o,o/4,1),s.position.set(a.x+e*hs+o/2,de,a.z+e*hs+o/8),s.renderOrder=5,s}function*Dl(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 fs(n){let e=Fi(n.document),t=wl(n,e),i=Sl(t.values()),r=i.maxX-i.minX+1,s=i.maxZ-i.minZ+1,o=r>ds||s>ds,a=new ol;a.name=pl,a.add(Pl(o?xl(t.values(),e):Cl(i,e)));let l=new Set(n.hiddenSectors??[]),c=r*s>gl?t.values():Dl(i);for(let u of c){let d=Ml(u,e,l.has(yt(u)));d&&a.add(d)}return a}import{Group as Tl,Mesh as gs}from"three";import{compileBrush as ys}from"@zylem/bridge";var vt=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 Tl;for(let[s,o]of e.solids){let a=ys(o),l=this.scene.solids.get(s)?.planes??o;a&&i.add(new gs(Y(a),this.scene.material(s,l)))}for(let s of e.split.values())s.forEach((o,a)=>{let l=ys(o);l&&i.add(new gs(Y(l),this.scene.half(a)))});let r=e.added.length>0?Vi(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 Wl=13157044,Kl=14998992,ql=["#5aa9ff","#ff9a5a"],Xl=4,Ss=null;function kh(){return Ss}function Hi(n){Ss=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 Zi(n,e){let t=n.size;return{x:t?.x??e.x,y:t?.y??e.y,z:t?.z??e.z}}function bs(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 Ql(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 Yl(n,e){let t=K(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 Ql(s)}}catch{}let i=Zi(e,{x:1,y:1,z:1});return new wt(new ws(i.x,i.y,i.z),new Ni({color:13157044}))}function ji(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 bt(n,e=null){let t=new Ni({color:e??(n?Kl:Wl),side:zl,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});return e&&n&&t.color.lerp(new Rl(16777215),.35),t}function he(n,e,t,i){return{id:n,...e?{elements:e}:{},...t?{additive:!0}:{},...i?{ungroup:!0}:{}}}function $l(n){return`${n.brushId}:${n.kind}:${n.planes.join(",")}`}var St=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 st(this.solids,this.objects,{camera:()=>e.camera(),viewport:()=>e.viewport()}),this.preview=new vt(this.tools,{solids:this.solids,objects:this.objects,selection:()=>this.selectionView,material:(t,i)=>bt(this.isObjectSelected(t),this.sectorTint(i)),half:t=>bt(!1,ql[t%2]),restore:(t,i)=>{let r=this.payload?dt(this.payload.document,t):null;r&&ji(i,r)}})}root=new vs;tools=new vs;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 rt;clipTool=new it;clipCursor=null;gizmo=new ut;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,Hi(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},Hi(e),this.rebuild()}close(){this.generation+=1,this.cancelGesture(),this.payload=null,Hi(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?ft(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 ct(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?jl(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?Kn(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=Vn(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)>=Xl}dragSet(e){let t=this.payload?.elements??[];return t.some(i=>An(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,bs(r.normal),J(e),this.viewBasis()),o=this.dragSet(t.ref);return new at(o,this.startPlanes(o),s,this.snapStep(),i.altKey===!0)}elementDrag(e){let t=this.dragSet(e.ref),i=Sn(this.host.cameraId(),this.host.viewDirection(),e.point),r=t.length===1&&e.ref.kind==="vertex"?e.corners[0]??null:null;return new lt(t,this.startPlanes(t),i,e.point,r,this.snapStep())}drawStart(e){let t=this.picker.face(e);if(t)return{frame:Zl(t.plane.normal,t.plane.distance),point:t.point};let i=Si(this.host.cameraId(),this.host.viewDirection()),r=Ee(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 Ci(i.point,i.plane,t);let r=Ee(Si(this.host.cameraId(),this.host.viewDirection())),s=k(J(e),r.normal,r.distance);return s?Ci(s,r,t):null}drawShape(){return{...this.payload?.drawShape??Il}}commitDraw(){let e=this.drawTool.commit(this.drawShape()),t=e?.shape;if(e&&t&&Nl(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?ss(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(os(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?Hl(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?$l(i.ref):null,()=>i?as(i.ref.kind,i.corners,pt,.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 Be(_i(t.topology),pt);let i=this.objects.get(e);if(!i)return null;let r=new kl().setFromObject(i);return r.isEmpty()?null:new Bl(r,pt)}isObjectSelected(e){return this.elementMode()==="object"&&(this.payload?.selectedIds.includes(e)??!1)}sectorTint(e){return this.payload?Gi(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 Al().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?bs(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?qn(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 us(e.solids,Ul(e))){let i=new wt(t.geometry,bt(!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(ms(s.planes,e))continue;let o=Gl(s.planes);if(!o)continue;let a=this.isObjectSelected(s.id),l=new wt(Y(o),bt(a,Gi(s.planes,e)));l.userData.levelId=s.id,this.root.add(l);let c=a?Fl(s.planes):null,u=c?ft(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=fs(e);s&&this.root.add(s)}if(t&&r!=="object"){let s=[...this.solids.values()].map(a=>a.topology),o=ns(s,r==="vertex");o&&this.root.add(o),this.selectionView=ls(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=Yl(s.typeId,s.props);ji(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 wt(new Vl(.3),new Ni({color:14904020}));ji(o,s.pose),o.userData.levelId=s.id,this.root.add(o),this.objects.set(s.id,o)}}triggerOutline(e){let t=Zi(e,{x:2,y:2,z:2});return new _l(new Ll(new ws(t.x,t.y,t.z)),new Ol({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:Zi(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=X(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=S().translate;return e>0?e:1}snapStep(){let e=S();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),Ri(e))}unmount(){this.mounted&&(this.host.getScene()?.remove(this.root),this.mounted=!1)}};var Ct=!1,B={},Cs=0,xs=0,Re=null;function Ps(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ui(){return Ct?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(Ct=!0),Ct)}function Rh(n){Ct=n,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=n)}function Wi(n){Ui()&&(Re=n,xs=Ps())}function Ki(){if(!Ui()||Re===null)return;let n=Ps()-xs;B[Re]=(B[Re]??0)+n,Re=null}function Es(){if(!Ui()||(Cs++,Cs%60!==0))return;let n=Object.values(B).reduce((t,i)=>t+(i??0),0),e=Object.keys(B).sort((t,i)=>(B[i]??0)-(B[t]??0)).map(t=>{let i=B[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(B))B[t]=0}function R(n,e){Wi(n);try{return e()}finally{Ki()}}var f={FirstPerson:"first-person",ThirdPerson:"third-person",SecondPerson:"second-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};function qi(n){switch(n){case f.Isometric:case f.TopDown:case f.Flat2D:case f.Fixed2D:return"orthographic";default:return"perspective"}}import{Vector3 as Jl,Quaternion as ec,MathUtils as Xi}from"three";function xt(){return{position:new Jl(0,0,10),rotation:new ec,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 Ms(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 Ds(n,e,t,i){let r=1-Math.pow(1-Xi.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=Xi.lerp(s.fov,e.fov,r)),e.zoom!=null&&s.zoom!=null&&(s.zoom=Xi.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 Pt=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=xt();_finalPose=xt();_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):xt(),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=Ms(t,o),s.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=Ds(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 Et}from"three";var tc={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={...tc,...r},this.initialPosition=t?g(t,T):void 0,this.initialLookAt=i?g(i,T):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 Et,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 Et,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 Et,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 Et,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 Ts,Quaternion as ic}from"three";var ks={position:{x:0,y:0,z:10},zoom:10},me=class{id="fixed-2d";projection="orthographic";defaults={damping:1};opts;constructor(e){this.opts={...ks,...e,position:g(e?.position,ks.position)}}getBasePose(e){return{position:new Ts(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new ic,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new Ts(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as Qi,Quaternion as Yi,Euler as zs,MathUtils as P}from"three";var rc={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},ze=class{id="first-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new Yi;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...rc,...r},this.initialPosition=t?g(t,T):void 0,this.initialLookAt=i?g(i,T):void 0,this._currentFov=this.opts.defaultFov,this._targetFov=this.opts.defaultFov,this._lookAtLerpSpeed=this.opts.lookAtLerpSpeed,this.initialPosition&&this.initialLookAt&&this.deriveYawPitchFromLookAt(this.initialPosition,this.initialLookAt)}look(e,t){this._yaw+=e,this._pitch=P.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=P.clamp(t,-this.opts.pitchLimit,this.opts.pitchLimit)}setEyeHeight(e){this.opts.eyeHeight=e}get yaw(){return this._yaw}get pitch(){return this._pitch}zoom(e){this._targetFov=e}resetZoom(){this._targetFov=this.opts.defaultFov}get currentFov(){return this._currentFov}lookAt(e,t){this._lookAtTarget=e,t!=null&&(this._lookAtLerpSpeed=t)}clearLookAt(){this._lookAtTarget&&this.deriveYawPitchFromQuaternion(this._currentRotation),this._lookAtTarget=null}getBasePose(e){let t=this.computePosition(e),i=this.computeRotation(t,e.dt);return this._currentFov=this.lerpFov(e.dt),{position:t,rotation:i,fov:this._currentFov,near:.1,far:1e3}}computePosition(e){let t=e.targets[this.opts.targetKey];if(t){let i=t.position.y+this.opts.eyeHeight,r=this.smoothVertical(i,e.dt);return new Qi(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new Qi(0,this.opts.eyeHeight,0)}smoothVertical(e,t){if(this.opts.verticalSmoothing>=1)return this._smoothedY=e,e;if(this._smoothedY==null)return this._smoothedY=e,e;let i=P.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=P.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new Yi().setFromEuler(new zs(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=Bs.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let s=Math.atan2(-r.x,-r.z),o=Math.asin(P.clamp(r.y,-1,1)),a=nc.setFromEuler(Rs.set(o,s,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(a,P.clamp(l,0,1)),this._currentRotation.clone()}}return this._currentRotation.copy(i),i}lerpFov(e){if(Math.abs(this._currentFov-this._targetFov)<.01)return this._targetFov;let t=1-Math.pow(1-Math.min(this.opts.fovLerpSpeed*e,1),1);return P.lerp(this._currentFov,this._targetFov,P.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=Bs.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(P.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=Rs.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=P.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},Bs=new Qi,nc=new Yi,Rs=new zs;import{Quaternion as sc,Vector3 as $i}from"three";var oc={distance:10,zoom:10,targetKey:"primary"},Ls=new $i(1,1,1).normalize(),Le=class{id="isometric";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...oc,...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(Ls,this.opts.distance);return this.pose(r,i)}staticPose(){return this.initialPosition?this.pose(this.initialPosition.clone(),this.initialLookAt?.clone()??new $i(0,0,0)):this.pose(Ls.clone().multiplyScalar(this.opts.distance),new $i(0,0,0))}pose(e,t){return{position:e,rotation:new sc,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as ac,Vector3 as Mt}from"three";var lc={height:10,zoom:10,targetKey:"primary"},Oe=class{id="top-down";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...lc,...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 Mt(i.x,i.y+this.opts.height,i.z),i)}staticPose(){if(this.initialPosition){let e=this.initialLookAt?.clone()??new Mt(this.initialPosition.x,this.initialPosition.y-this.opts.height,this.initialPosition.z);return this.pose(this.initialPosition.clone(),e)}return this.pose(new Mt(0,this.opts.height,0),new Mt(0,0,0))}pose(e,t){return{position:e,rotation:new ac,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as Os,Vector3 as Dt}from"three";var cc={anchorKey:"anchor",subjectKey:"primary",eyeHeight:1.7,fov:75},Ji=new Dt,_e=class{id="second-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...cc,...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 Dt(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 Os,fov:this.opts.fov,near:.1,far:1e3,lookAt:s}}staticPose(){let e=this.initialPosition?.clone()??new Dt(0,this.opts.eyeHeight,0),t=this.initialLookAt?.clone()??e.clone().add(new Dt(0,0,-1));return{position:e,rotation:new Os,fov:this.opts.fov,near:.1,far:1e3,lookAt:t}}anchorForward(e){return Ji.set(0,0,-1),e&&Ji.applyQuaternion(e),Ji.clone()}};function te(n,e){switch(n){case"third-person":return new pe(e);case"first-person":return new ze(e);case"second-person":return new _e(e);case"isometric":return new Le(e);case"top-down":return new Oe(e);case"flat-2d":return new me(e);case"fixed-2d":return new me(e);default:return new pe(e)}}import{Vector2 as yc,Vector3 as y,OrthographicCamera as tr,PerspectiveCamera as Bt}from"three";import{PerspectiveCamera as er,Vector3 as dc,OrthographicCamera as Ve,RenderTarget as hc,LinearFilter as _s}from"three";import{Vector3 as Tt}from"three";import{OrbitControls as uc}from"three/addons/controls/OrbitControls.js";var kt=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new Tt;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 Tt().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=Cr(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 uc(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 Tt),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 Tt;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={...mn};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 dc(0,0,0));let s=te(e);this.pipeline=new Pt(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 kt(this.camera,this._rendererManager.renderer.domElement,null),this.orbitController.setScene(e),this.isDebugViewCamera&&this.orbitController.setDebugViewCamera(!0),this._useOrbitalControls&&this.orbitController.enableUserOrbitControls())}async setupLegacy(e){this._rendererManager||(this._rendererManager=new $e(this.screenResolution),await this._rendererManager.initRenderer(),this._rendererManager.setupPostProcessing(e,this.camera),this._rendererManager.startRenderLoop(()=>{this._rendererManager&&this.sceneRef&&(this.isOrbitActive&&this.updateOrbitControls(),this._rendererManager.render(this.sceneRef,this.camera))})),await this.setup(e,this._rendererManager)}update(e){if(this.isDebugModeActive()||this._useOrbitalControls)return;this._elapsedTime+=e;let t=this.buildContext(e),i=this.pipeline.run(t);this.commitPose(i)}isDebugModeActive(){return this.orbitController?.isActive??!1}get isOrbitActive(){return this.orbitController?.isOrbitActive??!1}updateOrbitControls(){this.orbitController?.update()}enableOrbitalControls(){this._useOrbitalControls=!0,this.orbitController?.enableUserOrbitControls()}disableOrbitalControls(){this._useOrbitalControls=!1,this.orbitController?.disableUserOrbitControls()}armEditorOrbit(e,t=!1){this._skipDebugOrbit=!0,this.orbitController?.setScreenSpacePanning(t),this.orbitController?.setRotationLocked(e),this.enableOrbitalControls(),this.setOrbitInteractionEnabled(!0)}allowFullOrbit(){this.orbitController?.setFullPolarRange(!0)}disarmEditorOrbit(){this.setOrbitInteractionEnabled(!1)}get useOrbitalControls(){return this._useOrbitalControls}addTarget(e){this.targets.includes(e)||this.targets.push(e)}removeTarget(e){let t=this.targets.indexOf(e);t!==-1&&this.targets.splice(t,1)}clearTargets(){this.targets=[]}setViewport(e,t,i,r){this.viewport={x:e,y:t,width:i,height:r}}resize(e,t){if(this.screenResolution.set(e,t),this.camera instanceof er&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof Ve){let i=e/t;this.camera.left=this.frustumSize*i/-2,this.camera.right=this.frustumSize*i/2,this.camera.top=this.frustumSize/2,this.camera.bottom=this.frustumSize/-2,this.camera.updateProjectionMatrix()}}createRenderTarget(e=512,t=512){return this.renderTarget&&this.renderTarget.dispose(),this.renderTarget=new hc(e,t,{minFilter:_s,magFilter:_s}),this.renderTarget}getRenderTexture(){return this.renderTarget?.texture??null}destroy(){try{this.orbitController?.dispose()}catch{}try{this.renderTarget?.dispose()}catch{}this.renderTarget=null,this.sceneRef=null,this.targets=[],this._rendererManager=null}setDefaultOrbitTarget(e){this.orbitController?.setDefaultOrbitTarget(e)}seedDebugOrbitPose(e,t){this.isDebugViewCamera&&this.isDebugOrbitPoseSeeded()||this.orbitController?.seedOrbitPose(e,t)}replaceOrbitPose(e,t){if(this.orbitController){this.orbitController.seedOrbitPose(e,t);return}this.camera.position.copy(e),this.camera.lookAt(t)}applyOrthographicFrame(e,t,i){let r=this.camera;if(!(r instanceof Ve))return;this.frustumSize=e;let 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 er&&(e.fov!=null&&(this.camera.fov=e.fov),e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()),this.camera instanceof Ve){if(e.zoom!=null){let t=this.screenResolution.x/this.screenResolution.y,i=e.zoom;this.camera.left=-i*t/2,this.camera.right=i*t/2,this.camera.top=i/2,this.camera.bottom=-i/2}e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()}}applyPerspective(e,t){this._perspective=e,this.pipeline.setPerspective(t),this.ensureProjection(t.projection??qi(e))}ensureProjection(e){if((this.camera instanceof Ve?"orthographic":"perspective")===e)return;let i=this.screenResolution.x/Math.max(this.screenResolution.y,1),r=e==="orthographic"?this.createOrthographicCamera(i):this.createPerspectiveCamera(i);if(r.position.copy(this.camera.position),r.quaternion.copy(this.camera.quaternion),r.up.copy(this.camera.up),r.layers.mask=this.camera.layers.mask,r.name=this.camera.name,"near"in this.camera&&"near"in r){let o=this.camera,a=r;a.near=o.near,a.far=o.far,a.zoom=o.zoom,a.updateProjectionMatrix()}let 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 qi(this._perspective)==="orthographic"?this.createOrthographicCamera(e):this.createPerspectiveCamera(e)}createPerspectiveCamera(e){return new er(75,e,.1,1e3)}createOrthographicCamera(e){return new Ve(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3)}};import{OrthographicCamera as pc,PerspectiveCamera as mc,Vector3 as Vs}from"three";var fc=4;function As(n,e){if(n instanceof mc){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 pc){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 Is(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 gc(n){return Math.max(n.max.x-n.min.x,n.max.y-n.min.y,n.max.z-n.min.z)}function Fs(n,e){let t=fc*Math.max(e.width,e.height);return n.filter(i=>{if(i.isEmpty())return!1;let r=gc(i);return Number.isFinite(r)&&r<=t})}function Gs(n,e,t,i,r,s){let o=r.width/2,a=r.height/2,l=new Vs;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 D of p)for(let Ge of v)l.set(W,D,Ge).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 Hs(n,e,t,i){if(t.length===0)return i;let r=1/0,s=-1/0,o=new Vs;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 D=o.dot(e);r=Math.min(r,D),s=Math.max(s,D)}}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 js=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:-js,far:js}:{},position:(o,a)=>o.clone().addScaledVector(s,a),up:()=>i.clone()}}var fe=new y(0,1,0),vc=new y(0,0,-1),bc=new y(0,0,1),ir=[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),vc),Z(m.bottom,f.TopDown,new y(0,-1,0),bc),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 rr(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 Rt=class{cameras=new Map;_activeCameras=[];_editorCameras=new Map;_lockedEditorIds=new Set;_screenSpacePanIds=new Set;_framedEditorViews=new Set;_entityBounds=null;_rememberedGameCamera=null;_editorViewLocked=!1;_suspendedOrbits=new Set;_editorCamerasPromise=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;_unregisterEditorHost=null;get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}isEditorViewActive(){return this._editorViewLocked}activeEditorCameraId(){let e=this.primaryCamera;if(!e||!this._editorViewLocked)return null;for(let[t,i]of this._editorCameras)if(i===e)return t;return null}hasEditorCameras(){return this._editorCameras.size>0}setEditorEntityBounds(e){this._entityBounds=e}syncFreeCameraToGame(){let e=()=>{this.copyFreeFromGame()&&this.activateCameraById(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=Mr(this),Ze()&&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()}activateCameraById(e){if(e===Er){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 yc(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._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=rr(e.camera),i=this._rendererManager.screenResolution.clone(),r=Math.max(t.distance,4);this.isEditorCamera(e)||(this._rememberedGameCamera=e);for(let s of ir){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 tr||o.camera instanceof Bt)&&(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),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 ir.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=rr(i);return e.camera.up.copy(i.up),(i instanceof Bt||i instanceof tr)&&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 Bt&&(e instanceof Bt?(r.fov=e.fov,r.zoom=e.zoom,r.near=e.near,r.far=e.far):e instanceof tr&&(r.fov=Is(e,i),r.zoom=1),r.updateProjectionMatrix())}frameOrthographicView(e,t){let i=ir.find(To=>To.id===e),r=this.gameCameraToRestore();if(!i||!r)return!1;let s=r.camera;s.updateMatrixWorld(!0);let o=rr(s),a=As(s,o.distance),l=Fs(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),D=Gs(o.lookAt,d,p,l,a,W),Ge=Hs(t.camera.position,v,l,{near:i.near??.1,far:i.far??2e3});return t.applyOrthographicFrame(D,Ge.near,Ge.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 E=class{cameraRef;constructor(e){this.cameraRef=e}addTarget(e){this.cameraRef.addTarget(e)}removeTarget(e){this.cameraRef.removeTarget(e)}clearTargets(){this.cameraRef.clearTargets()}enableOrbitalControls(){this.cameraRef.enableOrbitalControls()}disableOrbitalControls(){this.cameraRef.disableOrbitalControls()}setViewport(e,t,i,r){this.cameraRef.setViewport(e,t,i,r)}addBehavior(e,t){this.cameraRef.pipeline.addBehavior(e,t)}removeBehavior(e){return this.cameraRef.pipeline.removeBehavior(e)}addAction(e){this.cameraRef.pipeline.addAction(e)}setPerspective(e,t){this.cameraRef.applyPerspective(e,te(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function am(n){let e=Br(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,T),s=g(n.target,T);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 E(i)}import{Vector3 as wc}from"three";function N(n){return!!n&&typeof n=="object"&&typeof n.create=="function"}function Ae(n){return!!n&&typeof n.then=="function"}function nr(n){return!!n&&typeof n=="object"&&n instanceof E}function Zs(n){return!n||typeof n!="object"||N(n)||nr(n)||Ae(n)||typeof n.then=="function"?!1:n.constructor===Object||n.constructor?.name==="Object"}function Ns(n){return n?!!(N(n)||typeof n=="function"||Ae(n)):!1}var Sc="/three/basis/";function Lt(n){return{...n,ktx2TranscoderPath:n?.ktx2TranscoderPath??Sc}}var zt=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 Cc(){return new zt({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},Xe,null,null,new wc(0,0,0),{},60,{},!0)}function Us(n=[]){let e=Cc(),t={},i=[],r=[],s=[];for(let l of n)nr(l)?s.push(l):N(l)?i.push(l):Ns(l)&&!N(l)?r.push(l):Zs(l)&&(t={...t,...l});let o=new zt(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 fm(n){return{...n}}var xc=Symbol("vessel"),Ie=class extends be{static type=xc;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=Pc();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function Pc(...n){let e=new Ie;return n.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Eo,Vector3 as Mo}from"three";import{createSimulation as Ec}from"@zylem/behaviors/core";function sr(n){return typeof n?.handlePostCollision=="function"&&typeof n?.handleIntersectionEvent=="function"}function Mc(n,e){return n<e?`${n}|${e}`:`${e}|${n}`}var Ot=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 Ec({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 Ke)&&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 Nr(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=Mc(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(!sr(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,oi.globals,r);let a=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);a&&l&&l._collision(a,oi.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&sr(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&&sr(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 Dc,Color as Ws,AmbientLight as Tc,DirectionalLight as kc,Vector3 as _t,GridHelper as Bc,Texture as Rc,SRGBColorSpace as zc}from"three";var Vt=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new Dc,o=i.backgroundColor instanceof Ws?i.backgroundColor:new Ws(i.backgroundColor);r.background=o,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&se.loadTexture(i.backgroundImage,{colorSpace:zc}).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(!Ne(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:C()})}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 Rc&&(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 Tc(16777215,1);e.add(t);let i=new kc(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 _t(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(q(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Lc(e);i&&i.attachToScene(this.scene);let r=e.options.position??new _t(0,0,0);if(e.physicsAttached&&e.body)try{let s=e.body.translation();r=new _t(s.x,s.y,s.z)}catch{r=e.options.position??new _t(0,0,0)}this.add(t,r),we(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new Bc(1e3,100);this.scene.add(i)}};function Lc(n){return n.constructor.type===Ur?n:null}var At=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 Oc}from"three";var Ks=new Oc;function qs(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&&(Ks.set(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w),s.setRotationFromQuaternion(Ks))}}import{nanoid as Gu}from"nanoid";import{Box3 as Qt,BufferAttribute as vo,BufferGeometry as Pu,LineBasicMaterial as Eu,LineSegments as Mu,Raycaster as Du,Vector2 as Tu,Vector3 as Yt}from"three";import{subscribe as ku}from"valtio/vanilla";import{nanoid as bo}from"nanoid";import{getZylemBridge as wo}from"@zylem/bridge";import{StageBodyKind as Bu}from"@zylem/behaviors/core";import{Box3 as _c,BoxGeometry as Xs,Color as Vc,EdgesGeometry as Qs,Group as Ac,LineBasicMaterial as Ic,LineSegments as Fc,Mesh as Gc,MeshBasicMaterial as Hc,Vector3 as Ys}from"three";var It=class{scene;container;fillMesh;edgeLines;currentColor=new Vc(65280);bbox=new _c;size=new Ys;center=new Ys;constructor(e){this.scene=e;let t=new Xs(1,1,1);this.fillMesh=new Gc(t,new Hc({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new Qs(t);this.edgeLines=new Fc(i,new Ic({color:this.currentColor,linewidth:1})),this.container=new Ac,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 Xs(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 Qs(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 jc,BoxGeometry as Zc,Group as Nc,Mesh as Uc,MeshBasicMaterial as Wc,Vector3 as $s}from"three";var Kc={x:0,y:0,z:0},qc=7128319,Xc=.35;function Qc(){return new Wc({color:qc,transparent:!0,opacity:Xc,depthWrite:!1})}function Yc(n){let e=n.size;return new $s(e?.x??1,e?.y??1,e?.z??1)}function $c(n,e){try{let t=n.create({position:Kc,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 Jc(n,e){n.traverse(t=>{let i=t;i.isMesh&&(i.material=e,i.castShadow=!1,i.receiveShadow=!1)})}var Ft=class{scene;container;builtFor=null;builtProps=null;material=null;extent=null;bounds=new jc;constructor(e){this.scene=e,this.container=new Nc,this.container.name="PlacementGhost",this.container.visible=!1,this.scene.add(this.container)}setType(e,t){let i=t??null;if(e===this.builtFor&&i===this.builtProps)return;if(this.builtFor=e,this.builtProps=i,this.clearSilhouette(),!e){this.hide();return}let r=K(e),s={...r?.defaultProps??{},...t??{}},a=(r?$c(r,s):null)??new Uc(new Zc(...Yc(s).toArray()));a.position.set(0,0,0),this.material=Qc(),Jc(a,this.material),this.container.add(a),this.bounds.setFromObject(a),this.extent=this.bounds.isEmpty()?null:this.bounds.getSize(new $s)}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 ru,Quaternion as Zt,Vector3 as M}from"three";import{nanoid as nu}from"nanoid";import{Vector3 as ge}from"three";var ar=.95,eu=16,Fe=new ge,tu=new ge,Js=new ge,or=new ge;function eo(n){return n?n.isPerspectiveCamera===!0||n.isOrthographicCamera===!0:!1}function Gt(n,e,t=ar){return Fe.copy(n).project(e),Math.abs(Fe.x)<=t&&Math.abs(Fe.y)<=t&&Fe.z>=-1&&Fe.z<=1}function to(n){let e=0,t=1;for(let i=0;i<eu;i+=1){let r=(e+t)/2;n(r)?e=r:t=r}return e}function io(n,e,t,i=ar){if(!eo(t))return e.clone();let r=t;if(Gt(e,r,i)||!Gt(n,r,i))return e.clone();let s=to(o=>Gt(tu.copy(n).lerp(e,o),r,i));return n.clone().lerp(e,s)}function ro(n,e,t,i,r=ar){if(!eo(i)||t.x<=1&&t.y<=1&&t.z<=1||n.isEmpty())return t.clone();let s=i;Js.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),iu(n,Js,o,s,r));if(a(1))return t.clone();let l=to(a);return new ge(1+(t.x-1)*l,1+(t.y-1)*l,1+(t.z-1)*l)}function iu(n,e,t,i,r){for(let s=0;s<8;s+=1)if(or.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),or.sub(e).multiply(t).add(e),!Gt(or,i,r))return!1;return!0}var su={translate:"Move",rotate:"Rotate",scale:"Scale"};function lr(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 M(i.x,i.y,i.z),quaternion:new Zt(r.x,r.y,r.z,r.w),scale:new M(s.x,s.y,s.z)}}function no(n){let e=ui(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 ou(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 Ht(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 au(n){let e=n?.group??n?.mesh;if(!e?.isObject3D)return null;let t=new ru().setFromObject(e);return t.isEmpty()?null:t}var cr=.02,ur=50;function lu(n){return new M(dr(n.x,cr,ur),dr(n.y,cr,ur),dr(n.z,cr,ur))}function dr(n,e,t){return Math.min(Math.max(n,e),t)}var hr=new Zt,cu=new M,jt=class{gizmo=new Ye;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:lr(o),startBounds:this.mode==="scale"?au(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=S(),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=lr(i.entity);ou(i.start,r)&&(e.mode==="scale"&&di(i.entity),t.push({uuid:i.uuid,before:no(i.start),after:no(r)}))}t.length&&ve({opId:nu(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=cu.copy(e.pivotStart).add(t),o=io(e.pivotStart,s,r),a=i>0?ne(o,i):o,l=new M(a.x-e.pivotStart.x,a.y-e.pivotStart.y,a.z-e.pivotStart.z);for(let c of e.entries)Ht(c.entity,{position:c.start.position.clone().add(l)})}applyRotate(e,t,i,r){let s=e.axis;for(let o of e.entries){hr.setFromAxisAngle(t,i);let a=hr.clone().multiply(o.start.quaternion),l=a;if(r>0&&(s==="x"||s==="y"||s==="z")){let u=ui(a);u[s]=Tr(u[s],r);let d=ci(u);l=new Zt(d.x,d.y,d.z,d.w)}let c=o.start.position.clone().sub(e.pivotStart).applyQuaternion(hr).add(e.pivotStart);Ht(o.entity,{position:c,quaternion:l})}}applyScale(e,t,i,r){for(let s of e.entries){let o=s.startBounds?ro(s.startBounds,s.start.position,t,r):t,a=lu(o),l=new M(s.start.scale.x*a.x,s.start.scale.y*a.y,s.start.scale.z*a.z),c=i>0?kr(l,i):l;Ht(s.entity,{scale:new M(c.x,c.y,c.z)})}}describeOperation(e){let t=su[e.mode];if(e.entries.length>1)return`${t} ${e.entries.length} entities`;let i=e.entries[0]?.entity,r=i?.name||String(i?.constructor?.type??"").replace("Symbol(","").replace(")","")||"Entity";return`${t} ${r}`}selectionPivot(){let e=h.selectedEntityIds;if(!e.length)return null;let t=new M,i=0;for(let r of e){let s=this.context.resolveEntity(r);s&&(t.add(lr(s).position),i++)}return i?t.divideScalar(i):null}};function so(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?ci(r.rotation):void 0);Ht(s,{position:r.position?new M(r.position.x,r.position.y,r.position.z):void 0,quaternion:o?new Zt(o.x,o.y,o.z,o.w):void 0,scale:r.scale?new M(r.scale.x,r.scale.y,r.scale.z):void 0}),r.scale&&di(s)}}var uu=200;function oo(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function du(n){return oo(n)&&(Ne(n)||zr(n))}var Nt=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(!oo(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=We("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(!du(s))return{ok:!1,reason:"invalid-props"};let o=e.setMaterial({shader:s},{disposePrevious:!1});return o?(i.previousMaterials?pr(o,i.previousMaterials):i.previousMaterials=o,{ok:!0,replaced:!1}):{ok:!1,reason:"no-material"}}applyBehavior(e,t,i){let r=We("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=We("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>uu;){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()??[];pr(r.previousMaterials??[],s),pr(r.redoMaterials??[],s)}}};function pr(n,e){for(let t of n)e.includes(t)||t.dispose()}import{Box3 as fu,Frustum as gu,Vector2 as Wt}from"three";import{Frustum as hu,Vector2 as ao,Vector3 as pu}from"three";var lo=Array.from({length:8},()=>new pu),b=new ao,w=new ao;function co(n,e,t,i=new hu){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]=lo,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){lo[n].set(e,t,i).unproject(r)}function ye(n,e,t,i){n.setFromCoplanarPoints(e,t,i)}function uo(n,e){return e.isEmpty()||!Number.isFinite(e.min.x)||!Number.isFinite(e.max.x)?!1:n.intersectsBox(e)}function ho(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 po(n){return n.altKey?"subtract":n.shiftKey?"add":"replace"}var mu="[data-zylem-overlay-root]";function mo(n){let e=n.parentElement;return e?e.querySelector(mu)??e:null}var Ut=class{element=null;host=null;show(e,t){let i=this.ensureElement(e);i.style.left=`${t.left}px`,i.style.top=`${t.top}px`,i.style.width=`${t.width}px`,i.style.height=`${t.height}px`,i.style.display="block"}hide(){this.element&&(this.element.style.display="none")}dispose(){this.element?.remove(),this.element=null,this.host=null}ensureElement(e){if(this.element&&this.host===e)return this.element;this.element?.remove();let t=document.createElement("div");t.dataset.zylemMarquee="true";let i=t.style;return i.position="absolute",i.pointerEvents="none",i.boxSizing="border-box",i.border="1px solid rgba(34, 255, 34, 0.9)",i.background="rgba(34, 255, 34, 0.12)",i.display="none",i.zIndex="20",e.appendChild(t),this.element=t,this.host=e,t}};var yu=4,vu=new fu,fo=new gu,Kt=class{context;overlay=new Ut;armed=!1;dragging=!1;mode="replace";baseSelection=[];startNdc=new Wt;currentNdc=new Wt;startClient=new Wt;currentClient=new Wt;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=po(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=mo(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)<yu)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;co(e,this.startNdc,this.currentNdc,fo);let t=[];this.context.forEachEntity((i,r)=>{let s=ae(r,vu);s&&uo(fo,s)&&t.push(i)}),vr(ho(this.baseSelection,t,this.mode))}};import{BoxGeometry as bu,EdgesGeometry as wu,Group as Su,LineBasicMaterial as Cu,LineSegments as xu,Vector3 as yo}from"three";var qt=new yo,go=new yo,Xt=class{scene;container=new Su;edges;material;pool=[];constructor(e,t=16765503){this.scene=e;let i=new bu(1,1,1);this.edges=new wu(i),i.dispose(),this.material=new Cu({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(go);let r=this.acquire(t);t+=1,r.position.copy(go),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 xu(this.edges,this.material);return i.frustumCulled=!1,this.container.add(i),this.pool.push(i),i}};var So=2293538,Ru=16724787,mr=new Qt,Co=new Yt,$t=class{stage;options;mouseNdc=new Tu(-2,-2);raycaster=new Du;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 Qt;grid=new $r;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 jt({getScene:()=>this.stage.scene?.scene??null,getCamera:()=>this.getDebugViewCamera()?.camera??null,resolveEntity:i=>this.resolveEntity(i)}),this.swatchApplier=new Nt({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 Kt({getCamera:()=>this.getDebugViewCamera()?.camera??null,forEachEntity:i=>this.forEachSelectableEntity(i)}),this.levelSession=new St(this.levelSessionHost()),this.syncWithDebugState(),this.debugStateUnsubscribe=ku(h,()=>{this.syncWithDebugState()}),this.entityResolverUnregister=yr(i=>this.resolveEntity(i)),this.focusContextUnregister=Dr({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&&Ze()&&!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.syncTransformTool(),this.syncGrid()}playLevel(e){this.levelSession.play(e),this.syncTransformTool(),this.syncGrid()}closeLevel(){this.levelSession.close(),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 Yt;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=Zr({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:Bu.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=>{wo().channel.send("level:gesture",{gesture:e})},publishSelect:e=>{wo().channel.send("level:select",e)},publishNotice:e=>{hi("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(S().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 Mu(new Pu,new Eu({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 It(e),this.placementGhost??=new Ft(e),this.selectionHighlight??=new Xt(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 Qt,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?li(o.uuid??null):je();let a=Sr();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(So);break;case"delete":this.debugCursor?.setColor(Ru);break;default:this.debugCursor?.setColor(h.pickMode?So: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&&je(),null;let o=this.currentRay(),l=s.raycast(o.origin,o.direction,this.options.maxRayDistance)?.uuid??null;if(!l)return r&&je(),null;r&&li(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 vo(new Float32Array(t.vertices),3)),this.debugLines.geometry.setAttribute("color",new vo(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=X(s,o,S(),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 Qt);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":so(e,t,r=>this.resolveEntity(r));break;case"create":for(let r of e.entries)i?this.stage.entityDelegate.detachEntity(r.uuid):this.stage.entityDelegate.restoreEntity(r.uuid);break;case"delete":for(let r of e.entries)i?this.stage.entityDelegate.restoreEntity(r.uuid):this.stage.entityDelegate.detachEntity(r.uuid);break;case"swatch":this.swatchApplier.applySceneOperation(e,t);break}}currentRay(){let e=this.getDebugViewCamera();return e?(this.raycaster.setFromCamera(this.mouseNdc,e.camera),{origin:this.raycaster.ray.origin.clone(),direction:this.raycaster.ray.direction.clone().normalize()}):{origin:new Yt,direction:new Yt(0,0,-1)}}handleAction(e,t={shiftKey:!1,altKey:!1}){let i=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&&br([a]):t.shiftKey?a&&wr(a):a?ai(a):ai(null);break}case"delete":{let o=s?.uuid??null;if(!o)break;this.stage.entityDelegate.detachEntity(o)&&ve({opId:bo(10),kind:"delete",label:"Delete entity",entries:[{uuid:o}]});break}case"add":this.placeEntity(e,s);break}}placeEntity(e,t){let i=X(e,t,S());if(!i)return;let{position:r,normal:s}=i,o=h.addTypeId,a={...o?K(o)?.defaultProps??{}:{},...h.addTypeProps??{}},l=o?K(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),ve({opId:bo(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"||(mr.setFromObject(r),mr.isEmpty()))return;mr.getSize(Co);let s=vi(t,Co,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),hi("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.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 zu}from"three";var Jt=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new zu(e,t);return new z(f.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new Rt;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 ei=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"?He.emit("stage:loading:start",t):e.type==="progress"?He.emit("stage:loading:progress",t):e.type==="complete"&&He.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 ti=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){Ce(e.options)||(this.scene?.addEntityGroup(e),we(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),we(i),oe(i),Ce(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 xo}from"@zylem/behaviors/core";var Lu=200,ii=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 Ie){e.create();for(let i of e.getChildren())i instanceof be&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:C(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();_r(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof be&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:C(),camera:this.camera}),this.tryRegisterRenderStrategy(t),q(t)||this.scene.addEntityGroup(t),oe(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),Vr(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),q(e)||this.scene.addEntityGroup(e),oe(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(Se(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!==xo.Static&&(e.bodyDesc.kind=xo.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof Ke){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)}Ue(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),q(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),Ue(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),q(i)||this.scene.addEntityGroup(i),Or(i),Ar(i),this.addEntityToStage(i),this.entityModelDelegate.observe(i),!0}isDetached(e){return this.detachedMap.has(e)}evictOldestDetached(){for(;this.detachedMap.size>Lu;){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:C()})}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 jr?{...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):Ae(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}Ae(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:fi,getGlobals:C}):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=>{Ue(t,!1);try{t.nodeDestroy({me:t,globals:C()})}catch{}le(t),e.push(t.uuid)}),this.detachedMap.forEach(({entity:t})=>{try{t.nodeDestroy?.({me:t,globals:C()})}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:fi,getGlobals:C});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 Po,Raycaster as Ou,Vector2 as _u,Vector3 as ri}from"three";var Vu=5e3,Au=new ri(0,1,0),ni=class{host;unsubscribe;known=new Set;targets=new Map;bounds=new Po;raycaster=new Ou;mouseNdc=new _u;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=[Fr((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)}}),Ir(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:fr(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 rn(e,this.session.representative))}syncTarget(e){Gr(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()??Au.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=mi(i,this.bounds);if(!r)continue;let s=Hr(e,r);s&&(t&&s.distance>=t.distance||(t={entity:i,distance:s.distance,point:s.point,center:r.getCenter(new ri)}))}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,Vu),i=this.session?.snap!=null?{enabled:!0,translate:this.session.snap}:{enabled:!1,translate:0};return X(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??tn,t.opacity??en),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:fr(t.position??Iu(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(!Fu(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:fr(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 Iu(n){let e=mi(n,new Po);return e?e.getCenter(new ri):new ri}function fr(n){return n?{x:n.x,y:n.y,z:n.z}:{x:0,y:0,z:0}}function Fu(n){return n==null||n===!1?!1:typeof n=="object"||typeof n=="function"}var Hu="Stage",si=class extends At{type=Hu;state={...Wr};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=Gu(),this.cameraDelegate=new Jt(this),this.loadingDelegate=new ei,this.entityModelDelegate=new ti,this.entityDelegate=new ii(this.loadingDelegate,this.entityModelDelegate),this.pointerDelegate=new ni(ju(this));let t=Us(e);this.camera=t.camera,this.cameras=t.cameras,this.entityDelegate.children=t.entities,t.asyncEntities.length&&this.entityDelegate.enqueue(...t.asyncEntities),this.state={...this.state,inputs:t.config.inputs,backgroundColor:t.config.backgroundColor,backgroundImage:t.config.backgroundImage,backgroundShader:t.config.backgroundShader,gravity:t.config.gravity,variables:t.config.variables,physicsRate:t.config.physicsRate,assetLoaders:t.config.assetLoaders,defaultLighting:t.config.defaultLighting,postProcessingEffects:t.config.postProcessingEffects,entities:[]},this.gravity=t.config.gravity??new Mo(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Eo?e:new Eo(e);Kr(i),qr(t),Xr(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 Vt(e,r,this.state);let s=this.gravity??new Mo(0,0,0);if(this.world=await Ot.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,...Lt(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,a=>this.entityDelegate.handleLateModelReady(a)),this.renderStrategy=new et,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 $t(this),this.hasSetup=!0}}_update(e){let{delta:t}=e;if(!this.scene||!this.world){this.logMissingEntities();return}let i=this.world,r=this.scene;R("behaviorSystems",()=>{for(let s of this.entityDelegate.behaviorSystems)s.update(void 0,t)}),R("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&&Jr(a,a.transformStore),s.markedForRemoval&&this.entityDelegate.removeEntityByUuid(s.uuid)}}),R("worldUpdate",()=>{i.update(e)}),R("behaviorPostUpdate",()=>{for(let s of this.entityDelegate.behaviorSystems)s.postUpdate?.(void 0,t)}),R("syncRenderPoses",()=>{qs({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),R("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),R("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),R("scene",()=>{r.update({delta:t})}),this.pointerDelegate.update(t),Es()}outOfLoop(){this.debugUpdate()}debugUpdate(){re()&&(Wi("debugUpdate"),this.debugDelegate?.update(),Ki())}_destroy(e){this.pointerDelegate.dispose(),this.entityDelegate.destroyAll(),this.world?.destroy(),this.scene?.destroy(),this.debugDelegate?.dispose(),this.debugDelegate=null,this.entityModelDelegate.dispose(),this.renderStrategy?.dispose(),this.renderStrategy=null,this.rendererManager&&this.rendererManager.stopRenderLoop(),this.world=null,this.scene=null,this.cameraRef=null,this.cameraManagerRef=null,Qr(),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 ju(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 Zu}from"valtio/vanilla";import{Vector3 as Nu}from"three";var Uu={backgroundColor:Xe,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new Nu(0,0,0),variables:{}},ie=Zu({...Uu});function Do(n){let e=Wu(),t={};return typeof n[0]=="object"&&(t=n.shift()??{}),[{...e,...t},...n]}function Wu(){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 gr=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Pr;inputConfig=null;pendingPlacement=null;placementGeneration=0;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];se.prepareGLTFRuntime(Lt(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=xr(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){this.wrappedStage?.pointerDelegate.dispose(),Qe.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new si(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 E?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,Qe.entities=[...Qe.entities,...c]};this.wrappedStage.onEntityAdded(c=>{if(Ce(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 E?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof E?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof E?this.wrappedStage?.setActiveCamera(e.cameraRef)??!1:this.wrappedStage?.setActiveCamera(e)??!1}getCamera(e){return this.wrappedStage?.getCamera(e)??null}dispatch(e,t){this.eventDelegate.dispatch(e,t),_.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function yy(...n){let e=Do(n);return new gr([...e])}export{td as a,$e as b,Se as c,Ce as d,q as e,Je as f,et as g,kh as h,Rh as i,f as j,ee as k,Pt as l,pe as m,me as n,ze as o,Le as p,Oe as q,_e as r,te as s,Rt as t,E as u,am as v,fm as w,Pc as x,gr as y,yy as z};
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as M,g as N,h as O,i as P,j as Q,k as R,l as S,m as T,n as U,o as V,p as W,q as X,r as Y}from"./chunk-NPA6GUGE.js";import{a,c as q,d as r,e as s,f as t,g as u,h as v,i as w,j as x,l as y,m as z,n as A,o as B,p as C,q as D,r as E,s as F,t as G,u as H,v as I,w as J,x as K,z as L}from"./chunk-BIZOIGCZ.js";import{e as g}from"./chunk-26EJFYDX.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-BH53MBAZ.js";import"./chunk-PCFF4LLO.js";import"./chunk-UG22Z42P.js";import"./chunk-Y5IU6IA5.js";import"./chunk-B6GDESCB.js";import"./chunk-SIRFF4DY.js";import"./chunk-273CUPEO.js";import"./chunk-UM5VNQPY.js";import"./chunk-ICJ2E2OV.js";import"./chunk-2HSR5XDQ.js";import"./chunk-2XMG3NJS.js";import{a as p}from"./chunk-7GYFZKK7.js";import"./chunk-QGIYILYI.js";import"./chunk-D2PATZCC.js";import"./chunk-3LXDHDJB.js";import"./chunk-BJYXY2FB.js";import"./chunk-YWH5HQDT.js";import"./chunk-UNCP6V7I.js";import"./chunk-CI7A5N6G.js";import"./chunk-EVYHPR3J.js";import"./chunk-XRP4JJXL.js";import"./chunk-YW2GTHCV.js";import"./chunk-5WRFDAZN.js";import"./chunk-2NO4YCLR.js";import"./chunk-T6O2SGH5.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-UUOPT2N4.js";import"./chunk-4QLJUQSJ.js";import{a as h,b as i,c as j,d as k,g as l,h as m,i as n,j as o}from"./chunk-7WRQ2UAN.js";import"./chunk-VUJXR5K5.js";import"./chunk-WOT6VMZA.js";export{b as AspectRatio,G as CameraManager,y as CameraPipeline,H as CameraWrapper,B as FirstPersonPerspective,A as Fixed2DPerspective,O as Game,C as IsometricPerspective,x as Perspectives,t as RenderBundleManager,u as RenderStrategyManager,S as STAGE_STATE_CHANGE,E as SecondPersonPerspective,N as StageManager,z as ThirdPersonPerspective,D as TopDownPerspective,i as VEC2_ONE,h as VEC2_ZERO,k as VEC3_ONE,j as VEC3_ZERO,I as createCamera,V as createFollowTarget,P as createGame,F as createPerspective,W as createPlatformFollow,L as createStage,X as createStrategyPan,p as crossfadeTransitionShader,U as dispatchStageState,R as entitySpawner,f as gameConfig,v as getActiveLevelDocument,c as getDisplayAspect,d as getPresetResolution,T as initStageStateDispatcher,s as isManagedRenderEntity,a as isWebGPUSupported,l as normalizeVec2,m as normalizeVec3,e as parseResolution,q as resolveRenderCategory,Y as setCameraFeed,w as setStageFrameProfilerEnabled,J as stageConfig,M as stageState,g as streamLevel,Q as streamLevelOnStage,n as toThreeVector2,o as toThreeVector3,r as usesManagedRenderPath,K as vessel};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as M,g as N,h as O,i as P,j as Q,k as R,l as S,m as T,n as U,o as V,p as W,q as X,r as Y}from"./chunk-JUA5KNND.js";import{a,c as q,d as r,e as s,f as t,g as u,h as v,i as w,j as x,l as y,m as z,n as A,o as B,p as C,q as D,r as E,s as F,t as G,u as H,v as I,w as J,x as K,z as L}from"./chunk-VUTKEMIE.js";import{e as g}from"./chunk-26EJFYDX.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-BH53MBAZ.js";import"./chunk-PCFF4LLO.js";import"./chunk-UG22Z42P.js";import"./chunk-Y5IU6IA5.js";import"./chunk-B6GDESCB.js";import"./chunk-SIRFF4DY.js";import"./chunk-273CUPEO.js";import"./chunk-UM5VNQPY.js";import"./chunk-ICJ2E2OV.js";import"./chunk-2HSR5XDQ.js";import"./chunk-2XMG3NJS.js";import{a as p}from"./chunk-7GYFZKK7.js";import"./chunk-QGIYILYI.js";import"./chunk-D2PATZCC.js";import"./chunk-3LXDHDJB.js";import"./chunk-BJYXY2FB.js";import"./chunk-YWH5HQDT.js";import"./chunk-UNCP6V7I.js";import"./chunk-CI7A5N6G.js";import"./chunk-EVYHPR3J.js";import"./chunk-XRP4JJXL.js";import"./chunk-YW2GTHCV.js";import"./chunk-5WRFDAZN.js";import"./chunk-2NO4YCLR.js";import"./chunk-T6O2SGH5.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-UUOPT2N4.js";import"./chunk-4QLJUQSJ.js";import{a as h,b as i,c as j,d as k,g as l,h as m,i as n,j as o}from"./chunk-7WRQ2UAN.js";import"./chunk-VUJXR5K5.js";import"./chunk-WOT6VMZA.js";export{b as AspectRatio,G as CameraManager,y as CameraPipeline,H as CameraWrapper,B as FirstPersonPerspective,A as Fixed2DPerspective,O as Game,C as IsometricPerspective,x as Perspectives,t as RenderBundleManager,u as RenderStrategyManager,S as STAGE_STATE_CHANGE,E as SecondPersonPerspective,N as StageManager,z as ThirdPersonPerspective,D as TopDownPerspective,i as VEC2_ONE,h as VEC2_ZERO,k as VEC3_ONE,j as VEC3_ZERO,I as createCamera,V as createFollowTarget,P as createGame,F as createPerspective,W as createPlatformFollow,L as createStage,X as createStrategyPan,p as crossfadeTransitionShader,U as dispatchStageState,R as entitySpawner,f as gameConfig,v as getActiveLevelDocument,c as getDisplayAspect,d as getPresetResolution,T as initStageStateDispatcher,s as isManagedRenderEntity,a as isWebGPUSupported,l as normalizeVec2,m as normalizeVec3,e as parseResolution,q as resolveRenderCategory,Y as setCameraFeed,w as setStageFrameProfilerEnabled,J as stageConfig,M as stageState,g as streamLevel,Q as streamLevelOnStage,n as toThreeVector2,o as toThreeVector3,r as usesManagedRenderPath,K as vessel};
@@ -1 +1 @@
1
- import{z as e}from"./chunk-BIZOIGCZ.js";import"./chunk-26EJFYDX.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-BH53MBAZ.js";import"./chunk-UG22Z42P.js";import"./chunk-Y5IU6IA5.js";import"./chunk-SIRFF4DY.js";import"./chunk-273CUPEO.js";import"./chunk-UM5VNQPY.js";import"./chunk-2HSR5XDQ.js";import"./chunk-D2PATZCC.js";import"./chunk-BJYXY2FB.js";import"./chunk-UNCP6V7I.js";import"./chunk-CI7A5N6G.js";import"./chunk-EVYHPR3J.js";import"./chunk-XRP4JJXL.js";import"./chunk-YW2GTHCV.js";import"./chunk-5WRFDAZN.js";import"./chunk-2NO4YCLR.js";import"./chunk-T6O2SGH5.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-UUOPT2N4.js";import"./chunk-4QLJUQSJ.js";import"./chunk-7WRQ2UAN.js";import"./chunk-WOT6VMZA.js";import{proxy as t}from"valtio/vanilla";var s=()=>({id:"zylem",globals:{},stages:[e()],debug:!1,time:0,input:void 0}),a=t({...s()});function o(){return{id:a.id??"zylem",globals:a.globals??{},stages:a.stages??[e()],debug:a.debug,time:a.time,input:a.input}}export{o as getGameDefaultConfig};
1
+ import{z as e}from"./chunk-VUTKEMIE.js";import"./chunk-26EJFYDX.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-BH53MBAZ.js";import"./chunk-UG22Z42P.js";import"./chunk-Y5IU6IA5.js";import"./chunk-SIRFF4DY.js";import"./chunk-273CUPEO.js";import"./chunk-UM5VNQPY.js";import"./chunk-2HSR5XDQ.js";import"./chunk-D2PATZCC.js";import"./chunk-BJYXY2FB.js";import"./chunk-UNCP6V7I.js";import"./chunk-CI7A5N6G.js";import"./chunk-EVYHPR3J.js";import"./chunk-XRP4JJXL.js";import"./chunk-YW2GTHCV.js";import"./chunk-5WRFDAZN.js";import"./chunk-2NO4YCLR.js";import"./chunk-T6O2SGH5.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-UUOPT2N4.js";import"./chunk-4QLJUQSJ.js";import"./chunk-7WRQ2UAN.js";import"./chunk-WOT6VMZA.js";import{proxy as t}from"valtio/vanilla";var s=()=>({id:"zylem",globals:{},stages:[e()],debug:!1,time:0,input:void 0}),a=t({...s()});function o(){return{id:a.id??"zylem",globals:a.globals??{},stages:a.stages??[e()],debug:a.debug,time:a.time,input:a.input}}export{o as getGameDefaultConfig};
package/dist/public.js CHANGED
@@ -1 +1 @@
1
- import{a as $m,b as en,c as rn,d as tn}from"./chunk-FZNEWOC5.js";import{a as on}from"./chunk-JCGW5PIR.js";import{a as an,b as pn,c as mn,d as nn,e as fn,f as xn,g as ln,h as sn,i as cn,j as dn,k as yn,l as vn,m as En,n as Sn,o as An,p as hn}from"./chunk-47DG7I7M.js";import{A as In,B as Jn,C as Kn,a as Rn,b as Pn,c as Ln,d as On,e as bn,f as Tn,g as Zn,h as Dn,i as gn,j as un,k as wn,l as Gn,m as Hn,n as _n,o as Fn,p as jn,q as kn,r as Bn,s as Cn,t as Mn,u as Vn,v as Wn,w as Yn,x as zn,y as Nn,z as qn}from"./chunk-KSEP7AUF.js";import{A as Nm,B as qm,C as Im,D as Jm,E as Km,a as Am,b as hm,c as Rm,d as Pm,e as Lm,f as Om,g as bm,h as Tm,i as Zm,j as Dm,k as gm,l as um,m as wm,n as Gm,o as Hm,p as _m,q as Fm,r as jm,s as km,t as Bm,u as Cm,v as Mm,w as Vm,x as Wm,y as Ym,z as zm}from"./chunk-IPWUDOV5.js";import{a as Qm,b as Um,c as Xm}from"./chunk-7QF6YTEZ.js";import"./chunk-ORIDWL3T.js";import{a as y,b as v,c as E,d as S,e as A,f as h}from"./chunk-YFXNZ2RS.js";import{a as R,b as P,c as L,d as O,e as b,f as T,g as Z,h as D,i as g,j as u,k as w,l as G,m as H,n as _,o as F,p as j,q as k,r as B,s as C,t as M,u as V,v as W,w as Y}from"./chunk-4DAITCJS.js";import"./chunk-BIGH6D34.js";import"./chunk-ELQN62PQ.js";import{a as Vi,b as Wi,c as em,d as rm,e as tm,f as om}from"./chunk-ZZO4CKRU.js";import{a as pp,c as ip,d as mp,e as np,f as fp,g as xp}from"./chunk-2PFNNGTV.js";import{a as Yi,b as zi,c as Ni,d as qi,e as Ii,f as Ji,g as Ki,h as Qi,i as Ui,j as Xi,k as $i}from"./chunk-NVVLLWIM.js";import"./chunk-VMXSE3EC.js";import{a as am,b as pm,c as im,d as mm,e as nm,f as fm,g as xm,h as lm,i as sm,j as cm,k as dm}from"./chunk-YNX3Q3CL.js";import{a as ym,b as vm,c as Em,d as Sm}from"./chunk-WQ3WMMZD.js";import{a as Fe,b as je,c as ke,d as Be,e as qe,f as Qp,g as Up,h as fi,i as xi,j as li,k as si,l as ci,m as di,n as yi,o as vi,p as Ei,q as Si,r as Ai}from"./chunk-NPA6GUGE.js";import{a as _e,c as Za,d as Da,e as ga,f as Rp,g as Pp,h as wp,i as Hp,j as _p,l as Fp,m as jp,n as kp,o as Bp,p as Cp,q as Mp,r as Vp,s as Wp,t as Yp,u as zp,v as Np,w as qp,x as Jp,z as Kp}from"./chunk-BIZOIGCZ.js";import{e as Ue,n as pr}from"./chunk-26EJFYDX.js";import{b as Ep}from"./chunk-WBQ5TNRZ.js";import{a as Ip}from"./chunk-BH53MBAZ.js";import{a as Ce,b as Me,c as Ve,d as We,e as Ye,f as ze,g as Ne}from"./chunk-PCFF4LLO.js";import{a as Pe,b as Le,c as Oe,d as be,e as Te,f as Ze,g as De,h as ge,i as ue,j as we,k as Ge,l as He}from"./chunk-UG22Z42P.js";import{c as d}from"./chunk-Y5IU6IA5.js";import{a as he,b as Re}from"./chunk-B6GDESCB.js";import{c as Dp,d as gp,e as up,f as Gp}from"./chunk-SIRFF4DY.js";import{a as Ke,b as Qe,c as Xe,d as $e,e as er,f as rr,g as tr,h as or,i as ar}from"./chunk-273CUPEO.js";import{B as Ee,C as Se,D as Ae,a as U,b as X,c as $,d as ee,e as re,f as te,h as oe,j as ae,l as pe,m as ie,n as me,o as ne,p as fe,q as xe,u as le,v as se,w as ce,x as de,y as ye,z as ve}from"./chunk-UM5VNQPY.js";import"./chunk-ICJ2E2OV.js";import"./chunk-2HSR5XDQ.js";import{a as ua,b as wa,c as Ga,d as Ha,e as _a,f as Fa,g as ja,h as ka,i as Ba,j as Ca,k as Ma,l as Va,m as Wa,n as Ya,o as za,p as Na,q as qa,r as lp,s as sp,t as cp}from"./chunk-2XMG3NJS.js";import{a as Ta}from"./chunk-7GYFZKK7.js";import{a as Ia,b as Ja,c as Ka,d as Qa,e as Ua,f as Xa,g as $a,h as ep,i as rp,j as tp,k as op,l as ap}from"./chunk-QGIYILYI.js";import{h as Lp,i as Op,j as bp,k as Tp,l as Zp}from"./chunk-D2PATZCC.js";import{a as hi,b as Ri,c as Pi,d as Li,e as Oi}from"./chunk-5NQGXW75.js";import{a as Xp,b as $p,c as ei,d as ri,e as ti,f as oi,g as ai,h as pi,i as ii,j as mi,l as ni}from"./chunk-3LXDHDJB.js";import{a as dp,b as yp,c as vp,d as Sp,e as Ap,f as hp}from"./chunk-BJYXY2FB.js";import{A as lt,B as st,C as ct,D as dt,E as yt,J as Tt,K as Zt,L as Dt,M as gt,N as ut,O as wt,b as Cr,c as Mr,d as Vr,e as Wr,f as Yr,g as zr,h as Nr,i as qr,j as Ir,k as Jr,l as Kr,m as Qr,n as Ur,o as Xr,p as $r,q as et,r as rt,s as tt,t as ot,u as at,v as pt,w as it,x as mt,y as nt,z as xt}from"./chunk-YWH5HQDT.js";import{d as ft,e as Lt,f as Ot,g as bt}from"./chunk-UNCP6V7I.js";import{E as Br,c as ur,d as wr,e as Gr,f as Hr,g as _r,h as Fr,i as jr,j as kr}from"./chunk-CI7A5N6G.js";import{b as gr}from"./chunk-EVYHPR3J.js";import{a as dr,b as yr,c as vr,d as Er,e as Sr,f as Ar,g as hr,h as Rr,i as Pr,j as Lr,k as Or,l as br,m as Tr,n as Zr,o as Dr}from"./chunk-XRP4JJXL.js";import{c as e,d as r,g as t,h as o,i as a,j as p,l as i,m,n,o as f,p as x,q as l,r as s,s as c}from"./chunk-YW2GTHCV.js";import"./chunk-5WRFDAZN.js";import"./chunk-2NO4YCLR.js";import"./chunk-T6O2SGH5.js";import{a as Ie,b as Je}from"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import{a as vt,b as Et,c as St,d as At,e as ht,f as Rt,g as Pt}from"./chunk-UUOPT2N4.js";import{e as z,f as N,g as q,h as I,i as J,j as K,m as Q}from"./chunk-4QLJUQSJ.js";import{a as ir,b as mr,c as nr,d as fr,g as xr,h as lr,i as sr,j as cr}from"./chunk-7WRQ2UAN.js";import{a as bi,b as Ti,c as Zi,d as Di,e as gi,f as ui,g as wi,h as Gi,i as Hi,j as _i,k as Fi,l as ji,m as ki,n as Bi,o as Ci,p as Mi}from"./chunk-6XFXPIVB.js";import{$ as wo,A as oo,Aa as aa,B as ao,Ba as pa,C as po,Ca as ia,D as io,Da as ma,E as mo,Ea as na,F as no,Fa as fa,G as fo,Ga as xa,H as xo,Ha as la,I as lo,Ia as sa,J as so,Ja as ca,K as co,Ka as da,L as yo,La as ya,M as vo,Ma as va,N as Eo,Na as Ea,O as So,Oa as Sa,P as Ao,Pa as Aa,Q as ho,Qa as ha,R as Ro,Ra,S as Po,Sa as Pa,T as Lo,Ta as La,U as Oo,Ua as Oa,V as bo,Va as ba,W as To,X as Zo,Y as Do,Z as go,_ as uo,aa as Go,b as Gt,ba as Ho,c as Ht,ca as _o,d as _t,da as Fo,e as Ft,ea as jo,f as jt,fa as ko,g as kt,ga as Bo,h as Bt,ha as Co,i as Ct,ia as Mo,j as Mt,ja as Vo,k as Vt,ka as Wo,l as Wt,la as Yo,m as Yt,ma as zo,n as zt,na as No,o as Nt,oa as qo,p as qt,pa as Io,q as It,qa as Jo,r as Jt,ra as Ko,s as Kt,sa as Qo,t as Qt,ta as Uo,u as Ut,ua as Xo,v as Xt,va as $o,w as $t,wa as ea,x as eo,xa as ra,y as ro,ya as ta,z as to,za as oa}from"./chunk-VUJXR5K5.js";import"./chunk-WOT6VMZA.js";export{dp as ACTOR_TYPE,Fe as AspectRatio,Ki as AudioClipSchema,sm as AudioItemSchema,Nr as BOX_TYPE,tn as BRIDGE_READY_EVENT,Gt as BoundaryRicochet3DCoordinator,Ht as BoundaryRicochetCoordinator,Ur as CONE_TYPE,ua as CUTSCENE_BEHAVIOR_KEY,ot as CYLINDER_TYPE,im as CameraKeyframeSchema,Yp as CameraManager,Fp as CameraPipeline,fm as CameraShotSchema,zp as CameraWrapper,Wn as ColorJsonSchema,Gp as ConstructionGrid,_t as CooldownBehavior,wa as CutsceneCameraBehavior,mm as CutsceneCameraSchema,dm as CutsceneDefinitionSchema,xm as CutsceneEventSchema,cp as CutscenePreviewController,pm as CutsceneSceneSchema,cm as CutsceneTrackSchema,$ as DEFAULT_SNAP_SETTINGS,xt as DISK_TYPE,v as DROPPABLE_AREA_TYPE,Ft as Destructible3DBehavior,jt as DestructibleMesh,nm as DollyPathSchema,Dn as EntityJsonSchema,Pn as EntitySchema,he as EntityThumbnailCache,Ie as EventEmitterDelegate,lm as EventItemSchema,Sp as FOG_TYPE,kt as FirstPersonBehavior,Bt as FirstPersonEvent,Ct as FirstPersonFSM,Bp as FirstPersonPerspective,Wt as FirstPersonPresentation,Mt as FirstPersonShooterCoordinator,Vt as FirstPersonState,kp as Fixed2DPerspective,c as Fn,Yt as FractureOptions,fi as Game,pr as GameBridge,Kn as GameConfigJsonSchema,Jn as GameDeviceConfigJsonSchema,Vn as GameInputConfigSchema,Mn as GameInputPlayerConfigSchema,y as HOVER_AREA_TYPE,om as Howl,Ni as InstrumentDefinitionSchema,zi as InstrumentEffectSchema,Yi as InstrumentPresetSchema,Cp as IsometricPerspective,zt as Jumper2DBehavior,Nt as Jumper2DEvent,qt as Jumper2DFSM,It as Jumper2DState,Jt as Jumper3DBehavior,Kt as Jumper3DEvent,Qt as Jumper3DFSM,Ut as Jumper3DState,un as KeyboardMappingSchema,gt as LIGHT_TYPE,ai as LINE_TYPE,Tn as LineEntityDataSchema,Cn as MouseConfigSchema,wn as MouseMappingSchema,Xt as MultidirectionalSpaceShooterCoordinator,Ji as NoteClipSchema,hi as PARTICLE_SYSTEM_TYPE,it as PILL_TYPE,ct as PLANE_TYPE,et as PYRAMID_TYPE,$t as ParticleEmitterBehavior,_p as Perspectives,eo as Platformer2DBehavior,ro as Platformer2DEvent,to as Platformer2DFSM,oo as Platformer2DState,ao as Platformer3DBehavior,po as Platformer3DEvent,io as Platformer3DFSM,mo as Platformer3DState,Tt as RECT_TYPE,wi as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,Gi as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,Hi as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,_i as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,Fi as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,ji as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,Rp as RenderBundleManager,Pp as RenderStrategyManager,In as ResolutionInputSchema,no as Ricochet2DBehavior,fo as Ricochet2DEvent,xo as Ricochet2DFSM,lo as Ricochet2DState,so as Ricochet3DBehavior,co as Ricochet3DEvent,yo as Ricochet3DFSM,vo as Ricochet3DState,bi as RuntimeBoundary2DBehavior,Ti as RuntimeDynamicCircleBody2DBehavior,Zi as RuntimeGoalZone2DBehavior,Di as RuntimePlayerInput2DBehavior,gi as RuntimeRicochet2DBehavior,ui as RuntimeTriggerRegion2DBehavior,vt as SELECTION_BOUNDS_MARGIN,Et as SELECTION_THIN_AXIS_FRACTION,At as SELECTION_THIN_AXIS_MAX,St as SELECTION_THIN_AXIS_MIN,Jr as SPHERE_TYPE,ri as SPRITE_TYPE,ci as STAGE_STATE_CHANGE,am as SceneTransitionSchema,Eo as ScreenVisibilityBehavior,So as ScreenVisibilityFSM,Ao as ScreenWrapBehavior,ho as ScreenWrapEvent,Ro as ScreenWrapFSM,Po as ScreenWrapState,Vp as SecondPersonPerspective,Lo as Shooter2DBehavior,Ep as SimulationBody,Qi as SongClipSchema,$i as SongDefinitionSchema,Xi as SongLoopSchema,qi as SongNoteSchema,Ii as SongTrackSchema,Zn as SpriteEntityDataSchema,Nn as StageAssetLoaderConfigSchema,dn as StageBodyKind,yn as StageBoundaryDim,qn as StageConfigJsonSchema,vn as StageEventType,zn as StageGLTFAssetLoaderConfigSchema,gn as StageJsonSchema,Up as StageManager,En as StageRicochetDim,Sn as StageRicochetReflection,Ln as StageSchema,An as StageTopDownPlane,Xp as TEXT_TYPE,U as TRANSFORM_TOOLS,On as TextEntityDataSchema,jp as ThirdPersonPerspective,Oo as ThrusterBehavior,bo as ThrusterEvent,To as ThrusterFSM,Zo as ThrusterState,Ui as TimeSignatureSchema,Do as TopDownMovementBehavior,Mp as TopDownPerspective,go as TopDownShooterCoordinator,up as TransformGizmo,mr as VEC2_ONE,ir as VEC2_ZERO,fr as VEC3_ONE,nr as VEC3_ZERO,Yn as Vec3ComponentsSchema,Rn as Vector2Schema,bn as Vector3TupleSchema,_n as VirtualTouchButtonConfigSchema,jn as VirtualTouchButtonsConfigSchema,Bn as VirtualTouchConfigSchema,Fn as VirtualTouchJoystickConfigSchema,kn as VirtualTouchJoysticksConfigSchema,Hn as VirtualTouchPositionSchema,Gn as VirtualTouchStyleSchema,uo as WorldBoundary2DBehavior,wo as WorldBoundary2DEvent,Go as WorldBoundary2DFSM,Ho as WorldBoundary2DState,_o as WorldBoundary3DBehavior,Fo as WorldBoundary3DEvent,jo as WorldBoundary3DFSM,ko as WorldBoundary3DState,Lt as ZONE_TYPE,yp as ZylemActor,qr as ZylemBox,Xr as ZylemCone,at as ZylemCylinder,lt as ZylemDisk,S as ZylemDroppableArea,Ap as ZylemFog,on as ZylemGameElement,E as ZylemHoverArea,ut as ZylemLight,ii as ZylemLine,Ri as ZylemParticleSystem,mt as ZylemPill,dt as ZylemPlane,rt as ZylemPyramid,Zt as ZylemRect,Kr as ZylemSphere,ti as ZylemSprite,$p as ZylemText,Ot as ZylemZone,G as abs,ka as activeShot,en as announceBridgeReady,o as applyEntityGlow,rn as applySwatchesToSelection,Ip as applyTransformChanges,w as asin,u as atan,tp as audibleTrackIds,Ia as beatsPerBar,Ka as beatsToSeconds,ki as bindRuntimeDynamicCircleBody2DHandle,ur as boxCollision,Cr as boxMesh,pn as buildBoxCollider,nn as buildCapsuleCollider,xn as buildConvexHullCollider,fn as buildCylinderCollider,sn as buildHeightfieldCollider,an as buildRuntimeBody,mn as buildSphereCollider,ln as buildTrimeshCollider,cn as bundleRuntimeCollision,Om as callFunc,za as cameraTracks,Z as clamp,Q as clearGlobalSubscriptions,ap as clipsAt,Dp as closestAxisValue,Bo as computeWorldBoundary2DHits,Co as computeWorldBoundary3DHits,Gr as coneCollision,Vr as coneMesh,g as cos,Br as create,vp as createActor,R as createBackgroundShader,Ir as createBox,Np as createCamera,$r as createCone,Li as createCooldownIcon,qa as createCutscenePlayer,pt as createCylinder,st as createDisk,h as createDroppableArea,ft as createEntity,ni as createEntityFactory,t as createEntityGlowMaterial,Mo as createFirstPersonInputComponent,Vo as createFirstPersonMovementComponent,Wo as createFirstPersonStateComponent,hp as createFog,vi as createFollowTarget,xi as createGame,N as createGlobal,A as createHoverArea,pp as createInstrument,Yo as createJumpConfig2D,zo as createJumpConfig3D,No as createJumpInput2D,qo as createJumpInput3D,Io as createJumpState2D,Jo as createJumpState3D,wt as createLight,mi as createLine,i as createNodeMaterialFromTSL,Pi as createParticleSystem,Wp as createPerspective,Ko as createPhysicsBodyComponent,nt as createPill,yt as createPlane,Ei as createPlatformFollow,Qo as createPlatformer2DInputComponent,Uo as createPlatformer2DMovementComponent,Xo as createPlatformer2DStateComponent,$o as createPlatformer3DInputComponent,ea as createPlatformer3DMovementComponent,ra as createPlatformer3DStateComponent,tt as createPyramid,Dt as createRect,ta as createShooter2DStateComponent,hn as createSimulation,fp as createSongPlayer,Qr as createSphere,oi as createSprite,Kp as createStage,sp as createStageCutsceneHost,Si as createStrategyPan,ei as createText,oa as createThrusterInputComponent,aa as createThrusterMovementComponent,pa as createThrusterStateComponent,ia as createTopDownMovementComponent,ma as createTopDownMovementInputComponent,na as createTopDownMovementStateComponent,fa as createTransformComponent,Hm as createTransformStore,Op as createVariable,bt as createZone,Ta as crossfadeTransitionShader,Na as cutsceneLength,_r as cylinderCollision,Yr as cylinderMesh,ep as dbToGain,ee as debugState,Ne as defaultTouchControls,xa as defineBehavior,or as degreesToRadians,Lm as delay,Oi as destroy,yi as dispatchStageState,Ca as dollyPointAt,M as dot,Ga as easeValue,Bi as emitRuntimeGoal,Ci as emitRuntimeRicochet,Mi as emitRuntimeTriggerRegionEnter,rm as encodeWav,tm as encodeWavBlob,mp as ensureAudio,d as entityRepresentative,si as entitySpawner,Re as entityThumbnailCache,Xe as eulerToQuaternion,Va as evaluateCameraPose,Wa as evaluateCutscene,H as exp,bm as fadeOpacity,la as fireCooldown,sa as fireShooter2DIfRequested,s as float,B as floor,Qe as focusEntity,C as fract,rp as gainToDb,qe as gameConfig,wp as getActiveLevelDocument,xp as getActiveSongPlayer,ca as getCooldown,da as getCooldownStore,je as getDisplayAspect,ya as getEntityFacingAngle2D,q as getGlobal,K as getGlobals,Se as getHoveredEntity,ye as getHoveredEntityId,Wm as getPosition,ke as getPresetResolution,Dr as getRotation,Ee as getSelectedEntity,me as getSelectedEntityId,fe as getSelectedEntityIds,le as getSnapSettings,bp as getVariable,Ym as getVelocity,$m as getZylemBridge,ym as globalChange,vm as globalChanges,va as hasAnyWorldBoundary2DHit,Ea as hasAnyWorldBoundary3DHit,di as initStageStateDispatcher,gp as intersectPlane,np as isAudioReady,p as isGLSLShader,ga as isManagedRenderEntity,ie as isPickMode,a as isTSLShader,X as isTransformTool,_e as isWebGPUSupported,Ya as itemsBetween,We as joystickBaseSvg,Ye as joystickThumbSvg,V as length,_a as lerpPose,Ha as lerpVec3,ip as loadTone,j as max,Rt as measureObjectSelectionBounds,He as mergeInputConfigs,Xa as midiToFrequency,$a as midiToNoteName,k as min,b as mix,Y as mod,_m as move,hm as moveBy,Vm as moveForwardXY,Rm as moveTo,Fm as moveX,Bm as moveXY,Cm as moveXZ,jm as moveY,km as moveZ,O as normalize,xr as normalizeVec2,lr as normalizeVec3,e as objectVertexShader,I as onGlobalChange,J as onGlobalChanges,Zm as onPress,Dm as onRelease,Tp as onVariableChange,Zp as onVariableChanges,gr as packCollisionGroups,ht as padSelectionBounds,um as parallel,Be as parseResolution,Sa as particleEffect,Aa as particlePresets,pi as pickZylemLine,Fr as pillCollision,zr as pillMesh,Wi as pingPongBeep,jr as planeCollision,L as positionWorld,P as positionWorldDirection,_ as pow,Ba as previousShot,Hr as pyramidCollision,Wr as pyramidMesh,$e as quaternionToEuler,ar as radiansToDegrees,ha as registerCooldown,re as registerDebugEntityResolver,Ke as registerEntityFocusContext,em as renderSong,wm as repeat,Gm as repeatForever,Ra as resetCooldown,Am as resetEntityOpacity,Mm as resetVelocity,Pa as resolveAim2D,Ve as resolveButtonAccent,te as resolveDebugEntity,Za as resolveRenderCategory,Pt as resolveSelectionBounds,Me as resolveTouchTheme,Vi as ricochetSound,Pm as rotateBy,vr as rotateEuler,dr as rotateInDirection,Sr as rotateX,Er as rotateY,yr as rotateYEuler,Ar as rotateZ,Ma as sampleDollyPath,Fa as sceneAt,op as scheduleSong,Xm as screenCenterLookDeltas,Um as screenCenterLookTargets,Qa as secondsToBeats,gm as sequence,de as setAddType,Ai as setCameraFeed,lp as setCutsceneTransitionShaders,ae as setDebugTool,z as setGlobal,ce as setGridVisible,ve as setHoveredEntityId,oe as setPaused,pe as setPickMode,zm as setPosition,Nm as setPositionX,qm as setPositionY,Im as setPositionZ,Tr as setRotation,Zr as setRotationDegrees,Lr as setRotationDegreesX,Rr as setRotationDegreesY,br as setRotationDegreesZ,Pr as setRotationX,hr as setRotationY,Or as setRotationZ,Ae as setSelectedEntity,ne as setSelectedEntityId,xe as setSelectedEntityIds,se as setSnapSettings,Hp as setStageFrameProfilerEnabled,Lp as setVariable,Qm as shortestAngleDelta,ja as shotAt,D as sin,T as smoothstep,tr as snapScale,er as snapToIncrement,rr as snapVec3,Ja as songLengthBeats,Ua as songLengthSeconds,wr as sphereCollision,Mr as sphereMesh,qp as stageConfig,Qp as stageState,r as standardShader,F as step,Ue as streamLevel,li as streamLevelOnStage,Tm as throttle,La as tickCooldowns,f as time,sr as toThreeVector2,cr as toThreeVector3,ze as touchButtonSvg,Ce as touchThemes,m as uniform,Oa as updateBoundaryRicochet,Pe as useArrowsForAxes,Oe as useArrowsForDirections,Le as useArrowsForSecondaryAxes,ba as useBehavior,Ze as useIJKLForAxes,De as useIJKLForDirections,we as useMouse,ge as useMouseLook,ue as useScreenCenterLook,Ge as useVirtualControls,Te as useWASDForAxes,be as useWASDForDirections,Da as usesManagedRenderPath,n as uv,Em as variableChange,Sm as variableChanges,W as vec2,x as vec3,l as vec4,Jp as vessel,Km as wrapAround3D,Jm as wrapAroundXY,kr as zoneCollision,Je as zylemEventBus};
1
+ import{a as $m,b as en,c as rn,d as tn}from"./chunk-FZNEWOC5.js";import{a as on}from"./chunk-JCGW5PIR.js";import{a as an,b as pn,c as mn,d as nn,e as fn,f as xn,g as ln,h as sn,i as cn,j as dn,k as yn,l as vn,m as En,n as Sn,o as An,p as hn}from"./chunk-47DG7I7M.js";import{A as In,B as Jn,C as Kn,a as Rn,b as Pn,c as Ln,d as On,e as bn,f as Tn,g as Zn,h as Dn,i as gn,j as un,k as wn,l as Gn,m as Hn,n as _n,o as Fn,p as jn,q as kn,r as Bn,s as Cn,t as Mn,u as Vn,v as Wn,w as Yn,x as zn,y as Nn,z as qn}from"./chunk-KSEP7AUF.js";import{A as Nm,B as qm,C as Im,D as Jm,E as Km,a as Am,b as hm,c as Rm,d as Pm,e as Lm,f as Om,g as bm,h as Tm,i as Zm,j as Dm,k as gm,l as um,m as wm,n as Gm,o as Hm,p as _m,q as Fm,r as jm,s as km,t as Bm,u as Cm,v as Mm,w as Vm,x as Wm,y as Ym,z as zm}from"./chunk-IPWUDOV5.js";import{a as Qm,b as Um,c as Xm}from"./chunk-7QF6YTEZ.js";import"./chunk-ORIDWL3T.js";import{a as y,b as v,c as E,d as S,e as A,f as h}from"./chunk-YFXNZ2RS.js";import{a as R,b as P,c as L,d as O,e as b,f as T,g as Z,h as D,i as g,j as u,k as w,l as G,m as H,n as _,o as F,p as j,q as k,r as B,s as C,t as M,u as V,v as W,w as Y}from"./chunk-4DAITCJS.js";import"./chunk-BIGH6D34.js";import"./chunk-ELQN62PQ.js";import{a as Vi,b as Wi,c as em,d as rm,e as tm,f as om}from"./chunk-ZZO4CKRU.js";import{a as pp,c as ip,d as mp,e as np,f as fp,g as xp}from"./chunk-2PFNNGTV.js";import{a as Yi,b as zi,c as Ni,d as qi,e as Ii,f as Ji,g as Ki,h as Qi,i as Ui,j as Xi,k as $i}from"./chunk-NVVLLWIM.js";import"./chunk-VMXSE3EC.js";import{a as am,b as pm,c as im,d as mm,e as nm,f as fm,g as xm,h as lm,i as sm,j as cm,k as dm}from"./chunk-YNX3Q3CL.js";import{a as ym,b as vm,c as Em,d as Sm}from"./chunk-WQ3WMMZD.js";import{a as Fe,b as je,c as ke,d as Be,e as qe,f as Qp,g as Up,h as fi,i as xi,j as li,k as si,l as ci,m as di,n as yi,o as vi,p as Ei,q as Si,r as Ai}from"./chunk-JUA5KNND.js";import{a as _e,c as Za,d as Da,e as ga,f as Rp,g as Pp,h as wp,i as Hp,j as _p,l as Fp,m as jp,n as kp,o as Bp,p as Cp,q as Mp,r as Vp,s as Wp,t as Yp,u as zp,v as Np,w as qp,x as Jp,z as Kp}from"./chunk-VUTKEMIE.js";import{e as Ue,n as pr}from"./chunk-26EJFYDX.js";import{b as Ep}from"./chunk-WBQ5TNRZ.js";import{a as Ip}from"./chunk-BH53MBAZ.js";import{a as Ce,b as Me,c as Ve,d as We,e as Ye,f as ze,g as Ne}from"./chunk-PCFF4LLO.js";import{a as Pe,b as Le,c as Oe,d as be,e as Te,f as Ze,g as De,h as ge,i as ue,j as we,k as Ge,l as He}from"./chunk-UG22Z42P.js";import{c as d}from"./chunk-Y5IU6IA5.js";import{a as he,b as Re}from"./chunk-B6GDESCB.js";import{c as Dp,d as gp,e as up,f as Gp}from"./chunk-SIRFF4DY.js";import{a as Ke,b as Qe,c as Xe,d as $e,e as er,f as rr,g as tr,h as or,i as ar}from"./chunk-273CUPEO.js";import{B as Ee,C as Se,D as Ae,a as U,b as X,c as $,d as ee,e as re,f as te,h as oe,j as ae,l as pe,m as ie,n as me,o as ne,p as fe,q as xe,u as le,v as se,w as ce,x as de,y as ye,z as ve}from"./chunk-UM5VNQPY.js";import"./chunk-ICJ2E2OV.js";import"./chunk-2HSR5XDQ.js";import{a as ua,b as wa,c as Ga,d as Ha,e as _a,f as Fa,g as ja,h as ka,i as Ba,j as Ca,k as Ma,l as Va,m as Wa,n as Ya,o as za,p as Na,q as qa,r as lp,s as sp,t as cp}from"./chunk-2XMG3NJS.js";import{a as Ta}from"./chunk-7GYFZKK7.js";import{a as Ia,b as Ja,c as Ka,d as Qa,e as Ua,f as Xa,g as $a,h as ep,i as rp,j as tp,k as op,l as ap}from"./chunk-QGIYILYI.js";import{h as Lp,i as Op,j as bp,k as Tp,l as Zp}from"./chunk-D2PATZCC.js";import{a as hi,b as Ri,c as Pi,d as Li,e as Oi}from"./chunk-5NQGXW75.js";import{a as Xp,b as $p,c as ei,d as ri,e as ti,f as oi,g as ai,h as pi,i as ii,j as mi,l as ni}from"./chunk-3LXDHDJB.js";import{a as dp,b as yp,c as vp,d as Sp,e as Ap,f as hp}from"./chunk-BJYXY2FB.js";import{A as lt,B as st,C as ct,D as dt,E as yt,J as Tt,K as Zt,L as Dt,M as gt,N as ut,O as wt,b as Cr,c as Mr,d as Vr,e as Wr,f as Yr,g as zr,h as Nr,i as qr,j as Ir,k as Jr,l as Kr,m as Qr,n as Ur,o as Xr,p as $r,q as et,r as rt,s as tt,t as ot,u as at,v as pt,w as it,x as mt,y as nt,z as xt}from"./chunk-YWH5HQDT.js";import{d as ft,e as Lt,f as Ot,g as bt}from"./chunk-UNCP6V7I.js";import{E as Br,c as ur,d as wr,e as Gr,f as Hr,g as _r,h as Fr,i as jr,j as kr}from"./chunk-CI7A5N6G.js";import{b as gr}from"./chunk-EVYHPR3J.js";import{a as dr,b as yr,c as vr,d as Er,e as Sr,f as Ar,g as hr,h as Rr,i as Pr,j as Lr,k as Or,l as br,m as Tr,n as Zr,o as Dr}from"./chunk-XRP4JJXL.js";import{c as e,d as r,g as t,h as o,i as a,j as p,l as i,m,n,o as f,p as x,q as l,r as s,s as c}from"./chunk-YW2GTHCV.js";import"./chunk-5WRFDAZN.js";import"./chunk-2NO4YCLR.js";import"./chunk-T6O2SGH5.js";import{a as Ie,b as Je}from"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import{a as vt,b as Et,c as St,d as At,e as ht,f as Rt,g as Pt}from"./chunk-UUOPT2N4.js";import{e as z,f as N,g as q,h as I,i as J,j as K,m as Q}from"./chunk-4QLJUQSJ.js";import{a as ir,b as mr,c as nr,d as fr,g as xr,h as lr,i as sr,j as cr}from"./chunk-7WRQ2UAN.js";import{a as bi,b as Ti,c as Zi,d as Di,e as gi,f as ui,g as wi,h as Gi,i as Hi,j as _i,k as Fi,l as ji,m as ki,n as Bi,o as Ci,p as Mi}from"./chunk-6XFXPIVB.js";import{$ as wo,A as oo,Aa as aa,B as ao,Ba as pa,C as po,Ca as ia,D as io,Da as ma,E as mo,Ea as na,F as no,Fa as fa,G as fo,Ga as xa,H as xo,Ha as la,I as lo,Ia as sa,J as so,Ja as ca,K as co,Ka as da,L as yo,La as ya,M as vo,Ma as va,N as Eo,Na as Ea,O as So,Oa as Sa,P as Ao,Pa as Aa,Q as ho,Qa as ha,R as Ro,Ra,S as Po,Sa as Pa,T as Lo,Ta as La,U as Oo,Ua as Oa,V as bo,Va as ba,W as To,X as Zo,Y as Do,Z as go,_ as uo,aa as Go,b as Gt,ba as Ho,c as Ht,ca as _o,d as _t,da as Fo,e as Ft,ea as jo,f as jt,fa as ko,g as kt,ga as Bo,h as Bt,ha as Co,i as Ct,ia as Mo,j as Mt,ja as Vo,k as Vt,ka as Wo,l as Wt,la as Yo,m as Yt,ma as zo,n as zt,na as No,o as Nt,oa as qo,p as qt,pa as Io,q as It,qa as Jo,r as Jt,ra as Ko,s as Kt,sa as Qo,t as Qt,ta as Uo,u as Ut,ua as Xo,v as Xt,va as $o,w as $t,wa as ea,x as eo,xa as ra,y as ro,ya as ta,z as to,za as oa}from"./chunk-VUJXR5K5.js";import"./chunk-WOT6VMZA.js";export{dp as ACTOR_TYPE,Fe as AspectRatio,Ki as AudioClipSchema,sm as AudioItemSchema,Nr as BOX_TYPE,tn as BRIDGE_READY_EVENT,Gt as BoundaryRicochet3DCoordinator,Ht as BoundaryRicochetCoordinator,Ur as CONE_TYPE,ua as CUTSCENE_BEHAVIOR_KEY,ot as CYLINDER_TYPE,im as CameraKeyframeSchema,Yp as CameraManager,Fp as CameraPipeline,fm as CameraShotSchema,zp as CameraWrapper,Wn as ColorJsonSchema,Gp as ConstructionGrid,_t as CooldownBehavior,wa as CutsceneCameraBehavior,mm as CutsceneCameraSchema,dm as CutsceneDefinitionSchema,xm as CutsceneEventSchema,cp as CutscenePreviewController,pm as CutsceneSceneSchema,cm as CutsceneTrackSchema,$ as DEFAULT_SNAP_SETTINGS,xt as DISK_TYPE,v as DROPPABLE_AREA_TYPE,Ft as Destructible3DBehavior,jt as DestructibleMesh,nm as DollyPathSchema,Dn as EntityJsonSchema,Pn as EntitySchema,he as EntityThumbnailCache,Ie as EventEmitterDelegate,lm as EventItemSchema,Sp as FOG_TYPE,kt as FirstPersonBehavior,Bt as FirstPersonEvent,Ct as FirstPersonFSM,Bp as FirstPersonPerspective,Wt as FirstPersonPresentation,Mt as FirstPersonShooterCoordinator,Vt as FirstPersonState,kp as Fixed2DPerspective,c as Fn,Yt as FractureOptions,fi as Game,pr as GameBridge,Kn as GameConfigJsonSchema,Jn as GameDeviceConfigJsonSchema,Vn as GameInputConfigSchema,Mn as GameInputPlayerConfigSchema,y as HOVER_AREA_TYPE,om as Howl,Ni as InstrumentDefinitionSchema,zi as InstrumentEffectSchema,Yi as InstrumentPresetSchema,Cp as IsometricPerspective,zt as Jumper2DBehavior,Nt as Jumper2DEvent,qt as Jumper2DFSM,It as Jumper2DState,Jt as Jumper3DBehavior,Kt as Jumper3DEvent,Qt as Jumper3DFSM,Ut as Jumper3DState,un as KeyboardMappingSchema,gt as LIGHT_TYPE,ai as LINE_TYPE,Tn as LineEntityDataSchema,Cn as MouseConfigSchema,wn as MouseMappingSchema,Xt as MultidirectionalSpaceShooterCoordinator,Ji as NoteClipSchema,hi as PARTICLE_SYSTEM_TYPE,it as PILL_TYPE,ct as PLANE_TYPE,et as PYRAMID_TYPE,$t as ParticleEmitterBehavior,_p as Perspectives,eo as Platformer2DBehavior,ro as Platformer2DEvent,to as Platformer2DFSM,oo as Platformer2DState,ao as Platformer3DBehavior,po as Platformer3DEvent,io as Platformer3DFSM,mo as Platformer3DState,Tt as RECT_TYPE,wi as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,Gi as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,Hi as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,_i as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,Fi as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,ji as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,Rp as RenderBundleManager,Pp as RenderStrategyManager,In as ResolutionInputSchema,no as Ricochet2DBehavior,fo as Ricochet2DEvent,xo as Ricochet2DFSM,lo as Ricochet2DState,so as Ricochet3DBehavior,co as Ricochet3DEvent,yo as Ricochet3DFSM,vo as Ricochet3DState,bi as RuntimeBoundary2DBehavior,Ti as RuntimeDynamicCircleBody2DBehavior,Zi as RuntimeGoalZone2DBehavior,Di as RuntimePlayerInput2DBehavior,gi as RuntimeRicochet2DBehavior,ui as RuntimeTriggerRegion2DBehavior,vt as SELECTION_BOUNDS_MARGIN,Et as SELECTION_THIN_AXIS_FRACTION,At as SELECTION_THIN_AXIS_MAX,St as SELECTION_THIN_AXIS_MIN,Jr as SPHERE_TYPE,ri as SPRITE_TYPE,ci as STAGE_STATE_CHANGE,am as SceneTransitionSchema,Eo as ScreenVisibilityBehavior,So as ScreenVisibilityFSM,Ao as ScreenWrapBehavior,ho as ScreenWrapEvent,Ro as ScreenWrapFSM,Po as ScreenWrapState,Vp as SecondPersonPerspective,Lo as Shooter2DBehavior,Ep as SimulationBody,Qi as SongClipSchema,$i as SongDefinitionSchema,Xi as SongLoopSchema,qi as SongNoteSchema,Ii as SongTrackSchema,Zn as SpriteEntityDataSchema,Nn as StageAssetLoaderConfigSchema,dn as StageBodyKind,yn as StageBoundaryDim,qn as StageConfigJsonSchema,vn as StageEventType,zn as StageGLTFAssetLoaderConfigSchema,gn as StageJsonSchema,Up as StageManager,En as StageRicochetDim,Sn as StageRicochetReflection,Ln as StageSchema,An as StageTopDownPlane,Xp as TEXT_TYPE,U as TRANSFORM_TOOLS,On as TextEntityDataSchema,jp as ThirdPersonPerspective,Oo as ThrusterBehavior,bo as ThrusterEvent,To as ThrusterFSM,Zo as ThrusterState,Ui as TimeSignatureSchema,Do as TopDownMovementBehavior,Mp as TopDownPerspective,go as TopDownShooterCoordinator,up as TransformGizmo,mr as VEC2_ONE,ir as VEC2_ZERO,fr as VEC3_ONE,nr as VEC3_ZERO,Yn as Vec3ComponentsSchema,Rn as Vector2Schema,bn as Vector3TupleSchema,_n as VirtualTouchButtonConfigSchema,jn as VirtualTouchButtonsConfigSchema,Bn as VirtualTouchConfigSchema,Fn as VirtualTouchJoystickConfigSchema,kn as VirtualTouchJoysticksConfigSchema,Hn as VirtualTouchPositionSchema,Gn as VirtualTouchStyleSchema,uo as WorldBoundary2DBehavior,wo as WorldBoundary2DEvent,Go as WorldBoundary2DFSM,Ho as WorldBoundary2DState,_o as WorldBoundary3DBehavior,Fo as WorldBoundary3DEvent,jo as WorldBoundary3DFSM,ko as WorldBoundary3DState,Lt as ZONE_TYPE,yp as ZylemActor,qr as ZylemBox,Xr as ZylemCone,at as ZylemCylinder,lt as ZylemDisk,S as ZylemDroppableArea,Ap as ZylemFog,on as ZylemGameElement,E as ZylemHoverArea,ut as ZylemLight,ii as ZylemLine,Ri as ZylemParticleSystem,mt as ZylemPill,dt as ZylemPlane,rt as ZylemPyramid,Zt as ZylemRect,Kr as ZylemSphere,ti as ZylemSprite,$p as ZylemText,Ot as ZylemZone,G as abs,ka as activeShot,en as announceBridgeReady,o as applyEntityGlow,rn as applySwatchesToSelection,Ip as applyTransformChanges,w as asin,u as atan,tp as audibleTrackIds,Ia as beatsPerBar,Ka as beatsToSeconds,ki as bindRuntimeDynamicCircleBody2DHandle,ur as boxCollision,Cr as boxMesh,pn as buildBoxCollider,nn as buildCapsuleCollider,xn as buildConvexHullCollider,fn as buildCylinderCollider,sn as buildHeightfieldCollider,an as buildRuntimeBody,mn as buildSphereCollider,ln as buildTrimeshCollider,cn as bundleRuntimeCollision,Om as callFunc,za as cameraTracks,Z as clamp,Q as clearGlobalSubscriptions,ap as clipsAt,Dp as closestAxisValue,Bo as computeWorldBoundary2DHits,Co as computeWorldBoundary3DHits,Gr as coneCollision,Vr as coneMesh,g as cos,Br as create,vp as createActor,R as createBackgroundShader,Ir as createBox,Np as createCamera,$r as createCone,Li as createCooldownIcon,qa as createCutscenePlayer,pt as createCylinder,st as createDisk,h as createDroppableArea,ft as createEntity,ni as createEntityFactory,t as createEntityGlowMaterial,Mo as createFirstPersonInputComponent,Vo as createFirstPersonMovementComponent,Wo as createFirstPersonStateComponent,hp as createFog,vi as createFollowTarget,xi as createGame,N as createGlobal,A as createHoverArea,pp as createInstrument,Yo as createJumpConfig2D,zo as createJumpConfig3D,No as createJumpInput2D,qo as createJumpInput3D,Io as createJumpState2D,Jo as createJumpState3D,wt as createLight,mi as createLine,i as createNodeMaterialFromTSL,Pi as createParticleSystem,Wp as createPerspective,Ko as createPhysicsBodyComponent,nt as createPill,yt as createPlane,Ei as createPlatformFollow,Qo as createPlatformer2DInputComponent,Uo as createPlatformer2DMovementComponent,Xo as createPlatformer2DStateComponent,$o as createPlatformer3DInputComponent,ea as createPlatformer3DMovementComponent,ra as createPlatformer3DStateComponent,tt as createPyramid,Dt as createRect,ta as createShooter2DStateComponent,hn as createSimulation,fp as createSongPlayer,Qr as createSphere,oi as createSprite,Kp as createStage,sp as createStageCutsceneHost,Si as createStrategyPan,ei as createText,oa as createThrusterInputComponent,aa as createThrusterMovementComponent,pa as createThrusterStateComponent,ia as createTopDownMovementComponent,ma as createTopDownMovementInputComponent,na as createTopDownMovementStateComponent,fa as createTransformComponent,Hm as createTransformStore,Op as createVariable,bt as createZone,Ta as crossfadeTransitionShader,Na as cutsceneLength,_r as cylinderCollision,Yr as cylinderMesh,ep as dbToGain,ee as debugState,Ne as defaultTouchControls,xa as defineBehavior,or as degreesToRadians,Lm as delay,Oi as destroy,yi as dispatchStageState,Ca as dollyPointAt,M as dot,Ga as easeValue,Bi as emitRuntimeGoal,Ci as emitRuntimeRicochet,Mi as emitRuntimeTriggerRegionEnter,rm as encodeWav,tm as encodeWavBlob,mp as ensureAudio,d as entityRepresentative,si as entitySpawner,Re as entityThumbnailCache,Xe as eulerToQuaternion,Va as evaluateCameraPose,Wa as evaluateCutscene,H as exp,bm as fadeOpacity,la as fireCooldown,sa as fireShooter2DIfRequested,s as float,B as floor,Qe as focusEntity,C as fract,rp as gainToDb,qe as gameConfig,wp as getActiveLevelDocument,xp as getActiveSongPlayer,ca as getCooldown,da as getCooldownStore,je as getDisplayAspect,ya as getEntityFacingAngle2D,q as getGlobal,K as getGlobals,Se as getHoveredEntity,ye as getHoveredEntityId,Wm as getPosition,ke as getPresetResolution,Dr as getRotation,Ee as getSelectedEntity,me as getSelectedEntityId,fe as getSelectedEntityIds,le as getSnapSettings,bp as getVariable,Ym as getVelocity,$m as getZylemBridge,ym as globalChange,vm as globalChanges,va as hasAnyWorldBoundary2DHit,Ea as hasAnyWorldBoundary3DHit,di as initStageStateDispatcher,gp as intersectPlane,np as isAudioReady,p as isGLSLShader,ga as isManagedRenderEntity,ie as isPickMode,a as isTSLShader,X as isTransformTool,_e as isWebGPUSupported,Ya as itemsBetween,We as joystickBaseSvg,Ye as joystickThumbSvg,V as length,_a as lerpPose,Ha as lerpVec3,ip as loadTone,j as max,Rt as measureObjectSelectionBounds,He as mergeInputConfigs,Xa as midiToFrequency,$a as midiToNoteName,k as min,b as mix,Y as mod,_m as move,hm as moveBy,Vm as moveForwardXY,Rm as moveTo,Fm as moveX,Bm as moveXY,Cm as moveXZ,jm as moveY,km as moveZ,O as normalize,xr as normalizeVec2,lr as normalizeVec3,e as objectVertexShader,I as onGlobalChange,J as onGlobalChanges,Zm as onPress,Dm as onRelease,Tp as onVariableChange,Zp as onVariableChanges,gr as packCollisionGroups,ht as padSelectionBounds,um as parallel,Be as parseResolution,Sa as particleEffect,Aa as particlePresets,pi as pickZylemLine,Fr as pillCollision,zr as pillMesh,Wi as pingPongBeep,jr as planeCollision,L as positionWorld,P as positionWorldDirection,_ as pow,Ba as previousShot,Hr as pyramidCollision,Wr as pyramidMesh,$e as quaternionToEuler,ar as radiansToDegrees,ha as registerCooldown,re as registerDebugEntityResolver,Ke as registerEntityFocusContext,em as renderSong,wm as repeat,Gm as repeatForever,Ra as resetCooldown,Am as resetEntityOpacity,Mm as resetVelocity,Pa as resolveAim2D,Ve as resolveButtonAccent,te as resolveDebugEntity,Za as resolveRenderCategory,Pt as resolveSelectionBounds,Me as resolveTouchTheme,Vi as ricochetSound,Pm as rotateBy,vr as rotateEuler,dr as rotateInDirection,Sr as rotateX,Er as rotateY,yr as rotateYEuler,Ar as rotateZ,Ma as sampleDollyPath,Fa as sceneAt,op as scheduleSong,Xm as screenCenterLookDeltas,Um as screenCenterLookTargets,Qa as secondsToBeats,gm as sequence,de as setAddType,Ai as setCameraFeed,lp as setCutsceneTransitionShaders,ae as setDebugTool,z as setGlobal,ce as setGridVisible,ve as setHoveredEntityId,oe as setPaused,pe as setPickMode,zm as setPosition,Nm as setPositionX,qm as setPositionY,Im as setPositionZ,Tr as setRotation,Zr as setRotationDegrees,Lr as setRotationDegreesX,Rr as setRotationDegreesY,br as setRotationDegreesZ,Pr as setRotationX,hr as setRotationY,Or as setRotationZ,Ae as setSelectedEntity,ne as setSelectedEntityId,xe as setSelectedEntityIds,se as setSnapSettings,Hp as setStageFrameProfilerEnabled,Lp as setVariable,Qm as shortestAngleDelta,ja as shotAt,D as sin,T as smoothstep,tr as snapScale,er as snapToIncrement,rr as snapVec3,Ja as songLengthBeats,Ua as songLengthSeconds,wr as sphereCollision,Mr as sphereMesh,qp as stageConfig,Qp as stageState,r as standardShader,F as step,Ue as streamLevel,li as streamLevelOnStage,Tm as throttle,La as tickCooldowns,f as time,sr as toThreeVector2,cr as toThreeVector3,ze as touchButtonSvg,Ce as touchThemes,m as uniform,Oa as updateBoundaryRicochet,Pe as useArrowsForAxes,Oe as useArrowsForDirections,Le as useArrowsForSecondaryAxes,ba as useBehavior,Ze as useIJKLForAxes,De as useIJKLForDirections,we as useMouse,ge as useMouseLook,ue as useScreenCenterLook,Ge as useVirtualControls,Te as useWASDForAxes,be as useWASDForDirections,Da as usesManagedRenderPath,n as uv,Em as variableChange,Sm as variableChanges,W as vec2,x as vec3,l as vec4,Jp as vessel,Km as wrapAround3D,Jm as wrapAroundXY,kr as zoneCollision,Je as zylemEventBus};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zylem/game-lib",
3
- "version": "0.9.8",
3
+ "version": "0.9.9",
4
4
  "type": "module",
5
5
  "description": "A powerful and easy-to-use framework for creating simple 3D digital interactive applications using TypeScript.",
6
6
  "license": "MIT",
@@ -255,8 +255,8 @@
255
255
  "@dgreenheck/three-pinata": "^2.0.1",
256
256
  "@sinclair/typebox": "^0.34.52",
257
257
  "@types/howler": "^2.2.13",
258
- "@zylem/behaviors": "^0.8.12",
259
- "@zylem/bridge": "^0.9.8",
258
+ "@zylem/behaviors": "^0.8.13",
259
+ "@zylem/bridge": "^0.9.9",
260
260
  "comlink": "^4.4.2",
261
261
  "howler": "^2.2.4",
262
262
  "idb-keyval": "^6.2.6",