@zylem/game-lib 0.8.2 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions.d.ts +5 -5
- package/dist/api/game-lib.api.json +2079 -1214
- package/dist/api/game-lib.api.md +150 -97
- package/dist/api/game-lib.d.ts +321 -95
- package/dist/api/game-lib.typedoc.json +141279 -214520
- package/dist/bridge.d.ts +111 -0
- package/dist/bridge.js +1 -0
- package/dist/{chunk-KVSJE4XD.js → chunk-3I537JFL.js} +1 -1
- package/dist/chunk-4CHZUWLF.js +1 -0
- package/dist/chunk-6B5JP7T5.js +24 -0
- package/dist/chunk-AIQ6IVT5.js +1 -0
- package/dist/chunk-C5NEGC3S.js +1 -0
- package/dist/chunk-D3JO4HW2.js +1 -0
- package/dist/chunk-HNCTOJP7.js +1 -0
- package/dist/chunk-LKFF6XJC.js +1 -0
- package/dist/{chunk-CD7ZOZ35.js → chunk-OAWK2UUY.js} +1 -1
- package/dist/chunk-PNLNC3FA.js +1 -0
- package/dist/chunk-TV3AZKT4.js +9 -0
- package/dist/chunk-VIPINV7V.js +19 -0
- package/dist/chunk-W5SXED5T.js +1 -0
- package/dist/{chunk-YAOXFYOD.js → chunk-WBQ5TNRZ.js} +1 -1
- package/dist/{collision-builder-B_tm8OVy.d.ts → collision-builder-4TVDzXsp.d.ts} +1 -1
- package/dist/core.d.ts +11 -11
- package/dist/core.js +1 -1
- package/dist/debug-state-s0s-qndj.d.ts +49 -0
- package/dist/debug.d.ts +32 -7
- package/dist/debug.js +1 -1
- package/dist/{entity-BGEq1yfC.d.ts → entity-BI7cSlK8.d.ts} +3 -3
- package/dist/{entity-B9yZeBm4.d.ts → entity-DDks47JB.d.ts} +1 -1
- package/dist/{entity-type-map-CW6RHQkx.d.ts → entity-type-map-COHu4fkW.d.ts} +41 -7
- package/dist/entity.d.ts +7 -7
- package/dist/entity.js +1 -1
- package/dist/events.d.ts +1 -64
- package/dist/events.js +1 -1
- package/dist/{game-DbqBQiFC.d.ts → game-4fsy55uN.d.ts} +55 -27
- package/dist/game-default-4PPYYGAR.js +1 -0
- package/dist/graphics.d.ts +5 -5
- package/dist/{material-DbSuZBbP.d.ts → material-BKPYeBC6.d.ts} +1 -1
- package/dist/public.d.ts +12 -10
- package/dist/public.js +1 -1
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.js +1 -1
- package/dist/{vector-DN6zlPoE.d.ts → vector-DPbwlzgG.d.ts} +10 -2
- package/dist/web-components.d.ts +9 -9
- package/dist/web-components.js +1 -1
- package/dist/{zylem-camera-Du2UPW9O.d.ts → zylem-camera-B73ZNcgs.d.ts} +1 -1
- package/package.json +20 -14
- package/LICENSE +0 -21
- package/dist/chunk-3PRBSSTS.js +0 -24
- package/dist/chunk-CFVRRRZZ.js +0 -1
- package/dist/chunk-COM6HJ2L.js +0 -1
- package/dist/chunk-JQKS42G4.js +0 -1
- package/dist/chunk-MZZCDXFB.js +0 -1
- package/dist/chunk-TAUWDQZF.js +0 -9
- package/dist/chunk-VS2D4B3W.js +0 -1
- package/dist/chunk-YHEWKN7N.js +0 -1
- package/dist/debug-state-DRoeasG2.d.ts +0 -17
- package/dist/game-default-6AZZCNST.js +0 -1
package/dist/bridge.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { GameConfigPayload, GameLoadingPayload, GameVariablePayload, GameNoticePayload, StageSnapshotPayload, EntitySummaryPayload, EntityThumbnailPayload } from '@zylem/bridge';
|
|
2
|
+
export { BRIDGE_READY_EVENT, BridgeChannel, BridgeDebugTool, BridgeHandler, GameLoadingPayload as BridgeLoadingPayload, BridgeMessageType, BridgeMessages, BridgeVec3, EditorToGameMessages, EntitySummaryPayload, EntityThumbnailPayload, GameConfigPayload, GameToEditorMessages, GameVariablePayload, StageConfigPayload, StageSnapshotPayload, ZylemBridge, announceBridgeReady, getZylemBridge } from '@zylem/bridge';
|
|
3
|
+
import { G as GameEntity } from './entity-BI7cSlK8.js';
|
|
4
|
+
import 'three';
|
|
5
|
+
import '@zylem/behaviors/core';
|
|
6
|
+
import './vector-DPbwlzgG.js';
|
|
7
|
+
import './material-BKPYeBC6.js';
|
|
8
|
+
import 'three/webgpu';
|
|
9
|
+
import './collision-builder-4TVDzXsp.js';
|
|
10
|
+
import './base-node-life-cycle-BK9xebT9.js';
|
|
11
|
+
import './stage-transition-CmGpV4tc.js';
|
|
12
|
+
import './events.js';
|
|
13
|
+
import 'mitt';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Game-side adapter for the shared editor ↔ game bridge.
|
|
17
|
+
*
|
|
18
|
+
* Owns the editor→game command subscriptions (debug/tool/playback, entity
|
|
19
|
+
* select/focus/transform, stage variables) and exposes typed publish helpers
|
|
20
|
+
* the running game uses to stream config, stage snapshots, entity upserts,
|
|
21
|
+
* and thumbnails to the editor. High-frequency publishes go through the
|
|
22
|
+
* channel's `queue`, which coalesces to at most one message per animation
|
|
23
|
+
* frame.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Host context supplied by the running game so bridge commands can act on
|
|
28
|
+
* live stage state without the bridge importing game internals.
|
|
29
|
+
*/
|
|
30
|
+
interface GameBridgeHost {
|
|
31
|
+
/** Resolve a live entity by UUID from the current stage. */
|
|
32
|
+
resolveEntity(uuid: string): GameEntity<any> | null;
|
|
33
|
+
/** Write a stage variable (editor `stage:variable:set`). */
|
|
34
|
+
setStageVariable?(key: string, value: unknown): void;
|
|
35
|
+
}
|
|
36
|
+
declare class GameBridge {
|
|
37
|
+
private channel;
|
|
38
|
+
private unsubscribes;
|
|
39
|
+
private host;
|
|
40
|
+
/**
|
|
41
|
+
* Values the editor is already known to hold, either because it commanded
|
|
42
|
+
* them or because we published them. Anything matching here is skipped, so
|
|
43
|
+
* an editor command can never echo back as a game update.
|
|
44
|
+
*/
|
|
45
|
+
private editorKnown;
|
|
46
|
+
constructor();
|
|
47
|
+
/**
|
|
48
|
+
* Subscribe to editor commands and announce the game side as ready.
|
|
49
|
+
* @param host Live-game context for entity/stage lookups
|
|
50
|
+
* @param announceTarget DOM node the `zylem:bridge:ready` event bubbles from
|
|
51
|
+
*/
|
|
52
|
+
connect(host: GameBridgeHost, announceTarget?: EventTarget): void;
|
|
53
|
+
disconnect(): void;
|
|
54
|
+
/**
|
|
55
|
+
* Publish only the parts of `debugState` the editor does not already know.
|
|
56
|
+
* Values that arrived as editor commands are recorded on `editorKnown`
|
|
57
|
+
* first, so they are never echoed back.
|
|
58
|
+
*/
|
|
59
|
+
private publishDebugStateChanges;
|
|
60
|
+
/**
|
|
61
|
+
* Whether anything is listening for entity list updates. Building entity
|
|
62
|
+
* summaries is pure editor overhead, so publishers skip it when no editor
|
|
63
|
+
* is attached.
|
|
64
|
+
*/
|
|
65
|
+
wantsEntityUpdates(): boolean;
|
|
66
|
+
/**
|
|
67
|
+
* Whether anything is listening for thumbnails. Each thumbnail costs an
|
|
68
|
+
* offscreen render plus a pixel readback on the renderer the game draws
|
|
69
|
+
* with, so this gate matters far more than the others.
|
|
70
|
+
*/
|
|
71
|
+
wantsThumbnails(): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Run a callback when an editor first subscribes to entity data, so the
|
|
74
|
+
* game can backfill state produced while nothing was listening.
|
|
75
|
+
*
|
|
76
|
+
* An editor takes out both entity subscriptions as it mounts, and each is
|
|
77
|
+
* a first-subscriber transition. Backfilling on both would republish the
|
|
78
|
+
* config, the whole stage snapshot, and every thumbnail twice per mount,
|
|
79
|
+
* so a signal is ignored while the other entity type still has a
|
|
80
|
+
* listener — that is the same editor finishing its setup, not a new one.
|
|
81
|
+
*
|
|
82
|
+
* @returns An unsubscribe function.
|
|
83
|
+
*/
|
|
84
|
+
onEditorAttached(callback: () => void): () => void;
|
|
85
|
+
publishConfig(config: GameConfigPayload): void;
|
|
86
|
+
publishLoading(payload: GameLoadingPayload): void;
|
|
87
|
+
publishStatus(status: {
|
|
88
|
+
paused?: boolean;
|
|
89
|
+
debug?: boolean;
|
|
90
|
+
}): void;
|
|
91
|
+
/**
|
|
92
|
+
* Publish a global's new value.
|
|
93
|
+
*
|
|
94
|
+
* Sent rather than queued: a queued payload is merged into the pending one
|
|
95
|
+
* for its type, and since each message names a single `path`, two globals
|
|
96
|
+
* changing in the same frame would collapse into one and the first
|
|
97
|
+
* variable's update would never reach the editor.
|
|
98
|
+
*/
|
|
99
|
+
publishVariable(payload: GameVariablePayload): void;
|
|
100
|
+
/** Surface a diagnostic message in the editor console. */
|
|
101
|
+
publishNotice(level: GameNoticePayload['level'], message: string): void;
|
|
102
|
+
publishStageSnapshot(snapshot: StageSnapshotPayload): void;
|
|
103
|
+
/** RAF-coalesced entity add/update stream; merged by uuid per frame. */
|
|
104
|
+
queueEntityUpsert(entities: EntitySummaryPayload[]): void;
|
|
105
|
+
/** RAF-coalesced entity removal stream. */
|
|
106
|
+
queueEntityRemoved(uuids: string[]): void;
|
|
107
|
+
/** RAF-coalesced thumbnail stream; merged by uuid per frame. */
|
|
108
|
+
queueThumbnails(thumbnails: EntityThumbnailPayload[]): void;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export { GameBridge, type GameBridgeHost };
|
package/dist/bridge.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as b,b as c,c as d}from"./chunk-HNCTOJP7.js";import{c as a}from"./chunk-D3JO4HW2.js";import"./chunk-LKFF6XJC.js";import"./chunk-W5SXED5T.js";export{d as BRIDGE_READY_EVENT,a as GameBridge,c as announceBridgeReady,b as getZylemBridge};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as V,d as ve,e as G,j as Se}from"./chunk-CM5YRNBJ.js";import{a as de,b as he}from"./chunk-YHEWKN7N.js";import{a as Q,b as Ce,c as xe}from"./chunk-EVYHPR3J.js";import{c as v,d as D,e as me,f as fe,g as ye,h as f,i as be,j as L}from"./chunk-7WRQ2UAN.js";import{p as ge}from"./chunk-XRP4JJXL.js";import{StageBodyKind as _e}from"@zylem/behaviors/core";import{Color as st,Vector2 as Oe,Vector3 as Ee}from"three";function F(i){if(!i||typeof i!="object")return!1;let e=Object.getPrototypeOf(i);return e===Object.prototype||e===null}function y(i){if(i==null||typeof i=="function"||typeof i!="object")return i;if(i instanceof st||i instanceof Oe||i instanceof Ee)return i.clone();if(i instanceof Float32Array)return new Float32Array(i);if(Array.isArray(i))return i.map(e=>y(e));if(F(i)){let e={};for(let[t,o]of Object.entries(i))t!=="_builders"&&(e[t]=y(o));return e}return i}function S(i,e){let t=y(i);if(!e)return t;if(!F(t)||!F(e))return y(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]=y(s);continue}if(r instanceof Oe&&me(s)){o[n]=be(s,r);continue}if(r instanceof Ee&&fe(s)){o[n]=L(s,r);continue}if(F(r)&&F(s)){o[n]=S(r,s);continue}o[n]=y(s)}return o}function Me(i){return i&&i.__kind==="collision"}function ee(i){return i.cloneComponent()}function rt(i,e){let t={kind:i?_e.Static:_e.Dynamic,position:[0,0,0],gravityScale:e.gravityScale??1,canSleep:e.canSleep??!1,ccdEnabled:e.ccdEnabled??!0},o=Q(e.lockRotations);o&&(t.lockRotation=o);let n=Q(e.lockTranslations);return n&&(t.lockTranslation=n),t}function at(i,e){if(e.offset){let t=f(e.offset,v);i.offset=[t.x,t.y,t.z]}e.sensor&&(i.sensor=!0),e.collisionType&&(i.collisionGroups=Ce(e.collisionType,e.collisionFilter))}function _(i,e,t){return at(i,e),{__kind:"collision",bodyDesc:rt(e.static??!1,e),colliderDesc:i,cloneComponent:t}}function lt(i={}){let e=f(i.size,D),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}},o=y(i);return _(t,i,()=>lt(o))}function ct(i={}){let e={shape:{type:"sphere",radius:i.radius??1}},t=y(i);return _(e,i,()=>ct(t))}function ut(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>ut(n))}function pt(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>pt(n))}function dt(i={}){let e=Math.max(i.radiusTop??1,i.radiusBottom??1),o={shape:{type:"cylinder",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>dt(n))}function ht(i={}){let e=i.radius??.5,o={shape:{type:"capsule",halfHeight:(i.length??1)/2,radius:e}},n=y(i);return _(o,i,()=>ht(n))}function mt(i={}){let e=ye(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=y(r);return _(s,r,()=>mt(a))}function ft(i={}){let e=f(i.size,D),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=y(o);return _(t,o,()=>ft(n))}import{Mesh as ze,ShaderMaterial as Et,Group as _t}from"three";var Ae=import.meta.env.VITE_DEBUG_FLAG==="true";import{nanoid as yt}from"nanoid";var C=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=yt()}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(bt(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 bt(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 Mt}from"@zylem/behaviors/core";import{makeMoveable as gt}from"@zylem/behaviors/core";function Pe(i){let e=gt(i);return ge(e)}import{clearVelocityIntent as je}from"@zylem/behaviors/core";import{Color as St,Vector3 as Ot}from"three";var we=Symbol("explicitSpawnPosition");function De(i){return i.filter(e=>!(e instanceof C)).some(e=>e!=null&&typeof e=="object"&&"position"in e)}function Be(i){i[we]=!0}function Ct(i){return i._spawnPositionExplicit?!0:i.options[we]===!0}function xt(i){return i.options.hideUntilPositioned!==!1}function Re(i){return i._spawnPlacementPending===!0}function vt(i){return i._spawnPositionExplicit===!0||i._spawnPlacementReady===!0}function U(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=f(i.options.position,v);e.position.set(t.x,t.y,t.z)}}}function T(i,e){i.group&&(i.group.visible=e),i.mesh&&(i.mesh.visible=e)}function Hi(i){if(i._spawnInProgress=!0,i._spawnPlacementReady=!1,!xt(i)){i._spawnPlacementPending=!1;return}i._spawnPositionExplicit=Ct(i),i._spawnPlacementPending=!0,T(i,!1)}function Yi(i){i._spawnInProgress=!1}function Fe(i){i._spawnPlacementReady=!0}function te(i){if(i._spawnPlacementPending){if(U(i),i._spawnPlacementPending=!1,i.options.visible===!1){T(i,!1);return}T(i,!0)}}function Wi(i){!Re(i)||i.options.hideUntilPositioned===!0&&!vt(i)||te(i)}function Te(i){U(i),i._spawnPlacementPending=!1,T(i,!0)}function ke(i){Re(i)&&T(i,!1)}var N={position:new Ot(0,0,0),material:{color:new St("#ffffff"),shader:V},collision:{static:!1}};function eo(i,e){let t=i.filter(n=>!(n instanceof C)),o=S(e);for(let n of t)o=S(o,n);return De(i)&&Be(o),o}function At(i){return i!=null&&typeof i=="object"}function Ie(i){return{phase:i?.phase??"stay",cooldownMs:i?.cooldownMs}}function Pt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var P=class extends C{group;mesh;materials;bodyDesc=null;body=null;physicsAttached=!1;physicsWorldRef=null;colliderDesc;custom={};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 de;behaviorRefs=[];cloneFactory=null;trackAddedComponents=!1;trackedComponents=[];transformStore;_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=Mt(),Pe(this),this.wrapSpawnPlacementMutators()}wrapSpawnPlacementMutators(){let e=()=>{Fe(this),!this._spawnInProgress&&(U(this),te(this))},t=s=>(r,a,l)=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(s(r,a,l),e())},o=s=>r=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(s(r),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.setPose.bind(this);this.setPose=s=>{let r=n(s);return r&&s.position!=null&&e(),r}}reveal(){this.options.visible=!0,Te(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=f(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}let t=this.body;if(!t)return!1;if(e.position){let o=f(e.position);t.setTranslation({x:o.x,y:o.y,z:o.z},!0)}return e.rotation&&t.setRotation(e.rotation,!0),!0}add(...e){for(let t of e)t instanceof ze?(this.addMeshComponent(t),this.trackComponent(t)):Me(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 _t,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=f(this.options?.position,v);this.bodyDesc.position=[t.x,t.y,t.z]}}trackComponent(e){if(this.trackAddedComponents){if(e instanceof ze){this.trackedComponents.push({kind:"mesh",component:Le(e)});return}this.trackedComponents.push({kind:"collision",component:ee(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,je(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,je(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(S(this.options,e)),o=this.copyBehaviorRefsTo(t),n=r=>Dt(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(Le(r.component));continue}t.add(ee(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||At(e[1]))){let n=e[0];if(!n)return this;let s=e[1];return t.push({id:o,callback:n,options:Ie(s)}),o+=1,this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}for(let n of e)t.push({id:o,callback:n,options:Ie()}),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}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,y(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:Pt()}){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}`,l=n.get(a);if(l!=null&&o.nowMs-l<r)continue;n.set(a,o.nowMs)}s.callback({entity:this,other:e,globals:t})}}updateMaterials(e){if(this.materials?.length)for(let t of this.materials)t instanceof Et&&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),he.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}disposeEvents(){this.eventDelegate.dispose()}};function wt(i){let e=new P;return e.options={...N,...i},ie(e,t=>wt(t??{}))}function Le(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 Dt(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 ie(i,e){return i.finalizeCloneSupport(e),i}function Ve(i){return typeof i?.load=="function"&&typeof i?.data=="function"}var Z=class{entityReference;constructor(e){this.entityReference=e}load(){this.entityReference.load&&this.entityReference.load()}data(){return this.entityReference.data?this.entityReference.data():null}};function Ge(i){let{args:e,defaultConfig:t,EntityClass:o,BuilderClass:n,entityType:s,MeshBuilderClass:r,CollisionBuilderClass:a,cloneFactory:l}=i,p=null,d,c=e.findIndex(b=>!(b instanceof C));c!==-1&&(d=e.splice(c,1).find(h=>!(h instanceof C)));let u=d?S(t,d):S(t);e.push(u);for(let b of e){if(b instanceof C)continue;let h=null,R=new o(b);try{if(Ve(R)){let I=new Z(R);I.load(),h=I.data()}}catch(I){console.error("Error creating entity with loader:",I)}p=new n(b,R,r?new r(h):null,a?new a(h):null),b.material&&p.withMaterial(b.material,s)}if(!p)throw new Error(`missing options for ${String(s)}, builder is not initialized.`);let m=p.build();return d!=null&&typeof d=="object"&&"position"in d&&(m._spawnPositionExplicit=!0),ie(m,b=>l(b))}import{Box3 as le,BufferAttribute as Vt,SkinnedMesh as Gt,MeshStandardMaterial as Ut,Group as Nt,Vector3 as M,Matrix4 as Ke}from"three";var B=class{async loadFile(e,t){switch(ve(e)){case"fbx":{let n=await G.loadFBX(e,t);return{object:n.object,animation:n.animations?.[0]}}case"gltf":case"glb":{let n=await G.loadGLTF(e,t);return{object:n.object,gltf:n.gltf}}case"obj":return{object:(await G.loadOBJ(e,t)).object};default:throw new Error(`Unsupported file type: ${e}`)}}};import{AnimationMixer as Bt,Bone as Ue,LoopOnce as Rt,LoopRepeat as Ft}from"three";function Tt(i){let e=i.lastIndexOf(".");return e>=0?i.slice(0,e):i}function Ne(i,e){if(!i?.name?.endsWith(".position"))return!1;let t=Tt(i.name),o=e.get(t);return o instanceof Ue?!(o.parent instanceof Ue):/hips\.position$/i.test(i.name)||/root\.position$/i.test(i.name)}function kt(i,e,t,o){for(let n of i.tracks){if(!Ne(n,e)||!n.values||n.values.length<3)continue;let s=n.values[0],r=o??n.values[1],a=n.values[2];for(let l=0;l<n.values.length;l+=3)n.values[l]=s,t&&(n.values[l+1]=r),n.values[l+2]=a}return i}function zt(i,e){for(let t of i.tracks)if(Ne(t,e)&&!(!t.values||t.values.length<3))return t.values[1];return null}var H=class{constructor(e){this.target=e}_mixer=null;_actions={};_animations=[];_currentAction=null;_pauseAtPercentage=0;_isPaused=!1;_queuedKey=null;_fadeDuration=.5;_currentKey="";_assetLoader=new B;async loadAnimations(e,t={}){if(!e.length)return;let o=t.stripRootMotionY??!1,n=t.referenceRootY,s=t.referenceAnimationPath,r=await Promise.all(e.map(c=>this._assetLoader.loadFile(c.path))),a=new Map;this.target.traverse(c=>{c.name&&a.set(c.name,c)});let l=[];if(r.forEach((c,u)=>{c.animation&&l.push({key:e[u].key||u.toString(),clip:c.animation,path:e[u].path})}),!l.length)return;let p=n;if(o&&p===void 0){let c=s?l.findIndex(m=>m.path===s):0,u=c>=0?[c,...l.map((m,g)=>g).filter(m=>m!==c)]:l.map((m,g)=>g);for(let m of u){let g=zt(l[m].clip,a);if(g!==null){p=g;break}}}let d=l.map(({key:c,clip:u})=>({key:c,clip:kt(u,a,o,p)}));this._animations=d.map(c=>c.clip),this._mixer=new Bt(this.target),d.forEach(({key:c,clip:u})=>{this._actions[c]=this._mixer.clipAction(u)}),this.playAnimation({key:d[0].key})}update(e){if(!this._mixer||!this._currentAction)return;this._mixer.update(e);let t=this._currentAction.getClip().duration*(this._pauseAtPercentage/100);if(!this._isPaused&&this._pauseAtPercentage>0&&this._currentAction.time>=t&&(this._currentAction.time=t,this._currentAction.paused=!0,this._isPaused=!0,this._queuedKey!==null)){let o=this._actions[this._queuedKey];o.reset().play(),this._currentAction.crossFadeTo(o,this._fadeDuration,!1),this._currentAction=o,this._currentKey=this._queuedKey,this._queuedKey=null}}playAnimation(e){if(!this._mixer)return;let{key:t,pauseAtPercentage:o=0,pauseAtEnd:n=!1,fadeToKey:s,fadeDuration:r=.5}=e;if(t===this._currentKey)return;let a=this._actions[t];if(!a)return;if(a===this._currentAction){this._currentKey=t;return}this._queuedKey=s||null,this._fadeDuration=r,this._pauseAtPercentage=n?100:o,this._isPaused=!1;let l=this._currentAction;this._pauseAtPercentage>0?(a.setLoop(Rt,1/0),a.clampWhenFinished=!0):(a.setLoop(Ft,1/0),a.clampWhenFinished=!1),a.reset().play(),l&&l.crossFadeTo(a,r,!1),this._currentAction=a,this._currentKey=t}dispose(){Object.values(this._actions).forEach(e=>{e.stop()}),this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this.target),this._mixer=null),this._actions={},this._animations=[],this._currentAction=null,this._currentKey=""}get currentAnimationKey(){return this._currentKey}get animations(){return this._animations}};import{BufferGeometry as It,Mesh as Ze,Color as Lt}from"three";import{Mesh as jt}from"three";var Y=class{_build(e,t,o){let n=new jt(t,o.at(-1));return n.position.set(0,0,0),n.castShadow=!0,n.receiveShadow=!0,n}_postBuild(){}};var W=class extends xe{},He=class extends Y{build(e){return new It}postBuild(){}},K=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 Se;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 Ze&&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}=f(this.options.position,v);e.bodyDesc.position=[n,s,r]}if(this.options.collisionType&&(e.collisionType=this.options.collisionType),this.options.color instanceof Lt){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 Ze&&o.material){let n=o.material;Array.isArray(n)?n.forEach(t):t(n)}})}return e}};var Xe={...N,material:{shader:V},animations:[],models:[],collisionShape:"capsule"};function k(i){return L(i.scale,D)}var Zt=1e-4,Ht=/foot$/i,oe=new M,q=new M,Ye=new M,X=new M,We=new Ke;function Yt(i){let e=1/0,t=!1;return i.traverse(o=>{if(!o.isSkinnedMesh)return;let n=o,s=n.geometry,r=s.attributes.position,a=s.attributes.skinIndex,l=s.attributes.skinWeight,p=n.skeleton;if(!r||!a||!l||!p)return;t=!0,p.update(),n.updateMatrixWorld(!0);let d=p.boneMatrices;if(d)for(let c=0;c<r.count;c++){Ye.fromBufferAttribute(r,c).applyMatrix4(n.bindMatrix),X.set(0,0,0);for(let u=0;u<4;u++){let m=l.getComponent(c,u);if(m===0)continue;let g=a.getComponent(c,u);We.fromArray(d,g*16),X.addScaledVector(q.copy(Ye).applyMatrix4(We),m)}X.applyMatrix4(n.bindMatrixInverse).applyMatrix4(n.matrixWorld),e=Math.min(e,X.y)}}),!t||!Number.isFinite(e)?null:e}function Wt(i,e){e.updateMatrixWorld(!0);let t=e.getWorldPosition(oe).y,o=Yt(i)??1/0;if(i.traverse(n=>{!n.isBone||!Ht.test(n.name)||(n.getWorldPosition(oe),o=Math.min(o,oe.y))}),Number.isFinite(o)||i.traverse(n=>{if(!n.isSkinnedMesh)return;let s=n;if(s.computeBoundingBox(),!s.boundingBox)return;let{min:r,max:a}=s.boundingBox;for(let l of[[r.x,r.y,r.z],[r.x,r.y,a.z],[r.x,a.y,r.z],[r.x,a.y,a.z],[a.x,r.y,r.z],[a.x,r.y,a.z],[a.x,a.y,r.z],[a.x,a.y,a.z]])q.set(l[0],l[1],l[2]),q.applyMatrix4(s.matrixWorld),o=Math.min(o,q.y)}),!Number.isFinite(o)){let n=new le().setFromObject(i);if(n.isEmpty())return null;o=n.min.y}return o-t}function Kt(i,e,t){return i.stripRootMotionY!==void 0?i.stripRootMotionY:!!(e&&t.some(o=>o===e))}function j(i){let e=i.collision?.position;return e?f(e,v):null}function ne(i){return!!i.collision?.size}function Xt(i){i.hasWarnedDynamicTrimesh||(i.hasWarnedDynamicTrimesh=!0,console.warn(`Actor "${i.name||i.uuid}" requested collisionShape="trimesh" on a dynamic body; falling back to bounds.`))}function $e(i,e,t){let o=i==="model"?"bounds":i??"capsule";return o==="trimesh"&&!e?(t?.(),"bounds"):o}function qe(i,e){let t=i.x||.5,o=i.y||1,n=i.z||.5,s=Math.max(t,n)/2,r=o/2;return{shape:{type:"capsule",halfHeight:Math.max(0,r-s),radius:s},offset:[e.x,e.y,e.z],sensor:!1}}function w(i){let e=f(i.collision?.size??i.size,{x:.5,y:1,z:.5}),t=e.y||1,o=j(i);return qe({x:e.x||.5,y:t,z:e.z||.5},o??{x:0,y:t/2,z:0})}function Je(i){let e=i.collision?.size;if(!e)return null;let t=f(e,v),o=t.x/2,n=t.y/2,s=t.z/2,r=j(i);return{shape:{type:"box",halfExtents:[o,n,s]},offset:[r?.x??0,r?.y??n,r?.z??0],sensor:!1}}function Qe(i,e,t){let n=e.matrixWorld.clone().invert().multiply(i.matrixWorld);return new Ke().makeScale(t.x,t.y,t.z).multiply(n)}function se(i,e,t){i.updateMatrixWorld(!0);let o=!1,n=new le;if(i.traverse(a=>{if(!a.isMesh)return;let l=a,p=l.geometry;if(!p)return;let d=null;if(l instanceof Gt?(l.computeBoundingBox(),d=l.boundingBox?.clone()??null):(p.computeBoundingBox(),d=p.boundingBox?.clone()??null),!d)return;let c=d.applyMatrix4(Qe(l,e,t));if(!o){n.copy(c),o=!0;return}n.union(c)}),!o||n.isEmpty())return null;let s=new M,r=new M;return n.getSize(s),n.getCenter(r),{size:s,center:r}}function $t(i,e,t){i.updateMatrixWorld(!0);let o=[],n=[],s=new le,r=new M,a=!1;if(i.traverse(p=>{if(!p.isMesh)return;let d=p,c=d.geometry;if(!c)return;let u=c.getAttribute("position");if(!(u instanceof Vt))return;let m=Qe(d,e,t),g=o.length/3;for(let h=0;h<u.count;h++)r.set(u.getX(h),u.getY(h),u.getZ(h)),r.applyMatrix4(m),o.push(r.x,r.y,r.z),s.expandByPoint(r);let b=c.getIndex();if(b)for(let h=0;h<b.count;h++)n.push(g+b.getX(h));else for(let h=0;h<u.count;h++)n.push(g+h);a=!0}),!a||o.length===0||n.length===0)return null;let l=new M;return s.getCenter(l),{vertices:new Float32Array(o),indices:new Uint32Array(n),center:l}}function et(i,e,t){let o=Je(t);if(o)return o;if(!i||!e)return w(t);let n=se(i,e,k(t));if(!n)return w(t);let s=j(t);return{shape:{type:"box",halfExtents:[n.size.x/2,n.size.y/2,n.size.z/2]},offset:[s?.x??n.center.x,s?.y??n.center.y,s?.z??n.center.z],sensor:!1}}function tt(i,e,t,o,n){if(ne(n)||!i||!e)return w(n);let s=se(i,e,k(n));if(!s)return w(n);let a=j(n);if(!a){let l=t&&o?se(t,o,k(n)):null;a=l?{x:l.center.x,y:l.center.y,z:l.center.z}:{x:s.center.x,y:s.center.y,z:s.center.z}}return qe({x:s.size.x,y:s.size.y,z:s.size.z},a)}function it(i,e,t){let o=Je(t);if(o)return o;if(!i||!e)return w(t);let n=$t(i,e,k(t));if(!n)return w(t);let s=j(t);return{shape:{type:"trimesh",vertices:n.vertices,indices:n.indices},offset:s?[s.x-n.center.x,s.y-n.center.y,s.z-n.center.z]:[0,0,0],sensor:!1}}function $(i){i&&i.traverse(e=>{if(!e.isMesh)return;let t=e;t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(o=>o.dispose()):t.material?.dispose()})}var re=class extends W{objectModel=null;collisionSource=null;collisionShape="capsule";constructor(e){super(),this.objectModel=e.objectModel,this.collisionSource=e.collisionSource??e.objectModel??null,this.collisionShape=e.collisionShape??"capsule"}collider(e){let t=$e(this.collisionShape,!!e.collision?.static);return t==="bounds"?et(this.objectModel,this.objectModel,e):t==="trimesh"?it(this.objectModel,this.objectModel,e):tt(this.collisionSource,this.collisionSource,this.objectModel,this.objectModel,e)}},ae=class extends K{createEntity(e){return new z(e)}},qt=Symbol("Actor"),z=class extends P{static type=qt;_object=null;_collisionSource=null;_animationDelegate=null;_modelFileNames=[];_assetLoader=new B;_loadGeneration=0;_loadStatus="idle";controlledRotation=!1;hasWarnedDynamicTrimesh=!1;constructor(e){super(),this.options=S(Xe,e),this.prependUpdate(this.actorUpdate.bind(this)),this.controlledRotation=!0}create(){return this._loadStatus==="idle"&&(this.options.models?.length??0)>0&&this.load(),super.create()}load(){this._loadStatus==="loading"||this._loadStatus==="loaded"||(this._modelFileNames=[...this.options.models||[]],this._modelFileNames.length!==0&&(this.disposeRuntimeState(!0),this._loadStatus="loading",this.loadModelsDeferred(++this._loadGeneration)))}data(){return{animations:this._animationDelegate?.animations,objectModel:this._object,collisionSource:this._collisionSource??this._object,collisionShape:this.options.collisionShape}}needsDeferredModelCollision(){return this.requiresLoadedCollisionSource()?!this.getRuntimeCollisionSource():!1}synchronizeRuntimeCollider(){let e=this.getResolvedCollisionShape(),t;if(e==="bounds")t=et(this._object,this.group??this._object,this.options);else if(e==="trimesh")t=it(this._object,this.group??this._object,this.options);else{let o=this.getRuntimeCollisionSource();t=tt(o,o,this._object,this._object,this.options)}this.colliderDesc=t,this.colliderDescs.length>0?this.colliderDescs[0]=t:this.colliderDescs.push(t)}actorUpdate(e){this._animationDelegate?.update(e.delta)}actorDestroy(){this._loadGeneration+=1,this._loadStatus="idle",this.disposeRuntimeState(!0),this._modelFileNames=[]}_cleanup(e){super._cleanup(e),this.actorDestroy()}playAnimation(e){this._animationDelegate?.playAnimation(e)}get object(){return this._object}get collisionSource(){return this._collisionSource??this._object}getDebugInfo(){let e={type:"Actor",models:this._modelFileNames.length>0?this._modelFileNames:"none",modelLoaded:!!this._object,scale:(()=>{let t=f(this.options.scale,D);return`${t.x}, ${t.y}, ${t.z}`})(),collisionShape:this.getResolvedCollisionShape()};if(this._animationDelegate&&(e.currentAnimation=this._animationDelegate.currentAnimationKey||"none",e.animationsCount=this.options.animations?.length||0),this._object){let t=0,o=0;this._object.traverse(n=>{if(!n.isMesh)return;t++;let s=n.geometry;s?.attributes.position&&(o+=s.attributes.position.count)}),e.meshCount=t,e.vertexCount=o}return e}getResolvedCollisionShape(){return $e(this.options.collisionShape,!!this.options.collision?.static,()=>Xt(this))}requiresLoadedCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?!ne(this.options):e==="capsule"?!ne(this.options)&&this.getCollisionSourceSelection().file!==null:!1}getRuntimeCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?this._object:this._collisionSource??this._object}getCollisionSourceSelection(){let e=this.options.models?.[0]??null,t=this.options.animations?.[0]?.path??null;return t?{file:t,reuseVisibleModel:t===e}:{file:e,reuseVisibleModel:!0}}disposeRuntimeState(e){this._animationDelegate&&(this._animationDelegate.dispose(),this._animationDelegate=null);let t=this._collisionSource;$(this._object),t&&t!==this._object&&$(t),this._object=null,this._collisionSource=null,e&&this.group&&(this.group.clear(),this.group=void 0)}loadModelsDeferred(e){this.dispatch("entity:model:loading",{entityId:this.uuid,files:this._modelFileNames});let t=this.getCollisionSourceSelection(),o=this._modelFileNames.map(s=>this._assetLoader.loadFile(s,{clone:!0})),n=t.file&&!t.reuseVisibleModel?this._assetLoader.loadFile(t.file,{clone:!0}):Promise.resolve(null);Promise.all([Promise.all(o),n]).then(([s,r])=>{if(e!==this._loadGeneration){s.forEach(l=>$(l.object??null)),r?.object&&$(r.object);return}this._object=s[0]?.object??null,this._collisionSource=t.reuseVisibleModel?this._object:r?.object??this._object,this._loadStatus=this._object?"loaded":"idle";let a=0;if(this._object){this._object.traverse(u=>{u.isMesh&&a++}),this.group=new Nt,this.group.add(this._object),this.group.scale.copy(k(this.options)),ke(this),this.applyMaterialOverrides(),this._animationDelegate=new H(this._object);let l=this.options.animations||[],p=this.options.models?.[0],d=l.map(u=>u.path),c=Kt(this.options,p,d);l.length>0?this._animationDelegate.loadAnimations(l,{stripRootMotionY:c,referenceAnimationPath:p}).then(()=>{e===this._loadGeneration&&(this.alignVisualModelToGround(),this.dispatch("entity:animation:loaded",{entityId:this.uuid,animationCount:l.length}))}):this.alignVisualModelToGround()}this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!!this._object,meshCount:a})}).catch(s=>{e===this._loadGeneration&&(this._loadStatus="idle",console.error("Failed to load actor model",s),this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!1,meshCount:0,errorMessage:s instanceof Error?s.message:String(s)}))})}alignVisualModelToGround(){if(!this._object||!this.group)return;this._animationDelegate?.update(0),this._object.updateMatrixWorld(!0);let e=Wt(this._object,this.group);if(e===null||Math.abs(e)<Zt)return;let t=this.group.scale.y||1;this._object.position.y-=e/t}applyMaterialOverrides(){let e=this.options.material;!e||!e.color&&!e.path&&e.opacity===void 0||this._object&&this._object.traverse(t=>{if(!t.isMesh)return;let o=t;o.material=Array.isArray(o.material)?o.material.map(n=>this.tintMaterial(n,e)):this.tintMaterial(o.material,e),e.color&&(o.castShadow=!0,o.receiveShadow=!0)})}tintMaterial(e,t){let o="color"in e,n=!!t.color,s=t.opacity!==void 0;if(!n&&!s)return e;if(n&&!o)return new Ut({color:t.color,emissiveIntensity:.5,lightMapIntensity:.5,fog:!0,opacity:t.opacity??1,transparent:s&&t.opacity<1});let r=e.clone();if(n&&"color"in r&&r.color.copy(t.color),s&&"opacity"in r&&"transparent"in r){let a=r;a.opacity=t.opacity,a.transparent=t.opacity<1}return r.needsUpdate=!0,r}};function Jt(...i){return Ge({args:i,defaultConfig:Xe,EntityClass:z,BuilderClass:ae,CollisionBuilderClass:re,entityType:z.type,cloneFactory:e=>Jt(e??{})})}import{Color as li,Fog as ci,FogExp2 as ui,Group as pi}from"three";import{Color as Qt}from"three";import{Fn as nt,fog as ei,positionWorld as ot,positionView as ti,uniform as x,float as ii,vec3 as O,clamp as ce,mix as E,max as oi,smoothstep as ni,floor as si,fract as ue,dot as ri}from"three/tsl";var J=class{values;u={time:x(0),heightEnabled:x(0),heightLevel:x(0),heightFalloff:x(0),noiseEnabled:x(0),noiseScale:x(0),noiseStrength:x(0),noiseSpeed:x(0)};attachedScene=null;constructor(e){this.values={...e},this.syncUniforms()}setValues(e){Object.assign(this.values,e),this.syncUniforms()}tick(e){this.values.time+=e,this.u.time.value=this.values.time}scan(e){if(this.attachedScene===e)return;let t=e.fog;t&&(e.fogNode=this.buildFogNode(t),this.attachedScene=e)}unpatchAll(){this.attachedScene&&(this.attachedScene.fogNode=null,this.attachedScene=null)}syncUniforms(){this.u.time.value=this.values.time,this.u.heightEnabled.value=this.values.heightEnabled,this.u.heightLevel.value=this.values.heightLevel,this.u.heightFalloff.value=this.values.heightFalloff,this.u.noiseEnabled.value=this.values.noiseEnabled,this.u.noiseScale.value=this.values.noiseScale,this.u.noiseStrength.value=this.values.noiseStrength,this.u.noiseSpeed.value=this.values.noiseSpeed}buildFogNode(e){let t=e.isFogExp2===!0,o=x(new Qt(e.color)),n=ti.z.negate(),s=t?this.exp2Factor(x(e.density),n):ni(x(e.near),x(e.far),n),r=this.u.heightLevel.sub(ot.y),a=ce(r.mul(oi(this.u.heightFalloff,0)),0,1),l=E(s,s.mul(a),this.u.heightEnabled),p=ot.mul(this.u.noiseScale).add(O(this.u.time.mul(this.u.noiseSpeed),0,this.u.time.mul(this.u.noiseSpeed).mul(.5))),c=ai(p).sub(.5).mul(2).mul(ce(this.u.noiseStrength,0,1)),u=ce(l.add(l.mul(c)),0,1),m=E(l,u,this.u.noiseEnabled);return ei(o,m)}exp2Factor(e,t){return e.mul(e).mul(t).mul(t).negate().exp().oneMinus()}},A=nt(([i])=>{let e=ue(i.mul(O(443.8975,397.2973,491.1871))),t=e.add(ri(e,e.yzx.add(19.27)));return ue(t.x.add(t.y).mul(t.z))}),ai=nt(([i])=>{let e=si(i),t=ue(i),o=t.mul(t).mul(ii(3).sub(t.mul(2))),n=A(e.add(O(0,0,0))),s=A(e.add(O(1,0,0))),r=A(e.add(O(0,1,0))),a=A(e.add(O(1,1,0))),l=A(e.add(O(0,0,1))),p=A(e.add(O(1,0,1))),d=A(e.add(O(0,1,1))),c=A(e.add(O(1,1,1))),u=E(n,s,o.x),m=E(r,a,o.x),g=E(l,p,o.x),b=E(d,c,o.x),h=E(u,m,o.y),R=E(g,b,o.y);return E(h,R,o.z)});var di=Symbol("Fog"),hi="#9aa3ad",mi=.015,fi=10,yi=250,bi=5,gi=.2,Ci=.05,xi=.15,vi=.1,pe=class extends P{static type=di;threeFog=null;attachedScene=null;patcher;patcherEnabled;constructor(e={}){super(),this.options={...e};let t=this.resolveUniformValues(this.options);this.patcher=new J(t),this.patcherEnabled=Oi(this.options)}create(){return super.create(),this.threeFog=Si(this.options),this.group=new pi,this.group.name=this.name?`Fog:${this.name}`:"Fog",this}attachToScene(e){this.threeFog&&(this.attachedScene=e,e.fog=this.threeFog,this.patcherEnabled&&this.patcher.scan(e))}_update(e){super._update(e),!(!this.attachedScene||!this.patcherEnabled)&&(this.patcher.tick(e.delta),this.patcher.scan(this.attachedScene))}_cleanup(e){this.patcher.unpatchAll(),this.attachedScene&&this.attachedScene.fog===this.threeFog&&(this.attachedScene.fog=null),this.attachedScene=null,this.threeFog=null,super._cleanup(e)}resolveUniformValues(e){let t=e.height,o=e.noise;return{time:0,heightEnabled:t?.enabled?1:0,heightLevel:t?.level??bi,heightFalloff:t?.falloff??gi,noiseEnabled:o?1:0,noiseScale:o?.scale??Ci,noiseStrength:o?.strength??xi,noiseSpeed:o?.speed??vi}}};function Si(i){let e=new li(i.color??hi);return(i.type??"linear")==="exp2"?new ui(e,i.density??mi):new ci(e,i.start??fi,i.end??yi)}function Oi(i){let e=!!i.height?.enabled,t=!!i.noise;return e||t}function _n(i={}){return new pe(i)}export{C as a,S as b,lt as c,ct as d,ut as e,pt as f,dt as g,ht as h,mt as i,ft as j,Re as k,Hi as l,Yi as m,Wi as n,ke as o,N as p,eo as q,P as r,wt as s,ie as t,Ge as u,W as v,He as w,K as x,qt as y,z,Jt as A,di as B,pe as C,_n as D};
|
|
1
|
+
import{b as V,d as ve,e as G,j as Se}from"./chunk-CM5YRNBJ.js";import{a as de,b as he}from"./chunk-AIQ6IVT5.js";import{a as Q,b as Ce,c as xe}from"./chunk-EVYHPR3J.js";import{c as v,d as D,e as me,f as fe,g as ye,h as f,i as be,j as L}from"./chunk-7WRQ2UAN.js";import{p as ge}from"./chunk-XRP4JJXL.js";import{StageBodyKind as _e}from"@zylem/behaviors/core";import{Color as st,Vector2 as Oe,Vector3 as Ee}from"three";function F(i){if(!i||typeof i!="object")return!1;let e=Object.getPrototypeOf(i);return e===Object.prototype||e===null}function y(i){if(i==null||typeof i=="function"||typeof i!="object")return i;if(i instanceof st||i instanceof Oe||i instanceof Ee)return i.clone();if(i instanceof Float32Array)return new Float32Array(i);if(Array.isArray(i))return i.map(e=>y(e));if(F(i)){let e={};for(let[t,o]of Object.entries(i))t!=="_builders"&&(e[t]=y(o));return e}return i}function S(i,e){let t=y(i);if(!e)return t;if(!F(t)||!F(e))return y(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]=y(s);continue}if(r instanceof Oe&&me(s)){o[n]=be(s,r);continue}if(r instanceof Ee&&fe(s)){o[n]=L(s,r);continue}if(F(r)&&F(s)){o[n]=S(r,s);continue}o[n]=y(s)}return o}function Me(i){return i&&i.__kind==="collision"}function ee(i){return i.cloneComponent()}function rt(i,e){let t={kind:i?_e.Static:_e.Dynamic,position:[0,0,0],gravityScale:e.gravityScale??1,canSleep:e.canSleep??!1,ccdEnabled:e.ccdEnabled??!0},o=Q(e.lockRotations);o&&(t.lockRotation=o);let n=Q(e.lockTranslations);return n&&(t.lockTranslation=n),t}function at(i,e){if(e.offset){let t=f(e.offset,v);i.offset=[t.x,t.y,t.z]}e.sensor&&(i.sensor=!0),e.collisionType&&(i.collisionGroups=Ce(e.collisionType,e.collisionFilter))}function _(i,e,t){return at(i,e),{__kind:"collision",bodyDesc:rt(e.static??!1,e),colliderDesc:i,cloneComponent:t}}function lt(i={}){let e=f(i.size,D),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}},o=y(i);return _(t,i,()=>lt(o))}function ct(i={}){let e={shape:{type:"sphere",radius:i.radius??1}},t=y(i);return _(e,i,()=>ct(t))}function ut(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>ut(n))}function pt(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>pt(n))}function dt(i={}){let e=Math.max(i.radiusTop??1,i.radiusBottom??1),o={shape:{type:"cylinder",halfHeight:(i.height??2)/2,radius:e}},n=y(i);return _(o,i,()=>dt(n))}function ht(i={}){let e=i.radius??.5,o={shape:{type:"capsule",halfHeight:(i.length??1)/2,radius:e}},n=y(i);return _(o,i,()=>ht(n))}function mt(i={}){let e=ye(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=y(r);return _(s,r,()=>mt(a))}function ft(i={}){let e=f(i.size,D),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=y(o);return _(t,o,()=>ft(n))}import{Mesh as ze,ShaderMaterial as Et,Group as _t}from"three";var Ae=import.meta.env.VITE_DEBUG_FLAG==="true";import{nanoid as yt}from"nanoid";var C=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=yt()}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(bt(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 bt(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 Mt}from"@zylem/behaviors/core";import{makeMoveable as gt}from"@zylem/behaviors/core";function Pe(i){let e=gt(i);return ge(e)}import{clearVelocityIntent as je}from"@zylem/behaviors/core";import{Color as St,Vector3 as Ot}from"three";var we=Symbol("explicitSpawnPosition");function De(i){return i.filter(e=>!(e instanceof C)).some(e=>e!=null&&typeof e=="object"&&"position"in e)}function Be(i){i[we]=!0}function Ct(i){return i._spawnPositionExplicit?!0:i.options[we]===!0}function xt(i){return i.options.hideUntilPositioned!==!1}function Re(i){return i._spawnPlacementPending===!0}function vt(i){return i._spawnPositionExplicit===!0||i._spawnPlacementReady===!0}function U(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=f(i.options.position,v);e.position.set(t.x,t.y,t.z)}}}function T(i,e){i.group&&(i.group.visible=e),i.mesh&&(i.mesh.visible=e)}function Hi(i){if(i._spawnInProgress=!0,i._spawnPlacementReady=!1,!xt(i)){i._spawnPlacementPending=!1;return}i._spawnPositionExplicit=Ct(i),i._spawnPlacementPending=!0,T(i,!1)}function Yi(i){i._spawnInProgress=!1}function Fe(i){i._spawnPlacementReady=!0}function te(i){if(i._spawnPlacementPending){if(U(i),i._spawnPlacementPending=!1,i.options.visible===!1){T(i,!1);return}T(i,!0)}}function Wi(i){!Re(i)||i.options.hideUntilPositioned===!0&&!vt(i)||te(i)}function Te(i){U(i),i._spawnPlacementPending=!1,T(i,!0)}function ke(i){Re(i)&&T(i,!1)}var N={position:new Ot(0,0,0),material:{color:new St("#ffffff"),shader:V},collision:{static:!1}};function eo(i,e){let t=i.filter(n=>!(n instanceof C)),o=S(e);for(let n of t)o=S(o,n);return De(i)&&Be(o),o}function At(i){return i!=null&&typeof i=="object"}function Ie(i){return{phase:i?.phase??"stay",cooldownMs:i?.cooldownMs}}function Pt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var P=class extends C{group;mesh;materials;bodyDesc=null;body=null;physicsAttached=!1;physicsWorldRef=null;colliderDesc;custom={};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 de;behaviorRefs=[];cloneFactory=null;trackAddedComponents=!1;trackedComponents=[];transformStore;_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=Mt(),Pe(this),this.wrapSpawnPlacementMutators()}wrapSpawnPlacementMutators(){let e=()=>{Fe(this),!this._spawnInProgress&&(U(this),te(this))},t=s=>(r,a,l)=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(s(r,a,l),e())},o=s=>r=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(s(r),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.setPose.bind(this);this.setPose=s=>{let r=n(s);return r&&s.position!=null&&e(),r}}reveal(){this.options.visible=!0,Te(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=f(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}let t=this.body;if(!t)return!1;if(e.position){let o=f(e.position);t.setTranslation({x:o.x,y:o.y,z:o.z},!0)}return e.rotation&&t.setRotation(e.rotation,!0),!0}add(...e){for(let t of e)t instanceof ze?(this.addMeshComponent(t),this.trackComponent(t)):Me(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 _t,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=f(this.options?.position,v);this.bodyDesc.position=[t.x,t.y,t.z]}}trackComponent(e){if(this.trackAddedComponents){if(e instanceof ze){this.trackedComponents.push({kind:"mesh",component:Le(e)});return}this.trackedComponents.push({kind:"collision",component:ee(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,je(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,je(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(S(this.options,e)),o=this.copyBehaviorRefsTo(t),n=r=>Dt(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(Le(r.component));continue}t.add(ee(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||At(e[1]))){let n=e[0];if(!n)return this;let s=e[1];return t.push({id:o,callback:n,options:Ie(s)}),o+=1,this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}for(let n of e)t.push({id:o,callback:n,options:Ie()}),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}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,y(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:Pt()}){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}`,l=n.get(a);if(l!=null&&o.nowMs-l<r)continue;n.set(a,o.nowMs)}s.callback({entity:this,other:e,globals:t})}}updateMaterials(e){if(this.materials?.length)for(let t of this.materials)t instanceof Et&&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),he.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}disposeEvents(){this.eventDelegate.dispose()}};function wt(i){let e=new P;return e.options={...N,...i},ie(e,t=>wt(t??{}))}function Le(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 Dt(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 ie(i,e){return i.finalizeCloneSupport(e),i}function Ve(i){return typeof i?.load=="function"&&typeof i?.data=="function"}var Z=class{entityReference;constructor(e){this.entityReference=e}load(){this.entityReference.load&&this.entityReference.load()}data(){return this.entityReference.data?this.entityReference.data():null}};function Ge(i){let{args:e,defaultConfig:t,EntityClass:o,BuilderClass:n,entityType:s,MeshBuilderClass:r,CollisionBuilderClass:a,cloneFactory:l}=i,p=null,d,c=e.findIndex(b=>!(b instanceof C));c!==-1&&(d=e.splice(c,1).find(h=>!(h instanceof C)));let u=d?S(t,d):S(t);e.push(u);for(let b of e){if(b instanceof C)continue;let h=null,R=new o(b);try{if(Ve(R)){let I=new Z(R);I.load(),h=I.data()}}catch(I){console.error("Error creating entity with loader:",I)}p=new n(b,R,r?new r(h):null,a?new a(h):null),b.material&&p.withMaterial(b.material,s)}if(!p)throw new Error(`missing options for ${String(s)}, builder is not initialized.`);let m=p.build();return d!=null&&typeof d=="object"&&"position"in d&&(m._spawnPositionExplicit=!0),ie(m,b=>l(b))}import{Box3 as le,BufferAttribute as Vt,SkinnedMesh as Gt,MeshStandardMaterial as Ut,Group as Nt,Vector3 as M,Matrix4 as Ke}from"three";var B=class{async loadFile(e,t){switch(ve(e)){case"fbx":{let n=await G.loadFBX(e,t);return{object:n.object,animation:n.animations?.[0]}}case"gltf":case"glb":{let n=await G.loadGLTF(e,t);return{object:n.object,gltf:n.gltf}}case"obj":return{object:(await G.loadOBJ(e,t)).object};default:throw new Error(`Unsupported file type: ${e}`)}}};import{AnimationMixer as Bt,Bone as Ue,LoopOnce as Rt,LoopRepeat as Ft}from"three";function Tt(i){let e=i.lastIndexOf(".");return e>=0?i.slice(0,e):i}function Ne(i,e){if(!i?.name?.endsWith(".position"))return!1;let t=Tt(i.name),o=e.get(t);return o instanceof Ue?!(o.parent instanceof Ue):/hips\.position$/i.test(i.name)||/root\.position$/i.test(i.name)}function kt(i,e,t,o){for(let n of i.tracks){if(!Ne(n,e)||!n.values||n.values.length<3)continue;let s=n.values[0],r=o??n.values[1],a=n.values[2];for(let l=0;l<n.values.length;l+=3)n.values[l]=s,t&&(n.values[l+1]=r),n.values[l+2]=a}return i}function zt(i,e){for(let t of i.tracks)if(Ne(t,e)&&!(!t.values||t.values.length<3))return t.values[1];return null}var H=class{constructor(e){this.target=e}_mixer=null;_actions={};_animations=[];_currentAction=null;_pauseAtPercentage=0;_isPaused=!1;_queuedKey=null;_fadeDuration=.5;_currentKey="";_assetLoader=new B;async loadAnimations(e,t={}){if(!e.length)return;let o=t.stripRootMotionY??!1,n=t.referenceRootY,s=t.referenceAnimationPath,r=await Promise.all(e.map(c=>this._assetLoader.loadFile(c.path))),a=new Map;this.target.traverse(c=>{c.name&&a.set(c.name,c)});let l=[];if(r.forEach((c,u)=>{c.animation&&l.push({key:e[u].key||u.toString(),clip:c.animation,path:e[u].path})}),!l.length)return;let p=n;if(o&&p===void 0){let c=s?l.findIndex(m=>m.path===s):0,u=c>=0?[c,...l.map((m,g)=>g).filter(m=>m!==c)]:l.map((m,g)=>g);for(let m of u){let g=zt(l[m].clip,a);if(g!==null){p=g;break}}}let d=l.map(({key:c,clip:u})=>({key:c,clip:kt(u,a,o,p)}));this._animations=d.map(c=>c.clip),this._mixer=new Bt(this.target),d.forEach(({key:c,clip:u})=>{this._actions[c]=this._mixer.clipAction(u)}),this.playAnimation({key:d[0].key})}update(e){if(!this._mixer||!this._currentAction)return;this._mixer.update(e);let t=this._currentAction.getClip().duration*(this._pauseAtPercentage/100);if(!this._isPaused&&this._pauseAtPercentage>0&&this._currentAction.time>=t&&(this._currentAction.time=t,this._currentAction.paused=!0,this._isPaused=!0,this._queuedKey!==null)){let o=this._actions[this._queuedKey];o.reset().play(),this._currentAction.crossFadeTo(o,this._fadeDuration,!1),this._currentAction=o,this._currentKey=this._queuedKey,this._queuedKey=null}}playAnimation(e){if(!this._mixer)return;let{key:t,pauseAtPercentage:o=0,pauseAtEnd:n=!1,fadeToKey:s,fadeDuration:r=.5}=e;if(t===this._currentKey)return;let a=this._actions[t];if(!a)return;if(a===this._currentAction){this._currentKey=t;return}this._queuedKey=s||null,this._fadeDuration=r,this._pauseAtPercentage=n?100:o,this._isPaused=!1;let l=this._currentAction;this._pauseAtPercentage>0?(a.setLoop(Rt,1/0),a.clampWhenFinished=!0):(a.setLoop(Ft,1/0),a.clampWhenFinished=!1),a.reset().play(),l&&l.crossFadeTo(a,r,!1),this._currentAction=a,this._currentKey=t}dispose(){Object.values(this._actions).forEach(e=>{e.stop()}),this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this.target),this._mixer=null),this._actions={},this._animations=[],this._currentAction=null,this._currentKey=""}get currentAnimationKey(){return this._currentKey}get animations(){return this._animations}};import{BufferGeometry as It,Mesh as Ze,Color as Lt}from"three";import{Mesh as jt}from"three";var Y=class{_build(e,t,o){let n=new jt(t,o.at(-1));return n.position.set(0,0,0),n.castShadow=!0,n.receiveShadow=!0,n}_postBuild(){}};var W=class extends xe{},He=class extends Y{build(e){return new It}postBuild(){}},K=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 Se;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 Ze&&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}=f(this.options.position,v);e.bodyDesc.position=[n,s,r]}if(this.options.collisionType&&(e.collisionType=this.options.collisionType),this.options.color instanceof Lt){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 Ze&&o.material){let n=o.material;Array.isArray(n)?n.forEach(t):t(n)}})}return e}};var Xe={...N,material:{shader:V},animations:[],models:[],collisionShape:"capsule"};function k(i){return L(i.scale,D)}var Zt=1e-4,Ht=/foot$/i,oe=new M,q=new M,Ye=new M,X=new M,We=new Ke;function Yt(i){let e=1/0,t=!1;return i.traverse(o=>{if(!o.isSkinnedMesh)return;let n=o,s=n.geometry,r=s.attributes.position,a=s.attributes.skinIndex,l=s.attributes.skinWeight,p=n.skeleton;if(!r||!a||!l||!p)return;t=!0,p.update(),n.updateMatrixWorld(!0);let d=p.boneMatrices;if(d)for(let c=0;c<r.count;c++){Ye.fromBufferAttribute(r,c).applyMatrix4(n.bindMatrix),X.set(0,0,0);for(let u=0;u<4;u++){let m=l.getComponent(c,u);if(m===0)continue;let g=a.getComponent(c,u);We.fromArray(d,g*16),X.addScaledVector(q.copy(Ye).applyMatrix4(We),m)}X.applyMatrix4(n.bindMatrixInverse).applyMatrix4(n.matrixWorld),e=Math.min(e,X.y)}}),!t||!Number.isFinite(e)?null:e}function Wt(i,e){e.updateMatrixWorld(!0);let t=e.getWorldPosition(oe).y,o=Yt(i)??1/0;if(i.traverse(n=>{!n.isBone||!Ht.test(n.name)||(n.getWorldPosition(oe),o=Math.min(o,oe.y))}),Number.isFinite(o)||i.traverse(n=>{if(!n.isSkinnedMesh)return;let s=n;if(s.computeBoundingBox(),!s.boundingBox)return;let{min:r,max:a}=s.boundingBox;for(let l of[[r.x,r.y,r.z],[r.x,r.y,a.z],[r.x,a.y,r.z],[r.x,a.y,a.z],[a.x,r.y,r.z],[a.x,r.y,a.z],[a.x,a.y,r.z],[a.x,a.y,a.z]])q.set(l[0],l[1],l[2]),q.applyMatrix4(s.matrixWorld),o=Math.min(o,q.y)}),!Number.isFinite(o)){let n=new le().setFromObject(i);if(n.isEmpty())return null;o=n.min.y}return o-t}function Kt(i,e,t){return i.stripRootMotionY!==void 0?i.stripRootMotionY:!!(e&&t.some(o=>o===e))}function j(i){let e=i.collision?.position;return e?f(e,v):null}function ne(i){return!!i.collision?.size}function Xt(i){i.hasWarnedDynamicTrimesh||(i.hasWarnedDynamicTrimesh=!0,console.warn(`Actor "${i.name||i.uuid}" requested collisionShape="trimesh" on a dynamic body; falling back to bounds.`))}function $e(i,e,t){let o=i==="model"?"bounds":i??"capsule";return o==="trimesh"&&!e?(t?.(),"bounds"):o}function qe(i,e){let t=i.x||.5,o=i.y||1,n=i.z||.5,s=Math.max(t,n)/2,r=o/2;return{shape:{type:"capsule",halfHeight:Math.max(0,r-s),radius:s},offset:[e.x,e.y,e.z],sensor:!1}}function w(i){let e=f(i.collision?.size??i.size,{x:.5,y:1,z:.5}),t=e.y||1,o=j(i);return qe({x:e.x||.5,y:t,z:e.z||.5},o??{x:0,y:t/2,z:0})}function Je(i){let e=i.collision?.size;if(!e)return null;let t=f(e,v),o=t.x/2,n=t.y/2,s=t.z/2,r=j(i);return{shape:{type:"box",halfExtents:[o,n,s]},offset:[r?.x??0,r?.y??n,r?.z??0],sensor:!1}}function Qe(i,e,t){let n=e.matrixWorld.clone().invert().multiply(i.matrixWorld);return new Ke().makeScale(t.x,t.y,t.z).multiply(n)}function se(i,e,t){i.updateMatrixWorld(!0);let o=!1,n=new le;if(i.traverse(a=>{if(!a.isMesh)return;let l=a,p=l.geometry;if(!p)return;let d=null;if(l instanceof Gt?(l.computeBoundingBox(),d=l.boundingBox?.clone()??null):(p.computeBoundingBox(),d=p.boundingBox?.clone()??null),!d)return;let c=d.applyMatrix4(Qe(l,e,t));if(!o){n.copy(c),o=!0;return}n.union(c)}),!o||n.isEmpty())return null;let s=new M,r=new M;return n.getSize(s),n.getCenter(r),{size:s,center:r}}function $t(i,e,t){i.updateMatrixWorld(!0);let o=[],n=[],s=new le,r=new M,a=!1;if(i.traverse(p=>{if(!p.isMesh)return;let d=p,c=d.geometry;if(!c)return;let u=c.getAttribute("position");if(!(u instanceof Vt))return;let m=Qe(d,e,t),g=o.length/3;for(let h=0;h<u.count;h++)r.set(u.getX(h),u.getY(h),u.getZ(h)),r.applyMatrix4(m),o.push(r.x,r.y,r.z),s.expandByPoint(r);let b=c.getIndex();if(b)for(let h=0;h<b.count;h++)n.push(g+b.getX(h));else for(let h=0;h<u.count;h++)n.push(g+h);a=!0}),!a||o.length===0||n.length===0)return null;let l=new M;return s.getCenter(l),{vertices:new Float32Array(o),indices:new Uint32Array(n),center:l}}function et(i,e,t){let o=Je(t);if(o)return o;if(!i||!e)return w(t);let n=se(i,e,k(t));if(!n)return w(t);let s=j(t);return{shape:{type:"box",halfExtents:[n.size.x/2,n.size.y/2,n.size.z/2]},offset:[s?.x??n.center.x,s?.y??n.center.y,s?.z??n.center.z],sensor:!1}}function tt(i,e,t,o,n){if(ne(n)||!i||!e)return w(n);let s=se(i,e,k(n));if(!s)return w(n);let a=j(n);if(!a){let l=t&&o?se(t,o,k(n)):null;a=l?{x:l.center.x,y:l.center.y,z:l.center.z}:{x:s.center.x,y:s.center.y,z:s.center.z}}return qe({x:s.size.x,y:s.size.y,z:s.size.z},a)}function it(i,e,t){let o=Je(t);if(o)return o;if(!i||!e)return w(t);let n=$t(i,e,k(t));if(!n)return w(t);let s=j(t);return{shape:{type:"trimesh",vertices:n.vertices,indices:n.indices},offset:s?[s.x-n.center.x,s.y-n.center.y,s.z-n.center.z]:[0,0,0],sensor:!1}}function $(i){i&&i.traverse(e=>{if(!e.isMesh)return;let t=e;t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(o=>o.dispose()):t.material?.dispose()})}var re=class extends W{objectModel=null;collisionSource=null;collisionShape="capsule";constructor(e){super(),this.objectModel=e.objectModel,this.collisionSource=e.collisionSource??e.objectModel??null,this.collisionShape=e.collisionShape??"capsule"}collider(e){let t=$e(this.collisionShape,!!e.collision?.static);return t==="bounds"?et(this.objectModel,this.objectModel,e):t==="trimesh"?it(this.objectModel,this.objectModel,e):tt(this.collisionSource,this.collisionSource,this.objectModel,this.objectModel,e)}},ae=class extends K{createEntity(e){return new z(e)}},qt=Symbol("Actor"),z=class extends P{static type=qt;_object=null;_collisionSource=null;_animationDelegate=null;_modelFileNames=[];_assetLoader=new B;_loadGeneration=0;_loadStatus="idle";controlledRotation=!1;hasWarnedDynamicTrimesh=!1;constructor(e){super(),this.options=S(Xe,e),this.prependUpdate(this.actorUpdate.bind(this)),this.controlledRotation=!0}create(){return this._loadStatus==="idle"&&(this.options.models?.length??0)>0&&this.load(),super.create()}load(){this._loadStatus==="loading"||this._loadStatus==="loaded"||(this._modelFileNames=[...this.options.models||[]],this._modelFileNames.length!==0&&(this.disposeRuntimeState(!0),this._loadStatus="loading",this.loadModelsDeferred(++this._loadGeneration)))}data(){return{animations:this._animationDelegate?.animations,objectModel:this._object,collisionSource:this._collisionSource??this._object,collisionShape:this.options.collisionShape}}needsDeferredModelCollision(){return this.requiresLoadedCollisionSource()?!this.getRuntimeCollisionSource():!1}synchronizeRuntimeCollider(){let e=this.getResolvedCollisionShape(),t;if(e==="bounds")t=et(this._object,this.group??this._object,this.options);else if(e==="trimesh")t=it(this._object,this.group??this._object,this.options);else{let o=this.getRuntimeCollisionSource();t=tt(o,o,this._object,this._object,this.options)}this.colliderDesc=t,this.colliderDescs.length>0?this.colliderDescs[0]=t:this.colliderDescs.push(t)}actorUpdate(e){this._animationDelegate?.update(e.delta)}actorDestroy(){this._loadGeneration+=1,this._loadStatus="idle",this.disposeRuntimeState(!0),this._modelFileNames=[]}_cleanup(e){super._cleanup(e),this.actorDestroy()}playAnimation(e){this._animationDelegate?.playAnimation(e)}get object(){return this._object}get collisionSource(){return this._collisionSource??this._object}getDebugInfo(){let e={type:"Actor",models:this._modelFileNames.length>0?this._modelFileNames:"none",modelLoaded:!!this._object,scale:(()=>{let t=f(this.options.scale,D);return`${t.x}, ${t.y}, ${t.z}`})(),collisionShape:this.getResolvedCollisionShape()};if(this._animationDelegate&&(e.currentAnimation=this._animationDelegate.currentAnimationKey||"none",e.animationsCount=this.options.animations?.length||0),this._object){let t=0,o=0;this._object.traverse(n=>{if(!n.isMesh)return;t++;let s=n.geometry;s?.attributes.position&&(o+=s.attributes.position.count)}),e.meshCount=t,e.vertexCount=o}return e}getResolvedCollisionShape(){return $e(this.options.collisionShape,!!this.options.collision?.static,()=>Xt(this))}requiresLoadedCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?!ne(this.options):e==="capsule"?!ne(this.options)&&this.getCollisionSourceSelection().file!==null:!1}getRuntimeCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?this._object:this._collisionSource??this._object}getCollisionSourceSelection(){let e=this.options.models?.[0]??null,t=this.options.animations?.[0]?.path??null;return t?{file:t,reuseVisibleModel:t===e}:{file:e,reuseVisibleModel:!0}}disposeRuntimeState(e){this._animationDelegate&&(this._animationDelegate.dispose(),this._animationDelegate=null);let t=this._collisionSource;$(this._object),t&&t!==this._object&&$(t),this._object=null,this._collisionSource=null,e&&this.group&&(this.group.clear(),this.group=void 0)}loadModelsDeferred(e){this.dispatch("entity:model:loading",{entityId:this.uuid,files:this._modelFileNames});let t=this.getCollisionSourceSelection(),o=this._modelFileNames.map(s=>this._assetLoader.loadFile(s,{clone:!0})),n=t.file&&!t.reuseVisibleModel?this._assetLoader.loadFile(t.file,{clone:!0}):Promise.resolve(null);Promise.all([Promise.all(o),n]).then(([s,r])=>{if(e!==this._loadGeneration){s.forEach(l=>$(l.object??null)),r?.object&&$(r.object);return}this._object=s[0]?.object??null,this._collisionSource=t.reuseVisibleModel?this._object:r?.object??this._object,this._loadStatus=this._object?"loaded":"idle";let a=0;if(this._object){this._object.traverse(u=>{u.isMesh&&a++}),this.group=new Nt,this.group.add(this._object),this.group.scale.copy(k(this.options)),ke(this),this.applyMaterialOverrides(),this._animationDelegate=new H(this._object);let l=this.options.animations||[],p=this.options.models?.[0],d=l.map(u=>u.path),c=Kt(this.options,p,d);l.length>0?this._animationDelegate.loadAnimations(l,{stripRootMotionY:c,referenceAnimationPath:p}).then(()=>{e===this._loadGeneration&&(this.alignVisualModelToGround(),this.dispatch("entity:animation:loaded",{entityId:this.uuid,animationCount:l.length}))}):this.alignVisualModelToGround()}this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!!this._object,meshCount:a})}).catch(s=>{e===this._loadGeneration&&(this._loadStatus="idle",console.error("Failed to load actor model",s),this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!1,meshCount:0,errorMessage:s instanceof Error?s.message:String(s)}))})}alignVisualModelToGround(){if(!this._object||!this.group)return;this._animationDelegate?.update(0),this._object.updateMatrixWorld(!0);let e=Wt(this._object,this.group);if(e===null||Math.abs(e)<Zt)return;let t=this.group.scale.y||1;this._object.position.y-=e/t}applyMaterialOverrides(){let e=this.options.material;!e||!e.color&&!e.path&&e.opacity===void 0||this._object&&this._object.traverse(t=>{if(!t.isMesh)return;let o=t;o.material=Array.isArray(o.material)?o.material.map(n=>this.tintMaterial(n,e)):this.tintMaterial(o.material,e),e.color&&(o.castShadow=!0,o.receiveShadow=!0)})}tintMaterial(e,t){let o="color"in e,n=!!t.color,s=t.opacity!==void 0;if(!n&&!s)return e;if(n&&!o)return new Ut({color:t.color,emissiveIntensity:.5,lightMapIntensity:.5,fog:!0,opacity:t.opacity??1,transparent:s&&t.opacity<1});let r=e.clone();if(n&&"color"in r&&r.color.copy(t.color),s&&"opacity"in r&&"transparent"in r){let a=r;a.opacity=t.opacity,a.transparent=t.opacity<1}return r.needsUpdate=!0,r}};function Jt(...i){return Ge({args:i,defaultConfig:Xe,EntityClass:z,BuilderClass:ae,CollisionBuilderClass:re,entityType:z.type,cloneFactory:e=>Jt(e??{})})}import{Color as li,Fog as ci,FogExp2 as ui,Group as pi}from"three";import{Color as Qt}from"three";import{Fn as nt,fog as ei,positionWorld as ot,positionView as ti,uniform as x,float as ii,vec3 as O,clamp as ce,mix as E,max as oi,smoothstep as ni,floor as si,fract as ue,dot as ri}from"three/tsl";var J=class{values;u={time:x(0),heightEnabled:x(0),heightLevel:x(0),heightFalloff:x(0),noiseEnabled:x(0),noiseScale:x(0),noiseStrength:x(0),noiseSpeed:x(0)};attachedScene=null;constructor(e){this.values={...e},this.syncUniforms()}setValues(e){Object.assign(this.values,e),this.syncUniforms()}tick(e){this.values.time+=e,this.u.time.value=this.values.time}scan(e){if(this.attachedScene===e)return;let t=e.fog;t&&(e.fogNode=this.buildFogNode(t),this.attachedScene=e)}unpatchAll(){this.attachedScene&&(this.attachedScene.fogNode=null,this.attachedScene=null)}syncUniforms(){this.u.time.value=this.values.time,this.u.heightEnabled.value=this.values.heightEnabled,this.u.heightLevel.value=this.values.heightLevel,this.u.heightFalloff.value=this.values.heightFalloff,this.u.noiseEnabled.value=this.values.noiseEnabled,this.u.noiseScale.value=this.values.noiseScale,this.u.noiseStrength.value=this.values.noiseStrength,this.u.noiseSpeed.value=this.values.noiseSpeed}buildFogNode(e){let t=e.isFogExp2===!0,o=x(new Qt(e.color)),n=ti.z.negate(),s=t?this.exp2Factor(x(e.density),n):ni(x(e.near),x(e.far),n),r=this.u.heightLevel.sub(ot.y),a=ce(r.mul(oi(this.u.heightFalloff,0)),0,1),l=E(s,s.mul(a),this.u.heightEnabled),p=ot.mul(this.u.noiseScale).add(O(this.u.time.mul(this.u.noiseSpeed),0,this.u.time.mul(this.u.noiseSpeed).mul(.5))),c=ai(p).sub(.5).mul(2).mul(ce(this.u.noiseStrength,0,1)),u=ce(l.add(l.mul(c)),0,1),m=E(l,u,this.u.noiseEnabled);return ei(o,m)}exp2Factor(e,t){return e.mul(e).mul(t).mul(t).negate().exp().oneMinus()}},A=nt(([i])=>{let e=ue(i.mul(O(443.8975,397.2973,491.1871))),t=e.add(ri(e,e.yzx.add(19.27)));return ue(t.x.add(t.y).mul(t.z))}),ai=nt(([i])=>{let e=si(i),t=ue(i),o=t.mul(t).mul(ii(3).sub(t.mul(2))),n=A(e.add(O(0,0,0))),s=A(e.add(O(1,0,0))),r=A(e.add(O(0,1,0))),a=A(e.add(O(1,1,0))),l=A(e.add(O(0,0,1))),p=A(e.add(O(1,0,1))),d=A(e.add(O(0,1,1))),c=A(e.add(O(1,1,1))),u=E(n,s,o.x),m=E(r,a,o.x),g=E(l,p,o.x),b=E(d,c,o.x),h=E(u,m,o.y),R=E(g,b,o.y);return E(h,R,o.z)});var di=Symbol("Fog"),hi="#9aa3ad",mi=.015,fi=10,yi=250,bi=5,gi=.2,Ci=.05,xi=.15,vi=.1,pe=class extends P{static type=di;threeFog=null;attachedScene=null;patcher;patcherEnabled;constructor(e={}){super(),this.options={...e};let t=this.resolveUniformValues(this.options);this.patcher=new J(t),this.patcherEnabled=Oi(this.options)}create(){return super.create(),this.threeFog=Si(this.options),this.group=new pi,this.group.name=this.name?`Fog:${this.name}`:"Fog",this}attachToScene(e){this.threeFog&&(this.attachedScene=e,e.fog=this.threeFog,this.patcherEnabled&&this.patcher.scan(e))}_update(e){super._update(e),!(!this.attachedScene||!this.patcherEnabled)&&(this.patcher.tick(e.delta),this.patcher.scan(this.attachedScene))}_cleanup(e){this.patcher.unpatchAll(),this.attachedScene&&this.attachedScene.fog===this.threeFog&&(this.attachedScene.fog=null),this.attachedScene=null,this.threeFog=null,super._cleanup(e)}resolveUniformValues(e){let t=e.height,o=e.noise;return{time:0,heightEnabled:t?.enabled?1:0,heightLevel:t?.level??bi,heightFalloff:t?.falloff??gi,noiseEnabled:o?1:0,noiseScale:o?.scale??Ci,noiseStrength:o?.strength??xi,noiseSpeed:o?.speed??vi}}};function Si(i){let e=new li(i.color??hi);return(i.type??"linear")==="exp2"?new ui(e,i.density??mi):new ci(e,i.start??fi,i.end??yi)}function Oi(i){let e=!!i.height?.enabled,t=!!i.noise;return e||t}function _n(i={}){return new pe(i)}export{C as a,S as b,lt as c,ct as d,ut as e,pt as f,dt as g,ht as h,mt as i,ft as j,Re as k,Hi as l,Yi as m,Wi as n,ke as o,N as p,eo as q,P as r,wt as s,ie as t,Ge as u,W as v,He as w,K as x,qt as y,z,Jt as A,di as B,pe as C,_n as D};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as Ue}from"./chunk-C5NEGC3S.js";import{b as je}from"./chunk-D3JO4HW2.js";import{a as He}from"./chunk-LKFF6XJC.js";import{a as u,b as Ie,f as we,i as Ze,j as ze,k as Ve,l as Ge}from"./chunk-W5SXED5T.js";import{a as K,b as et}from"./chunk-WBQ5TNRZ.js";import{B as tt,a as O,k as Qe,l as Ye,m as qe,n as x,o as B,r as $e,s as Ee,z as j}from"./chunk-3I537JFL.js";import{e as R,f as De,g as Xe,h as Je}from"./chunk-CM5YRNBJ.js";import{a as We,b as w}from"./chunk-AIQ6IVT5.js";import{a as Q,b as it,c as Y,d as rt,e as at,f as st,g as nt,m as q}from"./chunk-D2PATZCC.js";import{c as H,d as Pe,j as P}from"./chunk-4QLJUQSJ.js";import{c as b,i as Ke,j as g}from"./chunk-7WRQ2UAN.js";import{a as ot}from"./chunk-BH53MBAZ.js";import{l as Ne}from"./chunk-UG22Z42P.js";import{Vector2 as mt,RenderTarget as Yt,HalfFloatType as qt}from"three";import{WebGPURenderer as $t,RenderPipeline as Xt}from"three/webgpu";import{pass as Jt,renderOutput as pt,screenCoordinate as ei,vec2 as Me,vec4 as yt,fract as ht,sin as gt,dot as ft,texture as ti,uniform as ii}from"three/tsl";import{setConsoleFunction as Kt,getConsoleFunction as Qt}from"three";var lt="THREE.Abstract function.",dt=!1,ct=!1;function ut(){if(dt)return;dt=!0;let s=Qt();Kt((e,t,...i)=>{if(e==="warn"&&t===lt){ct||(ct=!0,console.warn(`${lt} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(s){s(e,t,...i);return}let r=i[0],a=e==="log"?console.log:e==="error"?console.error:console.warn;r&&r.isStackTrace&&typeof r.getError=="function"?a(r.getError(t)):a(t,...i)})}var bt={x:0,y:0,width:1,height:1};async function cr(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var $=class{renderer;postProcessing=null;renderScale=1;screenResolution;_initialized=!1;_sceneRef=null;_lastAnimationTimestamp=null;_postEffects=[];_postSceneRef=null;_postCameraRef=null;_transition=null;constructor(e){this.screenResolution=e||new mt(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(ut(),this.renderer=new $t({antialias:!0,alpha:!0}),await this.renderer.init(),this.renderer.setSize(this.screenResolution.x,this.screenResolution.y),this.renderer.shadowMap.enabled=!0,this._initialized=!0)}setScene(e){this._sceneRef=e}setupPostProcessing(e,t){this.disposePostProcessing(),this._postSceneRef=e,this._postCameraRef=t;let i=new Xt(this.renderer),r=Jt(e,t);this.renderScale!==1&&r.setResolutionScale(this.renderScale);let a=r;for(let l of this._postEffects)try{a=l(a,{scenePass:r,scene:e,camera:t})}catch(d){console.error("RendererManager: post-processing effect failed, skipping.",d)}i.outputColorTransform=!1;let n=pt(a),o=this._transition;if(o)try{n=yt(o.resolved.shader({fromNode:o.fromNode,toNode:n,progress:o.progressUniform})),o.composed=!0}catch(l){console.error("RendererManager: stage transition shader failed, skipping.",l)}i.outputNode=n.add(ai()),this.postProcessing=i}get transitionActive(){return this._transition!==null}beginSnapshotTransition(e,t,i){this.finishTransition();let r=new mt;this.renderer.getDrawingBufferSize(r);let a=new Yt(Math.max(1,r.x),Math.max(1,r.y),{type:qt}),n=this.renderer.getRenderTarget();try{this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(a),this.renderer.render(t,i)}catch(o){console.error("RendererManager: failed to capture transition snapshot.",o)}finally{this.renderer.setRenderTarget(n)}this._transition={resolved:e,progressUniform:ii(0),fromNode:pt(ti(a.texture)),elapsed:0,snapshotTarget:a,composed:!1}}finishTransition(){let e=this._transition;if(e){this._transition=null,e.progressUniform.value=1,this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef);try{e.resolved.onComplete?.()}catch(t){console.error("RendererManager: transition onComplete failed.",t)}this.releaseTransitionResources(e)}}cancelTransition(){let e=this._transition;if(e){this._transition=null;try{e.resolved.onComplete?.()}catch{}this.releaseTransitionResources(e)}}releaseTransitionResources(e){try{e.snapshotTarget?.dispose()}catch{}}advanceTransition(e){let t=this._transition;if(!t||!t.composed)return;t.elapsed+=e;let i=Math.min(t.elapsed/t.resolved.duration,1);t.progressUniform.value=t.resolved.easing(i),i>=1&&this.finishTransition()}setPostProcessingEffects(e){this._postEffects=[...e],this.postProcessing&&this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef)}setRenderScale(e){this.renderScale=Math.max(1,Number.isFinite(e)?e:1)}disposePostProcessing(){try{this.postProcessing?.dispose?.()}catch{}this.postProcessing=null}startRenderLoop(e){this._lastAnimationTimestamp=null,this.renderer.setAnimationLoop(t=>{let i=this._lastAnimationTimestamp===null?0:Math.max(0,(t-this._lastAnimationTimestamp)/1e3);this._lastAnimationTimestamp=t,this.advanceTransition(i),e(i)})}stopRenderLoop(){this._lastAnimationTimestamp=null;try{this.renderer.setAnimationLoop(null)}catch{}}renderCamera(e,t,i=!1){let r=t.viewport,a=this.screenResolution.x,n=this.screenResolution.y,o=Math.floor(r.x*a),l=Math.floor(r.y*n),d=Math.floor(r.width*a),c=Math.floor(r.height*n);this.renderer.setViewport(o,l,d,c),this.renderer.setScissor(o,l,d,c),this.renderer.setScissorTest(!0),i&&this.postProcessing?this.postProcessing.render():this.renderer.render(e,t.camera)}renderCameraToTarget(e,t){if(!t.renderTarget)return;let i=this.renderer.getRenderTarget();this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(t.renderTarget),this.renderer.clear(),this.renderer.render(e,t.camera),this.renderer.setRenderTarget(i)}renderCameras(e,t){if(!e||t.length===0)return;this.renderer.setScissorTest(!1),this.renderer.clear();let i=t.length===1&&ri(t[0].viewport);for(let r of t)this.renderCamera(e,r,i);this.renderer.setScissorTest(!1)}render(e,t){this.postProcessing?this.postProcessing.render():this.renderer.render(e,t)}resize(e,t){this.screenResolution.set(e,t),this.renderer.setSize(e,t,!1)}setPixelRatio(e){let t=Math.max(1,Number.isFinite(e)?e:1);this.renderer.setPixelRatio(t)}getDomElement(){return this.renderer.domElement}dispose(){this.stopRenderLoop(),this.cancelTransition(),this.disposePostProcessing();try{this.renderer.dispose()}catch{}this._sceneRef=null,this._postSceneRef=null,this._postCameraRef=null,this._postEffects=[],this._initialized=!1}};function ri(s){return s.x===0&&s.y===0&&s.width===1&&s.height===1}function ai(){let s=ei.xy,e=ht(gt(ft(s,Me(12.9898,78.233))).mul(43758.5453)),t=ht(gt(ft(s.add(Me(13,7)),Me(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return yt(i,i,i,0)}function F(s){return s?.category??"none"}function I(s){let e=F(s);return e==="environment"||e==="pack"}function k(s){return s.isInstanced===!0||s.isBundled===!0}import{BundleGroup as si}from"three/webgpu";var X=class{bundles=new Map;entityToBundle=new Map;scene=null;setScene(e){this.scene=e}register(e,t,i,r){if(e.isBundled)return!0;let a=e.mesh??e.group;if(!a)return!1;let n=this.getOrCreateBundle(r);return a.matrixAutoUpdate=!0,a.userData.zylemEntityUuid=e.uuid,a.parent&&a.parent.remove(a),n.add(a),n.needsUpdate=!0,e.isBundled=!0,e.bundleKey=r,this.entityToBundle.set(e.uuid,r),!0}unregister(e){let t=this.entityToBundle.get(e.uuid);if(!t)return;let i=this.bundles.get(t),r=e.mesh??e.group;i&&r&&(i.remove(r),i.needsUpdate=!0),e.isBundled=!1,e.bundleKey=null,this.entityToBundle.delete(e.uuid)}getStats(){return{bundleCount:this.bundles.size,entityCount:this.entityToBundle.size}}dispose(){for(let e of this.bundles.values())this.scene&&this.scene.remove(e);this.bundles.clear(),this.entityToBundle.clear()}getOrCreateBundle(e){let t=this.bundles.get(e);return t||(t=new si,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as vt,Matrix4 as Z,Vector3 as Ct,Quaternion as ni}from"three";var z=class s{packs=new Map;entityToPack=new Map;scene=null;static DEFAULT_CAPACITY=128;static GROWTH_FACTOR=2;setScene(e){this.scene=e}static generatePackKey(e){let t={geo:`${e.geometryType}:${De(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Xe(De(t))}static generateEntityPackKey(e){let t=e.options;if(t.runtime?.packKeyOverride)return t.runtime.packKeyOverride;let i=e.constructor?.type?.description||"unknown",r=t.size||{x:1,y:1,z:1},a=t.material||{};return s.generatePackKey({geometryType:i,dimensions:{x:r.x,y:r.y,z:r.z},materialPath:a.path||null,shaderType:a.shader?"custom":"standard",colorHex:a.color?.getHex?.()||t.color?.getHex?.()||16777215})}register(e,t,i,r){let a=this.packs.get(r);a||(a=this.createPack(r,t,i));let n;return a.freeIndices.length>0?n=a.freeIndices.pop():(n=a.entities.length,n>=a.capacity&&this.growPack(a),a.entities.push(null)),a.entities[n]=e,a.entityMap.set(e.uuid,n),this.entityToPack.set(e.uuid,r),a.instancedMesh.count=Math.max(a.instancedMesh.count,n+1),a.activeIndices.push(n),a.dirtyIndices.add(n),n}unregister(e){let t=this.entityToPack.get(e.uuid);if(!t)return;let i=this.packs.get(t);if(!i)return;let r=i.entityMap.get(e.uuid);if(r===void 0)return;i.entities[r]=null,i.entityMap.delete(e.uuid),this.entityToPack.delete(e.uuid),i.freeIndices.push(r);let a=i.activeIndices.indexOf(r);if(a!==-1){let o=i.activeIndices.pop();a<i.activeIndices.length&&(i.activeIndices[a]=o)}i.dirtyIndices.delete(r);let n=new Z;n.makeScale(0,0,0),i.instancedMesh.setMatrixAt(r,n),i.instancedMesh.instanceMatrix.needsUpdate=!0}markDirty(e){let t=this.entityToPack.get(e.uuid);if(!t)return;let i=this.packs.get(t);if(!i)return;let r=i.entityMap.get(e.uuid);r!==void 0&&i.dirtyIndices.add(r)}update(e=0){let t=new Z,i=new Ct,r=new ni,a=new Ct(1,1,1);for(let n of this.packs.values()){if(n.activeIndices.length===0)continue;let o=!1;for(let l of n.activeIndices){let d=n.entities[l];if(!d)continue;if(Qe(d)){t.makeScale(0,0,0),n.instancedMesh.setMatrixAt(l,t),o=!0;continue}let c=n.dirtyIndices.has(l),m=!!d.body;if(!(!c&&!m)){if(!c&&m){let p=d.body;if(typeof p.isRenderSleeping=="function"&&p.isRenderSleeping())continue}this.updateInstanceMatrix(n,l,t,i,r,a,e),o=!0}}n.dirtyIndices.clear(),o&&(n.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,a,n,o){let l=e.entities[t];if(l){if(l.body){let d=l.body;if(typeof d.writeRenderPose=="function")d.writeRenderPose(o,r,a);else{let c=K(l.body,o);r.set(c.position.x,c.position.y,c.position.z),a.set(c.rotation.x,c.rotation.y,c.rotation.z,c.rotation.w)}i.compose(r,a,n)}else l.mesh?(l.mesh.updateMatrix(),i.copy(l.mesh.matrix)):l.group&&(l.group.updateMatrix(),i.copy(l.group.matrix));e.instancedMesh.setMatrixAt(t,i)}}getPackInfo(e){let t=this.entityToPack.get(e.uuid);if(!t)return null;let i=this.packs.get(t);if(!i)return null;let r=i.entityMap.get(e.uuid);return r===void 0?null:{packKey:t,instanceId:r}}getStats(){let e=0,t=[];for(let[i,r]of this.packs){let a=r.entityMap.size;e+=a,t.push({key:i,count:a,capacity:r.capacity})}return{packCount:this.packs.size,totalInstances:e,packs:t}}dispose(){for(let e of this.packs.values())this.scene&&this.scene.remove(e.instancedMesh),e.instancedMesh.dispose(),e.geometry.dispose();this.packs.clear(),this.entityToPack.clear()}createPack(e,t,i){let r=s.DEFAULT_CAPACITY,a=new vt(t,i,r);a.count=0,a.frustumCulled=!1;let n=new Z().makeScale(0,0,0);for(let l=0;l<r;l++)a.setMatrixAt(l,n);a.instanceMatrix.needsUpdate=!0;let o={key:e,instancedMesh:a,geometry:t,material:i,entityMap:new Map,entities:[],freeIndices:[],activeIndices:[],dirtyIndices:new Set,capacity:r};return this.packs.set(e,o),this.scene&&this.scene.add(a),o}growPack(e){let t=e.capacity*s.GROWTH_FACTOR,i=new vt(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new Z;for(let n=0;n<e.capacity;n++)e.instancedMesh.getMatrixAt(n,r),i.setMatrixAt(n,r);let a=new Z().makeScale(0,0,0);for(let n=e.capacity;n<t;n++)i.setMatrixAt(n,a);i.instanceMatrix.needsUpdate=!0,this.scene&&(this.scene.remove(e.instancedMesh),this.scene.add(i)),e.instancedMesh.dispose(),e.instancedMesh=i,e.capacity=t}};var J=class{bundles=new X;instances=new z;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=F(e.options);if(t==="none")return!1;if(e.isInstanced||e.isBundled)return!0;if(!e.mesh?.geometry||!e.materials?.length)return!1;let i=e.mesh.geometry,r=e.materials[0],a=z.generateEntityPackKey(e);if(t==="pack"){let n=this.instances.register(e,i,r,a);return n<0?!1:(e.packKey=a,e.instanceId=n,e.isInstanced=!0,e.mesh&&(e.mesh.visible=!1),!0)}return t==="environment"&&this.bundles.register(e,i,r,a)?(e.mesh&&(e.mesh.visible=!0),!0):!1}unregister(e){e.isInstanced&&(this.instances.unregister(e),e.isInstanced=!1,e.instanceId=-1,e.packKey=null),e.isBundled&&this.bundles.unregister(e)}update(e=0){this.instances.update(e)}dispose(){this.bundles.dispose(),this.instances.dispose()}};var ee=!1,v={},St=0,Pt=0,V=null;function wt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function _e(){return ee?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(ee=!0),ee)}function _r(s){ee=s,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=s)}function Te(s){_e()&&(V=s,Pt=wt())}function xe(){if(!_e()||V===null)return;let s=wt()-Pt;v[V]=(v[V]??0)+s,V=null}function Et(){if(!_e()||(St++,St%60!==0))return;let s=Object.values(v).reduce((t,i)=>t+(i??0),0),e=Object.keys(v).sort((t,i)=>(v[i]??0)-(v[t]??0)).map(t=>{let i=v[t]??0,r=s>0?(i/s*100).toFixed(1):"0.0";return`${t}=${i.toFixed(2)}ms (${r}%)`});console.info(`[ZylemStage profile] avg over 60 frames (${s.toFixed(2)}ms/frame): ${e.join(", ")}`);for(let t of Object.keys(v))v[t]=0}function C(s,e){Te(s);try{return e()}finally{xe()}}var h={FirstPerson:"first-person",ThirdPerson:"third-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};import{Vector3 as oi,Quaternion as li,MathUtils as Re}from"three";function te(){return{position:new oi(0,0,10),rotation:new li,fov:75,zoom:1,near:.1,far:1e3}}function M(s){return{position:s.position.clone(),rotation:s.rotation.clone(),fov:s.fov,zoom:s.zoom,near:s.near,far:s.far,lookAt:s.lookAt?.clone()}}function Dt(s,e){let t=M(s);return e.position&&t.position.add(e.position),e.rotation&&t.rotation.multiply(e.rotation),e.fov!=null&&t.fov!=null&&(t.fov+=e.fov),e.zoom!=null&&t.zoom!=null&&(t.zoom+=e.zoom),t}function Mt(s,e,t,i){let r=1-Math.pow(1-Re.clamp(t,0,1),i*60),a=M(s);return a.position.lerp(e.position,r),a.rotation.slerp(e.rotation,r),e.fov!=null&&a.fov!=null&&(a.fov=Re.lerp(a.fov,e.fov,r)),e.zoom!=null&&a.zoom!=null&&(a.zoom=Re.lerp(a.zoom,e.zoom,r)),e.near!=null&&(a.near=e.near),e.far!=null&&(a.far=e.far),e.lookAt?a.lookAt?a.lookAt.lerp(e.lookAt,r):a.lookAt=e.lookAt.clone():a.lookAt=void 0,a}var ie=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=te();_finalPose=te();_initialized=!1;damping=.15;constructor(e){e&&(this.perspective=e,e.defaults?.damping!=null&&(this.damping=e.defaults.damping))}run(e){let t=this.perspective?this.perspective.getBasePose(e):te(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=M(t);for(let r=this.actions.length-1;r>=0;r--){let a=this.actions[r],n=a.update(e);t=Dt(t,n),a.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=Mt(this._finalPose,t,this.damping,e.dt):(this._finalPose=M(t),this._initialized=!0),this._finalPose}addBehavior(e,t,i){let r=this.behaviors.get(e);r?.onDetach&&i&&r.onDetach(i),this.behaviors.set(e,t),t.onAttach&&i&&t.onAttach(i)}removeBehavior(e,t){let i=this.behaviors.get(e);return i?(i.onDetach&&t&&i.onDetach(t),this.behaviors.delete(e)):!1}hasBehavior(e){return this.behaviors.has(e)}addAction(e){this.actions.push(e)}getState(){return{perspectiveId:this.perspective?.id??null,desiredPose:this._desiredPose?M(this._desiredPose):null,finalPose:this._finalPose?M(this._finalPose):null,activeBehaviors:Array.from(this.behaviors.keys()),activeActionCount:this.actions.length}}setPerspective(e){this.perspective=e,this._initialized=!1,e.defaults?.damping!=null&&(this.damping=e.defaults.damping)}getSortedBehaviors(){return Array.from(this.behaviors.values()).sort((e,t)=>(e.priority??0)-(t.priority??0))}};import{Vector3 as E,Quaternion as re}from"three";var di={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},_=class{id="third-person";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...di,...r},this.initialPosition=t?g(t,b):void 0,this.initialLookAt=i?g(i,b):void 0}getBasePose(e){let t=Object.keys(e.targets),i=e.targets[this.opts.targetKey];return t.length===0||!i?this.staticPose():t.length===1?this.singleTargetPose(i.position,e,this.opts.targetKey):this.multiTargetPose(e)}staticPose(){return this.initialPosition?{position:this.initialPosition.clone(),rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new E(0,0,0)}:{position:new E(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new E(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new E(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([m,p])=>this.getTrailedPosition(m,p.position,e.time)),r=new E;for(let m of i)r.add(m);r.divideScalar(i.length);let a=0;for(let m of i){let p=r.distanceTo(m);p>a&&(a=p)}let n=Math.max(a*this.opts.paddingFactor,this.opts.minDistance),o=new E(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=o.length(),d=l>0?o.clone().normalize():new E(0,.5,1).normalize(),c=r.clone().add(d.multiplyScalar(n));if(l>0){let m=this.opts.height/l;c.y=r.y+n*m}return{position:c,rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}getTrailedPosition(e,t,i){let r=this.opts.trailDelay;if(r<=0)return t;let a=this._trailBuffers.get(e);a||(a=[],this._trailBuffers.set(e,a)),a.push({time:i,pos:t.clone()});let n=i-r-.05;for(;a.length>1&&a[0].time<n;)a.shift();a.length>this.opts.trailBufferSize&&a.splice(0,a.length-this.opts.trailBufferSize);let o=i-r;if(a[0].time>=o)return a[0].pos.clone();for(let l=1;l<a.length;l++){let d=a[l-1],c=a[l];if(d.time<=o&&o<=c.time){let m=c.time-d.time,p=m>1e-6?(o-d.time)/m:0;return new E().lerpVectors(d.pos,c.pos,p)}}return a[a.length-1].pos.clone()}};import{Vector3 as _t,Quaternion as ci}from"three";var Tt={position:{x:0,y:0,z:10},zoom:10},L=class{id="fixed-2d";defaults={damping:1};opts;constructor(e){this.opts={...Tt,...e,position:g(e?.position,Tt.position)}}getBasePose(e){return{position:new _t(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new ci,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new _t(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as ke,Quaternion as Le,Euler as kt,MathUtils as f}from"three";var ui={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},G=class{id="first-person";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new Le;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...ui,...r},this.initialPosition=t?g(t,b):void 0,this.initialLookAt=i?g(i,b):void 0,this._currentFov=this.opts.defaultFov,this._targetFov=this.opts.defaultFov,this._lookAtLerpSpeed=this.opts.lookAtLerpSpeed,this.initialPosition&&this.initialLookAt&&this.deriveYawPitchFromLookAt(this.initialPosition,this.initialLookAt)}look(e,t){this._yaw+=e,this._pitch=f.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=f.clamp(t,-this.opts.pitchLimit,this.opts.pitchLimit)}setEyeHeight(e){this.opts.eyeHeight=e}get yaw(){return this._yaw}get pitch(){return this._pitch}zoom(e){this._targetFov=e}resetZoom(){this._targetFov=this.opts.defaultFov}get currentFov(){return this._currentFov}lookAt(e,t){this._lookAtTarget=e,t!=null&&(this._lookAtLerpSpeed=t)}clearLookAt(){this._lookAtTarget&&this.deriveYawPitchFromQuaternion(this._currentRotation),this._lookAtTarget=null}getBasePose(e){let t=this.computePosition(e),i=this.computeRotation(t,e.dt);return this._currentFov=this.lerpFov(e.dt),{position:t,rotation:i,fov:this._currentFov,near:.1,far:1e3}}computePosition(e){let t=e.targets[this.opts.targetKey];if(t){let i=t.position.y+this.opts.eyeHeight,r=this.smoothVertical(i,e.dt);return new ke(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new ke(0,this.opts.eyeHeight,0)}smoothVertical(e,t){if(this.opts.verticalSmoothing>=1)return this._smoothedY=e,e;if(this._smoothedY==null)return this._smoothedY=e,e;let i=f.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=f.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new Le().setFromEuler(new kt(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=xt.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let a=Math.atan2(-r.x,-r.z),n=Math.asin(f.clamp(r.y,-1,1)),o=mi.setFromEuler(Rt.set(n,a,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(o,f.clamp(l,0,1)),this._currentRotation.clone()}}return this._currentRotation.copy(i),i}lerpFov(e){if(Math.abs(this._currentFov-this._targetFov)<.01)return this._targetFov;let t=1-Math.pow(1-Math.min(this.opts.fovLerpSpeed*e,1),1);return f.lerp(this._currentFov,this._targetFov,f.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=xt.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(f.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=Rt.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=f.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},xt=new ke,mi=new Le,Rt=new kt;function A(s,e){switch(s){case"third-person":return new _(e);case"first-person":return new G(e);case"isometric":return new _({distance:10,height:10,...e});case"flat-2d":return new L(e);case"fixed-2d":return new L(e);default:return new _(e)}}import{Vector2 as fi,Object3D as yi,Vector3 as ne}from"three";import{PerspectiveCamera as U,Vector3 as hi,OrthographicCamera as se,RenderTarget as gi,LinearFilter as Lt}from"three";import{Vector3 as Ae}from"three";import{OrbitControls as pi}from"three/addons/controls/OrbitControls.js";var ae=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new Ae;debugDelegate=null;debugUnsubscribe=null;debugStateSnapshot={enabled:!1,selected:[]};savedCameraPosition=null;savedCameraQuaternion=null;savedCameraZoom=null;savedCameraLocalPosition=null;savedDebugCameraPosition=null;savedDebugCameraQuaternion=null;savedDebugCameraZoom=null;savedDebugOrbitTarget=null;_userOrbitEnabled=!1;_isDebugViewCamera=!1;_defaultOrbitTarget=null;_debugPoseSeeded=!1;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}setDebugViewCamera(e){this._isDebugViewCamera=e}setDefaultOrbitTarget(e){this._defaultOrbitTarget=e,e&&!this.orbitTarget&&this.debugStateSnapshot.enabled&&(this.orbitTarget=e)}seedOrbitPose(e,t){this.camera.position.copy(e),this.camera.lookAt(t),this.orbitControls&&(this.orbitControls.target.copy(t),this.orbitControls.update()),this._debugPoseSeeded=!0}get isDebugViewCamera(){return this._isDebugViewCamera}get isDebugOrbitPoseSeeded(){return this._debugPoseSeeded}get isActive(){return this.debugStateSnapshot.enabled}get isOrbitActive(){return this.debugStateSnapshot.enabled||this._userOrbitEnabled}update(){this.orbitControls&&this.orbitTarget&&(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)),this.orbitControls?.update()}enableUserOrbitControls(){this._userOrbitEnabled=!0,this.orbitControls||this.enableOrbitControls()}disableUserOrbitControls(){this._userOrbitEnabled=!1,this.debugStateSnapshot.enabled||this.disableOrbitControls()}setDebugDelegate(e){if(this.debugDelegate===e)return;if(this.detachDebugDelegate(),this.debugDelegate=e,!e){this.applyDebugState({enabled:!1,selected:[]});return}let t=e.subscribe(i=>{this.applyDebugState(i)});this.debugUnsubscribe=()=>{t?.()}}dispose(){this.disableOrbitControls(),this.detachDebugDelegate()}get debugState(){return this.debugStateSnapshot}frameTarget(e){!this.orbitControls&&(this.debugStateSnapshot.enabled||this._userOrbitEnabled)&&this.enableOrbitControls(),this.orbitControls||this.enableOrbitControls(),this.orbitTarget=e;let t=new Ae().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=Ue(e,this.camera,t);this.orbitControls.target.copy(i.center),this.orbitControls.update()}applyDebugState(e){let t=this.debugStateSnapshot.enabled;if(this.debugStateSnapshot={enabled:e.enabled,selected:[...e.selected]},this._isDebugViewCamera){e.enabled&&!t?(this.enableOrbitControls(),this._debugPoseSeeded&&this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this._userOrbitEnabled||this.disableOrbitControls()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected);return}e.enabled&&!t?(this.saveCameraState(),this.detachCameraFromRig(),this.enableOrbitControls(),this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this.orbitTarget=null,this._userOrbitEnabled||this.disableOrbitControls(),this.reattachCameraToRig(),this.restoreCameraState()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected)}enableOrbitControls(){this.orbitControls||(this.orbitControls=new pi(this.camera,this.domElement),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.05,this.orbitControls.screenSpacePanning=!1,this.orbitControls.minDistance=1,this.orbitControls.maxDistance=500,this.orbitControls.maxPolarAngle=Math.PI/2,this.orbitControls.target.set(0,0,0))}disableOrbitControls(){this.orbitControls&&(this.orbitControls.dispose(),this.orbitControls=null)}updateOrbitTargetFromSelection(e){if(!this.debugDelegate||e.length===0){this.orbitTarget=this._defaultOrbitTarget,this.orbitControls&&(this.orbitTarget?(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)):this.orbitControls.target.set(0,0,0));return}for(let t=e.length-1;t>=0;t-=1){let i=e[t],r=this.debugDelegate.resolveTarget(i);if(r){this.orbitTarget=r,this.orbitControls&&(r.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos));return}}this.orbitTarget=this._defaultOrbitTarget,this.orbitControls&&(this.orbitTarget?(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)):this.orbitControls.target.set(0,0,0))}detachDebugDelegate(){if(this.debugUnsubscribe)try{this.debugUnsubscribe()}catch{}this.debugUnsubscribe=null,this.debugDelegate=null}saveCameraState(){this.savedCameraPosition=this.camera.position.clone(),this.savedCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedCameraZoom=this.camera.zoom)}restoreCameraState(){this.savedCameraPosition&&(this.camera.position.copy(this.savedCameraPosition),this.savedCameraPosition=null),this.savedCameraQuaternion&&(this.camera.quaternion.copy(this.savedCameraQuaternion),this.savedCameraQuaternion=null),this.savedCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedCameraZoom,this.camera.updateProjectionMatrix?.(),this.savedCameraZoom=null)}saveDebugCameraState(){this.savedDebugCameraPosition=this.camera.position.clone(),this.savedDebugCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedDebugCameraZoom=this.camera.zoom),this.orbitControls&&(this.savedDebugOrbitTarget=this.orbitControls.target.clone())}restoreDebugCameraState(){this.savedDebugCameraPosition&&this.camera.position.copy(this.savedDebugCameraPosition),this.savedDebugCameraQuaternion&&this.camera.quaternion.copy(this.savedDebugCameraQuaternion),this.savedDebugCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedDebugCameraZoom,this.camera.updateProjectionMatrix?.()),this.savedDebugOrbitTarget&&this.orbitControls&&this.orbitControls.target.copy(this.savedDebugOrbitTarget)}detachCameraFromRig(){if(!this.cameraRig||this.camera.parent!==this.cameraRig)return;this.savedCameraLocalPosition=this.camera.position.clone();let e=new Ae;this.camera.getWorldPosition(e),this.cameraRig.remove(this.camera),this.sceneRef&&this.sceneRef.add(this.camera),this.camera.position.copy(e)}reattachCameraToRig(){!this.cameraRig||this.camera.parent===this.cameraRig||(this.sceneRef&&this.camera.parent===this.sceneRef&&this.sceneRef.remove(this.camera),this.cameraRig.add(this.camera),this.savedCameraLocalPosition&&(this.camera.position.copy(this.savedCameraLocalPosition),this.savedCameraLocalPosition=null))}};var S=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...bt};targets=[];pipeline;renderTarget=null;get target(){return this.targets.length>0?this.targets[0]:null}set target(e){e?this.targets.length===0?this.targets.push(e):this.targets[0]=e:this.targets=[]}orbitController=null;_useOrbitalControls=!1;_skipDebugOrbit=!1;isDebugViewCamera=!1;_rendererManager=null;_elapsedTime=0;constructor(e,t,i=10){this._perspective=e,this.screenResolution=t,this.frustumSize=i;let r=t.x/t.y;this.camera=this.createCameraForPerspective(r),this.camera.position.set(0,0,10),this.camera.lookAt(new hi(0,0,0));let a=A(e);this.pipeline=new ie(a)}async setup(e,t){this.sceneRef=e,t&&(this._rendererManager=t),this._rendererManager&&!this._rendererManager.initialized&&await this._rendererManager.initRenderer(),this._rendererManager&&(this.orbitController=new ae(this.camera,this._rendererManager.renderer.domElement,null),this.orbitController.setScene(e),this.isDebugViewCamera&&this.orbitController.setDebugViewCamera(!0),this._useOrbitalControls&&this.orbitController.enableUserOrbitControls())}async setupLegacy(e){this._rendererManager||(this._rendererManager=new $(this.screenResolution),await this._rendererManager.initRenderer(),this._rendererManager.setupPostProcessing(e,this.camera),this._rendererManager.startRenderLoop(()=>{this._rendererManager&&this.sceneRef&&(this.isOrbitActive&&this.updateOrbitControls(),this._rendererManager.render(this.sceneRef,this.camera))})),await this.setup(e,this._rendererManager)}update(e){if(this.isDebugModeActive()||this._useOrbitalControls)return;this._elapsedTime+=e;let t=this.buildContext(e),i=this.pipeline.run(t);this.commitPose(i)}isDebugModeActive(){return this.orbitController?.isActive??!1}get isOrbitActive(){return this.orbitController?.isOrbitActive??!1}updateOrbitControls(){this.orbitController?.update()}enableOrbitalControls(){this._useOrbitalControls=!0,this.orbitController?.enableUserOrbitControls()}disableOrbitalControls(){this._useOrbitalControls=!1,this.orbitController?.disableUserOrbitControls()}get useOrbitalControls(){return this._useOrbitalControls}addTarget(e){this.targets.includes(e)||this.targets.push(e)}removeTarget(e){let t=this.targets.indexOf(e);t!==-1&&this.targets.splice(t,1)}clearTargets(){this.targets=[]}setViewport(e,t,i,r){this.viewport={x:e,y:t,width:i,height:r}}resize(e,t){if(this.screenResolution.set(e,t),this.camera instanceof U&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof se){let i=e/t;this.camera.left=this.frustumSize*i/-2,this.camera.right=this.frustumSize*i/2,this.camera.top=this.frustumSize/2,this.camera.bottom=this.frustumSize/-2,this.camera.updateProjectionMatrix()}}createRenderTarget(e=512,t=512){return this.renderTarget&&this.renderTarget.dispose(),this.renderTarget=new gi(e,t,{minFilter:Lt,magFilter:Lt}),this.renderTarget}getRenderTexture(){return this.renderTarget?.texture??null}destroy(){try{this.orbitController?.dispose()}catch{}try{this.renderTarget?.dispose()}catch{}this.renderTarget=null,this.sceneRef=null,this.targets=[],this._rendererManager=null}setDefaultOrbitTarget(e){this.orbitController?.setDefaultOrbitTarget(e)}seedDebugOrbitPose(e,t){this.isDebugViewCamera&&this.isDebugOrbitPoseSeeded()||this.orbitController?.seedOrbitPose(e,t)}isDebugOrbitPoseSeeded(){return this.orbitController?.isDebugOrbitPoseSeeded??!1}setDebugDelegate(e){this._skipDebugOrbit||this.orbitController?.setDebugDelegate(e)}frameObject(e){this.orbitController?.frameTarget(e)}move(e){(this._perspective===h.Flat2D||this._perspective===h.Fixed2D)&&(this.frustumSize=e.z),this.camera.position.set(e.x,e.y,e.z)}rotate(e,t,i){this.camera.rotateX(e),this.camera.rotateY(t),this.camera.rotateZ(i)}getDomElement(){if(this._rendererManager)return this._rendererManager.getDomElement();throw new Error("ZylemCamera: No renderer manager available. Call setup() first.")}getRendererManager(){return this._rendererManager}setRendererManager(e){this._rendererManager=e}get renderer(){return this._rendererManager?.renderer}get composer(){return this._rendererManager?.postProcessing}setPixelRatio(e){this._rendererManager?.setPixelRatio(e)}buildContext(e){let t={};for(let i=0;i<this.targets.length;i++){let r=this.targets[i],a=i===0?"primary":`target_${i}`;r.group&&(t[a]={position:r.group.position,rotation:r.group.quaternion})}return{dt:e,time:this._elapsedTime,viewport:{width:this.screenResolution.x,height:this.screenResolution.y,aspect:this.screenResolution.x/this.screenResolution.y},targets:t}}commitPose(e){if(this.camera.position.copy(e.position),e.lookAt?this.camera.lookAt(e.lookAt):this.camera.quaternion.copy(e.rotation),this.camera instanceof U&&(e.fov!=null&&(this.camera.fov=e.fov),e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()),this.camera instanceof se){if(e.zoom!=null){let t=this.screenResolution.x/this.screenResolution.y,i=e.zoom;this.camera.left=-i*t/2,this.camera.right=i*t/2,this.camera.top=i/2,this.camera.bottom=-i/2}e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()}}createCameraForPerspective(e){switch(this._perspective){case h.ThirdPerson:return new U(75,e,.1,1e3);case h.FirstPerson:return new U(75,e,.1,1e3);case h.Isometric:return new se(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);case h.Flat2D:case h.Fixed2D:return new se(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);default:return new U(75,e,.1,1e3)}}};var oe=class{cameras=new Map;_activeCameras=[];_debugCamera=null;_preDebugPrimary=null;_debugOrbitTargetAnchor=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;constructor(){}get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}get debugCamera(){return this._debugCamera}get preDebugPrimary(){return this._preDebugPrimary}get allCameras(){return Array.from(this.cameras.values())}addCamera(e,t){let i=t||e.name||`camera_${this._autoNameCounter++}`;return e.name=i,this.cameras.set(i,e),this._activeCameras.length===0&&this._activeCameras.push(e),i}removeCamera(e){let t;if(typeof e=="string")t=e;else for(let[a,n]of this.cameras.entries())if(n===e){t=a;break}if(!t)return!1;let i=this.cameras.get(t);if(!i)return!1;if(i===this._debugCamera)return console.warn("CameraManager: Cannot remove the debug camera"),!1;this.cameras.delete(t);let r=this._activeCameras.indexOf(i);return r!==-1&&this._activeCameras.splice(r,1),!0}setActiveCamera(e){let t=this.resolveCamera(e);if(!t)return console.warn(`CameraManager: Camera not found: ${e}`),!1;let i=this._activeCameras.filter(r=>r!==this._activeCameras[0]&&r.viewport.width<1);return this._activeCameras=[t,...i],!0}addActiveCamera(e){let t=this.resolveCamera(e);return t?(this._activeCameras.includes(t)||this._activeCameras.push(t),!0):!1}deactivateCamera(e){let t=this.resolveCamera(e);if(!t)return!1;let i=this._activeCameras.indexOf(t);return i!==-1?(this._activeCameras.splice(i,1),!0):!1}getCamera(e){return this.cameras.get(e)??null}async setup(e,t){this._sceneRef=e,this._rendererManager=t,this.createDebugCamera(t.screenResolution),this._debugOrbitTargetAnchor=new yi,this._debugOrbitTargetAnchor.name="__debug_orbit_target__",e.add(this._debugOrbitTargetAnchor);for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._debugCamera&&this._debugOrbitTargetAnchor&&this._debugCamera.setDefaultOrbitTarget(this._debugOrbitTargetAnchor)}activateDebugCamera(){if(!this._debugCamera)return!1;let e=this.primaryCamera;if(e===this._debugCamera)return!0;this._preDebugPrimary=e;let t=this.setActiveCamera(this._debugCamera);return t&&this.seedDebugCameraPose(e),t}deactivateDebugCamera(){if(!this._debugCamera)return!1;let e=this._preDebugPrimary;if(this._preDebugPrimary=null,e&&e!==this._debugCamera)return this.setActiveCamera(e);for(let t of this.cameras.values())if(t!==this._debugCamera)return this.setActiveCamera(t);return!1}update(e){for(let t of this._activeCameras)t.update(e)}render(e){if(!this._rendererManager||this._activeCameras.length===0)return;this.updateOrbitingCamerasForRender();let t=[],i=[];for(let r of this._activeCameras)r.renderTarget?t.push(r):i.push(r);for(let r of t)this._rendererManager.renderCameraToTarget(e,r);i.length>0&&this._rendererManager.renderCameras(e,i)}updateOrbitingCamerasForRender(){for(let e of this._activeCameras)e.isOrbitActive&&e.updateOrbitControls()}ensureDefaultCamera(){if(this.cameras.size===0||this._activeCameras.length===0){let e=this._rendererManager?.screenResolution||new fi(window.innerWidth,window.innerHeight),t=new S(h.ThirdPerson,e);return this.addCamera(t,"default"),t}return this._activeCameras[0]}dispose(){for(let e of this.cameras.values())e.destroy();this._debugCamera&&!this.cameras.has("__debug__")&&this._debugCamera.destroy(),this.cameras.clear(),this._activeCameras=[],this._debugCamera=null,this._preDebugPrimary=null,this._debugOrbitTargetAnchor&&this._sceneRef&&this._sceneRef.remove(this._debugOrbitTargetAnchor),this._debugOrbitTargetAnchor=null,this._rendererManager=null,this._sceneRef=null}createDebugCamera(e){this._debugCamera=new S(h.ThirdPerson,e),this._debugCamera.name="__debug__",this._debugCamera.isDebugViewCamera=!0,this._debugCamera.enableOrbitalControls(),this.cameras.set("__debug__",this._debugCamera)}seedDebugCameraPose(e){if(!this._debugCamera||this._debugCamera.isDebugOrbitPoseSeeded())return;let t=new ne(0,0,0),i=new ne(0,6,12);if(e&&e!==this._debugCamera){let r=e.camera.position,a=new ne().subVectors(r,t);a.lengthSq()>1&&i.copy(a.normalize().multiplyScalar(12).add(new ne(0,4,0)))}this._debugCamera.seedDebugOrbitPose(i,t)}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;if(e===this._debugCamera)return this._debugCamera;for(let t of this.cameras.values())if(t===e)return t;return null}};var y=class{cameraRef;constructor(e){this.cameraRef=e}addTarget(e){this.cameraRef.addTarget(e)}removeTarget(e){this.cameraRef.removeTarget(e)}clearTargets(){this.cameraRef.clearTargets()}enableOrbitalControls(){this.cameraRef.enableOrbitalControls()}disableOrbitalControls(){this.cameraRef.disableOrbitalControls()}setViewport(e,t,i,r){this.cameraRef.setViewport(e,t,i,r)}addBehavior(e,t){this.cameraRef.pipeline.addBehavior(e,t)}removeBehavior(e){return this.cameraRef.pipeline.removeBehavior(e)}addAction(e){this.cameraRef.pipeline.addAction(e)}setPerspective(e,t){this.cameraRef.pipeline.setPerspective(A(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function La(s){let e=Ke(s.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;s.perspective==="fixed-2d"&&(t=s.zoom||10);let i=new S(s.perspective||"third-person",e,t);s.name&&(i.name=s.name);let r=g(s.position,b),a=g(s.target,b);i.move(r),i.camera.lookAt(a);let n=s.perspective||"third-person";if(n==="fixed-2d"||n==="flat-2d"?i.pipeline.setPerspective(A(n,{zoom:t})):i.pipeline.setPerspective(A(n,{initialPosition:r.clone(),initialLookAt:a.clone()})),s.viewport&&(i.viewport={...s.viewport}),s.useOrbitalControls&&(i._useOrbitalControls=!0),s.skipDebugOrbit&&(i._skipDebugOrbit=!0),s.damping!=null&&(i.pipeline.damping=s.damping),s.behaviors)for(let[o,l]of Object.entries(s.behaviors))i.pipeline.addBehavior(o,l);if(s.renderToTexture){let{width:o=512,height:l=512}=s.renderToTexture;i.createRenderTarget(o,l)}return new y(i)}import{Vector3 as bi}from"three";function D(s){return!!s&&typeof s=="object"&&typeof s.create=="function"}function N(s){return!!s&&typeof s.then=="function"}function Oe(s){return!!s&&typeof s=="object"&&s instanceof y}function At(s){return!s||typeof s!="object"||D(s)||Oe(s)||N(s)||typeof s.then=="function"?!1:s.constructor===Object||s.constructor?.name==="Object"}function Ot(s){return s?!!(D(s)||typeof s=="function"||N(s)):!1}var vi="/three/basis/";function de(s){return{...s,ktx2TranscoderPath:s?.ktx2TranscoderPath??vi}}var le=class{constructor(e,t,i,r,a,n,o=60,l={},d=!0,c=[]){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=a;this.variables=n;this.physicsRate=o;this.assetLoaders=l;this.defaultLighting=d;this.postProcessingEffects=c}};function Ci(){return new le({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},Q,null,null,new bi(0,0,0),{},60,{},!0)}function Bt(s=[]){let e=Ci(),t={},i=[],r=[],a=[];for(let l of s)Oe(l)?a.push(l):D(l)?i.push(l):Ot(l)&&!D(l)?r.push(l):At(l)&&(t={...t,...l});let n=new le(t.inputs??e.inputs,t.backgroundColor??e.backgroundColor,t.backgroundImage??e.backgroundImage,t.backgroundShader??e.backgroundShader,t.gravity??e.gravity,t.variables??e.variables,t.physicsRate??e.physicsRate,t.assetLoaders??e.assetLoaders,t.defaultLighting??e.defaultLighting,t.postProcessingEffects??e.postProcessingEffects),o=a.length>0?a[0]:void 0;return{config:n,entities:i,asyncEntities:r,camera:o,cameras:a}}function Va(s){return{...s}}var Si=Symbol("vessel"),W=class extends O{static type=Si;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=Pi();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function Pi(...s){let e=new W;return s.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Wt,Vector3 as Ht}from"three";import{createSimulation as wi}from"@zylem/behaviors/core";function Be(s){return typeof s?.handlePostCollision=="function"&&typeof s?.handleIntersectionEvent=="function"}function Ei(s,e){return s<e?`${s}|${e}`:`${e}|${s}`}var ce=class s{type="World";simulation;collisionMap=new Map;collisionBehaviorMap=new Map;_removalMap=new Map;activeCollisionPairs=new Map;livePairs=new Map;handleIdToUuid=new Map;currentCollisionTimeMs=0;zeroGravity;fixedTimestep;interpolationAlpha=0;stepClock={steps:0};static async create(e,t=60){let i={x:e?.x??0,y:e?.y??0,z:e?.z??0},r=await wi({gravity:[i.x,i.y,i.z],fixedTimestep:1/t,initialCapacity:4096});return new s(r,t,i.x===0&&i.y===0&&i.z===0)}constructor(e,t=60,i=!1){this.simulation=e,this.fixedTimestep=1/t,this.zeroGravity=i,this.simulation?.setEventsEnabled?.(!1)}addEntity(e){let t={...e.bodyDesc??{}},i=e.colliderDescs?.length?e.colliderDescs:e.colliderDesc?[e.colliderDesc]:[];this.zeroGravity&&(t.lockTranslation=t.lockTranslation??[!0,!0,!0],t.lockRotation=t.lockRotation??[!0,!0,!0]),(e.controlledRotation||e instanceof j)&&e.bodyDesc?.lockRotation===void 0&&(t.lockRotation=[!0,!0,!0]);let r=this.simulation.spawn({body:t,colliders:i});if(!r){console.warn(`ZylemWorld: failed to spawn entity ${e.uuid} into simulation`);return}e.body=new et(this.simulation,r,this.stepClock),e.physicsAttached=!0,e.physicsWorldRef=this,e.simulationHandle=r,e.runtimeHandle=r.slot,e.runtimeAttached=!0,e.wasmStageRef=this.simulation.adapter,this.handleIdToUuid.set(r.id,e.uuid),this.collisionMap.set(e.uuid,e)}setForRemoval(e){e.physicsAttached&&this._removalMap.set(e.uuid,e)}destroyEntity(e){if(!(e.physicsWorldRef===this)){this.removeEntityFromTracking(e.uuid);return}let i=e.simulationHandle;if(i){try{this.simulation.despawn(i)}catch{}this.handleIdToUuid.delete(i.id)}this.removeEntityFromTracking(e.uuid),this.clearEntityPhysicsState(e)}setup(){}update(e){let{delta:t}=e;this.currentCollisionTimeMs+=t*1e3,this.processPendingRemovals();let i=this.hasCollisionPhaseListeners();i&&!this.simulation.areEventsEnabled&&this.simulation.setEventsEnabled?.(!0);let r=this.simulation.update(t);this.stepClock.steps+=r.stepsTaken,this.interpolationAlpha=r.alpha,i&&(this.applyCollisionEvents(r.events),this.processCollisionPairs(t,this.currentCollisionTimeMs))}hasCollisionPhaseListeners(){for(let e of this.collisionMap.values())if(e?.collisionDelegate?.collision?.length)return!0;return!1}applyCollisionEvents(e){for(let t of e){if(t.type!=="collisionStarted"&&t.type!=="collisionStopped")continue;let i=t.a?this.handleIdToUuid.get(t.a.id):void 0,r=t.b?this.handleIdToUuid.get(t.b.id):void 0;if(!i||!r||i===r)continue;let a=Ei(i,r),n=this.livePairs.get(a);n||(n={uuidA:i<r?i:r,uuidB:i<r?r:i,contactCount:0,intersectionCount:0},this.livePairs.set(a,n));let o=t.type==="collisionStarted"?1:-1;t.sensor?n.intersectionCount=Math.max(0,n.intersectionCount+o):n.contactCount=Math.max(0,n.contactCount+o),n.contactCount===0&&n.intersectionCount===0&&this.livePairs.delete(a)}}snapshotLivePairs(){let e=new Map;for(let[t,i]of this.livePairs)e.set(t,{uuidA:i.uuidA,uuidB:i.uuidB,hasContact:i.contactCount>0,hasIntersection:i.intersectionCount>0});return e}updatePostCollisionBehaviors(e){let t=this.collisionBehaviorMap;for(let[i,r]of t){let a=r;if(!Be(a))continue;a.handlePostCollision({entity:a,delta:e})||this.collisionBehaviorMap.delete(i)}}processPendingRemovals(){if(this._removalMap.size!==0){for(let[,e]of this._removalMap)this.destroyEntity(e);this._removalMap.clear()}}removeEntityFromTracking(e){this.collisionMap.delete(e),this._removalMap.delete(e),this.pruneActiveCollisionPairs(e)}pruneActiveCollisionPairs(e){for(let[t,i]of this.activeCollisionPairs)(i.uuidA===e||i.uuidB===e)&&this.activeCollisionPairs.delete(t);for(let[t,i]of this.livePairs)(i.uuidA===e||i.uuidB===e)&&this.livePairs.delete(t)}entityHasCollisionPhaseListener(e,t){let i=e?.collisionDelegate.collision;if(!i?.length)return!1;for(let r of i)if(r.options.phase===t)return!0;return!1}processCollisionPairs(e,t=this.currentCollisionTimeMs){let i=this.snapshotLivePairs();for(let[r,a]of i){let n=this.collisionMap.get(a.uuidA),o=this.collisionMap.get(a.uuidB);this.activeCollisionPairs.has(r)||this.dispatchCollisionPhase(a,"enter",t),(this.entityHasCollisionPhaseListener(n,"stay")||this.entityHasCollisionPhaseListener(o,"stay"))&&this.dispatchCollisionPhase(a,"stay",t),a.hasIntersection&&this.dispatchIntersectionDelegates(a,e)}this.updatePostCollisionBehaviors(e),this.activeCollisionPairs=i}dispatchCollisionPhase(e,t,i){let r={phase:t,nowMs:i},a=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);a&&n&&a._collision(n,Pe.globals,r);let o=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);o&&l&&l._collision(o,Pe.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&Be(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let a=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);a&&n&&Be(n)&&(n.handleIntersectionEvent({entity:n,other:a,delta:t}),this.collisionBehaviorMap.set(n.uuid,n))}raycast(e,t,i){let r=this.simulation.castRay([e.x,e.y,e.z],[t.x,t.y,t.z],i,!0);return r?{uuid:r.entity?this.handleIdToUuid.get(r.entity.id)??null:null,distance:r.distance,normal:r.normal}:null}destroy(){try{for(let[,e]of this.collisionMap)try{this.clearEntityPhysicsState(e)}catch{}try{this.simulation.dispose()}catch{}this.collisionMap.clear(),this.collisionBehaviorMap.clear(),this._removalMap.clear(),this.activeCollisionPairs.clear(),this.livePairs.clear(),this.handleIdToUuid.clear()}catch{}}clearEntityPhysicsState(e){e.physicsAttached=!1,e.body=null,e.runtimeHandle=-1,e.runtimeAttached=!1,e.wasmStageRef=null,e.simulationHandle=void 0,e.physicsWorldRef===this&&(e.physicsWorldRef=null)}};import{Scene as Di,Color as Ft,AmbientLight as Mi,DirectionalLight as _i,Vector3 as ue,GridHelper as Ti,Texture as xi,SRGBColorSpace as Ri}from"three";var me=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new Di,n=i.backgroundColor instanceof Ft?i.backgroundColor:new Ft(i.backgroundColor);r.background=n,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&R.loadTexture(i.backgroundImage,{colorSpace:Ri}).then(o=>{r.background=o}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),u.enabled&&this.debugScene()}setupBackgroundShader(e,t){if(!Je(t)){console.warn("ZylemScene: GLSL background shaders are not supported on the WebGPU renderer. Provide a TSL shader (ZylemTSLShader) as backgroundShader. Keeping solid background.");return}e.background=null,e.backgroundNode=t.colorNode}setup(){this._setup&&this._setup({me:this,camera:this.zylemCamera,globals:P()})}destroy(){this.cameraManager?(this.cameraManager.dispose(),this.cameraManager=null):this.zylemCamera&&this.zylemCamera.destroy&&this.zylemCamera.destroy(),this.scene&&(this.scene.backgroundNode=null,this.scene.background instanceof xi&&(this.scene.background.dispose(),this.scene.background=null),this.scene.traverse(e=>{if(e.geometry&&e.geometry.dispose?.(),e.material){let t=Array.isArray(e.material)?e.material:[e.material];for(let i of t)i.map&&i.map.dispose?.(),i.normalMap&&i.normalMap.dispose?.(),i.aoMap&&i.aoMap.dispose?.(),i.emissiveMap&&i.emissiveMap.dispose?.(),i.roughnessMap&&i.roughnessMap.dispose?.(),i.metalnessMap&&i.metalnessMap.dispose?.(),i.envMap&&i.envMap.dispose?.(),i.lightMap&&i.lightMap.dispose?.(),i.bumpMap&&i.bumpMap.dispose?.(),i.displacementMap&&i.displacementMap.dispose?.(),i.alphaMap&&i.alphaMap.dispose?.(),i.dispose?.()}e.isLight&&e.shadow?.map&&e.shadow.map.dispose()}),this.scene.clear())}async setupCamera(e,t,i){this.addCameraToScene(e,t),i?await t.setup(e,i):await t.setupLegacy(e)}async setupCameraManager(e,t,i){this.cameraManager=t;for(let r of t.activeCameras)this.addCameraToScene(e,r);await t.setup(e,i)}addCameraToScene(e,t){t.cameraRig?e.add(t.cameraRig):e.add(t.camera)}setupLighting(e){let t=new Mi(16777215,1);e.add(t);let i=new _i(16777215,2);i.name="Light",i.position.set(0,100,0),i.castShadow=!0,i.shadow.camera.near=.1,i.shadow.camera.far=2e3,i.shadow.camera.left=-100,i.shadow.camera.right=100,i.shadow.camera.top=100,i.shadow.camera.bottom=-100,i.shadow.mapSize.width=2048,i.shadow.mapSize.height=2048,e.add(i)}updateRenderer(e,t){if(this.cameraManager)for(let i of this.cameraManager.allCameras)i.resize(e,t);else this.zylemCamera.resize(e,t)}add(e,t=new ue(0,0,0)){e.position.set(t.x,t.y,t.z),this.scene.add(e)}addEntity(e){let t=e.group??e.mesh;!t||this.isAttachedOutsideScene(t)||this.add(t,e.options.position)}addEntityGroup(e){if(k(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=ki(e);i&&i.attachToScene(this.scene);let r=e.options.position??new ue(0,0,0);if(e.physicsAttached&&e.body)try{let a=e.body.translation();r=new ue(a.x,a.y,a.z)}catch{r=e.options.position??new ue(0,0,0)}this.add(t,r),B(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new Ti(1e3,100);this.scene.add(i)}};function ki(s){return s.constructor.type===tt?s:null}var pe=class{update=()=>{};setup=()=>{};destroy=()=>{};nodeSetup(e){typeof this._setup=="function"&&this._setup(e),this.setup&&this.setup(e)}nodeUpdate(e){typeof this._update=="function"&&this._update(e),this.update&&this.update(e)}nodeDestroy(e){this.destroy&&this.destroy(e),typeof this._destroy=="function"&&this._destroy(e)}};import{Quaternion as Li}from"three";var It=new Li;function Zt(s){let e=s._childrenMap,t=s._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval||i.isInstanced||i.isBundled||i.skipRenderPoseSync)continue;let r=i.body,a=i.group??i.mesh,n=a?K(r,t?.interpolationAlpha??0):null;a&&n&&a.position.set(n.position.x,n.position.y,n.position.z),!i.controlledRotation&&a&&n&&(It.set(n.rotation.x,n.rotation.y,n.rotation.z,n.rotation.w),a.setRotationFromQuaternion(It))}}import{nanoid as qi}from"nanoid";import{BufferAttribute as Ut,BufferGeometry as Gi,LineBasicMaterial as Ui,LineSegments as Ni,Raycaster as Wi,Vector2 as Hi}from"three";import{subscribe as ji}from"valtio/vanilla";import{subscribe as Ai}from"valtio/vanilla";var he=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),Ai(u,t)}resolveTarget(e){let t=this.stage.entityDelegate.debugMap.get(e)||this.stage.entityDelegate.childrenMap.get(e)||this.stage.world?.collisionMap.get(e)||null;return t?.group??t?.mesh??null??null}snapshot(){return{enabled:u.enabled,selected:u.selectedEntityId?[u.selectedEntityId]:[]}}};import{Box3 as Oi,BoxGeometry as zt,Color as Bi,EdgesGeometry as Vt,Group as Fi,LineBasicMaterial as Ii,LineSegments as Zi,Mesh as zi,MeshBasicMaterial as Vi,Vector3 as Gt}from"three";var ge=class{scene;container;fillMesh;edgeLines;currentColor=new Bi(65280);bbox=new Oi;size=new Gt;center=new Gt;constructor(e){this.scene=e;let t=new zt(1,1,1);this.fillMesh=new zi(t,new Vi({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new Vt(t);this.edgeLines=new Zi(i,new Ii({color:this.currentColor,linewidth:1})),this.container=new Fi,this.container.name="DebugEntityCursor",this.container.add(this.fillMesh),this.container.add(this.edgeLines),this.container.visible=!1,this.scene.add(this.container)}setColor(e){this.currentColor.set(e),this.fillMesh.material.color.set(this.currentColor),this.edgeLines.material.color.set(this.currentColor)}updateFromObject(e){if(!e){this.hide();return}if(this.bbox.setFromObject(e),!isFinite(this.bbox.min.x)||!isFinite(this.bbox.max.x)){this.hide();return}this.bbox.getSize(this.size),this.bbox.getCenter(this.center);let t=new zt(Math.max(this.size.x,1e-6),Math.max(this.size.y,1e-6),Math.max(this.size.z,1e-6));this.fillMesh.geometry.dispose(),this.fillMesh.geometry=t;let i=new Vt(t);this.edgeLines.geometry.dispose(),this.edgeLines.geometry=i,this.container.position.copy(this.center),this.container.visible=!0}hide(){this.container.visible=!1}dispose(){this.scene.remove(this.container),this.fillMesh.geometry.dispose(),this.fillMesh.material.dispose(),this.edgeLines.geometry.dispose(),this.edgeLines.material.dispose()}};var Ki=2293538,Qi=16724787,fe=class{stage;options;mouseNdc=new Hi(-2,-2);raycaster=new Wi;isMouseDown=!1;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;debugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;focusContextUnregister=null;entityResolverUnregister=null;lastDebugEnabled=null;warnedMissingAddFactory=!1;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.syncWithDebugState(),this.debugStateUnsubscribe=ji(u,()=>{this.syncWithDebugState()}),this.entityResolverUnregister=Ie(i=>this.resolveEntity(i)),this.focusContextUnregister=He({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{this.ensureCameraDebugDelegate(),this.getDebugViewCamera()?.frameObject(i)},ensureDebugReady:()=>{u.enabled||(u.enabled=!0),this.lastDebugEnabled=!0,this.activate()}})}setAddEntityFactory(e){this.options.addEntityFactory=e,this.warnedMissingAddFactory=!1}getDebugViewCamera(){return this.stage.cameraManagerRef?.primaryCamera??this.stage.cameraManagerRef?.debugCamera??this.stage.cameraRef??null}resolveEntity(e){let t=this.stage.entityDelegate.debugMap.get(e);if(t)return t;let i=this.stage.entityDelegate.childrenMap.get(e);return i||(this.stage.world?.collisionMap.get(e)??null)}populateDebugMap(){this.stage.entityDelegate.childrenMap.forEach((e,t)=>{this.stage.entityDelegate.debugMap.set(t,e)})}ensureCameraDebugDelegate(){let e=this.stage.cameraManagerRef?.debugCamera??null;e&&(this.cameraDebugDelegate||(this.cameraDebugDelegate=new he(this.stage)),e.setDebugDelegate(this.cameraDebugDelegate))}syncWithDebugState(){let e=u.enabled;e!==this.lastDebugEnabled&&(this.lastDebugEnabled=e,e?this.activate():this.deactivate())}activate(){this.domListenersAttached||(this.domListenersAttached=this.attachDomListeners()),this.populateDebugMap(),this.stage.cameraManagerRef?.activateDebugCamera();let e=this.stage.cameraManagerRef?.debugCamera??null;this.rebindPostProcessing(e),this.ensureCameraDebugDelegate(),document.pointerLockElement&&document.exitPointerLock()}deactivate(){this.disposeDebugVisuals();let e=this.stage.cameraManagerRef?.debugCamera;e&&e.setDebugDelegate(null),this.stage.cameraRef&&this.stage.cameraRef!==e&&this.stage.cameraRef.setDebugDelegate(null),this.cameraDebugDelegate=null,this.stage.cameraManagerRef?.deactivateDebugCamera();let t=this.stage.cameraManagerRef?.primaryCamera??this.stage.cameraRef??null;this.rebindPostProcessing(t)}rebindPostProcessing(e){let t=this.stage.scene?.scene,i=this.stage.rendererManager;t&&i&&e&&i.setupPostProcessing(t,e.camera)}initDebugVisuals(){this.debugLines||!this.stage.scene||(this.debugLines=new Ni(new Gi,new Ui({vertexColors:!0})),this.stage.scene.scene.add(this.debugLines),this.debugLines.visible=!0,this.debugCursor=new ge(this.stage.scene.scene))}disposeDebugVisuals(){this.debugLines&&this.stage.scene&&(this.stage.scene.scene.remove(this.debugLines),this.debugLines.geometry.dispose(),this.debugLines.material.dispose(),this.debugLines=null),this.debugCursor?.dispose(),this.debugCursor=null}update(){if(!u.enabled){this.debugLines&&this.disposeDebugVisuals();return}let e=this.getDebugViewCamera();if(!this.stage.scene||!this.stage.world||!e)return;this.debugLines||this.initDebugVisuals();let{world:t}=this.stage;if(this.debugLines){let p=t.simulation.getDebugRender();p&&p.vertices.length>0?(this.debugLines.geometry.setAttribute("position",new Ut(new Float32Array(p.vertices),3)),this.debugLines.geometry.setAttribute("color",new Ut(new Float32Array(p.colors),4)),this.debugLines.geometry.attributes.position.needsUpdate=!0,this.debugLines.geometry.attributes.color.needsUpdate=!0,this.debugLines.visible=!0):this.debugLines.visible=!1}let i=we(),r=i==="select"||i==="delete";if(!(r||i==="add")){this.isMouseDown=!1,this.debugCursor?.hide();return}this.raycaster.setFromCamera(this.mouseNdc,e.camera);let n=this.raycaster.ray.origin.clone(),o=this.raycaster.ray.direction.clone().normalize(),l=t.raycast(n,o,this.options.maxRayDistance);l?(r&&Ve(l.uuid??null),this.isMouseDown&&this.handleActionOnHit(l.uuid??null,n,o,l.distance)):r&&Ge(),this.isMouseDown=!1;let d=r?ze():null;if(!d){this.debugCursor?.hide();return}let c=this.resolveEntity(d),m=c?.group??c?.mesh??null;if(!m){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(Ki);break;case"delete":this.debugCursor?.setColor(Qi);break;default:this.debugCursor?.setColor(16777215);break}this.debugCursor?.updateFromObject(m)}dispose(){this.focusContextUnregister?.(),this.focusContextUnregister=null,this.entityResolverUnregister?.(),this.entityResolverUnregister=null,this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.deactivate(),this.domDisposeFns.forEach(e=>e()),this.domDisposeFns=[],this.domListenersAttached=!1}handleActionOnHit(e,t,i,r){switch(we()){case"select":{e&&this.resolveEntity(e)&&Ze(e);break}case"delete":{e&&this.stage.entityDelegate.removeEntityByUuid(e);break}case"add":{if(!this.options.addEntityFactory){if(!this.warnedMissingAddFactory){this.warnedMissingAddFactory=!0;let l="Add tool: no `addEntityFactory` configured for this stage, so there is nothing to spawn.";console.warn(l),je("warn",l)}break}let n=t.clone().add(i.clone().multiplyScalar(r)),o=this.options.addEntityFactory({position:n});o&&Promise.resolve(o).then(l=>{l&&this.stage.entityDelegate.spawnEntity(l)}).catch(()=>{});break}default:break}}attachDomListeners(){let e=this.stage.rendererManager?.getDomElement();if(!e)return!1;let t=r=>{let a=e.getBoundingClientRect(),n=(r.clientX-a.left)/a.width*2-1,o=-((r.clientY-a.top)/a.height*2-1);this.mouseNdc.set(n,o)},i=()=>{this.isMouseDown=!0};return e.addEventListener("mousemove",t),e.addEventListener("mousedown",i),this.domDisposeFns.push(()=>e.removeEventListener("mousemove",t)),this.domDisposeFns.push(()=>e.removeEventListener("mousedown",i)),!0}};import{Vector2 as Yi}from"three";var ye=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Yi(e,t);return new S(h.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new oe;if(e)return i.addCamera(e,e.name||"main"),i;let r=t.filter(a=>a!==void 0);if(r.length>0){for(let a of r){let n=a.cameraRef;i.addCamera(n,n.name||void 0)}for(let a=1;a<r.length;a++)i.addActiveCamera(r[a].cameraRef)}else{let a=this.createDefaultCamera();i.addCamera(a,"default")}return i}};var be=class{loadingHandlers=[];stageName;stageIndex;setStageContext(e,t){this.stageName=e,this.stageIndex=t}onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let i of this.loadingHandlers)try{i(e)}catch(r){console.error("Loading handler failed",r)}let t={...e,stageName:this.stageName,stageIndex:this.stageIndex};e.type==="start"?H.emit("stage:loading:start",t):e.type==="progress"?H.emit("stage:loading:progress",t):e.type==="complete"&&H.emit("stage:loading:complete",t)}emitStart(e="Loading stage..."){this.emit({type:"start",message:e,progress:0})}emitProgress(e,t,i){let r=i>0?t/i:0;this.emit({type:"progress",message:e,progress:r,current:t,total:i})}emitComplete(e="Stage loaded"){this.emit({type:"complete",message:e,progress:1})}dispose(){this.loadingHandlers=[]}};var ve=class{scene=null;onEntityReady=null;pendingEntities=new Map;modelLoadedHandler=null;attach(e,t){this.scene=e,this.onEntityReady=t??null,this.modelLoadedHandler=i=>{this.handleModelLoaded(i.entityId,i.success)},w.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){I(e.options)||(this.scene?.addEntityGroup(e),B(e),x(e),this.onEntityReady?.(e));return}this.pendingEntities.set(e.uuid,e)}unobserve(e){this.pendingEntities.delete(e)}handleModelLoaded(e,t){let i=this.pendingEntities.get(e);if(!i||!t){this.pendingEntities.delete(e);return}this.scene?.addEntityGroup(i),B(i),x(i),I(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(w.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as Nt}from"@zylem/behaviors/core";var Ce=class s{static EMPTY_BEHAVIOR_LINKS=[];children=[];childrenMap=new Map;debugMap=new Map;pendingEntities=[];pendingPromises=[];_isLoaded=!1;entityAddedHandlers=[];behaviorSystems=[];behaviorSystemByKey=new Map;registeredSystemKeys=new Set;behaviorEntityIndex=new Map;behaviorLinksByUuid=new Map;scene=null;world=null;renderStrategy=null;camera=null;wasmStage=null;loadingDelegate;entityModelDelegate;constructor(e,t){this.loadingDelegate=e,this.entityModelDelegate=t}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}attach(e){this.scene=e.scene,this.world=e.world,this.renderStrategy=e.renderStrategy,this.camera=e.camera,this.wasmStage=e.world.simulation.adapter}async spawnEntity(e){if(!this.scene||!this.world)return;if(e instanceof W){e.create();for(let i of e.getChildren())i instanceof O&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:P(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();Ye(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof O&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:P(),camera:this.camera}),this.tryRegisterRenderStrategy(t),k(t)||this.scene.addEntityGroup(t),x(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),qe(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),k(e)||this.scene.addEntityGroup(e),x(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(F(e.options)!=="environment")return;let t=e.options.collision??{};t.static!==!0&&(console.warn(`category 'environment' forces static collision for entity '${e.name||e.uuid}'`),e.options.collision={...t,static:!0}),e.bodyDesc&&e.bodyDesc.kind!==Nt.Static&&(e.bodyDesc.kind=Nt.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof j){if(e.needsDeferredModelCollision())return;e.synchronizeRuntimeCollider()}this.world.addEntity(e)}}addEntityToStage(e){this.childrenMap.set(e.uuid,e),u.enabled&&this.debugMap.set(e.uuid,e);for(let t of this.entityAddedHandlers)try{t(e)}catch(i){console.error("onEntityAdded handler failed",i)}}removeEntityByUuid(e){if(!this.scene||!this.world)return!1;let t=this.world.collisionMap.get(e),i=this.childrenMap.get(e),r=t??i??this.debugMap.get(e);return r?(this.unregisterBehaviorLinks(r),this.entityModelDelegate.unobserve(e),k(r)&&this.renderStrategy?.unregister(r),this.world.destroyEntity(r),r.group?this.scene.scene.remove(r.group):r.mesh&&this.scene.scene.remove(r.mesh),this.childrenMap.delete(e),this.debugMap.delete(e),w.emit("entity:destroyed",{entityId:e}),!0):!1}getEntityByName(e){for(let t of this.childrenMap.values())if(t.name===e)return t;return console.warn(`Entity ${e} not found`),null}buildEntityState(e){return e instanceof $e?{...e.buildInfo()}:{uuid:e.uuid,name:e.name}}onEntityAdded(e,t){return this.entityAddedHandlers.push(e),t?.replayExisting&&this._isLoaded&&this.childrenMap.forEach(i=>{try{e(i)}catch(r){console.error("onEntityAdded replay failed",r)}}),()=>{this.entityAddedHandlers=this.entityAddedHandlers.filter(i=>i!==e)}}enqueue(...e){for(let t of e)if(t){if(D(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();D(i)?this.handleEntityImmediatelyOrQueue(i):N(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}N(t)&&this.handlePromiseWithSpawnOnResolve(t)}}handleEntityImmediatelyOrQueue(e){this._isLoaded?this.spawnEntity(e):this.children.push(e)}handlePromiseWithSpawnOnResolve(e){this._isLoaded?e.then(t=>this.spawnEntity(t)).catch(t=>console.error("Failed to build async entity",t)):this.pendingPromises.push(e)}yieldToEventLoop(){return new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>e(),t.port2.postMessage(void 0)})}async runEntityLoadGenerator(){let t=0;if(this.pendingEntities.length){let a=[...this.pendingEntities];this.pendingEntities=[],this.enqueue(...a)}let i=[...this.pendingPromises];this.pendingPromises=[];let r=this.children.length+i.length;for(let a of this.children)await this.spawnEntity(a),t++,this.loadingDelegate.emitProgress(`Loaded ${a.name||"unknown"}`,t,r),t%5===0&&await this.yieldToEventLoop();for(let a of i){try{let n=await a;n&&await this.spawnEntity(n)}catch(n){console.error("Failed to resolve pending stage entity",n)}t++,this.loadingDelegate.emitProgress("Loaded async entity",t,r),t%5===0&&await this.yieldToEventLoop()}t%5!==0&&await this.yieldToEventLoop()}registerSystem(e){if(!this.world||!this.scene)return;let t;typeof e=="function"?t=e({world:this.world,scene:this.scene,getBehaviorLinks:i=>this.behaviorEntityIndex.get(i)??s.EMPTY_BEHAVIOR_LINKS,createEntity:Ee,getGlobals:P}):t=e,this.behaviorSystems.push(t)}destroyAll(){for(let t of this.behaviorSystems)t.destroy?.();this.behaviorSystems.length=0,this.behaviorSystemByKey.clear(),this.registeredSystemKeys.clear(),this.behaviorEntityIndex.clear(),this.behaviorLinksByUuid.clear();let e=[];this.childrenMap.forEach(t=>{try{t.nodeDestroy({me:t,globals:P()})}catch{}q(t),e.push(t.uuid)}),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[];for(let t of e)w.emit("entity:destroyed",{entityId:t});this._isLoaded=!1,this.scene=null,this.world=null,this.renderStrategy=null,this.camera=null,this.wasmStage=null}registerBehaviorLinks(e){if(!this.world||!this.scene||typeof e?.getBehaviorRefs!="function")return;let t=e.getBehaviorRefs();if(!Array.isArray(t)||t.length===0)return;let i=[];for(let r of t){let a=r.descriptor.key,n={entity:e,ref:r};i.push(n);let o=this.behaviorEntityIndex.get(a);o||(o=new Set,this.behaviorEntityIndex.set(a,o)),o.add(n);let l=this.behaviorSystemByKey.get(a);if(!l&&!this.registeredSystemKeys.has(a)){let d=r.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:c=>this.behaviorEntityIndex.get(c)??s.EMPTY_BEHAVIOR_LINKS,createEntity:Ee,getGlobals:P});l=d,this.behaviorSystems.push(d),this.behaviorSystemByKey.set(a,d),this.registeredSystemKeys.add(a)}l?.attach?.(n)}this.behaviorLinksByUuid.set(e.uuid,i)}unregisterBehaviorLinks(e){let t=this.behaviorLinksByUuid.get(e?.uuid);if(t){for(let i of t){let r=i.ref?.descriptor?.key;if(!r)continue;let a=this.behaviorEntityIndex.get(r);a&&(this.behaviorSystemByKey.get(r)?.detach?.(i),a.delete(i),a.size===0&&this.behaviorEntityIndex.delete(r))}this.behaviorLinksByUuid.delete(e.uuid)}}};var $i="Stage",Se=class extends pe{type=$i;state={...it};gravity;world;scene;renderStrategy=null;debugDelegate=null;uuid;wrapperRef=null;camera;cameras=[];cameraRef=null;cameraManagerRef=null;rendererManager=null;cameraDelegate;loadingDelegate;entityModelDelegate;childUpdateParams={};entityDelegate;constructor(e=[]){super(),this.world=null,this.scene=null,this.uuid=qi(),this.cameraDelegate=new ye(this),this.loadingDelegate=new be,this.entityModelDelegate=new ve,this.entityDelegate=new Ce(this.loadingDelegate,this.entityModelDelegate);let t=Bt(e);this.camera=t.camera,this.cameras=t.cameras,this.entityDelegate.children=t.entities,t.asyncEntities.length&&this.entityDelegate.enqueue(...t.asyncEntities),this.state={...this.state,inputs:t.config.inputs,backgroundColor:t.config.backgroundColor,backgroundImage:t.config.backgroundImage,backgroundShader:t.config.backgroundShader,gravity:t.config.gravity,variables:t.config.variables,physicsRate:t.config.physicsRate,assetLoaders:t.config.assetLoaders,defaultLighting:t.config.defaultLighting,postProcessingEffects:t.config.postProcessingEffects,entities:[]},this.gravity=t.config.gravity??new Ht(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Wt?e:new Wt(e);rt(i),at(t),st(this.state.variables??{})}resolveRenderer(e){return this.rendererManager?.renderer?this.rendererManager.renderer:e.renderer?e.renderer:null}async load(e,t,i){this.setState(),i&&(this.rendererManager=i),this.rendererManager&&(this.cameraManagerRef=this.cameraDelegate.buildCameraManager(t,...this.cameras));let r=this.cameraManagerRef?.primaryCamera??this.cameraDelegate.resolveCamera(t,this.camera);this.cameraRef=r,this.scene=new me(e,r,this.state);let a=this.gravity??new Ht(0,0,0);if(this.world=await ce.create(a,this.state.physicsRate),this.scene.setup(),this.cameraManagerRef&&this.rendererManager){await this.scene.setupCameraManager(this.scene.scene,this.cameraManagerRef,this.rendererManager);let o=this.cameraManagerRef.primaryCamera;o&&(this.rendererManager.setPostProcessingEffects(this.state.postProcessingEffects??[]),this.rendererManager.setupPostProcessing(this.scene.scene,o.camera)),this.rendererManager.startRenderLoop(()=>{this.cameraManagerRef?.render(this.scene.scene)})}else await this.scene.setupCamera(this.scene.scene,r);let n=this.resolveRenderer(r);await R.configureGLTFRuntime({renderer:n,...de(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,o=>this.entityDelegate.handleLateModelReady(o)),this.renderStrategy=new J,this.renderStrategy.setScene(this.scene.scene),this.entityDelegate.attach({scene:this.scene,world:this.world,renderStrategy:this.renderStrategy,camera:r}),this.loadingDelegate.emitStart(),await this.entityDelegate.runEntityLoadGenerator(),this.entityDelegate.isLoaded=!0,this.loadingDelegate.emitComplete()}hasSetup=!1;_setup(e){if(!this.hasSetup){if(!this.scene||!this.world){this.logMissingEntities();return}this.debugDelegate=new fe(this),this.hasSetup=!0}}_update(e){let{delta:t}=e;if(!this.scene||!this.world){this.logMissingEntities();return}let i=this.world,r=this.scene;C("behaviorSystems",()=>{for(let a of this.entityDelegate.behaviorSystems)a.update(void 0,t)}),C("entityLoop",()=>{for(let a of this.entityDelegate.childrenMap.values()){let n=this.childUpdateParams;n.delta=e.delta,n.inputs=e.inputs,n.globals=e.globals,n.camera=e.camera,n.stage=e.stage,n.game=e.game,n.me=a,a.nodeUpdate(n);let o=a;o.transformStore&&ot(o,o.transformStore),a.markedForRemoval&&this.entityDelegate.removeEntityByUuid(a.uuid)}}),C("worldUpdate",()=>{i.update(e)}),C("behaviorPostUpdate",()=>{for(let a of this.entityDelegate.behaviorSystems)a.postUpdate?.(void 0,t)}),C("syncRenderPoses",()=>{Zt({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),C("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),C("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),C("scene",()=>{r.update({delta:t})}),Et()}outOfLoop(){this.debugUpdate()}debugUpdate(){u.enabled&&(Te("debugUpdate"),this.debugDelegate?.update(),xe())}_destroy(e){this.entityDelegate.destroyAll(),this.world?.destroy(),this.scene?.destroy(),this.debugDelegate?.dispose(),this.debugDelegate=null,this.entityModelDelegate.dispose(),this.renderStrategy?.dispose(),this.renderStrategy=null,this.rendererManager&&this.rendererManager.stopRenderLoop(),this.world=null,this.scene=null,this.cameraRef=null,this.cameraManagerRef=null,nt(),q(this)}async spawnEntity(e){return this.entityDelegate.spawnEntity(e)}buildEntityState(e){return this.entityDelegate.buildEntityState(e)}onEntityAdded(e,t){return this.entityDelegate.onEntityAdded(e,t)}onLoading(e){return this.loadingDelegate.onLoading(e)}registerSystem(e){return this.entityDelegate.registerSystem(e),this}removeEntityByUuid(e){return this.entityDelegate.removeEntityByUuid(e)}getEntityByName(e){return this.entityDelegate.getEntityByName(e)}enqueue(...e){this.entityDelegate.enqueue(...e)}logMissingEntities(){console.warn("Zylem world or scene is null")}addCamera(e,t){return this.cameraManagerRef?this.cameraManagerRef.addCamera(e,t):(console.warn("ZylemStage: CameraManager not available. Ensure stage is loaded with a RendererManager."),null)}removeCamera(e){return this.cameraManagerRef?.removeCamera(e)??!1}setActiveCamera(e){return this.cameraManagerRef?.setActiveCamera(e)??!1}getCamera(e){return this.cameraManagerRef?.getCamera(e)??null}resize(e,t){this.scene&&this.scene.updateRenderer(e,t)}};import{proxy as Xi}from"valtio/vanilla";import{Vector3 as Ji}from"three";var er={backgroundColor:Q,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new Ji(0,0,0),variables:{}},T=Xi({...er});function jt(s){let e=tr(),t={};return typeof s[0]=="object"&&(t=s.shift()??{}),[{...e,...t},...s]}function tr(){return{backgroundColor:T.backgroundColor,backgroundImage:T.backgroundImage??null,inputs:T.inputs?{...T.inputs}:void 0,gravity:T.gravity,variables:T.variables?{...T.variables}:void 0}}var Fe=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new We;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];R.prepareGLTFRuntime(de(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=Ne(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){Y.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new Se(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(d=>{this.wrappedStage.onLoading(d)}),this.pendingLoadingCallbacks=[];let a=t instanceof y?t.cameraRef:t;await this.wrappedStage.load(e,a,i);let n=null,o=!1,l=()=>{if(o=!1,!n?.length){n=null;return}let d=n;n=null,Y.entities=[...Y.entities,...d]};this.wrappedStage.onEntityAdded(d=>{if(I(d.options))return;let c=this.wrappedStage.buildEntityState(d);n||(n=[]),n.push(c),o||(o=!0,queueMicrotask(l))},{replayExisting:!0}),this.applyLifecycleCallbacks()}applyLifecycleCallbacks(){this.wrappedStage&&(this.setupCallbacks.length>0&&(this.wrappedStage.setup=e=>{let t={...e,stage:this};this.setupCallbacks.forEach(i=>i(t))}),this.updateCallbacks.length>0&&(this.wrappedStage.update=e=>{let t={...e,stage:this};this.updateCallbacks.forEach(i=>i(t))}),this.destroyCallbacks.length>0&&(this.wrappedStage.destroy=e=>{let t={...e,stage:this};this.destroyCallbacks.forEach(i=>i(t))}))}async addEntities(e){this._pendingEntities.push(...e),this.wrappedStage&&this.wrappedStage.enqueue(...e)}add(...e){this.addToBlueprints(...e),this.addToStage(...e)}addToBlueprints(...e){this.wrappedStage||this.options.push(...e)}addToStage(...e){this.wrappedStage&&this.wrappedStage.enqueue(...e)}start(e){!this.wrappedStage||this.wrappedStage.hasSetup||this.wrappedStage.nodeSetup(e)}onUpdate(...e){return this.updateCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.update=t=>{let i={...t,stage:this};this.updateCallbacks.forEach(r=>r(i))}),this}onSetup(...e){return this.setupCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.setup=t=>{let i={...t,stage:this};this.setupCallbacks.forEach(r=>r(i))}),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.destroy=t=>{let i={...t,stage:this};this.destroyCallbacks.forEach(r=>r(i))}),this}onLoading(e){return this.wrappedStage?this.wrappedStage.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e)})}getEntityByName(e,t){return this.wrappedStage?.getEntityByName(e)}addCamera(e,t){let i=e instanceof y?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof y?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof y?this.wrappedStage?.setActiveCamera(e.cameraRef)??!1:this.wrappedStage?.setActiveCamera(e)??!1}getCamera(e){return this.wrappedStage?.getCamera(e)??null}dispatch(e,t){this.eventDelegate.dispatch(e,t),w.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function Un(...s){let e=jt(s);return new Fe([...e])}export{cr as a,$ as b,F as c,I as d,k as e,X as f,J as g,_r as h,h as i,M as j,ie as k,_ as l,L as m,G as n,A as o,oe as p,y as q,La as r,Va as s,Pi as t,Fe as u,Un as v};
|