@zylem/game-lib 0.8.8 → 0.9.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.
Files changed (95) hide show
  1. package/README.md +7 -1
  2. package/dist/actions.d.ts +2 -2
  3. package/dist/actions.js +1 -1
  4. package/dist/api/game-lib.api.json +35786 -18973
  5. package/dist/api/game-lib.api.md +1209 -13
  6. package/dist/api/game-lib.d.ts +1609 -7
  7. package/dist/api/game-lib.typedoc.json +220861 -97409
  8. package/dist/audio.d.ts +193 -1
  9. package/dist/audio.js +1 -1
  10. package/dist/behavior.js +1 -1
  11. package/dist/bridge.d.ts +46 -6
  12. package/dist/bridge.js +1 -1
  13. package/dist/catalog.d.ts +91 -3
  14. package/dist/catalog.js +1 -1
  15. package/dist/chunk-2HSR5XDQ.js +1 -0
  16. package/dist/chunk-2MHB4X6B.js +24 -0
  17. package/dist/chunk-2PFNNGTV.js +1 -0
  18. package/dist/chunk-2XMG3NJS.js +1 -0
  19. package/dist/chunk-4CZZZCFB.js +9 -0
  20. package/dist/{chunk-7NYP4YAG.js → chunk-6FGXC4T6.js} +1 -1
  21. package/dist/chunk-6XFXPIVB.js +1 -0
  22. package/dist/{chunk-CBUQBP2U.js → chunk-BQRMYLYD.js} +1 -1
  23. package/dist/chunk-FZNEWOC5.js +1 -0
  24. package/dist/chunk-GPCSX3M6.js +1 -0
  25. package/dist/chunk-HISTSRAL.js +1 -0
  26. package/dist/chunk-K3NNXZIJ.js +1 -0
  27. package/dist/chunk-KP6DLLJO.js +1 -0
  28. package/dist/{chunk-JNFFTNMH.js → chunk-KSEP7AUF.js} +1 -1
  29. package/dist/{chunk-YOVE25NW.js → chunk-LI43BZQN.js} +1 -1
  30. package/dist/chunk-LSFWI46T.js +1 -0
  31. package/dist/chunk-NVVLLWIM.js +1 -0
  32. package/dist/chunk-QGIYILYI.js +1 -0
  33. package/dist/chunk-STVEILJJ.js +1 -0
  34. package/dist/chunk-UUOPT2N4.js +1 -0
  35. package/dist/chunk-VMXSE3EC.js +0 -0
  36. package/dist/chunk-VSFULLND.js +1 -0
  37. package/dist/chunk-VUJXR5K5.js +1 -0
  38. package/dist/chunk-WOT6VMZA.js +1 -0
  39. package/dist/chunk-YNX3Q3CL.js +1 -0
  40. package/dist/chunk-YQS7CGXE.js +1 -0
  41. package/dist/chunk-ZZO4CKRU.js +1 -0
  42. package/dist/cinematics.d.ts +279 -0
  43. package/dist/cinematics.js +1 -0
  44. package/dist/core.d.ts +13 -10
  45. package/dist/core.js +1 -1
  46. package/dist/cutscene-definition-C479fkei.d.ts +509 -0
  47. package/dist/{debug-state-CpnNRUFh.d.ts → debug-state-Cg3f5FB6.d.ts} +1 -1
  48. package/dist/debug.d.ts +3 -2
  49. package/dist/debug.js +1 -1
  50. package/dist/{entity-XZNGBeca.d.ts → entity-XqvuWgPm.d.ts} +54 -0
  51. package/dist/{entity-type-map-CkkFMSrL.d.ts → entity-type-map-CrsrKT8c.d.ts} +13 -4
  52. package/dist/entity.d.ts +4 -3
  53. package/dist/entity.js +1 -1
  54. package/dist/events.js +1 -1
  55. package/dist/game-9PjI5z2p.d.ts +652 -0
  56. package/dist/game-default-WBKQCEDJ.js +1 -0
  57. package/dist/globals.js +1 -1
  58. package/dist/graphics.d.ts +1 -1
  59. package/dist/graphics.js +1 -1
  60. package/dist/input-ui.js +1 -1
  61. package/dist/input.js +1 -1
  62. package/dist/public.d.ts +14 -8
  63. package/dist/public.js +1 -1
  64. package/dist/runtime.js +1 -1
  65. package/dist/schema/cutscene.schema.json +782 -0
  66. package/dist/schema/entity.schema.json +24 -24
  67. package/dist/schema/game-config.schema.json +10 -10
  68. package/dist/schema/song.schema.json +430 -0
  69. package/dist/schema/stage.schema.json +29 -29
  70. package/dist/schema.d.ts +2 -0
  71. package/dist/schema.js +1 -1
  72. package/dist/selection-bounds-BKmSo9aG.d.ts +50 -0
  73. package/dist/song-definition-rEKksP0B.d.ts +263 -0
  74. package/dist/song-player-7QPLFLAS.js +1 -0
  75. package/dist/{game-BPOr7zTB.d.ts → stage-BuGkjZnr.d.ts} +90 -644
  76. package/dist/web-components.d.ts +7 -5
  77. package/dist/web-components.js +1 -1
  78. package/dist/{zylem-camera-DZTpPOiD.d.ts → zylem-camera-Baf5vH8Z.d.ts} +8 -0
  79. package/package.json +25 -16
  80. package/dist/chunk-34MYRTRP.js +0 -9
  81. package/dist/chunk-AE3CTVHY.js +0 -1
  82. package/dist/chunk-BMRFDDMR.js +0 -1
  83. package/dist/chunk-EVMLNMGU.js +0 -1
  84. package/dist/chunk-F5LROYZL.js +0 -24
  85. package/dist/chunk-GHJQ2HKI.js +0 -1
  86. package/dist/chunk-HNCTOJP7.js +0 -1
  87. package/dist/chunk-IBJLPJLE.js +0 -1
  88. package/dist/chunk-MXO4VGDB.js +0 -1
  89. package/dist/chunk-QDQ4QMAI.js +0 -1
  90. package/dist/chunk-SAQA4SXW.js +0 -1
  91. package/dist/chunk-XK63E4SX.js +0 -1
  92. package/dist/chunk-ZRT3ZQVH.js +0 -1
  93. package/dist/chunk-ZTYNZ2N2.js +0 -1
  94. package/dist/game-default-7HCJJF5S.js +0 -1
  95. /package/dist/{chunk-MSCVL5OK.js → chunk-ELQN62PQ.js} +0 -0
