@zylem/game-lib 0.6.4 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -2
- package/dist/actions.d.ts +321 -11
- package/dist/actions.js +1 -936
- package/dist/api/game-lib.api.json +54074 -0
- package/dist/api/game-lib.api.md +4544 -0
- package/dist/api/game-lib.d.ts +8258 -0
- package/dist/api/game-lib.typedoc.json +345421 -0
- package/dist/audio.d.ts +13 -0
- package/dist/audio.js +1 -0
- package/dist/base-node-life-cycle-D2NuN1VB.d.ts +151 -0
- package/dist/behavior.d.ts +2 -0
- package/dist/behavior.js +1 -0
- package/dist/blueprints-TbGY-h53.d.ts +162 -0
- package/dist/chunk-4QLJUQSJ.js +1 -0
- package/dist/chunk-7FR5JSQ2.js +1 -0
- package/dist/chunk-7GYFZKK7.js +1 -0
- package/dist/chunk-7WRQ2UAN.js +1 -0
- package/dist/chunk-BH53MBAZ.js +1 -0
- package/dist/chunk-BIGH6D34.js +0 -0
- package/dist/chunk-CM5YRNBJ.js +19 -0
- package/dist/chunk-COM6HJ2L.js +1 -0
- package/dist/chunk-D2PATZCC.js +1 -0
- package/dist/chunk-DFLI7ICU.js +0 -0
- package/dist/chunk-E3UBSUPX.js +1 -0
- package/dist/chunk-FKIKN7RP.js +24 -0
- package/dist/chunk-G4HONLWC.js +1 -0
- package/dist/chunk-IKWE2W6L.js +1 -0
- package/dist/chunk-IPWUDOV5.js +1 -0
- package/dist/chunk-JEHFHUH4.js +0 -0
- package/dist/chunk-JNKPTL77.js +1 -0
- package/dist/chunk-JQKS42G4.js +1 -0
- package/dist/chunk-M3XNO56P.js +1 -0
- package/dist/chunk-MSC2BEO5.js +1 -0
- package/dist/chunk-ORIDWL3T.js +0 -0
- package/dist/chunk-QB3NL7VQ.js +1 -0
- package/dist/chunk-QXVH6POE.js +1 -0
- package/dist/chunk-RXDTAWI2.js +29 -0
- package/dist/chunk-TAUWDQZF.js +9 -0
- package/dist/chunk-VS2D4B3W.js +1 -0
- package/dist/chunk-WQ3WMMZD.js +1 -0
- package/dist/chunk-XK63E4SX.js +1 -0
- package/dist/chunk-XNDS4YFR.js +1 -0
- package/dist/chunk-XNHVRFAK.js +1 -0
- package/dist/chunk-XRP4JJXL.js +1 -0
- package/dist/chunk-YHEWKN7N.js +1 -0
- package/dist/chunk-ZRT3ZQVH.js +1 -0
- package/dist/collision-builder-jF-toPIl.d.ts +38 -0
- package/dist/core.d.ts +223 -16
- package/dist/core.js +1 -12424
- package/dist/debug-state-BPT6jEog.d.ts +17 -0
- package/dist/debug.d.ts +76 -0
- package/dist/debug.js +1 -0
- package/dist/default-controls-0-vCnli7.d.ts +111 -0
- package/dist/{entity-vj-HTjzU.d.ts → entity-BdSI8CL3.d.ts} +119 -626
- package/dist/{entity-Bq_eNEDI.d.ts → entity-DZbFQ1Wg.d.ts} +4 -4
- package/dist/entity-type-map-Bd69SpAS.d.ts +928 -0
- package/dist/entity.d.ts +268 -0
- package/dist/entity.js +1 -0
- package/dist/events.d.ts +181 -0
- package/dist/events.js +1 -0
- package/dist/game-C1FHVqXl.d.ts +1886 -0
- package/dist/game-default-QHROHW2O.js +1 -0
- package/dist/game-interfaces-mchNYSZE.d.ts +90 -0
- package/dist/globals.d.ts +115 -0
- package/dist/globals.js +1 -0
- package/dist/graphics.d.ts +53 -0
- package/dist/graphics.js +1 -0
- package/dist/input-ui.d.ts +35 -0
- package/dist/input-ui.js +1 -0
- package/dist/input.d.ts +73 -0
- package/dist/input.js +1 -0
- package/dist/material-9vJ6SZaI.d.ts +126 -0
- package/dist/public.d.ts +38 -0
- package/dist/public.js +1 -0
- package/dist/runtime.d.ts +59 -0
- package/dist/runtime.js +1 -0
- package/dist/schema/entity.schema.json +244 -0
- package/dist/schema/game-config.schema.json +625 -0
- package/dist/schema/input-config.schema.json +499 -0
- package/dist/schema/stage-config.schema.json +93 -0
- package/dist/schema/stage.schema.json +271 -0
- package/dist/schema.d.ts +538 -0
- package/dist/schema.js +1 -0
- package/dist/stage-transition-CmGpV4tc.d.ts +46 -0
- package/dist/vector-CiSHbivc.d.ts +133 -0
- package/dist/web-components.d.ts +70 -0
- package/dist/web-components.js +1 -0
- package/dist/zylem-camera-C3bn6BTI.d.ts +575 -0
- package/package.json +70 -73
- package/dist/actions.js.map +0 -1
- package/dist/behavior/jumper-2d.d.ts +0 -114
- package/dist/behavior/jumper-2d.js +0 -711
- package/dist/behavior/jumper-2d.js.map +0 -1
- package/dist/behavior/platformer-3d.d.ts +0 -296
- package/dist/behavior/platformer-3d.js +0 -761
- package/dist/behavior/platformer-3d.js.map +0 -1
- package/dist/behavior/ricochet-2d.d.ts +0 -275
- package/dist/behavior/ricochet-2d.js +0 -425
- package/dist/behavior/ricochet-2d.js.map +0 -1
- package/dist/behavior/ricochet-3d.d.ts +0 -117
- package/dist/behavior/ricochet-3d.js +0 -443
- package/dist/behavior/ricochet-3d.js.map +0 -1
- package/dist/behavior/screen-visibility.d.ts +0 -79
- package/dist/behavior/screen-visibility.js +0 -358
- package/dist/behavior/screen-visibility.js.map +0 -1
- package/dist/behavior/screen-wrap.d.ts +0 -87
- package/dist/behavior/screen-wrap.js +0 -246
- package/dist/behavior/screen-wrap.js.map +0 -1
- package/dist/behavior/shooter-2d.d.ts +0 -79
- package/dist/behavior/shooter-2d.js +0 -180
- package/dist/behavior/shooter-2d.js.map +0 -1
- package/dist/behavior/thruster.d.ts +0 -11
- package/dist/behavior/thruster.js +0 -292
- package/dist/behavior/thruster.js.map +0 -1
- package/dist/behavior/top-down-movement.d.ts +0 -56
- package/dist/behavior/top-down-movement.js +0 -125
- package/dist/behavior/top-down-movement.js.map +0 -1
- package/dist/behavior/world-boundary-2d.d.ts +0 -142
- package/dist/behavior/world-boundary-2d.js +0 -235
- package/dist/behavior/world-boundary-2d.js.map +0 -1
- package/dist/behavior/world-boundary-3d.d.ts +0 -76
- package/dist/behavior/world-boundary-3d.js +0 -274
- package/dist/behavior/world-boundary-3d.js.map +0 -1
- package/dist/behavior-descriptor-BXnVR8Ki.d.ts +0 -159
- package/dist/blueprints-DmbK2dki.d.ts +0 -26
- package/dist/camera-4XO5gbQH.d.ts +0 -905
- package/dist/camera.d.ts +0 -6
- package/dist/camera.js +0 -1993
- package/dist/camera.js.map +0 -1
- package/dist/composition-BASvMKrW.d.ts +0 -218
- package/dist/core-CARRaS55.d.ts +0 -541
- package/dist/core.js.map +0 -1
- package/dist/entities-ChFirVL9.d.ts +0 -410
- package/dist/entities.d.ts +0 -9
- package/dist/entities.js +0 -4986
- package/dist/entities.js.map +0 -1
- package/dist/entity-types-DAu8sGJH.d.ts +0 -26
- package/dist/global-change-2JvMaz44.d.ts +0 -25
- package/dist/main.d.ts +0 -1353
- package/dist/main.js +0 -19525
- package/dist/main.js.map +0 -1
- package/dist/physics-pose-DCc4oE44.d.ts +0 -25
- package/dist/physics-protocol-BDD3P5W2.d.ts +0 -200
- package/dist/physics-worker.d.ts +0 -21
- package/dist/physics-worker.js +0 -306
- package/dist/physics-worker.js.map +0 -1
- package/dist/physics.d.ts +0 -205
- package/dist/physics.js +0 -577
- package/dist/physics.js.map +0 -1
- package/dist/stage-types-C19IhuzA.d.ts +0 -731
- package/dist/stage.d.ts +0 -52
- package/dist/stage.js +0 -8479
- package/dist/stage.js.map +0 -1
- package/dist/sync-state-machine-CZyspBpj.d.ts +0 -16
- package/dist/thruster-23lzoPZd.d.ts +0 -180
- package/dist/world-DfgxoNMt.d.ts +0 -105
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{b as fe}from"./chunk-7GYFZKK7.js";import{b as y}from"./chunk-COM6HJ2L.js";import{b as me,d as P,j as be,u as L,v as G}from"./chunk-JNKPTL77.js";import{a as v,b as ce,c as J}from"./chunk-JQKS42G4.js";import{l as ve}from"./chunk-XNDS4YFR.js";import{a as K,m as W}from"./chunk-XNHVRFAK.js";import{j as ye}from"./chunk-CM5YRNBJ.js";import{a as ge,b as f}from"./chunk-YHEWKN7N.js";import{c as S}from"./chunk-D2PATZCC.js";import{c as se,d as C,e as re,h as le,i as ue,j as pe,k as Z,l as x,m as de}from"./chunk-4QLJUQSJ.js";import{j as $}from"./chunk-7WRQ2UAN.js";import{g as he}from"./chunk-RXDTAWI2.js";import{k as b}from"./chunk-MSC2BEO5.js";function Le(){return{pressed:!1,released:!1,held:0}}function De(){return{value:0,held:0}}function D(a){let e=new Map;if(!a)return e;for(let[t,n]of Object.entries(a)){if(!n||n.length===0)continue;let i=[];for(let o of n){let[r,s]=(o||"").split(".");if(!r||!s)continue;let l=r.toLowerCase(),u=s.toLowerCase();if(l==="buttons"){let p={a:"A",b:"B",x:"X",y:"Y",start:"Start",select:"Select",l:"L",r:"R"}[u];p&&i.push({category:"buttons",property:p})}else if(l==="directions"){let p={up:"Up",down:"Down",left:"Left",right:"Right"}[u];p&&i.push({category:"directions",property:p})}else if(l==="shoulders"){let p={ltrigger:"LTrigger",rtrigger:"RTrigger"}[u];p&&i.push({category:"shoulders",property:p})}else if(l==="axes"){let p={left:{property:"Horizontal",direction:-1},right:{property:"Horizontal",direction:1},up:{property:"Vertical",direction:-1},down:{property:"Vertical",direction:1},secondaryleft:{property:"SecondaryHorizontal",direction:-1},secondaryright:{property:"SecondaryHorizontal",direction:1},secondaryup:{property:"SecondaryVertical",direction:-1},secondarydown:{property:"SecondaryVertical",direction:1}}[u];p&&i.push({category:"axes",property:p.property,axisDirection:p.direction})}}i.length>0&&e.set(t,i)}return e}function d(a,e){return!a&&!e?Le():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function g(a,e){return!a&&!e?De():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var w=class{keyStates=new Map;keyButtonStates=new Map;analogStates=new Map;compiledMapping;includeDefaultBase=!0;onKeyDown=({key:e})=>this.keyStates.set(e,!0);onKeyUp=({key:e})=>this.keyStates.set(e,!1);constructor(e,t){this.includeDefaultBase=t?.includeDefaultBase??!0,this.compiledMapping=D(e??null),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}dispose(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),this.keyStates.clear(),this.keyButtonStates.clear(),this.analogStates.clear()}isKeyPressed(e){return this.keyStates.get(e)||!1}handleButtonState(e,t){let n=this.keyButtonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.keyButtonStates.set(e,n));let i=this.isKeyPressed(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleAnalogState(e,t,n){let i=`${e}:${t}`,o=this.analogStates.get(i);return o||(o={value:0,held:0},this.analogStates.set(i,o)),o.value=this.getAxisValue(e,t),o.held=o.value!==0?o.held+n:0,o}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map;for(let[i,o]of this.compiledMapping.entries()){let r=null;for(let s of o)if(s.category==="axes")n.has(s.property)||n.set(s.property,0),this.isKeyPressed(i)&&n.set(s.property,n.get(s.property)+s.axisDirection);else{r||(r=this.handleButtonState(i,t));let l=e[s.category]??={};l[s.property]=d(l[s.property],r)}}if(n.size>0){e.axes||(e.axes={});for(let[i,o]of n.entries()){let r=`custom:${i}`,s=this.analogStates.get(r);s||(s={value:0,held:0},this.analogStates.set(r,s)),s.value=o,s.held=o!==0?s.held+t:0,e.axes[i]=g(e.axes[i],s)}}return e}getInput(e){let t={};return this.includeDefaultBase&&(t.buttons={A:this.handleButtonState("z",e),B:this.handleButtonState("x",e),X:this.handleButtonState("a",e),Y:this.handleButtonState("s",e),Start:this.handleButtonState(" ",e),Select:this.handleButtonState("Enter",e),L:this.handleButtonState("q",e),R:this.handleButtonState("e",e)},t.directions={Up:this.handleButtonState("ArrowUp",e),Down:this.handleButtonState("ArrowDown",e),Left:this.handleButtonState("ArrowLeft",e),Right:this.handleButtonState("ArrowRight",e)},t.shoulders={LTrigger:this.handleButtonState("Q",e),RTrigger:this.handleButtonState("E",e)}),this.applyCustomMapping(t,e)}getName(){return"keyboard"}getAxisValue(e,t){return(this.isKeyPressed(t)?1:0)-(this.isKeyPressed(e)?1:0)}isConnected(){return!0}};var k=class{gamepadIndex;connected=!1;buttonStates={};analogStates={};onConnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!0)};onDisconnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!1)};constructor(e){this.gamepadIndex=e,window.addEventListener("gamepadconnected",this.onConnected),window.addEventListener("gamepaddisconnected",this.onDisconnected)}dispose(){window.removeEventListener("gamepadconnected",this.onConnected),window.removeEventListener("gamepaddisconnected",this.onDisconnected),this.buttonStates={},this.analogStates={}}handleButtonState(e,t,n){let i=this.buttonStates[e];i||(i={pressed:!1,released:!1,held:0},this.buttonStates[e]=i);let o=t.buttons[e].pressed;return i.pressed=o&&i.held===0,i.released=!o&&i.held>0,i.held=o?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates[e];return i||(i={value:0,held:0},this.analogStates[e]=i),i.value=t.axes[e],i.held=i.value!==0?i.held+n:0,i}getInput(e){let t=navigator.getGamepads()[this.gamepadIndex];return t?{buttons:{A:this.handleButtonState(0,t,e),B:this.handleButtonState(1,t,e),X:this.handleButtonState(2,t,e),Y:this.handleButtonState(3,t,e),Start:this.handleButtonState(9,t,e),Select:this.handleButtonState(8,t,e),L:this.handleButtonState(4,t,e),R:this.handleButtonState(5,t,e)},directions:{Up:this.handleButtonState(12,t,e),Down:this.handleButtonState(13,t,e),Left:this.handleButtonState(14,t,e),Right:this.handleButtonState(15,t,e)},axes:{Horizontal:this.handleAnalogState(0,t,e),Vertical:this.handleAnalogState(1,t,e),SecondaryHorizontal:this.handleAnalogState(2,t,e),SecondaryVertical:this.handleAnalogState(3,t,e)},shoulders:{LTrigger:this.handleButtonState(6,t,e),RTrigger:this.handleButtonState(7,t,e)}}:{}}getName(){return`gamepad-${this.gamepadIndex+1}`}isConnected(){return this.connected}};var ke=.002,T=class{buttonStates=new Map;analogStates=new Map;compiledMapping;movementX=0;movementY=0;pointerX=0;pointerY=0;mouseButtonDown=new Set;sensitivity;usePointerLock;isLocked=!1;targetElement;onMouseMove=e=>{this.movementX+=e.movementX,this.movementY+=e.movementY,this.pointerX=e.clientX/window.innerWidth,this.pointerY=e.clientY/window.innerHeight};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&this.targetElement.requestPointerLock())};onMouseUp=e=>{this.mouseButtonDown.delete(e.button)};onContextMenu=e=>{e.preventDefault()};onPointerLockChange=()=>{this.isLocked=document.pointerLockElement===this.targetElement};constructor(e,t){this.sensitivity=e?.sensitivity??ke,this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=D(e?.mapping??null),this.targetElement=t??document.body,window.addEventListener("mousemove",this.onMouseMove),this.targetElement.addEventListener("mousedown",this.onMouseDown),this.targetElement.addEventListener("mouseup",this.onMouseUp),this.targetElement.addEventListener("contextmenu",this.onContextMenu),this.usePointerLock&&document.addEventListener("pointerlockchange",this.onPointerLockChange)}dispose(){window.removeEventListener("mousemove",this.onMouseMove),this.targetElement.removeEventListener("mousedown",this.onMouseDown),this.targetElement.removeEventListener("mouseup",this.onMouseUp),this.targetElement.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.isLocked&&document.exitPointerLock(),this.buttonStates.clear(),this.analogStates.clear(),this.mouseButtonDown.clear(),this.movementX=0,this.movementY=0}handleMouseButton(e,t){let n=this.buttonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.buttonStates.set(e,n));let i=this.mouseButtonDown.has(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleMovementAxis(e,t){let n=this.analogStates.get(e);n||(n={value:0,held:0},this.analogStates.set(e,n));let i=e==="x"?this.movementX:this.movementY;return n.value=Math.max(-1,Math.min(1,i*this.sensitivity)),n.held=n.value!==0?n.held+t:0,n}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map,i={leftbutton:()=>this.handleMouseButton(0,t),rightbutton:()=>this.handleMouseButton(2,t),middlebutton:()=>this.handleMouseButton(1,t)};for(let[o,r]of this.compiledMapping.entries()){let s=o.toLowerCase();for(let l of r)if(l.category==="axes")n.has(l.property)||n.set(l.property,0),s==="movex"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementX*this.sensitivity))*l.axisDirection):s==="movey"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementY*this.sensitivity))*l.axisDirection):s in i&&this.mouseButtonDown.has(this.buttonIndexForAction(s))&&n.set(l.property,n.get(l.property)+l.axisDirection);else{let u=i[s];if(u){let m=u();if(m){let p=e[l.category]??={};p[l.property]=d(p[l.property],m)}}}}if(n.size>0){e.axes||(e.axes={});for(let[o,r]of n.entries()){let s=`custom:${o}`,l=this.analogStates.get(s);l||(l={value:0,held:0},this.analogStates.set(s,l)),l.value=Math.max(-1,Math.min(1,r)),l.held=r!==0?l.held+t:0,e.axes[o]=g(e.axes[o],l)}}return e}buttonIndexForAction(e){switch(e){case"leftbutton":return 0;case"middlebutton":return 1;case"rightbutton":return 2;default:return-1}}getInput(e){let t={axes:{Horizontal:{value:0,held:0},Vertical:{value:0,held:0},SecondaryHorizontal:this.handleMovementAxis("x",e),SecondaryVertical:this.handleMovementAxis("y",e)},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(t,e)}getName(){return"mouse"}isConnected(){return!0}};function R(a={}){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent,t=/android/i.test(e)||/iPad|iPhone|iPod/.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1,o=a.viewportSize?.width??window.innerWidth??0,r=a.viewportSize?.height??window.innerHeight??0,s=Math.max(o,r),l=s===0||s<=1024;return a.allowViewportOnly&&a.viewportSize?l:t||(n||i)&&l}var ze=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],Ae=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),Ve={A:{size:72,label:"A",position:{right:98,bottom:44}},B:{size:72,label:"B",position:{right:24,bottom:108}},X:{size:72,label:"X",position:{right:172,bottom:108}},Y:{size:72,label:"Y",position:{right:98,bottom:172}},Start:{size:64,label:"Start",position:{left:"50%",top:24,transform:"translateX(28px)"}},Select:{size:64,label:"Select",position:{left:"50%",top:24,transform:"translateX(-108px)"}},L:{size:62,label:"L",position:{left:28,bottom:184}},R:{size:62,label:"R",position:{right:236,bottom:184}},LTrigger:{size:76,label:"LT",position:{left:24,top:24}},RTrigger:{size:76,label:"RT",position:{right:24,top:24}},Up:{enabled:!1,size:64,label:"Up"},Down:{enabled:!1,size:64,label:"Down"},Left:{enabled:!1,size:64,label:"Left"},Right:{enabled:!1,size:64,label:"Right"}},He={left:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"Horizontal",verticalAxis:"Vertical",emitDirections:!0,position:{left:24,bottom:24}},right:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"SecondaryHorizontal",verticalAxis:"SecondaryVertical",emitDirections:!1,position:{right:24,bottom:236}}},I=class{config;targetElement;buttonStates=new Map;analogStates=new Map;buttons=new Map;joysticks=new Map;rootElement=null;enabled=!1;onPointerMove=e=>{for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.updateJoystickFromPoint(t,e.clientX,e.clientY))};onPointerUp=e=>{for(let t of this.buttons.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseButton(t));for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseJoystick(t))};onWindowBlur=()=>{for(let e of this.buttons.values())this.releaseButton(e);for(let e of this.joysticks.values())this.releaseJoystick(e)};constructor(e,t){this.config=e??{},this.targetElement=t??document.body,this.enabled=this.resolveEnabledState(),this.enabled&&(this.mountControls(),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),window.addEventListener("pointercancel",this.onPointerUp),window.addEventListener("blur",this.onWindowBlur))}getInput(e){if(!this.enabled)return{};let t={};for(let n of this.buttons.values()){let i=this.handleButtonState(`button:${n.slot}`,n.pointerId!==null,e);this.assignButtonState(t,this.resolveButtonTarget(n.slot),i)}for(let n of this.joysticks.values()){let i=this.handleAnalogState(`joystick:${n.id}:x`,n.valueX,e),o=this.handleAnalogState(`joystick:${n.id}:y`,n.valueY,e);this.assignAxisState(t,n.config.horizontalAxis,i),this.assignAxisState(t,n.config.verticalAxis,o),n.config.emitDirections&&(this.assignButtonState(t,this.resolveButtonTarget("Left"),this.handleButtonState(`joystick:${n.id}:left`,n.valueX<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Right"),this.handleButtonState(`joystick:${n.id}:right`,n.valueX>=n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Up"),this.handleButtonState(`joystick:${n.id}:up`,n.valueY<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Down"),this.handleButtonState(`joystick:${n.id}:down`,n.valueY>=n.config.directionThreshold,e)))}return t}getName(){return"virtual-touch"}isConnected(){return this.enabled}dispose(){window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerUp),window.removeEventListener("blur",this.onWindowBlur),this.rootElement?.remove(),this.rootElement=null,this.buttons.clear(),this.joysticks.clear(),this.buttonStates.clear(),this.analogStates.clear()}resolveEnabledState(){return typeof window>"u"||typeof document>"u"?!1:this.config.enabled===!0?!0:this.config.enabled===!1?!1:R()}mountControls(){this.rootElement=document.createElement("div"),this.rootElement.className="zylem-virtual-touch",this.rootElement.dataset.zylemTouchRoot="true",this.rootElement.style.position="absolute",this.rootElement.style.inset="0",this.rootElement.style.pointerEvents="none",this.rootElement.style.touchAction="none",this.rootElement.style.userSelect="none",this.rootElement.style.WebkitUserSelect="none",this.rootElement.style.WebkitTouchCallout="none",this.rootElement.style.color="rgba(245, 247, 255, 0.96)",this.rootElement.style.zIndex="20",this.appendClassName(this.rootElement,this.config.className),E(this.rootElement,this.config.style),this.rootElement.addEventListener("contextmenu",e=>e.preventDefault());for(let[e,t]of this.resolveButtons())this.rootElement.appendChild(this.createButton(e,t));for(let[e,t]of this.resolveJoysticks())this.rootElement.appendChild(this.createJoystick(e,t));this.targetElement.appendChild(this.rootElement)}resolveButtons(){if(this.config.buttons===!1)return[];let e=this.config.buttons,t=[];for(let n of ze){let i=Ve[n],o=e?.[n];if(o===!1)continue;let r={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},label:o?.label??i.label??n,size:o?.size??i.size??72};r.enabled!==!1&&t.push([n,r])}return t}resolveJoysticks(){if(this.config.joysticks===!1)return[];let e=this.config.joysticks,t=[];for(let n of["left","right"]){let i=He[n],o=e?.[n];if(o===!1)continue;let r={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},svg:{...i.svg,...o?.svg},size:o?.size??i.size??140,thumbSize:o?.thumbSize??i.thumbSize??58,maxDistance:o?.maxDistance??i.maxDistance??44,deadzone:o?.deadzone??i.deadzone??.12,directionThreshold:o?.directionThreshold??i.directionThreshold??.34,horizontalAxis:o?.horizontalAxis??i.horizontalAxis??"Horizontal",verticalAxis:o?.verticalAxis??i.verticalAxis??"Vertical",emitDirections:o?.emitDirections??i.emitDirections??!1};r.enabled!==!1&&t.push([n,r])}return t}createButton(e,t){let n=document.createElement("button"),i=document.createElement("div");n.type="button",n.ariaLabel=t.label,n.className=`zylem-virtual-touch__button zylem-virtual-touch__button--${e}`,n.dataset.zylemTouchButton=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.padding="0",n.style.margin="0",n.style.border="0",n.style.background="transparent",n.style.pointerEvents="auto",n.style.touchAction="none",n.style.cursor="pointer",n.style.appearance="none",n.style.outline="none",n.style.userSelect="none",n.style.WebkitTapHighlightColor="transparent",E(n,t.position),E(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__button-content",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.transform="scale(1)",i.style.transformOrigin="center",i.style.transition="transform 120ms ease, opacity 120ms ease",i.style.opacity="0.92",i.innerHTML=t.svg??_e(t.label),n.appendChild(i),n.addEventListener("pointerdown",r=>{if(!Se(r))return;let s=this.buttons.get(e);!s||s.pointerId!==null||(this.consumeEvent(r),s.pointerId=r.pointerId,this.updateButtonVisual(s,!0))});let o={slot:e,config:t,element:n,content:i,pointerId:null};return this.buttons.set(e,o),n}createJoystick(e,t){let n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");n.className=`zylem-virtual-touch__joystick zylem-virtual-touch__joystick--${e}`,n.dataset.zylemTouchJoystick=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.pointerEvents="auto",n.style.touchAction="none",n.style.userSelect="none",E(n,t.position),E(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__joystick-base",i.style.position="absolute",i.style.inset="0",i.style.pointerEvents="none",i.style.opacity="0.88",i.style.transition="opacity 120ms ease",i.innerHTML=t.svg?.base??Ne(),o.className="zylem-virtual-touch__joystick-thumb",o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.width=`${t.thumbSize}px`,o.style.height=`${t.thumbSize}px`,o.style.pointerEvents="none",o.style.transform="translate(-50%, -50%) translate(0px, 0px)",o.style.transition="transform 60ms linear, opacity 120ms ease",o.style.opacity="0.94",o.innerHTML=t.svg?.thumb??Fe(),n.append(i,o);let r={id:e,config:t,element:n,base:i,thumb:o,pointerId:null,centerX:0,centerY:0,rawX:0,rawY:0,valueX:0,valueY:0};return this.joysticks.set(e,r),n.addEventListener("pointerdown",s=>{if(!Se(s))return;let l=this.joysticks.get(e);if(!l||l.pointerId!==null)return;this.consumeEvent(s);let u=l.element.getBoundingClientRect();l.pointerId=s.pointerId,l.centerX=u.left+u.width/2,l.centerY=u.top+u.height/2,this.updateJoystickVisual(l,!0),this.updateJoystickFromPoint(l,s.clientX,s.clientY)}),n}handleButtonState(e,t,n){let i=this.buttonStates.get(e);return i||(i={pressed:!1,released:!1,held:0},this.buttonStates.set(e,i)),i.pressed=t&&i.held===0,i.released=!t&&i.held>0,i.held=t?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates.get(e);return i||(i={value:0,held:0},this.analogStates.set(e,i)),i.value=t,i.held=t!==0?i.held+n:0,i}assignAxisState(e,t,n){e.axes||(e.axes={}),e.axes[t]=g(e.axes[t],n)}assignButtonState(e,t,n){if(t.category==="buttons"){e.buttons??={},e.buttons[t.property]=d(e.buttons[t.property],n);return}if(t.category==="directions"){e.directions??={},e.directions[t.property]=d(e.directions[t.property],n);return}e.shoulders??={},e.shoulders[t.property]=d(e.shoulders[t.property],n)}resolveButtonTarget(e){switch(e){case"LTrigger":case"RTrigger":return{category:"shoulders",property:e};case"Up":case"Down":case"Left":case"Right":return{category:"directions",property:e};default:return{category:"buttons",property:e}}}updateJoystickFromPoint(e,t,n){let i=t-e.centerX,o=n-e.centerY,r=Math.hypot(i,o),s=e.config.maxDistance,l=r>s&&r>0?s/r:1;e.rawX=i*l,e.rawY=o*l;let u=Oe(e.rawX/s,e.rawY/s,e.config.deadzone);e.valueX=u.x,e.valueY=u.y,e.thumb.style.transform=`translate(-50%, -50%) translate(${e.rawX}px, ${e.rawY}px)`}releaseButton(e){e.pointerId=null,this.updateButtonVisual(e,!1)}releaseJoystick(e){e.pointerId=null,e.rawX=0,e.rawY=0,e.valueX=0,e.valueY=0,e.thumb.style.transform="translate(-50%, -50%) translate(0px, 0px)",this.updateJoystickVisual(e,!1)}updateButtonVisual(e,t){e.element.dataset.active=String(t),e.content.style.transform=t?"scale(0.94)":"scale(1)",e.content.style.opacity=t?"1":"0.92"}updateJoystickVisual(e,t){e.element.dataset.active=String(t),e.base.style.opacity=t?"1":"0.88",e.thumb.style.opacity=t?"1":"0.94"}consumeEvent(e){e.cancelable&&e.preventDefault(),e.stopPropagation()}appendClassName(e,t){t&&(e.className=`${e.className} ${t}`.trim())}};function E(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!Ae.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function Oe(a,e,t){let n=Math.hypot(a,e);if(n===0||n<=t)return{x:0,y:0};let o=Math.min(1,(n-t)/Math.max(1-t,1e-4))/n;return{x:a*o,y:e*o}}function _e(a){let e=Ue(a);return`
|
|
2
|
+
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true">
|
|
3
|
+
<circle cx="50" cy="50" r="45" fill="rgba(12,18,24,0.72)" stroke="currentColor" stroke-width="4" />
|
|
4
|
+
<circle cx="50" cy="50" r="34" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
|
|
5
|
+
<text
|
|
6
|
+
x="50"
|
|
7
|
+
y="56"
|
|
8
|
+
text-anchor="middle"
|
|
9
|
+
font-family="ui-sans-serif, system-ui, sans-serif"
|
|
10
|
+
font-size="${e.length>2?24:34}"
|
|
11
|
+
font-weight="700"
|
|
12
|
+
fill="currentColor"
|
|
13
|
+
>${e}</text>
|
|
14
|
+
</svg>
|
|
15
|
+
`}function Ne(){return`
|
|
16
|
+
<svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
|
|
17
|
+
<circle cx="70" cy="70" r="62" fill="rgba(10,16,20,0.64)" stroke="currentColor" stroke-width="4" />
|
|
18
|
+
<circle cx="70" cy="70" r="40" fill="rgba(255,255,255,0.04)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
|
|
19
|
+
</svg>
|
|
20
|
+
`}function Fe(){return`
|
|
21
|
+
<svg viewBox="0 0 64 64" width="100%" height="100%" aria-hidden="true">
|
|
22
|
+
<circle cx="32" cy="32" r="28" fill="rgba(22,30,38,0.9)" stroke="currentColor" stroke-width="3.5" />
|
|
23
|
+
</svg>
|
|
24
|
+
`}function Ue(a){return a.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Se(a){return a.pointerType==="touch"}var z=class{inputMap=new Map;currentInputs={};previousInputs={};targetElement;mouseTargetElement;constructor(e,t){this.targetElement=t?.targetElement,this.mouseTargetElement=t?.mouseTargetElement??t?.targetElement;let n=this.buildPlayerEntries(e);for(let{player:i,config:o,gamepadIndex:r,isP1:s}of n)this.addConfigurableProviders(i,o,s),this.addInputProvider(i,new k(r))}configure(e){let t=this.buildPlayerEntries(e);for(let{player:n,config:i,isP1:o}of t){let s=(this.inputMap.get(n)??[]).filter(l=>l instanceof w||l instanceof T||l instanceof I?(l.dispose(),!1):!0);this.inputMap.set(n,[...this.createConfigurableProviders(i,o),...s])}}addInputProvider(e,t){this.inputMap.has(e)||this.inputMap.set(e,[]),this.inputMap.get(e)?.push(t)}dispose(){for(let e of this.inputMap.values())for(let t of e)t.dispose?.();this.inputMap.clear(),this.currentInputs={},this.previousInputs={}}getInputs(e){let t={};return this.inputMap.forEach((n,i)=>{let o=`p${i}`,r=n.reduce((s,l)=>{let u=l.getInput(e);return this.mergeInputs(s,u)},{});t[o]={playerNumber:i,...r}}),t}buildPlayerEntries(e){return[{player:1,config:e?.p1,gamepadIndex:0,isP1:!0},{player:2,config:e?.p2,gamepadIndex:1,isP1:!1},{player:3,config:e?.p3,gamepadIndex:2,isP1:!1},{player:4,config:e?.p4,gamepadIndex:3,isP1:!1},{player:5,config:e?.p5,gamepadIndex:4,isP1:!1},{player:6,config:e?.p6,gamepadIndex:5,isP1:!1},{player:7,config:e?.p7,gamepadIndex:6,isP1:!1},{player:8,config:e?.p8,gamepadIndex:7,isP1:!1}]}addConfigurableProviders(e,t,n){for(let i of this.createConfigurableProviders(t,n))this.addInputProvider(e,i)}createConfigurableProviders(e,t){let n=[];if(e?.key){let i=e.includeDefaults??t;n.push(new w(e.key,{includeDefaultBase:i}))}else t&&n.push(new w);return e?.mouse&&n.push(new T(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new I(e.touch,this.targetElement)),n}mergeInputs(e,t){return{buttons:{A:d(e.buttons?.A,t.buttons?.A),B:d(e.buttons?.B,t.buttons?.B),X:d(e.buttons?.X,t.buttons?.X),Y:d(e.buttons?.Y,t.buttons?.Y),Start:d(e.buttons?.Start,t.buttons?.Start),Select:d(e.buttons?.Select,t.buttons?.Select),L:d(e.buttons?.L,t.buttons?.L),R:d(e.buttons?.R,t.buttons?.R)},directions:{Up:d(e.directions?.Up,t.directions?.Up),Down:d(e.directions?.Down,t.directions?.Down),Left:d(e.directions?.Left,t.directions?.Left),Right:d(e.directions?.Right,t.directions?.Right)},axes:{Horizontal:g(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:g(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:g(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:g(e.axes?.SecondaryVertical,t.axes?.SecondaryVertical)},shoulders:{LTrigger:d(e.shoulders?.LTrigger,t.shoulders?.LTrigger),RTrigger:d(e.shoulders?.RTrigger,t.shoulders?.RTrigger)},pointer:t.pointer??e.pointer}}};var A=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=j(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=Xe.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=j()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:j())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function j(){return performance.now()}function Xe(){this._document.hidden===!1&&this.reset()}var B={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},V=class{container;canvas;aspectRatio;onResize;handleResizeBound;resizeObserver=null;constructor(e){this.container=e.container,this.canvas=e.canvas,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio),this.onResize=e.onResize,this.handleResizeBound=this.apply.bind(this)}attach(){window.addEventListener("resize",this.handleResizeBound),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(this.handleResizeBound),this.resizeObserver.observe(this.container)),this.apply()}detach(){window.removeEventListener("resize",this.handleResizeBound),this.resizeObserver?.disconnect(),this.resizeObserver=null}measure(){let e=this.container.getBoundingClientRect(),t=Math.round(e.width||this.container.clientWidth||0),n=Math.round(e.height||this.container.clientHeight||0);if(t>0&&n>0){if(t/n>this.aspectRatio){let u=n;return{width:Math.round(u*this.aspectRatio),height:u}}let s=t,l=Math.round(s/this.aspectRatio);return{width:s,height:l}}if(t>0){let r=t,s=Math.round(r/this.aspectRatio);return{width:r,height:s}}if(n>0){let r=n;return{width:Math.round(r*this.aspectRatio),height:r}}let i=window.innerWidth,o=Math.round(i/this.aspectRatio);return{width:i,height:o}}apply(){let{width:e,height:t}=this.measure();this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.onResize?.(e,t)}};var we={NES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x240",width:256,height:240,notes:"Standard NTSC; effective 240p."}]},SNES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x224",width:256,height:224,notes:"Common 240p-equivalent mode."},{key:"512x448",width:512,height:448,notes:"Hi-res interlaced (480i)."}]},N64:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Common 240p mode."},{key:"640x480",width:640,height:480,notes:"Higher resolution (480i)."}]},PS1:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Progressive 240p common."},{key:"640x480",width:640,height:480,notes:"Interlaced 480i for higher detail."}]},PS2:{displayAspect:1.3333333333333333,resolutions:[{key:"640x480",width:640,height:480,notes:"480i/480p baseline."},{key:"720x480",width:720,height:480,notes:"480p (widescreen capable in some titles)."},{key:"1280x720",width:1280,height:720,notes:"720p (select titles)."}]},PS5:{displayAspect:1.7777777777777777,resolutions:[{key:"720x480",width:720,height:480,notes:"Legacy compatibility."},{key:"1280x720",width:1280,height:720,notes:"720p."},{key:"1920x1080",width:1920,height:1080,notes:"1080p."},{key:"2560x1440",width:2560,height:1440,notes:"1440p."},{key:"3840x2160",width:3840,height:2160,notes:"4K (up to 120Hz)."},{key:"7680x4320",width:7680,height:4320,notes:"8K (limited)."}]},XboxOne:{displayAspect:1.7777777777777777,resolutions:[{key:"1280x720",width:1280,height:720,notes:"720p (original)."},{key:"1920x1080",width:1920,height:1080,notes:"1080p (original)."},{key:"3840x2160",width:3840,height:2160,notes:"4K UHD (S/X models)."}]},MobilePortrait:{displayAspect:.5625,resolutions:[{key:"360x640",width:360,height:640,notes:"Low-density phone portrait baseline."},{key:"720x1280",width:720,height:1280,notes:"HD phone portrait."},{key:"1080x1920",width:1080,height:1920,notes:"Full HD phone portrait."}]}};function q(a){return we[a].displayAspect}function Q(a,e){let t=we[a]?.resolutions||[];if(!e)return t[0];let n=e.toLowerCase().replace(/\s+/g,"").replace("\xD7","x");return t.find(i=>i.key.toLowerCase()===n)}function ee(a){if(!a)return null;let t=String(a).toLowerCase().trim().replace(/\s+/g,"").replace("\xD7","x").match(/^(\d+)x(\d+)$/);if(!t)return null;let n=parseInt(t[1],10),i=parseInt(t[2],10);return!Number.isFinite(n)||!Number.isFinite(i)?null:{width:n,height:i}}var te=null,ne=class{constructor(e,t,n,i,o,r,s,l,u,m,p,h,Y){this.id=e;this.globals=t;this.stages=n;this.debug=i;this.time=o;this.input=r;this.aspectRatio=s;this.internalResolution=l;this.fullscreen=u;this.bodyBackground=m;this.container=p;this.containerId=h;this.canvas=Y}};function Ye(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?R({viewportSize:a.viewportSize,allowViewportOnly:!0}):R()}function Ze(a,e){if(e)return e;if(a){let i=document.getElementById(a);if(i)return i}let t=a||"zylem-root",n=document.createElement("main");return n.setAttribute("id",t),n.style.position="relative",n.style.width="100%",n.style.height="100%",document.body.appendChild(n),n}function Je(a){let e=a?.id??"zylem";return{id:e,globals:a?.globals??{},stages:a?.stages??[],debug:!!a?.debug,time:a?.time??0,input:a?.input,aspectRatio:B.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var Ce=360;function xe(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return te;let i=ee(a);if(i)return i;if(e){let o=Q(e,a);if(o)return{width:o.width,height:o.height}}return}let t=a.width,n=a.height;if(Number.isFinite(t)&&Number.isFinite(n))return{width:t,height:n}}function Ke(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return B[a]??t;if(e)try{return q(e)||t}catch{return t}return n?n.width/n.height:t}function $e(a){let e=Number.isFinite(a)&&a>0?a:B.SixteenByNine;if(e>=1){let i=Ce;return{width:Math.round(i*e),height:i}}let t=Ce,n=Math.round(t/e);return{width:t,height:n}}function M(a,e={}){let t=Je({id:a?.id??"zylem",debug:!!a?.debug,time:a?.time??0,input:a?.input,stages:a?.stages??[],globals:a?.globals??{}}),n=a?.containerId??t.containerId,i=Ze(n,a?.container??null),o=a?.mobile,r=Ye(e),s=r?o?.preset??a?.preset:a?.preset,l=xe(a?.resolution,a?.preset),u=xe(o?.resolution,o?.preset??a?.preset),m=(r?Ge(u):void 0)??Ge(l),p=r?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,h=Ke(p,s,t.aspectRatio,m),Y=We(r,u,l,h),Ie=a?.fullscreen??t.fullscreen,Be=a?.bodyBackground??t.bodyBackground,Me=a?.canvas??void 0,Pe=je(a?.input??t.input,o?.controls);return new ne(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,Pe,h,Y,Ie,Be,i,n,Me)}function Ge(a){if(a)return a}function We(a,e,t,n){if(a)return e===te?void 0:e??$e(n);if(t!==te)return t}function je(a,e){if(!e)return a;let n=he("p1",{enabled:"auto",...e===!0?{}:e});return b(n,a??{})}function qe(a){return{...a}}var H=class{id;container;canvas;bodyBackground;fullscreen;aspectRatio;ratioDelegate=null;overlayContainer=null;constructor(e){this.id=e.id,this.container=this.ensureContainer(e.containerId??e.id,e.container),this.canvas=e.canvas??document.createElement("canvas"),this.bodyBackground=e.bodyBackground,this.fullscreen=!!e.fullscreen,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio)}applyBodyBackground(){this.bodyBackground&&(document.body.style.background=this.bodyBackground)}mountCanvas(){this.mountChildren(this.canvas)}mountRenderer(e,t){this.mountChildren(e),this.canvas=e,this.attachAspectRatio(t)}getOverlayContainer(){return this.ensureOverlayContainer()}centerIfFullscreen(){if(!this.fullscreen)return;let e=this.container.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.position="relative",e.inset="0"}attachAspectRatio(e){this.ratioDelegate?(this.ratioDelegate.canvas=this.canvas,this.ratioDelegate.onResize=e,this.ratioDelegate.aspectRatio=this.aspectRatio,this.ratioDelegate.apply()):(this.ratioDelegate=new V({container:this.container,canvas:this.canvas,aspectRatio:this.aspectRatio,onResize:e}),this.ratioDelegate.attach())}setAspectRatio(e){this.aspectRatio=e,this.ratioDelegate&&(this.ratioDelegate.aspectRatio=e,this.ratioDelegate.apply())}reapplyLayout(){this.ratioDelegate?.apply()}destroy(){this.ratioDelegate?.detach(),this.ratioDelegate=null}mountChildren(e){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.appendChild(e),this.container.appendChild(this.ensureOverlayContainer())}ensureOverlayContainer(){if(this.overlayContainer)return this.overlayContainer;let e=document.createElement("div");return e.dataset.zylemOverlayRoot="true",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.touchAction="none",e.style.zIndex="10",this.overlayContainer=e,e}ensureContainer(e,t){if(t)return t;if(e){let o=document.getElementById(e);if(o)return o}let n=e||this.id||"zylem-root",i=document.createElement("main");return i.setAttribute("id",n),i.style.position="relative",i.style.width="100%",i.style.height="100%",document.body.appendChild(i),i}};import Qe from"stats.js";import{subscribe as et}from"valtio/vanilla";var O=class{statsRef=null;unsubscribe=null;constructor(){this.updateDebugUI(),this.unsubscribe=et(v,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}updateDebugUI(){v.enabled&&!this.statsRef?(this.statsRef=new Qe,this.statsRef.showPanel(0),this.statsRef.dom.style.position="absolute",this.statsRef.dom.style.bottom="0",this.statsRef.dom.style.right="0",this.statsRef.dom.style.top="auto",this.statsRef.dom.style.left="auto",document.body.appendChild(this.statsRef.dom)):!v.enabled&&this.statsRef&&(this.statsRef.dom.parentNode&&this.statsRef.dom.parentNode.removeChild(this.statsRef.dom),this.statsRef=null)}dispose(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.statsRef?.dom?.parentNode&&this.statsRef.dom.parentNode.removeChild(this.statsRef.dom),this.statsRef=null}};var _=class{loadingHandlers=[];stageLoadingUnsubscribes=[];onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let n of this.loadingHandlers)try{n(e)}catch(i){console.error("Game loading handler failed",i)}let t=`loading:${e.type}`;f.emit(t,e)}wireStageLoading(e,t){let n=e.onLoading(i=>{this.emit({type:i.type,message:i.message??"",progress:i.progress??0,current:i.current,total:i.total,stageName:e.uuid??`Stage ${t}`,stageIndex:t})});typeof n=="function"&&this.stageLoadingUnsubscribes.push(n)}unwireAllStages(){for(let e of this.stageLoadingUnsubscribes)try{e()}catch{}this.stageLoadingUnsubscribes=[]}dispose(){this.unwireAllStages(),this.loadingHandlers=[]}};var N=class{container=null;camera=null;rendererManager=null;gameCanvas=null;config=null;stage=null;mounted=!1;setGameCanvas(e){this.gameCanvas=e,this.tryMount()}setConfig(e){this.config=e,this.tryMount()}setContainer(e){this.container=e,this.tryMount()}setStage(e){this.stage=e,this.mounted&&this.gameCanvas?.reapplyLayout()}setCamera(e){this.camera=e,this.tryMount()}setRendererManager(e){this.rendererManager=e,this.tryMount()}tryMount(){this.mounted||!this.container||!this.gameCanvas||(this.rendererManager?this.mountWithRendererManager():this.camera&&this.mountWithCamera())}mountWithRendererManager(){if(!this.rendererManager||!this.gameCanvas)return;let e=this.rendererManager.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.rendererManager)return;let i=this.config?.internalResolution;if(i)this.rendererManager.setPixelRatio(1),this.rendererManager.resize(i.width,i.height),this.stage?.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.rendererManager.setPixelRatio(o),this.rendererManager.resize(t,n),this.stage?.resize(t,n)}}),this.mounted=!0}mountWithCamera(){if(!this.camera||!this.gameCanvas)return;let e=this.camera.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.camera)return;let i=this.config?.internalResolution;if(i)this.camera.setPixelRatio(1),this.camera.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.camera.setPixelRatio(o),this.camera.resize(t,n)}}),this.mounted=!0}reset(){this.camera=null,this.stage=null,this.mounted=!1}dispose(){this.container=null,this.camera=null,this.rendererManager=null,this.gameCanvas=null,this.config=null,this.stage=null,this.mounted=!1}};var F=class a{id;initialGlobals={};customSetup=null;customUpdate=null;customDestroy=null;stages=[];stageMap=new Map;currentStageId="";previousTimeStamp=0;totalTime=0;timer;inputManager;wrapperRef;globalInputConfig;defaultCamera=null;rendererManager=null;container=null;canvas=null;aspectRatioDelegate=null;resolvedConfig=null;gameCanvas=null;animationFrameId=null;isDisposed=!1;loadInFlight=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new _;rendererObserver=new N;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];entityDispatchTimer=null;pendingEntityDispatchPath=null;static ENTITY_DISPATCH_DEBOUNCE_MS=150;gameUpdateParams={};stageSetupParams={};stageUpdateParams={};frameCallback=e=>this.loop(e);sourceOptions;displayRuntime;static FRAME_LIMIT=120;static FRAME_DURATION=1e3/a.FRAME_LIMIT;static MAX_DELTA_SECONDS=1/30;constructor(e,t,n={}){this.wrapperRef=t,this.timer=new A,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=M(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new z(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e)}setDisplayRuntime(e){this.displayRuntime={...e};let t=M(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.emitStateDispatch("@game:display-config")}loadGameCanvas(e){this.gameCanvas=new H({id:e.id,container:e.container,containerId:e.containerId,canvas:this.canvas??void 0,bodyBackground:e.bodyBackground,fullscreen:e.fullscreen,aspectRatio:e.aspectRatio}),this.gameCanvas.applyBodyBackground(),this.gameCanvas.mountCanvas(),this.gameCanvas.centerIfFullscreen(),this.rendererObserver.setGameCanvas(this.gameCanvas),this.resolvedConfig&&this.rendererObserver.setConfig(this.resolvedConfig),this.container&&this.rendererObserver.setContainer(this.container),this.subscribeToEventBus()}loadDebugOptions(e){e.debug!==void 0&&(v.enabled=!!e.debug),this.debugDelegate=new O}isLoading(){return this.loadInFlight}async loadStage(e,t=0,n){if(this.loadInFlight){console.warn("loadStage ignored: a stage load is already in progress");return}this.loadInFlight=!0;try{await this.performLoadStage(e,t,n)}finally{this.loadInFlight=!1}}async performLoadStage(e,t=0,n){let i=n?fe(n):null,o=this.currentStage()??null,r=o?.wrappedStage??null,s=r?.scene?.scene??null,l=r?.cameraManagerRef?.primaryCamera?.camera??r?.cameraRef?.camera??null;i&&this.rendererManager?.initialized&&o&&s&&l&&this.rendererManager.beginSnapshotTransition(i,s,l),this.unloadCurrentStage();let m=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new me,await this.rendererManager.initRenderer()),y.setRenderer(this.rendererManager.renderer),await e.load(this.id,m?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.wireEntityThumbnails(e),this.rendererObserver.setStage(e.wrappedStage??null),this.rendererManager&&this.rendererObserver.setRendererManager(this.rendererManager),this.applyInputConfig(e),e.onInputConfigChanged=()=>this.applyInputConfig(e),this.hasStarted&&e.wrappedStage&&!e.wrappedStage.hasSetup){let p=this.params(),h={...this.stageSetupParams};h.inputs=p.inputs,h.globals=p.globals,h.camera=p.camera,h.stage=p.stage,h.game=p.game,h.me=e.wrappedStage,e.start(h)}this.emitStateDispatch("@stage:loaded")}applyInputConfig(e){let t=b(this.globalInputConfig??{},e.inputConfig??{});this.inputManager.configure(t)}setGlobalInputConfig(e){this.globalInputConfig=e;let t=this.currentStage();t&&this.applyInputConfig(t)}unloadCurrentStage(){if(!this.currentStageId)return;let e=this.getStage(this.currentStageId);if(e){if(this.clearEntityThumbnailWiring(),y.clear(),e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:C.globals})}catch(t){console.error("Failed to destroy previous stage",t)}e.wrappedStage=null}e.dispose(),this.stageMap.delete(this.currentStageId),this.currentStageId="",this.defaultCamera=null,this.rendererObserver.reset()}}setGlobals(e){this.initialGlobals={...e.globals};for(let t in this.initialGlobals){let n=this.initialGlobals[t];n===void 0&&console.error(`global ${t} is undefined`),re(t,n)}}params(){let e=this.currentStage(),t=this.timer.getDelta(),n=this.inputManager.getInputs(t),i=e?.wrappedStage?.cameraRef||this.defaultCamera,o=this.gameUpdateParams;return o.delta=t,o.inputs=n,o.globals=pe(),o.me=this,o.camera=i,o.stage=e,o.game=this.wrapperRef,o}start(){let e=this.currentStage(),t=this.params(),n=this.stageSetupParams;n.inputs=t.inputs,n.globals=t.globals,n.camera=t.camera,n.stage=t.stage,n.game=t.game,n.me=e.wrappedStage,e.start(n),this.customSetup&&this.customSetup(t),this.hasStarted=!0,this.loop(0)}step(e){let t=this.currentStage();if(!t||!t.wrappedStage)return;let n=this.params(),i=e!==void 0?e:n.delta,o=Math.min(Math.max(i,0),a.MAX_DELTA_SECONDS);n.delta=o,this.customUpdate&&this.customUpdate(n);let r=this.currentStage();if(r!==t||!r?.wrappedStage){this.totalTime+=o,C.time=this.totalTime;return}let s=this.stageUpdateParams;s.delta=n.delta,s.inputs=n.inputs,s.globals=n.globals,s.camera=n.camera,s.stage=n.stage,s.game=n.game,s.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(s),this.totalTime+=o,C.time=this.totalTime}loop(e){this.debugDelegate?.begin(),ce()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(y.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:C.globals}),x()}outOfLoop(){let e=this.currentStage();e&&e.wrappedStage.outOfLoop()}getStage(e){return this.stageMap.get(e)}currentStage(){return this.getStage(this.currentStageId)}onLoading(e){return this.loadingDelegate.onLoading(e)}buildStageConfigPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=e.wrappedStage.state,n=t.backgroundColor,i=typeof n=="string"?n:`#${n.getHexString()}`;return{id:e.wrappedStage.uuid,backgroundColor:i,backgroundImage:t.backgroundImage,gravity:{x:t.gravity.x,y:t.gravity.y,z:t.gravity.z},inputs:t.inputs,variables:t.variables}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{if(P(n.options))return;let i=n.constructor.type,o=i?String(i).replace("Symbol(","").replace(")",""):"Unknown",r=n.position??{x:0,y:0,z:0},s=n.rotation??{x:0,y:0,z:0},l=n.scale??{x:1,y:1,z:1},u=y.get(n.uuid);t.push({uuid:n.uuid,name:n.name||"Unnamed",type:o,position:{x:r.x??0,y:r.y??0,z:r.z??0},rotation:{x:s.x??0,y:s.y??0,z:s.z??0},scale:{x:l.x??1,y:l.y??1,z:l.z??1},thumbnail:u?.dataUrl??null,bounds:u?.bounds})}),t}wireEntityThumbnails(e){if(this.clearEntityThumbnailWiring(),!e.wrappedStage)return;let t=r=>{if(P(r.options))return;let s=r.group??r.mesh??null;s&&y.ensure(r.uuid,s).then(l=>{l&&this.queueEntityStateDispatch("@entity:thumbnail")})},n=e.wrappedStage.onEntityAdded(r=>{t(r)},{replayExisting:!0});this.thumbnailUnsubscribes.push(n);let i=r=>{if(!r.success)return;let s=e.wrappedStage?.entityDelegate.childrenMap.get(r.entityId);s&&(y.invalidate(r.entityId),t(s))};f.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{f.off("entity:model:loaded",i)});let o=r=>{y.invalidate(r.entityId),this.queueEntityStateDispatch("@entity:destroyed")};f.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{f.off("entity:destroyed",o)})}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[],this.entityDispatchTimer!==null&&(clearTimeout(this.entityDispatchTimer),this.entityDispatchTimer=null),this.pendingEntityDispatchPath=null}queueEntityStateDispatch(e){this.pendingEntityDispatchPath=e,this.entityDispatchTimer===null&&(this.entityDispatchTimer=setTimeout(()=>{this.entityDispatchTimer=null;let t=this.pendingEntityDispatchPath;this.pendingEntityDispatchPath=null,t&&!this.isDisposed&&this.emitStateDispatch(t)},a.ENTITY_DISPATCH_DEBOUNCE_MS))}emitStateDispatch(e,t,n){let i={scope:"game",path:e,value:t,previousValue:n,config:this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null,stageConfig:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()};f.emit("state:dispatch",i)}subscribeToEventBus(){this.eventBusUnsubscribes.push(se.on("game:state:updated",e=>{this.emitStateDispatch(e.path,e.value,e.previousValue)}))}};async function Te(a){let{getGameDefaultConfig:e}=await import("./game-default-QHROHW2O.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(s=>{if(s instanceof L)i.push(s);else if(s instanceof W)o.push(s);else if(s instanceof K)o.push(s);else if(s?.constructor?.name==="Object"&&typeof s=="object"){let l=Object.assign({...e()},{...s});n.push(l)}}),n.forEach(s=>{t=Object.assign(t,{...s})});let r=t;return r.input=n[0].input,i.forEach(s=>{s.addEntities(o)}),i.length?r.stages=i:r.stages[0].addEntities(o),r}function Re(a){return!!a.find(t=>t instanceof L)}function ie(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof L)&&!(e instanceof K)&&!(e instanceof W)){let t=e;if(t.globals)return t.globals}}import{proxy as tt}from"valtio/vanilla";import{get as nt,set as it}from"idb-keyval";import{pack as at,unpack as ot}from"msgpackr";var c=tt({previous:null,current:null,next:null,isLoading:!1}),U={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await nt(a);if(e)return ot(e)}catch(e){console.warn(`Failed to load stage ${a} from storage`,e)}if(this.staticRegistry.has(a))return this.staticRegistry.get(a);throw new Error(`Stage ${a} not found in storage and static loading not fully implemented.`)},async transitionForward(a,e){if(!c.isLoading){c.isLoading=!0;try{c.current&&await it(c.current.id,at(c.current)),c.previous=c.current,c.current=c.next,c.current?.id!==a&&(e?c.current=await e(a):c.current=await this.loadStageData(a)),c.next=null}catch(t){console.error("Failed to transition stage:",t)}finally{c.isLoading=!1}}},async preloadNext(a,e){e?c.next=await e(a):c.next=await this.loadStageData(a)}};var ae={async createFromBlueprint(a){let e=G({});if(a.entities)for(let t of a.entities)try{let n=await ve.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var X=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new ge;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,Re(e)||this.options.push(G());let t=ie(e);t&&Z(t)}onSetup(...e){return this.setupCallbacks.push(...e),this}onUpdate(...e){return this.updateCallbacks.push(...e),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this}setInputConfiguration(...e){let t=b(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){x();let e=ie(this.options);e&&Z(e);let t=await this.load();return this.wrappedGame=t,this.setOverrides(),this.registerGlobalSubscriptions(),t.start(),this}setDisplayRuntime(e){return this.displayRuntime={...this.displayRuntime,...e},this.wrappedGame&&this.wrappedGame.setDisplayRuntime(this.displayRuntime),this}setDeviceProfile(e){return this.setDisplayRuntime({deviceProfile:e})}setViewportSize(e,t){return this.setDisplayRuntime({viewportSize:{width:e,height:t}})}async load(){let e=await Te(this.options),t=M(e,this.displayRuntime);this.pendingInputConfig&&(t.input=b(t.input??{},this.pendingInputConfig));let n=new F({...e,...t},this,this.displayRuntime);for(let i of this.pendingLoadingCallbacks)n.onLoading(i);return await n.loadStage(e.stages[0]),n}setOverrides(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.customSetup=e=>{this.setupCallbacks.forEach(t=>t(e))},this.wrappedGame.customUpdate=e=>{this.updateCallbacks.forEach(t=>t(e))},this.wrappedGame.customDestroy=e=>{this.destroyCallbacks.forEach(t=>t(e))}}onGlobalChange(e,t){return this.globalChangeCallbacks.push({path:e,callback:t}),this}onGlobalChanges(e,t){return this.globalChangesCallbacks.push({paths:e,callback:t}),this}registerGlobalSubscriptions(){for(let{path:e,callback:t}of this.globalChangeCallbacks){let n=le(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=ue(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}experimental={getRuntime:()=>this.getCurrentStage()?.wrappedStage?.world?.simulation??null};async pause(){J(!0)}async resume(){J(!1),this.wrappedGame&&(this.wrappedGame.previousTimeStamp=0,this.wrappedGame.timer.reset())}step(e=1/60){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.step(e)}async reset(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.isLoading()||await this.wrappedGame.loadStage(this.wrappedGame.stages[0],0,e?.transition)}previousStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n-1];if(!i){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(i,n-1,e?.transition)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await U.loadStageData(e),n=await ae.createFromBlueprint(t);await this.wrappedGame.loadStage(n),c.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;if(c.next){console.log("next stage called");let o=c.next.id;if(U.transitionForward(o),c.current){ae.createFromBlueprint(c.current).then(r=>{this.wrappedGame?.loadStage(r,0,e?.transition)});return}}let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n+1];if(!i){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(i,n+1,e?.transition)}async goToStage(){}async end(){}dispose(){this.eventDelegate.dispose();for(let e of this.activeGlobalSubscriptions)e();this.activeGlobalSubscriptions=[],this.wrappedGame&&(this.wrappedGame.dispose(),this.wrappedGame=null),de(),x(),ye.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),f.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}onLoading(e){return this.wrappedGame?this.wrappedGame.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e),this.wrappedGame})}};function st(...a){return new X(a)}import{Euler as rt,Quaternion as lt,Vector2 as ut}from"three";function pt(a){return{spawn:async(e,t,n)=>{let i=await Promise.resolve(a(t,n));return e.add(i),i},spawnRelative:async(e,t,n=new ut(0,1))=>{if(!e.body){console.warn("body missing for entity during spawnRelative");return}let{x:i,y:o,z:r}=e.body.translation(),s=e._rotation2DAngle??0;try{let p=e.body.rotation(),h=new lt(p.x,p.y,p.z,p.w);s=new rt().setFromQuaternion(h,"XYZ").z}catch{}let l=Math.sin(-s)*(n.x??0),u=Math.cos(-s)*(n.y??0),m=await Promise.resolve(a(i+l,o+u));return t.add(m),m}}}import{subscribe as dt}from"valtio/vanilla";var oe="STAGE_STATE_CHANGE";function ct(){return dt(S,()=>{let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(oe,{detail:a}))})}function mt(){let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(oe,{detail:a}))}import{MathUtils as ht,Vector3 as gt}from"three";var Ee={targetKey:"primary",offset:new gt(0,0,0),lerpFactor:.1};function ft(a){let e={...Ee,...a,offset:$(a?.offset,Ee.offset)},t=null;return{priority:0,enabled:!0,onAttach(){t=null},update(n,i){let o=n.targets[e.targetKey];if(!o)return i;let r=o.position.clone().add(e.offset),s=be(i);if(!t)t=r.clone();else{let l=ht.clamp(e.lerpFactor,0,1),u=1-Math.pow(1-l,n.dt*60);t.lerp(r,u)}return s.position.copy(t),s.lookAt=o.position.clone(),s},onDetach(){t=null}}}import{MeshBasicMaterial as yt}from"three";function bt(a,e,t){let n=e.cameraRef;if(!n.renderTarget){let r=t?.width??512,s=t?.height??512;n.createRenderTarget(r,s)}let i=n.getRenderTexture();if(!i){console.warn("setCameraFeed: Failed to obtain render texture from camera.");return}if(!a.mesh){console.warn("setCameraFeed: Entity has no mesh to apply the camera feed to.");return}let o=new yt({map:i});a.mesh.material=o}export{B as a,q as b,Q as c,ee as d,qe as e,c as f,U as g,X as h,st as i,pt as j,oe as k,ct as l,mt as m,ft as n,bt as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Quaternion as S}from"three";import{Quaternion as p}from"three";var h=new WeakMap,m=new p,x=new p,a=new p;function f(t){return{x:t.x,y:t.y,z:t.z}}function b(t){return{x:t.x,y:t.y,z:t.z,w:t.w}}function r(t){return{position:f(t.position),rotation:b(t.rotation)}}function l(t){return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function u(t){return{position:f(t.translation()),rotation:b(t.rotation())}}function w(t){let e=r(t);return{previous:r(e),current:e}}function v(t){let e=u(t),s=h.get(t)??w(e);return s.previous=r(e),s.current=r(e),h.set(t,s),s}function d(t,e,s){let o=l(s);return m.set(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w),x.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),a.slerpQuaternions(m,x,o),{position:{x:t.position.x+(e.position.x-t.position.x)*o,y:t.position.y+(e.position.y-t.position.y)*o,z:t.position.z+(e.position.z-t.position.z)*o},rotation:{x:a.x,y:a.y,z:a.z,w:a.w}}}function Q(t,e){if(H(t))return t.getRenderPose(e);let s=h.get(t);if(!s)return u(t);let o=u(t);if(!R(o,s.current)){let n=v(t);return r(n.current)}return d(s.previous,s.current,e)}function H(t){return t!=null&&typeof t=="object"&&typeof t.getPoseHistory=="function"&&typeof t.getRenderPose=="function"}function R(t,e){return t.position.x===e.position.x&&t.position.y===e.position.y&&t.position.z===e.position.z&&t.rotation.x===e.rotation.x&&t.rotation.y===e.rotation.y&&t.rotation.z===e.rotation.z&&t.rotation.w===e.rotation.w}var P={x:0,y:0,z:0},c=new S,z=new S,g=class t{constructor(e,s,o){this.simulation=e;this.handle=s;this.clock=o}poseScratch={position:[0,0,0],rotation:[0,0,0,1]};renderScratch={position:[0,0,0],rotation:[0,0,0,1],scale:1,custom:[0,0,0,0],isSleeping:!1};previousScratch={position:[0,0,0],rotation:[0,0,0,1],scale:1,custom:[0,0,0,0],isSleeping:!1};translation(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{x:e.position[0],y:e.position[1],z:e.position[2]}:{...P}}rotation(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}:{x:0,y:0,z:0,w:1}}linvel(){let e=this.simulation.getLinearVelocity(this.handle);return e?{x:e[0],y:e[1],z:e[2]}:{...P}}angvel(){let e=this.simulation.adapter.getAngularVelocity(this.handle.slot);return e?{x:e[0],y:e[1],z:e[2]}:{...P}}setTranslation(e,s=!0){this.simulation.setPosition(this.handle,e.x,e.y,e.z)}setRotation(e,s=!0){this.simulation.setRotation(this.handle,e.x,e.y,e.z,e.w)}setLinvel(e,s=!0){this.simulation.setLinearVelocity(this.handle,e.x,e.y,e.z)}setAngvel(e,s=!0){this.simulation.setAngularVelocity(this.handle,e.x,e.y,e.z)}applyImpulse(e,s=!0){this.simulation.applyImpulse(this.handle,e.x,e.y,e.z)}setLinearDamping(e){}setGravityScale(e,s=!0){}bodyInfo(){return this.simulation.getBodyInfo(this.handle)}bodyType(){return this.bodyInfo()?.bodyType??0}mass(){return this.bodyInfo()?.mass??0}isSleeping(){return this.bodyInfo()?.isSleeping??!1}isEnabled(){return this.bodyInfo()?.isEnabled??!0}livePose(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{position:{x:e.position[0],y:e.position[1],z:e.position[2]},rotation:{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}}:{position:{...P},rotation:{x:0,y:0,z:0,w:1}}}static slotToPose(e){return{position:{x:e.position[0],y:e.position[1],z:e.position[2]},rotation:{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}}}getPoseHistory(){if(this.clock.steps===0){let i=this.livePose();return{previous:r(i),current:i}}let e=this.simulation.readRenderSlot(this.handle,this.renderScratch),s=this.simulation.readPreviousRenderSlot(this.handle,this.previousScratch),o=e?t.slotToPose(e):this.livePose();return{previous:s?t.slotToPose(s):r(o),current:o}}getRenderPose(e){let s=this.getPoseHistory();return d(s.previous,s.current,e)}isRenderSleeping(){return this.simulation.readRenderSlot(this.handle,this.renderScratch)?.isSleeping===!0}writeRenderPose(e,s,o){if(this.clock.steps===0){this.writeLivePose(s,o);return}let n=this.simulation.readRenderSlot(this.handle,this.renderScratch);if(!n){this.writeLivePose(s,o);return}let i=this.simulation.readPreviousRenderSlot(this.handle,this.previousScratch)??n,y=l(e);s.x=i.position[0]+(n.position[0]-i.position[0])*y,s.y=i.position[1]+(n.position[1]-i.position[1])*y,s.z=i.position[2]+(n.position[2]-i.position[2])*y,c.set(i.rotation[0],i.rotation[1],i.rotation[2],i.rotation[3]),z.set(n.rotation[0],n.rotation[1],n.rotation[2],n.rotation[3]),c.slerp(z,y),o.x=c.x,o.y=c.y,o.z=c.z,o.w=c.w}writeLivePose(e,s){let o=this.simulation.getPose(this.handle,this.poseScratch);o?(e.x=o.position[0],e.y=o.position[1],e.z=o.position[2],s.x=o.rotation[0],s.y=o.rotation[1],s.z=o.rotation[2],s.w=o.rotation[3]):(e.x=0,e.y=0,e.z=0,s.x=0,s.y=0,s.z=0,s.w=1)}};export{Q as a,g as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-E3UBSUPX.js";import{c as r,d as u,h as t}from"./chunk-7WRQ2UAN.js";import{StageBodyKind as T,StageBoundaryDim as V,StageEventType as F,StageRicochetDim as H,StageRicochetReflection as z,StageTopDownPlane as A,createSimulation as I}from"@zylem/behaviors/core";import{StageBodyKind as g}from"@zylem/behaviors/core";var n={kind:g.Dynamic,position:[0,0,0],rotation:[0,0,0,1],linearDamping:0,angularDamping:0,gravityScale:1,canSleep:!1,ccdEnabled:!0,lockRotation:[!1,!1,!1],lockTranslation:[!1,!1,!1]};function c(e={}){let i=t(e.position,r);return{kind:e.kind??n.kind,position:[i.x,i.y,i.z],rotation:e.rotation??n.rotation,linearDamping:e.linearDamping??n.linearDamping,angularDamping:e.angularDamping??n.angularDamping,gravityScale:e.gravityScale??n.gravityScale,canSleep:e.canSleep??n.canSleep,ccdEnabled:e.ccdEnabled??n.ccdEnabled,lockRotation:e.lockRotation??n.lockRotation,lockTranslation:e.lockTranslation??n.lockTranslation}}function l(e,i){let o=t(i.offset,r);return{shape:e,offset:[o.x,o.y,o.z],friction:i.friction??.5,restitution:i.restitution??0,sensor:i.sensor??!1,collisionGroups:a(i.collisionType,i.collisionFilter)}}function p(e,i={}){let o=t(e,u);return l({type:"box",halfExtents:[o.x/2,o.y/2,o.z/2]},i)}function C(e,i={}){return l({type:"sphere",radius:e},i)}function s(e,i,o={}){return l({type:"capsule",halfHeight:e,radius:i},o)}function f(e,i,o={}){return l({type:"cylinder",halfHeight:e,radius:i},o)}function y(e,i={}){return l({type:"convexHull",vertices:e},i)}function S(e,i,o={}){return l({type:"trimesh",vertices:e,indices:i},o)}function b(e,i,o,d,m={}){return l({type:"heightfield",rows:e,cols:i,heights:o,scale:d},m)}function R(e,i){return{body:e,colliders:i}}export{c as a,p as b,C as c,s as d,f as e,y as f,S as g,b as h,R as i,T as j,V as k,F as l,H as m,z as n,A as o,I as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=class{duration;done=!1;persistent=!1;elapsed=0;constructor(t){this.duration=t/1e3}tick(t,i){if(this.done)return;this.elapsed+=i;let n=this.duration>0?Math.min(this.elapsed/this.duration,1):1;this.onTick(t,i,n),this.elapsed>=this.duration&&(this.done=!0)}reset(){this.elapsed=0,this.done=!1}};import{setVelocityIntent as w}from"@zylem/behaviors/core";function A(e){let t=[];for(let i of e)i.traverse(n=>{if(!n.isMesh)return;let r=n,o=s=>{!("opacity"in s)||!("transparent"in s)||t.push(s)};Array.isArray(r.material)?r.material.forEach(o):r.material&&o(r.material)});return t}function E(e,t){if(t&&t.length>0)return t;let i=e.group??e.mesh;return i?[i]:[]}function G(e,t=1,i=!1){let n=E(e,void 0);for(let r of A(n))r.transparent=i,r.opacity=t,r.needsUpdate=!0}function D(e){return new l(e)}var l=class extends c{dx;dy;dz;constructor(t){super(t.duration),this.dx=t.x??0,this.dy=t.y??0,this.dz=t.z??0}onTick(t,i,n){if(this.duration<=0)return;let r=this.dx/this.duration,o=this.dy/this.duration,s=this.dz/this.duration,a=t.transformStore;a&&w(a,"actions",{x:r,y:o,z:s},{mode:"add"})}};function P(e){return new d(e)}var d=class extends c{targetX;targetY;targetZ;dx=0;dy=0;dz=0;initialized=!1;constructor(t){super(t.duration),this.targetX=t.x,this.targetY=t.y,this.targetZ=t.z}onTick(t,i,n){if(this.duration<=0)return;if(!this.initialized){let u=t.getPosition?.(),k=u?.x??0,M=u?.y??0,T=u?.z??0;this.dx=this.targetX-k,this.dy=this.targetY-M,this.dz=this.targetZ-T,this.initialized=!0}let r=this.dx/this.duration,o=this.dy/this.duration,s=this.dz/this.duration,a=t.transformStore;a&&w(a,"actions",{x:r,y:o,z:s},{mode:"add"})}reset(){super.reset(),this.initialized=!1}};function R(e){return new p(e)}var p=class extends c{rx;ry;rz;constructor(t){super(t.duration);let i=Math.PI/180;this.rx=(t.x??0)*i,this.ry=(t.y??0)*i,this.rz=(t.z??0)*i}onTick(t,i,n){if(this.duration<=0)return;let r=this.rx/this.duration,o=this.ry/this.duration,s=this.rz/this.duration,a=t.transformStore;a.angularVelocity.x+=r,a.angularVelocity.y+=o,a.angularVelocity.z+=s,a.dirty.angularVelocity=!0}};function I(e){return new m(e)}var m=class extends c{constructor(t){super(t)}onTick(){}};function X(e){return new h(e)}var h=class extends c{fn;called=!1;constructor(t){super(0),this.fn=t}onTick(){this.called||(this.fn(),this.called=!0)}reset(){super.reset(),this.called=!1}};function Y(e){return new f(e)}var f=class extends c{from;to;targets;restoreOpaque;materials=null;finalized=!1;constructor(t){super(t.duration),this.from=t.from??1,this.to=t.to??0,this.targets=t.targets,this.restoreOpaque=t.restoreOpaque??!1}onTick(t,i,n){if(!this.materials){this.materials=A(E(t,this.targets));for(let o of this.materials)o.transparent=!0,o.needsUpdate=!0}let r=this.from+(this.to-this.from)*n;for(let o of this.materials)o.opacity=r;if(n>=1&&!this.finalized&&(this.finalized=!0,this.restoreOpaque&&this.to>=1))for(let o of this.materials)o.transparent=!1,o.needsUpdate=!0}reset(){super.reset(),this.materials=null,this.finalized=!1}};function B(e){return new y(e.duration)}var y=class{duration;done=!1;persistent=!0;ready=!1;elapsed=0;constructor(t){this.duration=t/1e3}tick(t,i){this.elapsed+=i,this.elapsed>=this.duration&&(this.ready=!0)}consume(){this.ready=!1,this.elapsed=0}reset(){this.elapsed=0,this.ready=!1}};function Z(){return new b}var b=class{duration=1/0;done=!1;persistent=!0;triggered=!1;wasPressed=!1;tick(){this.triggered=!1}check(t){t&&!this.wasPressed&&(this.triggered=!0),this.wasPressed=t}reset(){this.triggered=!1,this.wasPressed=!1}};function j(){return new v}var v=class{duration=1/0;done=!1;persistent=!0;triggered=!1;wasPressed=!1;tick(){this.triggered=!1}check(t){!t&&this.wasPressed&&(this.triggered=!0),this.wasPressed=t}reset(){this.triggered=!1,this.wasPressed=!1}};function V(...e){return new x(e)}var x=class{duration;done=!1;persistent=!1;actions;currentIndex=0;constructor(t){this.actions=t,this.duration=t.reduce((i,n)=>i+n.duration,0)}tick(t,i){if(this.done||this.actions.length===0){this.done=!0;return}let n=i;for(;n>0&&this.currentIndex<this.actions.length;){let r=this.actions[this.currentIndex];if(r.tick(t,n),r.done){let o=r.duration,s=r.elapsed??o;n=Math.max(0,s-o),this.currentIndex++}else n=0}this.currentIndex>=this.actions.length&&(this.done=!0)}reset(){this.currentIndex=0,this.done=!1;for(let t of this.actions)t.reset()}};function q(...e){return new g(e)}var g=class{duration;done=!1;persistent=!1;actions;constructor(t){this.actions=t,this.duration=Math.max(0,...t.map(i=>i.duration))}tick(t,i){if(this.done)return;let n=!0;for(let r of this.actions)r.done||r.tick(t,i),r.done||(n=!1);n&&(this.done=!0)}reset(){this.done=!1;for(let t of this.actions)t.reset()}};function F(e,t){return new O(e,t)}var O=class{duration;done=!1;persistent=!1;action;totalTimes;currentCount=0;constructor(t,i){this.action=t,this.totalTimes=i,this.duration=t.duration*i}tick(t,i){this.done||(this.action.tick(t,i),this.action.done&&(this.currentCount++,this.currentCount>=this.totalTimes?this.done=!0:this.action.reset()))}reset(){this.currentCount=0,this.done=!1,this.action.reset()}};function _(e){return new z(e)}var z=class{duration=1/0;done=!1;persistent=!1;action;constructor(t){this.action=t}tick(t,i){this.action.tick(t,i),this.action.done&&this.action.reset()}reset(){this.done=!1,this.action.reset()}};import{createTransformStore as yt}from"@zylem/behaviors/core";import{move as xt,moveX as gt,moveY as Ot,moveZ as zt,moveXY as wt,moveXZ as At,resetVelocity as Et,moveForwardXY as kt,getPosition as Mt,getVelocity as Tt,setPosition as Gt,setPositionX as Dt,setPositionY as Pt,setPositionZ as Rt,wrapAroundXY as It,wrapAround3D as Xt}from"@zylem/behaviors/core";export{G as a,D as b,P as c,R as d,I as e,X as f,Y as g,B as h,Z as i,j,V as k,q as l,F as m,_ as n,yt as o,xt as p,gt as q,Ot as r,zt as s,wt as t,At as u,Et as v,kt as w,Mt as x,Tt as y,Gt as z,Dt as A,Pt as B,Rt as C,It as D,Xt as E};
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as ze,c as Xe}from"./chunk-VS2D4B3W.js";import{a as p,d as Ce,f as Be,g as Oe,h as Fe,i as Ie}from"./chunk-JQKS42G4.js";import{a as W,b as We}from"./chunk-G4HONLWC.js";import{a as A,m as Ue,n as Se,u as H,w as je}from"./chunk-XNHVRFAK.js";import{e as T,f as Pe,g as Ne,h as He}from"./chunk-CM5YRNBJ.js";import{a as Ve,b as k}from"./chunk-YHEWKN7N.js";import{a as j,b as Ke,c as K,d as Qe,e as Ye,f as $e,g as qe,m as Q}from"./chunk-D2PATZCC.js";import{c as N,d as be,j as S}from"./chunk-4QLJUQSJ.js";import{c as v,i as Ge,j as g}from"./chunk-7WRQ2UAN.js";import{a as Je}from"./chunk-BH53MBAZ.js";import{k as Ze}from"./chunk-MSC2BEO5.js";import{Vector2 as at,RenderTarget as Gt,HalfFloatType as Ut}from"three";import{WebGPURenderer as Nt,RenderPipeline as Ht}from"three/webgpu";import{pass as Wt,renderOutput as st,screenCoordinate as jt,vec2 as we,vec4 as ct,fract as nt,sin as ot,dot as lt,texture as Kt,uniform as Qt}from"three/tsl";import{setConsoleFunction as Zt,getConsoleFunction as Vt}from"three";var et="THREE.Abstract function.",tt=!1,it=!1;function rt(){if(tt)return;tt=!0;let s=Vt();Zt((e,t,...i)=>{if(e==="warn"&&t===et){it||(it=!0,console.warn(`${et} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(s){s(e,t,...i);return}let r=i[0],a=e==="log"?console.log:e==="error"?console.error:console.warn;r&&r.isStackTrace&&typeof r.getError=="function"?a(r.getError(t)):a(t,...i)})}var dt={x:0,y:0,width:1,height:1};async function tr(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var Y=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 at(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(rt(),this.renderer=new Nt({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 Ht(this.renderer),r=Wt(e,t);this.renderScale!==1&&r.setResolutionScale(this.renderScale);let a=r;for(let l of this._postEffects)try{a=l(a,{scenePass:r,scene:e,camera:t})}catch(c){console.error("RendererManager: post-processing effect failed, skipping.",c)}i.outputColorTransform=!1;let n=st(a),o=this._transition;if(o)try{n=ct(o.resolved.shader({fromNode:o.fromNode,toNode:n,progress:o.progressUniform})),o.composed=!0}catch(l){console.error("RendererManager: stage transition shader failed, skipping.",l)}i.outputNode=n.add($t()),this.postProcessing=i}get transitionActive(){return this._transition!==null}beginSnapshotTransition(e,t,i){this.finishTransition();let r=new at;this.renderer.getDrawingBufferSize(r);let a=new Gt(Math.max(1,r.x),Math.max(1,r.y),{type:Ut}),n=this.renderer.getRenderTarget();try{this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(a),this.renderer.render(t,i)}catch(o){console.error("RendererManager: failed to capture transition snapshot.",o)}finally{this.renderer.setRenderTarget(n)}this._transition={resolved:e,progressUniform:Qt(0),fromNode:st(Kt(a.texture)),elapsed:0,snapshotTarget:a,composed:!1}}finishTransition(){let e=this._transition;if(e){this._transition=null,e.progressUniform.value=1,this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef);try{e.resolved.onComplete?.()}catch(t){console.error("RendererManager: transition onComplete failed.",t)}this.releaseTransitionResources(e)}}cancelTransition(){let e=this._transition;if(e){this._transition=null;try{e.resolved.onComplete?.()}catch{}this.releaseTransitionResources(e)}}releaseTransitionResources(e){try{e.snapshotTarget?.dispose()}catch{}}advanceTransition(e){let t=this._transition;if(!t||!t.composed)return;t.elapsed+=e;let i=Math.min(t.elapsed/t.resolved.duration,1);t.progressUniform.value=t.resolved.easing(i),i>=1&&this.finishTransition()}setPostProcessingEffects(e){this._postEffects=[...e],this.postProcessing&&this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef)}setRenderScale(e){this.renderScale=Math.max(1,Number.isFinite(e)?e:1)}disposePostProcessing(){try{this.postProcessing?.dispose?.()}catch{}this.postProcessing=null}startRenderLoop(e){this._lastAnimationTimestamp=null,this.renderer.setAnimationLoop(t=>{let i=this._lastAnimationTimestamp===null?0:Math.max(0,(t-this._lastAnimationTimestamp)/1e3);this._lastAnimationTimestamp=t,this.advanceTransition(i),e(i)})}stopRenderLoop(){this._lastAnimationTimestamp=null;try{this.renderer.setAnimationLoop(null)}catch{}}renderCamera(e,t,i=!1){let r=t.viewport,a=this.screenResolution.x,n=this.screenResolution.y,o=Math.floor(r.x*a),l=Math.floor(r.y*n),c=Math.floor(r.width*a),d=Math.floor(r.height*n);this.renderer.setViewport(o,l,c,d),this.renderer.setScissor(o,l,c,d),this.renderer.setScissorTest(!0),i&&this.postProcessing?this.postProcessing.render():this.renderer.render(e,t.camera)}renderCameraToTarget(e,t){if(!t.renderTarget)return;let i=this.renderer.getRenderTarget();this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(t.renderTarget),this.renderer.clear(),this.renderer.render(e,t.camera),this.renderer.setRenderTarget(i)}renderCameras(e,t){if(!e||t.length===0)return;this.renderer.setScissorTest(!1),this.renderer.clear();let i=t.length===1&&Yt(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 Yt(s){return s.x===0&&s.y===0&&s.width===1&&s.height===1}function $t(){let s=jt.xy,e=nt(ot(lt(s,we(12.9898,78.233))).mul(43758.5453)),t=nt(ot(lt(s.add(we(13,7)),we(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return ct(i,i,i,0)}function B(s){return s?.category??"none"}function O(s){let e=B(s);return e==="environment"||e==="pack"}function R(s){return s.isInstanced===!0||s.isBundled===!0}import{BundleGroup as qt}from"three/webgpu";var $=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 a=e.mesh??e.group;if(!a)return!1;let n=this.getOrCreateBundle(r);return a.matrixAutoUpdate=!0,a.userData.zylemEntityUuid=e.uuid,a.parent&&a.parent.remove(a),n.add(a),n.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 qt,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as ut,Matrix4 as F,Vector3 as pt,Quaternion as Xt}from"three";var I=class s{packs=new Map;entityToPack=new Map;scene=null;static DEFAULT_CAPACITY=128;static GROWTH_FACTOR=2;setScene(e){this.scene=e}static generatePackKey(e){let t={geo:`${e.geometryType}:${Pe(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Ne(Pe(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},a=t.material||{};return s.generatePackKey({geometryType:i,dimensions:{x:r.x,y:r.y,z:r.z},materialPath:a.path||null,shaderType:a.shader?"custom":"standard",colorHex:a.color?.getHex?.()||t.color?.getHex?.()||16777215})}register(e,t,i,r){let a=this.packs.get(r);a||(a=this.createPack(r,t,i));let n;return a.freeIndices.length>0?n=a.freeIndices.pop():(n=a.entities.length,n>=a.capacity&&this.growPack(a),a.entities.push(null)),a.entities[n]=e,a.entityMap.set(e.uuid,n),this.entityToPack.set(e.uuid,r),a.instancedMesh.count=Math.max(a.instancedMesh.count,n+1),a.activeIndices.push(n),a.dirtyIndices.add(n),n}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 a=i.activeIndices.indexOf(r);if(a!==-1){let o=i.activeIndices.pop();a<i.activeIndices.length&&(i.activeIndices[a]=o)}i.dirtyIndices.delete(r);let n=new F;n.makeScale(0,0,0),i.instancedMesh.setMatrixAt(r,n),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 F,i=new pt,r=new Xt,a=new pt(1,1,1);for(let n of this.packs.values()){if(n.activeIndices.length===0)continue;let o=!1;for(let l of n.activeIndices){let c=n.entities[l];if(!c)continue;let d=n.dirtyIndices.has(l),u=!!c.body;if(!(!d&&!u)){if(!d&&u){let h=c.body;if(typeof h.isRenderSleeping=="function"&&h.isRenderSleeping())continue}this.updateInstanceMatrix(n,l,t,i,r,a,e),o=!0}}n.dirtyIndices.clear(),o&&(n.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,a,n,o){let l=e.entities[t];if(l){if(l.body){let c=l.body;if(typeof c.writeRenderPose=="function")c.writeRenderPose(o,r,a);else{let d=W(l.body,o);r.set(d.position.x,d.position.y,d.position.z),a.set(d.rotation.x,d.rotation.y,d.rotation.z,d.rotation.w)}i.compose(r,a,n)}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 a=r.entityMap.size;e+=a,t.push({key:i,count:a,capacity:r.capacity})}return{packCount:this.packs.size,totalInstances:e,packs:t}}dispose(){for(let e of this.packs.values())this.scene&&this.scene.remove(e.instancedMesh),e.instancedMesh.dispose(),e.geometry.dispose();this.packs.clear(),this.entityToPack.clear()}createPack(e,t,i){let r=s.DEFAULT_CAPACITY,a=new ut(t,i,r);a.count=0,a.frustumCulled=!1;let n=new F().makeScale(0,0,0);for(let l=0;l<r;l++)a.setMatrixAt(l,n);a.instanceMatrix.needsUpdate=!0;let o={key:e,instancedMesh:a,geometry:t,material:i,entityMap:new Map,entities:[],freeIndices:[],activeIndices:[],dirtyIndices:new Set,capacity:r};return this.packs.set(e,o),this.scene&&this.scene.add(a),o}growPack(e){let t=e.capacity*s.GROWTH_FACTOR,i=new ut(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new F;for(let n=0;n<e.capacity;n++)e.instancedMesh.getMatrixAt(n,r),i.setMatrixAt(n,r);let a=new F().makeScale(0,0,0);for(let n=e.capacity;n<t;n++)i.setMatrixAt(n,a);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 q=class{bundles=new $;instances=new I;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=B(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],a=I.generateEntityPackKey(e);if(t==="pack"){let n=this.instances.register(e,i,r,a);return n<0?!1:(e.packKey=a,e.instanceId=n,e.isInstanced=!0,e.mesh&&(e.mesh.visible=!1),!0)}return t==="environment"&&this.bundles.register(e,i,r,a)?(e.mesh&&(e.mesh.visible=!0),!0):!1}unregister(e){e.isInstanced&&(this.instances.unregister(e),e.isInstanced=!1,e.instanceId=-1,e.packKey=null),e.isBundled&&this.bundles.unregister(e)}update(e=0){this.instances.update(e)}dispose(){this.bundles.dispose(),this.instances.dispose()}};var X=!1,b={},mt=0,ht=0,z=null;function gt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ee(){return X?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(X=!0),X)}function yr(s){X=s,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=s)}function Me(s){Ee()&&(z=s,ht=gt())}function De(){if(!Ee()||z===null)return;let s=gt()-ht;b[z]=(b[z]??0)+s,z=null}function ft(){if(!Ee()||(mt++,mt%60!==0))return;let s=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=s>0?(i/s*100).toFixed(1):"0.0";return`${t}=${i.toFixed(2)}ms (${r}%)`});console.info(`[ZylemStage profile] avg over 60 frames (${s.toFixed(2)}ms/frame): ${e.join(", ")}`);for(let t of Object.keys(b))b[t]=0}function P(s,e){Me(s);try{return e()}finally{De()}}var m={FirstPerson:"first-person",ThirdPerson:"third-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};import{Vector3 as Jt,Quaternion as ei,MathUtils as xe}from"three";function J(){return{position:new Jt(0,0,10),rotation:new ei,fov:75,zoom:1,near:.1,far:1e3}}function M(s){return{position:s.position.clone(),rotation:s.rotation.clone(),fov:s.fov,zoom:s.zoom,near:s.near,far:s.far,lookAt:s.lookAt?.clone()}}function yt(s,e){let t=M(s);return e.position&&t.position.add(e.position),e.rotation&&t.rotation.multiply(e.rotation),e.fov!=null&&t.fov!=null&&(t.fov+=e.fov),e.zoom!=null&&t.zoom!=null&&(t.zoom+=e.zoom),t}function vt(s,e,t,i){let r=1-Math.pow(1-xe.clamp(t,0,1),i*60),a=M(s);return a.position.lerp(e.position,r),a.rotation.slerp(e.rotation,r),e.fov!=null&&a.fov!=null&&(a.fov=xe.lerp(a.fov,e.fov,r)),e.zoom!=null&&a.zoom!=null&&(a.zoom=xe.lerp(a.zoom,e.zoom,r)),e.near!=null&&(a.near=e.near),e.far!=null&&(a.far=e.far),e.lookAt?a.lookAt?a.lookAt.lerp(e.lookAt,r):a.lookAt=e.lookAt.clone():a.lookAt=void 0,a}var ee=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=J();_finalPose=J();_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):J(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=M(t);for(let r=this.actions.length-1;r>=0;r--){let a=this.actions[r],n=a.update(e);t=yt(t,n),a.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=vt(this._finalPose,t,this.damping,e.dt):(this._finalPose=M(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?M(this._desiredPose):null,finalPose:this._finalPose?M(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 w,Quaternion as te}from"three";var ti={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},D=class{id="third-person";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...ti,...r},this.initialPosition=t?g(t,v):void 0,this.initialLookAt=i?g(i,v):void 0}getBasePose(e){let t=Object.keys(e.targets),i=e.targets[this.opts.targetKey];return t.length===0||!i?this.staticPose():t.length===1?this.singleTargetPose(i.position,e,this.opts.targetKey):this.multiTargetPose(e)}staticPose(){return this.initialPosition?{position:this.initialPosition.clone(),rotation:new te,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new w(0,0,0)}:{position:new w(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new te,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new w(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new w(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new te,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([u,h])=>this.getTrailedPosition(u,h.position,e.time)),r=new w;for(let u of i)r.add(u);r.divideScalar(i.length);let a=0;for(let u of i){let h=r.distanceTo(u);h>a&&(a=h)}let n=Math.max(a*this.opts.paddingFactor,this.opts.minDistance),o=new w(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=o.length(),c=l>0?o.clone().normalize():new w(0,.5,1).normalize(),d=r.clone().add(c.multiplyScalar(n));if(l>0){let u=this.opts.height/l;d.y=r.y+n*u}return{position:d,rotation:new te,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 a=this._trailBuffers.get(e);a||(a=[],this._trailBuffers.set(e,a)),a.push({time:i,pos:t.clone()});let n=i-r-.05;for(;a.length>1&&a[0].time<n;)a.shift();a.length>this.opts.trailBufferSize&&a.splice(0,a.length-this.opts.trailBufferSize);let o=i-r;if(a[0].time>=o)return a[0].pos.clone();for(let l=1;l<a.length;l++){let c=a[l-1],d=a[l];if(c.time<=o&&o<=d.time){let u=d.time-c.time,h=u>1e-6?(o-c.time)/u:0;return new w().lerpVectors(c.pos,d.pos,h)}}return a[a.length-1].pos.clone()}};import{Vector3 as bt,Quaternion as ii}from"three";var Ct={position:{x:0,y:0,z:10},zoom:10},_=class{id="fixed-2d";defaults={damping:1};opts;constructor(e){this.opts={...Ct,...e,position:g(e?.position,Ct.position)}}getBasePose(e){return{position:new bt(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new ii,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new bt(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as Te,Quaternion as Re,Euler as wt,MathUtils as f}from"three";var ri={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},Z=class{id="first-person";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new Re;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...ri,...r},this.initialPosition=t?g(t,v):void 0,this.initialLookAt=i?g(i,v):void 0,this._currentFov=this.opts.defaultFov,this._targetFov=this.opts.defaultFov,this._lookAtLerpSpeed=this.opts.lookAtLerpSpeed,this.initialPosition&&this.initialLookAt&&this.deriveYawPitchFromLookAt(this.initialPosition,this.initialLookAt)}look(e,t){this._yaw+=e,this._pitch=f.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=f.clamp(t,-this.opts.pitchLimit,this.opts.pitchLimit)}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 Te(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new Te(0,this.opts.eyeHeight,0)}smoothVertical(e,t){if(this.opts.verticalSmoothing>=1)return this._smoothedY=e,e;if(this._smoothedY==null)return this._smoothedY=e,e;let i=f.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=f.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new Re().setFromEuler(new wt(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=St.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let a=Math.atan2(-r.x,-r.z),n=Math.asin(f.clamp(r.y,-1,1)),o=ai.setFromEuler(Pt.set(n,a,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(o,f.clamp(l,0,1)),this._currentRotation.clone()}}return this._currentRotation.copy(i),i}lerpFov(e){if(Math.abs(this._currentFov-this._targetFov)<.01)return this._targetFov;let t=1-Math.pow(1-Math.min(this.opts.fovLerpSpeed*e,1),1);return f.lerp(this._currentFov,this._targetFov,f.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=St.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(f.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=Pt.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=f.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},St=new Te,ai=new Re,Pt=new wt;function L(s,e){switch(s){case"third-person":return new D(e);case"first-person":return new Z(e);case"isometric":return new D({distance:10,height:10,...e});case"flat-2d":return new _(e);case"fixed-2d":return new _(e);default:return new D(e)}}import{Vector2 as li}from"three";import{PerspectiveCamera as V,Vector3 as ni,OrthographicCamera as re,RenderTarget as oi,LinearFilter as Et}from"three";import{Vector3 as _e}from"three";import{OrbitControls as si}from"three/addons/controls/OrbitControls.js";var ie=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new _e;debugDelegate=null;debugUnsubscribe=null;debugStateSnapshot={enabled:!1,selected:[]};savedCameraPosition=null;savedCameraQuaternion=null;savedCameraZoom=null;savedCameraLocalPosition=null;savedDebugCameraPosition=null;savedDebugCameraQuaternion=null;savedDebugCameraZoom=null;savedDebugOrbitTarget=null;_userOrbitEnabled=!1;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}get isActive(){return this.debugStateSnapshot.enabled}get isOrbitActive(){return this.debugStateSnapshot.enabled||this._userOrbitEnabled}update(){this.orbitControls&&this.orbitTarget&&(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)),this.orbitControls?.update()}enableUserOrbitControls(){this._userOrbitEnabled=!0,this.orbitControls||this.enableOrbitControls()}disableUserOrbitControls(){this._userOrbitEnabled=!1,this.debugStateSnapshot.enabled||this.disableOrbitControls()}setDebugDelegate(e){if(this.debugDelegate===e)return;if(this.detachDebugDelegate(),this.debugDelegate=e,!e){this.applyDebugState({enabled:!1,selected:[]});return}let t=e.subscribe(i=>{this.applyDebugState(i)});this.debugUnsubscribe=()=>{t?.()}}dispose(){this.disableOrbitControls(),this.detachDebugDelegate()}get debugState(){return this.debugStateSnapshot}frameTarget(e){!this.orbitControls&&(this.debugStateSnapshot.enabled||this._userOrbitEnabled)&&this.enableOrbitControls(),this.orbitControls||this.enableOrbitControls(),this.orbitTarget=e;let t=new _e().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=ze(e,this.camera,t);this.orbitControls.target.copy(i.center),this.orbitControls.update()}applyDebugState(e){let t=this.debugStateSnapshot.enabled;this.debugStateSnapshot={enabled:e.enabled,selected:[...e.selected]},e.enabled&&!t?(this.saveCameraState(),this.detachCameraFromRig(),this.enableOrbitControls(),this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this.orbitTarget=null,this._userOrbitEnabled||this.disableOrbitControls(),this.reattachCameraToRig(),this.restoreCameraState()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected)}enableOrbitControls(){this.orbitControls||(this.orbitControls=new si(this.camera,this.domElement),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.05,this.orbitControls.screenSpacePanning=!1,this.orbitControls.minDistance=1,this.orbitControls.maxDistance=500,this.orbitControls.maxPolarAngle=Math.PI/2,this.orbitControls.target.set(0,0,0))}disableOrbitControls(){this.orbitControls&&(this.orbitControls.dispose(),this.orbitControls=null)}updateOrbitTargetFromSelection(e){if(!this.debugDelegate||e.length===0){this.orbitTarget=null,this.orbitControls&&this.orbitControls.target.set(0,0,0);return}for(let t=e.length-1;t>=0;t-=1){let i=e[t],r=this.debugDelegate.resolveTarget(i);if(r){this.orbitTarget=r,this.orbitControls&&(r.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos));return}}this.orbitTarget=null}detachDebugDelegate(){if(this.debugUnsubscribe)try{this.debugUnsubscribe()}catch{}this.debugUnsubscribe=null,this.debugDelegate=null}saveCameraState(){this.savedCameraPosition=this.camera.position.clone(),this.savedCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedCameraZoom=this.camera.zoom)}restoreCameraState(){this.savedCameraPosition&&(this.camera.position.copy(this.savedCameraPosition),this.savedCameraPosition=null),this.savedCameraQuaternion&&(this.camera.quaternion.copy(this.savedCameraQuaternion),this.savedCameraQuaternion=null),this.savedCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedCameraZoom,this.camera.updateProjectionMatrix?.(),this.savedCameraZoom=null)}saveDebugCameraState(){this.savedDebugCameraPosition=this.camera.position.clone(),this.savedDebugCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedDebugCameraZoom=this.camera.zoom),this.orbitControls&&(this.savedDebugOrbitTarget=this.orbitControls.target.clone())}restoreDebugCameraState(){this.savedDebugCameraPosition&&this.camera.position.copy(this.savedDebugCameraPosition),this.savedDebugCameraQuaternion&&this.camera.quaternion.copy(this.savedDebugCameraQuaternion),this.savedDebugCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedDebugCameraZoom,this.camera.updateProjectionMatrix?.()),this.savedDebugOrbitTarget&&this.orbitControls&&this.orbitControls.target.copy(this.savedDebugOrbitTarget)}detachCameraFromRig(){if(!this.cameraRig||this.camera.parent!==this.cameraRig)return;this.savedCameraLocalPosition=this.camera.position.clone();let e=new _e;this.camera.getWorldPosition(e),this.cameraRig.remove(this.camera),this.sceneRef&&this.sceneRef.add(this.camera),this.camera.position.copy(e)}reattachCameraToRig(){!this.cameraRig||this.camera.parent===this.cameraRig||(this.sceneRef&&this.camera.parent===this.sceneRef&&this.sceneRef.remove(this.camera),this.cameraRig.add(this.camera),this.savedCameraLocalPosition&&(this.camera.position.copy(this.savedCameraLocalPosition),this.savedCameraLocalPosition=null))}};var C=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...dt};targets=[];pipeline;renderTarget=null;get target(){return this.targets.length>0?this.targets[0]:null}set target(e){e?this.targets.length===0?this.targets.push(e):this.targets[0]=e:this.targets=[]}orbitController=null;_useOrbitalControls=!1;_skipDebugOrbit=!1;_rendererManager=null;_elapsedTime=0;constructor(e,t,i=10){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 ni(0,0,0));let a=L(e);this.pipeline=new ee(a)}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 ie(this.camera,this._rendererManager.renderer.domElement,null),this.orbitController.setScene(e),this._useOrbitalControls&&this.orbitController.enableUserOrbitControls())}async setupLegacy(e){this._rendererManager||(this._rendererManager=new Y(this.screenResolution),await this._rendererManager.initRenderer(),this._rendererManager.setupPostProcessing(e,this.camera),this._rendererManager.startRenderLoop(()=>{this._rendererManager&&this.sceneRef&&(this.isOrbitActive&&this.updateOrbitControls(),this._rendererManager.render(this.sceneRef,this.camera))})),await this.setup(e,this._rendererManager)}update(e){if(this.isDebugModeActive()||this._useOrbitalControls)return;this._elapsedTime+=e;let t=this.buildContext(e),i=this.pipeline.run(t);this.commitPose(i)}isDebugModeActive(){return this.orbitController?.isActive??!1}get isOrbitActive(){return this.orbitController?.isOrbitActive??!1}updateOrbitControls(){this.orbitController?.update()}enableOrbitalControls(){this._useOrbitalControls=!0,this.orbitController?.enableUserOrbitControls()}disableOrbitalControls(){this._useOrbitalControls=!1,this.orbitController?.disableUserOrbitControls()}get useOrbitalControls(){return this._useOrbitalControls}addTarget(e){this.targets.includes(e)||this.targets.push(e)}removeTarget(e){let t=this.targets.indexOf(e);t!==-1&&this.targets.splice(t,1)}clearTargets(){this.targets=[]}setViewport(e,t,i,r){this.viewport={x:e,y:t,width:i,height:r}}resize(e,t){if(this.screenResolution.set(e,t),this.camera instanceof V&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof re){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 oi(e,t,{minFilter:Et,magFilter:Et}),this.renderTarget}getRenderTexture(){return this.renderTarget?.texture??null}destroy(){try{this.orbitController?.dispose()}catch{}try{this.renderTarget?.dispose()}catch{}this.renderTarget=null,this.sceneRef=null,this.targets=[],this._rendererManager=null}setDebugDelegate(e){this._skipDebugOrbit||this.orbitController?.setDebugDelegate(e)}frameObject(e){this.orbitController?.frameTarget(e)}move(e){(this._perspective===m.Flat2D||this._perspective===m.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],a=i===0?"primary":`target_${i}`;r.group&&(t[a]={position:r.group.position,rotation:r.group.quaternion})}return{dt:e,time:this._elapsedTime,viewport:{width:this.screenResolution.x,height:this.screenResolution.y,aspect:this.screenResolution.x/this.screenResolution.y},targets:t}}commitPose(e){if(this.camera.position.copy(e.position),e.lookAt?this.camera.lookAt(e.lookAt):this.camera.quaternion.copy(e.rotation),this.camera instanceof V&&(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 re){if(e.zoom!=null){let t=this.screenResolution.x/this.screenResolution.y,i=e.zoom;this.camera.left=-i*t/2,this.camera.right=i*t/2,this.camera.top=i/2,this.camera.bottom=-i/2}e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()}}createCameraForPerspective(e){switch(this._perspective){case m.ThirdPerson:return new V(75,e,.1,1e3);case m.FirstPerson:return new V(75,e,.1,1e3);case m.Isometric:return new re(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);case m.Flat2D:case m.Fixed2D:return new re(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);default:return new V(75,e,.1,1e3)}}};var ae=class{cameras=new Map;_activeCameras=[];_debugCamera=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;constructor(){}get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}get debugCamera(){return this._debugCamera}get allCameras(){return Array.from(this.cameras.values())}addCamera(e,t){let i=t||e.name||`camera_${this._autoNameCounter++}`;return e.name=i,this.cameras.set(i,e),this._activeCameras.length===0&&this._activeCameras.push(e),i}removeCamera(e){let t;if(typeof e=="string")t=e;else for(let[a,n]of this.cameras.entries())if(n===e){t=a;break}if(!t)return!1;let i=this.cameras.get(t);if(!i)return!1;if(i===this._debugCamera)return console.warn("CameraManager: Cannot remove the debug camera"),!1;this.cameras.delete(t);let r=this._activeCameras.indexOf(i);return r!==-1&&this._activeCameras.splice(r,1),!0}setActiveCamera(e){let t=this.resolveCamera(e);if(!t)return console.warn(`CameraManager: Camera not found: ${e}`),!1;let i=this._activeCameras.filter(r=>r!==this._activeCameras[0]&&r.viewport.width<1);return this._activeCameras=[t,...i],!0}addActiveCamera(e){let t=this.resolveCamera(e);return t?(this._activeCameras.includes(t)||this._activeCameras.push(t),!0):!1}deactivateCamera(e){let t=this.resolveCamera(e);if(!t)return!1;let i=this._activeCameras.indexOf(t);return i!==-1?(this._activeCameras.splice(i,1),!0):!1}getCamera(e){return this.cameras.get(e)??null}async setup(e,t){this._sceneRef=e,this._rendererManager=t,this.createDebugCamera(t.screenResolution);for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._debugCamera&&(this._debugCamera.setRendererManager(t),await this._debugCamera.setup(e,t))}update(e){for(let t of this._activeCameras)t.update(e)}render(e){if(!this._rendererManager||this._activeCameras.length===0)return;this.updateOrbitingCamerasForRender();let t=[],i=[];for(let r of this._activeCameras)r.renderTarget?t.push(r):i.push(r);for(let r of t)this._rendererManager.renderCameraToTarget(e,r);i.length>0&&this._rendererManager.renderCameras(e,i)}updateOrbitingCamerasForRender(){for(let e of this._activeCameras)e.isOrbitActive&&e.updateOrbitControls()}ensureDefaultCamera(){if(this.cameras.size===0||this._activeCameras.length===0){let e=this._rendererManager?.screenResolution||new li(window.innerWidth,window.innerHeight),t=new C(m.ThirdPerson,e);return this.addCamera(t,"default"),t}return this._activeCameras[0]}dispose(){for(let e of this.cameras.values())e.destroy();this._debugCamera?.destroy(),this.cameras.clear(),this._activeCameras=[],this._debugCamera=null,this._rendererManager=null,this._sceneRef=null}createDebugCamera(e){this._debugCamera=new C(m.ThirdPerson,e),this._debugCamera.name="__debug__",this._debugCamera.enableOrbitalControls()}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;for(let t of this.cameras.values())if(t===e)return t;return null}};var y=class{cameraRef;constructor(e){this.cameraRef=e}addTarget(e){this.cameraRef.addTarget(e)}removeTarget(e){this.cameraRef.removeTarget(e)}clearTargets(){this.cameraRef.clearTargets()}enableOrbitalControls(){this.cameraRef.enableOrbitalControls()}disableOrbitalControls(){this.cameraRef.disableOrbitalControls()}setViewport(e,t,i,r){this.cameraRef.setViewport(e,t,i,r)}addBehavior(e,t){this.cameraRef.pipeline.addBehavior(e,t)}removeBehavior(e){return this.cameraRef.pipeline.removeBehavior(e)}addAction(e){this.cameraRef.pipeline.addAction(e)}setPerspective(e,t){this.cameraRef.pipeline.setPerspective(L(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function Pa(s){let e=Ge(s.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;s.perspective==="fixed-2d"&&(t=s.zoom||10);let i=new C(s.perspective||"third-person",e,t);s.name&&(i.name=s.name);let r=g(s.position,v),a=g(s.target,v);i.move(r),i.camera.lookAt(a);let n=s.perspective||"third-person";if(n==="fixed-2d"||n==="flat-2d"?i.pipeline.setPerspective(L(n,{zoom:t})):i.pipeline.setPerspective(L(n,{initialPosition:r.clone(),initialLookAt:a.clone()})),s.viewport&&(i.viewport={...s.viewport}),s.useOrbitalControls&&(i._useOrbitalControls=!0),s.skipDebugOrbit&&(i._skipDebugOrbit=!0),s.damping!=null&&(i.pipeline.damping=s.damping),s.behaviors)for(let[o,l]of Object.entries(s.behaviors))i.pipeline.addBehavior(o,l);if(s.renderToTexture){let{width:o=512,height:l=512}=s.renderToTexture;i.createRenderTarget(o,l)}return new y(i)}import{Vector3 as ci}from"three";function E(s){return!!s&&typeof s=="object"&&typeof s.create=="function"}function G(s){return!!s&&typeof s.then=="function"}function Le(s){return!!s&&typeof s=="object"&&s instanceof y}function Mt(s){return!s||typeof s!="object"||E(s)||Le(s)||G(s)||typeof s.then=="function"?!1:s.constructor===Object||s.constructor?.name==="Object"}function Dt(s){return s?!!(E(s)||typeof s=="function"||G(s)):!1}var di="/three/basis/";function ne(s){return{...s,ktx2TranscoderPath:s?.ktx2TranscoderPath??di}}var se=class{constructor(e,t,i,r,a,n,o=60,l={},c=!0,d=[]){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=a;this.variables=n;this.physicsRate=o;this.assetLoaders=l;this.defaultLighting=c;this.postProcessingEffects=d}};function ui(){return new se({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},j,null,null,new ci(0,0,0),{},60,{},!0)}function xt(s=[]){let e=ui(),t={},i=[],r=[],a=[];for(let l of s)Le(l)?a.push(l):E(l)?i.push(l):Dt(l)&&!E(l)?r.push(l):Mt(l)&&(t={...t,...l});let n=new se(t.inputs??e.inputs,t.backgroundColor??e.backgroundColor,t.backgroundImage??e.backgroundImage,t.backgroundShader??e.backgroundShader,t.gravity??e.gravity,t.variables??e.variables,t.physicsRate??e.physicsRate,t.assetLoaders??e.assetLoaders,t.defaultLighting??e.defaultLighting,t.postProcessingEffects??e.postProcessingEffects),o=a.length>0?a[0]:void 0;return{config:n,entities:i,asyncEntities:r,camera:o,cameras:a}}function _a(s){return{...s}}var pi=Symbol("vessel"),U=class extends A{static type=pi;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=mi();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function mi(...s){let e=new U;return s.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Ft,Vector3 as It}from"three";import{createSimulation as hi}from"@zylem/behaviors/core";function ke(s){return typeof s?.handlePostCollision=="function"&&typeof s?.handleIntersectionEvent=="function"}function gi(s,e){return s<e?`${s}|${e}`:`${e}|${s}`}var oe=class s{type="World";simulation;collisionMap=new Map;collisionBehaviorMap=new Map;_removalMap=new Map;activeCollisionPairs=new Map;livePairs=new Map;handleIdToUuid=new Map;currentCollisionTimeMs=0;zeroGravity;fixedTimestep;interpolationAlpha=0;stepClock={steps:0};static async create(e,t=60){let i={x:e?.x??0,y:e?.y??0,z:e?.z??0},r=await hi({gravity:[i.x,i.y,i.z],fixedTimestep:1/t,initialCapacity:4096});return new s(r,t,i.x===0&&i.y===0&&i.z===0)}constructor(e,t=60,i=!1){this.simulation=e,this.fixedTimestep=1/t,this.zeroGravity=i,this.simulation?.setEventsEnabled?.(!1)}addEntity(e){let t={...e.bodyDesc??{}},i=e.colliderDescs?.length?e.colliderDescs:e.colliderDesc?[e.colliderDesc]:[];this.zeroGravity&&(t.lockTranslation=[!0,!0,!0],t.lockRotation=[!0,!0,!0]),(e.controlledRotation||e instanceof H)&&(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 We(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 a=gi(i,r),n=this.livePairs.get(a);n||(n={uuidA:i<r?i:r,uuidB:i<r?r:i,contactCount:0,intersectionCount:0},this.livePairs.set(a,n));let o=t.type==="collisionStarted"?1:-1;t.sensor?n.intersectionCount=Math.max(0,n.intersectionCount+o):n.contactCount=Math.max(0,n.contactCount+o),n.contactCount===0&&n.intersectionCount===0&&this.livePairs.delete(a)}}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 a=r;if(!ke(a))continue;a.handlePostCollision({entity:a,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,a]of i){let n=this.collisionMap.get(a.uuidA),o=this.collisionMap.get(a.uuidB);this.activeCollisionPairs.has(r)||this.dispatchCollisionPhase(a,"enter",t),(this.entityHasCollisionPhaseListener(n,"stay")||this.entityHasCollisionPhaseListener(o,"stay"))&&this.dispatchCollisionPhase(a,"stay",t),a.hasIntersection&&this.dispatchIntersectionDelegates(a,e)}this.updatePostCollisionBehaviors(e),this.activeCollisionPairs=i}dispatchCollisionPhase(e,t,i){let r={phase:t,nowMs:i},a=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);a&&n&&a._collision(n,be.globals,r);let o=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);o&&l&&l._collision(o,be.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&ke(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let a=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);a&&n&&ke(n)&&(n.handleIntersectionEvent({entity:n,other:a,delta:t}),this.collisionBehaviorMap.set(n.uuid,n))}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 fi,Color as Tt,AmbientLight as yi,DirectionalLight as vi,Vector3 as le,GridHelper as bi,Texture as Ci,SRGBColorSpace as Si}from"three";var ce=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new fi,n=i.backgroundColor instanceof Tt?i.backgroundColor:new Tt(i.backgroundColor);r.background=n,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&T.loadTexture(i.backgroundImage,{colorSpace:Si}).then(o=>{r.background=o}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),p.enabled&&this.debugScene()}setupBackgroundShader(e,t){if(!He(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:S()})}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 Ci&&(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 yi(16777215,1);e.add(t);let i=new vi(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 le(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(R(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Pi(e);i&&i.attachToScene(this.scene);let r=e.options.position??new le(0,0,0);if(e.physicsAttached&&e.body)try{let a=e.body.translation();r=new le(a.x,a.y,a.z)}catch{r=e.options.position??new le(0,0,0)}this.add(t,r)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new bi(1e3,100);this.scene.add(i)}};function Pi(s){return s.constructor.type===je?s:null}var de=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 wi}from"three";var Rt=new wi;function _t(s){let e=s._childrenMap,t=s._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval||i.isInstanced||i.isBundled)continue;let r=i.body,a=i.group??i.mesh,n=a?W(r,t?.interpolationAlpha??0):null;a&&n&&a.position.set(n.position.x,n.position.y,n.position.z),!i.controlledRotation&&a&&n&&(Rt.set(n.rotation.x,n.rotation.y,n.rotation.z,n.rotation.w),a.setRotationFromQuaternion(Rt))}}import{nanoid as Gi}from"nanoid";import{BufferAttribute as Bt,BufferGeometry as ki,LineBasicMaterial as Ai,LineSegments as Bi,Raycaster as Oi,Vector2 as Fi}from"three";import{subscribe as Ii}from"valtio/vanilla";import{subscribe as Ei}from"valtio/vanilla";var ue=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),Ei(p,t)}resolveTarget(e){let t=this.stage.entityDelegate.debugMap.get(e)||this.stage.entityDelegate.childrenMap.get(e)||this.stage.world?.collisionMap.get(e)||null;return t?.group??t?.mesh??null??null}snapshot(){return{enabled:p.enabled,selected:p.selectedEntity?[p.selectedEntity.uuid]:[]}}};import{Box3 as Mi,BoxGeometry as Lt,Color as Di,EdgesGeometry as kt,Group as xi,LineBasicMaterial as Ti,LineSegments as Ri,Mesh as _i,MeshBasicMaterial as Li,Vector3 as At}from"three";var pe=class{scene;container;fillMesh;edgeLines;currentColor=new Di(65280);bbox=new Mi;size=new At;center=new At;constructor(e){this.scene=e;let t=new Lt(1,1,1);this.fillMesh=new _i(t,new Li({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new kt(t);this.edgeLines=new Ri(i,new Ti({color:this.currentColor,linewidth:1})),this.container=new xi,this.container.name="DebugEntityCursor",this.container.add(this.fillMesh),this.container.add(this.edgeLines),this.container.visible=!1,this.scene.add(this.container)}setColor(e){this.currentColor.set(e),this.fillMesh.material.color.set(this.currentColor),this.edgeLines.material.color.set(this.currentColor)}updateFromObject(e){if(!e){this.hide();return}if(this.bbox.setFromObject(e),!isFinite(this.bbox.min.x)||!isFinite(this.bbox.max.x)){this.hide();return}this.bbox.getSize(this.size),this.bbox.getCenter(this.center);let t=new Lt(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 kt(t);this.edgeLines.geometry.dispose(),this.edgeLines.geometry=i,this.container.position.copy(this.center),this.container.visible=!0}hide(){this.container.visible=!1}dispose(){this.scene.remove(this.container),this.fillMesh.geometry.dispose(),this.fillMesh.material.dispose(),this.edgeLines.geometry.dispose(),this.edgeLines.material.dispose()}};var zi=2293538,Zi=16724787,me=class{stage;options;mouseNdc=new Fi(-2,-2);raycaster=new Oi;isMouseDown=!1;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;debugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;focusContextUnregister=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.syncWithDebugState(),this.debugStateUnsubscribe=Ii(p,()=>{this.syncWithDebugState()}),this.focusContextUnregister=Xe({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{this.ensureCameraDebugDelegate(),this.stage.cameraRef?.frameObject(i)},ensureDebugReady:()=>{p.enabled||(p.enabled=!0),this.activate(),this.populateDebugMap()}})}resolveEntity(e){let t=this.stage.entityDelegate.debugMap.get(e);if(t)return t;let i=this.stage.entityDelegate.childrenMap.get(e);return i||(this.stage.world?.collisionMap.get(e)??null)}populateDebugMap(){this.stage.entityDelegate.childrenMap.forEach((e,t)=>{this.stage.entityDelegate.debugMap.set(t,e)})}ensureCameraDebugDelegate(){this.stage.cameraRef&&!this.cameraDebugDelegate&&(this.cameraDebugDelegate=new ue(this.stage),this.stage.cameraRef.setDebugDelegate(this.cameraDebugDelegate))}syncWithDebugState(){p.enabled?this.activate():this.deactivate()}activate(){this.domListenersAttached||(this.attachDomListeners(),this.domListenersAttached=!0),this.populateDebugMap(),this.ensureCameraDebugDelegate()}deactivate(){this.disposeDebugVisuals(),this.stage.cameraRef&&this.stage.cameraRef.setDebugDelegate(null),this.cameraDebugDelegate=null}initDebugVisuals(){this.debugLines||!this.stage.scene||(this.debugLines=new Bi(new ki,new Ai({vertexColors:!0})),this.stage.scene.scene.add(this.debugLines),this.debugLines.visible=!0,this.debugCursor=new pe(this.stage.scene.scene))}disposeDebugVisuals(){this.debugLines&&this.stage.scene&&(this.stage.scene.scene.remove(this.debugLines),this.debugLines.geometry.dispose(),this.debugLines.material.dispose(),this.debugLines=null),this.debugCursor?.dispose(),this.debugCursor=null}update(){if(!p.enabled){this.debugLines&&this.disposeDebugVisuals();return}if(!this.stage.scene||!this.stage.world||!this.stage.cameraRef)return;this.debugLines||this.initDebugVisuals();let{world:e,cameraRef:t}=this.stage;if(this.debugLines){let u=e.simulation.getDebugRender();u&&u.vertices.length>0?(this.debugLines.geometry.setAttribute("position",new Bt(new Float32Array(u.vertices),3)),this.debugLines.geometry.setAttribute("color",new Bt(new Float32Array(u.colors),4)),this.debugLines.geometry.attributes.position.needsUpdate=!0,this.debugLines.geometry.attributes.color.needsUpdate=!0,this.debugLines.visible=!0):this.debugLines.visible=!1}let i=Ce(),r=i==="select"||i==="delete";this.raycaster.setFromCamera(this.mouseNdc,t.camera);let a=this.raycaster.ray.origin.clone(),n=this.raycaster.ray.direction.clone().normalize(),o=e.raycast(a,n,this.options.maxRayDistance);if(o&&r){let u=o.uuid;if(u){let h=this.stage.entityDelegate.debugMap.get(u);h&&Fe(h)}else Ie();this.isMouseDown&&this.handleActionOnHit(u??null,a,n,o.distance)}this.isMouseDown=!1;let l=Oe();if(!l){this.debugCursor?.hide();return}let c=this.stage.entityDelegate.debugMap.get(`${l}`),d=c?.group??c?.mesh??null;if(!d){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(zi);break;case"delete":this.debugCursor?.setColor(Zi);break;default:this.debugCursor?.setColor(16777215);break}this.debugCursor?.updateFromObject(d)}dispose(){this.focusContextUnregister?.(),this.focusContextUnregister=null,this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.deactivate(),this.domDisposeFns.forEach(e=>e()),this.domDisposeFns=[],this.domListenersAttached=!1}handleActionOnHit(e,t,i,r){switch(Ce()){case"select":{if(e){let n=this.resolveEntity(e);n&&Be(n)}break}case"delete":{e&&this.stage.entityDelegate.removeEntityByUuid(e);break}case"scale":{if(!this.options.addEntityFactory)break;let n=t.clone().add(i.clone().multiplyScalar(r)),o=this.options.addEntityFactory({position:n});o&&Promise.resolve(o).then(l=>{l&&this.stage.entityDelegate.spawnEntity(l)}).catch(()=>{});break}default:break}}attachDomListeners(){let e=this.stage.cameraRef?.renderer.domElement??this.stage.scene?.zylemCamera.renderer.domElement;if(!e)return;let t=r=>{let a=e.getBoundingClientRect(),n=(r.clientX-a.left)/a.width*2-1,o=-((r.clientY-a.top)/a.height*2-1);this.mouseNdc.set(n,o)},i=()=>{this.isMouseDown=!0};e.addEventListener("mousemove",t),e.addEventListener("mousedown",i),this.domDisposeFns.push(()=>e.removeEventListener("mousemove",t)),this.domDisposeFns.push(()=>e.removeEventListener("mousedown",i))}};import{Vector2 as Vi}from"three";var he=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Vi(e,t);return new C(m.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new ae;if(e)return i.addCamera(e,e.name||"main"),i;let r=t.filter(a=>a!==void 0);if(r.length>0){for(let a of r){let n=a.cameraRef;i.addCamera(n,n.name||void 0)}for(let a=1;a<r.length;a++)i.addActiveCamera(r[a].cameraRef)}else{let a=this.createDefaultCamera();i.addCamera(a,"default")}return i}};var ge=class{loadingHandlers=[];stageName;stageIndex;setStageContext(e,t){this.stageName=e,this.stageIndex=t}onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let i of this.loadingHandlers)try{i(e)}catch(r){console.error("Loading handler failed",r)}let t={...e,stageName:this.stageName,stageIndex:this.stageIndex};e.type==="start"?N.emit("stage:loading:start",t):e.type==="progress"?N.emit("stage:loading:progress",t):e.type==="complete"&&N.emit("stage:loading:complete",t)}emitStart(e="Loading stage..."){this.emit({type:"start",message:e,progress:0})}emitProgress(e,t,i){let r=i>0?t/i:0;this.emit({type:"progress",message:e,progress:r,current:t,total:i})}emitComplete(e="Stage loaded"){this.emit({type:"complete",message:e,progress:1})}dispose(){this.loadingHandlers=[]}};var fe=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)},k.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){O(e.options)||(this.scene?.addEntityGroup(e),this.onEntityReady?.(e));return}this.pendingEntities.set(e.uuid,e)}unobserve(e){this.pendingEntities.delete(e)}handleModelLoaded(e,t){let i=this.pendingEntities.get(e);if(!i||!t){this.pendingEntities.delete(e);return}this.scene?.addEntityGroup(i),O(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(k.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as Ot}from"@zylem/behaviors/core";var ye=class s{static EMPTY_BEHAVIOR_LINKS=[];children=[];childrenMap=new Map;debugMap=new Map;pendingEntities=[];pendingPromises=[];_isLoaded=!1;entityAddedHandlers=[];behaviorSystems=[];behaviorSystemByKey=new Map;registeredSystemKeys=new Set;behaviorEntityIndex=new Map;behaviorLinksByUuid=new Map;scene=null;world=null;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 U){e.create();for(let i of e.getChildren())i instanceof A&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:S(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof A&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:S(),camera:this.camera}),this.tryRegisterRenderStrategy(t),R(t)||this.scene.addEntityGroup(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),R(e)||this.scene.addEntityGroup(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(B(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!==Ot.Static&&(e.bodyDesc.kind=Ot.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof H){if(e.needsDeferredModelCollision())return;e.synchronizeRuntimeCollider()}this.world.addEntity(e)}}addEntityToStage(e){this.childrenMap.set(e.uuid,e),p.enabled&&this.debugMap.set(e.uuid,e);for(let t of this.entityAddedHandlers)try{t(e)}catch(i){console.error("onEntityAdded handler failed",i)}}removeEntityByUuid(e){if(!this.scene||!this.world)return!1;let t=this.world.collisionMap.get(e),i=this.childrenMap.get(e),r=t??i??this.debugMap.get(e);return r?(this.unregisterBehaviorLinks(r),this.entityModelDelegate.unobserve(e),R(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),!0):!1}getEntityByName(e){for(let t of this.childrenMap.values())if(t.name===e)return t;return console.warn(`Entity ${e} not found`),null}buildEntityState(e){return e instanceof Ue?{...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(E(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();E(i)?this.handleEntityImmediatelyOrQueue(i):G(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}G(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 a=[...this.pendingEntities];this.pendingEntities=[],this.enqueue(...a)}let i=[...this.pendingPromises];this.pendingPromises=[];let r=this.children.length+i.length;for(let a of this.children)await this.spawnEntity(a),t++,this.loadingDelegate.emitProgress(`Loaded ${a.name||"unknown"}`,t,r),t%5===0&&await this.yieldToEventLoop();for(let a of i){try{let n=await a;n&&await this.spawnEntity(n)}catch(n){console.error("Failed to resolve pending stage entity",n)}t++,this.loadingDelegate.emitProgress("Loaded async entity",t,r),t%5===0&&await this.yieldToEventLoop()}t%5!==0&&await this.yieldToEventLoop()}registerSystem(e){if(!this.world||!this.scene)return;let t;typeof e=="function"?t=e({world:this.world,scene:this.scene,getBehaviorLinks:i=>this.behaviorEntityIndex.get(i)??s.EMPTY_BEHAVIOR_LINKS,createEntity:Se,getGlobals:S}):t=e,this.behaviorSystems.push(t)}destroyAll(){for(let e of this.behaviorSystems)e.destroy?.();this.behaviorSystems.length=0,this.behaviorSystemByKey.clear(),this.registeredSystemKeys.clear(),this.behaviorEntityIndex.clear(),this.behaviorLinksByUuid.clear(),this.childrenMap.forEach(e=>{try{e.nodeDestroy({me:e,globals:S()})}catch{}Q(e)}),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[],this._isLoaded=!1,this.scene=null,this.world=null,this.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){let a=r.descriptor.key,n={entity:e,ref:r};i.push(n);let o=this.behaviorEntityIndex.get(a);o||(o=new Set,this.behaviorEntityIndex.set(a,o)),o.add(n);let l=this.behaviorSystemByKey.get(a);if(!l&&!this.registeredSystemKeys.has(a)){let c=r.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:d=>this.behaviorEntityIndex.get(d)??s.EMPTY_BEHAVIOR_LINKS,createEntity:Se,getGlobals:S});l=c,this.behaviorSystems.push(c),this.behaviorSystemByKey.set(a,c),this.registeredSystemKeys.add(a)}l?.attach?.(n)}this.behaviorLinksByUuid.set(e.uuid,i)}unregisterBehaviorLinks(e){let t=this.behaviorLinksByUuid.get(e?.uuid);if(t){for(let i of t){let r=i.ref?.descriptor?.key;if(!r)continue;let a=this.behaviorEntityIndex.get(r);a&&(this.behaviorSystemByKey.get(r)?.detach?.(i),a.delete(i),a.size===0&&this.behaviorEntityIndex.delete(r))}this.behaviorLinksByUuid.delete(e.uuid)}}};var Ui="Stage",ve=class extends de{type=Ui;state={...Ke};gravity;world;scene;renderStrategy=null;debugDelegate=null;uuid;wrapperRef=null;camera;cameras=[];cameraRef=null;cameraManagerRef=null;rendererManager=null;cameraDelegate;loadingDelegate;entityModelDelegate;childUpdateParams={};entityDelegate;constructor(e=[]){super(),this.world=null,this.scene=null,this.uuid=Gi(),this.cameraDelegate=new he(this),this.loadingDelegate=new ge,this.entityModelDelegate=new fe,this.entityDelegate=new ye(this.loadingDelegate,this.entityModelDelegate);let t=xt(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 It(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Ft?e:new Ft(e);Qe(i),Ye(t),$e(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 ce(e,r,this.state);let a=this.gravity??new It(0,0,0);if(this.world=await oe.create(a,this.state.physicsRate),this.scene.setup(),this.cameraManagerRef&&this.rendererManager){await this.scene.setupCameraManager(this.scene.scene,this.cameraManagerRef,this.rendererManager);let o=this.cameraManagerRef.primaryCamera;o&&(this.rendererManager.setPostProcessingEffects(this.state.postProcessingEffects??[]),this.rendererManager.setupPostProcessing(this.scene.scene,o.camera)),this.rendererManager.startRenderLoop(()=>{this.cameraManagerRef?.render(this.scene.scene)})}else await this.scene.setupCamera(this.scene.scene,r);let n=this.resolveRenderer(r);await T.configureGLTFRuntime({renderer:n,...ne(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,o=>this.entityDelegate.handleLateModelReady(o)),this.renderStrategy=new q,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 me(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;P("behaviorSystems",()=>{for(let a of this.entityDelegate.behaviorSystems)a.update(void 0,t)}),P("entityLoop",()=>{for(let a of this.entityDelegate.childrenMap.values()){let n=this.childUpdateParams;n.delta=e.delta,n.inputs=e.inputs,n.globals=e.globals,n.camera=e.camera,n.stage=e.stage,n.game=e.game,n.me=a,a.nodeUpdate(n);let o=a;o.transformStore&&Je(o,o.transformStore),a.markedForRemoval&&this.entityDelegate.removeEntityByUuid(a.uuid)}}),P("worldUpdate",()=>{i.update(e)}),P("syncRenderPoses",()=>{_t({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),P("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),P("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),P("scene",()=>{r.update({delta:t})}),ft()}outOfLoop(){this.debugUpdate()}debugUpdate(){p.enabled&&(Me("debugUpdate"),this.debugDelegate?.update(),De())}_destroy(e){this.entityDelegate.destroyAll(),this.world?.destroy(),this.scene?.destroy(),this.debugDelegate?.dispose(),this.debugDelegate=null,this.entityModelDelegate.dispose(),this.renderStrategy?.dispose(),this.renderStrategy=null,this.rendererManager&&this.rendererManager.stopRenderLoop(),this.world=null,this.scene=null,this.cameraRef=null,this.cameraManagerRef=null,qe(),Q(this)}async spawnEntity(e){return this.entityDelegate.spawnEntity(e)}buildEntityState(e){return this.entityDelegate.buildEntityState(e)}onEntityAdded(e,t){return this.entityDelegate.onEntityAdded(e,t)}onLoading(e){return this.loadingDelegate.onLoading(e)}registerSystem(e){return this.entityDelegate.registerSystem(e),this}removeEntityByUuid(e){return this.entityDelegate.removeEntityByUuid(e)}getEntityByName(e){return this.entityDelegate.getEntityByName(e)}enqueue(...e){this.entityDelegate.enqueue(...e)}logMissingEntities(){console.warn("Zylem world or scene is null")}addCamera(e,t){return this.cameraManagerRef?this.cameraManagerRef.addCamera(e,t):(console.warn("ZylemStage: CameraManager not available. Ensure stage is loaded with a RendererManager."),null)}removeCamera(e){return this.cameraManagerRef?.removeCamera(e)??!1}setActiveCamera(e){return this.cameraManagerRef?.setActiveCamera(e)??!1}getCamera(e){return this.cameraManagerRef?.getCamera(e)??null}resize(e,t){this.scene&&this.scene.updateRenderer(e,t)}};import{proxy as Ni}from"valtio/vanilla";import{Vector3 as Hi}from"three";var Wi={backgroundColor:j,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new Hi(0,0,0),variables:{}},x=Ni({...Wi});function zt(s){let e=ji(),t={};return typeof s[0]=="object"&&(t=s.shift()??{}),[{...e,...t},...s]}function ji(){return{backgroundColor:x.backgroundColor,backgroundImage:x.backgroundImage??null,inputs:x.inputs?{...x.inputs}:void 0,gravity:x.gravity,variables:x.variables?{...x.variables}:void 0}}var Ae=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Ve;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];T.prepareGLTFRuntime(ne(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=Ze(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){K.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new ve(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(c=>{this.wrappedStage.onLoading(c)}),this.pendingLoadingCallbacks=[];let a=t instanceof y?t.cameraRef:t;await this.wrappedStage.load(e,a,i);let n=null,o=!1,l=()=>{if(o=!1,!n?.length){n=null;return}let c=n;n=null,K.entities=[...K.entities,...c]};this.wrappedStage.onEntityAdded(c=>{if(O(c.options))return;let d=this.wrappedStage.buildEntityState(c);n||(n=[]),n.push(d),o||(o=!0,queueMicrotask(l))},{replayExisting:!0}),this.applyLifecycleCallbacks()}applyLifecycleCallbacks(){this.wrappedStage&&(this.setupCallbacks.length>0&&(this.wrappedStage.setup=e=>{let t={...e,stage:this};this.setupCallbacks.forEach(i=>i(t))}),this.updateCallbacks.length>0&&(this.wrappedStage.update=e=>{let t={...e,stage:this};this.updateCallbacks.forEach(i=>i(t))}),this.destroyCallbacks.length>0&&(this.wrappedStage.destroy=e=>{let t={...e,stage:this};this.destroyCallbacks.forEach(i=>i(t))}))}async addEntities(e){this._pendingEntities.push(...e),this.wrappedStage&&this.wrappedStage.enqueue(...e)}add(...e){this.addToBlueprints(...e),this.addToStage(...e)}addToBlueprints(...e){this.wrappedStage||this.options.push(...e)}addToStage(...e){this.wrappedStage&&this.wrappedStage.enqueue(...e)}start(e){!this.wrappedStage||this.wrappedStage.hasSetup||this.wrappedStage.nodeSetup(e)}onUpdate(...e){return this.updateCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.update=t=>{let i={...t,stage:this};this.updateCallbacks.forEach(r=>r(i))}),this}onSetup(...e){return this.setupCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.setup=t=>{let i={...t,stage:this};this.setupCallbacks.forEach(r=>r(i))}),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.destroy=t=>{let i={...t,stage:this};this.destroyCallbacks.forEach(r=>r(i))}),this}onLoading(e){return this.wrappedStage?this.wrappedStage.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e)})}getEntityByName(e,t){return this.wrappedStage?.getEntityByName(e)}addCamera(e,t){let i=e instanceof y?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof y?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof y?this.wrappedStage?.setActiveCamera(e.cameraRef)??!1:this.wrappedStage?.setActiveCamera(e)??!1}getCamera(e){return this.wrappedStage?.getCamera(e)??null}dispatch(e,t){this.eventDelegate.dispatch(e,t),k.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function En(...s){let e=zt(s);return new Ae([...e])}export{tr as a,Y as b,B as c,O as d,R as e,$ as f,q as g,yr as h,m as i,M as j,ee as k,D as l,_ as m,Z as n,L as o,ae as p,y as q,Pa as r,_a as s,mi as t,Ae as u,En as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{proxy as n}from"valtio/vanilla";var e=n({enabled:!1,paused:!1,tool:"none",selectedEntity:null,hoveredEntity:null,flags:new Set});function l(){return e.paused}function i(t){e.paused=t}function a(){return e.tool}function r(t){e.tool=t}function u(t){e.selectedEntity=t}function s(){return e.hoveredEntity}function d(t){e.hoveredEntity=t}function y(){e.hoveredEntity=null}export{e as a,l as b,i as c,a as d,r as e,u as f,s as g,d as h,y as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Type as e}from"@sinclair/typebox";var n=e.Tuple([e.Number(),e.Number()],{title:"Vector2",description:"A 2D position as [x, y]."}),s=e.Object({id:e.String(),type:e.String({minLength:1}),position:e.Optional(n),data:e.Optional(e.Record(e.String(),e.Any()))},{$id:"EntityBlueprint",title:"EntityBlueprint",additionalProperties:!1}),D=e.Object({id:e.String(),name:e.Optional(e.String()),entities:e.Array(s),assets:e.Optional(e.Array(e.String()))},{$id:"StageBlueprint",title:"StageBlueprint",additionalProperties:!1}),S=e.Object({value:e.Optional(e.String()),color:e.Optional(e.String()),fontSize:e.Optional(e.Number()),fontFamily:e.Optional(e.String())},{title:"TextEntityData",additionalProperties:!0}),m=e.Tuple([e.Number(),e.Number(),e.Number()],{title:"Vector3Tuple"}),g=e.Object({points:e.Array(m,{minItems:2}),color:e.Optional(e.String()),colors:e.Optional(e.Array(e.String())),linewidth:e.Optional(e.Number()),worldUnits:e.Optional(e.Boolean()),alphaToCoverage:e.Optional(e.Boolean()),opacity:e.Optional(e.Number()),transparent:e.Optional(e.Boolean()),dashed:e.Optional(e.Boolean()),dashSize:e.Optional(e.Number()),gapSize:e.Optional(e.Number()),pickThreshold:e.Optional(e.Number())},{title:"LineEntityData",additionalProperties:!0}),u=e.Object({imagePath:e.Optional(e.String()),width:e.Optional(e.Number()),height:e.Optional(e.Number())},{title:"SpriteEntityData",additionalProperties:!0}),h=e.Union([e.Object({id:e.String(),type:e.Literal("text"),position:e.Optional(n),data:e.Optional(S)}),e.Object({id:e.String(),type:e.Literal("sprite"),position:e.Optional(n),data:e.Optional(u)}),e.Object({id:e.String(),type:e.Literal("line"),position:e.Optional(n),data:e.Optional(g)}),e.Object({id:e.String(),type:e.String({minLength:1}),position:e.Optional(n),data:e.Optional(e.Record(e.String(),e.Unknown()))})],{$id:"EntityJson",title:"EntityJson"}),B=e.Object({id:e.String(),name:e.Optional(e.String()),entities:e.Array(h),assets:e.Optional(e.Array(e.String()))},{$id:"StageJson",title:"StageJson",additionalProperties:!1});import{Type as t}from"@sinclair/typebox";var y=t.Record(t.String(),t.Array(t.String()),{title:"KeyboardMapping"}),O=t.Record(t.String(),t.Array(t.String()),{title:"MouseMapping"}),a=t.Record(t.String(),t.Union([t.String(),t.Number()]),{title:"VirtualTouchStyle"}),p=t.Object({top:t.Optional(t.Union([t.String(),t.Number()])),right:t.Optional(t.Union([t.String(),t.Number()])),bottom:t.Optional(t.Union([t.String(),t.Number()])),left:t.Optional(t.Union([t.String(),t.Number()])),transform:t.Optional(t.String())},{title:"VirtualTouchPosition",additionalProperties:!1}),f=t.Object({enabled:t.Optional(t.Boolean()),className:t.Optional(t.String()),style:t.Optional(a),position:t.Optional(p),size:t.Optional(t.Number()),label:t.Optional(t.String()),svg:t.Optional(t.String())},{title:"VirtualTouchButtonConfig",additionalProperties:!1}),r=t.Object({enabled:t.Optional(t.Boolean()),className:t.Optional(t.String()),style:t.Optional(a),position:t.Optional(p),size:t.Optional(t.Number()),thumbSize:t.Optional(t.Number()),maxDistance:t.Optional(t.Number()),deadzone:t.Optional(t.Number()),directionThreshold:t.Optional(t.Number()),horizontalAxis:t.Optional(t.Union([t.Literal("Horizontal"),t.Literal("SecondaryHorizontal")])),verticalAxis:t.Optional(t.Union([t.Literal("Vertical"),t.Literal("SecondaryVertical")])),emitDirections:t.Optional(t.Boolean()),svg:t.Optional(t.Object({base:t.Optional(t.String()),thumb:t.Optional(t.String())}))},{title:"VirtualTouchJoystickConfig",additionalProperties:!1}),j=t.Union([f,t.Literal(!1)]),d=t.Record(t.String(),j,{title:"VirtualTouchButtonsConfig",description:"Keys are touch button slots: A, B, X, Y, Start, Select, L, R, LTrigger, RTrigger, Up, Down, Left, Right."}),C=t.Object({left:t.Optional(t.Union([r,t.Literal(!1)])),right:t.Optional(t.Union([r,t.Literal(!1)]))},{title:"VirtualTouchJoysticksConfig",additionalProperties:!1}),b=t.Object({enabled:t.Optional(t.Union([t.Boolean(),t.Literal("auto")])),className:t.Optional(t.String()),style:t.Optional(a),joysticks:t.Optional(t.Union([C,t.Literal(!1)])),buttons:t.Optional(t.Union([d,t.Literal(!1)]))},{title:"VirtualTouchConfig",additionalProperties:!1}),x=t.Object({mapping:t.Optional(O),pointerLock:t.Optional(t.Boolean()),sensitivity:t.Optional(t.Number())},{title:"MouseConfig",additionalProperties:!1}),J=t.Object({key:t.Optional(y),mouse:t.Optional(x),touch:t.Optional(b),includeDefaults:t.Optional(t.Boolean())},{title:"GameInputPlayerConfig",additionalProperties:!1}),l=t.Record(t.String(),J,{$id:"GameInputConfig",title:"GameInputConfig",description:"Keys are player slots: p1, p2, p3, p4, p5, p6, p7, p8."});import{Type as i}from"@sinclair/typebox";var T=i.Union([i.String(),i.Number()],{title:"ColorJson",description:"CSS color string or numeric hex (Three.js Color-compatible)."}),E=i.Tuple([i.Number(),i.Number(),i.Number()],{title:"Vec3Components"}),L=i.Object({meshopt:i.Optional(i.Boolean()),ktx2TranscoderPath:i.Optional(i.String())},{title:"StageGLTFAssetLoaderConfig",additionalProperties:!1}),V=i.Object({gltf:i.Optional(L)},{title:"StageAssetLoaderConfig",additionalProperties:!1}),G=i.Object({inputs:i.Optional(i.Record(i.String(),i.Array(i.String()))),backgroundColor:i.Optional(T),backgroundImage:i.Optional(i.Union([i.String(),i.Null()])),gravity:i.Optional(E),variables:i.Optional(i.Record(i.String(),i.Unknown())),physicsRate:i.Optional(i.Number({exclusiveMinimum:0})),assetLoaders:i.Optional(V),defaultLighting:i.Optional(i.Boolean())},{$id:"StageConfigJson",title:"StageConfigJson",additionalProperties:!1});import{Type as o}from"@sinclair/typebox";var c=o.Union([o.String(),o.Object({width:o.Number({exclusiveMinimum:0}),height:o.Number({exclusiveMinimum:0})}),o.Literal("native")],{title:"ResolutionInput"}),N=o.Object({aspectRatio:o.Optional(o.Union([o.Number(),o.String()])),preset:o.Optional(o.String()),resolution:o.Optional(c),controls:o.Optional(o.Boolean())},{title:"GameDeviceConfigJson",additionalProperties:!1}),P=o.Object({id:o.Optional(o.String()),globals:o.Optional(o.Record(o.String(),o.Unknown())),debug:o.Optional(o.Boolean()),time:o.Optional(o.Number()),input:o.Optional(l),aspectRatio:o.Optional(o.Union([o.Number(),o.String()])),preset:o.Optional(o.String()),resolution:o.Optional(c),mobile:o.Optional(N),fullscreen:o.Optional(o.Boolean()),bodyBackground:o.Optional(o.String()),containerId:o.Optional(o.String())},{$id:"GameConfigJson",title:"GameConfigJson",additionalProperties:!1});export{n as a,s as b,D as c,S as d,m as e,g as f,u as g,h,B as i,y as j,O as k,a as l,p as m,f as n,r as o,d as p,C as q,b as r,x as s,J as t,l as u,T as v,E as w,L as x,V as y,G as z,c as A,N as B,P as C};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function r(n,e){return{[n]:{key:e}}}function k(n){return r(n,{ArrowLeft:["axes.Left"],ArrowRight:["axes.Right"],ArrowUp:["axes.Up"],ArrowDown:["axes.Down"]})}function x(n){return r(n,{ArrowLeft:["axes.SecondaryLeft"],ArrowRight:["axes.SecondaryRight"],ArrowUp:["axes.SecondaryUp"],ArrowDown:["axes.SecondaryDown"]})}function w(n){return r(n,{ArrowLeft:["directions.Left"],ArrowRight:["directions.Right"],ArrowUp:["directions.Up"],ArrowDown:["directions.Down"]})}function A(n){return r(n,{w:["directions.Up"],s:["directions.Down"],a:["directions.Left"],d:["directions.Right"]})}function G(n){return r(n,{a:["axes.Left"],d:["axes.Right"],w:["axes.Up"],s:["axes.Down"]})}function J(n){return r(n,{j:["axes.Left"],l:["axes.Right"],i:["axes.Up"],k:["axes.Down"]})}function B(n){return r(n,{j:["directions.Left"],l:["directions.Right"],i:["directions.Up"],k:["directions.Down"]})}function D(n,e){return{[n]:{mouse:{pointerLock:!0,sensitivity:e?.sensitivity}}}}function P(n,e){return{[n]:{mouse:{pointerLock:!1,sensitivity:e?.sensitivity}}}}function b(n,e){return{[n]:{touch:{enabled:e?.enabled??"auto",...e}}}}var h=["p1","p2","p3","p4","p5","p6","p7","p8"];function L(...n){let e={};for(let u of n)for(let t of h){let s=u[t];if(!s)continue;let o=e[t]??{},f=o.mouse||s.mouse?{...o.mouse,...s.mouse,mapping:{...o.mouse?.mapping,...s.mouse?.mapping}}:void 0,a=T(o.touch,s.touch);e[t]={key:{...o.key,...s.key},mouse:f,touch:a,includeDefaults:s.includeDefaults??o.includeDefaults}}return e}function T(n,e){if(!(!n&&!e))return n?e?{...n,...e,style:i(n.style,e.style),joysticks:m(n.joysticks,e.joysticks),buttons:I(n.buttons,e.buttons)}:d(n):d(e)}function m(n,e){if(e===void 0)return p(n);if(e===!1)return!1;let u=n||void 0;return{left:c(u?.left,e.left),right:c(u?.right,e.right)}}function c(n,e){return e===void 0?l(n):e===!1?!1:n?{...n,...e,style:i(n.style,e.style),position:i(n.position,e.position),svg:i(n.svg,e.svg)}:l(e)}function I(n,e){if(e===void 0)return y(n);if(e===!1)return!1;let u=n||void 0,t=u?C(u):{};for(let[s,o]of Object.entries(e)){let f=s,a=t[f];if(o===!1){t[f]=!1;continue}if(!a){t[f]=g(o);continue}t[f]={...a,...o,style:i(a.style,o.style),position:i(a.position,o.position)}}return t}function d(n){if(n)return{...n,style:i(void 0,n.style),joysticks:p(n.joysticks),buttons:y(n.buttons)}}function p(n){if(n!==void 0)return n===!1?!1:V(n)}function l(n){if(n!==void 0)return n===!1?!1:{...n,style:i(void 0,n.style),position:i(void 0,n.position),svg:i(void 0,n.svg)}}function y(n){if(n!==void 0)return n===!1?!1:C(n)}function g(n){return{...n,style:i(void 0,n.style),position:i(void 0,n.position)}}function V(n){return{left:l(n.left),right:l(n.right)}}function C(n){let e={};for(let[u,t]of Object.entries(n))e[u]=t===!1?!1:g(t);return e}function i(n,e){if(!(!n&&!e))return{...n??{},...e??{}}}export{k as a,x as b,w as c,A as d,G as e,J as f,B as g,D as h,P as i,b as j,L as k};
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{positionWorldDirection as v,positionWorld as j,normalize as k,mix as B,smoothstep as E,clamp as F,sin as W,cos as w,atan as z,asin as C,abs as D,exp as G,pow as M,step as N,max as O,min as P,floor as V,fract as q,dot as A,length as H,vec2 as I,mod as J}from"three/tsl";function o(e,r=!1){return{colorNode:e,transparent:r}}export{o as a,v as b,j as c,k as d,B as e,E as f,F as g,W as h,w as i,z as j,C as k,D as l,G as m,M as n,N as o,O as p,P as q,V as r,q as s,A as t,H as u,I as v,J as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function n(t){return{all:t=t||new Map,on:function(e,f){var i=t.get(e);i?i.push(f):t.set(e,[f])},off:function(e,f){var i=t.get(e);i&&(f?i.splice(i.indexOf(f)>>>0,1):t.set(e,[]))},emit:function(e,f){var i=t.get(e);i&&i.slice().map(function(c){c(f)}),(i=t.get("*"))&&i.slice().map(function(c){c(e,f)})}}}export{n as a};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import{j as y}from"./chunk-MSC2BEO5.js";var r={baseFill:"rgba(12,18,24,0.72)",joystickStroke:"rgba(245,247,255,0.72)",joystickInnerStroke:"rgba(255,255,255,0.18)",joystickAccentFill:"rgba(255,255,255,0.04)",joystickTabFill:"rgba(245,247,255,0.45)",thumbFill:"rgba(22,30,38,0.92)",thumbStroke:"rgba(245,247,255,0.85)",thumbInnerFill:"rgba(255,255,255,0.08)",defaultButtonAccent:"rgba(245,247,255,0.92)"},b={baseFill:"rgba(8,14,24,0.70)",joystickStroke:"rgba(207,250,254,0.85)",joystickInnerStroke:"rgba(45,212,191,0.35)",joystickAccentFill:"rgba(20,184,166,0.08)",joystickTabFill:"rgba(207,250,254,0.55)",thumbFill:"rgba(13,148,136,0.88)",thumbStroke:"rgba(240,253,250,0.95)",thumbInnerFill:"rgba(240,253,250,0.16)",defaultButtonAccent:"#67e8f9",buttonAccents:{A:"#8b5cf6",B:"#fb7185",X:"#22d3ee",Y:"#facc15"}},m={default:r,lagoon:b};function l(e){return e?typeof e=="string"?m[e]??r:e:r}function f(e,t,o){return o||(e.buttonAccents?.[t]??e.defaultButtonAccent)}function h(e){let t=l(e);return`
|
|
2
|
+
<svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
|
|
3
|
+
<circle cx="70" cy="70" r="62" fill="${t.baseFill}" stroke="${t.joystickStroke}" stroke-width="4" />
|
|
4
|
+
<circle cx="70" cy="70" r="42" fill="${t.joystickAccentFill}" stroke="${t.joystickInnerStroke}" stroke-width="2" />
|
|
5
|
+
<path d="M70 24 L78 40 L62 40 Z" fill="${t.joystickTabFill}" />
|
|
6
|
+
<path d="M116 70 L100 78 L100 62 Z" fill="${t.joystickTabFill}" />
|
|
7
|
+
<path d="M70 116 L62 100 L78 100 Z" fill="${t.joystickTabFill}" />
|
|
8
|
+
<path d="M24 70 L40 62 L40 78 Z" fill="${t.joystickTabFill}" />
|
|
9
|
+
</svg>
|
|
10
|
+
`}function a(e){let t=l(e);return`
|
|
11
|
+
<svg viewBox="0 0 64 64" width="100%" height="100%" aria-hidden="true">
|
|
12
|
+
<circle cx="32" cy="32" r="28" fill="${t.thumbFill}" stroke="${t.thumbStroke}" stroke-width="3.5" />
|
|
13
|
+
<circle cx="32" cy="32" r="15" fill="${t.thumbInnerFill}" stroke="${t.thumbStroke}" stroke-width="1.5" />
|
|
14
|
+
</svg>
|
|
15
|
+
`}function g(e,t={}){let o=l(t.theme),n=t.accent??o.defaultButtonAccent,i=B(e),u=i.length>2?24:34;return`
|
|
16
|
+
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true">
|
|
17
|
+
<circle cx="50" cy="50" r="45" fill="${o.baseFill}" stroke="${n}" stroke-width="4.5" />
|
|
18
|
+
<circle cx="50" cy="50" r="33" fill="${n}" opacity="0.18" />
|
|
19
|
+
<text
|
|
20
|
+
x="50"
|
|
21
|
+
y="60"
|
|
22
|
+
text-anchor="middle"
|
|
23
|
+
font-family="ui-sans-serif, system-ui, sans-serif"
|
|
24
|
+
font-size="${u}"
|
|
25
|
+
font-weight="700"
|
|
26
|
+
fill="${n}"
|
|
27
|
+
>${i}</text>
|
|
28
|
+
</svg>
|
|
29
|
+
`}function B(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var S=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"];function C(e="p1",t={}){let o=l(t.theme),n=V(o,t),i=t.override?A(n,t.override):n;return y(e,i)}function V(e,t){return{enabled:t.enabled??"auto",joysticks:j(e,t.joysticks??"left"),buttons:x(e,t)}}function j(e,t){if(t==="none")return!1;let o={svg:{base:h(e),thumb:a(e)}},n={};return t==="left"||t==="both"?n.left={...o}:n.left=!1,t==="right"||t==="both"?n.right={...o}:n.right=!1,n}function x(e,t){let o=t.buttons??["A","B"],n=new Set(o),i=t.buttonAccents,u=t.buttonLabels,c={};for(let s of S){if(!n.has(s)){c[s]=!1;continue}let T=u?.[s]??s,p=f(e,s,i?.[s]),d={label:T,svg:g(T,{accent:p,theme:e})};c[s]=d}return c}function A(e,t){let o={...e,...t};(e.style||t.style)&&(o.style={...e.style,...t.style});let n=F(e.joysticks,t.joysticks);n!==void 0?o.joysticks=n:delete o.joysticks;let i=v(e.buttons,t.buttons);return i!==void 0?o.buttons=i:delete o.buttons,o}function F(e,t){if(t===void 0)return e;if(t===!1)return!1;if(!e)return t;let o={},n=k(e.left,t.left);n!==void 0&&(o.left=n);let i=k(e.right,t.right);return i!==void 0&&(o.right=i),o}function k(e,t){if(t===void 0)return e;if(t===!1)return!1;if(!e)return t;let o={...e,...t};return(e.style||t.style)&&(o.style={...e.style,...t.style}),(e.position||t.position)&&(o.position={...e.position,...t.position}),(e.svg||t.svg)&&(o.svg={...e.svg,...t.svg}),o}function v(e,t){if(t===void 0)return e;if(t===!1)return!1;if(!e)return t;let o={...e};for(let[n,i]of Object.entries(t)){if(i===void 0)continue;let u=o[n];if(i===!1||!u){o[n]=i;continue}let c={...u,...i};(u.style||i.style)&&(c.style={...u.style,...i.style}),(u.position||i.position)&&(c.position={...u.position,...i.position}),o[n]=c}return o}export{m as a,l as b,f as c,h as d,a as e,g as f,C as g};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as n,c as o,e as a}from"./chunk-JQKS42G4.js";var s=class r extends HTMLElement{_game=null;_state={};container;resizeObserver=null;_viewportProfile="auto";static HOST_CONFIG_MARKER=Symbol("zylem:host-config");constructor(){super(),this.attachShadow({mode:"open"});let e=document.createElement("style");e.textContent=`
|
|
2
|
+
:host {
|
|
3
|
+
display: block;
|
|
4
|
+
width: 100%;
|
|
5
|
+
height: 100%;
|
|
6
|
+
min-width: 0;
|
|
7
|
+
min-height: 0;
|
|
8
|
+
}
|
|
9
|
+
`,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.outline="none",this.container.tabIndex=0,this.shadowRoot.append(e,this.container)}focus(){this.container.focus()}connectedCallback(){typeof ResizeObserver<"u"&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(()=>{this.syncDisplayRuntime()}),this.resizeObserver.observe(this)),this.syncDisplayRuntime()}set game(e){this._game&&this._game.dispose(),this._game=e,this.attachHostContainer(e),this.syncDisplayRuntime(),e.start()}get game(){return this._game}set state(e){this._state=e,this.syncDebugState(),this.syncToolbarState()}get state(){return this._state}set viewportProfile(e){let t=e==="mobile"||e==="desktop"?e:"auto";this._viewportProfile!==t&&(this._viewportProfile=t,this.syncDisplayRuntime())}get viewportProfile(){return this._viewportProfile}static get observedAttributes(){return["viewport-profile"]}attributeChangedCallback(e,t,i){e==="viewport-profile"&&(this.viewportProfile=i??"auto")}syncDebugState(){let e=this._state.gameState?.debugFlag;e!==void 0&&(n.enabled=e)}syncToolbarState(){let{tool:e,paused:t}=this._state.toolbarState??{};e!==void 0&&a(e),t!==void 0&&o(t)}disconnectedCallback(){this.resizeObserver?.disconnect(),this.resizeObserver=null,this._game&&(this._game.dispose(),this._game=null)}attachHostContainer(e){let t=r.HOST_CONFIG_MARKER,i=e.options.find(l=>!!l?.[t]);if(i){i.container=this.container;return}e.options.push({container:this.container,[t]:!0})}syncDisplayRuntime(){if(!this._game)return;let e=this.getBoundingClientRect(),t=Math.round(e.width||this.clientWidth||0),i=Math.round(e.height||this.clientHeight||0);this._game.setDisplayRuntime({deviceProfile:this._viewportProfile,viewportSize:t>0&&i>0?{width:t,height:i}:void 0})}};customElements.define("zylem-game",s);export{s as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as f,f as b}from"./chunk-JQKS42G4.js";var i=null;function g(n){return i=n,()=>{i===n&&(i=null)}}function O(n){if(!i)return console.warn("focusEntity: no active stage focus context"),!1;let t=i.resolveEntity(n);if(!t)return console.warn(`focusEntity: entity ${n} not found`),!1;let r=t.group??t.mesh??null;return r?(f.enabled||(f.enabled=!0),i.ensureDebugReady?.(),b(t),i.frameObject(r),!0):(console.warn(`focusEntity: entity ${n} has no group/mesh`),!1)}import{Box3 as d,PerspectiveCamera as p,Vector3 as u}from"three";var m=new d,a=new u,x=new u,h=new u;function l(n){m.setFromObject(n),m.getSize(a),m.getCenter(x);let t=Math.max(a.x,1e-4),r=Math.max(a.y,1e-4),o=Math.max(a.z,1e-4),e=Math.max(t,r,o);return{width:t,height:r,depth:o,center:x.clone(),maxDim:e}}function y(n,t,r=1.35){let o=t.fov*(Math.PI/180),e=n/(2*Math.tan(o/2))*r;return Math.max(e,.5)}function M(n,t,r=1.35){let o=l(n),e=y(o.maxDim,t,r);return t.position.copy(o.center).add(new u(e,e,e)),t.lookAt(o.center),t.near=Math.max(e/100,.01),t.far=Math.max(e*20,100),t.updateProjectionMatrix(),o}function v(n,t,r,o=1.5){let e=l(n),c=h.copy(r);c.lengthSq()<1e-8&&c.set(1,1,1),c.normalize();let s=e.maxDim*o;return t instanceof p&&(s=y(e.maxDim,t,o),t.near=Math.max(s/100,.01),t.far=Math.max(s*20,100),t.updateProjectionMatrix()),t.position.copy(e.center).addScaledVector(c,s),t.lookAt(e.center),e}export{M as a,v as b,g as c,O as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function u(t,r){let n;return a=>{let e=a.globals?.[t];n!==e&&(n===void 0&&e===void 0||r(e,a),n=e)}}function f(t,r){let n=new Array(t.length).fill(void 0);return a=>{let e=t.map(i=>a.globals?.[i]);if(e.some((i,l)=>n[l]!==i)){let i=n.every(o=>o===void 0),l=e.every(o=>o===void 0);i&&l||r(e,a),n=e}}}function g(t,r){let n;return a=>{let e=a.stage?.getVariable?.(t)??void 0;n!==e&&(n===void 0&&e===void 0||r(e,a),n=e)}}function C(t,r){let n=new Array(t.length).fill(void 0);return a=>{let e=l=>a.stage?.getVariable?.(l),d=t.map(e);if(d.some((l,o)=>n[o]!==l)){let l=n.every(s=>s===void 0),o=d.every(s=>s===void 0);l&&o||r(d,a),n=d}}}export{u as a,f as b,g as c,C as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BoundaryRicochet3DCoordinator as o,BoundaryRicochetCoordinator as r,CooldownBehavior as n,Destructible3DBehavior as i,DestructibleMesh as a,FirstPersonBehavior as D,FirstPersonEvent as m,FirstPersonFSM as c,FirstPersonShooterCoordinator as l,FirstPersonState as p,FirstPersonPresentation as u,FractureOptions as s,Jumper2DBehavior as h,Jumper2DEvent as d,Jumper2DFSM as B,Jumper2DState as C,Jumper3DBehavior as y,Jumper3DEvent as S,Jumper3DFSM as R,Jumper3DState as P,MultidirectionalSpaceShooterCoordinator as v,ParticleEmitterBehavior as E,Platformer2DBehavior as f,Platformer2DEvent as M,Platformer2DFSM as O,Platformer2DState as g,Platformer3DBehavior as T,Platformer3DEvent as I,Platformer3DFSM as F,Platformer3DState as W,Ricochet2DBehavior as H,Ricochet2DEvent as _,Ricochet2DFSM as J,Ricochet2DState as w,Ricochet3DBehavior as b,Ricochet3DEvent as A,Ricochet3DFSM as x,Ricochet3DState as V,ScreenVisibilityBehavior as k,ScreenVisibilityFSM as N,ScreenWrapBehavior as G,ScreenWrapEvent as Y,ScreenWrapFSM as U,ScreenWrapState as K,Shooter2DBehavior as L,ThrusterBehavior as Z,ThrusterEvent as z,ThrusterFSM as q,ThrusterState as j,TopDownMovementBehavior as Q,TopDownShooterCoordinator as X,WorldBoundary2DBehavior as $,WorldBoundary2DEvent as ee,WorldBoundary2DFSM as te,WorldBoundary2DState as oe,WorldBoundary3DBehavior as re,WorldBoundary3DEvent as ne,WorldBoundary3DFSM as ie,WorldBoundary3DState as ae,computeWorldBoundary2DHits as De,computeWorldBoundary3DHits as me,createFirstPersonInputComponent as ce,createFirstPersonMovementComponent as le,createFirstPersonStateComponent as pe,createJumpConfig2D as ue,createJumpConfig3D as se,createJumpInput2D as he,createJumpInput3D as de,createJumpState2D as Be,createJumpState3D as Ce,createPhysicsBodyComponent as ye,createPlatformer2DInputComponent as Se,createPlatformer2DMovementComponent as Re,createPlatformer2DStateComponent as Pe,createPlatformer3DInputComponent as ve,createPlatformer3DMovementComponent as Ee,createPlatformer3DStateComponent as fe,createShooter2DStateComponent as Me,createThrusterInputComponent as Oe,createThrusterMovementComponent as ge,createThrusterStateComponent as Te,createTopDownMovementComponent as Ie,createTopDownMovementInputComponent as Fe,createTopDownMovementStateComponent as We,createTransformComponent as He,defineBehavior as _e,fireCooldown as Je,fireShooter2DIfRequested as we,getCooldown as be,getCooldownStore as Ae,getEntityFacingAngle2D as xe,hasAnyWorldBoundary2DHit as Ve,hasAnyWorldBoundary3DHit as ke,particleEffect as Ne,particlePresets as Ge,registerCooldown as Ye,resetCooldown as Ue,resolveAim2D as Ke,tickCooldowns as Le,updateBoundaryRicochet as Ze,useBehavior as ze}from"@zylem/behaviors";import{RuntimeBoundary2DBehavior as Xe,RuntimeDynamicCircleBody2DBehavior as $e,RuntimeGoalZone2DBehavior as et,RuntimePlayerInput2DBehavior as tt,RuntimeRicochet2DBehavior as ot,RuntimeTriggerRegion2DBehavior as rt,RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY as nt,RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY as it,RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY as at,RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY as Dt,RUNTIME_RICOCHET_2D_BEHAVIOR_KEY as mt,RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY as ct,bindRuntimeDynamicCircleBody2DHandle as lt,emitRuntimeGoal as pt,emitRuntimeRicochet as ut,emitRuntimeTriggerRegionEnter as st}from"@zylem/behaviors/runtime-2d";export{o as a,r as b,n as c,i as d,a as e,D as f,m as g,c as h,l as i,p as j,u as k,s as l,h as m,d as n,B as o,C as p,y as q,S as r,R as s,P as t,v as u,E as v,f as w,M as x,O as y,g as z,T as A,I as B,F as C,W as D,H as E,_ as F,J as G,w as H,b as I,A as J,x as K,V as L,k as M,N,G as O,Y as P,U as Q,K as R,L as S,Z as T,z as U,q as V,j as W,Q as X,X as Y,$ as Z,ee as _,te as $,oe as aa,re as ba,ne as ca,ie as da,ae as ea,De as fa,me as ga,ce as ha,le as ia,pe as ja,ue as ka,se as la,he as ma,de as na,Be as oa,Ce as pa,ye as qa,Se as ra,Re as sa,Pe as ta,ve as ua,Ee as va,fe as wa,Me as xa,Oe as ya,ge as za,Te as Aa,Ie as Ba,Fe as Ca,We as Da,He as Ea,_e as Fa,Je as Ga,we as Ha,be as Ia,Ae as Ja,xe as Ka,Ve as La,ke as Ma,Ne as Na,Ge as Oa,Ye as Pa,Ue as Qa,Ke as Ra,Le as Sa,Ze as Ta,ze as Ua,Xe as Va,$e as Wa,et as Xa,tt as Ya,ot as Za,rt as _a,nt as $a,it as ab,at as bb,Dt as cb,mt as db,ct as eb,lt as fb,pt as gb,ut as hb,st as ib};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as d,k as v,l as V,m as y,o as D,p as S,q as B,s as b}from"./chunk-XNHVRFAK.js";import{c as k}from"./chunk-CM5YRNBJ.js";import{c as h,d as _,h as u,i as T,j as C}from"./chunk-7WRQ2UAN.js";import{Color as $,Group as nt,Sprite as st,SpriteMaterial as rt,CanvasTexture as U,LinearFilter as E,Vector2 as ot,ClampToEdgeWrapping as H}from"three";import{MeshStandardMaterial as K,MeshBasicMaterial as tt,MeshPhongMaterial as et}from"three";function it(i){return i&&typeof i.getDebugInfo=="function"}var c=class{entity;constructor(t){this.entity=t}getPositionString(){if(this.entity.mesh){let{x:r,y:s,z:o}=this.entity.mesh.position;return`${r.toFixed(2)}, ${s.toFixed(2)}, ${o.toFixed(2)}`}let{x:t,y:e,z:n}=this.entity.options.position||{x:0,y:0,z:0};return`${t.toFixed(2)}, ${e.toFixed(2)}, ${n.toFixed(2)}`}getRotationString(){if(this.entity.mesh){let{x:s,y:o,z:a}=this.entity.mesh.rotation,p=l=>(l*180/Math.PI).toFixed(1);return`${p(s)}\xB0, ${p(o)}\xB0, ${p(a)}\xB0`}let{x:t,y:e,z:n}=this.entity.options.rotation||{x:0,y:0,z:0},r=s=>(s*180/Math.PI).toFixed(1);return`${r(t)}\xB0, ${r(e)}\xB0, ${r(n)}\xB0`}getMaterialInfo(){if(!this.entity.mesh||!this.entity.mesh.material)return{type:"none"};let t=Array.isArray(this.entity.mesh.material)?this.entity.mesh.material[0]:this.entity.mesh.material,e={type:t.type};return(t instanceof K||t instanceof tt||t instanceof et)&&(e.color=`#${t.color.getHexString()}`,e.opacity=t.opacity,e.transparent=t.transparent),"roughness"in t&&(e.roughness=t.roughness),"metalness"in t&&(e.metalness=t.metalness),e}getPhysicsInfo(){if(!this.entity.body)return null;let t={type:this.entity.body.bodyType(),mass:this.entity.body.mass(),isEnabled:this.entity.body.isEnabled(),isSleeping:this.entity.body.isSleeping()},e=this.entity.body.linvel();return t.velocity=`${e.x.toFixed(2)}, ${e.y.toFixed(2)}, ${e.z.toFixed(2)}`,t}buildDebugInfo(){let t={name:this.entity.name||this.entity.uuid,uuid:this.entity.uuid,position:this.getPositionString(),rotation:this.getRotationString(),material:this.getMaterialInfo()},e=this.getPhysicsInfo();if(e&&(t.physics=e),it(this.entity)){let n=this.entity.getDebugInfo();return{...t,...n}}return t}};var f={position:void 0,text:"",fontFamily:'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',fontSize:18,fontColor:"#FFFFFF",backgroundColor:null,padding:4,stickToViewport:!0,screenPosition:new ot(24,24),zDistance:1},O=class extends b{createEntity(t){return new g(t)}},at=Symbol("Text"),g=class i extends y{static type=at;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=d(f,t),this.options.screenPosition=T(this.options.screenPosition,f.screenPosition),this.prependSetup(this.textSetup.bind(this)),this.prependUpdate(this.textUpdate.bind(this)),this.onCleanup(this.textDestroy.bind(this))}create(){return this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._lastCanvasW=0,this._lastCanvasH=0,this.group=new nt,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new U(this._canvas),this._texture.minFilter=E,this._texture.magFilter=E;let t=new rt({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new st(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,n,r){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${n}`;let s=this._ctx.measureText(t),o=Math.ceil(s.width),a=Math.ceil(e*1.4),p=Math.max(2,o+r*2),l=Math.max(2,a+r*2),w=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:w}}drawCenteredText(t,e,n){!this._canvas||!this._ctx||(this._ctx.font=`${e}px ${n}`,this._ctx.textAlign="center",this._ctx.textBaseline="middle",this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this.options.backgroundColor&&(this._ctx.fillStyle=this.toCssColor(this.options.backgroundColor),this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height)),this._ctx.fillStyle=this.toCssColor(this.options.fontColor??"#FFFFFF"),this._ctx.fillText(t,this._canvas.width/2,this._canvas.height/2))}updateTexture(t){!this._texture||!this._canvas||(t&&(this._texture.dispose(),this._texture=new U(this._canvas),this._texture.minFilter=E,this._texture.magFilter=E,this._texture.wrapS=H,this._texture.wrapT=H),this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0))}redrawText(t){if(!this._canvas||!this._ctx)return;let e=this.options.fontSize??18,n=this.options.fontFamily??f.fontFamily,r=this.options.padding??4,{sizeChanged:s}=this.measureAndResizeCanvas(t,e,n,r);this.drawCenteredText(t,e,n),this.updateTexture(!!s),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof $?t:new $(t)).getHexString()}`}textSetup(t){this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}textUpdate(t){this._sprite&&this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}getResolution(){return{width:this._cameraRef?.screenResolution.x??1,height:this._cameraRef?.screenResolution.y??1}}getScreenPixels(t,e,n){let r=t.x>=0&&t.x<=1,s=t.y>=0&&t.y<=1;return{px:r?t.x*e:t.x,py:s?t.y*n:t.y}}computeWorldExtents(t,e){let n=1,r=1;if(t.isPerspectiveCamera){let s=t,o=Math.tan(s.fov*Math.PI/180/2)*e;n=o*s.aspect,r=o}else if(t.isOrthographicCamera){let s=t;n=(s.right-s.left)/2,r=(s.top-s.bottom)/2}return{worldHalfW:n,worldHalfH:r}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let r=t*2/e,s=this._canvas.height,o=Math.max(1e-4,s*r),a=this._canvas.width/this._canvas.height,p=o*a;this._sprite.scale.set(p,o,1)}updateWorldSpriteScale(){if(!this._canvas||!this._sprite)return;let t=this._canvas.width/Math.max(1,this._canvas.height),e=Math.max(1,this.options.fontSize??18),n=Math.max(.25,e/32),r=n*t;this._sprite.scale.set(r,n,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:n}=this.getResolution(),r=T(this.options.screenPosition,f.screenPosition),{px:s,py:o}=this.getScreenPixels(r,e,n),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:p,worldHalfH:l}=this.computeWorldExtents(t,a),w=s/e*2-1,Q=1-o/n*2,q=w*p,J=Q*l;this.group?.position.set(q,J,-a),this.updateSpriteScale(l,n)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type),text:this.options.text??"",sticky:this.options.stickToViewport}}textDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null}};function I(...i){return S({args:i,defaultConfig:{...f},EntityClass:g,BuilderClass:O,entityType:g.type,cloneFactory:t=>I(t??{})})}import{Euler as pt,Group as lt,Quaternion as ct,Vector3 as mt}from"three";import{TextureLoader as ht,SpriteMaterial as ut,Sprite as dt,SRGBColorSpace as yt}from"three";var W={...v,size:new mt(1,1,1),images:[],animations:[]},R=class extends B{collider(t){let e=C(t.collisionSize,t.size??_);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},F=class extends b{createEntity(t){return new x(t)}},ft=Symbol("Sprite"),x=class i extends y{static type=ft;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;constructor(t){super(),this.options=d(W,t),this.prependSetup(this.spriteSetup.bind(this)),this.prependUpdate(this.spriteUpdate.bind(this)),this.onCleanup(this.spriteDestroy.bind(this))}create(){return this.sprites=[],this.spriteMap.clear(),this.animations.clear(),this.currentAnimation=null,this.currentAnimationFrame="",this.currentAnimationIndex=0,this.currentAnimationTime=0,this.group=void 0,this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new ht,n=C(this.options.size,_);t.forEach((r,s)=>{let o=e.load(r.file);o.colorSpace=yt,o.anisotropy=k;let a=new ut({map:o,transparent:!0}),p=new dt(a);p.position.normalize(),p.scale.set(n.x,n.y,n.z),p.visible=s===0,this.sprites.push(p),this.spriteMap.set(r.name,s)}),this.group=new lt,this.group.add(...this.sprites)}createAnimations(t){t.forEach(e=>{let{name:n,frames:r,loop:s=!1,speed:o=1}=e,a={frames:r.map((p,l)=>({key:p,index:l,time:(typeof o=="number"?o:o[l])*(l+1),duration:typeof o=="number"?o:o[l]})),loop:s};this.animations.set(n,a)})}setSprite(t){let n=this.spriteMap.get(t)??0;this.currentSpriteIndex=n,this.sprites.forEach((r,s)=>{r.visible=this.currentSpriteIndex===s})}setAnimation(t,e){let n=this.animations.get(t);if(!n)return;let{loop:r,frames:s}=n,o=s[this.currentAnimationIndex];t===this.currentAnimation?(this.currentAnimationFrame=o.key,this.currentAnimationTime+=e,this.setSprite(this.currentAnimationFrame)):this.currentAnimation=t,this.currentAnimationTime>o.time&&this.currentAnimationIndex++,this.currentAnimationIndex>=s.length&&(r?(this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime=s[this.currentAnimationIndex].time)}getCurrentRotationQuaternion(){return this.transformStore?.dirty.rotation?this.transformStore.rotation:this.body?.rotation?.()??null}syncSpriteMaterials(){let t=this.getCurrentRotationQuaternion();this.sprites.forEach(e=>{if(e.material&&t){let r=new ct(t.x,t.y,t.z,t.w),s=new pt().setFromQuaternion(r,"XYZ");e.material.rotation=s.z}let n=C(this.options.size,_);e.scale.set(n.x,n.y,n.z)})}spriteSetup(t){this.syncSpriteMaterials()}spriteUpdate(t){this.syncSpriteMaterials()}spriteDestroy(t){this.sprites.forEach(e=>{e.removeFromParent()}),this.group?.remove(...this.sprites),this.group?.removeFromParent()}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type)}}};function P(...i){return S({args:i,defaultConfig:W,EntityClass:x,BuilderClass:F,CollisionBuilderClass:R,entityType:x.type,cloneFactory:t=>P(t??{})})}import{Color as X,Group as xt}from"three";import{Line2NodeMaterial as _t}from"three/webgpu";import{Line2 as Ct}from"three/addons/lines/webgpu/Line2.js";import{Color as N}from"three";import{LineGeometry as gt}from"three/addons/lines/LineGeometry.js";function z(i){let t=[];for(let e of i){let{x:n,y:r,z:s}=u(e,h);t.push(n,r,s)}return t}function L(i,t,e){if(!i||i.length===0)return;let n=[],r=new N(e);for(let s=0;s<t;s++){let o=i[s]??i[i.length-1]??e,a=new N(o??r);n.push(a.r,a.g,a.b)}return n}function Y(i){let t=new gt,e=z(i.points);t.setPositions(e);let n=L(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var m={...v,points:[{x:0,y:0,z:0},{x:1,y:0,z:0}],linewidth:1,worldUnits:!0,alphaToCoverage:!1,opacity:1,transparent:!1,dashed:!1,dashSize:1,gapSize:1,pickThreshold:0},vt=Symbol("Line");function M(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function j(i){return i instanceof X?i.clone():new X(i??"#ffffff")}function St(i){let t=!!i.colors?.length,e=new _t({color:j(i.color).getHex(),linewidth:i.linewidth??m.linewidth,worldUnits:i.worldUnits??m.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??m.dashSize,gapSize:i.gapSize??m.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function bt(i){return!i.point||!i.pointOnLine||i.faceIndex==null?null:{point:i.point.clone(),pointOnLine:i.pointOnLine.clone(),faceIndex:i.faceIndex,distance:i.distance}}function Et(i,t,e={}){let n=t.getLineObject();if(!n)return null;let r=e.threshold??t.options.pickThreshold??0,s=i.params.Line2??{threshold:0};s.threshold=r,i.params.Line2=s;let a=i.intersectObject(n,!1)[0];return a?bt(a):null}var Z=class i extends y{static type=vt;_line=null;_geometry=null;_material=null;constructor(t){super();let e=d(m,t);e.points=M(e.points,"ZylemLine").map(n=>u(n,h)),this.options=e}create(){return this.disposeLineResources(),this.group=new xt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(M(t,"setPoints"),this.options.points=t.map(r=>u(r,h)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(z(this.options.points));let n=L(this.options.colors,this.options.points.length,j(this.options.color));return n&&this._geometry.setColors(n),this._material.vertexColors=!!this.options.colors?.length,this.options.dashed&&this._line.computeLineDistances(),this._geometry.computeBoundingBox(),this._geometry.computeBoundingSphere(),this}getLineObject(){return this._line}pickFromRaycaster(t,e={}){return Et(t,this,e)}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??m.linewidth,worldUnits:this.options.worldUnits??m.worldUnits}}rebuildLine(){this._geometry=Y({points:this.options.points,colors:this.options.colors}),this._material=St(this.options),this._line=new Ct(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=u(this.options.position,h);this.group.position.set(t.x,t.y,t.z)}_cleanup(t){this.disposeLineResources(),super._cleanup(t)}disposeLineResources(){this._line?.removeFromParent(),this._geometry?.dispose(),this._material?.dispose(),this._line=null,this._geometry=null,this._material=null}};function G(...i){let t=V(i,m);M(t.points,"createLine");let e=new Z(t);return D(e,n=>G(n??{}))}var A={registry:new Map,register(i,t){this.registry.set(i,t)},createFromBlueprint(i){let t=this.registry.get(i.type);if(!t)throw new Error(`Unknown entity type: ${i.type}`);let e={...i.data,position:i.position?{x:i.position[0],y:i.position[1],z:0}:void 0,name:i.id};return t(e)}};A.register("text",i=>I(i));A.register("sprite",i=>P(i));A.register("line",i=>G(i));function Ce(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{c as a,at as b,g as c,I as d,ft as e,x as f,P as g,vt as h,Et as i,Z as j,G as k,A as l,Ce as m};
|