@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.
Files changed (58) hide show
  1. package/dist/actions.d.ts +5 -5
  2. package/dist/api/game-lib.api.json +2079 -1214
  3. package/dist/api/game-lib.api.md +150 -97
  4. package/dist/api/game-lib.d.ts +321 -95
  5. package/dist/api/game-lib.typedoc.json +141279 -214520
  6. package/dist/bridge.d.ts +111 -0
  7. package/dist/bridge.js +1 -0
  8. package/dist/{chunk-KVSJE4XD.js → chunk-3I537JFL.js} +1 -1
  9. package/dist/chunk-4CHZUWLF.js +1 -0
  10. package/dist/chunk-6B5JP7T5.js +24 -0
  11. package/dist/chunk-AIQ6IVT5.js +1 -0
  12. package/dist/chunk-C5NEGC3S.js +1 -0
  13. package/dist/chunk-D3JO4HW2.js +1 -0
  14. package/dist/chunk-HNCTOJP7.js +1 -0
  15. package/dist/chunk-LKFF6XJC.js +1 -0
  16. package/dist/{chunk-CD7ZOZ35.js → chunk-OAWK2UUY.js} +1 -1
  17. package/dist/chunk-PNLNC3FA.js +1 -0
  18. package/dist/chunk-TV3AZKT4.js +9 -0
  19. package/dist/chunk-VIPINV7V.js +19 -0
  20. package/dist/chunk-W5SXED5T.js +1 -0
  21. package/dist/{chunk-YAOXFYOD.js → chunk-WBQ5TNRZ.js} +1 -1
  22. package/dist/{collision-builder-B_tm8OVy.d.ts → collision-builder-4TVDzXsp.d.ts} +1 -1
  23. package/dist/core.d.ts +11 -11
  24. package/dist/core.js +1 -1
  25. package/dist/debug-state-s0s-qndj.d.ts +49 -0
  26. package/dist/debug.d.ts +32 -7
  27. package/dist/debug.js +1 -1
  28. package/dist/{entity-BGEq1yfC.d.ts → entity-BI7cSlK8.d.ts} +3 -3
  29. package/dist/{entity-B9yZeBm4.d.ts → entity-DDks47JB.d.ts} +1 -1
  30. package/dist/{entity-type-map-CW6RHQkx.d.ts → entity-type-map-COHu4fkW.d.ts} +41 -7
  31. package/dist/entity.d.ts +7 -7
  32. package/dist/entity.js +1 -1
  33. package/dist/events.d.ts +1 -64
  34. package/dist/events.js +1 -1
  35. package/dist/{game-DbqBQiFC.d.ts → game-4fsy55uN.d.ts} +55 -27
  36. package/dist/game-default-4PPYYGAR.js +1 -0
  37. package/dist/graphics.d.ts +5 -5
  38. package/dist/{material-DbSuZBbP.d.ts → material-BKPYeBC6.d.ts} +1 -1
  39. package/dist/public.d.ts +12 -10
  40. package/dist/public.js +1 -1
  41. package/dist/runtime.d.ts +3 -3
  42. package/dist/runtime.js +1 -1
  43. package/dist/{vector-DN6zlPoE.d.ts → vector-DPbwlzgG.d.ts} +10 -2
  44. package/dist/web-components.d.ts +9 -9
  45. package/dist/web-components.js +1 -1
  46. package/dist/{zylem-camera-Du2UPW9O.d.ts → zylem-camera-B73ZNcgs.d.ts} +1 -1
  47. package/package.json +20 -14
  48. package/LICENSE +0 -21
  49. package/dist/chunk-3PRBSSTS.js +0 -24
  50. package/dist/chunk-CFVRRRZZ.js +0 -1
  51. package/dist/chunk-COM6HJ2L.js +0 -1
  52. package/dist/chunk-JQKS42G4.js +0 -1
  53. package/dist/chunk-MZZCDXFB.js +0 -1
  54. package/dist/chunk-TAUWDQZF.js +0 -9
  55. package/dist/chunk-VS2D4B3W.js +0 -1
  56. package/dist/chunk-YHEWKN7N.js +0 -1
  57. package/dist/debug-state-DRoeasG2.d.ts +0 -17
  58. package/dist/game-default-6AZZCNST.js +0 -1