@@ -0,0 +1 @@
1
+ import{b as R}from"./chunk-7GYFZKK7.js";import{b as K}from"./chunk-QGIYILYI.js";import{Vector3 as L}from"three";var I="cutscene",w=class{priority=1e3;enabled=!1;target=null;smoothed=null;damping=0;setPose(t,e=0){this.target=t,this.damping=e,this.enabled=t!==null,t||(this.smoothed=null)}snap(){this.smoothed=null}onDetach(){this.smoothed=null}update(t,e){let i=this.target;if(!i)return e;let a=new L(i.position.x,i.position.y,i.position.z),s=new L(i.lookAt.x,i.lookAt.y,i.lookAt.z);if(this.damping>0&&this.smoothed){let r=1-Math.pow(this.damping,t.dt*60);this.smoothed.position.lerp(a,r),this.smoothed.lookAt.lerp(s,r)}else this.smoothed={position:a.clone(),lookAt:s.clone()};return{...e,position:this.smoothed.position.clone(),lookAt:this.smoothed.lookAt.clone(),fov:i.fov}}};import{CatmullRomCurve3 as oe,Vector3 as re}from"three";function z(n,t){let e=Math.min(1,Math.max(0,t));switch(n){case"easeIn":return e*e;case"easeOut":return 1-(1-e)*(1-e);case"easeInOut":return e<.5?2*e*e:1-(-2*e+2)**2/2;default:return e}}function x(n,t,e){return{x:n.x+(t.x-n.x)*e,y:n.y+(t.y-n.y)*e,z:n.z+(t.z-n.z)*e}}function ae(n,t,e){return{position:x(n.position,t.position,e),lookAt:x(n.lookAt,t.lookAt,e),fov:n.fov+(t.fov-n.fov)*e}}function se(n,t){let e;for(let i of n)t>=i.start&&t<i.end&&(e=i);return e??n[n.length-1]}function le(n,t){let e;for(let i of n)t>=i.start&&t<i.end&&(e=i);return e}function ue(n,t){for(let e of n.tracks){if(e.kind!=="camera")continue;let i=le(e.items,t);if(i)return i}}function ce(n,t){let e;for(let i of n.tracks)if(i.kind==="camera")for(let a of i.items)a.id===t.id||a.end>t.start+1e-6||(!e||a.end>e.end)&&(e=a);return e}var F=new WeakMap;function de(n){let t=JSON.stringify([n.points,n.closed,n.tension]),e=F.get(n);if(e&&e.key===t)return e.curve;let i=new oe(n.points.map(a=>new re(a.x,a.y,a.z)),n.closed,n.tension===.5?"centripetal":"catmullrom",n.tension);return F.set(n,{key:t,curve:i}),i}function q(n,t){if(n.points.length<2)return{...n.points[0]??{x:0,y:0,z:0}};let e=de(n).getPointAt(Math.min(1,Math.max(0,t)));return{x:e.x,y:e.y,z:e.z}}function we(n,t=32){let e=[];for(let i=0;i<=t;i+=1)e.push(q(n,i/t));return e}function M(n,t,e,i,a,s){let r={value:e,time:i},c=!0,u;for(let p of n){let y=t(p);y!==void 0&&(p.time<=a?(c||p.time>=r.time)&&(r={value:y,time:p.time},c=!1):(!u||p.time<u.time)&&(u={value:y,time:p.time,easing:p.easing}))}if(!u)return r.value;let f=u.time-r.time,d=f<=0?1:(a-r.time)/f;return s(r.value,u.value,z(u.easing,d))}function N(n,t,e,i,a){let s={...n.pose.position},r={...n.pose.lookAt},c=n.target?a?.(n.target):void 0;if(n.kind==="dolly"&&n.dollyId){let d=t.dollies.find(p=>p.id===n.dollyId);if(d){let p=e.end-e.start,y=p<=0?1:(i-e.start)/p;s=q(d,z(n.dollyEasing,y))}c&&(r=c)}else if(n.kind==="follow"&&c){let d=n.offset??{x:0,y:3,z:8};s={x:c.x+d.x,y:c.y+d.y,z:c.z+d.z},r=c}let u=[...n.keyframes].sort((d,p)=>d.time-p.time);s=M(u,d=>d.position,s,e.start,i,x),r=M(u,d=>d.lookAt,r,e.start,i,x);let f=M(u,d=>d.fov,n.fov,e.start,i,(d,p,y)=>d+(p-d)*y);return{position:s,lookAt:r,fov:f}}function T(n,t,e){let i=se(n.scenes,t),a=ue(n,t);if(!a)return{scene:i,shot:void 0,camera:void 0,pose:void 0,blend:1};let s=n.cameras.find(u=>u.id===a.cameraId);if(!s)return{scene:i,shot:a,camera:void 0,pose:void 0,blend:1};let r=N(s,n,a,t,e),c=1;if(a.blend.duration>0&&t<a.start+a.blend.duration){let u=ce(n,a),f=u?n.cameras.find(d=>d.id===u.cameraId):void 0;if(u&&f){let d=N(f,n,u,Math.min(t,u.end),e);c=z(a.blend.easing,(t-a.start)/a.blend.duration),r=ae(d,r,c)}}return{scene:i,shot:a,camera:s,pose:r,blend:c}}function O(n,t,e){return n.filter(i=>i.time>t&&i.time<=e).sort((i,a)=>i.time-a.time)}function xe(n){return n.tracks.filter(t=>t.kind==="camera")}function _(n){return Math.max(n.duration,...n.scenes.map(t=>t.end))}import{PerspectiveCamera as fe,Vector3 as pe}from"three";var me=1e-6;function J(n,t){let{host:e}=t,i=new w,a=n,s="idle",r=0,c,u,f,d=null,p=.15,y=0,g=0,v=!1,k={time:new Set,state:new Set,scene:new Set,shot:new Set,event:new Set,audio:new Set,complete:new Set,skip:new Set},h=(o,...l)=>{for(let m of k[o])try{m(...l)}catch(V){console.error(`CutscenePlayer: ${o} listener failed`,V)}},S=o=>{s!==o&&(s=o,h("state",o))},$=()=>{let o=e.camera();!o||o===d||(E(),d=o,p=o.pipeline.damping,o.pipeline.damping=1,o.pipeline.addBehavior(I,i))},E=()=>{d&&(d.pipeline.removeBehavior(I),d.pipeline.damping=p,d=null,i.setPose(null))},G=o=>{let l=d?.camera;l&&(l.position.set(o.position.x,o.position.y,o.position.z),l.lookAt(new pe(o.lookAt.x,o.lookAt.y,o.lookAt.z)),l instanceof fe&&(l.fov=o.fov,l.updateProjectionMatrix()))},A=o=>e.entityPosition?.(o),P=(o={})=>{$();let l=T(a,r,A);c=l.pose;let m=l.camera?.kind==="follow"?Math.min(.98,l.camera.damping):0;return i.setPose(c??null,m),o.snap&&(i.snap(),c&&G(c)),l.shot?.id!==f&&(f=l.shot?.id,h("shot",l.shot)),l},X=o=>{let{event:l}=o;try{switch(l.type){case"emit":e.dispatch?.(l.name,l.payload);break;case"playAnimation":e.playAnimation?.(l.entity,l.key);break;case"playSong":e.playSong?.(l.song,{loop:l.loop,volume:0});break;case"stopSong":e.stopSong?.(l.song);break;case"setVariable":e.setVariable?.(l.name,l.value);break;default:break}}catch(m){console.error("CutscenePlayer: event failed",o,m)}h("event",o)},ee=o=>{try{o.kind==="song"?e.playSong?.(o.ref,{loop:o.loop,volume:o.volume}):e.playSfx?.(o.ref,{volume:o.volume,loop:o.loop})}catch(l){console.error("CutscenePlayer: audio failed",o,l)}h("audio",o)},te=(o,l)=>{for(let m of a.tracks)m.kind==="event"?O(m.items,o,l).forEach(X):m.kind==="audio"&&O(m.items,o,l).forEach(ee)},ne=o=>t.transitionShader?.(o),Z=(o,l)=>{if(o?.id===u)return;let m=u;u=o?.id,o&&l.transition&&m!==void 0&&o.transitionIn.type!=="cut"&&e.beginTransition?.(o.transitionIn,ne(o.transitionIn.type)),h("scene",o)},C=()=>_(a),D=(o,l,m)=>{r=Math.min(Math.max(0,l),C());let V=T(a,r,A).scene;Z(V,{transition:m.transitions}),P({snap:!m.transitions}),m.fireEvents&&te(o,r),h("time",r),r>=C()-me&&s==="playing"&&j()},j=()=>{S("finished"),b(),h("complete")},B=o=>{if(v||s!=="playing")return;let l=g?Math.min(.1,(o-g)/1e3):0;g=o,H.update(l),s==="playing"&&(y=requestAnimationFrame(B))},ie=()=>{t.tick==="manual"||typeof requestAnimationFrame!="function"||(cancelAnimationFrame(y),g=0,y=requestAnimationFrame(B))},b=()=>{typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(y),g=0},H={get definition(){return a},get state(){return s},get time(){return r},get length(){return C()},get pose(){return c},play(o){v||(o!==void 0&&(r=Math.min(Math.max(0,o),C()),u=void 0),s==="finished"&&o===void 0&&(r=0,u=void 0),S("playing"),Z(T(a,r,A).scene,{transition:!1}),P({snap:!0}),h("time",r),ie())},pause(){s==="playing"&&(S("paused"),b())},stop(){b(),r=0,u=void 0,f=void 0,c=void 0,E(),S("idle"),h("time",0)},seek(o){if(v)return;D(r,o,{fireEvents:!!t.fireEventsOnSeek,transitions:!1}),(s==="idle"||s==="finished")&&S("paused")},skip(){return!a.skippable||v?!1:(h("skip"),D(r,C(),{fireEvents:!1,transitions:!1}),s!=="finished"&&j(),!0)},update(o){if(v||s!=="playing")return;let l=o*(t.timeScale??1);if(l<=0){P();return}D(r,r+l,{fireEvents:!0,transitions:!0})},setDefinition(o){a=o,s!=="idle"&&P({snap:s!=="playing"})},on(o,l){return k[o].add(l),()=>k[o].delete(l)},dispose(){if(!v){v=!0,b(),E();for(let o of Object.values(k))o.clear()}}};return H}import{Howl as ye}from"howler";var W=null;function Oe(n){W=n}function he(n){return"wrappedStage"in n?n.wrappedStage:n}function ve(n){let t=n?.group??n?.mesh;if(t)return{x:t.position.x,y:t.position.y,z:t.position.z}}function U(n,t={}){let e=()=>he(n),i=new Map,a=new Set,s=r=>{for(let[c,u]of i)r!==void 0&&c!==r||(u.stop(),u.dispose(),i.delete(c))};return{camera:()=>e()?.cameraRef??null,entityPosition:r=>ve(e()?.getEntityByName(r)),playAnimation:(r,c)=>{e()?.getEntityByName(r)?.playAnimation?.({key:c})},dispatch:(r,c)=>{t.onEvent?.(r,c),e()?.wrapperRef?.dispatch?.(r,c)},setVariable:(r,c)=>{let u=e()?.state;u&&(u.variables[r]=c)},playSong:(r,{loop:c,volume:u})=>{t.resolveSong&&(async()=>{let f=await t.resolveSong(r);if(!f)return;let d=await import("./song-player-7QPLFLAS.js");s(r);let p=d.createSongPlayer({...f,loop:c?{enabled:!0,start:0,end:K(f)}:f.loop,masterVolume:(f.masterVolume??0)+u});i.set(r,p),await p.play()})().catch(f=>console.error("Cutscene: could not play song",r,f))},stopSong:s,playSfx:(r,{volume:c,loop:u})=>{let f=new ye({src:[r],volume:Math.pow(10,c/20),loop:u,html5:!0});a.add(f),f.once("end",()=>{u||a.delete(f)}),f.play()},beginTransition:(r,c)=>{let u=e(),f=u?.rendererManager,d=u?.scene?.scene,p=u?.cameraRef?.camera;!f||!d||!p||f.beginInStageTransition(R({duration:r.duration,easing:r.easing==="linear"?"linear":"easeInOut",shader:c??t.transitionShader?.(r.type)??W?.(r.type)}),d,p)}}}import{Matrix4 as Y,PerspectiveCamera as ge,Vector3 as Se}from"three";var Q=class{constructor(t,e,i={},a){this.getStage=t;this.publish=e;this.hostOptions=i;this.publishView=a}player=null;lastStatus=null;pending=null;viewInverse=new Y;viewProjection=new Y;lastView=null;get active(){return this.player!==null}stageReady(){let t=this.pending;t&&(this.pending=null,this.load(t))}load(t){let e=t.definition;if(!Array.isArray(e?.tracks)||!Array.isArray(e?.cameras)){console.warn("CutscenePreview: ignoring malformed cutscene definition");return}if(this.player&&this.player.definition.id===e.id)this.player.setDefinition(e);else{this.unload();let i=this.getStage();if(!i){this.pending=t;return}let a=J(e,{host:U(i,this.hostOptions),fireEventsOnSeek:!1});a.on("time",()=>this.report()),a.on("state",()=>this.report()),a.on("shot",()=>this.report()),a.on("scene",()=>this.report()),this.player=a}t.time!==void 0&&this.player.seek(t.time),t.autoplay&&this.player.play(t.time),this.report(!0)}play(t){this.player?.play(t)}pause(){this.player?.pause()}stop(){this.player?.stop()}seek(t){this.player?.seek(t)}releaseStage(){this.player&&(this.player.dispose(),this.player=null,this.lastView=null,this.report(!0))}frame(){if(!this.player||!this.publishView)return;let t=this.getStage(),e=t?.cameraRef?.camera,i=t?.rendererManager?.getDomElement()??t?.cameraRef?.renderer?.domElement;if(!e||!i)return;e.updateMatrixWorld(),this.viewInverse.copy(e.matrixWorld).invert(),this.viewProjection.multiplyMatrices(e.projectionMatrix,this.viewInverse);let a=i.getBoundingClientRect(),s={viewProjection:this.viewProjection.toArray(),inverseViewProjection:[],viewport:{x:Math.round(a.left),y:Math.round(a.top),width:Math.round(a.width),height:Math.round(a.height)}},r=JSON.stringify(s);r!==this.lastView&&(this.lastView=r,s.inverseViewProjection=this.viewProjection.clone().invert().toArray(),this.publishView(s))}unload(){this.pending=null,this.releaseStage()}cameraPose(){let t=this.getStage()?.cameraRef?.camera;if(!t)return null;let e=new Se(0,0,-1).applyQuaternion(t.quaternion),i=t.position.clone().add(e.multiplyScalar(10));return{position:{x:t.position.x,y:t.position.y,z:t.position.z},lookAt:{x:i.x,y:i.y,z:i.z},fov:t instanceof ge?t.fov:void 0}}report(t=!1){let e=this.player,i=e?{cutsceneId:e.definition.id,state:e.state,time:Math.round(e.time*1e3)/1e3,sceneId:null,shotId:null}:{cutsceneId:null,state:"idle",time:0,sceneId:null,shotId:null};if(e){let s=Ce(e);i.sceneId=s.sceneId,i.shotId=s.shotId}let a=JSON.stringify(i);!t&&a===this.lastStatus||(this.lastStatus=a,this.publish(i))}};function Ce(n){let{definition:t,time:e}=n,i=null;for(let s of t.scenes)e>=s.start&&e<s.end&&(i=s.id);let a=null;for(let s of t.tracks)if(!(s.kind!=="camera"||a))for(let r of s.items)e>=r.start&&e<r.end&&(a=r.id);return{sceneId:i,shotId:a}}export{I as a,w as b,z as c,x as d,ae as e,se as f,le as g,ue as h,ce as i,q as j,we as k,N as l,T as m,O as n,xe as o,_ as p,J as q,Oe as r,U as s,Q as t};
@@ -0,0 +1,9 @@
1
+ import{d as s,h as o,j as a}from"./chunk-GPCSX3M6.js";import{announceBridgeReady as h}from"@zylem/bridge";var n=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().then(()=>{this._game===e&&h(this)})}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&&(s.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",n);export{n as a};
@@ -16,4 +16,4 @@ void main() {
16
16
 
17
17
  gl_FragColor = texel;
18
18
  }
19
- `,O={vertex:C,fragment:D};import{Color as F,RepeatWrapping as v,SRGBColorSpace as te}from"three";import{MeshBasicNodeMaterial as re,MeshStandardNodeMaterial as P}from"three/webgpu";function G(s){let e=Object.keys(s).sort().reduce((t,r)=>(t[r]=s[r],t),{});return JSON.stringify(e)}function E(s){let e=0;for(let t=0;t<s.length;t++)e=Math.imul(31,e)+s.charCodeAt(t)|0;return e.toString(36)}import{LoadingManager as ee,Cache as k}from"three";import{TextureLoader as X,RepeatWrapping as B}from"three";var b=16,L=class{loader;constructor(){this.loader=new X}isSupported(e){let t=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","bmp","tga"].includes(t||"")}async load(e,t){let r=await this.loader.loadAsync(e,a=>{t?.onProgress&&a.lengthComputable&&t.onProgress(a.loaded/a.total)});return t?.repeat&&r.repeat.copy(h(t.repeat,p)),r.wrapS=t?.wrapS??B,r.wrapT=t?.wrapT??B,t?.colorSpace!==void 0&&(r.colorSpace=t.colorSpace),r.anisotropy=t?.anisotropy??b,r}clone(e){let t=e.clone();return t.anisotropy=e.anisotropy||b,t.needsUpdate=!0,t}};import{GLTFLoader as J}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as K}from"three/addons/loaders/DRACOLoader.js";import{KTX2Loader as Z}from"three/addons/loaders/KTX2Loader.js";import{MeshoptDecoder as $}from"three/addons/libs/meshopt_decoder.module.js";import{Mesh as j}from"three";import{clone as W}from"three/addons/utils/SkeletonUtils.js";function u(s){let e=W(s),t=[],r=[];s.traverse(a=>t.push(a)),e.traverse(a=>r.push(a));for(let a=0;a<t.length;a++){let o=t[a],n=r[a];!(o instanceof j)||!(n instanceof j)||(o.geometry?.clone&&(n.geometry=o.geometry.clone()),o.material&&(n.material=Array.isArray(o.material)?o.material.map(i=>i.clone()):o.material.clone()))}return e}function I(s){let e=s.indexOf("?"),t=s.indexOf("#"),r=[e,t].filter(a=>a>=0).reduce((a,o)=>Math.min(a,o),s.length);return s.slice(0,r)}function c(s){let e=I(s),t=e.lastIndexOf("/"),r=t>=0?e.slice(t+1):e,a=r.lastIndexOf(".");return a<0||a===r.length-1?null:r.slice(a+1).toLowerCase()}var V=["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"],H="https://www.gstatic.com/draco/v1/decoders/",g=class{loader;dracoLoader;ktx2Loader=null;meshoptEnabled=!1;configuredRenderer=null;ktx2TranscoderPath=null;constructor(){this.dracoLoader=new K,this.dracoLoader.setDecoderPath(H),this.loader=new J,this.loader.setDRACOLoader(this.dracoLoader),this.setMeshoptEnabled(!0)}isSupported(e){let t=c(e);return["gltf","glb"].includes(t||"")}async configureRuntime({meshopt:e=!0,ktx2TranscoderPath:t,renderer:r=null}={}){this.setMeshoptEnabled(e!==!1);let a=this.normalizeTranscoderPath(t);if(!a){this.clearKTX2Loader();return}if(!r)throw new Error("GLTFLoaderAdapter.configureRuntime requires a renderer when ktx2TranscoderPath is provided.");(!this.ktx2Loader||this.ktx2TranscoderPath!==a)&&(this.clearKTX2Loader(),this.ktx2Loader=new Z,this.ktx2Loader.setTranscoderPath(a),this.loader.setKTX2Loader(this.ktx2Loader),this.ktx2TranscoderPath=a,this.configuredRenderer=null),!(!this.ktx2Loader||this.configuredRenderer===r)&&(this.ktx2Loader.detectSupport(r),this.configuredRenderer=r)}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=await this.loader.parseAsync(a,e);return this.applyTextureAnisotropy(o.scene),{object:o.scene,animations:o.animations,gltf:o}}catch(r){return console.error(`Async fetch GLTF load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{this.applyTextureAnisotropy(o.scene),r({object:o.scene,animations:o.animations,gltf:o})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone()),gltf:e.gltf}}applyTextureAnisotropy(e){e.traverse(t=>{let r=t.material;if(!r)return;let a=Array.isArray(r)?r:[r];for(let o of a)for(let n of V){let i=o[n];if(i&&i.isTexture){let d=i;d.anisotropy=b,d.needsUpdate=!0}}})}setMeshoptEnabled(e){if(e){if(this.meshoptEnabled)return;this.loader.setMeshoptDecoder($),this.meshoptEnabled=!0;return}this.meshoptEnabled&&(this.loader.setMeshoptDecoder(void 0),this.meshoptEnabled=!1)}clearKTX2Loader(){this.ktx2Loader&&(this.ktx2Loader.dispose(),this.ktx2Loader=null),this.loader.setKTX2Loader(void 0),this.configuredRenderer=null,this.ktx2TranscoderPath=null}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}};import{FBXLoader as _}from"three/addons/loaders/FBXLoader.js";var T=class{loader;constructor(){this.loader=new _}isSupported(e){return c(e)==="fbx"}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=this.loader.parse(a,e);return{object:o,animations:o.animations||[]}}catch(r){return console.error(`Async fetch FBX load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:o.animations||[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone())}}};import{OBJLoader as z}from"three/addons/loaders/OBJLoader.js";import{MTLLoader as Y}from"three/addons/loaders/MTLLoader.js";var y=class{loader;mtlLoader;constructor(){this.loader=new z,this.mtlLoader=new Y}isSupported(e){return c(e)==="obj"}async load(e,t){return t?.mtlPath&&await this.loadMTL(t.mtlPath),new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}async loadMTL(e){return new Promise((t,r)=>{this.mtlLoader.load(e,a=>{a.preload(),this.loader.setMaterials(a),t()},void 0,a=>r(a))})}clone(e){return{object:u(e.object),animations:[]}}};import{AudioLoader as q}from"three";var x=class{loader;constructor(){this.loader=new q}isSupported(e){let t=c(e);return["mp3","ogg","wav","flac","aac","m4a"].includes(t||"")}async load(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>r(o),o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}};import{FileLoader as Q}from"three";var m=class{loader;constructor(){this.loader=new Q}isSupported(e){return!0}async load(e,t){let r=t?.responseType??"text";return this.loader.setResponseType(r),new Promise((a,o)=>{this.loader.load(e,n=>a(n),n=>{t?.onProgress&&n.lengthComputable&&t.onProgress(n.loaded/n.total)},n=>o(n))})}},M=class{fileLoader;constructor(){this.fileLoader=new m}isSupported(e){return c(e)==="json"}async load(e,t){return await this.fileLoader.load(e,{...t,responseType:"json"})}};var w=class s{static instance=null;textureCache=new Map;modelCache=new Map;audioCache=new Map;fileCache=new Map;jsonCache=new Map;pendingGLTFRuntimePath=null;pendingGLTFRuntimePromise=null;pendingGLTFRuntimeResolve=null;textureLoader;gltfLoader;fbxLoader;objLoader;audioLoader;fileLoader;jsonLoader;loadingManager;events;stats={texturesLoaded:0,modelsLoaded:0,audioLoaded:0,filesLoaded:0,cacheHits:0,cacheMisses:0};constructor(){this.textureLoader=new L,this.gltfLoader=new g,this.fbxLoader=new T,this.objLoader=new y,this.audioLoader=new x,this.fileLoader=new m,this.jsonLoader=new M,this.loadingManager=new ee,this.loadingManager.onProgress=(e,t,r)=>{this.events.emit("batch:progress",{loaded:t,total:r})},this.events=R(),k.enabled=!0}static getInstance(){return s.instance||(s.instance=new s),s.instance}static resetInstance(){s.instance&&(s.instance.clearCache(),s.instance=null)}async loadTexture(e,t){return this.loadWithCache(e,"texture",this.textureCache,()=>this.textureLoader.load(e,t),t,r=>{if(!t?.clone)return r;let a=this.textureLoader.clone(r);return t.repeat&&a.repeat.copy(h(t.repeat,p)),t.wrapS!==void 0&&(a.wrapS=t.wrapS),t.wrapT!==void 0&&(a.wrapT=t.wrapT),a})}async loadGLTF(e,t){return await this.waitForPreparedGLTFRuntime(),this.loadWithCache(e,"gltf",this.modelCache,()=>this.gltfLoader.load(e,t),t,r=>t?.clone?this.gltfLoader.clone(r):r)}prepareGLTFRuntime(e){let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&(this.pendingGLTFRuntimePath===t&&this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePath=t,this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePromise=new Promise(r=>{this.pendingGLTFRuntimeResolve=r}))))}async configureGLTFRuntime(e){await this.gltfLoader.configureRuntime(e);let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&e?.renderer&&this.resolvePreparedGLTFRuntime(t)}async loadFBX(e,t){return this.loadWithCache(e,"fbx",this.modelCache,()=>this.fbxLoader.load(e,t),t,r=>t?.clone?this.fbxLoader.clone(r):r)}async loadOBJ(e,t){let r=t?.mtlPath?`${e}:${t.mtlPath}`:e;return this.loadWithCache(r,"obj",this.modelCache,()=>this.objLoader.load(e,t),t,a=>t?.clone?this.objLoader.clone(a):a)}async loadModel(e,t){let r=c(e);switch(r){case"gltf":case"glb":return this.loadGLTF(e,t);case"fbx":return this.loadFBX(e,t);case"obj":return this.loadOBJ(e,t);default:throw new Error(`Unsupported model format: ${r}`)}}async loadAudio(e,t){return this.loadWithCache(e,"audio",this.audioCache,()=>this.audioLoader.load(e,t),t)}async loadFile(e,t){let r=t?.responseType?`${e}:${t.responseType}`:e;return this.loadWithCache(r,"file",this.fileCache,()=>this.fileLoader.load(e,t),t)}async loadJSON(e,t){return this.loadWithCache(e,"json",this.jsonCache,()=>this.jsonLoader.load(e,t),t)}async loadBatch(e){let t=new Map,r=e.map(async a=>{try{let o;switch(a.type){case"texture":o=await this.loadTexture(a.url,a.options);break;case"gltf":o=await this.loadGLTF(a.url,a.options);break;case"fbx":o=await this.loadFBX(a.url,a.options);break;case"obj":o=await this.loadOBJ(a.url,a.options);break;case"audio":o=await this.loadAudio(a.url,a.options);break;case"file":o=await this.loadFile(a.url,a.options);break;case"json":o=await this.loadJSON(a.url,a.options);break;default:throw new Error(`Unknown asset type: ${a.type}`)}t.set(a.url,o)}catch(o){throw this.events.emit("asset:error",{url:a.url,type:a.type,error:o}),o}});return await Promise.all(r),this.events.emit("batch:complete",{urls:e.map(a=>a.url)}),t}async preload(e){await this.loadBatch(e)}isCached(e){return this.textureCache.has(e)||this.modelCache.has(e)||this.audioCache.has(e)||this.fileCache.has(e)||this.jsonCache.has(e)}clearCache(e){e?(this.textureCache.delete(e),this.modelCache.delete(e),this.audioCache.delete(e),this.fileCache.delete(e),this.jsonCache.delete(e)):(this.textureCache.clear(),this.modelCache.clear(),this.audioCache.clear(),this.fileCache.clear(),this.jsonCache.clear(),k.clear(),this.pendingGLTFRuntimePath=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimeResolve=null)}getStats(){return{...this.stats}}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}async loadWithCache(e,t,r,a,o,n){o?.forceReload&&r.delete(e);let i=r.get(e);if(i){this.stats.cacheHits++,this.events.emit("asset:loaded",{url:e,type:t,fromCache:!0});let l=await i.promise;return n?n(l):l}this.stats.cacheMisses++,this.events.emit("asset:loading",{url:e,type:t});let d=a(),f={promise:d,loadedAt:Date.now()};r.set(e,f);try{let l=await d;return f.result=l,this.updateStats(t),this.events.emit("asset:loaded",{url:e,type:t,fromCache:!1}),n?n(l):l}catch(l){throw r.delete(e),this.events.emit("asset:error",{url:e,type:t,error:l}),l}}updateStats(e){switch(e){case"texture":this.stats.texturesLoaded++;break;case"gltf":case"fbx":case"obj":this.stats.modelsLoaded++;break;case"audio":this.stats.audioLoaded++;break;case"file":case"json":this.stats.filesLoaded++;break}}async waitForPreparedGLTFRuntime(){this.pendingGLTFRuntimePromise&&await this.pendingGLTFRuntimePromise}resolvePreparedGLTFRuntime(e){this.pendingGLTFRuntimePath&&this.pendingGLTFRuntimePath!==e||(this.pendingGLTFRuntimeResolve?.(),this.pendingGLTFRuntimeResolve=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimePath=null)}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}},A=w.getInstance();import{uniform as vt,uv as Ot,time as wt,vec3 as At,vec4 as Ft,float as Pt,Fn as St}from"three/tsl";function ae(s){return"colorNode"in s}function N(s){return"fragment"in s&&"vertex"in s}function oe(s){return!!s&&N(s)&&s.vertex===O.vertex&&s.fragment===O.fragment}var U=class s{static sharedMaterialMap=new Map;static clearSharedMaterialCache(){s.sharedMaterialMap.clear()}materials=[];useTSL;constructor(e=!0){this.useTSL=e}trackSharedMaterial(e,t){let r=E(G(e)),a=s.sharedMaterialMap.get(r);if(a){let o=a.geometryMap.get(t);o?a.geometryMap.set(t,o+1):a.geometryMap.set(t,1)}else s.sharedMaterialMap.set(r,{geometryMap:new Map([[t,1]]),material:this.materials[0]})}build(e,t){let{path:r,normalMap:a,repeat:o,color:n,shader:i,opacity:d}=e,f=oe(i),l=!!i&&!f,S=!!r&&(!i||f);S?this.setTexture(r??null,o,!0,d,n):l&&i?ae(i)?this.setTSLShader(i,d):N(i)&&(console.warn("MaterialBuilder: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(n??new F("#ffffff"),!0,d)):r&&this.setTexture(r,o,!0,d,n),n&&!S&&!l&&this.withColor(n,!0,d),this.materials.length===0&&this.setColor(new F("#ffffff"),!0,d),a&&this.materials.length>0&&this.setNormalMap(a,o),this.trackSharedMaterial(e,t)}withColor(e,t=!1,r){return this.setColor(e,t,r),this}withShader(e,t){return this.setShader(e,t),this}withTSLShader(e,t){return this.setTSLShader(e,t),this}applyOpacity(e,t,r=!1){t!==void 0&&(e.opacity=t),e.transparent=r||t!==void 0&&t<1,e.needsUpdate=!0}setTexture(e=null,t=p,r=!0,a,o){if(!e)return;let n=new P;o&&(n.color=o),this.applyOpacity(n,a),this.materials.push(n),A.loadTexture(e,{clone:!0,repeat:h(t,p),colorSpace:te}).then(i=>{i.wrapS=v,i.wrapT=v,n.map=i,n.needsUpdate=!0})}setNormalMap(e,t=p){let r=this.materials[this.materials.length-1];r&&A.loadTexture(e,{clone:!0,repeat:h(t,p)}).then(a=>{a.wrapS=v,a.wrapT=v,r instanceof P&&(r.normalMap=a,r.needsUpdate=!0)})}setColor(e,t=!0,r){let a=new P;a.color=e,this.applyOpacity(a,r),this.materials.push(a)}setShader(e,t){console.warn("MaterialBuilder.setShader: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(new F("#ffffff"),!0,t)}setTSLShader(e,t){this.materials.push(se(e,t))}};function se(s,e){let t=new re;return t.colorNode=s.colorNode,s.positionNode&&(t.positionNode=s.positionNode),s.normalNode&&(t.normalNode=s.normalNode),s.blending!==void 0&&(t.blending=s.blending),s.side!==void 0&&(t.side=s.side),s.depthTest!==void 0&&(t.depthTest=s.depthTest),e!==void 0&&(t.opacity=e),t.transparent=!!s.transparent||e!==void 0&&e<1,t.needsUpdate=!0,t}export{C as a,O as b,G as c,E as d,b as e,c as f,A as g,ae as h,N as i,U as j,se as k,vt as l,Ot as m,wt as n,At as o,Ft as p,Pt as q,St as r};
19
+ `,O={vertex:C,fragment:D};import{Color as F,RepeatWrapping as v,SRGBColorSpace as te}from"three";import{MeshBasicNodeMaterial as re,MeshStandardNodeMaterial as P}from"three/webgpu";function G(s){let e=Object.keys(s).sort().reduce((t,r)=>(t[r]=s[r],t),{});return JSON.stringify(e)}function E(s){let e=0;for(let t=0;t<s.length;t++)e=Math.imul(31,e)+s.charCodeAt(t)|0;return e.toString(36)}import{LoadingManager as ee,Cache as k}from"three";import{TextureLoader as X,RepeatWrapping as B}from"three";var b=16,L=class{loader;constructor(){this.loader=new X}isSupported(e){let t=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","bmp","tga"].includes(t||"")}async load(e,t){let r=await this.loader.loadAsync(e,a=>{t?.onProgress&&a.lengthComputable&&t.onProgress(a.loaded/a.total)});return t?.repeat&&r.repeat.copy(h(t.repeat,p)),r.wrapS=t?.wrapS??B,r.wrapT=t?.wrapT??B,t?.colorSpace!==void 0&&(r.colorSpace=t.colorSpace),r.anisotropy=t?.anisotropy??b,r}clone(e){let t=e.clone();return t.anisotropy=e.anisotropy||b,t.needsUpdate=!0,t}};import{GLTFLoader as J}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as K}from"three/addons/loaders/DRACOLoader.js";import{KTX2Loader as Z}from"three/addons/loaders/KTX2Loader.js";import{MeshoptDecoder as $}from"three/addons/libs/meshopt_decoder.module.js";import{Mesh as j}from"three";import{clone as W}from"three/addons/utils/SkeletonUtils.js";function u(s){let e=W(s),t=[],r=[];s.traverse(a=>t.push(a)),e.traverse(a=>r.push(a));for(let a=0;a<t.length;a++){let o=t[a],n=r[a];!(o instanceof j)||!(n instanceof j)||(o.geometry?.clone&&(n.geometry=o.geometry.clone()),o.material&&(n.material=Array.isArray(o.material)?o.material.map(i=>i.clone()):o.material.clone()))}return e}function I(s){let e=s.indexOf("?"),t=s.indexOf("#"),r=[e,t].filter(a=>a>=0).reduce((a,o)=>Math.min(a,o),s.length);return s.slice(0,r)}function c(s){let e=I(s),t=e.lastIndexOf("/"),r=t>=0?e.slice(t+1):e,a=r.lastIndexOf(".");return a<0||a===r.length-1?null:r.slice(a+1).toLowerCase()}var V=["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"],H="https://www.gstatic.com/draco/v1/decoders/",g=class{loader;dracoLoader;ktx2Loader=null;meshoptEnabled=!1;configuredRenderer=null;ktx2TranscoderPath=null;constructor(){this.dracoLoader=new K,this.dracoLoader.setDecoderPath(H),this.loader=new J,this.loader.setDRACOLoader(this.dracoLoader),this.setMeshoptEnabled(!0)}isSupported(e){let t=c(e);return["gltf","glb"].includes(t||"")}async configureRuntime({meshopt:e=!0,ktx2TranscoderPath:t,renderer:r=null}={}){this.setMeshoptEnabled(e!==!1);let a=this.normalizeTranscoderPath(t);if(!a){this.clearKTX2Loader();return}if(!r)throw new Error("GLTFLoaderAdapter.configureRuntime requires a renderer when ktx2TranscoderPath is provided.");(!this.ktx2Loader||this.ktx2TranscoderPath!==a)&&(this.clearKTX2Loader(),this.ktx2Loader=new Z,this.ktx2Loader.setTranscoderPath(a),this.loader.setKTX2Loader(this.ktx2Loader),this.ktx2TranscoderPath=a,this.configuredRenderer=null),!(!this.ktx2Loader||this.configuredRenderer===r)&&(this.ktx2Loader.detectSupport(r),this.configuredRenderer=r)}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=await this.loader.parseAsync(a,e);return this.applyTextureAnisotropy(o.scene),{object:o.scene,animations:o.animations,gltf:o}}catch(r){return console.error(`Async fetch GLTF load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{this.applyTextureAnisotropy(o.scene),r({object:o.scene,animations:o.animations,gltf:o})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone()),gltf:e.gltf}}applyTextureAnisotropy(e){e.traverse(t=>{let r=t.material;if(!r)return;let a=Array.isArray(r)?r:[r];for(let o of a)for(let n of V){let i=o[n];if(i&&i.isTexture){let d=i;d.anisotropy=b,d.needsUpdate=!0}}})}setMeshoptEnabled(e){if(e){if(this.meshoptEnabled)return;this.loader.setMeshoptDecoder($),this.meshoptEnabled=!0;return}this.meshoptEnabled&&(this.loader.setMeshoptDecoder(void 0),this.meshoptEnabled=!1)}clearKTX2Loader(){this.ktx2Loader&&(this.ktx2Loader.dispose(),this.ktx2Loader=null),this.loader.setKTX2Loader(void 0),this.configuredRenderer=null,this.ktx2TranscoderPath=null}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}};import{FBXLoader as _}from"three/addons/loaders/FBXLoader.js";var T=class{loader;constructor(){this.loader=new _}isSupported(e){return c(e)==="fbx"}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=this.loader.parse(a,e);return{object:o,animations:o.animations||[]}}catch(r){return console.error(`Async fetch FBX load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:o.animations||[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone())}}};import{OBJLoader as z}from"three/addons/loaders/OBJLoader.js";import{MTLLoader as Y}from"three/addons/loaders/MTLLoader.js";var y=class{loader;mtlLoader;constructor(){this.loader=new z,this.mtlLoader=new Y}isSupported(e){return c(e)==="obj"}async load(e,t){return t?.mtlPath&&await this.loadMTL(t.mtlPath),new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}async loadMTL(e){return new Promise((t,r)=>{this.mtlLoader.load(e,a=>{a.preload(),this.loader.setMaterials(a),t()},void 0,a=>r(a))})}clone(e){return{object:u(e.object),animations:[]}}};import{AudioLoader as q}from"three";var x=class{loader;constructor(){this.loader=new q}isSupported(e){let t=c(e);return["mp3","ogg","wav","flac","aac","m4a"].includes(t||"")}async load(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>r(o),o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}};import{FileLoader as Q}from"three";var m=class{loader;constructor(){this.loader=new Q}isSupported(e){return!0}async load(e,t){let r=t?.responseType??"text";return this.loader.setResponseType(r),new Promise((a,o)=>{this.loader.load(e,n=>a(n),n=>{t?.onProgress&&n.lengthComputable&&t.onProgress(n.loaded/n.total)},n=>o(n))})}},M=class{fileLoader;constructor(){this.fileLoader=new m}isSupported(e){return c(e)==="json"}async load(e,t){return await this.fileLoader.load(e,{...t,responseType:"json"})}};var w=class s{static instance=null;textureCache=new Map;modelCache=new Map;audioCache=new Map;fileCache=new Map;jsonCache=new Map;pendingGLTFRuntimePath=null;pendingGLTFRuntimePromise=null;pendingGLTFRuntimeResolve=null;textureLoader;gltfLoader;fbxLoader;objLoader;audioLoader;fileLoader;jsonLoader;loadingManager;events;stats={texturesLoaded:0,modelsLoaded:0,audioLoaded:0,filesLoaded:0,cacheHits:0,cacheMisses:0};constructor(){this.textureLoader=new L,this.gltfLoader=new g,this.fbxLoader=new T,this.objLoader=new y,this.audioLoader=new x,this.fileLoader=new m,this.jsonLoader=new M,this.loadingManager=new ee,this.loadingManager.onProgress=(e,t,r)=>{this.events.emit("batch:progress",{loaded:t,total:r})},this.events=R(),k.enabled=!0}static getInstance(){return s.instance||(s.instance=new s),s.instance}static resetInstance(){s.instance&&(s.instance.clearCache(),s.instance=null)}async loadTexture(e,t){return this.loadWithCache(e,"texture",this.textureCache,()=>this.textureLoader.load(e,t),t,r=>{if(!t?.clone)return r;let a=this.textureLoader.clone(r);return t.repeat&&a.repeat.copy(h(t.repeat,p)),t.wrapS!==void 0&&(a.wrapS=t.wrapS),t.wrapT!==void 0&&(a.wrapT=t.wrapT),a})}async loadGLTF(e,t){return await this.waitForPreparedGLTFRuntime(),this.loadWithCache(e,"gltf",this.modelCache,()=>this.gltfLoader.load(e,t),t,r=>t?.clone?this.gltfLoader.clone(r):r)}prepareGLTFRuntime(e){let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&(this.pendingGLTFRuntimePath===t&&this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePath=t,this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePromise=new Promise(r=>{this.pendingGLTFRuntimeResolve=r}))))}async configureGLTFRuntime(e){await this.gltfLoader.configureRuntime(e);let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&e?.renderer&&this.resolvePreparedGLTFRuntime(t)}async loadFBX(e,t){return this.loadWithCache(e,"fbx",this.modelCache,()=>this.fbxLoader.load(e,t),t,r=>t?.clone?this.fbxLoader.clone(r):r)}async loadOBJ(e,t){let r=t?.mtlPath?`${e}:${t.mtlPath}`:e;return this.loadWithCache(r,"obj",this.modelCache,()=>this.objLoader.load(e,t),t,a=>t?.clone?this.objLoader.clone(a):a)}async loadModel(e,t){let r=c(e);switch(r){case"gltf":case"glb":return this.loadGLTF(e,t);case"fbx":return this.loadFBX(e,t);case"obj":return this.loadOBJ(e,t);default:throw new Error(`Unsupported model format: ${r}`)}}async loadAudio(e,t){return this.loadWithCache(e,"audio",this.audioCache,()=>this.audioLoader.load(e,t),t)}async loadFile(e,t){let r=t?.responseType?`${e}:${t.responseType}`:e;return this.loadWithCache(r,"file",this.fileCache,()=>this.fileLoader.load(e,t),t)}async loadJSON(e,t){return this.loadWithCache(e,"json",this.jsonCache,()=>this.jsonLoader.load(e,t),t)}async loadBatch(e){let t=new Map,r=e.map(async a=>{try{let o;switch(a.type){case"texture":o=await this.loadTexture(a.url,a.options);break;case"gltf":o=await this.loadGLTF(a.url,a.options);break;case"fbx":o=await this.loadFBX(a.url,a.options);break;case"obj":o=await this.loadOBJ(a.url,a.options);break;case"audio":o=await this.loadAudio(a.url,a.options);break;case"file":o=await this.loadFile(a.url,a.options);break;case"json":o=await this.loadJSON(a.url,a.options);break;default:throw new Error(`Unknown asset type: ${a.type}`)}t.set(a.url,o)}catch(o){throw this.events.emit("asset:error",{url:a.url,type:a.type,error:o}),o}});return await Promise.all(r),this.events.emit("batch:complete",{urls:e.map(a=>a.url)}),t}async preload(e){await this.loadBatch(e)}isCached(e){return this.textureCache.has(e)||this.modelCache.has(e)||this.audioCache.has(e)||this.fileCache.has(e)||this.jsonCache.has(e)}clearCache(e){e?(this.textureCache.delete(e),this.modelCache.delete(e),this.audioCache.delete(e),this.fileCache.delete(e),this.jsonCache.delete(e)):(this.textureCache.clear(),this.modelCache.clear(),this.audioCache.clear(),this.fileCache.clear(),this.jsonCache.clear(),k.clear(),this.pendingGLTFRuntimePath=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimeResolve=null)}getStats(){return{...this.stats}}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}async loadWithCache(e,t,r,a,o,n){o?.forceReload&&r.delete(e);let i=r.get(e);if(i){this.stats.cacheHits++,this.events.emit("asset:loaded",{url:e,type:t,fromCache:!0});let l=await i.promise;return n?n(l):l}this.stats.cacheMisses++,this.events.emit("asset:loading",{url:e,type:t});let d=a(),f={promise:d,loadedAt:Date.now()};r.set(e,f);try{let l=await d;return f.result=l,this.updateStats(t),this.events.emit("asset:loaded",{url:e,type:t,fromCache:!1}),n?n(l):l}catch(l){throw r.delete(e),this.events.emit("asset:error",{url:e,type:t,error:l}),l}}updateStats(e){switch(e){case"texture":this.stats.texturesLoaded++;break;case"gltf":case"fbx":case"obj":this.stats.modelsLoaded++;break;case"audio":this.stats.audioLoaded++;break;case"file":case"json":this.stats.filesLoaded++;break}}async waitForPreparedGLTFRuntime(){this.pendingGLTFRuntimePromise&&await this.pendingGLTFRuntimePromise}resolvePreparedGLTFRuntime(e){this.pendingGLTFRuntimePath&&this.pendingGLTFRuntimePath!==e||(this.pendingGLTFRuntimeResolve?.(),this.pendingGLTFRuntimeResolve=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimePath=null)}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}},A=w.getInstance();import{uniform as vt,uv as Ot,time as wt,vec3 as At,vec4 as Ft,float as Pt,Fn as St}from"three/tsl";function ae(s){return"colorNode"in s}function N(s){return"fragment"in s&&"vertex"in s}function oe(s){return!!s&&N(s)&&s.vertex===O.vertex&&s.fragment===O.fragment}var U=class s{static sharedMaterialMap=new Map;static clearSharedMaterialCache(){s.sharedMaterialMap.clear()}materials=[];useTSL;constructor(e=!0){this.useTSL=e}trackSharedMaterial(e,t){let r=E(G(e)),a=s.sharedMaterialMap.get(r);if(a){let o=a.geometryMap.get(t);o?a.geometryMap.set(t,o+1):a.geometryMap.set(t,1)}else s.sharedMaterialMap.set(r,{geometryMap:new Map([[t,1]]),material:this.materials[0]})}build(e,t){let{path:r,normalMap:a,repeat:o,color:n,shader:i,opacity:d}=e,f=oe(i),l=!!i&&!f,S=!!r&&(!i||f);S?this.setTexture(r??null,o,!0,d,n):l&&i?ae(i)?this.setTSLShader(i,d):N(i)&&(console.warn("MaterialBuilder: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(n??new F("#ffffff"),!0,d)):r&&this.setTexture(r,o,!0,d,n),n&&!S&&!l&&this.withColor(n,!0,d),this.materials.length===0&&this.setColor(new F("#ffffff"),!0,d),a&&this.materials.length>0&&this.setNormalMap(a,o),this.trackSharedMaterial(e,t)}withColor(e,t=!1,r){return this.setColor(e,t,r),this}withShader(e,t){return this.setShader(e,t),this}withTSLShader(e,t){return this.setTSLShader(e,t),this}applyOpacity(e,t,r=!1){t!==void 0&&(e.opacity=t),e.transparent=r||t!==void 0&&t<1,e.needsUpdate=!0}setTexture(e=null,t=p,r=!0,a,o){if(!e)return;let n=new P;o&&(n.color=o),this.applyOpacity(n,a),this.materials.push(n),A.loadTexture(e,{clone:!0,repeat:h(t,p),colorSpace:te}).then(i=>{i.wrapS=v,i.wrapT=v,n.map=i,n.needsUpdate=!0})}setNormalMap(e,t=p){let r=this.materials[this.materials.length-1];r&&A.loadTexture(e,{clone:!0,repeat:h(t,p)}).then(a=>{a.wrapS=v,a.wrapT=v,r instanceof P&&(r.normalMap=a,r.needsUpdate=!0)})}setColor(e,t=!0,r){let a=new P;a.color=e,this.applyOpacity(a,r),this.materials.push(a)}setShader(e,t){console.warn("MaterialBuilder.setShader: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(new F("#ffffff"),!0,t)}setTSLShader(e,t){this.materials.push(se(e,t))}};function se(s,e){let t=new re;return t.colorNode=s.colorNode,s.positionNode&&(t.positionNode=s.positionNode),s.normalNode&&(t.normalNode=s.normalNode),s.blending!==void 0&&(t.blending=s.blending),s.side!==void 0&&(t.side=s.side),s.depthTest!==void 0&&(t.depthTest=s.depthTest),e!==void 0&&(t.opacity=e),t.transparent=!!s.transparent||e!==void 0&&e<1,t.needsUpdate=!0,t}export{G as a,E as b,C as c,O as d,b as e,c as f,A as g,ae as h,N as i,U as j,se as k,vt as l,Ot as m,wt as n,At as o,Ft as p,Pt as q,St as r};
@@ -0,0 +1 @@
1
+ import{RuntimeBoundary2DBehavior as R,RuntimeDynamicCircleBody2DBehavior as t,RuntimeGoalZone2DBehavior as o,RuntimePlayerInput2DBehavior as m,RuntimeRicochet2DBehavior as r,RuntimeTriggerRegion2DBehavior as D,RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY as _,RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY as u,RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY as E,RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY as a,RUNTIME_RICOCHET_2D_BEHAVIOR_KEY as B,RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY as I,bindRuntimeDynamicCircleBody2DHandle as c,emitRuntimeGoal as O,emitRuntimeRicochet as l,emitRuntimeTriggerRegionEnter as g}from"@zylem/behaviors/runtime-2d";export{R as a,t as b,o as c,m as d,r as e,D as f,_ as g,u as h,E as i,a as j,B as k,I as l,c as m,O as n,l as o,g as p};
@@ -1 +1 @@
1
- import{d as i,o as f}from"./chunk-EVMLNMGU.js";var n=null;function b(e){return n=e,()=>{n===e&&(n=null)}}function x(e){if(!n)return console.warn("focusEntity: no active stage focus context"),!1;let t=n.resolveEntity(e);if(!t)return console.warn(`focusEntity: entity ${e} not found`),!1;let o=t.group??t.mesh??null;return o?(i.enabled||(i.enabled=!0),n.ensureDebugReady?.(),f(e),n.frameObject(o),!0):(console.warn(`focusEntity: entity ${e} has no group/mesh`),!1)}import{Euler as y,Quaternion as m}from"three";var u=new y,r=new m;function d(e){return u.set(e.x,e.y,e.z,"XYZ"),r.setFromEuler(u),{x:r.x,y:r.y,z:r.z,w:r.w}}function g(e){return r.set(e.x,e.y,e.z,e.w),u.setFromQuaternion(r,"XYZ"),{x:u.x,y:u.y,z:u.z}}function s(e,t){return!Number.isFinite(t)||t<=0?e:Math.round(e/t)*t}function h(e,t){return{x:s(e.x,t),y:s(e.y,t),z:s(e.z,t)}}function z(e,t){let o=a=>{let c=s(a,t);return c!==0?c:t>0?t:a};return{x:o(e.x),y:o(e.y),z:o(e.z)}}function w(e){return e*Math.PI/180}function I(e){return e*180/Math.PI}export{b as a,x as b,d as c,g as d,s as e,h as f,z as g,w as h,I as i};
1
+ import{d as i,o as f}from"./chunk-GPCSX3M6.js";var n=null;function b(e){return n=e,()=>{n===e&&(n=null)}}function x(e){if(!n)return console.warn("focusEntity: no active stage focus context"),!1;let t=n.resolveEntity(e);if(!t)return console.warn(`focusEntity: entity ${e} not found`),!1;let o=t.group??t.mesh??null;return o?(i.enabled||(i.enabled=!0),n.ensureDebugReady?.(),f(e),n.frameObject(o),!0):(console.warn(`focusEntity: entity ${e} has no group/mesh`),!1)}import{Euler as y,Quaternion as m}from"three";var u=new y,r=new m;function d(e){return u.set(e.x,e.y,e.z,"XYZ"),r.setFromEuler(u),{x:r.x,y:r.y,z:r.z,w:r.w}}function g(e){return r.set(e.x,e.y,e.z,e.w),u.setFromQuaternion(r,"XYZ"),{x:u.x,y:u.y,z:u.z}}function s(e,t){return!Number.isFinite(t)||t<=0?e:Math.round(e/t)*t}function h(e,t){return{x:s(e.x,t),y:s(e.y,t),z:s(e.z,t)}}function z(e,t){let o=a=>{let c=s(a,t);return c!==0?c:t>0?t:a};return{x:o(e.x),y:o(e.y),z:o(e.z)}}function w(e){return e*Math.PI/180}function I(e){return e*180/Math.PI}export{b as a,x as b,d as c,g as d,s as e,h as f,z as g,w as h,I as i};
@@ -0,0 +1 @@
1
+ import{getZylemBridge as p,announceBridgeReady as d,applySwatchesToSelection as o,BRIDGE_READY_EVENT as i}from"@zylem/bridge";export{p as a,d as b,o as c,i as d};
@@ -0,0 +1 @@
1
+ import{proxy as c}from"valtio/vanilla";var a=["translate","rotate","scale"];function b(t){return a.includes(t)}var y={enabled:!0,translate:.25,rotate:Math.PI/12,scale:.1},e=c({enabled:!1,paused:!1,tool:"none",selectedEntityId:null,selectedEntityIds:[],hoveredEntityId:null,snap:{...y},gridVisible:!1,addTypeId:null,addTypeProps:null,pickMode:!1,flags:new Set}),l=null;function S(t){return l=t,()=>{l===t&&(l=null)}}function d(t){return!t||!l?null:l(t)}function s(t,n){if(t==null)return null;if(typeof t=="string")return t;let o=t.uuid;if(typeof o=="string")return console.warn(`${n}: received a live entity. Pass the UUID instead \u2014 storing entities in debugState makes valtio deep-proxy the scene graph.`),o;throw new TypeError(`${n} expects an entity UUID string or null, received ${typeof t}.`)}function v(){return e.paused}function T(t){e.paused=t}function m(){return e.tool}function D(t){e.tool=t}function h(){return e.enabled||e.tool!=="none"||e.pickMode}function k(t){e.pickMode=t,!t&&e.tool!=="select"&&e.tool!=="delete"&&x()}function P(){return e.pickMode}function R(){return e.selectedEntityId}function p(t){let n=s(t,"setSelectedEntityId");e.selectedEntityId!==n&&(e.selectedEntityId=n,e.selectedEntityIds=n?[n]:[])}function M(){return[...e.selectedEntityIds]}function u(t){let n=t.map((i,r)=>s(i,`setSelectedEntityIds[${r}]`)).filter(i=>i!==null);n.length===e.selectedEntityIds.length&&n.every((i,r)=>e.selectedEntityIds[r]===i)||(e.selectedEntityIds=n,e.selectedEntityId=n[0]??null)}function g(t){let n=e.selectedEntityIds,o=t.filter((i,r)=>!n.includes(i)&&t.indexOf(i)===r);o.length!==0&&u([...n,...o])}function f(t){let n=new Set(t);u(e.selectedEntityIds.filter(o=>!n.has(o)))}function w(t){let n=s(t,"toggleSelectedEntityId");n&&(e.selectedEntityIds.includes(n)?f([n]):g([n]))}function G(){return{...e.snap}}function O(t){Object.assign(e.snap,t)}function H(t){e.gridVisible=t}function A(t,n){e.addTypeId=t,e.addTypeProps=t?n??null:null}function U(){return e.hoveredEntityId}function E(t){let n=s(t,"setHoveredEntityId");e.hoveredEntityId!==n&&(e.hoveredEntityId=n)}function x(){E(null)}function F(){return d(e.selectedEntityId)}function N(){return d(e.hoveredEntityId)}function V(t){p(s(t,"setSelectedEntity"))}export{a,b,y as c,e as d,S as e,d as f,v as g,T as h,m as i,D as j,h as k,k as l,P as m,R as n,p as o,M as p,u as q,g as r,f as s,w as t,G as u,O as v,H as w,A as x,U as y,E as z,x as A,F as B,N as C,V as D};
@@ -0,0 +1 @@
1
+ import{b as x,c as C,d as k}from"./chunk-BQRMYLYD.js";import{d as a,h as y,j as f,l as b,o as g,q as d,r as m,s as S,t as v,v as w,w as E,x as P}from"./chunk-GPCSX3M6.js";import{subscribe as A}from"valtio/vanilla";import{announceBridgeReady as K,getZylemBridge as c}from"@zylem/bridge";function u(t,e){return[t[0]*e.x,t[1]*e.y,t[2]*e.z]}function D(t,e){let i=new Float32Array(t.length);for(let n=0;n<t.length;n+=3)i[n]=t[n]*e.x,i[n+1]=t[n+1]*e.y,i[n+2]=t[n+2]*e.z;return i}function U(t,e){let{shape:i}=t,n=t.offset?u(t.offset,e):t.offset,o;switch(i.type){case"box":o={type:"box",halfExtents:u(i.halfExtents,e)};break;case"sphere":o={type:"sphere",radius:i.radius*Math.max(e.x,e.y,e.z)};break;case"capsule":case"cylinder":case"cone":o={type:i.type,halfHeight:i.halfHeight*e.y,radius:i.radius*Math.max(e.x,e.z)};break;case"convexHull":o={type:"convexHull",vertices:D(i.vertices,e)};break;case"trimesh":o={type:"trimesh",vertices:D(i.vertices,e),indices:i.indices};break;case"heightfield":o={...i,scale:u(i.scale,e)};break;default:o=i;break}return{...t,shape:o,offset:n}}function q(t){if(!t.colliderBaseline){let e=t.colliderDescs.length?t.colliderDescs:t.colliderDesc?[t.colliderDesc]:[];t.colliderBaseline=e.map(i=>({...i}))}return t.colliderBaseline}function B(t){if(!t.colliderScaleDirty)return!1;t.colliderScaleDirty=!1;let e=q(t);if(!e.length)return!1;let i=t.getScale(),n=e.map(r=>U(r,i));t.colliderDescs=n,t.colliderDesc=n[0];let o=t.physicsWorldRef;if(!o)return!0;let s=t.getPose();return o.destroyEntity(t),s&&t.bodyDesc&&(t.bodyDesc.position=[s.position.x,s.position.y,s.position.z],t.bodyDesc.rotation=[s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w]),o.addEntity(t),!0}function V(t){return(t?.group??t?.mesh)?.scale}function G(t){let i=(typeof t?.getScale=="function"?t.getScale():void 0)??t?.scale??V(t)??{};return{x:i.x??1,y:i.y??1,z:i.z??1}}function _(t){let e=typeof t?.getPose=="function"?t.getPose():null;if(!e?.rotation)return;let{x:i,y:n,z:o,w:s}=e.rotation;return{x:i,y:n,z:o,w:s}}function h(t){let e=typeof t?.getPose=="function"?t.getPose():null,i=e?.position??{x:0,y:0,z:0},n=e?.rotation??{x:0,y:0,z:0,w:1};return{position:{x:i.x,y:i.y,z:i.z},rotation:k(n),quaternion:{x:n.x,y:n.y,z:n.z,w:n.w},scale:G(t)}}function T(t,e){if(typeof t?.setScale=="function"){t.setScale(e.x,e.y,e.z);return}V(t)?.set?.(e.x,e.y,e.z)}function R(t){!t||typeof t.getScale!="function"||B(t)}function N(t,e){if(!t)return!1;let i=e.quaternion??(e.rotation?C(e.rotation):void 0),n=!1;return(e.position||i)&&typeof t.setPose=="function"&&(n=t.setPose({position:e.position,rotation:i})),e.scale&&(T(t,e.scale),n=!0),n}function $(t){let e=t?.constructor?.type;return e?String(e).replace("Symbol(","").replace(")",""):"Unknown"}function H(t){let e=t;if(!e?.uuid)return;let i=c().channel;if(!i.hasSubscribers("entity:upsert"))return;let n=h(t);i.queue("entity:upsert",[{uuid:e.uuid,name:e.name||"Unnamed",type:$(t),position:n.position,rotation:n.rotation,scale:n.scale,quaternion:n.quaternion}])}function ee(t,e){c().channel.send("game:notice",{level:t,message:e})}function L(t,e,i){let n=[...new Set(t.swatches.map(r=>r.source))],o=[...new Set(e.map(r=>r.uuid))],s=o.length===1?i(o[0])||"entity":`${o.length} entities`;return`Apply ${n.join(", ")} to ${s}`}function M(t,e){return!e||t.length!==e.length?!1:t.every((i,n)=>i===e[n])}function Q(t,e){switch(e){case"add":m(t);break;case"subtract":S(t);break;case"toggle":for(let i of t)v(i);break;default:d(t);break}}var O=class{channel;unsubscribes=[];host=null;editorKnown={};applyingSceneOperation=!1;constructor(){this.channel=c().channel}connect(e,i){this.disconnect(),this.host=e,this.unsubscribes.push(this.channel.on("debug:set",({enabled:n})=>{this.editorKnown.debug=n,a.enabled=n}),this.channel.on("tool:set",({tool:n})=>{f(n)}),this.channel.on("playback:set",({paused:n})=>{this.editorKnown.paused=n,y(n)}),this.channel.on("entity:select",({uuid:n,uuids:o,mode:s})=>{o?Q(o,s??"replace"):g(n),this.editorKnown.selectedUuid=a.selectedEntityId,this.editorKnown.selectedUuids=[...a.selectedEntityIds]}),this.channel.on("entity:focus",({uuid:n})=>{x(n)}),this.channel.on("entity:transform",({uuid:n,position:o,rotation:s,quaternion:r,scale:p})=>{let l=this.host?.resolveEntity(n);if(!l)return;let I=h(l);if(N(l,{position:o,rotation:s,quaternion:r,scale:p}),p&&R(l),H(l),this.applyingSceneOperation)return;let z=h(l);this.channel.send("scene:operation",{opId:`tx-${n}-${Date.now().toString(36)}`,kind:"transform",label:`Set ${l.name||"entity"} transform`,entries:[{uuid:n,before:I,after:z}]})}),this.channel.on("entity:create",({typeId:n,props:o,pose:s})=>{this.host?.createEntity?.(n,o,s)}),this.channel.on("scene:operation:apply",({op:n,direction:o})=>{this.applyingSceneOperation=!0;try{this.host?.applySceneOperation?.(n,o)}finally{this.applyingSceneOperation=!1}}),this.channel.on("add:type:set",({typeId:n,props:o})=>{P(n,o??null)}),this.channel.on("snap:set",n=>{w(n)}),this.channel.on("grid:set",({visible:n})=>{E(n)}),this.channel.on("stage:variable:set",({key:n,value:o})=>{this.host?.setStageVariable?.(n,o)}),this.channel.on("pick:mode:set",({enabled:n})=>{b(n)}),this.channel.on("entity:pick",({requestId:n,ndc:o})=>{let s=this.host?.pickEntity?.(o)??null;this.channel.send("entity:pick:result",{requestId:n,hit:s})}),this.channel.on("entity:apply-swatch",n=>{this.handleApplySwatch(n)}),this.channel.on("cutscene:load",n=>this.host?.cutscene?.load(n)),this.channel.on("cutscene:play",({from:n})=>this.host?.cutscene?.play(n)),this.channel.on("cutscene:pause",()=>this.host?.cutscene?.pause()),this.channel.on("cutscene:stop",()=>this.host?.cutscene?.stop()),this.channel.on("cutscene:seek",({time:n})=>this.host?.cutscene?.seek(n)),this.channel.on("cutscene:unload",()=>this.host?.cutscene?.unload()),this.channel.on("camera:pose:get",({requestId:n})=>{let o=this.host?.cameraPose?.();o&&this.channel.send("camera:pose",{requestId:n,...o})}),A(a,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),K(i)}publishCutsceneStatus(e){this.channel.queue("cutscene:status",e)}publishCutsceneView(e){this.channel.queue("cutscene:view",e)}disconnect(){for(let e of this.unsubscribes)e();this.unsubscribes=[],this.host=null,this.editorKnown={}}handleApplySwatch(e){let i=e.opId??`swatch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,n=this.host?.applySwatches?this.host.applySwatches({...e,opId:i}):{results:e.uuids.flatMap(s=>e.swatches.map(r=>({uuid:s,kind:r.kind,source:r.source,ok:!1,reason:"entity-not-found"}))),entries:[]},o=[...new Set(n.entries.map(s=>s.uuid))];e.select&&o.length>0&&d(o),n.entries.length>0&&!this.applyingSceneOperation&&this.channel.send("scene:operation",{opId:i,kind:"swatch",label:L(e,n.entries,s=>this.host?.resolveEntity(s)?.name),entries:n.entries}),this.channel.send("entity:swatch-applied",{opId:i,results:n.results})}publishDebugStateChanges(){let e={};a.paused!==this.editorKnown.paused&&(this.editorKnown.paused=a.paused,e.paused=a.paused),a.enabled!==this.editorKnown.debug&&(this.editorKnown.debug=a.enabled,e.debug=a.enabled),(e.paused!==void 0||e.debug!==void 0)&&this.publishStatus(e),(a.selectedEntityId!==this.editorKnown.selectedUuid||a.hoveredEntityId!==this.editorKnown.hoveredUuid||!M(a.selectedEntityIds,this.editorKnown.selectedUuids))&&(this.editorKnown.selectedUuid=a.selectedEntityId,this.editorKnown.selectedUuids=[...a.selectedEntityIds],this.editorKnown.hoveredUuid=a.hoveredEntityId,this.channel.queue("entity:selection",{selectedUuid:a.selectedEntityId,hoveredUuid:a.hoveredEntityId,selectedUuids:[...a.selectedEntityIds]}))}wantsEntityUpdates(){return this.channel.hasSubscribers("entity:upsert")||this.channel.hasSubscribers("stage:snapshot")}wantsThumbnails(){return this.channel.hasSubscribers("entity:thumbnail")}onEditorAttached(e){return this.channel.onSubscriberAdded(i=>{if(i!=="entity:upsert"&&i!=="entity:thumbnail")return;let n=i==="entity:upsert"?"entity:thumbnail":"entity:upsert";this.channel.subscriberCount(n)>0||e()})}publishConfig(e){this.channel.send("game:config",e)}publishLoading(e){this.channel.send("game:loading",e)}publishStatus(e){this.channel.queue("game:status",e)}publishVariable(e){this.channel.send("game:variable",e)}publishNotice(e,i){this.channel.send("game:notice",{level:e,message:i})}publishStageSnapshot(e){this.channel.send("stage:snapshot",e)}queueEntityUpsert(e){e.length&&this.channel.queue("entity:upsert",e)}queueEntityRemoved(e){e.length&&this.channel.queue("entity:removed",{uuids:e})}queueThumbnails(e){e.length&&this.channel.queue("entity:thumbnail",e)}publishCatalog(e){this.channel.send("catalog:snapshot",{entities:e})}publishSceneOperation(e){this.channel.send("scene:operation",e)}wantsSceneOperations(){return this.channel.hasSubscribers("scene:operation")}};function te(t){c().channel.send("scene:operation",t)}export{B as a,G as b,_ as c,h as d,$ as e,ee as f,O as g,te as h};
@@ -0,0 +1 @@
1
+ import{a as I,b as y,r as Z,t as f,v as d}from"./chunk-KP6DLLJO.js";import{e as R}from"./chunk-UUOPT2N4.js";import{j as E}from"./chunk-4QLJUQSJ.js";import{a as O,g as b,i as T,j as w}from"./chunk-7WRQ2UAN.js";import{Group as W,Quaternion as X,Vector3 as S}from"three";import{ParticleEmitterBehavior as x}from"@zylem/behaviors/particle-emitter";var U={...Z,effect:{create(){throw new Error("createParticleSystem(...) requires an effect or preset definition.")}},preset:void 0,autoplay:!0,localOffset:void 0,followPosition:!0,followRotation:!0,autoDestroy:!1},M=Symbol("ParticleSystem"),C=1,Q=new S(C,C,C),H=new S;function $(n){return{effect:n.preset??n.effect,autoplay:n.autoplay,localOffset:n.localOffset,followPosition:n.followPosition,followRotation:n.followRotation,autoDestroy:n.autoDestroy}}var P=class n extends f{static type=M;particleHandle=null;getSelectionBounds(o){return this.group?(this.group.getWorldPosition(H),o.setFromCenterAndSize(H,Q),R(o)):null}constructor(o,e=!0){super(),this.options=y(U,o),this.group=new W;let t=this.options.position;t&&this.group.position.copy(w(t)),this.__zylemParticleSystemEntity=!0,this.bindStandaloneTransforms(),e&&(this.particleHandle=this.use(x,$(this.options)))}bindStandaloneTransforms(){let o=()=>{this.options.position=new S(this.group?.position.x??0,this.group?.position.y??0,this.group?.position.z??0)},e=()=>{this.group&&(this._rotation2DAngle=this.group.rotation.z)};this.setPosition=(t,i,r)=>{this.group?.position.set(t,i,r),o()},this.setPositionX=t=>{this.group&&(this.group.position.x=t,o())},this.setPositionY=t=>{this.group&&(this.group.position.y=t,o())},this.setPositionZ=t=>{this.group&&(this.group.position.z=t,o())},this.getPosition=()=>this.group?{x:this.group.position.x,y:this.group.position.y,z:this.group.position.z}:null,this.setRotation=(t,i,r)=>{this.group?.rotation.set(t,i,r),e()},this.setRotationX=t=>{this.group&&(this.group.rotation.x=t,e())},this.setRotationY=t=>{this.group&&(this.group.rotation.y=t,e())},this.setRotationZ=t=>{this.group&&(this.group.rotation.z=t,e())},this.setRotationDegrees=(t,i,r)=>{this.group?.rotation.set(t*Math.PI/180,i*Math.PI/180,r*Math.PI/180),e()},this.setRotationDegreesX=t=>{this.group&&(this.group.rotation.x=t*Math.PI/180,e())},this.setRotationDegreesY=t=>{this.group&&(this.group.rotation.y=t*Math.PI/180,e())},this.setRotationDegreesZ=t=>{this.group&&(this.group.rotation.z=t*Math.PI/180,e())},this.rotateX=t=>{this.group?.rotateX(t),e()},this.rotateY=t=>{this.group?.rotateY(t),e()},this.rotateZ=t=>{this.group?.rotateZ(t),e()},this.getRotation=()=>{if(!this.group)return null;let t=new X;return this.group.getWorldQuaternion(t),t}}resolveParticleHandle(){if(this.particleHandle)return this.particleHandle;let o=this.getBehaviorRefs().find(i=>i.descriptor.key===x.key);if(!o)return null;let e={getFSM:()=>o.fsm??null,getOptions:()=>o.options,ref:o},t=x.createHandle?.(o)??{};return this.particleHandle={...e,...t},this.particleHandle}play(){this.resolveParticleHandle()?.play()}stop(){this.resolveParticleHandle()?.stop()}pause(){this.resolveParticleHandle()?.pause()}restart(){this.resolveParticleHandle()?.restart()}burst(){this.resolveParticleHandle()?.burst()}isPlaying(){return this.resolveParticleHandle()?.isPlaying()??!1}getSystem(){return this.resolveParticleHandle()?.getSystem()}buildInfo(){return{...super.buildInfo(),type:String(n.type)}}};function z(n,o=!0){let e=new P(n,o);return d(e,t=>z(t,!1))}function q(n){return z(n,!0)}import{Group as K,Sprite as j,SpriteMaterial as J,CanvasTexture as tt,LinearFilter as D,Color as Y,ClampToEdgeWrapping as B}from"three";import{getCooldown as L}from"@zylem/behaviors/cooldown";var et={"top-left":{fx:0,fy:0},"top-center":{fx:.5,fy:0},"top-right":{fx:1,fy:0},"center-left":{fx:0,fy:.5},center:{fx:.5,fy:.5},"center-right":{fx:1,fy:.5},"bottom-left":{fx:0,fy:1},"bottom-center":{fx:.5,fy:1},"bottom-right":{fx:1,fy:1}},A=192,ot={xs:8,sm:16,md:32,lg:48,xl:64},_={position:void 0,cooldown:"",iconSize:"md",fillColor:"#333333",showTimer:!0,stickToViewport:!0,screenAnchor:"top-left",screenPosition:{x:0,y:0},zDistance:1,overlayColor:"rgba(0, 0, 0, 0.65)"},it=Symbol("CooldownIcon"),v=class extends f{static type=it;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_iconTexture=null;_iconImage=null;_lastRenderedProgress=-1;constructor(o){super(),this.options=y(_,o),this.options.screenPosition=T(this.options.screenPosition,_.screenPosition),this.group=new K,this.createSprite(),this.prependSetup(this.iconSetup.bind(this)),this.prependUpdate(this.iconUpdate.bind(this)),this.onCleanup(this.iconDestroy.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._canvas.width=256,this._canvas.height=256,this._ctx=this._canvas.getContext("2d"),this._texture=new tt(this._canvas),this._texture.minFilter=D,this._texture.magFilter=D,this._texture.wrapS=B,this._texture.wrapT=B;let e=new J({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1});if(this._sprite=new j(e),this.group?.add(this._sprite),this.options.icon){let t=new Image;t.crossOrigin="anonymous",t.onload=()=>{this._iconImage=t,this.redraw(this._lastRenderedProgress>=0?this._lastRenderedProgress:1)},t.src=this.options.icon}this.redraw(1)}redraw(o){if(!this._canvas||!this._ctx)return;let e=this._ctx,t=this._canvas.width,i=this._canvas.height,r=t/2,s=i/2,l=Math.min(r,s);if(e.clearRect(0,0,t,i),this._iconImage?e.drawImage(this._iconImage,0,0,t,i):(e.fillStyle=this.toCssColor(this.options.fillColor??"#333333"),e.fillRect(0,0,t,i)),o<1){let p=(1-o)*Math.PI*2,c=-Math.PI/2,h=c+p;if(e.save(),e.fillStyle=this.options.overlayColor??"rgba(0, 0, 0, 0.65)",e.beginPath(),e.moveTo(r,s),e.arc(r,s,l+1,c,h,!1),e.closePath(),e.fill(),e.restore(),this.options.showTimer){let a=L(this.options.cooldown);if(a){let m=Math.max(0,a.duration-a.elapsed),g=m>=10?Math.ceil(m).toString():m.toFixed(1),u=Math.floor(t*.3);e.font=`bold ${u}px sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillStyle="#FFFFFF",e.strokeStyle="#000000",e.lineWidth=2,e.strokeText(g,r,s),e.fillText(g,r,s)}}}this._texture&&(this._texture.needsUpdate=!0),this._lastRenderedProgress=o}toCssColor(o){return typeof o=="string"?o:`#${(o instanceof Y?o:new Y(o)).getHexString()}`}getResolution(){try{let o=this._cameraRef?.renderer?.domElement;if(o)return{width:o.clientWidth||1,height:o.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}iconSetup(o){this._sprite||this.createSprite(),this._cameraRef=o.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}iconUpdate(o){let t=L(this.options.cooldown)?.progress??1;(Math.abs(t-this._lastRenderedProgress)>.02||t===1&&this._lastRenderedProgress!==1)&&this.redraw(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}resolveScreenPosition(o,e){let t=this.options.screenAnchor??"top-left",i=b(this.options.screenPosition,O),r=i.x,s=i.y,{fx:l,fy:p}=et[t],c=l*o,h=p*e,a=e/A;return{px:c+r*a,py:h+s*a}}resolveIconSize(o){let e=this.options.iconSize??"md",t,i;typeof e=="string"?t=i=ot[e]:typeof e=="number"?t=i=e:(t=e.width,i=e.height);let r=o/A;return{widthPx:t*r,heightPx:i*r}}computeWorldExtents(o,e){let t=1,i=1;if(o.isPerspectiveCamera){let r=o,s=Math.tan(r.fov*Math.PI/180/2)*e;t=s*r.aspect,i=s}else if(o.isOrthographicCamera){let r=o;t=(r.right-r.left)/2,i=(r.top-r.bottom)/2}return{worldHalfW:t,worldHalfH:i}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let o=this._cameraRef.camera,{width:e,height:t}=this.getResolution(),{px:i,py:r}=this.resolveScreenPosition(e,t),s=Math.max(.001,this.options.zDistance??1),{worldHalfW:l,worldHalfH:p}=this.computeWorldExtents(o,s),c=i/e*2-1,h=1-r/t*2,a=c*l,m=h*p;{let u=p*2/t,{widthPx:k,heightPx:N}=this.resolveIconSize(t),G=Math.max(1e-4,k*u),V=Math.max(1e-4,N*u);this._sprite.scale.set(G,V,1)}this.group?.position.set(a,m,-s)}iconDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._iconTexture?.dispose(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null,this._iconTexture=null,this._iconImage=null}};function F(...n){let o=n.filter(t=>!(t instanceof I)),e={..._};for(let t of o)e={...e,...t};return d(new v(e),t=>F(t??{}))}function rt(n,o,e){e({me:n,globals:o})}function nt(n,o){let e=o??E();rt(n,e,n.nodeDestroy.bind(n))}export{M as a,P as b,q as c,F as d,nt as e};
@@ -0,0 +1 @@
1
+ import{d as H,j as E}from"./chunk-6FGXC4T6.js";import{a as G,b as V}from"./chunk-AIQ6IVT5.js";import{a as M,b as Z,c as j}from"./chunk-EVYHPR3J.js";import{c as m,d as S,e as z,f as F,g as L,h as c,i as U,j as N}from"./chunk-7WRQ2UAN.js";import{p as X}from"./chunk-XRP4JJXL.js";import{StageBodyKind as W}from"@zylem/behaviors/core";import{Color as be,Vector2 as Y,Vector3 as K}from"three";function g(i){if(!i||typeof i!="object")return!1;let e=Object.getPrototypeOf(i);return e===Object.prototype||e===null}function l(i){if(i==null||typeof i=="function"||typeof i!="object")return i;if(i instanceof be||i instanceof Y||i instanceof K)return i.clone();if(i instanceof Float32Array)return new Float32Array(i);if(Array.isArray(i))return i.map(e=>l(e));if(g(i)){let e={};for(let[t,o]of Object.entries(i))t!=="_builders"&&(e[t]=l(o));return e}return i}function d(i,e){let t=l(i);if(!e)return t;if(!g(t)||!g(e))return l(e);let o=t;for(let[n,s]of Object.entries(e)){if(n==="_builders"||s===void 0)continue;let r=o[n];if(n==="shader"){o[n]=l(s);continue}if(r instanceof Y&&z(s)){o[n]=U(s,r);continue}if(r instanceof K&&F(s)){o[n]=N(s,r);continue}if(g(r)&&g(s)){o[n]=d(r,s);continue}o[n]=l(s)}return o}function $(i){return i&&i.__kind==="collision"}function k(i){return i.cloneComponent()}function Ce(i,e){let t={kind:i?W.Static:W.Dynamic,position:[0,0,0],gravityScale:e.gravityScale??1,canSleep:e.canSleep??!1,ccdEnabled:e.ccdEnabled??!0},o=M(e.lockRotations);o&&(t.lockRotation=o);let n=M(e.lockTranslations);return n&&(t.lockTranslation=n),t}function ge(i,e){if(e.offset){let t=c(e.offset,m);i.offset=[t.x,t.y,t.z]}e.sensor&&(i.sensor=!0),e.collisionType&&(i.collisionGroups=Z(e.collisionType,e.collisionFilter))}function h(i,e,t){return ge(i,e),{__kind:"collision",bodyDesc:Ce(e.static??!1,e),colliderDesc:i,cloneComponent:t}}function ve(i={}){let e=c(i.size,S),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}},o=l(i);return h(t,i,()=>ve(o))}function xe(i={}){let e={shape:{type:"sphere",radius:i.radius??1}},t=l(i);return h(e,i,()=>xe(t))}function Ee(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>Ee(n))}function Oe(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>Oe(n))}function Pe(i={}){let e=Math.max(i.radiusTop??1,i.radiusBottom??1),o={shape:{type:"cylinder",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>Pe(n))}function Re(i={}){let e=i.radius??.5,o={shape:{type:"capsule",halfHeight:(i.length??1)/2,radius:e}},n=l(i);return h(o,i,()=>Re(n))}function Be(i={}){let e=L(i.tile,{x:10,y:10}),t=i.subdivisions??10,o=(t+1)*(t+1),n=i.heightData??new Float32Array(o),s={shape:{type:"heightfield",rows:t,cols:t,heights:n,scale:[e.x,1,e.y]}},r={...i,static:i.static??!0},a=l(r);return h(s,r,()=>Be(a))}function we(i={}){let e=c(i.size,S),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]},sensor:!0},o={...i,static:i.static??!0,sensor:!0},n=l(o);return h(t,o,()=>we(n))}import{Mesh as ae,ShaderMaterial as Ve,Group as ze}from"three";var Q=import.meta.env.VITE_DEBUG_FLAG==="true";import{nanoid as Se}from"nanoid";var p=class i{parent=null;children=[];options;uuid="";name="";markedForRemoval=!1;lifecycleCallbacks={setup:[],loaded:[],update:[],destroy:[],cleanup:[]};trackLifecycleRegistrations=!1;userLifecycleRegistrations=[];constructor(e=[]){let t=e.filter(o=>!(o instanceof i)).reduce((o,n)=>({...o,...n}),{});this.options=t,this.uuid=Se()}onSetup(...e){return this.lifecycleCallbacks.setup.push(...e),this.recordLifecycleRegistration("onSetup",e),this}onLoaded(...e){return this.lifecycleCallbacks.loaded.push(...e),this.recordLifecycleRegistration("onLoaded",e),this}onUpdate(...e){return this.lifecycleCallbacks.update.push(...e),this.recordLifecycleRegistration("onUpdate",e),this}onDestroy(...e){return this.lifecycleCallbacks.destroy.push(...e),this.recordLifecycleRegistration("onDestroy",e),this}onCleanup(...e){return this.lifecycleCallbacks.cleanup.push(...e),this.recordLifecycleRegistration("onCleanup",e),this}prependSetup(...e){return this.lifecycleCallbacks.setup.unshift(...e),this.recordLifecycleRegistration("prependSetup",e),this}prependUpdate(...e){return this.lifecycleCallbacks.update.unshift(...e),this.recordLifecycleRegistration("prependUpdate",e),this}setParent(e){this.parent=e}getParent(){return this.parent}add(e){this.children.push(e),e.setParent(this)}remove(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),e.setParent(null))}getChildren(){return this.children}isComposite(){return this.children.length>0}enableUserLifecycleTracking(){this.trackLifecycleRegistrations=!0}replayUserLifecycleRegistrationsTo(e,t){for(let o of this.userLifecycleRegistrations){let n=t?o.callbacks.map(s=>t(s)):[...o.callbacks];switch(o.method){case"onSetup":e.onSetup(...n);break;case"onLoaded":e.onLoaded(...n);break;case"onUpdate":e.onUpdate(...n);break;case"onDestroy":e.onDestroy(...n);break;case"onCleanup":e.onCleanup(...n);break;case"prependSetup":e.prependSetup(...n);break;case"prependUpdate":e.prependUpdate(...n);break}}}cloneChildrenInto(e){for(let t of this.children)e.add(Me(t))}nodeSetup(e){this.markedForRemoval=!1,typeof this._setup=="function"&&this._setup(e);for(let t of this.lifecycleCallbacks.setup)t(e);this.children.forEach(t=>t.nodeSetup(e))}nodeUpdate(e){if(!this.markedForRemoval){typeof this._update=="function"&&this._update(e),typeof this._tickActions=="function"&&this._tickActions(e.delta);for(let t of this.lifecycleCallbacks.update)t(e);this.children.forEach(t=>t.nodeUpdate(e))}}nodeDestroy(e){if(!this.markedForRemoval){this.children.forEach(t=>t.nodeDestroy(e));for(let t of this.lifecycleCallbacks.destroy)t(e);typeof this._destroy=="function"&&this._destroy(e),this.markedForRemoval=!0;for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}}async nodeLoaded(e){typeof this._loaded=="function"&&await this._loaded(e);for(let t of this.lifecycleCallbacks.loaded)t(e)}nodeCleanup(e){this.children.forEach(t=>t.nodeCleanup?.(e));for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}getOptions(){return this.options}setOptions(e){this.options={...this.options,...e}}recordLifecycleRegistration(e,t){!this.trackLifecycleRegistrations||t.length===0||this.userLifecycleRegistrations.push({method:e,callbacks:[...t]})}};function Me(i){let e=i?.clone;if(typeof e!="function")throw new Error(`Cannot clone child node "${i.name||i.uuid||"unknown"}": missing clone() support.`);return e.call(i)}import{createTransformStore as Fe}from"@zylem/behaviors/core";import{makeMoveable as ke}from"@zylem/behaviors/core";function q(i){let e=ke(i);return X(e)}import{clearVelocityIntent as le}from"@zylem/behaviors/core";import{Color as Ie,Vector3 as Ge}from"three";import{Quaternion as De}from"three";var J=Symbol("explicitSpawnPosition"),O=new De;function ee(i){return i.filter(e=>!(e instanceof p)).some(e=>e!=null&&typeof e=="object"&&"position"in e)}function te(i){i[J]=!0}function Te(i){return i._spawnPositionExplicit?!0:i.options[J]===!0}function _e(i){return i.options.hideUntilPositioned!==!1}function ie(i){return i._spawnPlacementPending===!0}function Ae(i){return i._spawnPositionExplicit===!0||i._spawnPlacementReady===!0}function P(i){let e=i.group??i.mesh;if(e){if(i.physicsAttached&&i.body)try{let t=i.body.translation();e.position.set(t.x,t.y,t.z);return}catch{}if(i.wasmStageRef&&(i.runtimeHandle??-1)>=0){let t=i.wasmStageRef.getPose(i.runtimeHandle);if(t){e.position.set(t.position[0],t.position[1],t.position[2]);return}}if(i.options.position){let t=c(i.options.position,m);e.position.set(t.x,t.y,t.z)}}}function oe(i){let e=i.group??i.mesh;if(!(!e||i.controlledRotation)){if(i.physicsAttached&&i.body)try{let t=i.body.rotation();O.set(t.x,t.y,t.z,t.w),e.setRotationFromQuaternion(O);return}catch{}if(i.wasmStageRef&&(i.runtimeHandle??-1)>=0){let t=i.wasmStageRef.getPose(i.runtimeHandle);t&&(O.set(t.rotation[0],t.rotation[1],t.rotation[2],t.rotation[3]),e.setRotationFromQuaternion(O))}}}function v(i,e){i.group&&(i.group.visible=e),i.mesh&&(i.mesh.visible=e)}function yt(i){if(i._spawnInProgress=!0,i._spawnPlacementReady=!1,!_e(i)){i._spawnPlacementPending=!1;return}i._spawnPositionExplicit=Te(i),i._spawnPlacementPending=!0,v(i,!1)}function bt(i){i._spawnInProgress=!1}function ne(i){i._spawnPlacementReady=!0}function D(i){if(i._spawnPlacementPending){if(P(i),i._spawnPlacementPending=!1,i.options.visible===!1){v(i,!1);return}v(i,!0)}}function Ct(i){!ie(i)||i.options.hideUntilPositioned===!0&&!Ae(i)||D(i)}function se(i){P(i),i._spawnPlacementPending=!1,v(i,!0)}function gt(i){ie(i)&&v(i,!1)}var re={position:new Ge(0,0,0),material:{color:new Ie("#ffffff"),shader:H},collision:{static:!1}};function Bt(i,e){let t=i.filter(n=>!(n instanceof p)),o=d(e);for(let n of t)o=d(o,n);return ee(i)&&te(o),o}function Le(i){return i!=null&&typeof i=="object"}function ce(i){return{phase:i?.phase??"stay",cooldownMs:i?.cooldownMs}}function Ue(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var T=class extends p{group;mesh;materials;bodyDesc=null;body=null;physicsAttached=!1;physicsWorldRef=null;colliderDesc;custom={};colliderBaseline=null;colliderScaleDirty=!1;colliderDescs=[];compoundMeshes=[];debugInfo={};debugMaterial;collisionDelegate={collision:[],cooldowns:new Map,nextId:0};collisionType;packKey=null;bundleKey=null;instanceId=-1;isInstanced=!1;isBundled=!1;runtimeHandle=-1;runtimeAttached=!1;wasmStageRef=null;eventDelegate=new G;behaviorRefs=[];cloneFactory=null;trackAddedComponents=!1;trackedComponents=[];transformStore;_scale={x:1,y:1,z:1};_spawnPlacementPending=!1;_spawnPositionExplicit=!1;_spawnPlacementReady=!1;_spawnInProgress=!1;moveX;moveY;moveZ;moveXY;moveXZ;move;resetVelocity;moveForwardXY;getPosition;getVelocity;setPosition;setPositionX;setPositionY;setPositionZ;wrapAroundXY;wrapAround3D;rotateInDirection;rotateYEuler;rotateEuler;rotateX;rotateY;rotateZ;setRotationY;setRotationX;setRotationZ;setRotationDegrees;setRotationDegreesY;setRotationDegreesX;setRotationDegreesZ;setRotation;getRotation;constructor(){super(),this.transformStore=Fe(),q(this),this.wrapSpawnPlacementMutators()}wrapSpawnPlacementMutators(){let e=()=>{ne(this),!this._spawnInProgress&&(P(this),D(this))},t=r=>(a,f,y)=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(r(a,f,y),e())},o=r=>a=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(r(a),e())};this.setPosition=t(this.setPosition.bind(this)),this.setPositionX=o(this.setPositionX.bind(this)),this.setPositionY=o(this.setPositionY.bind(this)),this.setPositionZ=o(this.setPositionZ.bind(this));let n=()=>{this._spawnInProgress||oe(this)},s=this.setPose.bind(this);this.setPose=r=>{let a=s(r);return a&&(r.position!=null&&e(),r.rotation!=null&&n(),a)}}reveal(){this.options.visible=!0,se(this)}getPose(){if(this.wasmStageRef&&this.runtimeHandle>=0){let n=this.wasmStageRef.getPose(this.runtimeHandle);if(n)return{position:{x:n.position[0],y:n.position[1],z:n.position[2]},rotation:{x:n.rotation[0],y:n.rotation[1],z:n.rotation[2],w:n.rotation[3]}}}let e=this.body;if(!e)return null;let t=e.translation(),o=e.rotation();return{position:{x:t.x,y:t.y,z:t.z},rotation:{x:o.x,y:o.y,z:o.z,w:o.w}}}setPose(e){if(this.wasmStageRef&&this.runtimeHandle>=0){let o=!0;if(e.position){let n=c(e.position);o=this.wasmStageRef.setPosition(this.runtimeHandle,n.x,n.y,n.z)&&o}if(e.rotation){let{x:n,y:s,z:r,w:a}=e.rotation;o=this.wasmStageRef.setRotation(this.runtimeHandle,n,s,r,a)&&o}return o&&this.body?.markPoseDiscontinuity(),o}let t=this.body;if(!t)return!1;if(e.position){let o=c(e.position);t.setTranslation({x:o.x,y:o.y,z:o.z},!0)}return e.rotation&&t.setRotation(e.rotation,!0),!0}getScale(){return{...this._scale}}setScale(e,t,o){this._scale={x:e,y:t,z:o},(this.group??this.mesh)?.scale.set(e,t,o),this.colliderScaleDirty=!0}add(...e){for(let t of e)t instanceof ae?(this.addMeshComponent(t),this.trackComponent(t)):$(t)?(this.addCollisionComponent(t),this.trackComponent(t)):super.add(t);return this}addMeshComponent(e){if(this.mesh)this.compoundMeshes.push(e),this.group||(this.group=new ze,this.group.add(this.mesh)),this.group.add(e);else if(this.mesh=e,this.materials||(this.materials=[]),e.material){let t=e.material;Array.isArray(t)?this.materials.push(...t):this.materials.push(t)}}addCollisionComponent(e){if(this.bodyDesc)this.colliderDescs.push(e.colliderDesc);else{this.bodyDesc=e.bodyDesc,this.colliderDesc=e.colliderDesc,this.colliderDescs.push(e.colliderDesc);let t=c(this.options?.position,m);this.bodyDesc.position=[t.x,t.y,t.z]}}trackComponent(e){if(this.trackAddedComponents){if(e instanceof ae){this.trackedComponents.push({kind:"mesh",component:pe(e)});return}this.trackedComponents.push({kind:"collision",component:k(e)})}}_actions=[];runAction(e){return this._actions.push(e),e}action(e){return e.persistent=!0,this._actions.push(e),e}clearActions(){this._actions.length=0}_tickActions(e){if(this._actions.length===0)return;let t=this.transformStore;t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,le(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1;for(let o=this._actions.length-1;o>=0;o--){let n=this._actions[o];n.tick(this,e),n.done&&!n.persistent&&this._actions.splice(o,1)}this._actions.length===0&&(t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,le(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1)}create(){return this.name=this.options.name||"",this}clone(e){if(!this.cloneFactory)throw new Error(`Cannot clone ${this.constructor.name}: clone() is only supported for entities created by official factory helpers.`);let t=this.cloneFactory(d(this.options,e)),o=this.copyBehaviorRefsTo(t),n=r=>He(r,o);this.replayUserLifecycleRegistrationsTo(t,n);let s=this.getCollisionRegistrations();if(s.length>0)for(let r of s)t.onCollision(n(r.callback),r.options);for(let r of this.trackedComponents){if(r.kind==="mesh"){t.add(pe(r.component));continue}t.add(k(r.component))}return this.cloneChildrenInto(t),t}finalizeCloneSupport(e){return this.cloneFactory=e,this.enableUserLifecycleTracking(),this.trackAddedComponents=!0,this}onCollision(...e){let t=[...this.collisionDelegate.collision??[]],o=this.collisionDelegate.nextId??0;if(e.length===1||e.length===2&&(e[1]==null||Le(e[1]))){let n=e[0];if(!n)return this;let s=e[1];return t.push({id:o,callback:n,options:ce(s)}),o+=1,this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}for(let n of e)t.push({id:o,callback:n,options:ce()}),o+=1;return this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}use(e,t){let o={descriptor:e,options:{...e.defaultOptions,...t}};this.behaviorRefs.push(o);let n={getFSM:()=>o.fsm??null,getOptions:()=>o.options,ref:o},s=e.createHandle?.(o)??{};return{...n,...s}}getBehaviorRefs(){return this.behaviorRefs}getBehaviorRef(e){return this.behaviorRefs.find(t=>t.descriptor.key===e.key)??null}hasBehavior(e){return this.getBehaviorRef(e)!==null}removeBehavior(e){let t="descriptor"in e?this.behaviorRefs.indexOf(e):this.behaviorRefs.findIndex(n=>n.descriptor.key===e.key);if(t===-1)return null;let[o]=this.behaviorRefs.splice(t,1);return o??null}restoreBehaviorRef(e){this.behaviorRefs.includes(e)||this.behaviorRefs.push(e)}getCollisionCallbacks(){return this.getCollisionRegistrations().map(e=>e.callback)}getCollisionRegistrations(){return(this.collisionDelegate.collision??[]).map(e=>({id:e.id,callback:e.callback,options:{...e.options}}))}copyBehaviorRefsTo(e){let t=new Map;for(let o of this.behaviorRefs){e.use(o.descriptor,l(o.options));let n=e.getBehaviorRefs().at(-1);n&&t.set(o,n)}return t}_setup(e){for(let t=this._actions.length-1;t>=0;t--){let o=this._actions[t];o.done&&!o.persistent?this._actions.splice(t,1):o.reset()}}async _loaded(e){}_update(e){this.updateMaterials(e)}_destroy(e){}_cleanup(e){this.disposeEvents();for(let t of this.compoundMeshes)t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(o=>o.dispose()):t.material?.dispose();this.compoundMeshes.length=0,this.debugMaterial?.dispose(),this.debugMaterial=void 0,this.group?.removeFromParent()}_collision(e,t,o={phase:"stay",nowMs:Ue()}){if(!this.collisionDelegate.collision?.length)return;let n=this.collisionDelegate.cooldowns??new Map;this.collisionDelegate.cooldowns=n;for(let s of this.collisionDelegate.collision){if(s.options.phase!==o.phase)continue;let r=s.options.cooldownMs;if(r!=null){let a=`${s.id}:${e.uuid}`,f=n.get(a);if(f!=null&&o.nowMs-f<r)continue;n.set(a,o.nowMs)}s.callback({entity:this,other:e,globals:t})}}hasMaterial(){return this.mesh!==void 0||this.compoundMeshes.length>0}getMaterials(){return this.materials?[...this.materials]:[]}setMaterial(e,t={}){if(!this.hasMaterial())return null;let o=new E,n=this.constructor.type??Symbol.for("zylem:entity");return o.build(e,n),this.replaceMaterials(o.materials,t)}replaceMaterials(e,t={}){if(!this.hasMaterial()||e.length===0)return null;let{disposePrevious:o=!0}=t,n=this.materials?[...this.materials]:[],s=r=>{Array.isArray(r.material)?r.material=r.material.map((a,f)=>e[f%e.length]):r.material=e[0]};this.mesh&&s(this.mesh);for(let r of this.compoundMeshes)s(r);if(this.materials=[...e],o)for(let r of n)e.includes(r)||r.dispose();return n}updateMaterials(e){if(this.materials?.length)for(let t of this.materials)t instanceof Ve&&t.uniforms&&t.uniforms.iTime&&(t.uniforms.iTime.value+=e.delta)}buildInfo(){let e={};return e.name=this.name,e.uuid=this.uuid,e}dispatch(e,t){this.eventDelegate.dispatch(e,t),V.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}disposeEvents(){this.eventDelegate.dispose()}};function Ne(i){let e=new T;return e.options={...re,...i},_(e,t=>Ne(t??{}))}function pe(i){let e=i.clone(!0),t=[],o=[];i.traverse(n=>t.push(n)),e.traverse(n=>o.push(n));for(let n=0;n<t.length;n++){let s=t[n],r=o[n];s?.geometry?.clone&&(r.geometry=s.geometry.clone()),s?.material&&(r.material=Array.isArray(s.material)?s.material.map(a=>a.clone()):s.material.clone())}return e}function He(i,e){return e.size===0?i:((...t)=>{let o=Array.from(e.entries()).map(([n,s])=>({sourceRef:n,options:n.options,fsm:n.fsm,hasFSM:Object.prototype.hasOwnProperty.call(n,"fsm"),targetRef:s}));for(let n of o)n.sourceRef.options=n.targetRef.options,n.targetRef.fsm===void 0?delete n.sourceRef.fsm:n.sourceRef.fsm=n.targetRef.fsm;try{return i(...t)}finally{for(let n=o.length-1;n>=0;n--){let s=o[n];s.sourceRef.options=s.options,s.hasFSM?s.sourceRef.fsm=s.fsm:delete s.sourceRef.fsm}}})}function _(i,e){return i.finalizeCloneSupport(e),i}function ue(i){return typeof i?.load=="function"&&typeof i?.data=="function"}var R=class{entityReference;constructor(e){this.entityReference=e}load(){this.entityReference.load&&this.entityReference.load()}data(){return this.entityReference.data?this.entityReference.data():null}};function ei(i){let{args:e,defaultConfig:t,EntityClass:o,BuilderClass:n,entityType:s,MeshBuilderClass:r,CollisionBuilderClass:a,cloneFactory:f}=i,y=null,b,A=e.findIndex(u=>!(u instanceof p));A!==-1&&(b=e.splice(A,1).find(C=>!(C instanceof p)));let ye=b?d(t,b):d(t);e.push(ye);for(let u of e){if(u instanceof p)continue;let C=null,w=new o(u);try{if(ue(w)){let x=new R(w);x.load(),C=x.data()}}catch(x){console.error("Error creating entity with loader:",x)}y=new n(u,w,r?new r(C):null,a?new a(C):null),u.material&&y.withMaterial(u.material,s)}if(!y)throw new Error(`missing options for ${String(s)}, builder is not initialized.`);let I=y.build();return b!=null&&typeof b=="object"&&"position"in b&&(I._spawnPositionExplicit=!0),_(I,u=>f(u))}import{BufferGeometry as Ze,Mesh as de,Color as je}from"three";import{Mesh as Xe}from"three";var B=class{_build(e,t,o){let n=new Xe(t,o.at(-1));return n.position.set(0,0,0),n.castShadow=!0,n.receiveShadow=!0,n}_postBuild(){}};var fe=class extends j{},me=class extends B{build(e){return new Ze}postBuild(){}},he=class{meshBuilder;collisionBuilder;materialBuilder;options;entity;constructor(e,t,o,n){this.options=e,this.entity=t,this.meshBuilder=o,this.collisionBuilder=n,this.materialBuilder=new E;let s={meshBuilder:this.meshBuilder,collisionBuilder:this.collisionBuilder,materialBuilder:this.materialBuilder};this.options._builders=s,t&&t.options&&(t.options._builders=s)}withPosition(e){return this.options.position=e,this}withMaterial(e,t){return this.materialBuilder&&this.materialBuilder.build(e,t),this}applyMaterialToGroup(e,t){e.traverse(o=>{o instanceof de&&o.type==="SkinnedMesh"&&t[0]&&!o.material.map&&(o.material=t[0]),o.castShadow=!0,o.receiveShadow=!0})}build(){let e=this.entity;if(this.materialBuilder&&(e.materials=this.materialBuilder.materials),this.meshBuilder&&e.materials){let t=this.meshBuilder.build(this.options);e.mesh=this.meshBuilder._build(this.options,t,e.materials),this.meshBuilder.postBuild()}if(e.group&&e.materials&&this.applyMaterialToGroup(e.group,e.materials),this.collisionBuilder){this.collisionBuilder.withCollision(this.options?.collision||{});let[t,o]=this.collisionBuilder.build(this.options);e.bodyDesc=t,e.colliderDesc=o,e.colliderDescs.push(o);let{x:n,y:s,z:r}=c(this.options.position,m);e.bodyDesc.position=[n,s,r]}if(this.options.collisionType&&(e.collisionType=this.options.collisionType),this.options.color instanceof je){let t=o=>{let n=o;n&&n.color&&n.color.set&&n.color.set(this.options.color)};if(e.materials?.length)for(let o of e.materials)t(o);if(e.mesh&&e.mesh.material){let o=e.mesh.material;Array.isArray(o)?o.forEach(t):t(o)}e.group&&e.group.traverse(o=>{if(o instanceof de&&o.material){let n=o.material;Array.isArray(n)?n.forEach(t):t(n)}})}return e}};export{p as a,d as b,ve as c,xe as d,Ee as e,Oe as f,Pe as g,Re as h,Be as i,we as j,ie as k,P as l,yt as m,bt as n,Ct as o,se as p,gt as q,re as r,Bt as s,T as t,Ne as u,_ as v,fe as w,me as x,he as y,ei as z};
@@ -1 +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()),lookMode:t.Optional(t.Union([t.Literal("delta"),t.Literal("screenCenter")])),maxLookDegrees:t.Optional(t.Number()),lookSensitivity: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)."}),L=i.Tuple([i.Number(),i.Number(),i.Number()],{title:"Vec3Components"}),E=i.Object({meshopt:i.Optional(i.Boolean()),ktx2TranscoderPath:i.Optional(i.String())},{title:"StageGLTFAssetLoaderConfig",additionalProperties:!1}),V=i.Object({gltf:i.Optional(E)},{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(L),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,L as w,E as x,V as y,G as z,c as A,N as B,P as C};
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}),N=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"}),f=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}),O=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([O,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(f),pointerLock:t.Optional(t.Boolean()),sensitivity:t.Optional(t.Number()),lookMode:t.Optional(t.Union([t.Literal("delta"),t.Literal("screenCenter")])),maxLookDegrees:t.Optional(t.Number()),lookSensitivity: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)."}),L=i.Tuple([i.Number(),i.Number(),i.Number()],{title:"Vec3Components"}),D=i.Object({meshopt:i.Optional(i.Boolean()),ktx2TranscoderPath:i.Optional(i.String())},{title:"StageGLTFAssetLoaderConfig",additionalProperties:!1}),E=i.Object({gltf:i.Optional(D)},{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(L),variables:i.Optional(i.Record(i.String(),i.Unknown())),physicsRate:i.Optional(i.Number({exclusiveMinimum:0})),assetLoaders:i.Optional(E),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"}),V=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(V),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,N as c,S as d,m as e,g as f,u as g,h,B as i,y as j,f as k,a as l,p as m,O 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,L as w,D as x,E as y,G as z,c as A,V as B,P as C};
@@ -1 +1 @@
1
- import{a as f}from"./chunk-BMRFDDMR.js";import{b as u,r as C,s as V,t as d,v as G,w as U,y as v,z as b}from"./chunk-SAQA4SXW.js";import{e as D}from"./chunk-7NYP4YAG.js";import{c as h,d as y,h as m,i as E,j as x}from"./chunk-7WRQ2UAN.js";import{Color as B,Group as st,Sprite as ot,SpriteMaterial as at,CanvasTexture as H,LinearFilter as w,Vector2 as pt,ClampToEdgeWrapping as W}from"three";var g={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 pt(24,24),zDistance:1},O=class extends v{createEntity(t){return new _(t)}},lt=Symbol("Text"),_=class i extends d{static type=lt;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=u(g,t),this.options.screenPosition=E(this.options.screenPosition,g.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 st,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w;let t=new at({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new ot(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,n,s){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${n}`;let r=this._ctx.measureText(t),o=Math.ceil(r.width),a=Math.ceil(e*1.4),p=Math.max(2,o+s*2),l=Math.max(2,a+s*2),T=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:T}}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 H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w,this._texture.wrapS=W,this._texture.wrapT=W),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??g.fontFamily,s=this.options.padding??4,{sizeChanged:r}=this.measureAndResizeCanvas(t,e,n,s);this.drawCenteredText(t,e,n),this.updateTexture(!!r),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof B?t:new B(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 s=t.x>=0&&t.x<=1,r=t.y>=0&&t.y<=1;return{px:s?t.x*e:t.x,py:r?t.y*n:t.y}}computeWorldExtents(t,e){let n=1,s=1;if(t.isPerspectiveCamera){let r=t,o=Math.tan(r.fov*Math.PI/180/2)*e;n=o*r.aspect,s=o}else if(t.isOrthographicCamera){let r=t;n=(r.right-r.left)/2,s=(r.top-r.bottom)/2}return{worldHalfW:n,worldHalfH:s}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let s=t*2/e,r=this._canvas.height,o=Math.max(1e-4,r*s),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),s=n*t;this._sprite.scale.set(s,n,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:n}=this.getResolution(),s=E(this.options.screenPosition,g.screenPosition),{px:r,py:o}=this.getScreenPixels(s,e,n),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:p,worldHalfH:l}=this.computeWorldExtents(t,a),T=r/e*2-1,it=1-o/n*2,nt=T*p,rt=it*l;this.group?.position.set(nt,rt,-a),this.updateSpriteScale(l,n)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new f(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 F(...i){return b({args:i,defaultConfig:{...g},EntityClass:_,BuilderClass:O,entityType:_.type,cloneFactory:t=>F(t??{})})}import{Euler as ct,Group as X,Quaternion as ht,Vector3 as mt}from"three";import{TextureLoader as N,SpriteMaterial as Y,Sprite as $,SRGBColorSpace as j}from"three";import{ClampToEdgeWrapping as Q,LinearFilter as ut,NearestFilter as dt}from"three";var q={...C,size:new mt(1,1,1),images:[],animations:[]},L=class extends U{collider(t){let e=x(t.collisionSize,t.size??y);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},I=class extends v{createEntity(t){return new S(t)}},ft=Symbol("Sprite"),S=class i extends d{static type=ft;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;sheetTexture=null;flippedX=!1;constructor(t){super(),this.options=u(q,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.sheetTexture=null,this.group=void 0,this.options?.sheet?this.createSpriteFromSheet(this.options.sheet):this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new N,n=x(this.options.size,y);t.forEach((s,r)=>{let o=e.load(s.file);o.colorSpace=j,o.anisotropy=D;let a=new Y({map:o,transparent:!0}),p=new $(a);p.position.normalize(),p.scale.set(n.x,n.y,n.z),p.visible=r===0,this.sprites.push(p),this.spriteMap.set(s.name,r)}),this.group=new X,this.group.add(...this.sprites)}createSpriteFromSheet(t){let e=x(this.options.size,y),n=new N().load(t.file);n.colorSpace=j,n.wrapS=Q,n.wrapT=Q;let s=t.filter==="linear"?ut:dt;n.magFilter=s,n.minFilter=s,n.generateMipmaps=!1,n.repeat.set(1/t.columns,1/t.rows);let r=new Y({map:n,transparent:!0}),o=new $(r);o.position.normalize(),o.scale.set(e.x,e.y,e.z),this.sheetTexture=n,this.sprites.push(o),t.frames.forEach((p,l)=>{p&&this.spriteMap.set(p,l)}),this.group=new X,this.group.add(o);let a=t.frames.find(p=>!!p);a&&this.setSprite(a)}createAnimations(t){t.forEach(e=>{let{name:n,frames:s,loop:r=!1,speed:o=1}=e,a={frames:s.map((p,l)=>({key:p,index:l,duration:typeof o=="number"?o:o[l]})),loop:r};this.animations.set(n,a)})}setSprite(t){let n=this.spriteMap.get(t)??0;if(this.currentSpriteIndex=n,this.sheetTexture){this.applySheetFrame(n);return}this.sprites.forEach((s,r)=>{s.visible=this.currentSpriteIndex===r})}setFlipX(t){if(this.flippedX!==t){if(this.flippedX=t,this.sheetTexture){this.applySheetFrame(this.currentSpriteIndex);return}this.sprites.forEach(e=>{e.material.map?.repeat.setX(t?-1:1),e.material.map?.offset.setX(t?1:0)})}}isFlippedX(){return this.flippedX}applySheetFrame(t){let e=this.options.sheet,n=this.sheetTexture;if(!e||!n)return;let s=t%e.columns,r=Math.floor(t/e.columns),o=1/e.columns,a=1/e.rows;n.repeat.x=this.flippedX?-o:o,n.offset.x=this.flippedX?(s+1)*o:s*o,n.offset.y=1-(r+1)*a}setAnimation(t,e){let n=this.animations.get(t);if(!n)return;let{loop:s,frames:r}=n;if(r.length!==0){for(t!==this.currentAnimation?(this.currentAnimation=t,this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime+=e;;){let o=r[this.currentAnimationIndex].duration;if(!(o>0)||this.currentAnimationTime<o)break;if(this.currentAnimationTime-=o,this.currentAnimationIndex+1<r.length)this.currentAnimationIndex++;else if(s)this.currentAnimationIndex=0;else{this.currentAnimationTime=0;break}}this.currentAnimationFrame=r[this.currentAnimationIndex].key,this.setSprite(this.currentAnimationFrame)}}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 s=new ht(t.x,t.y,t.z,t.w),r=new ct().setFromQuaternion(s,"XYZ");e.material.rotation=r.z}let n=x(this.options.size,y);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(),this.sheetTexture?.dispose(),this.sheetTexture=null}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type)}}};function z(...i){return b({args:i,defaultConfig:q,EntityClass:S,BuilderClass:I,CollisionBuilderClass:L,entityType:S.type,cloneFactory:t=>z(t??{})})}import{Color as tt,Group as xt}from"three";import{Line2NodeMaterial as gt}from"three/webgpu";import{Line2 as _t}from"three/addons/lines/webgpu/Line2.js";import{Color as J}from"three";import{LineGeometry as yt}from"three/addons/lines/LineGeometry.js";function R(i){let t=[];for(let e of i){let{x:n,y:s,z:r}=m(e,h);t.push(n,s,r)}return t}function P(i,t,e){if(!i||i.length===0)return;let n=[],s=new J(e);for(let r=0;r<t;r++){let o=i[r]??i[i.length-1]??e,a=new J(o??s);n.push(a.r,a.g,a.b)}return n}function K(i){let t=new yt,e=R(i.points);t.setPositions(e);let n=P(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var c={...C,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},St=Symbol("Line");function Z(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function et(i){return i instanceof tt?i.clone():new tt(i??"#ffffff")}function Ct(i){let t=!!i.colors?.length,e=new gt({color:et(i.color).getHex(),linewidth:i.linewidth??c.linewidth,worldUnits:i.worldUnits??c.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??c.dashSize,gapSize:i.gapSize??c.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function vt(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 bt(i,t,e={}){let n=t.getLineObject();if(!n)return null;let s=e.threshold??t.options.pickThreshold??0,r=i.params.Line2??{threshold:0};r.threshold=s,i.params.Line2=r;let a=i.intersectObject(n,!1)[0];return a?vt(a):null}var A=class i extends d{static type=St;_line=null;_geometry=null;_material=null;constructor(t){super();let e=u(c,t);e.points=Z(e.points,"ZylemLine").map(n=>m(n,h)),this.options=e}create(){return this.disposeLineResources(),this.group=new xt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(Z(t,"setPoints"),this.options.points=t.map(s=>m(s,h)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(R(this.options.points));let n=P(this.options.colors,this.options.points.length,et(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 bt(t,this,e)}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??c.linewidth,worldUnits:this.options.worldUnits??c.worldUnits}}rebuildLine(){this._geometry=K({points:this.options.points,colors:this.options.colors}),this._material=Ct(this.options),this._line=new _t(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=m(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 M(...i){let t=V(i,c);Z(t.points,"createLine");let e=new A(t);return G(e,n=>M(n??{}))}var k={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)}};k.register("text",i=>F(i));k.register("sprite",i=>z(i));k.register("line",i=>M(i));function ge(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{lt as a,_ as b,F as c,ft as d,S as e,z as f,St as g,bt as h,A as i,M as j,k,ge as l};
1
+ import{a as f}from"./chunk-STVEILJJ.js";import{b as u,r as C,s as G,t as d,v as D,w as U,y as v,z as b}from"./chunk-KP6DLLJO.js";import{e as V}from"./chunk-6FGXC4T6.js";import{c as h,d as y,h as m,i as E,j as x}from"./chunk-7WRQ2UAN.js";import{Color as B,Group as st,Sprite as ot,SpriteMaterial as at,CanvasTexture as H,LinearFilter as w,Vector2 as pt,ClampToEdgeWrapping as W}from"three";var g={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 pt(24,24),zDistance:1},O=class extends v{createEntity(t){return new _(t)}},lt=Symbol("Text"),_=class i extends d{static type=lt;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=u(g,t),this.options.screenPosition=E(this.options.screenPosition,g.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 st,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w;let t=new at({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new ot(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,n,s){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${n}`;let r=this._ctx.measureText(t),o=Math.ceil(r.width),a=Math.ceil(e*1.4),p=Math.max(2,o+s*2),l=Math.max(2,a+s*2),T=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:T}}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 H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w,this._texture.wrapS=W,this._texture.wrapT=W),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??g.fontFamily,s=this.options.padding??4,{sizeChanged:r}=this.measureAndResizeCanvas(t,e,n,s);this.drawCenteredText(t,e,n),this.updateTexture(!!r),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof B?t:new B(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 s=t.x>=0&&t.x<=1,r=t.y>=0&&t.y<=1;return{px:s?t.x*e:t.x,py:r?t.y*n:t.y}}computeWorldExtents(t,e){let n=1,s=1;if(t.isPerspectiveCamera){let r=t,o=Math.tan(r.fov*Math.PI/180/2)*e;n=o*r.aspect,s=o}else if(t.isOrthographicCamera){let r=t;n=(r.right-r.left)/2,s=(r.top-r.bottom)/2}return{worldHalfW:n,worldHalfH:s}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let s=t*2/e,r=this._canvas.height,o=Math.max(1e-4,r*s),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),s=n*t;this._sprite.scale.set(s,n,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:n}=this.getResolution(),s=E(this.options.screenPosition,g.screenPosition),{px:r,py:o}=this.getScreenPixels(s,e,n),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:p,worldHalfH:l}=this.computeWorldExtents(t,a),T=r/e*2-1,it=1-o/n*2,nt=T*p,rt=it*l;this.group?.position.set(nt,rt,-a),this.updateSpriteScale(l,n)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new f(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 F(...i){return b({args:i,defaultConfig:{...g},EntityClass:_,BuilderClass:O,entityType:_.type,cloneFactory:t=>F(t??{})})}import{Euler as ct,Group as X,Quaternion as ht,Vector3 as mt}from"three";import{TextureLoader as N,SpriteMaterial as Y,Sprite as $,SRGBColorSpace as j}from"three";import{ClampToEdgeWrapping as Q,LinearFilter as ut,NearestFilter as dt}from"three";var q={...C,size:new mt(1,1,1),images:[],animations:[]},L=class extends U{collider(t){let e=x(t.collisionSize,t.size??y);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},I=class extends v{createEntity(t){return new S(t)}},ft=Symbol("Sprite"),S=class i extends d{static type=ft;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;sheetTexture=null;flippedX=!1;constructor(t){super(),this.options=u(q,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.sheetTexture=null,this.group=void 0,this.options?.sheet?this.createSpriteFromSheet(this.options.sheet):this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new N,n=x(this.options.size,y);t.forEach((s,r)=>{let o=e.load(s.file);o.colorSpace=j,o.anisotropy=V;let a=new Y({map:o,transparent:!0}),p=new $(a);p.position.normalize(),p.scale.set(n.x,n.y,n.z),p.visible=r===0,this.sprites.push(p),this.spriteMap.set(s.name,r)}),this.group=new X,this.group.add(...this.sprites)}createSpriteFromSheet(t){let e=x(this.options.size,y),n=new N().load(t.file);n.colorSpace=j,n.wrapS=Q,n.wrapT=Q;let s=t.filter==="linear"?ut:dt;n.magFilter=s,n.minFilter=s,n.generateMipmaps=!1,n.repeat.set(1/t.columns,1/t.rows);let r=new Y({map:n,transparent:!0}),o=new $(r);o.position.normalize(),o.scale.set(e.x,e.y,e.z),this.sheetTexture=n,this.sprites.push(o),t.frames.forEach((p,l)=>{p&&this.spriteMap.set(p,l)}),this.group=new X,this.group.add(o);let a=t.frames.find(p=>!!p);a&&this.setSprite(a)}createAnimations(t){t.forEach(e=>{let{name:n,frames:s,loop:r=!1,speed:o=1}=e,a={frames:s.map((p,l)=>({key:p,index:l,duration:typeof o=="number"?o:o[l]})),loop:r};this.animations.set(n,a)})}setSprite(t){let n=this.spriteMap.get(t)??0;if(this.currentSpriteIndex=n,this.sheetTexture){this.applySheetFrame(n);return}this.sprites.forEach((s,r)=>{s.visible=this.currentSpriteIndex===r})}setFlipX(t){if(this.flippedX!==t){if(this.flippedX=t,this.sheetTexture){this.applySheetFrame(this.currentSpriteIndex);return}this.sprites.forEach(e=>{e.material.map?.repeat.setX(t?-1:1),e.material.map?.offset.setX(t?1:0)})}}isFlippedX(){return this.flippedX}applySheetFrame(t){let e=this.options.sheet,n=this.sheetTexture;if(!e||!n)return;let s=t%e.columns,r=Math.floor(t/e.columns),o=1/e.columns,a=1/e.rows;n.repeat.x=this.flippedX?-o:o,n.offset.x=this.flippedX?(s+1)*o:s*o,n.offset.y=1-(r+1)*a}setAnimation(t,e){let n=this.animations.get(t);if(!n)return;let{loop:s,frames:r}=n;if(r.length!==0){for(t!==this.currentAnimation?(this.currentAnimation=t,this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime+=e;;){let o=r[this.currentAnimationIndex].duration;if(!(o>0)||this.currentAnimationTime<o)break;if(this.currentAnimationTime-=o,this.currentAnimationIndex+1<r.length)this.currentAnimationIndex++;else if(s)this.currentAnimationIndex=0;else{this.currentAnimationTime=0;break}}this.currentAnimationFrame=r[this.currentAnimationIndex].key,this.setSprite(this.currentAnimationFrame)}}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 s=new ht(t.x,t.y,t.z,t.w),r=new ct().setFromQuaternion(s,"XYZ");e.material.rotation=r.z}let n=x(this.options.size,y);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(),this.sheetTexture?.dispose(),this.sheetTexture=null}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type)}}};function z(...i){return b({args:i,defaultConfig:q,EntityClass:S,BuilderClass:I,CollisionBuilderClass:L,entityType:S.type,cloneFactory:t=>z(t??{})})}import{Color as tt,Group as xt}from"three";import{Line2NodeMaterial as gt}from"three/webgpu";import{Line2 as _t}from"three/addons/lines/webgpu/Line2.js";import{Color as J}from"three";import{LineGeometry as yt}from"three/addons/lines/LineGeometry.js";function R(i){let t=[];for(let e of i){let{x:n,y:s,z:r}=m(e,h);t.push(n,s,r)}return t}function P(i,t,e){if(!i||i.length===0)return;let n=[],s=new J(e);for(let r=0;r<t;r++){let o=i[r]??i[i.length-1]??e,a=new J(o??s);n.push(a.r,a.g,a.b)}return n}function K(i){let t=new yt,e=R(i.points);t.setPositions(e);let n=P(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var c={...C,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},St=Symbol("Line");function Z(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function et(i){return i instanceof tt?i.clone():new tt(i??"#ffffff")}function Ct(i){let t=!!i.colors?.length,e=new gt({color:et(i.color).getHex(),linewidth:i.linewidth??c.linewidth,worldUnits:i.worldUnits??c.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??c.dashSize,gapSize:i.gapSize??c.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function vt(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 bt(i,t,e={}){let n=t.getLineObject();if(!n)return null;let s=e.threshold??t.options.pickThreshold??0,r=i.params.Line2??{threshold:0};r.threshold=s,i.params.Line2=r;let a=i.intersectObject(n,!1)[0];return a?vt(a):null}var A=class i extends d{static type=St;_line=null;_geometry=null;_material=null;constructor(t){super();let e=u(c,t);e.points=Z(e.points,"ZylemLine").map(n=>m(n,h)),this.options=e}create(){return this.disposeLineResources(),this.group=new xt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(Z(t,"setPoints"),this.options.points=t.map(s=>m(s,h)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(R(this.options.points));let n=P(this.options.colors,this.options.points.length,et(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 bt(t,this,e)}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??c.linewidth,worldUnits:this.options.worldUnits??c.worldUnits}}rebuildLine(){this._geometry=K({points:this.options.points,colors:this.options.colors}),this._material=Ct(this.options),this._line=new _t(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=m(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 M(...i){let t=G(i,c);Z(t.points,"createLine");let e=new A(t);return D(e,n=>M(n??{}))}var k={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)}};k.register("text",i=>F(i));k.register("sprite",i=>z(i));k.register("line",i=>M(i));function ge(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{lt as a,_ as b,F as c,ft as d,S as e,z as f,St as g,bt as h,A as i,M as j,k,ge as l};