package/dist/public.js CHANGED
@@ -1 +1 @@
1
- import{a as s,b as n,c as l,d as S,e as h,f as y,g as L,h as v,i as Z,j as b,k as g,l as u,m as T,n as j,o as F,p as W,q as k,r as w,s as z,t as B,u as D,v as E,w as G}from"./chunk-QB3NL7VQ.js";import"./chunk-BIGH6D34.js";import"./chunk-DFLI7ICU.js";import{a as Ha}from"./chunk-TAUWDQZF.js";import{a as Ia,b as Ja,c as Ka,d as Qa,e as Ra,f as Ua,g as Xa,h as Ya,i as _a,j as $a,k as op,l as rp,m as ep,n as tp,o as mp,p as ap}from"./chunk-47DG7I7M.js";import{A as Dp,B as Ep,C as Gp,a as pp,b as fp,c as xp,d as ip,e as dp,f as cp,g as sp,h as np,i as lp,j as Sp,k as hp,l as yp,m as Lp,n as vp,o as Zp,p as bp,q as gp,r as up,s as Tp,t as jp,u as Fp,v as Wp,w as kp,x as wp,y as zp,z as Bp}from"./chunk-JNFFTNMH.js";import{a as fo,b as xo,c as io,d as co,e as vo,f as Nr,g as Or,h as Ur,i as Xr,j as Yr,k as _r,l as $r,m as oe,n as re,o as ee}from"./chunk-3PRBSSTS.js";import{a as go}from"./chunk-7GYFZKK7.js";import{a as K,b as Q}from"./chunk-COM6HJ2L.js";import{a as po,c as uo,d as To,e as jo,f as nr,g as lr,h as gr,i as ur,k as Tr,l as jr,m as Fr,n as Wr,o as kr,p as wr,q as zr,r as Br,s as Dr,t as Gr,v as Mr}from"./chunk-CFVRRRZZ.js";import{c as Zr,d as br}from"./chunk-VS2D4B3W.js";import{a as C,c as H,e as I,f as J}from"./chunk-JQKS42G4.js";import{b as ir}from"./chunk-YAOXFYOD.js";import{A as we,B as ze,C as Be,D as De,E as Ee,F as Ge,G as Me,H as Ne,I as Oe,J as Pe,K as Ve,L as qe,M as Ae,N as Ce,O as He,P as Ie,Q as Je,R as Ke,a as te,b as me,c as ae,d as pe,e as fe,f as xe,g as ie,h as de,i as ce,j as se,k as ne,l as le,m as Se,n as he,o as ye,p as Le,q as ve,r as Ze,s as be,t as ge,u as ue,v as Te,w as je,x as Fe,y as We,z as ke}from"./chunk-CD7ZOZ35.js";import{b as Pr,c as Vr,d as qr,e as Ar,f as Cr,g as Hr,h as Ir,i as Jr,j as Kr,k as Qr,m as Rr}from"./chunk-MZZCDXFB.js";import{A as xr,B as dr,C as cr,D as sr,c as Xo,d as Yo,e as _o,f as $o,g as or,h as rr,i as er,j as tr,s as mr,u as ar,y as pr,z as fr}from"./chunk-KVSJE4XD.js";import{a as o,b as r,h as e,i as t,k as m,l as a,m as p,n as f,o as x,p as i,q as d,r as c}from"./chunk-CM5YRNBJ.js";import{a as Zo,b as bo}from"./chunk-YHEWKN7N.js";import"./chunk-QXVH6POE.js";import{b as Uo}from"./chunk-EVYHPR3J.js";import{$ as Kt,$a as Km,A as vt,Aa as vm,B as Zt,Ba as Zm,C as bt,Ca as bm,D as gt,Da as gm,E as ut,Ea as um,F as Tt,Fa as Tm,G as jt,Ga as jm,H as Ft,Ha as Fm,I as Wt,Ia as Wm,J as kt,Ja as km,K as wt,Ka as wm,L as zt,La as zm,M as Bt,Ma as Bm,N as Dt,Na as Dm,O as Et,Oa as Em,P as Gt,Pa as Gm,Q as Mt,Qa as Mm,R as Nt,Ra as Nm,S as Ot,Sa as Om,T as Pt,Ta as Pm,U as Vt,Ua as Vm,V as qt,Va as qm,W as At,Wa as Am,X as Ct,Xa as Cm,Y as Ht,Ya as Hm,Z as It,Za as Im,_ as Jt,_a as Jm,a as Qe,aa as Qt,ab as Qm,b as Re,ba as Rt,bb as Rm,c as Ue,ca as Ut,cb as Um,d as Xe,da as Xt,db as Xm,e as Ye,ea as Yt,eb as Ym,f as _e,fa as _t,fb as _m,g as $e,ga as $t,gb as $m,h as ot,ha as om,hb as oa,i as rt,ia as rm,ib as ra,j as et,ja as em,k as tt,ka as tm,l as mt,la as mm,m as at,ma as am,n as pt,na as pm,o as ft,oa as fm,p as xt,pa as xm,q as it,qa as im,r as dt,ra as dm,s as ct,sa as cm,t as st,ta as sm,u as nt,ua as nm,v as lt,va as lm,w as St,wa as Sm,x as ht,xa as hm,y as yt,ya as ym,z as Lt,za as Lm}from"./chunk-XK63E4SX.js";import{a as ea,b as ta,c as ma}from"./chunk-ZRT3ZQVH.js";import{a as aa,b as pa,c as fa,d as xa}from"./chunk-WQ3WMMZD.js";import{h as Sr,i as hr,j as yr,k as Lr,l as vr}from"./chunk-D2PATZCC.js";import{e as M,f as N,g as O,h as P,i as V,j as q,m as A}from"./chunk-4QLJUQSJ.js";import{a as Fo,b as Wo,c as ko,d as wo,g as zo,h as Bo,i as Do,j as Eo}from"./chunk-7WRQ2UAN.js";import{A as Ma,B as Na,C as Oa,D as Pa,E as Va,a as ia,b as da,c as ca,d as sa,e as na,f as la,g as Sa,h as ha,i as ya,j as La,k as va,l as Za,m as ba,n as ga,o as ua,p as Ta,q as ja,r as Fa,s as Wa,t as ka,u as wa,v as za,w as Ba,x as Da,y as Ea,z as Ga}from"./chunk-IPWUDOV5.js";import{a as Er}from"./chunk-BH53MBAZ.js";import{a as Go,b as Mo,c as No,d as Oo,e as Po,f as Vo,g as qo,h as Ao,i as Co,j as Ho,k as Io,l as Jo,m as Ko,n as Qo,o as Ro}from"./chunk-XRP4JJXL.js";import{a as qa,b as Aa,c as Ca}from"./chunk-7QF6YTEZ.js";import"./chunk-ORIDWL3T.js";import{a as so,b as no,c as lo,d as So,e as ho,f as yo,g as Lo}from"./chunk-PCFF4LLO.js";import{a as R,b as U,c as X,d as Y,e as _,f as $,g as oo,h as ro,i as eo,j as to,k as mo,l as ao}from"./chunk-UG22Z42P.js";export{pr as ACTOR_TYPE,fo as AspectRatio,ie as BOX_TYPE,Qe as BoundaryRicochet3DCoordinator,Re as BoundaryRicochetCoordinator,We as CONE_TYPE,Ee as CYLINDER_TYPE,wr as CameraManager,Tr as CameraPipeline,zr as CameraWrapper,Wp as ColorJsonSchema,Ue as CooldownBehavior,Te as DISK_TYPE,Xe as Destructible3DBehavior,Ye as DestructibleMesh,np as EntityJsonSchema,fp as EntitySchema,K as EntityThumbnailCache,Zo as EventEmitterDelegate,dr as FOG_TYPE,_e as FirstPersonBehavior,$e as FirstPersonEvent,ot as FirstPersonFSM,Wr as FirstPersonPerspective,tt as FirstPersonPresentation,rt as FirstPersonShooterCoordinator,et as FirstPersonState,Fr as Fixed2DPerspective,c as Fn,mt as FractureOptions,Ur as Game,Gp as GameConfigJsonSchema,Ep as GameDeviceConfigJsonSchema,Fp as GameInputConfigSchema,jp as GameInputPlayerConfigSchema,ma as Howl,at as Jumper2DBehavior,pt as Jumper2DEvent,ft as Jumper2DFSM,xt as Jumper2DState,it as Jumper3DBehavior,dt as Jumper3DEvent,ct as Jumper3DFSM,st as Jumper3DState,Sp as KeyboardMappingSchema,Ce as LIGHT_TYPE,Ir as LINE_TYPE,cp as LineEntityDataSchema,Tp as MouseConfigSchema,hp as MouseMappingSchema,nt as MultidirectionalSpaceShooterCoordinator,Ve as PARTICLE_SYSTEM_TYPE,Ne as PILL_TYPE,Se as PLANE_TYPE,ze as PYRAMID_TYPE,lt as ParticleEmitterBehavior,ur as Perspectives,St as Platformer2DBehavior,ht as Platformer2DEvent,yt as Platformer2DFSM,Lt as Platformer2DState,vt as Platformer3DBehavior,Zt as Platformer3DEvent,bt as Platformer3DFSM,gt as Platformer3DState,be as RECT_TYPE,Km as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,Qm as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,Rm as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,Um as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,Xm as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,Ym as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,nr as RenderBundleManager,lr as RenderStrategyManager,Dp as ResolutionInputSchema,ut as Ricochet2DBehavior,Tt as Ricochet2DEvent,jt as Ricochet2DFSM,Ft as Ricochet2DState,Wt as Ricochet3DBehavior,kt as Ricochet3DEvent,wt as Ricochet3DFSM,zt as Ricochet3DState,qm as RuntimeBoundary2DBehavior,Am as RuntimeDynamicCircleBody2DBehavior,Cm as RuntimeGoalZone2DBehavior,Hm as RuntimePlayerInput2DBehavior,Im as RuntimeRicochet2DBehavior,Jm as RuntimeTriggerRegion2DBehavior,se as SPHERE_TYPE,Ar as SPRITE_TYPE,_r as STAGE_STATE_CHANGE,Bt as ScreenVisibilityBehavior,Dt as ScreenVisibilityFSM,Et as ScreenWrapBehavior,Gt as ScreenWrapEvent,Mt as ScreenWrapFSM,Nt as ScreenWrapState,Ot as Shooter2DBehavior,ir as SimulationBody,sp as SpriteEntityDataSchema,zp as StageAssetLoaderConfigSchema,$a as StageBodyKind,op as StageBoundaryDim,Bp as StageConfigJsonSchema,rp as StageEventType,wp as StageGLTFAssetLoaderConfigSchema,lp as StageJsonSchema,Or as StageManager,ep as StageRicochetDim,tp as StageRicochetReflection,xp as StageSchema,mp as StageTopDownPlane,Pr as TEXT_TYPE,ip as TextEntityDataSchema,jr as ThirdPersonPerspective,Pt as ThrusterBehavior,Vt as ThrusterEvent,qt as ThrusterFSM,At as ThrusterState,Ct as TopDownMovementBehavior,Ht as TopDownShooterCoordinator,Wo as VEC2_ONE,Fo as VEC2_ZERO,wo as VEC3_ONE,ko as VEC3_ZERO,kp as Vec3ComponentsSchema,pp as Vector2Schema,dp as Vector3TupleSchema,vp as VirtualTouchButtonConfigSchema,bp as VirtualTouchButtonsConfigSchema,up as VirtualTouchConfigSchema,Zp as VirtualTouchJoystickConfigSchema,gp as VirtualTouchJoysticksConfigSchema,Lp as VirtualTouchPositionSchema,yp as VirtualTouchStyleSchema,It as WorldBoundary2DBehavior,Jt as WorldBoundary2DEvent,Kt as WorldBoundary2DFSM,Qt as WorldBoundary2DState,Rt as WorldBoundary3DBehavior,Ut as WorldBoundary3DEvent,Xt as WorldBoundary3DFSM,Yt as WorldBoundary3DState,Le as ZONE_TYPE,fr as ZylemActor,de as ZylemBox,ke as ZylemCone,Ge as ZylemCylinder,je as ZylemDisk,cr as ZylemFog,Ha as ZylemGameElement,He as ZylemLight,Kr as ZylemLine,qe as ZylemParticleSystem,Oe as ZylemPill,he as ZylemPlane,Be as ZylemPyramid,ge as ZylemRect,ne as ZylemSphere,Cr as ZylemSprite,Vr as ZylemText,ve as ZylemZone,u as abs,Er as applyTransformChanges,g as asin,b as atan,_m as bindRuntimeDynamicCircleBody2DHandle,Xo as boxCollision,te as boxMesh,Ja as buildBoxCollider,Qa as buildCapsuleCollider,Ua as buildConvexHullCollider,Ra as buildCylinderCollider,Ya as buildHeightfieldCollider,Ia as buildRuntimeBody,Ka as buildSphereCollider,Xa as buildTrimeshCollider,_a as bundleRuntimeCollision,la as callFunc,L as clamp,A as clearGlobalSubscriptions,_t as computeWorldBoundary2DHits,$t as computeWorldBoundary3DHits,_o as coneCollision,ae as coneMesh,Z as cos,mr as create,xr as createActor,s as createBackgroundShader,ce as createBox,Br as createCamera,we as createCone,Je as createCooldownIcon,Me as createCylinder,Fe as createDisk,ar as createEntity,Rr as createEntityFactory,om as createFirstPersonInputComponent,rm as createFirstPersonMovementComponent,em as createFirstPersonStateComponent,sr as createFog,re as createFollowTarget,Xr as createGame,N as createGlobal,tm as createJumpConfig2D,mm as createJumpConfig3D,am as createJumpInput2D,pm as createJumpInput3D,fm as createJumpState2D,xm as createJumpState3D,Ie as createLight,Qr as createLine,m as createNodeMaterialFromTSL,Ae as createParticleSystem,kr as createPerspective,im as createPhysicsBodyComponent,Pe as createPill,ye as createPlane,dm as createPlatformer2DInputComponent,cm as createPlatformer2DMovementComponent,sm as createPlatformer2DStateComponent,nm as createPlatformer3DInputComponent,lm as createPlatformer3DMovementComponent,Sm as createPlatformer3DStateComponent,De as createPyramid,ue as createRect,hm as createShooter2DStateComponent,ap as createSimulation,le as createSphere,Hr as createSprite,Mr as createStage,qr as createText,ym as createThrusterInputComponent,Lm as createThrusterMovementComponent,vm as createThrusterStateComponent,Zm as createTopDownMovementComponent,bm as createTopDownMovementInputComponent,gm as createTopDownMovementStateComponent,um as createTransformComponent,ua as createTransformStore,hr as createVariable,Ze as createZone,go as crossfadeTransitionShader,or as cylinderCollision,fe as cylinderMesh,C as debugState,Lo as defaultTouchControls,Tm as defineBehavior,na as delay,Ke as destroy,oe as dispatchStageState,B as dot,$m as emitRuntimeGoal,oa as emitRuntimeRicochet,ra as emitRuntimeTriggerRegionEnter,Yr as entitySpawner,Q as entityThumbnailCache,T as exp,Sa as fadeOpacity,jm as fireCooldown,Fm as fireShooter2DIfRequested,d as float,w as floor,br as focusEntity,z as fract,vo as gameConfig,Wm as getCooldown,km as getCooldownStore,xo as getDisplayAspect,wm as getEntityFacingAngle2D,O as getGlobal,q as getGlobals,Da as getPosition,io as getPresetResolution,Ro as getRotation,yr as getVariable,Ea as getVelocity,aa as globalChange,pa as globalChanges,zm as hasAnyWorldBoundary2DHit,Bm as hasAnyWorldBoundary3DHit,$r as initStageStateDispatcher,t as isGLSLShader,jo as isManagedRenderEntity,e as isTSLShader,po as isWebGPUSupported,So as joystickBaseSvg,ho as joystickThumbSvg,D as length,W as max,ao as mergeInputConfigs,k as min,h as mix,G as mod,Ta as move,da as moveBy,Ba as moveForwardXY,ca as moveTo,ja as moveX,ka as moveXY,wa as moveXZ,Fa as moveY,Wa as moveZ,S as normalize,zo as normalizeVec2,Bo as normalizeVec3,o as objectVertexShader,P as onGlobalChange,V as onGlobalChanges,ya as onPress,La as onRelease,Lr as onVariableChange,vr as onVariableChanges,Uo as packCollisionGroups,Za as parallel,co as parseResolution,Dm as particleEffect,Em as particlePresets,Jr as pickZylemLine,rr as pillCollision,xe as pillMesh,ta as pingPongBeep,er as planeCollision,l as positionWorld,n as positionWorldDirection,j as pow,$o as pyramidCollision,pe as pyramidMesh,Gm as registerCooldown,Zr as registerEntityFocusContext,ba as repeat,ga as repeatForever,Mm as resetCooldown,ia as resetEntityOpacity,za as resetVelocity,Nm as resolveAim2D,lo as resolveButtonAccent,uo as resolveRenderCategory,no as resolveTouchTheme,ea as ricochetSound,sa as rotateBy,No as rotateEuler,Go as rotateInDirection,Po as rotateX,Oo as rotateY,Mo as rotateYEuler,Vo as rotateZ,Ca as screenCenterLookDeltas,Aa as screenCenterLookTargets,va as sequence,ee as setCameraFeed,I as setDebugTool,M as setGlobal,H as setPaused,Ga as setPosition,Ma as setPositionX,Na as setPositionY,Oa as setPositionZ,Ko as setRotation,Qo as setRotationDegrees,Ho as setRotationDegreesX,Ao as setRotationDegreesY,Jo as setRotationDegreesZ,Co as setRotationX,qo as setRotationY,Io as setRotationZ,J as setSelectedEntity,gr as setStageFrameProfilerEnabled,Sr as setVariable,qa as shortestAngleDelta,v as sin,y as smoothstep,Yo as sphereCollision,me as sphereMesh,Dr as stageConfig,Nr as stageState,r as standardShader,F as step,ha as throttle,Om as tickCooldowns,f as time,Do as toThreeVector2,Eo as toThreeVector3,yo as touchButtonSvg,so as touchThemes,a as uniform,Pm as updateBoundaryRicochet,R as useArrowsForAxes,X as useArrowsForDirections,U as useArrowsForSecondaryAxes,Vm as useBehavior,$ as useIJKLForAxes,oo as useIJKLForDirections,to as useMouse,ro as useMouseLook,eo as useScreenCenterLook,mo as useVirtualControls,_ as useWASDForAxes,Y as useWASDForDirections,To as usesManagedRenderPath,p as uv,fa as variableChange,xa as variableChanges,E as vec2,x as vec3,i as vec4,Gr as vessel,Va as wrapAround3D,Pa as wrapAroundXY,tr as zoneCollision,bo as zylemEventBus};
1
+ import{a as s,b as n,c as l,d as S,e as h,f as y,g as L,h as v,i as Z,j as b,k as g,l as u,m as T,n as j,o as F,p as W,q as k,r as w,s as z,t as B,u as D,v as E,w as G}from"./chunk-QB3NL7VQ.js";import"./chunk-BIGH6D34.js";import"./chunk-DFLI7ICU.js";import{a as _a,b as $a,c as op}from"./chunk-HNCTOJP7.js";import{a as rp}from"./chunk-TV3AZKT4.js";import{a as ep,b as tp,c as mp,d as ap,e as pp,f as fp,g as xp,h as ip,i as dp,j as cp,k as sp,l as np,m as lp,n as Sp,o as hp,p as yp}from"./chunk-47DG7I7M.js";import{A as Ip,B as Jp,C as Kp,a as Lp,b as vp,c as Zp,d as bp,e as gp,f as up,g as Tp,h as jp,i as Fp,j as Wp,k as kp,l as wp,m as zp,n as Bp,o as Dp,p as Ep,q as Gp,r as Mp,s as Np,t as Op,u as Pp,v as Vp,w as qp,x as Ap,y as Cp,z as Hp}from"./chunk-JNFFTNMH.js";import{a as ho,b as yo,c as Lo,d as vo,e as Wo,f as Jr,g as Kr,h as me,i as ae,j as pe,k as fe,l as xe,m as ie,n as de,o as ce}from"./chunk-6B5JP7T5.js";import{a as So,c as Go,d as Mo,e as No,f as Tr,g as jr,h as Br,i as Dr,k as Er,l as Gr,m as Mr,n as Nr,o as Or,p as Pr,q as Vr,r as qr,s as Ar,t as Hr,v as Ir}from"./chunk-4CHZUWLF.js";import{a as Eo}from"./chunk-7GYFZKK7.js";import{a as oo,b as ro}from"./chunk-VIPINV7V.js";import"./chunk-C5NEGC3S.js";import{c as Do}from"./chunk-D3JO4HW2.js";import{a as zo,b as Bo}from"./chunk-LKFF6XJC.js";import{a as C,b as H,c as I,e as J,g as K,h as Q,i as R,j as U,k as X,m as Y,n as _,o as $}from"./chunk-W5SXED5T.js";import{b as Zr}from"./chunk-WBQ5TNRZ.js";import{A as Pe,B as Ve,C as qe,D as Ae,E as Ce,F as He,G as Ie,H as Je,I as Ke,J as Qe,K as Re,L as Ue,M as Xe,N as Ye,O as _e,P as $e,Q as ot,R as rt,a as se,b as ne,c as le,d as Se,e as he,f as ye,g as Le,h as ve,i as Ze,j as be,k as ge,l as ue,m as Te,n as je,o as Fe,p as We,q as ke,r as we,s as ze,t as Be,u as De,v as Ee,w as Ge,x as Me,y as Ne,z as Oe}from"./chunk-OAWK2UUY.js";import{b as Qr,c as Rr,d as Ur,e as Xr,f as Yr,g as _r,h as $r,i as oe,j as re,k as ee,m as te}from"./chunk-PNLNC3FA.js";import{A as vr,B as br,C as gr,D as ur,c as fr,d as xr,e as ir,f as dr,g as cr,h as sr,i as nr,j as lr,s as Sr,u as hr,y as yr,z as Lr}from"./chunk-3I537JFL.js";import{a as o,b as r,h as e,i as t,k as m,l as a,m as p,n as f,o as x,p as i,q as d,r as c}from"./chunk-CM5YRNBJ.js";import{a as ko,b as wo}from"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import{b as pr}from"./chunk-EVYHPR3J.js";import{$ as rm,$a as ra,A as kt,Aa as km,B as wt,Ba as wm,C as zt,Ca as zm,D as Bt,Da as Bm,E as Dt,Ea as Dm,F as Et,Fa as Em,G as Gt,Ga as Gm,H as Mt,Ha as Mm,I as Nt,Ia as Nm,J as Ot,Ja as Om,K as Pt,Ka as Pm,L as Vt,La as Vm,M as qt,Ma as qm,N as At,Na as Am,O as Ct,Oa as Cm,P as Ht,Pa as Hm,Q as It,Qa as Im,R as Jt,Ra as Jm,S as Kt,Sa as Km,T as Qt,Ta as Qm,U as Rt,Ua as Rm,V as Ut,Va as Um,W as Xt,Wa as Xm,X as Yt,Xa as Ym,Y as _t,Ya as _m,Z as $t,Za as $m,_ as om,_a as oa,a as et,aa as em,ab as ea,b as tt,ba as tm,bb as ta,c as mt,ca as mm,cb as ma,d as at,da as am,db as aa,e as pt,ea as pm,eb as pa,f as ft,fa as fm,fb as fa,g as xt,ga as xm,gb as xa,h as it,ha as im,hb as ia,i as dt,ia as dm,ib as da,j as ct,ja as cm,k as st,ka as sm,l as nt,la as nm,m as lt,ma as lm,n as St,na as Sm,o as ht,oa as hm,p as yt,pa as ym,q as Lt,qa as Lm,r as vt,ra as vm,s as Zt,sa as Zm,t as bt,ta as bm,u as gt,ua as gm,v as ut,va as um,w as Tt,wa as Tm,x as jt,xa as jm,y as Ft,ya as Fm,z as Wt,za as Wm}from"./chunk-XK63E4SX.js";import{a as ca,b as sa,c as na}from"./chunk-ZRT3ZQVH.js";import{a as la,b as Sa,c as ha,d as ya}from"./chunk-WQ3WMMZD.js";import{h as Fr,i as Wr,j as kr,k as wr,l as zr}from"./chunk-D2PATZCC.js";import{e as M,f as N,g as O,h as P,i as V,j as q,m as A}from"./chunk-4QLJUQSJ.js";import{a as Oo,b as Po,c as Vo,d as qo,g as Ao,h as Co,i as Ho,j as Io}from"./chunk-7WRQ2UAN.js";import{A as Ia,B as Ja,C as Ka,D as Qa,E as Ra,a as La,b as va,c as Za,d as ba,e as ga,f as ua,g as Ta,h as ja,i as Fa,j as Wa,k as ka,l as wa,m as za,n as Ba,o as Da,p as Ea,q as Ga,r as Ma,s as Na,t as Oa,u as Pa,v as Va,w as qa,x as Aa,y as Ca,z as Ha}from"./chunk-IPWUDOV5.js";import{a as Cr}from"./chunk-BH53MBAZ.js";import{a as Jo,b as Ko,c as Qo,d as Ro,e as Uo,f as Xo,g as Yo,h as _o,i as $o,j as or,k as rr,l as er,m as tr,n as mr,o as ar}from"./chunk-XRP4JJXL.js";import{a as Ua,b as Xa,c as Ya}from"./chunk-7QF6YTEZ.js";import"./chunk-ORIDWL3T.js";import{a as Zo,b as bo,c as go,d as uo,e as To,f as jo,g as Fo}from"./chunk-PCFF4LLO.js";import{a as eo,b as to,c as mo,d as ao,e as po,f as fo,g as xo,h as io,i as co,j as so,k as no,l as lo}from"./chunk-UG22Z42P.js";export{yr as ACTOR_TYPE,ho as AspectRatio,Le as BOX_TYPE,op as BRIDGE_READY_EVENT,et as BoundaryRicochet3DCoordinator,tt as BoundaryRicochetCoordinator,Ne as CONE_TYPE,Ce as CYLINDER_TYPE,Pr as CameraManager,Er as CameraPipeline,Vr as CameraWrapper,Vp as ColorJsonSchema,mt as CooldownBehavior,Ee as DISK_TYPE,at as Destructible3DBehavior,pt as DestructibleMesh,jp as EntityJsonSchema,vp as EntitySchema,oo as EntityThumbnailCache,ko as EventEmitterDelegate,br as FOG_TYPE,ft as FirstPersonBehavior,xt as FirstPersonEvent,it as FirstPersonFSM,Nr as FirstPersonPerspective,st as FirstPersonPresentation,dt as FirstPersonShooterCoordinator,ct as FirstPersonState,Mr as Fixed2DPerspective,c as Fn,nt as FractureOptions,me as Game,Do as GameBridge,Kp as GameConfigJsonSchema,Jp as GameDeviceConfigJsonSchema,Pp as GameInputConfigSchema,Op as GameInputPlayerConfigSchema,na as Howl,lt as Jumper2DBehavior,St as Jumper2DEvent,ht as Jumper2DFSM,yt as Jumper2DState,Lt as Jumper3DBehavior,vt as Jumper3DEvent,Zt as Jumper3DFSM,bt as Jumper3DState,Wp as KeyboardMappingSchema,Ye as LIGHT_TYPE,$r as LINE_TYPE,up as LineEntityDataSchema,Np as MouseConfigSchema,kp as MouseMappingSchema,gt as MultidirectionalSpaceShooterCoordinator,Re as PARTICLE_SYSTEM_TYPE,Je as PILL_TYPE,Te as PLANE_TYPE,Ve as PYRAMID_TYPE,ut as ParticleEmitterBehavior,Dr as Perspectives,Tt as Platformer2DBehavior,jt as Platformer2DEvent,Ft as Platformer2DFSM,Wt as Platformer2DState,kt as Platformer3DBehavior,wt as Platformer3DEvent,zt as Platformer3DFSM,Bt as Platformer3DState,ze as RECT_TYPE,ra as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,ea as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,ta as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,ma as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,aa as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,pa as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,Tr as RenderBundleManager,jr as RenderStrategyManager,Ip as ResolutionInputSchema,Dt as Ricochet2DBehavior,Et as Ricochet2DEvent,Gt as Ricochet2DFSM,Mt as Ricochet2DState,Nt as Ricochet3DBehavior,Ot as Ricochet3DEvent,Pt as Ricochet3DFSM,Vt as Ricochet3DState,Um as RuntimeBoundary2DBehavior,Xm as RuntimeDynamicCircleBody2DBehavior,Ym as RuntimeGoalZone2DBehavior,_m as RuntimePlayerInput2DBehavior,$m as RuntimeRicochet2DBehavior,oa as RuntimeTriggerRegion2DBehavior,be as SPHERE_TYPE,Xr as SPRITE_TYPE,fe as STAGE_STATE_CHANGE,qt as ScreenVisibilityBehavior,At as ScreenVisibilityFSM,Ct as ScreenWrapBehavior,Ht as ScreenWrapEvent,It as ScreenWrapFSM,Jt as ScreenWrapState,Kt as Shooter2DBehavior,Zr as SimulationBody,Tp as SpriteEntityDataSchema,Cp as StageAssetLoaderConfigSchema,cp as StageBodyKind,sp as StageBoundaryDim,Hp as StageConfigJsonSchema,np as StageEventType,Ap as StageGLTFAssetLoaderConfigSchema,Fp as StageJsonSchema,Kr as StageManager,lp as StageRicochetDim,Sp as StageRicochetReflection,Zp as StageSchema,hp as StageTopDownPlane,Qr as TEXT_TYPE,bp as TextEntityDataSchema,Gr as ThirdPersonPerspective,Qt as ThrusterBehavior,Rt as ThrusterEvent,Ut as ThrusterFSM,Xt as ThrusterState,Yt as TopDownMovementBehavior,_t as TopDownShooterCoordinator,Po as VEC2_ONE,Oo as VEC2_ZERO,qo as VEC3_ONE,Vo as VEC3_ZERO,qp as Vec3ComponentsSchema,Lp as Vector2Schema,gp as Vector3TupleSchema,Bp as VirtualTouchButtonConfigSchema,Ep as VirtualTouchButtonsConfigSchema,Mp as VirtualTouchConfigSchema,Dp as VirtualTouchJoystickConfigSchema,Gp as VirtualTouchJoysticksConfigSchema,zp as VirtualTouchPositionSchema,wp as VirtualTouchStyleSchema,$t as WorldBoundary2DBehavior,om as WorldBoundary2DEvent,rm as WorldBoundary2DFSM,em as WorldBoundary2DState,tm as WorldBoundary3DBehavior,mm as WorldBoundary3DEvent,am as WorldBoundary3DFSM,pm as WorldBoundary3DState,We as ZONE_TYPE,Lr as ZylemActor,ve as ZylemBox,Oe as ZylemCone,He as ZylemCylinder,Ge as ZylemDisk,gr as ZylemFog,rp as ZylemGameElement,_e as ZylemLight,re as ZylemLine,Ue as ZylemParticleSystem,Ke as ZylemPill,je as ZylemPlane,qe as ZylemPyramid,Be as ZylemRect,ge as ZylemSphere,Yr as ZylemSprite,Rr as ZylemText,ke as ZylemZone,u as abs,$a as announceBridgeReady,Cr as applyTransformChanges,g as asin,b as atan,fa as bindRuntimeDynamicCircleBody2DHandle,fr as boxCollision,se as boxMesh,tp as buildBoxCollider,ap as buildCapsuleCollider,fp as buildConvexHullCollider,pp as buildCylinderCollider,ip as buildHeightfieldCollider,ep as buildRuntimeBody,mp as buildSphereCollider,xp as buildTrimeshCollider,dp as bundleRuntimeCollision,ua as callFunc,L as clamp,A as clearGlobalSubscriptions,fm as computeWorldBoundary2DHits,xm as computeWorldBoundary3DHits,ir as coneCollision,le as coneMesh,Z as cos,Sr as create,vr as createActor,s as createBackgroundShader,Ze as createBox,qr as createCamera,Pe as createCone,ot as createCooldownIcon,Ie as createCylinder,Me as createDisk,hr as createEntity,te as createEntityFactory,im as createFirstPersonInputComponent,dm as createFirstPersonMovementComponent,cm as createFirstPersonStateComponent,ur as createFog,de as createFollowTarget,ae as createGame,N as createGlobal,sm as createJumpConfig2D,nm as createJumpConfig3D,lm as createJumpInput2D,Sm as createJumpInput3D,hm as createJumpState2D,ym as createJumpState3D,$e as createLight,ee as createLine,m as createNodeMaterialFromTSL,Xe as createParticleSystem,Or as createPerspective,Lm as createPhysicsBodyComponent,Qe as createPill,Fe as createPlane,vm as createPlatformer2DInputComponent,Zm as createPlatformer2DMovementComponent,bm as createPlatformer2DStateComponent,gm as createPlatformer3DInputComponent,um as createPlatformer3DMovementComponent,Tm as createPlatformer3DStateComponent,Ae as createPyramid,De as createRect,jm as createShooter2DStateComponent,yp as createSimulation,ue as createSphere,_r as createSprite,Ir as createStage,Ur as createText,Fm as createThrusterInputComponent,Wm as createThrusterMovementComponent,km as createThrusterStateComponent,wm as createTopDownMovementComponent,zm as createTopDownMovementInputComponent,Bm as createTopDownMovementStateComponent,Dm as createTransformComponent,Da as createTransformStore,Wr as createVariable,we as createZone,Eo as crossfadeTransitionShader,cr as cylinderCollision,he as cylinderMesh,C as debugState,Fo as defaultTouchControls,Em as defineBehavior,ga as delay,rt as destroy,ie as dispatchStageState,B as dot,xa as emitRuntimeGoal,ia as emitRuntimeRicochet,da as emitRuntimeTriggerRegionEnter,pe as entitySpawner,ro as entityThumbnailCache,T as exp,Ta as fadeOpacity,Gm as fireCooldown,Mm as fireShooter2DIfRequested,d as float,w as floor,Bo as focusEntity,z as fract,Wo as gameConfig,Nm as getCooldown,Om as getCooldownStore,yo as getDisplayAspect,Pm as getEntityFacingAngle2D,O as getGlobal,q as getGlobals,_ as getHoveredEntity,U as getHoveredEntityId,Aa as getPosition,Lo as getPresetResolution,ar as getRotation,Y as getSelectedEntity,Q as getSelectedEntityId,kr as getVariable,Ca as getVelocity,_a as getZylemBridge,la as globalChange,Sa as globalChanges,Vm as hasAnyWorldBoundary2DHit,qm as hasAnyWorldBoundary3DHit,xe as initStageStateDispatcher,t as isGLSLShader,No as isManagedRenderEntity,e as isTSLShader,So as isWebGPUSupported,uo as joystickBaseSvg,To as joystickThumbSvg,D as length,W as max,lo as mergeInputConfigs,k as min,h as mix,G as mod,Ea as move,va as moveBy,qa as moveForwardXY,Za as moveTo,Ga as moveX,Oa as moveXY,Pa as moveXZ,Ma as moveY,Na as moveZ,S as normalize,Ao as normalizeVec2,Co as normalizeVec3,o as objectVertexShader,P as onGlobalChange,V as onGlobalChanges,Fa as onPress,Wa as onRelease,wr as onVariableChange,zr as onVariableChanges,pr as packCollisionGroups,wa as parallel,vo as parseResolution,Am as particleEffect,Cm as particlePresets,oe as pickZylemLine,sr as pillCollision,ye as pillMesh,sa as pingPongBeep,nr as planeCollision,l as positionWorld,n as positionWorldDirection,j as pow,dr as pyramidCollision,Se as pyramidMesh,Hm as registerCooldown,H as registerDebugEntityResolver,zo as registerEntityFocusContext,za as repeat,Ba as repeatForever,Im as resetCooldown,La as resetEntityOpacity,Va as resetVelocity,Jm as resolveAim2D,go as resolveButtonAccent,I as resolveDebugEntity,Go as resolveRenderCategory,bo as resolveTouchTheme,ca as ricochetSound,ba as rotateBy,Qo as rotateEuler,Jo as rotateInDirection,Uo as rotateX,Ro as rotateY,Ko as rotateYEuler,Xo as rotateZ,Ya as screenCenterLookDeltas,Xa as screenCenterLookTargets,ka as sequence,ce as setCameraFeed,K as setDebugTool,M as setGlobal,X as setHoveredEntityId,J as setPaused,Ha as setPosition,Ia as setPositionX,Ja as setPositionY,Ka as setPositionZ,tr as setRotation,mr as setRotationDegrees,or as setRotationDegreesX,_o as setRotationDegreesY,er as setRotationDegreesZ,$o as setRotationX,Yo as setRotationY,rr as setRotationZ,$ as setSelectedEntity,R as setSelectedEntityId,Br as setStageFrameProfilerEnabled,Fr as setVariable,Ua as shortestAngleDelta,v as sin,y as smoothstep,xr as sphereCollision,ne as sphereMesh,Ar as stageConfig,Jr as stageState,r as standardShader,F as step,ja as throttle,Km as tickCooldowns,f as time,Ho as toThreeVector2,Io as toThreeVector3,jo as touchButtonSvg,Zo as touchThemes,a as uniform,Qm as updateBoundaryRicochet,eo as useArrowsForAxes,mo as useArrowsForDirections,to as useArrowsForSecondaryAxes,Rm as useBehavior,fo as useIJKLForAxes,xo as useIJKLForDirections,so as useMouse,io as useMouseLook,co as useScreenCenterLook,no as useVirtualControls,po as useWASDForAxes,ao as useWASDForDirections,Mo as usesManagedRenderPath,p as uv,ha as variableChange,ya as variableChanges,E as vec2,x as vec3,i as vec4,Hr as vessel,Ra as wrapAround3D,Qa as wrapAroundXY,lr as zoneCollision,wo as zylemEventBus};
package/dist/runtime.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { StageBodyKindValue, StageBodyConfig, StageColliderConfig } from '@zylem/behaviors/core';
2
2
  export { BehaviorRuntime, EntityDefinition, EntityHandle, Simulation, SimulationBodyDefinition, SimulationColliderDefinition, SimulationEvent, SimulationFrame, SimulationOptions, StageBodyConfig, StageBodyInfo, StageBodyKind, StageBodyKindValue, StageBoundaryDim, StageColliderConfig, StageColliderShape, StageDebugRender, StageEvent, StageEventType, StagePose, StageRaycastHit, StageRenderSlot, StageRicochetDim, StageRicochetReflection, StageTopDownPlane, createSimulation } from '@zylem/behaviors/core';
3
- import { e as Vec3Input } from './vector-DN6zlPoE.js';
4
- export { l as SimulationBody, S as SimulationStepClock } from './vector-DN6zlPoE.js';
5
- export { p as packCollisionGroups } from './collision-builder-B_tm8OVy.js';
3
+ import { e as Vec3Input } from './vector-DPbwlzgG.js';
4
+ export { l as SimulationBody, S as SimulationStepClock } from './vector-DPbwlzgG.js';
5
+ export { p as packCollisionGroups } from './collision-builder-4TVDzXsp.js';
6
6
  import 'three';
7
7
 
8
8
  /**
package/dist/runtime.js CHANGED
@@ -1 +1 @@
1
- import{a as c,b as d,c as e,d as f,e as g,f as h,g as i,h as j,i as k,j as l,k as m,l as n,m as o,n as p,o as q,p as r}from"./chunk-47DG7I7M.js";import{b}from"./chunk-YAOXFYOD.js";import{b as a}from"./chunk-EVYHPR3J.js";import"./chunk-7WRQ2UAN.js";export{b as SimulationBody,l as StageBodyKind,m as StageBoundaryDim,n as StageEventType,o as StageRicochetDim,p as StageRicochetReflection,q as StageTopDownPlane,d as buildBoxCollider,f as buildCapsuleCollider,h as buildConvexHullCollider,g as buildCylinderCollider,j as buildHeightfieldCollider,c as buildRuntimeBody,e as buildSphereCollider,i as buildTrimeshCollider,k as bundleRuntimeCollision,r as createSimulation,a as packCollisionGroups};
1
+ import{a as c,b as d,c as e,d as f,e as g,f as h,g as i,h as j,i as k,j as l,k as m,l as n,m as o,n as p,o as q,p as r}from"./chunk-47DG7I7M.js";import{b}from"./chunk-WBQ5TNRZ.js";import{b as a}from"./chunk-EVYHPR3J.js";import"./chunk-7WRQ2UAN.js";export{b as SimulationBody,l as StageBodyKind,m as StageBoundaryDim,n as StageEventType,o as StageRicochetDim,p as StageRicochetReflection,q as StageTopDownPlane,d as buildBoxCollider,f as buildCapsuleCollider,h as buildConvexHullCollider,g as buildCylinderCollider,j as buildHeightfieldCollider,c as buildRuntimeBody,e as buildSphereCollider,i as buildTrimeshCollider,k as bundleRuntimeCollision,r as createSimulation,a as packCollisionGroups};
@@ -46,8 +46,16 @@ declare class SimulationBody implements PhysicsRenderPoseProvider {
46
46
  */
47
47
  private interpolationValidAfterStep;
48
48
  constructor(simulation: Simulation, handle: EntityHandle, clock: SimulationStepClock);
49
- /** Suppress interpolation until the render buffers catch up. */
50
- private markPoseDiscontinuity;
49
+ /**
50
+ * Suppress interpolation until the render buffers catch up.
51
+ *
52
+ * Called automatically by the pose setters below. Wasm-side behaviors that
53
+ * teleport a body during a step (e.g. `screen_wrap`) bypass those setters,
54
+ * so their host systems must call this after the step and before render
55
+ * poses are synced — otherwise the render buffers straddle the teleport and
56
+ * the body is drawn sweeping between the two poses.
57
+ */
58
+ markPoseDiscontinuity(): void;
51
59
  private isInterpolationStale;
52
60
  translation(): PhysicsVector3;
53
61
  rotation(): PhysicsQuaternion;
@@ -1,22 +1,22 @@
1
- import { G as Game, D as DeviceProfile } from './game-DbqBQiFC.js';
2
- import { D as DebugTools } from './debug-state-DRoeasG2.js';
1
+ import { G as Game, D as DeviceProfile } from './game-4fsy55uN.js';
2
+ import { D as DebugTools } from './debug-state-s0s-qndj.js';
3
3
  import './base-node-life-cycle-BK9xebT9.js';
4
4
  import 'three';
5
5
  import './stage-transition-CmGpV4tc.js';
6
6
  import './game-interfaces-vF5sRi1n.js';
7
- import './entity-BGEq1yfC.js';
7
+ import './entity-BI7cSlK8.js';
8
8
  import '@zylem/behaviors/core';
9
- import './vector-DN6zlPoE.js';
10
- import './material-DbSuZBbP.js';
9
+ import './vector-DPbwlzgG.js';
10
+ import './material-BKPYeBC6.js';
11
11
  import 'three/webgpu';
12
- import './collision-builder-B_tm8OVy.js';
12
+ import './collision-builder-4TVDzXsp.js';
13
13
  import './events.js';
14
14
  import 'mitt';
15
- import './entity-type-map-CW6RHQkx.js';
16
- import './entity-B9yZeBm4.js';
15
+ import './entity-type-map-COHu4fkW.js';
16
+ import './entity-DDks47JB.js';
17
17
  import '@zylem/behaviors/particle-emitter';
18
18
  import 'three/addons/lines/webgpu/Line2.js';
19
- import './zylem-camera-Du2UPW9O.js';
19
+ import './zylem-camera-B73ZNcgs.js';
20
20
  import './default-controls-CAKJ5zlo.js';
21
21
 
22
22
  /**
@@ -1 +1 @@
1
- import{a}from"./chunk-TAUWDQZF.js";import"./chunk-JQKS42G4.js";export{a as ZylemGameElement};
1
+ import{a}from"./chunk-TV3AZKT4.js";import"./chunk-W5SXED5T.js";export{a as ZylemGameElement};
@@ -1,5 +1,5 @@
1
1
  import { Object3D, Vector2, Scene, Camera, Vector3, Quaternion, RenderTarget, Texture } from 'three';
2
- import { S as StageEntity } from './entity-B9yZeBm4.js';
2
+ import { S as StageEntity } from './entity-DDks47JB.js';
3
3
  import { WebGPURenderer, RenderPipeline } from 'three/webgpu';
4
4
  import { R as ResolvedStageTransition } from './stage-transition-CmGpV4tc.js';
5
5
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zylem/game-lib",
3
- "version": "0.8.2",
3
+ "version": "0.8.4",
4
4
  "type": "module",
5
5
  "description": "A powerful and easy-to-use framework for creating simple 3D digital interactive applications using TypeScript.",
6
6
  "license": "MIT",
@@ -61,6 +61,10 @@
61
61
  "types": "./dist/debug.d.ts",
62
62
  "import": "./dist/debug.js"
63
63
  },
64
+ "./bridge": {
65
+ "types": "./dist/bridge.d.ts",
66
+ "import": "./dist/bridge.js"
67
+ },
64
68
  "./web-components": {
65
69
  "types": "./dist/web-components.d.ts",
66
70
  "import": "./dist/web-components.js"
@@ -97,11 +101,24 @@
97
101
  "files": [
98
102
  "dist"
99
103
  ],
104
+ "scripts": {
105
+ "build": "tsup && pnpm api:extract && pnpm api:typedoc && pnpm schema:emit",
106
+ "dev": "tsup --watch",
107
+ "api:extract": "mkdir -p dist/api temp && api-extractor run --local --verbose",
108
+ "api:typedoc": "mkdir -p dist/api && typedoc --options typedoc.json",
109
+ "schema:emit": "node --experimental-strip-types ./scripts/emit-json-schemas.ts",
110
+ "prepublishOnly": "NODE_ENV=production pnpm build",
111
+ "lint": "biome check .",
112
+ "typecheck": "tsgo --noEmit",
113
+ "test": "vitest --reporter=verbose",
114
+ "coverage": "vitest run --coverage"
115
+ },
100
116
  "dependencies": {
101
117
  "@dgreenheck/three-pinata": "^2.0.1",
102
118
  "@sinclair/typebox": "^0.34.41",
103
119
  "@types/howler": "^2.2.12",
104
- "@zylem/behaviors": "link:../../../behaviors",
120
+ "@zylem/behaviors": "^0.5.8",
121
+ "@zylem/bridge": "workspace:*",
105
122
  "comlink": "^4.4.2",
106
123
  "howler": "^2.2.4",
107
124
  "idb-keyval": "^6.2.2",
@@ -132,16 +149,5 @@
132
149
  "typescript": "6.0.3",
133
150
  "vite-plugin-solid": "^2.11.8",
134
151
  "vitest": "^4.0.9"
135
- },
136
- "scripts": {
137
- "build": "tsup && pnpm api:extract && pnpm api:typedoc && pnpm schema:emit",
138
- "dev": "tsup --watch",
139
- "api:extract": "mkdir -p dist/api temp && api-extractor run --local --verbose",
140
- "api:typedoc": "mkdir -p dist/api && typedoc --options typedoc.json",
141
- "schema:emit": "node --experimental-strip-types ./scripts/emit-json-schemas.ts",
142
- "lint": "biome check .",
143
- "typecheck": "tsgo --noEmit",
144
- "test": "vitest --reporter=verbose",
145
- "coverage": "vitest run --coverage"
146
152
  }
147
- }
153
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 Timothy Cool
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,24 +0,0 @@
1
- import{b as ye}from"./chunk-7GYFZKK7.js";import{b}from"./chunk-COM6HJ2L.js";import{b as he,d as P,j as ve,u as L,v as G}from"./chunk-CFVRRRZZ.js";import{a as g,b as me,c as K}from"./chunk-JQKS42G4.js";import{l as Se}from"./chunk-MZZCDXFB.js";import{a as $,r as j}from"./chunk-KVSJE4XD.js";import{j as be}from"./chunk-CM5YRNBJ.js";import{a as fe,b as y}from"./chunk-YHEWKN7N.js";import{c as S}from"./chunk-D2PATZCC.js";import{c as re,d as C,e as le,h as ue,i as pe,j as de,k as J,l as x,m as ce}from"./chunk-4QLJUQSJ.js";import{j as W}from"./chunk-7WRQ2UAN.js";import{g as ge}from"./chunk-PCFF4LLO.js";import{l as v}from"./chunk-UG22Z42P.js";function De(){return{pressed:!1,released:!1,held:0}}function ke(){return{value:0,held:0}}function D(a){let e=new Map;if(!a)return e;for(let[t,n]of Object.entries(a)){if(!n||n.length===0)continue;let i=[];for(let o of n){let[r,s]=(o||"").split(".");if(!r||!s)continue;let l=r.toLowerCase(),u=s.toLowerCase();if(l==="buttons"){let p={a:"A",b:"B",x:"X",y:"Y",start:"Start",select:"Select",l:"L",r:"R"}[u];p&&i.push({category:"buttons",property:p})}else if(l==="directions"){let p={up:"Up",down:"Down",left:"Left",right:"Right"}[u];p&&i.push({category:"directions",property:p})}else if(l==="shoulders"){let p={ltrigger:"LTrigger",rtrigger:"RTrigger"}[u];p&&i.push({category:"shoulders",property:p})}else if(l==="axes"){let p={left:{property:"Horizontal",direction:-1},right:{property:"Horizontal",direction:1},up:{property:"Vertical",direction:-1},down:{property:"Vertical",direction:1},secondaryleft:{property:"SecondaryHorizontal",direction:-1},secondaryright:{property:"SecondaryHorizontal",direction:1},secondaryup:{property:"SecondaryVertical",direction:-1},secondarydown:{property:"SecondaryVertical",direction:1}}[u];p&&i.push({category:"axes",property:p.property,axisDirection:p.direction})}}i.length>0&&e.set(t,i)}return e}function d(a,e){return!a&&!e?De():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function f(a,e){return!a&&!e?ke():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var w=class{keyStates=new Map;keyButtonStates=new Map;analogStates=new Map;compiledMapping;includeDefaultBase=!0;onKeyDown=({key:e})=>this.keyStates.set(e,!0);onKeyUp=({key:e})=>this.keyStates.set(e,!1);constructor(e,t){this.includeDefaultBase=t?.includeDefaultBase??!0,this.compiledMapping=D(e??null),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}dispose(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),this.keyStates.clear(),this.keyButtonStates.clear(),this.analogStates.clear()}isKeyPressed(e){return this.keyStates.get(e)||!1}handleButtonState(e,t){let n=this.keyButtonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.keyButtonStates.set(e,n));let i=this.isKeyPressed(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleAnalogState(e,t,n){let i=`${e}:${t}`,o=this.analogStates.get(i);return o||(o={value:0,held:0},this.analogStates.set(i,o)),o.value=this.getAxisValue(e,t),o.held=o.value!==0?o.held+n:0,o}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map;for(let[i,o]of this.compiledMapping.entries()){let r=null;for(let s of o)if(s.category==="axes")n.has(s.property)||n.set(s.property,0),this.isKeyPressed(i)&&n.set(s.property,n.get(s.property)+s.axisDirection);else{r||(r=this.handleButtonState(i,t));let l=e[s.category]??={};l[s.property]=d(l[s.property],r)}}if(n.size>0){e.axes||(e.axes={});for(let[i,o]of n.entries()){let r=`custom:${i}`,s=this.analogStates.get(r);s||(s={value:0,held:0},this.analogStates.set(r,s)),s.value=o,s.held=o!==0?s.held+t:0,e.axes[i]=f(e.axes[i],s)}}return e}getInput(e){let t={};return this.includeDefaultBase&&(t.buttons={A:this.handleButtonState("z",e),B:this.handleButtonState("x",e),X:this.handleButtonState("a",e),Y:this.handleButtonState("s",e),Start:this.handleButtonState(" ",e),Select:this.handleButtonState("Enter",e),L:this.handleButtonState("q",e),R:this.handleButtonState("e",e)},t.directions={Up:this.handleButtonState("ArrowUp",e),Down:this.handleButtonState("ArrowDown",e),Left:this.handleButtonState("ArrowLeft",e),Right:this.handleButtonState("ArrowRight",e)},t.shoulders={LTrigger:this.handleButtonState("Q",e),RTrigger:this.handleButtonState("E",e)}),this.applyCustomMapping(t,e)}getName(){return"keyboard"}getAxisValue(e,t){return(this.isKeyPressed(t)?1:0)-(this.isKeyPressed(e)?1:0)}isConnected(){return!0}};var k=class{gamepadIndex;connected=!1;buttonStates={};analogStates={};onConnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!0)};onDisconnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!1)};constructor(e){this.gamepadIndex=e,window.addEventListener("gamepadconnected",this.onConnected),window.addEventListener("gamepaddisconnected",this.onDisconnected)}dispose(){window.removeEventListener("gamepadconnected",this.onConnected),window.removeEventListener("gamepaddisconnected",this.onDisconnected),this.buttonStates={},this.analogStates={}}handleButtonState(e,t,n){let i=this.buttonStates[e];i||(i={pressed:!1,released:!1,held:0},this.buttonStates[e]=i);let o=t.buttons[e].pressed;return i.pressed=o&&i.held===0,i.released=!o&&i.held>0,i.held=o?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates[e];return i||(i={value:0,held:0},this.analogStates[e]=i),i.value=t.axes[e],i.held=i.value!==0?i.held+n:0,i}getInput(e){let t=navigator.getGamepads()[this.gamepadIndex];return t?{buttons:{A:this.handleButtonState(0,t,e),B:this.handleButtonState(1,t,e),X:this.handleButtonState(2,t,e),Y:this.handleButtonState(3,t,e),Start:this.handleButtonState(9,t,e),Select:this.handleButtonState(8,t,e),L:this.handleButtonState(4,t,e),R:this.handleButtonState(5,t,e)},directions:{Up:this.handleButtonState(12,t,e),Down:this.handleButtonState(13,t,e),Left:this.handleButtonState(14,t,e),Right:this.handleButtonState(15,t,e)},axes:{Horizontal:this.handleAnalogState(0,t,e),Vertical:this.handleAnalogState(1,t,e),SecondaryHorizontal:this.handleAnalogState(2,t,e),SecondaryVertical:this.handleAnalogState(3,t,e)},shoulders:{LTrigger:this.handleButtonState(6,t,e),RTrigger:this.handleButtonState(7,t,e)}}:{}}getName(){return`gamepad-${this.gamepadIndex+1}`}isConnected(){return this.connected}};import{subscribe as ze}from"valtio/vanilla";var Ae=.002;function z(a,e,t){return Math.max(e,Math.min(t,a))}function Ve(a){if(a instanceof HTMLCanvasElement)return a;let e=a.querySelector("canvas");if(e instanceof HTMLCanvasElement)return e;for(let t of a.querySelectorAll("*")){let n=t.shadowRoot;if(!n)continue;let i=n.querySelector("canvas");if(i instanceof HTMLCanvasElement)return i}return null}var T=class{buttonStates=new Map;analogStates=new Map;compiledMapping;movementX=0;movementY=0;pointerX=.5;pointerY=.5;pointerCenterX=0;pointerCenterY=0;mouseButtonDown=new Set;sensitivity;usePointerLock;lookMode;isLocked=!1;targetElement;debugUnsubscribe=null;updatePointerPosition(e,t){this.pointerX=e/window.innerWidth,this.pointerY=t/window.innerHeight;let n=Ve(this.targetElement);if(n){let i=n.getBoundingClientRect();if(i.width>0&&i.height>0){let o=i.left+i.width/2,r=i.top+i.height/2;this.pointerCenterX=z((e-o)/(i.width/2),-1,1),this.pointerCenterY=z((t-r)/(i.height/2),-1,1);return}}this.pointerCenterX=z((this.pointerX-.5)*2,-1,1),this.pointerCenterY=z((this.pointerY-.5)*2,-1,1)}onMouseMove=e=>{this.updatePointerPosition(e.clientX,e.clientY),!(g.enabled||this.lookMode==="screenCenter")&&(this.movementX+=e.movementX,this.movementY+=e.movementY)};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&!g.enabled&&this.targetElement.requestPointerLock())};onMouseUp=e=>{this.mouseButtonDown.delete(e.button)};onContextMenu=e=>{e.preventDefault()};onPointerLockChange=()=>{this.isLocked=document.pointerLockElement===this.targetElement};constructor(e,t){this.sensitivity=e?.sensitivity??Ae,this.lookMode=e?.lookMode??"delta",this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=D(e?.mapping??null),this.targetElement=t??document.body,window.addEventListener("mousemove",this.onMouseMove),this.targetElement.addEventListener("mousedown",this.onMouseDown),this.targetElement.addEventListener("mouseup",this.onMouseUp),this.targetElement.addEventListener("contextmenu",this.onContextMenu),this.usePointerLock&&(document.addEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe=ze(g,()=>{g.enabled&&document.pointerLockElement===this.targetElement&&document.exitPointerLock()}))}dispose(){window.removeEventListener("mousemove",this.onMouseMove),this.targetElement.removeEventListener("mousedown",this.onMouseDown),this.targetElement.removeEventListener("mouseup",this.onMouseUp),this.targetElement.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe?.(),this.debugUnsubscribe=null,this.isLocked&&document.exitPointerLock(),this.buttonStates.clear(),this.analogStates.clear(),this.mouseButtonDown.clear(),this.movementX=0,this.movementY=0}handleMouseButton(e,t){let n=this.buttonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.buttonStates.set(e,n));let i=this.mouseButtonDown.has(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleMovementAxis(e,t){let n=this.analogStates.get(e);n||(n={value:0,held:0},this.analogStates.set(e,n));let i=e==="x"?this.movementX:this.movementY;return n.value=Math.max(-1,Math.min(1,i*this.sensitivity)),n.held=n.value!==0?n.held+t:0,n}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map,i={leftbutton:()=>this.handleMouseButton(0,t),rightbutton:()=>this.handleMouseButton(2,t),middlebutton:()=>this.handleMouseButton(1,t)};for(let[o,r]of this.compiledMapping.entries()){let s=o.toLowerCase();for(let l of r)if(l.category==="axes")n.has(l.property)||n.set(l.property,0),s==="movex"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementX*this.sensitivity))*l.axisDirection):s==="movey"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementY*this.sensitivity))*l.axisDirection):s in i&&this.mouseButtonDown.has(this.buttonIndexForAction(s))&&n.set(l.property,n.get(l.property)+l.axisDirection);else{let u=i[s];if(u){let m=u();if(m){let p=e[l.category]??={};p[l.property]=d(p[l.property],m)}}}}if(n.size>0){e.axes||(e.axes={});for(let[o,r]of n.entries()){let s=`custom:${o}`,l=this.analogStates.get(s);l||(l={value:0,held:0},this.analogStates.set(s,l)),l.value=Math.max(-1,Math.min(1,r)),l.held=r!==0?l.held+t:0,e.axes[o]=f(e.axes[o],l)}}return e}buttonIndexForAction(e){switch(e){case"leftbutton":return 0;case"middlebutton":return 1;case"rightbutton":return 2;default:return-1}}getInput(e){g.enabled&&(this.movementX=0,this.movementY=0);let t={value:0,held:0},n=this.lookMode==="delta",i={axes:{Horizontal:t,Vertical:t,SecondaryHorizontal:n?this.handleMovementAxis("x",e):t,SecondaryVertical:n?this.handleMovementAxis("y",e):t},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY,centerX:this.pointerCenterX,centerY:this.pointerCenterY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(i,e)}getName(){return"mouse"}isConnected(){return!0}};function R(a={}){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent,t=/android/i.test(e)||/iPad|iPhone|iPod/.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1,o=a.viewportSize?.width??window.innerWidth??0,r=a.viewportSize?.height??window.innerHeight??0,s=Math.max(o,r),l=s===0||s<=1024;return a.allowViewportOnly&&a.viewportSize?l:t||(n||i)&&l}var He=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],Oe=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),_e={A:{size:72,label:"A",position:{right:98,bottom:44}},B:{size:72,label:"B",position:{right:24,bottom:108}},X:{size:72,label:"X",position:{right:172,bottom:108}},Y:{size:72,label:"Y",position:{right:98,bottom:172}},Start:{size:64,label:"Start",position:{left:"50%",top:24,transform:"translateX(28px)"}},Select:{size:64,label:"Select",position:{left:"50%",top:24,transform:"translateX(-108px)"}},L:{size:62,label:"L",position:{left:28,bottom:184}},R:{size:62,label:"R",position:{right:236,bottom:184}},LTrigger:{size:76,label:"LT",position:{left:24,top:24}},RTrigger:{size:76,label:"RT",position:{right:24,top:24}},Up:{enabled:!1,size:64,label:"Up"},Down:{enabled:!1,size:64,label:"Down"},Left:{enabled:!1,size:64,label:"Left"},Right:{enabled:!1,size:64,label:"Right"}},Ne={left:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"Horizontal",verticalAxis:"Vertical",emitDirections:!0,position:{left:24,bottom:24}},right:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"SecondaryHorizontal",verticalAxis:"SecondaryVertical",emitDirections:!1,position:{right:24,bottom:236}}},M=class{config;targetElement;buttonStates=new Map;analogStates=new Map;buttons=new Map;joysticks=new Map;rootElement=null;enabled=!1;onPointerMove=e=>{for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.updateJoystickFromPoint(t,e.clientX,e.clientY))};onPointerUp=e=>{for(let t of this.buttons.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseButton(t));for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseJoystick(t))};onWindowBlur=()=>{for(let e of this.buttons.values())this.releaseButton(e);for(let e of this.joysticks.values())this.releaseJoystick(e)};constructor(e,t){this.config=e??{},this.targetElement=t??document.body,this.enabled=this.resolveEnabledState(),this.enabled&&(this.mountControls(),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),window.addEventListener("pointercancel",this.onPointerUp),window.addEventListener("blur",this.onWindowBlur))}getInput(e){if(!this.enabled)return{};let t={};for(let n of this.buttons.values()){let i=this.handleButtonState(`button:${n.slot}`,n.pointerId!==null,e);this.assignButtonState(t,this.resolveButtonTarget(n.slot),i)}for(let n of this.joysticks.values()){let i=this.handleAnalogState(`joystick:${n.id}:x`,n.valueX,e),o=this.handleAnalogState(`joystick:${n.id}:y`,n.valueY,e);this.assignAxisState(t,n.config.horizontalAxis,i),this.assignAxisState(t,n.config.verticalAxis,o),n.config.emitDirections&&(this.assignButtonState(t,this.resolveButtonTarget("Left"),this.handleButtonState(`joystick:${n.id}:left`,n.valueX<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Right"),this.handleButtonState(`joystick:${n.id}:right`,n.valueX>=n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Up"),this.handleButtonState(`joystick:${n.id}:up`,n.valueY<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Down"),this.handleButtonState(`joystick:${n.id}:down`,n.valueY>=n.config.directionThreshold,e)))}return t}getName(){return"virtual-touch"}isConnected(){return this.enabled}dispose(){window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerUp),window.removeEventListener("blur",this.onWindowBlur),this.rootElement?.remove(),this.rootElement=null,this.buttons.clear(),this.joysticks.clear(),this.buttonStates.clear(),this.analogStates.clear()}resolveEnabledState(){return typeof window>"u"||typeof document>"u"?!1:this.config.enabled===!0?!0:this.config.enabled===!1?!1:R()}mountControls(){this.rootElement=document.createElement("div"),this.rootElement.className="zylem-virtual-touch",this.rootElement.dataset.zylemTouchRoot="true",this.rootElement.style.position="absolute",this.rootElement.style.inset="0",this.rootElement.style.pointerEvents="none",this.rootElement.style.touchAction="none",this.rootElement.style.userSelect="none",this.rootElement.style.WebkitUserSelect="none",this.rootElement.style.WebkitTouchCallout="none",this.rootElement.style.color="rgba(245, 247, 255, 0.96)",this.rootElement.style.zIndex="20",this.appendClassName(this.rootElement,this.config.className),E(this.rootElement,this.config.style),this.rootElement.addEventListener("contextmenu",e=>e.preventDefault());for(let[e,t]of this.resolveButtons())this.rootElement.appendChild(this.createButton(e,t));for(let[e,t]of this.resolveJoysticks())this.rootElement.appendChild(this.createJoystick(e,t));this.targetElement.appendChild(this.rootElement)}resolveButtons(){if(this.config.buttons===!1)return[];let e=this.config.buttons,t=[];for(let n of He){let i=_e[n],o=e?.[n];if(o===!1)continue;let r={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},label:o?.label??i.label??n,size:o?.size??i.size??72};r.enabled!==!1&&t.push([n,r])}return t}resolveJoysticks(){if(this.config.joysticks===!1)return[];let e=this.config.joysticks,t=[];for(let n of["left","right"]){let i=Ne[n],o=e?.[n];if(o===!1)continue;let r={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},svg:{...i.svg,...o?.svg},size:o?.size??i.size??140,thumbSize:o?.thumbSize??i.thumbSize??58,maxDistance:o?.maxDistance??i.maxDistance??44,deadzone:o?.deadzone??i.deadzone??.12,directionThreshold:o?.directionThreshold??i.directionThreshold??.34,horizontalAxis:o?.horizontalAxis??i.horizontalAxis??"Horizontal",verticalAxis:o?.verticalAxis??i.verticalAxis??"Vertical",emitDirections:o?.emitDirections??i.emitDirections??!1};r.enabled!==!1&&t.push([n,r])}return t}createButton(e,t){let n=document.createElement("button"),i=document.createElement("div");n.type="button",n.ariaLabel=t.label,n.className=`zylem-virtual-touch__button zylem-virtual-touch__button--${e}`,n.dataset.zylemTouchButton=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.padding="0",n.style.margin="0",n.style.border="0",n.style.background="transparent",n.style.pointerEvents="auto",n.style.touchAction="none",n.style.cursor="pointer",n.style.appearance="none",n.style.outline="none",n.style.userSelect="none",n.style.WebkitTapHighlightColor="transparent",E(n,t.position),E(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__button-content",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.transform="scale(1)",i.style.transformOrigin="center",i.style.transition="transform 120ms ease, opacity 120ms ease",i.style.opacity="0.92",i.innerHTML=t.svg??Fe(t.label),n.appendChild(i),n.addEventListener("pointerdown",r=>{if(!we(r))return;let s=this.buttons.get(e);!s||s.pointerId!==null||(this.consumeEvent(r),s.pointerId=r.pointerId,this.updateButtonVisual(s,!0))});let o={slot:e,config:t,element:n,content:i,pointerId:null};return this.buttons.set(e,o),n}createJoystick(e,t){let n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");n.className=`zylem-virtual-touch__joystick zylem-virtual-touch__joystick--${e}`,n.dataset.zylemTouchJoystick=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.pointerEvents="auto",n.style.touchAction="none",n.style.userSelect="none",E(n,t.position),E(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__joystick-base",i.style.position="absolute",i.style.inset="0",i.style.pointerEvents="none",i.style.opacity="0.88",i.style.transition="opacity 120ms ease",i.innerHTML=t.svg?.base??Xe(),o.className="zylem-virtual-touch__joystick-thumb",o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.width=`${t.thumbSize}px`,o.style.height=`${t.thumbSize}px`,o.style.pointerEvents="none",o.style.transform="translate(-50%, -50%) translate(0px, 0px)",o.style.transition="transform 60ms linear, opacity 120ms ease",o.style.opacity="0.94",o.innerHTML=t.svg?.thumb??Ye(),n.append(i,o);let r={id:e,config:t,element:n,base:i,thumb:o,pointerId:null,centerX:0,centerY:0,rawX:0,rawY:0,valueX:0,valueY:0};return this.joysticks.set(e,r),n.addEventListener("pointerdown",s=>{if(!we(s))return;let l=this.joysticks.get(e);if(!l||l.pointerId!==null)return;this.consumeEvent(s);let u=l.element.getBoundingClientRect();l.pointerId=s.pointerId,l.centerX=u.left+u.width/2,l.centerY=u.top+u.height/2,this.updateJoystickVisual(l,!0),this.updateJoystickFromPoint(l,s.clientX,s.clientY)}),n}handleButtonState(e,t,n){let i=this.buttonStates.get(e);return i||(i={pressed:!1,released:!1,held:0},this.buttonStates.set(e,i)),i.pressed=t&&i.held===0,i.released=!t&&i.held>0,i.held=t?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates.get(e);return i||(i={value:0,held:0},this.analogStates.set(e,i)),i.value=t,i.held=t!==0?i.held+n:0,i}assignAxisState(e,t,n){e.axes||(e.axes={}),e.axes[t]=f(e.axes[t],n)}assignButtonState(e,t,n){if(t.category==="buttons"){e.buttons??={},e.buttons[t.property]=d(e.buttons[t.property],n);return}if(t.category==="directions"){e.directions??={},e.directions[t.property]=d(e.directions[t.property],n);return}e.shoulders??={},e.shoulders[t.property]=d(e.shoulders[t.property],n)}resolveButtonTarget(e){switch(e){case"LTrigger":case"RTrigger":return{category:"shoulders",property:e};case"Up":case"Down":case"Left":case"Right":return{category:"directions",property:e};default:return{category:"buttons",property:e}}}updateJoystickFromPoint(e,t,n){let i=t-e.centerX,o=n-e.centerY,r=Math.hypot(i,o),s=e.config.maxDistance,l=r>s&&r>0?s/r:1;e.rawX=i*l,e.rawY=o*l;let u=Ue(e.rawX/s,e.rawY/s,e.config.deadzone);e.valueX=u.x,e.valueY=u.y,e.thumb.style.transform=`translate(-50%, -50%) translate(${e.rawX}px, ${e.rawY}px)`}releaseButton(e){e.pointerId=null,this.updateButtonVisual(e,!1)}releaseJoystick(e){e.pointerId=null,e.rawX=0,e.rawY=0,e.valueX=0,e.valueY=0,e.thumb.style.transform="translate(-50%, -50%) translate(0px, 0px)",this.updateJoystickVisual(e,!1)}updateButtonVisual(e,t){e.element.dataset.active=String(t),e.content.style.transform=t?"scale(0.94)":"scale(1)",e.content.style.opacity=t?"1":"0.92"}updateJoystickVisual(e,t){e.element.dataset.active=String(t),e.base.style.opacity=t?"1":"0.88",e.thumb.style.opacity=t?"1":"0.94"}consumeEvent(e){e.cancelable&&e.preventDefault(),e.stopPropagation()}appendClassName(e,t){t&&(e.className=`${e.className} ${t}`.trim())}};function E(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!Oe.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function Ue(a,e,t){let n=Math.hypot(a,e);if(n===0||n<=t)return{x:0,y:0};let o=Math.min(1,(n-t)/Math.max(1-t,1e-4))/n;return{x:a*o,y:e*o}}function Fe(a){let e=Ze(a);return`
2
- <svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true">
3
- <circle cx="50" cy="50" r="45" fill="rgba(12,18,24,0.72)" stroke="currentColor" stroke-width="4" />
4
- <circle cx="50" cy="50" r="34" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
5
- <text
6
- x="50"
7
- y="56"
8
- text-anchor="middle"
9
- font-family="ui-sans-serif, system-ui, sans-serif"
10
- font-size="${e.length>2?24:34}"
11
- font-weight="700"
12
- fill="currentColor"
13
- >${e}</text>
14
- </svg>
15
- `}function Xe(){return`
16
- <svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
17
- <circle cx="70" cy="70" r="62" fill="rgba(10,16,20,0.64)" stroke="currentColor" stroke-width="4" />
18
- <circle cx="70" cy="70" r="40" fill="rgba(255,255,255,0.04)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
19
- </svg>
20
- `}function Ye(){return`
21
- <svg viewBox="0 0 64 64" width="100%" height="100%" aria-hidden="true">
22
- <circle cx="32" cy="32" r="28" fill="rgba(22,30,38,0.9)" stroke="currentColor" stroke-width="3.5" />
23
- </svg>
24
- `}function Ze(a){return a.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function we(a){return a.pointerType==="touch"}var A=class{inputMap=new Map;currentInputs={};previousInputs={};targetElement;mouseTargetElement;constructor(e,t){this.targetElement=t?.targetElement,this.mouseTargetElement=t?.mouseTargetElement??t?.targetElement;let n=this.buildPlayerEntries(e);for(let{player:i,config:o,gamepadIndex:r,isP1:s}of n)this.addConfigurableProviders(i,o,s),this.addInputProvider(i,new k(r))}configure(e){let t=this.buildPlayerEntries(e);for(let{player:n,config:i,isP1:o}of t){let s=(this.inputMap.get(n)??[]).filter(l=>l instanceof w||l instanceof T||l instanceof M?(l.dispose(),!1):!0);this.inputMap.set(n,[...this.createConfigurableProviders(i,o),...s])}}addInputProvider(e,t){this.inputMap.has(e)||this.inputMap.set(e,[]),this.inputMap.get(e)?.push(t)}dispose(){for(let e of this.inputMap.values())for(let t of e)t.dispose?.();this.inputMap.clear(),this.currentInputs={},this.previousInputs={}}getInputs(e){let t={};return this.inputMap.forEach((n,i)=>{let o=`p${i}`,r=n.reduce((s,l)=>{let u=l.getInput(e);return this.mergeInputs(s,u)},{});t[o]={playerNumber:i,...r}}),t}buildPlayerEntries(e){return[{player:1,config:e?.p1,gamepadIndex:0,isP1:!0},{player:2,config:e?.p2,gamepadIndex:1,isP1:!1},{player:3,config:e?.p3,gamepadIndex:2,isP1:!1},{player:4,config:e?.p4,gamepadIndex:3,isP1:!1},{player:5,config:e?.p5,gamepadIndex:4,isP1:!1},{player:6,config:e?.p6,gamepadIndex:5,isP1:!1},{player:7,config:e?.p7,gamepadIndex:6,isP1:!1},{player:8,config:e?.p8,gamepadIndex:7,isP1:!1}]}addConfigurableProviders(e,t,n){for(let i of this.createConfigurableProviders(t,n))this.addInputProvider(e,i)}createConfigurableProviders(e,t){let n=[];if(e?.key){let i=e.includeDefaults??t;n.push(new w(e.key,{includeDefaultBase:i}))}else t&&n.push(new w);return e?.mouse&&n.push(new T(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new M(e.touch,this.targetElement)),n}mergeInputs(e,t){return{buttons:{A:d(e.buttons?.A,t.buttons?.A),B:d(e.buttons?.B,t.buttons?.B),X:d(e.buttons?.X,t.buttons?.X),Y:d(e.buttons?.Y,t.buttons?.Y),Start:d(e.buttons?.Start,t.buttons?.Start),Select:d(e.buttons?.Select,t.buttons?.Select),L:d(e.buttons?.L,t.buttons?.L),R:d(e.buttons?.R,t.buttons?.R)},directions:{Up:d(e.directions?.Up,t.directions?.Up),Down:d(e.directions?.Down,t.directions?.Down),Left:d(e.directions?.Left,t.directions?.Left),Right:d(e.directions?.Right,t.directions?.Right)},axes:{Horizontal:f(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:f(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:f(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:f(e.axes?.SecondaryVertical,t.axes?.SecondaryVertical)},shoulders:{LTrigger:d(e.shoulders?.LTrigger,t.shoulders?.LTrigger),RTrigger:d(e.shoulders?.RTrigger,t.shoulders?.RTrigger)},pointer:t.pointer??e.pointer}}};var V=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=q(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=Je.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=q()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:q())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function q(){return performance.now()}function Je(){this._document.hidden===!1&&this.reset()}var I={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},H=class{container;canvas;aspectRatio;onResize;handleResizeBound;resizeObserver=null;constructor(e){this.container=e.container,this.canvas=e.canvas,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio),this.onResize=e.onResize,this.handleResizeBound=this.apply.bind(this)}attach(){window.addEventListener("resize",this.handleResizeBound),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(this.handleResizeBound),this.resizeObserver.observe(this.container)),this.apply()}detach(){window.removeEventListener("resize",this.handleResizeBound),this.resizeObserver?.disconnect(),this.resizeObserver=null}measure(){let e=this.container.getBoundingClientRect(),t=Math.round(e.width||this.container.clientWidth||0),n=Math.round(e.height||this.container.clientHeight||0);if(t>0&&n>0){if(t/n>this.aspectRatio){let u=n;return{width:Math.round(u*this.aspectRatio),height:u}}let s=t,l=Math.round(s/this.aspectRatio);return{width:s,height:l}}if(t>0){let r=t,s=Math.round(r/this.aspectRatio);return{width:r,height:s}}if(n>0){let r=n;return{width:Math.round(r*this.aspectRatio),height:r}}let i=window.innerWidth,o=Math.round(i/this.aspectRatio);return{width:i,height:o}}apply(){let{width:e,height:t}=this.measure();this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.onResize?.(e,t)}};var Ce={NES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x240",width:256,height:240,notes:"Standard NTSC; effective 240p."}]},SNES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x224",width:256,height:224,notes:"Common 240p-equivalent mode."},{key:"512x448",width:512,height:448,notes:"Hi-res interlaced (480i)."}]},N64:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Common 240p mode."},{key:"640x480",width:640,height:480,notes:"Higher resolution (480i)."}]},PS1:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Progressive 240p common."},{key:"640x480",width:640,height:480,notes:"Interlaced 480i for higher detail."}]},PS2:{displayAspect:1.3333333333333333,resolutions:[{key:"640x480",width:640,height:480,notes:"480i/480p baseline."},{key:"720x480",width:720,height:480,notes:"480p (widescreen capable in some titles)."},{key:"1280x720",width:1280,height:720,notes:"720p (select titles)."}]},PS5:{displayAspect:1.7777777777777777,resolutions:[{key:"720x480",width:720,height:480,notes:"Legacy compatibility."},{key:"1280x720",width:1280,height:720,notes:"720p."},{key:"1920x1080",width:1920,height:1080,notes:"1080p."},{key:"2560x1440",width:2560,height:1440,notes:"1440p."},{key:"3840x2160",width:3840,height:2160,notes:"4K (up to 120Hz)."},{key:"7680x4320",width:7680,height:4320,notes:"8K (limited)."}]},XboxOne:{displayAspect:1.7777777777777777,resolutions:[{key:"1280x720",width:1280,height:720,notes:"720p (original)."},{key:"1920x1080",width:1920,height:1080,notes:"1080p (original)."},{key:"3840x2160",width:3840,height:2160,notes:"4K UHD (S/X models)."}]},MobilePortrait:{displayAspect:.5625,resolutions:[{key:"360x640",width:360,height:640,notes:"Low-density phone portrait baseline."},{key:"720x1280",width:720,height:1280,notes:"HD phone portrait."},{key:"1080x1920",width:1080,height:1920,notes:"Full HD phone portrait."}]}};function Q(a){return Ce[a].displayAspect}function ee(a,e){let t=Ce[a]?.resolutions||[];if(!e)return t[0];let n=e.toLowerCase().replace(/\s+/g,"").replace("\xD7","x");return t.find(i=>i.key.toLowerCase()===n)}function te(a){if(!a)return null;let t=String(a).toLowerCase().trim().replace(/\s+/g,"").replace("\xD7","x").match(/^(\d+)x(\d+)$/);if(!t)return null;let n=parseInt(t[1],10),i=parseInt(t[2],10);return!Number.isFinite(n)||!Number.isFinite(i)?null:{width:n,height:i}}var ne=null,ie=class{constructor(e,t,n,i,o,r,s,l,u,m,p,h,Z){this.id=e;this.globals=t;this.stages=n;this.debug=i;this.time=o;this.input=r;this.aspectRatio=s;this.internalResolution=l;this.fullscreen=u;this.bodyBackground=m;this.container=p;this.containerId=h;this.canvas=Z}};function Ke(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?R({viewportSize:a.viewportSize,allowViewportOnly:!0}):R()}function $e(a,e){if(e)return e;if(a){let i=document.getElementById(a);if(i)return i}let t=a||"zylem-root",n=document.createElement("main");return n.setAttribute("id",t),n.style.position="relative",n.style.width="100%",n.style.height="100%",document.body.appendChild(n),n}function We(a){let e=a?.id??"zylem";return{id:e,globals:a?.globals??{},stages:a?.stages??[],debug:!!a?.debug,time:a?.time??0,input:a?.input,aspectRatio:I.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var xe=360;function Ge(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return ne;let i=te(a);if(i)return i;if(e){let o=ee(e,a);if(o)return{width:o.width,height:o.height}}return}let t=a.width,n=a.height;if(Number.isFinite(t)&&Number.isFinite(n))return{width:t,height:n}}function je(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return I[a]??t;if(e)try{return Q(e)||t}catch{return t}return n?n.width/n.height:t}function qe(a){let e=Number.isFinite(a)&&a>0?a:I.SixteenByNine;if(e>=1){let i=xe;return{width:Math.round(i*e),height:i}}let t=xe,n=Math.round(t/e);return{width:t,height:n}}function B(a,e={}){let t=We({id:a?.id??"zylem",debug:!!a?.debug,time:a?.time??0,input:a?.input,stages:a?.stages??[],globals:a?.globals??{}}),n=a?.containerId??t.containerId,i=$e(n,a?.container??null),o=a?.mobile,r=Ke(e),s=r?o?.preset??a?.preset:a?.preset,l=Ge(a?.resolution,a?.preset),u=Ge(o?.resolution,o?.preset??a?.preset),m=(r?Te(u):void 0)??Te(l),p=r?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,h=je(p,s,t.aspectRatio,m),Z=Qe(r,u,l,h),Ie=a?.fullscreen??t.fullscreen,Be=a?.bodyBackground??t.bodyBackground,Pe=a?.canvas??void 0,Le=et(a?.input??t.input,o?.controls);return new ie(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,Le,h,Z,Ie,Be,i,n,Pe)}function Te(a){if(a)return a}function Qe(a,e,t,n){if(a)return e===ne?void 0:e??qe(n);if(t!==ne)return t}function et(a,e){if(!e)return a;let n=ge("p1",{enabled:"auto",...e===!0?{}:e});return v(n,a??{})}function tt(a){return{...a}}var O=class{id;container;canvas;bodyBackground;fullscreen;aspectRatio;ratioDelegate=null;overlayContainer=null;constructor(e){this.id=e.id,this.container=this.ensureContainer(e.containerId??e.id,e.container),this.canvas=e.canvas??document.createElement("canvas"),this.bodyBackground=e.bodyBackground,this.fullscreen=!!e.fullscreen,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio)}applyBodyBackground(){this.bodyBackground&&(document.body.style.background=this.bodyBackground)}mountCanvas(){this.mountChildren(this.canvas)}mountRenderer(e,t){this.mountChildren(e),this.canvas=e,this.attachAspectRatio(t)}getOverlayContainer(){return this.ensureOverlayContainer()}centerIfFullscreen(){if(!this.fullscreen)return;let e=this.container.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.position="relative",e.inset="0"}attachAspectRatio(e){this.ratioDelegate?(this.ratioDelegate.canvas=this.canvas,this.ratioDelegate.onResize=e,this.ratioDelegate.aspectRatio=this.aspectRatio,this.ratioDelegate.apply()):(this.ratioDelegate=new H({container:this.container,canvas:this.canvas,aspectRatio:this.aspectRatio,onResize:e}),this.ratioDelegate.attach())}setAspectRatio(e){this.aspectRatio=e,this.ratioDelegate&&(this.ratioDelegate.aspectRatio=e,this.ratioDelegate.apply())}reapplyLayout(){this.ratioDelegate?.apply()}destroy(){this.ratioDelegate?.detach(),this.ratioDelegate=null}mountChildren(e){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.appendChild(e),this.container.appendChild(this.ensureOverlayContainer())}ensureOverlayContainer(){if(this.overlayContainer)return this.overlayContainer;let e=document.createElement("div");return e.dataset.zylemOverlayRoot="true",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.touchAction="none",e.style.zIndex="10",this.overlayContainer=e,e}ensureContainer(e,t){if(t)return t;if(e){let o=document.getElementById(e);if(o)return o}let n=e||this.id||"zylem-root",i=document.createElement("main");return i.setAttribute("id",n),i.style.position="relative",i.style.width="100%",i.style.height="100%",document.body.appendChild(i),i}};import nt from"stats.js";import{subscribe as it}from"valtio/vanilla";var _=class{statsRef=null;unsubscribe=null;constructor(){this.updateDebugUI(),this.unsubscribe=it(g,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}updateDebugUI(){g.enabled&&!this.statsRef?(this.statsRef=new nt,this.statsRef.showPanel(0),this.statsRef.dom.style.position="absolute",this.statsRef.dom.style.bottom="0",this.statsRef.dom.style.right="0",this.statsRef.dom.style.top="auto",this.statsRef.dom.style.left="auto",document.body.appendChild(this.statsRef.dom)):!g.enabled&&this.statsRef&&(this.statsRef.dom.parentNode&&this.statsRef.dom.parentNode.removeChild(this.statsRef.dom),this.statsRef=null)}dispose(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.statsRef?.dom?.parentNode&&this.statsRef.dom.parentNode.removeChild(this.statsRef.dom),this.statsRef=null}};var N=class{loadingHandlers=[];stageLoadingUnsubscribes=[];onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let n of this.loadingHandlers)try{n(e)}catch(i){console.error("Game loading handler failed",i)}let t=`loading:${e.type}`;y.emit(t,e)}wireStageLoading(e,t){let n=e.onLoading(i=>{this.emit({type:i.type,message:i.message??"",progress:i.progress??0,current:i.current,total:i.total,stageName:e.uuid??`Stage ${t}`,stageIndex:t})});typeof n=="function"&&this.stageLoadingUnsubscribes.push(n)}unwireAllStages(){for(let e of this.stageLoadingUnsubscribes)try{e()}catch{}this.stageLoadingUnsubscribes=[]}dispose(){this.unwireAllStages(),this.loadingHandlers=[]}};var U=class{container=null;camera=null;rendererManager=null;gameCanvas=null;config=null;stage=null;mounted=!1;setGameCanvas(e){this.gameCanvas=e,this.tryMount()}setConfig(e){this.config=e,this.tryMount()}setContainer(e){this.container=e,this.tryMount()}setStage(e){this.stage=e,this.mounted&&this.gameCanvas?.reapplyLayout()}setCamera(e){this.camera=e,this.tryMount()}setRendererManager(e){this.rendererManager=e,this.tryMount()}tryMount(){this.mounted||!this.container||!this.gameCanvas||(this.rendererManager?this.mountWithRendererManager():this.camera&&this.mountWithCamera())}mountWithRendererManager(){if(!this.rendererManager||!this.gameCanvas)return;let e=this.rendererManager.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.rendererManager)return;let i=this.config?.internalResolution;if(i)this.rendererManager.setPixelRatio(1),this.rendererManager.resize(i.width,i.height),this.stage?.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.rendererManager.setPixelRatio(o),this.rendererManager.resize(t,n),this.stage?.resize(t,n)}}),this.mounted=!0}mountWithCamera(){if(!this.camera||!this.gameCanvas)return;let e=this.camera.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.camera)return;let i=this.config?.internalResolution;if(i)this.camera.setPixelRatio(1),this.camera.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.camera.setPixelRatio(o),this.camera.resize(t,n)}}),this.mounted=!0}reset(){this.camera=null,this.stage=null,this.mounted=!1}dispose(){this.container=null,this.camera=null,this.rendererManager=null,this.gameCanvas=null,this.config=null,this.stage=null,this.mounted=!1}};var F=class a{id;initialGlobals={};customSetup=null;customUpdate=null;customDestroy=null;stages=[];stageMap=new Map;currentStageId="";previousTimeStamp=0;totalTime=0;timer;inputManager;wrapperRef;globalInputConfig;defaultCamera=null;rendererManager=null;container=null;canvas=null;aspectRatioDelegate=null;resolvedConfig=null;gameCanvas=null;animationFrameId=null;isDisposed=!1;loadInFlight=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new N;rendererObserver=new U;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];entityDispatchTimer=null;pendingEntityDispatchPath=null;static ENTITY_DISPATCH_DEBOUNCE_MS=150;gameUpdateParams={};stageSetupParams={};stageUpdateParams={};frameCallback=e=>this.loop(e);sourceOptions;displayRuntime;static FRAME_LIMIT=120;static FRAME_DURATION=1e3/a.FRAME_LIMIT;static MAX_DELTA_SECONDS=1/30;constructor(e,t,n={}){this.wrapperRef=t,this.timer=new V,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=B(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new A(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e)}setDisplayRuntime(e){this.displayRuntime={...e};let t=B(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.emitStateDispatch("@game:display-config")}loadGameCanvas(e){this.gameCanvas=new O({id:e.id,container:e.container,containerId:e.containerId,canvas:this.canvas??void 0,bodyBackground:e.bodyBackground,fullscreen:e.fullscreen,aspectRatio:e.aspectRatio}),this.gameCanvas.applyBodyBackground(),this.gameCanvas.mountCanvas(),this.gameCanvas.centerIfFullscreen(),this.rendererObserver.setGameCanvas(this.gameCanvas),this.resolvedConfig&&this.rendererObserver.setConfig(this.resolvedConfig),this.container&&this.rendererObserver.setContainer(this.container),this.subscribeToEventBus()}loadDebugOptions(e){e.debug!==void 0&&(g.enabled=!!e.debug),this.debugDelegate=new _}isLoading(){return this.loadInFlight}async loadStage(e,t=0,n){if(this.loadInFlight){console.warn("loadStage ignored: a stage load is already in progress");return}this.loadInFlight=!0;try{await this.performLoadStage(e,t,n)}finally{this.loadInFlight=!1}}async performLoadStage(e,t=0,n){let i=n?ye(n):null,o=this.currentStage()??null,r=o?.wrappedStage??null,s=r?.scene?.scene??null,l=r?.cameraManagerRef?.primaryCamera?.camera??r?.cameraRef?.camera??null;i&&this.rendererManager?.initialized&&o&&s&&l&&this.rendererManager.beginSnapshotTransition(i,s,l),this.unloadCurrentStage();let m=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new he,await this.rendererManager.initRenderer()),b.setRenderer(this.rendererManager.renderer),await e.load(this.id,m?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.wireEntityThumbnails(e),this.rendererObserver.setStage(e.wrappedStage??null),this.rendererManager&&this.rendererObserver.setRendererManager(this.rendererManager),this.applyInputConfig(e),e.onInputConfigChanged=()=>this.applyInputConfig(e),this.hasStarted&&e.wrappedStage&&!e.wrappedStage.hasSetup){let p=this.params(),h={...this.stageSetupParams};h.inputs=p.inputs,h.globals=p.globals,h.camera=p.camera,h.stage=p.stage,h.game=p.game,h.me=e.wrappedStage,e.start(h)}this.emitStateDispatch("@stage:loaded")}applyInputConfig(e){let t=v(this.globalInputConfig??{},e.inputConfig??{});this.inputManager.configure(t)}setGlobalInputConfig(e){this.globalInputConfig=e;let t=this.currentStage();t&&this.applyInputConfig(t)}unloadCurrentStage(){if(!this.currentStageId)return;let e=this.getStage(this.currentStageId);if(e){if(this.clearEntityThumbnailWiring(),b.clear(),e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:C.globals})}catch(t){console.error("Failed to destroy previous stage",t)}e.wrappedStage=null}e.dispose(),this.stageMap.delete(this.currentStageId),this.currentStageId="",this.defaultCamera=null,this.rendererObserver.reset()}}setGlobals(e){this.initialGlobals={...e.globals};for(let t in this.initialGlobals){let n=this.initialGlobals[t];n===void 0&&console.error(`global ${t} is undefined`),le(t,n)}}params(){let e=this.currentStage(),t=this.timer.getDelta(),n=this.inputManager.getInputs(t),i=e?.wrappedStage?.cameraRef||this.defaultCamera,o=this.gameUpdateParams;return o.delta=t,o.inputs=n,o.globals=de(),o.me=this,o.camera=i,o.stage=e,o.game=this.wrapperRef,o}start(){let e=this.currentStage(),t=this.params(),n=this.stageSetupParams;n.inputs=t.inputs,n.globals=t.globals,n.camera=t.camera,n.stage=t.stage,n.game=t.game,n.me=e.wrappedStage,e.start(n),this.customSetup&&this.customSetup(t),this.hasStarted=!0,this.loop(0)}step(e){let t=this.currentStage();if(!t||!t.wrappedStage)return;let n=this.params(),i=e!==void 0?e:n.delta,o=Math.min(Math.max(i,0),a.MAX_DELTA_SECONDS);n.delta=o,this.customUpdate&&this.customUpdate(n);let r=this.currentStage();if(r!==t||!r?.wrappedStage){this.totalTime+=o,C.time=this.totalTime;return}let s=this.stageUpdateParams;s.delta=n.delta,s.inputs=n.inputs,s.globals=n.globals,s.camera=n.camera,s.stage=n.stage,s.game=n.game,s.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(s),this.totalTime+=o,C.time=this.totalTime}loop(e){this.debugDelegate?.begin(),me()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(b.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:C.globals}),x()}outOfLoop(){let e=this.currentStage();e&&e.wrappedStage.outOfLoop()}getStage(e){return this.stageMap.get(e)}currentStage(){return this.getStage(this.currentStageId)}onLoading(e){return this.loadingDelegate.onLoading(e)}buildStageConfigPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=e.wrappedStage.state,n=t.backgroundColor,i=typeof n=="string"?n:`#${n.getHexString()}`;return{id:e.wrappedStage.uuid,backgroundColor:i,backgroundImage:t.backgroundImage,gravity:{x:t.gravity.x,y:t.gravity.y,z:t.gravity.z},inputs:t.inputs,variables:t.variables}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{if(P(n.options))return;let i=n.constructor.type,o=i?String(i).replace("Symbol(","").replace(")",""):"Unknown",r=n.position??{x:0,y:0,z:0},s=n.rotation??{x:0,y:0,z:0},l=n.scale??{x:1,y:1,z:1},u=b.get(n.uuid);t.push({uuid:n.uuid,name:n.name||"Unnamed",type:o,position:{x:r.x??0,y:r.y??0,z:r.z??0},rotation:{x:s.x??0,y:s.y??0,z:s.z??0},scale:{x:l.x??1,y:l.y??1,z:l.z??1},thumbnail:u?.dataUrl??null,bounds:u?.bounds})}),t}wireEntityThumbnails(e){if(this.clearEntityThumbnailWiring(),!e.wrappedStage)return;let t=r=>{if(P(r.options))return;let s=r.group??r.mesh??null;s&&b.ensure(r.uuid,s).then(l=>{l&&this.queueEntityStateDispatch("@entity:thumbnail")})},n=e.wrappedStage.onEntityAdded(r=>{t(r)},{replayExisting:!0});this.thumbnailUnsubscribes.push(n);let i=r=>{if(!r.success)return;let s=e.wrappedStage?.entityDelegate.childrenMap.get(r.entityId);s&&(b.invalidate(r.entityId),t(s))};y.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{y.off("entity:model:loaded",i)});let o=r=>{b.invalidate(r.entityId),this.queueEntityStateDispatch("@entity:destroyed")};y.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{y.off("entity:destroyed",o)})}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[],this.entityDispatchTimer!==null&&(clearTimeout(this.entityDispatchTimer),this.entityDispatchTimer=null),this.pendingEntityDispatchPath=null}queueEntityStateDispatch(e){this.pendingEntityDispatchPath=e,this.entityDispatchTimer===null&&(this.entityDispatchTimer=setTimeout(()=>{this.entityDispatchTimer=null;let t=this.pendingEntityDispatchPath;this.pendingEntityDispatchPath=null,t&&!this.isDisposed&&this.emitStateDispatch(t)},a.ENTITY_DISPATCH_DEBOUNCE_MS))}emitStateDispatch(e,t,n){let i={scope:"game",path:e,value:t,previousValue:n,config:this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null,stageConfig:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()};y.emit("state:dispatch",i)}subscribeToEventBus(){this.eventBusUnsubscribes.push(re.on("game:state:updated",e=>{this.emitStateDispatch(e.path,e.value,e.previousValue)}))}};async function Re(a){let{getGameDefaultConfig:e}=await import("./game-default-6AZZCNST.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(s=>{if(s instanceof L)i.push(s);else if(s instanceof j)o.push(s);else if(s instanceof $)o.push(s);else if(s?.constructor?.name==="Object"&&typeof s=="object"){let l=Object.assign({...e()},{...s});n.push(l)}}),n.forEach(s=>{t=Object.assign(t,{...s})});let r=t;return r.input=n[0].input,i.forEach(s=>{s.addEntities(o)}),i.length?r.stages=i:r.stages[0].addEntities(o),r}function Ee(a){return!!a.find(t=>t instanceof L)}function ae(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof L)&&!(e instanceof $)&&!(e instanceof j)){let t=e;if(t.globals)return t.globals}}import{proxy as at}from"valtio/vanilla";import{get as ot,set as st}from"idb-keyval";import{pack as rt,unpack as lt}from"msgpackr";var c=at({previous:null,current:null,next:null,isLoading:!1}),X={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await ot(a);if(e)return lt(e)}catch(e){console.warn(`Failed to load stage ${a} from storage`,e)}if(this.staticRegistry.has(a))return this.staticRegistry.get(a);throw new Error(`Stage ${a} not found in storage and static loading not fully implemented.`)},async transitionForward(a,e){if(!c.isLoading){c.isLoading=!0;try{c.current&&await st(c.current.id,rt(c.current)),c.previous=c.current,c.current=c.next,c.current?.id!==a&&(e?c.current=await e(a):c.current=await this.loadStageData(a)),c.next=null}catch(t){console.error("Failed to transition stage:",t)}finally{c.isLoading=!1}}},async preloadNext(a,e){e?c.next=await e(a):c.next=await this.loadStageData(a)}};var oe={async createFromBlueprint(a){let e=G({});if(a.entities)for(let t of a.entities)try{let n=await Se.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var Y=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new fe;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,Ee(e)||this.options.push(G());let t=ae(e);t&&J(t)}onSetup(...e){return this.setupCallbacks.push(...e),this}onUpdate(...e){return this.updateCallbacks.push(...e),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this}setInputConfiguration(...e){let t=v(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){x();let e=ae(this.options);e&&J(e);let t=await this.load();return this.wrappedGame=t,this.setOverrides(),this.registerGlobalSubscriptions(),t.start(),this}setDisplayRuntime(e){return this.displayRuntime={...this.displayRuntime,...e},this.wrappedGame&&this.wrappedGame.setDisplayRuntime(this.displayRuntime),this}setDeviceProfile(e){return this.setDisplayRuntime({deviceProfile:e})}setViewportSize(e,t){return this.setDisplayRuntime({viewportSize:{width:e,height:t}})}async load(){let e=await Re(this.options),t=B(e,this.displayRuntime);this.pendingInputConfig&&(t.input=v(t.input??{},this.pendingInputConfig));let n=new F({...e,...t},this,this.displayRuntime);for(let i of this.pendingLoadingCallbacks)n.onLoading(i);return await n.loadStage(e.stages[0]),n}setOverrides(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.customSetup=e=>{this.setupCallbacks.forEach(t=>t(e))},this.wrappedGame.customUpdate=e=>{this.updateCallbacks.forEach(t=>t(e))},this.wrappedGame.customDestroy=e=>{this.destroyCallbacks.forEach(t=>t(e))}}onGlobalChange(e,t){return this.globalChangeCallbacks.push({path:e,callback:t}),this}onGlobalChanges(e,t){return this.globalChangesCallbacks.push({paths:e,callback:t}),this}registerGlobalSubscriptions(){for(let{path:e,callback:t}of this.globalChangeCallbacks){let n=ue(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=pe(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}experimental={getRuntime:()=>this.getCurrentStage()?.wrappedStage?.world?.simulation??null};async pause(){K(!0)}async resume(){K(!1),this.wrappedGame&&(this.wrappedGame.previousTimeStamp=0,this.wrappedGame.timer.reset())}step(e=1/60){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.step(e)}async reset(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.isLoading()||await this.wrappedGame.loadStage(this.wrappedGame.stages[0],0,e?.transition)}previousStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n-1];if(!i){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(i,n-1,e?.transition)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await X.loadStageData(e),n=await oe.createFromBlueprint(t);await this.wrappedGame.loadStage(n),c.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;if(c.next){console.log("next stage called");let o=c.next.id;if(X.transitionForward(o),c.current){oe.createFromBlueprint(c.current).then(r=>{this.wrappedGame?.loadStage(r,0,e?.transition)});return}}let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n+1];if(!i){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(i,n+1,e?.transition)}async goToStage(){}async end(){}dispose(){this.eventDelegate.dispose();for(let e of this.activeGlobalSubscriptions)e();this.activeGlobalSubscriptions=[],this.wrappedGame&&(this.wrappedGame.dispose(),this.wrappedGame=null),ce(),x(),be.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),y.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}onLoading(e){return this.wrappedGame?this.wrappedGame.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e),this.wrappedGame})}};function ut(...a){return new Y(a)}import{Euler as pt,Quaternion as dt,Vector2 as ct}from"three";function mt(a){return{spawn:async(e,t,n)=>{let i=await Promise.resolve(a(t,n));return e.add(i),i},spawnRelative:async(e,t,n=new ct(0,1))=>{if(!e.body){console.warn("body missing for entity during spawnRelative");return}let{x:i,y:o,z:r}=e.body.translation(),s=e._rotation2DAngle??0;try{let p=e.body.rotation(),h=new dt(p.x,p.y,p.z,p.w);s=new pt().setFromQuaternion(h,"XYZ").z}catch{}let l=Math.sin(-s)*(n.x??0),u=Math.cos(-s)*(n.y??0),m=await Promise.resolve(a(i+l,o+u));return t.add(m),m}}}import{subscribe as ht}from"valtio/vanilla";var se="STAGE_STATE_CHANGE";function gt(){return ht(S,()=>{let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(se,{detail:a}))})}function ft(){let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(se,{detail:a}))}import{MathUtils as yt,Vector3 as bt}from"three";var Me={targetKey:"primary",offset:new bt(0,0,0),lerpFactor:.1};function vt(a){let e={...Me,...a,offset:W(a?.offset,Me.offset)},t=null;return{priority:0,enabled:!0,onAttach(){t=null},update(n,i){let o=n.targets[e.targetKey];if(!o)return i;let r=o.position.clone().add(e.offset),s=ve(i);if(!t)t=r.clone();else{let l=yt.clamp(e.lerpFactor,0,1),u=1-Math.pow(1-l,n.dt*60);t.lerp(r,u)}return s.position.copy(t),s.lookAt=o.position.clone(),s},onDetach(){t=null}}}import{MeshBasicMaterial as St}from"three";function wt(a,e,t){let n=e.cameraRef;if(!n.renderTarget){let r=t?.width??512,s=t?.height??512;n.createRenderTarget(r,s)}let i=n.getRenderTexture();if(!i){console.warn("setCameraFeed: Failed to obtain render texture from camera.");return}if(!a.mesh){console.warn("setCameraFeed: Entity has no mesh to apply the camera feed to.");return}let o=new St({map:i});a.mesh.material=o}export{I as a,Q as b,ee as c,te as d,tt as e,c as f,X as g,Y as h,ut as i,mt as j,se as k,gt as l,ft as m,vt as n,wt as o};
@@ -1 +0,0 @@
1
- import{b as Ge,c as at}from"./chunk-VS2D4B3W.js";import{a as m,d as we,f as Ie,g as Ze,h as ze,i as Ve}from"./chunk-JQKS42G4.js";import{a as K,b as qe}from"./chunk-YAOXFYOD.js";import{B as Xe,a as O,k as He,l as je,m as Ke,n as T,o as B,r as Qe,s as Ee,z as j}from"./chunk-KVSJE4XD.js";import{e as x,f as Me,g as Ye,h as $e}from"./chunk-CM5YRNBJ.js";import{a as Ne,b as A}from"./chunk-YHEWKN7N.js";import{a as Q,b as Je,c as Y,d as et,e as tt,f as it,g as rt,m as $}from"./chunk-D2PATZCC.js";import{c as H,d as Pe,j as S}from"./chunk-4QLJUQSJ.js";import{c as b,i as We,j as g}from"./chunk-7WRQ2UAN.js";import{a as st}from"./chunk-BH53MBAZ.js";import{l as Ue}from"./chunk-UG22Z42P.js";import{Vector2 as ct,RenderTarget as Kt,HalfFloatType as Qt}from"three";import{WebGPURenderer as Yt,RenderPipeline as $t}from"three/webgpu";import{pass as qt,renderOutput as ut,screenCoordinate as Xt,vec2 as De,vec4 as gt,fract as mt,sin as pt,dot as ht,texture as Jt,uniform as ei}from"three/tsl";import{setConsoleFunction as Ht,getConsoleFunction as jt}from"three";var nt="THREE.Abstract function.",ot=!1,lt=!1;function dt(){if(ot)return;ot=!0;let s=jt();Ht((e,t,...i)=>{if(e==="warn"&&t===nt){lt||(lt=!0,console.warn(`${nt} (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 ft={x:0,y:0,width:1,height:1};async function lr(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var q=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 ct(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(dt(),this.renderer=new Yt({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 $t(this.renderer),r=qt(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=ut(a),o=this._transition;if(o)try{n=gt(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(ii()),this.postProcessing=i}get transitionActive(){return this._transition!==null}beginSnapshotTransition(e,t,i){this.finishTransition();let r=new ct;this.renderer.getDrawingBufferSize(r);let a=new Kt(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:ei(0),fromNode:ut(Jt(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&&ti(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 ti(s){return s.x===0&&s.y===0&&s.width===1&&s.height===1}function ii(){let s=Xt.xy,e=mt(pt(ht(s,De(12.9898,78.233))).mul(43758.5453)),t=mt(pt(ht(s.add(De(13,7)),De(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return gt(i,i,i,0)}function F(s){return s?.category??"none"}function I(s){let e=F(s);return e==="environment"||e==="pack"}function R(s){return s.isInstanced===!0||s.isBundled===!0}import{BundleGroup as ri}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 ri,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as yt,Matrix4 as Z,Vector3 as bt,Quaternion as ai}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}:${Me(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Ye(Me(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 bt,r=new ai,a=new bt(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(He(d)){t.makeScale(0,0,0),n.instancedMesh.setMatrixAt(l,t),o=!0;continue}let c=n.dirtyIndices.has(l),u=!!d.body;if(!(!c&&!u)){if(!c&&u){let h=d.body;if(typeof h.isRenderSleeping=="function"&&h.isRenderSleeping())continue}this.updateInstanceMatrix(n,l,t,i,r,a,e),o=!0}}n.dirtyIndices.clear(),o&&(n.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,a,n,o){let l=e.entities[t];if(l){if(l.body){let 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 yt(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 yt(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={},vt=0,Ct=0,V=null;function St(){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 Mr(s){ee=s,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=s)}function Te(s){_e()&&(V=s,Ct=St())}function xe(){if(!_e()||V===null)return;let s=St()-Ct;v[V]=(v[V]??0)+s,V=null}function Pt(){if(!_e()||(vt++,vt%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 P(s,e){Te(s);try{return e()}finally{xe()}}var p={FirstPerson:"first-person",ThirdPerson:"third-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};import{Vector3 as si,Quaternion as ni,MathUtils as Re}from"three";function te(){return{position:new si(0,0,10),rotation:new ni,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 wt(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 Et(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=wt(t,n),a.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=Et(this._finalPose,t,this.damping,e.dt):(this._finalPose=M(t),this._initialized=!0),this._finalPose}addBehavior(e,t,i){let r=this.behaviors.get(e);r?.onDetach&&i&&r.onDetach(i),this.behaviors.set(e,t),t.onAttach&&i&&t.onAttach(i)}removeBehavior(e,t){let i=this.behaviors.get(e);return i?(i.onDetach&&t&&i.onDetach(t),this.behaviors.delete(e)):!1}hasBehavior(e){return this.behaviors.has(e)}addAction(e){this.actions.push(e)}getState(){return{perspectiveId:this.perspective?.id??null,desiredPose:this._desiredPose?M(this._desiredPose):null,finalPose:this._finalPose?M(this._finalPose):null,activeBehaviors:Array.from(this.behaviors.keys()),activeActionCount:this.actions.length}}setPerspective(e){this.perspective=e,this._initialized=!1,e.defaults?.damping!=null&&(this.damping=e.defaults.damping)}getSortedBehaviors(){return Array.from(this.behaviors.values()).sort((e,t)=>(e.priority??0)-(t.priority??0))}};import{Vector3 as w,Quaternion as re}from"three";var oi={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},D=class{id="third-person";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...oi,...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 w(0,0,0)}:{position:new w(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new w(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new w(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new re,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([u,h])=>this.getTrailedPosition(u,h.position,e.time)),r=new w;for(let u of i)r.add(u);r.divideScalar(i.length);let a=0;for(let u of i){let h=r.distanceTo(u);h>a&&(a=h)}let n=Math.max(a*this.opts.paddingFactor,this.opts.minDistance),o=new w(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=o.length(),d=l>0?o.clone().normalize():new w(0,.5,1).normalize(),c=r.clone().add(d.multiplyScalar(n));if(l>0){let u=this.opts.height/l;c.y=r.y+n*u}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 u=c.time-d.time,h=u>1e-6?(o-d.time)/u:0;return new w().lerpVectors(d.pos,c.pos,h)}}return a[a.length-1].pos.clone()}};import{Vector3 as Mt,Quaternion as li}from"three";var Dt={position:{x:0,y:0,z:10},zoom:10},k=class{id="fixed-2d";defaults={damping:1};opts;constructor(e){this.opts={...Dt,...e,position:g(e?.position,Dt.position)}}getBasePose(e){return{position:new Mt(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new li,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new Mt(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as ke,Quaternion as Le,Euler as xt,MathUtils as f}from"three";var di={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={...di,...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 xt(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=_t.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=ci.setFromEuler(Tt.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=_t.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=Tt.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=f.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},_t=new ke,ci=new Le,Tt=new xt;function L(s,e){switch(s){case"third-person":return new D(e);case"first-person":return new G(e);case"isometric":return new D({distance:10,height:10,...e});case"flat-2d":return new k(e);case"fixed-2d":return new k(e);default:return new D(e)}}import{Vector2 as hi,Object3D as gi,Vector3 as ne}from"three";import{PerspectiveCamera as U,Vector3 as mi,OrthographicCamera as se,RenderTarget as pi,LinearFilter as Rt}from"three";import{Vector3 as Ae}from"three";import{OrbitControls as ui}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=Ge(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 ui(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 C=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...ft};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 mi(0,0,0));let a=L(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 q(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 pi(e,t,{minFilter:Rt,magFilter:Rt}),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===p.Flat2D||this._perspective===p.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 p.ThirdPerson:return new U(75,e,.1,1e3);case p.FirstPerson:return new U(75,e,.1,1e3);case p.Isometric:return new se(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);case p.Flat2D:case p.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 gi,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 hi(window.innerWidth,window.innerHeight),t=new C(p.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 C(p.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(L(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function Ra(s){let e=We(s.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;s.perspective==="fixed-2d"&&(t=s.zoom||10);let i=new C(s.perspective||"third-person",e,t);s.name&&(i.name=s.name);let r=g(s.position,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(L(n,{zoom:t})):i.pipeline.setPerspective(L(n,{initialPosition:r.clone(),initialLookAt:a.clone()})),s.viewport&&(i.viewport={...s.viewport}),s.useOrbitalControls&&(i._useOrbitalControls=!0),s.skipDebugOrbit&&(i._skipDebugOrbit=!0),s.damping!=null&&(i.pipeline.damping=s.damping),s.behaviors)for(let[o,l]of Object.entries(s.behaviors))i.pipeline.addBehavior(o,l);if(s.renderToTexture){let{width:o=512,height:l=512}=s.renderToTexture;i.createRenderTarget(o,l)}return new y(i)}import{Vector3 as fi}from"three";function E(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 kt(s){return!s||typeof s!="object"||E(s)||Oe(s)||N(s)||typeof s.then=="function"?!1:s.constructor===Object||s.constructor?.name==="Object"}function Lt(s){return s?!!(E(s)||typeof s=="function"||N(s)):!1}var yi="/three/basis/";function de(s){return{...s,ktx2TranscoderPath:s?.ktx2TranscoderPath??yi}}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 bi(){return new le({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},Q,null,null,new fi(0,0,0),{},60,{},!0)}function At(s=[]){let e=bi(),t={},i=[],r=[],a=[];for(let l of s)Oe(l)?a.push(l):E(l)?i.push(l):Lt(l)&&!E(l)?r.push(l):kt(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 Za(s){return{...s}}var vi=Symbol("vessel"),W=class extends O{static type=vi;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=Ci();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function Ci(...s){let e=new W;return s.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Ut,Vector3 as Nt}from"three";import{createSimulation as Si}from"@zylem/behaviors/core";function Be(s){return typeof s?.handlePostCollision=="function"&&typeof s?.handleIntersectionEvent=="function"}function Pi(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 Si({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 qe(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=Pi(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 wi,Color as Ot,AmbientLight as Ei,DirectionalLight as Mi,Vector3 as ue,GridHelper as Di,Texture as _i,SRGBColorSpace as Ti}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 wi,n=i.backgroundColor instanceof Ot?i.backgroundColor:new Ot(i.backgroundColor);r.background=n,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&x.loadTexture(i.backgroundImage,{colorSpace:Ti}).then(o=>{r.background=o}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),m.enabled&&this.debugScene()}setupBackgroundShader(e,t){if(!$e(t)){console.warn("ZylemScene: GLSL background shaders are not supported on the WebGPU renderer. Provide a TSL shader (ZylemTSLShader) as backgroundShader. Keeping solid background.");return}e.background=null,e.backgroundNode=t.colorNode}setup(){this._setup&&this._setup({me:this,camera:this.zylemCamera,globals:S()})}destroy(){this.cameraManager?(this.cameraManager.dispose(),this.cameraManager=null):this.zylemCamera&&this.zylemCamera.destroy&&this.zylemCamera.destroy(),this.scene&&(this.scene.backgroundNode=null,this.scene.background instanceof _i&&(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 Ei(16777215,1);e.add(t);let i=new Mi(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(R(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=xi(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 Di(1e3,100);this.scene.add(i)}};function xi(s){return s.constructor.type===Xe?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 Ri}from"three";var Bt=new Ri;function Ft(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&&(Bt.set(n.rotation.x,n.rotation.y,n.rotation.z,n.rotation.w),a.setRotationFromQuaternion(Bt))}}import{nanoid as Qi}from"nanoid";import{BufferAttribute as Vt,BufferGeometry as zi,LineBasicMaterial as Vi,LineSegments as Gi,Raycaster as Ui,Vector2 as Ni}from"three";import{subscribe as Wi}from"valtio/vanilla";import{subscribe as ki}from"valtio/vanilla";var he=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),ki(m,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:m.enabled,selected:m.selectedEntity?[m.selectedEntity.uuid]:[]}}};import{Box3 as Li,BoxGeometry as It,Color as Ai,EdgesGeometry as Zt,Group as Oi,LineBasicMaterial as Bi,LineSegments as Fi,Mesh as Ii,MeshBasicMaterial as Zi,Vector3 as zt}from"three";var ge=class{scene;container;fillMesh;edgeLines;currentColor=new Ai(65280);bbox=new Li;size=new zt;center=new zt;constructor(e){this.scene=e;let t=new It(1,1,1);this.fillMesh=new Ii(t,new Zi({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new Zt(t);this.edgeLines=new Fi(i,new Bi({color:this.currentColor,linewidth:1})),this.container=new Oi,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 It(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 Zt(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 Hi=2293538,ji=16724787,fe=class{stage;options;mouseNdc=new Ni(-2,-2);raycaster=new Ui;isMouseDown=!1;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;debugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;focusContextUnregister=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.syncWithDebugState(),this.debugStateUnsubscribe=Wi(m,()=>{this.syncWithDebugState()}),this.focusContextUnregister=at({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{this.ensureCameraDebugDelegate(),this.getDebugViewCamera()?.frameObject(i)},ensureDebugReady:()=>{m.enabled||(m.enabled=!0),this.activate(),this.populateDebugMap()}})}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(){m.enabled?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 Gi(new zi,new Vi({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(!m.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 u=t.simulation.getDebugRender();u&&u.vertices.length>0?(this.debugLines.geometry.setAttribute("position",new Vt(new Float32Array(u.vertices),3)),this.debugLines.geometry.setAttribute("color",new Vt(new Float32Array(u.colors),4)),this.debugLines.geometry.attributes.position.needsUpdate=!0,this.debugLines.geometry.attributes.color.needsUpdate=!0,this.debugLines.visible=!0):this.debugLines.visible=!1}let i=we(),r=i==="select"||i==="delete";this.raycaster.setFromCamera(this.mouseNdc,e.camera);let a=this.raycaster.ray.origin.clone(),n=this.raycaster.ray.direction.clone().normalize(),o=t.raycast(a,n,this.options.maxRayDistance);if(o&&r){let u=o.uuid;if(u){let h=this.stage.entityDelegate.debugMap.get(u);h&&ze(h)}else Ve();this.isMouseDown&&this.handleActionOnHit(u??null,a,n,o.distance)}this.isMouseDown=!1;let l=Ze();if(!l){this.debugCursor?.hide();return}let d=this.stage.entityDelegate.debugMap.get(`${l}`),c=d?.group??d?.mesh??null;if(!c){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(Hi);break;case"delete":this.debugCursor?.setColor(ji);break;default:this.debugCursor?.setColor(16777215);break}this.debugCursor?.updateFromObject(c)}dispose(){this.focusContextUnregister?.(),this.focusContextUnregister=null,this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.deactivate(),this.domDisposeFns.forEach(e=>e()),this.domDisposeFns=[],this.domListenersAttached=!1}handleActionOnHit(e,t,i,r){switch(we()){case"select":{if(e){let n=this.resolveEntity(e);n&&Ie(n)}break}case"delete":{e&&this.stage.entityDelegate.removeEntityByUuid(e);break}case"scale":{if(!this.options.addEntityFactory)break;let n=t.clone().add(i.clone().multiplyScalar(r)),o=this.options.addEntityFactory({position:n});o&&Promise.resolve(o).then(l=>{l&&this.stage.entityDelegate.spawnEntity(l)}).catch(()=>{});break}default:break}}attachDomListeners(){let e=this.stage.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 Ki}from"three";var ye=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Ki(e,t);return new C(p.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)},A.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){I(e.options)||(this.scene?.addEntityGroup(e),B(e),T(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),T(i),I(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(A.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as Gt}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:S(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();je(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:S(),camera:this.camera}),this.tryRegisterRenderStrategy(t),R(t)||this.scene.addEntityGroup(t),T(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),Ke(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),R(e)||this.scene.addEntityGroup(e),T(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!==Gt.Static&&(e.bodyDesc.kind=Gt.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),m.enabled&&this.debugMap.set(e.uuid,e);for(let t of this.entityAddedHandlers)try{t(e)}catch(i){console.error("onEntityAdded handler failed",i)}}removeEntityByUuid(e){if(!this.scene||!this.world)return!1;let t=this.world.collisionMap.get(e),i=this.childrenMap.get(e),r=t??i??this.debugMap.get(e);return r?(this.unregisterBehaviorLinks(r),this.entityModelDelegate.unobserve(e),R(r)&&this.renderStrategy?.unregister(r),this.world.destroyEntity(r),r.group?this.scene.scene.remove(r.group):r.mesh&&this.scene.scene.remove(r.mesh),this.childrenMap.delete(e),this.debugMap.delete(e),!0):!1}getEntityByName(e){for(let t of this.childrenMap.values())if(t.name===e)return t;return console.warn(`Entity ${e} not found`),null}buildEntityState(e){return e instanceof Qe?{...e.buildInfo()}:{uuid:e.uuid,name:e.name}}onEntityAdded(e,t){return this.entityAddedHandlers.push(e),t?.replayExisting&&this._isLoaded&&this.childrenMap.forEach(i=>{try{e(i)}catch(r){console.error("onEntityAdded replay failed",r)}}),()=>{this.entityAddedHandlers=this.entityAddedHandlers.filter(i=>i!==e)}}enqueue(...e){for(let t of e)if(t){if(E(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();E(i)?this.handleEntityImmediatelyOrQueue(i):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:S}):t=e,this.behaviorSystems.push(t)}destroyAll(){for(let e of this.behaviorSystems)e.destroy?.();this.behaviorSystems.length=0,this.behaviorSystemByKey.clear(),this.registeredSystemKeys.clear(),this.behaviorEntityIndex.clear(),this.behaviorLinksByUuid.clear(),this.childrenMap.forEach(e=>{try{e.nodeDestroy({me:e,globals:S()})}catch{}$(e)}),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[],this._isLoaded=!1,this.scene=null,this.world=null,this.renderStrategy=null,this.camera=null,this.wasmStage=null}registerBehaviorLinks(e){if(!this.world||!this.scene||typeof e?.getBehaviorRefs!="function")return;let t=e.getBehaviorRefs();if(!Array.isArray(t)||t.length===0)return;let i=[];for(let r of t){let a=r.descriptor.key,n={entity:e,ref:r};i.push(n);let o=this.behaviorEntityIndex.get(a);o||(o=new Set,this.behaviorEntityIndex.set(a,o)),o.add(n);let l=this.behaviorSystemByKey.get(a);if(!l&&!this.registeredSystemKeys.has(a)){let 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:S});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 Yi="Stage",Se=class extends pe{type=Yi;state={...Je};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=At(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 Nt(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Ut?e:new Ut(e);et(i),tt(t),it(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 Nt(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 x.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;P("behaviorSystems",()=>{for(let a of this.entityDelegate.behaviorSystems)a.update(void 0,t)}),P("entityLoop",()=>{for(let a of this.entityDelegate.childrenMap.values()){let n=this.childUpdateParams;n.delta=e.delta,n.inputs=e.inputs,n.globals=e.globals,n.camera=e.camera,n.stage=e.stage,n.game=e.game,n.me=a,a.nodeUpdate(n);let o=a;o.transformStore&&st(o,o.transformStore),a.markedForRemoval&&this.entityDelegate.removeEntityByUuid(a.uuid)}}),P("worldUpdate",()=>{i.update(e)}),P("syncRenderPoses",()=>{Ft({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),P("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),P("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),P("scene",()=>{r.update({delta:t})}),Pt()}outOfLoop(){this.debugUpdate()}debugUpdate(){m.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,rt(),$(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 $i}from"valtio/vanilla";import{Vector3 as qi}from"three";var Xi={backgroundColor:Q,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new qi(0,0,0),variables:{}},_=$i({...Xi});function Wt(s){let e=Ji(),t={};return typeof s[0]=="object"&&(t=s.shift()??{}),[{...e,...t},...s]}function Ji(){return{backgroundColor:_.backgroundColor,backgroundImage:_.backgroundImage??null,inputs:_.inputs?{..._.inputs}:void 0,gravity:_.gravity,variables:_.variables?{..._.variables}:void 0}}var Fe=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Ne;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];x.prepareGLTFRuntime(de(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=Ue(...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),A.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function Zn(...s){let e=Wt(s);return new Fe([...e])}export{lr as a,q as b,F as c,I as d,R as e,X as f,J as g,Mr as h,p as i,M as j,ie as k,D as l,k as m,G as n,L as o,oe as p,y as q,Ra as r,Za as s,Ci as t,Fe as u,Zn as v};